def compileAllOnPath(path, rootPath=None, recursive=False, debug=False, trace=False, force=False, compress=False): CoffeescriptBuilder._results = "" CoffeescriptBuilder._missing = {} if recursive: print("RECURSIVE COMPILE AT: " + path) def walker(paths, dirName, names): out = CoffeescriptBuilder._compileAllInDirectory( os.path.join(paths[0], dirName), paths[1], debug=debug, trace=trace, force=force, compress=compress ) CoffeescriptBuilder._results += out["res"] for n, v in DictUtils.iter(out["missing"]): if n in CoffeescriptBuilder._missing: continue CoffeescriptBuilder._missing[n] = v FileUtils.walkPath(path, walker, [path, rootPath]) print("\n\nCOMPILATION RESULTS:" + CoffeescriptBuilder._results) if CoffeescriptBuilder._missing: print("\n\nMISSING IMPORTS:" + "\n\n") for n, v in DictUtils.iter(CoffeescriptBuilder._missing): print(v["class"] + " [LINE: #" + str(v["line"]) + " | " + v["package"] + "]") else: print("COMPILING DIRECTORY: " + path) CoffeescriptBuilder._compileAllInDirectory( path, rootPath, debug=debug, trace=trace, force=force, compress=compress )
def deployDebugNativeExtensions(cls, cmd, settings): from CompilerDeck.adobe.flex.FlexProjectData import FlexProjectData sets = settings if not sets.aneIncludes: return None debugPath = FileUtils.createPath( sets.projectPath, 'NativeExtensions', '__debug__', isDir=True, noTail=True) if os.path.exists(debugPath): SystemUtils.remove(debugPath) os.makedirs(debugPath) extensionIDs = [] for ane in sets.aneIncludes: anePath = FileUtils.createPath(sets.projectPath, 'NativeExtensions', ane, isDir=True) aneSets = FlexProjectData(anePath) extensionIDs.append(aneSets.getSetting('ID')) aneFilename = aneSets.getSetting('FILENAME') aneFile = FileUtils.createPath(anePath, aneFilename + '.ane', isFile=True) z = zipfile.ZipFile(aneFile) z.extractall(FileUtils.createPath(debugPath, aneFilename + '.ane', isDir=True, noTail=True)) AirUtils.updateAppExtensions(sets.appDescriptorPath, extensionIDs) cmd.extend(['-extdir', '"%s"' % debugPath]) return debugPath
def _executeBuildScript(self, scriptName): pd = self._flexData scriptsPath = FileUtils.createPath(pd.projectPath, 'compiler', 'scripts', isDir=True) if not os.path.exists(scriptsPath): return False typePath = FileUtils.createPath(scriptsPath, self._flexData.buildTypeFolderName, isDir=True) if not os.path.exists(typePath): return False platformPath = FileUtils.createPath(typePath, pd.currentPlatformID.lower(), isDir=True) if not os.path.exists(platformPath): return False targetPath = FileUtils.createPath(platformPath, scriptName, isFile=True) if not os.path.exists(targetPath): targetPath += '.py' if not os.path.exists(targetPath): return False self._log.write('Running post build script: ' + scriptName) f = open(targetPath, 'r') script = f.read() f.close() module = imp.new_module('postBuildScriptModule') setattr(module, '__file__', targetPath) setattr(module, 'logger', self._log) setattr(module, 'flexProjectData', self._flexData) exec script in module.__dict__ self._log.write('Post build script execution complete')
def path(self): if not self._path: return None if not StringUtils.ends(self._path, '.csv'): if not FileUtils.getFileExtension(self._path): self._path += '.csv' return FileUtils.cleanupPath(self._path, isFile=True)
def checkEnvFile(cls, target, otherPaths=None): """Doc...""" pathSep = OsUtils.getPerOsValue(';', ':') additions = cls._getSourcePaths(otherPaths=otherPaths) with open(target, 'r') as f: contents = f.read() result = cls._PYTHON_PATH_PATTERN.search(contents) if not result: return False paths = result.groupdict()['paths'].split(pathSep) for addition in additions: found = False for p in paths: p = FileUtils.cleanupPath(p, noTail=True) if p == FileUtils.cleanupPath(addition.folderPath, noTail=True): found = True break if not found: return False return True
def _createMacDmg(self, binPath): print 'CREATING Mac DMG' target = FileUtils.createPath(binPath, self.application.appID + '.dmg', isFile=True) tempTarget = FileUtils.createPath(binPath, 'pack.tmp.dmg', isFile=True) distPath = FileUtils.createPath(binPath, 'dist', isDir=True, noTail=True) if os.path.exists(tempTarget): SystemUtils.remove(tempTarget) cmd = ['hdiutil', 'create', '-size', '500m', '"%s"' % tempTarget, '-ov', '-volname', '"%s"' % self.appDisplayName, '-fs', 'HFS+', '-srcfolder', '"%s"' % distPath] result = SystemUtils.executeCommand(cmd, wait=True) if result['code']: print 'Failed Command Execution:' print result return False cmd = ['hdiutil', 'convert', "%s" % tempTarget, '-format', 'UDZO', '-imagekey', 'zlib-level=9', '-o', "%s" % target] if os.path.exists(target): SystemUtils.remove(target) result = SystemUtils.executeCommand(cmd) if result['code']: print 'Failed Command Execution:' print result return False SystemUtils.remove(tempTarget) return True
def locateMayaEnvFiles(cls): """ Finds the location of all Maya.env files located in the default location on the host and return them as a list. If no such env files exist, the method returns an empty list. """ home = FileUtils.cleanupPath(OsUtils.getHomePath(), isDir=True) if not os.path.exists(home): return [] if OsUtils.isWindows(): root = FileUtils.createPath(OsUtils.getDocumentsPath(), 'maya', isDir=True) if not os.path.exists(root): return [] elif OsUtils.isMac(): root = FileUtils.createPath(home, 'Library', 'Preferences', 'Autodesk', 'maya', isDir=True) if not os.path.exists(root): return [] else: return [] out = [] FileUtils.walkPath(root, cls._handleFindEnvFiles, out) return out
def __init__(self, containerPath, isRemoteDeploy =False, sourceRootFolder ='src', **kwargs): """Creates a new instance of Site.""" super(Site, self).__init__() self.errorCount = 0 self.warningCount = 0 self._staticPaths = [] self._logger = ArgsUtils.getLogger(self, kwargs) self._sourceRootFolderName = sourceRootFolder # NGinx root path in which all files reside self._containerPath = FileUtils.cleanupPath(containerPath, isDir=True) # Location of the source files used to create the website self._sourceWebRootPath = FileUtils.createPath(containerPath, sourceRootFolder, isDir=True) # Locations where files should be deployed. If the target root path is None, which is the # default value, the local web root path is used in its place. if isRemoteDeploy: self._targetWebRootPath = FileUtils.cleanupPath( tempfile.mkdtemp(prefix='staticFlow_'), isDir=True) else: self._targetWebRootPath = None self._localWebRootPath = FileUtils.createPath( containerPath, ArgsUtils.get('localRootFolder', 'root', kwargs), isDir=True) path = FileUtils.createPath(self.sourceWebRootPath, '__site__.def', isFile=True) try: self._data.data = JSON.fromFile(path, throwError=True) except Exception, err: self.writeLogError(u'Unable to load site definition file: "%s"' % path, error=err) pass
def appleProvisioningProfile(self): if self._currentPlatformID != self.IOS_PLATFORM: return None certPaths = [ FileUtils.createPath( self.platformProjectPath, 'cert', self.buildTypeFolderName, isDir=True), FileUtils.createPath(self.platformProjectPath, 'cert', isDir=True) ] if self.iosAdHoc: certPaths.insert(0, FileUtils.createPath( self.platformProjectPath, 'cert', 'adhoc', isDir=True)) for certPath in certPaths: if not os.path.exists(certPath): continue filename = self.getSetting('PROVISIONING_PROFILE', None) if filename is None: for path in FileUtils.getFilesOnPath(certPath): if path.endswith('.mobileprovision'): return path continue filename = filename.replace('\\', '/').strip('/').split('/') path = FileUtils.createPath(certPath, filename, isFile=True) if not os.path.exists(path) and os.path.exists(path + '.mobileprovision'): path += '.mobileprovision' if os.path.exists(path): return path return None
def certificate(self): """Returns the absolute path to the certificate file needed for packaging.""" certPaths = [ FileUtils.createPath( self.platformProjectPath, 'cert', self.buildTypeFolderName, isDir=True), FileUtils.createPath(self.platformProjectPath, 'cert', isDir=True) ] for certPath in certPaths: if not os.path.exists(certPath): continue certFileName = self.getSetting('CERTIFICATE') if certFileName is None: for path in FileUtils.getFilesOnPath(certPath): if path.endswith('.p12'): return path continue certFileName = certFileName.replace('\\', '/').strip('/').split('/') certPath = FileUtils.createPath(certPath, certFileName, isFile=True) if not os.path.exists(certPath) and os.path.exists(certPath + '.p12'): certPath += '.p12' if os.path.exists(certPath): return certPath return None
def initializeEnvironment(cls, path): """ CREATE MISSING FILES AND FOLDERS Due to the limited file creation privileges while running NGinx as a normal user, certain files and folders must exist prior to starting the server. """ for folderParts in cls._NGINX_FOLDERS: p = FileUtils.createPath(path, *folderParts, isDir=True) if not os.path.exists(p): os.makedirs(p) for fileParts in cls._NGINX_FILES: p = FileUtils.createPath(path, *fileParts, isFile=True) if not os.path.exists(p): f = open(p, 'w+') f.close() #------------------------------------------------------------------------------------------- # COPY CONF FILES # NGinx requires a number of conf files to be present and comes with a default set of # files, which must be cloned to the target location if they do not already exist. nginxExeConfFolder = FileUtils.createPath(NGinxSetupOps.getExePath(), 'conf', isDir=True) for item in os.listdir(nginxExeConfFolder): itemPath = FileUtils.createPath(nginxExeConfFolder, item) if not os.path.isfile(itemPath): continue targetPath = FileUtils.createPath(path, 'conf', item, isFile=True) if os.path.exists(targetPath): continue shutil.copy(itemPath, targetPath)
def save(self, toPDF=True): """ Writes the current _drawing in SVG format to the file specified at initialization. If one wishes to have create a PDF file (same file name as used for the .SVG, but with suffix .PDF), then call with toPDF True). """ if not self.siteMapReady: return # Make sure the directory where the file will be saved exists before saving FileUtils.getDirectoryOf(self._drawing.filename, createIfMissing=True) self._drawing.save() # we're done if no PDF version is also required if not toPDF: return # strip any extension off of the file name basicName = self.fileName.split(".")[0] # load up the command cmd = ["/Applications/Inkscape.app/Contents/Resources/bin/inkscape", "-f", None, "-A", None] cmd[2] = basicName + ".svg" cmd[4] = basicName + ".pdf" # and execute it response = SystemUtils.executeCommand(cmd) if response["error"]: print("response[error]=%s" % response["error"])
def _copyResourceFolder(self, sourcePath, parts): targetPath = FileUtils.createPath(self._targetPath, *parts, isDir=True) WidgetUiCompiler(sourcePath).run() if self._verbose: self._log.write('COPYING: %s -> %s' % (sourcePath, targetPath)) return FileUtils.mergeCopy(sourcePath, targetPath)
def compileCoffeescriptFile(cls, source, destFolder, minify =True): iniDirectory = os.curdir os.chdir(os.path.dirname(source)) cmd = cls.modifyNodeCommand([ StaticFlowEnvironment.getNodeCommandAbsPath('coffee'), '--output', '"%s"' % FileUtils.stripTail(destFolder), '--compile', '"%s"' % source ]) result = SystemUtils.executeCommand(cmd) if not minify or result['code']: os.chdir(iniDirectory) return result name = os.path.splitext(os.path.basename(source))[0] + '.js' dest = FileUtils.createPath(destFolder, name, isFile=True) tempOutPath = dest + '.tmp' shutil.move(dest, tempOutPath) cmd = cls.modifyNodeCommand([ StaticFlowEnvironment.getNodeCommandAbsPath('uglifyjs'), '"%s"' % tempOutPath, '>', '"%s"' % dest ]) result = SystemUtils.executeCommand(cmd) os.remove(tempOutPath) os.chdir(iniDirectory) return result
def _copyV4SupportLib(self): v4Path = self._owner.mainWindow.getAndroidSDKPath(*AndroidCompiler._V4_SUPPORT_LIB, isDir=True) for item in os.listdir(v4Path): itemPath = FileUtils.createPath(v4Path, item, isDir=True) self._copyMerges.append( FileUtils.mergeCopy(itemPath, self.getTargetPath('android', 'src'), False) )
def _getJDKPath(cls, *args, **kwargs): if cls._JDK_PATH is None: jdkPath = None lastParts = [0, 0, 0, 0] for root in [cls._PROG_64_PATH, cls._PROG_PATH]: for p in os.listdir(FileUtils.createPath(root, 'java')): if not p.lower().startswith('jdk'): continue parts = cls._NUM_FINDER.findall(p) skip = False index = 0 while index < len(lastParts) and index < len(parts): if parts[index] < lastParts[index]: skip = True break index += 1 if not skip: lastParts = parts jdkPath = FileUtils.createPath(cls._PROG_64_PATH, 'java', p) cls._JDK_PATH = jdkPath if cls._JDK_PATH is None: raise Exception, 'Unable to locate a Java Development Kit installation.' return FileUtils.createPath(cls._JDK_PATH, *args, **kwargs)
def _deployResources(cls): """ On windows the resource folder data is stored within the application install directory. However, due to permissions issues, certain file types cannot be accessed from that directory without causing the program to crash. Therefore, the stored resources must be expanded into the user's AppData/Local folder. The method checks the currently deployed resources folder and deploys the stored resources if the existing resources either don't exist or don't match the currently installed version of the program. """ if not OsUtils.isWindows() or not PyGlassEnvironment.isDeployed: return False storagePath = PyGlassEnvironment.getInstallationPath('resource_storage', isDir=True) storageStampPath = FileUtils.makeFilePath(storagePath, 'install.stamp') resourcePath = PyGlassEnvironment.getRootResourcePath(isDir=True) resourceStampPath = FileUtils.makeFilePath(resourcePath, 'install.stamp') try: resousrceData = JSON.fromFile(resourceStampPath) storageData = JSON.fromFile(storageStampPath) if resousrceData['CTS'] == storageData['CTS']: return False except Exception as err: pass SystemUtils.remove(resourcePath) FileUtils.mergeCopy(storagePath, resourcePath) return True
def rootPath(self): if self._rootPath: return self._rootPath if self._appFilePath: return FileUtils.getDirectoryOf(self._appFilePath) return FileUtils.createPath(os.path.expanduser('~'), self.appName, isDir=True)
def platformProjectPath(self): """The root project path for the currently active platform.""" pid = self._currentPlatformID if pid == self.ANDROID_PLATFORM: return FileUtils.createPath(self.projectPath, 'android', isDir=True) elif pid == self.IOS_PLATFORM: return FileUtils.createPath(self.projectPath, 'ios', isDir=True) return self.projectPath
def _compileUiFile(self, path, filename): """Doc...""" source = FileUtils.createPath(path, filename, isFile=True) if self._verbose: self._log.write('COMPILING: ' + source) if PyGlassEnvironment.isWindows: uicCommand = FileUtils.createPath(self._pythonPath, 'Scripts', 'pyside-uic.exe') else: uicCommand = 'pyside-uic' cmd = '%s %s' % (uicCommand, source) pipe = subprocess.Popen( cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, error = pipe.communicate() if pipe.returncode or error: self._log.write('ERROR: Failed to compile %s widget: %s' % (str(source), str(error))) return False res = WidgetUiCompiler._CLASS_NAME_RE.search(out) if not res: self._log.write('ERROR: Failed to find widget class name for ' + str(source)) return False out = WidgetUiCompiler._CLASS_NAME_RE.sub('PySideUiFileSetup', out, 1) res = WidgetUiCompiler._SETUP_UI_RE.search(out) if not res: self._log.write('ERROR: Failed to find widget setupUi method for ' + str(source)) return False targetName = res.groupdict().get('parentName') out = WidgetUiCompiler._SETUP_UI_RE.sub('\g<parentName>', out, 1) res = WidgetUiCompiler._RETRANSLATE_RE.search(out) if not res: self._log.write('ERROR: Failed to find widget retranslateUi method for ' + str(source)) return False out = WidgetUiCompiler._RETRANSLATE_RE.sub('\g<parentName>', out, 1) if isinstance(out, unicode): out = out.encode('utf8', 'ignore') out = WidgetUiCompiler._SELF_RE.sub(targetName + '.', out) dest = FileUtils.createPath(path, filename[:-3] + '.py', isFile=True) if os.path.exists(dest): os.remove(dest) f = open(dest, 'w+') f.write(out) f.close() py_compile.compile(dest) return True
def initialize(my_path): if os.path.isfile(my_path): my_path = FileUtils.getDirectoryOf(my_path) path = FileUtils.makeFolderPath(my_path, 'data') SystemUtils.remove(path) os.makedirs(path) return path
def path(self): if self._common: return FileUtils.createPath( self._gui.appResourcePath, ApplicationConfig._APP_COMMON_CONFIG_FILENAME) return FileUtils.createPath( self._gui.localAppResourcePath, ApplicationConfig._APP_CONFIG_FILENAME)
def faviconUrl(self): path = FileUtils.createPath(self.sourceWebRootPath, 'favicon.png', isFile=True) if os.path.exists(path): return self.getSiteUrl('/favicon.png') path = FileUtils.createPath(self.sourceWebRootPath, 'favicon.ico', isFile=True) if os.path.exists(path): return self.getSiteUrl('/favicon.ico') return None
def _createIcon(self, binPath): iconPath = self._getIconPath() if not iconPath: return iconPath if os.path.isfile(iconPath): return iconPath #------------------------------------------------------------------------------------------- # MAC ICON CREATION # On OSX use Apple's iconutil (XCode developer tools must be installed) to create an # icns file from the icons.iconset folder at the specified location. if OsUtils.isMac(): targetPath = FileUtils.createPath(binPath, self.appDisplayName + '.icns', isFile=True) result = SystemUtils.executeCommand([ 'iconutil', '-c', 'icns', '-o', '"' + targetPath + '"', '"' + iconPath + '"']) if result['code']: return '' return targetPath #------------------------------------------------------------------------------------------- # WINDOWS ICON CREATION # On Windows use convert (ImageMagick must be installed and on the PATH) to create an # ico file from the icons folder of png files. result = SystemUtils.executeCommand('where convert') if result['code']: return '' items = result['out'].replace('\r', '').strip().split('\n') convertCommand = None for item in items: if item.find('System32') == -1: convertCommand = item break if not convertCommand: return '' images = os.listdir(iconPath) cmd = ['"' + convertCommand + '"'] for image in images: if not StringUtils.ends(image, ('.png', '.jpg')): continue imagePath = FileUtils.createPath(iconPath, image, isFile=True) cmd.append('"' + imagePath + '"') if len(cmd) < 2: return '' targetPath = FileUtils.createPath(binPath, self.appDisplayName + '.ico', isFile=True) cmd.append('"' + targetPath + '"') result = SystemUtils.executeCommand(cmd) if result['code'] or not os.path.exists(targetPath): print 'FAILED:' print result['command'] print result['error'] return '' return targetPath
def run(self): """ Executes the analysis process, iterating through each of the analysis stages before cleaning up and exiting. """ print('[OUTPUT PATH]: %s' % self.analysisRootPath) print(analysisStamp) print(tracksStamp) self._startTime = TimeUtils.getNowDatetime() myRootPath = self.getPath(isDir=True) if os.path.exists(myRootPath): FileUtils.emptyFolder(myRootPath) if not os.path.exists(myRootPath): os.makedirs(myRootPath) tempPath = self.tempPath if os.path.exists(tempPath): SystemUtils.remove(tempPath) os.makedirs(tempPath) if not self.logger.loggingPath: self.logger.loggingPath = myRootPath try: session = self.getAnalysisSession() self._preAnalyze() for stage in self._stages: self._currentStage = stage stage.analyze() self._currentStage = None self._postAnalyze() session.commit() session.close() self._success = True except Exception as err: session = self.getAnalysisSession() session.close() msg = [ '[ERROR]: Failed to execute analysis', 'STAGE: %s' % self._currentStage] self._errorMessage = Logger.createErrorMessage(msg, err) self.logger.writeError(msg, err) session = self.getTracksSession() session.close() self._cleanup() SystemUtils.remove(tempPath) self.logger.write('\n\n[%s]: %s (%s)' % ( 'SUCCESS' if self._success else 'FAILED', self.__class__.__name__, TimeUtils.toPrettyElapsedTime(self.elapsedTime) ), indent=False)
def platformDistributionPath(self): ptype = self.buildTypeFolderName if self.isNative: platform = 'win' if OsUtils.isWindows() else 'mac' return FileUtils.createPath( self.platformProjectPath, 'dist', 'native', platform, ptype, isDir=True) return FileUtils.createPath(self.platformProjectPath, 'dist', ptype, isDir=True)
def updateAppExtensions(cls, descriptorPath, extensionIDs): s = [] offset = '\n ' for eid in extensionIDs: s.append('<extensionID>%s</extensionID>' % eid) print 'EXTENSIONS:', s data = FileUtils.getContents(descriptorPath) data = cls.APP_EXTENSION_PATTERN.sub( '\g<prefix>' + offset + offset.join(s) + '\n \g<suffix>', data) return FileUtils.putContents(data, descriptorPath)
def _cleanupInFolder(self, arg, dirname, names): for name in names: if StringUtils.ends(name, self._compiler.ignoreExtensions): os.remove(FileUtils.createPath(dirname, name, isFile=True)) # Deletes python (.py) files associated with ui files so only .pyc files remain. if name.endswith('.ui'): pyName = name.rsplit('.', 1)[0] + '.py' pyNamePath = FileUtils.createPath(dirname, pyName, isFile=True) if os.path.exists(pyNamePath): os.remove(pyNamePath)
def _writeGoogleFiles(self): vid = self.get(('GOOGLE', 'SITE_VERIFY_ID')) if not vid: return False if not vid.endswith('.html'): vid += '.html' path = FileUtils.createPath(self.targetWebRootPath, vid, isFile=True) FileUtils.putContents(u'google-site-verification: ' + vid, path) SiteProcessUtils.createHeaderFile(path, None) return True
def _htmlDefinitionWalker(self, args, path, names): # If a folder definition is found, use it to populate the directory with any missing # definition files before proceeding if '__folder__.def' in names: self._processFolderDefinitions( FileUtils.createPath(path, '__folder__.def', isFile=True)) names = os.listdir(path) # For each definition file in the directory create page data for processing for name in names: if name.endswith('.def') and not name.startswith('__'): self._pages.create(FileUtils.createPath(path, name, isFile=True))
def updateAppIconList(cls, descriptorPath, iconDefs): s = [] offset = '\n ' for icon in iconDefs: size = icon['size'] name = icon['name'] s.append('<image%sx%s>icons/%s</image%sx%s>' % (size, size, name, size, size)) data = FileUtils.getContents(descriptorPath) data = cls.APP_ICON_PATTERN.sub( '\g<prefix>' + offset + offset.join(s) + '\n \g<suffix>', data) return FileUtils.putContents(data, descriptorPath)
def _copyWalker(self, walkData): staticFolder = False for folder in self._staticPaths: path = FileUtils.cleanupPath(walkData.folder, isDir=True) folder = FileUtils.cleanupPath(folder, isDir=True) if path == folder or FileUtils.isInFolder(path, folder): staticFolder = True break copiedNames = [] for item in walkData.names: if not staticFolder and not StringUtils.ends(item, self._FILE_COPY_TYPES): continue sourcePath = FileUtils.createPath(walkData.folder, item) if os.path.isdir(sourcePath): continue destPath = FileUtils.changePathRoot( sourcePath, self.sourceWebRootPath, self.targetWebRootPath) try: FileUtils.getDirectoryOf(destPath, createIfMissing=True) shutil.copy(sourcePath, destPath) lastModified = FileUtils.getUTCModifiedDatetime(sourcePath) SiteProcessUtils.createHeaderFile(destPath, lastModified) SiteProcessUtils.copyToCdnFolder(destPath, self, lastModified) copiedNames.append(item) except Exception, err: self.writeLogError(u'Unable to copy file', error=err, extras={ 'SOURCE':sourcePath, 'TARGET':destPath }) return
def compressPath(self, rootPath): # First compile any coffee scripts to js files if self._compileCoffee: try: from pyaid.web.coffeescript.CoffeescriptBuilder import CoffeescriptBuilder CoffeescriptBuilder.compileAllOnPath(rootPath, rootPath, True) self._log.write('Coffee scripts compiled.') except Exception as err: self._log.writeError('Failed to compile coffeescript files.', err) return False FileUtils.walkPath(rootPath, self._compressInFolder, None) self._log.write('Compression operation complete.') return True
def loggingPath(self, value): self._logPath = FileUtils.cleanupPath(value) logFolder = self.getLogFolder() if logFolder: name = self._name extension = self.logFileExtension if self.timestampFileSuffix: name += '_' + self._timeCode self._logFile = FileUtils.createPath(logFolder, name + '.' + extension) if self.removeIfExists: self.resetLogFile() else: self._logFile = None
def convertDirectory(self, path, srcType, targetType, recursive =False): if srcType is None or targetType is None: self._log.write('ERROR: Source and/or target types are invalid. Operation aborted.') return False if not os.path.exists(path): self._log.write('ERROR: The specified path [%s] does not exist. Operation aborted.' \ % str(path)) return False if recursive: FileUtils.walkPath(path, self._convertInDirectory, [srcType, targetType]) else: self._convertInDirectory([srcType, targetType], path, os.listdir(path)) return True
def _handleLocatePath(self): self.refreshGui() path = QtGui.QFileDialog.getExistingDirectory( self, caption=u'Specify Root NGinx Path', dir=self.rootPath) if path: path = FileUtils.cleanupPath(path) self._pathLineEdit.setText(path)
def toFile(self, path): path = FileUtils.cleanupPath(path, isFile=True) try: f = open(path, 'wb') f.write(self._data) f.close() except Exception: print('FAILED: Write ByteChunk to file') raise
def compileAllOnPath(path, rootPath=None, recursive=False, debug=False, trace=False, force=False, compress=False): CoffeescriptBuilder._results = '' CoffeescriptBuilder._missing = {} if recursive: print('RECURSIVE COMPILE AT: ' + path) def walker(paths, dirName, names): out = CoffeescriptBuilder._compileAllInDirectory( os.path.join(paths[0], dirName), paths[1], debug=debug, trace=trace, force=force, compress=compress) CoffeescriptBuilder._results += out['res'] for n, v in DictUtils.iter(out['missing']): if n in CoffeescriptBuilder._missing: continue CoffeescriptBuilder._missing[n] = v FileUtils.walkPath(path, walker, [path, rootPath]) print('\n\nCOMPILATION RESULTS:' + CoffeescriptBuilder._results) if CoffeescriptBuilder._missing: print('\n\nMISSING IMPORTS:' + '\n\n') for n, v in DictUtils.iter(CoffeescriptBuilder._missing): print(v['class'] + ' [LINE: #' + str(v['line']) + ' | ' + v['package'] + ']') else: print('COMPILING DIRECTORY: ' + path) CoffeescriptBuilder._compileAllInDirectory(path, rootPath, debug=debug, trace=trace, force=force, compress=compress)
def _generateHeaders(cls, keyName, expires=None, eTag=None, maxAge=-1, gzipped=False): """Doc...""" headers = dict() if expires: if StringUtils.isStringType(expires): headers['Expires'] = StringUtils.toBytes(expires) elif StringUtils.isBinaryType(expires): headers['Expires'] = expires else: headers['Expires'] = StringUtils.toBytes( TimeUtils.dateTimeToWebTimestamp(expires)) elif eTag: headers['ETag'] = StringUtils.toBytes(eTag) if maxAge > -1: headers['Cache-Control'] = StringUtils.toBytes( 'max-age=%s; public' % maxAge) if keyName.endswith('.jpg'): contentType = MIME_TYPES.JPEG_IMAGE elif keyName.endswith('.png'): contentType = MIME_TYPES.PNG_IMAGE elif keyName.endswith('.gif'): contentType = MIME_TYPES.GIF_IMAGE else: contentType = FileUtils.getMimeType(keyName) if StringUtils.begins(contentType, ('text/', 'application/')): contentType = '%s; charset=UTF-8' % contentType headers['Content-Type'] = contentType if gzipped: headers['Content-Encoding'] = 'gzip' return headers
def _getSourcePaths(cls, otherPaths=None): nimbleEntry = MayaEnvEntry.fromRootPath( FileUtils.createPath(FileUtils.getDirectoryOf(nimble.__file__), noTail=True)) pyaidEntry = MayaEnvEntry.fromRootPath( FileUtils.createPath(FileUtils.getDirectoryOf(pyaid.__file__), noTail=True)) pyglassEntry = MayaEnvEntry.fromRootPath( FileUtils.createPath(FileUtils.getDirectoryOf(pyglass.__file__), noTail=True)) additions = [nimbleEntry, pyaidEntry, pyglassEntry] if not otherPaths: return additions for p in otherPaths: additions.append(p if isinstance(p, MayaEnvEntry) else MayaEnvEntry .fromRootPath(p)) return additions
def rootPath(self): return FileUtils.createPath(self.folderPath, self.rootName, noTail=True)
def _handleFindEnvFiles(cls, walkData): for name in walkData.names: if name == 'Maya.env': walkData.data.append( FileUtils.createPath(walkData.folder, name))
def rootPath(self, value): self._pathLineEdit.setText(FileUtils.cleanupPath(value))
def modifyEnvFile(cls, target, install=True, test=False, otherPaths=None): """Doc...""" pathSep = OsUtils.getPerOsValue(';', ':') removals = [] entries = cls._getSourcePaths(otherPaths=otherPaths) additions = entries + [] with open(target, 'r') as f: contents = f.read().strip() result = cls._PYTHON_PATH_PATTERN.search(contents) if not result: if install and not test: with open(target, 'w') as f: f.write((contents + '\n' if contents else '') + 'PYTHONPATH=' + cls._joinPathEntries(additions)) return cls.MAYA_ENV_MODIFIED_RESULT_NT( additions if install else [], removals) paths = result.groupdict()['paths'].strip() paths = paths.split(pathSep) if paths else [] if not paths and not install: return cls.MAYA_ENV_MODIFIED_RESULT_NT([], []) index = 0 while index < len(paths): # Stop if no more additions remain if not additions: break p = FileUtils.cleanupPath(paths[index], noTail=True) # If path already exists don't add it again pathMatch = cls._hasPath(p, additions) if pathMatch: additions.remove(pathMatch) # If uninstalling add to removals if not install: removals.append(pathMatch) paths.remove(p) else: index += 1 continue elif not install: index += 1 continue for entry in entries: testPath = FileUtils.createPath(p, entry.rootName, noTail=True) if os.path.exists(testPath): paths.remove(p) index += 1 for entry in additions: paths.append(entry.folderPath) insertion = ('PYTHONPATH=' + pathSep.join(paths) + '\n') if paths else '' contents = contents[:result.start()] + insertion + contents[result.end( ):] result = cls.MAYA_ENV_MODIFIED_RESULT_NT(additions if install else [], removals) if test: return result with open(target, 'w') as f: f.write(contents) return result
# helloPythonImport.py # (C)2014 # Scott Ernst """ This example shows how to use the advanced import scripting in Nimble. """ from __future__ import print_function, absolute_import, unicode_literals, division import sys from pyaid.file.FileUtils import FileUtils import nimble # Add the src path for this example to the python system path for access to the scripts scriptPath = FileUtils.createPath(FileUtils.getDirectoryOf(__file__), 'src', isDir=True) sys.path.append(scriptPath) from helloPythonImportExample.scripts import CreateSpheres # Create a Nimble connection object. This object will be used to send and receive across the # nimble communication bridge between this script and the Nimble server running in Maya conn = nimble.getConnection() # Add the script src path to the Maya Python environment as well so that it can import and run # the scripts directly result = conn.addToMayaPythonPath(scriptPath) if not result.success: print( 'Unable to modify Maya Python path. Are you sure Maya is running a Nimble server?'
def fromRootPath(cls, path): """Doc...""" parts = path.rsplit(os.sep, 1) return MayaEnvEntry(parts[-1], FileUtils.cleanupPath(parts[0], noTail=True))
cmds.move(offset, offset, offset, name) cmds.rotate(50, 20, 10, name) cmds.scale(2, 2, 2, name) response = nimble.createRemoteResponse(globals()) response.put('name', name) response.put('offset', offset) """ #--------------------------------------------------------------------------------------------------- print('RUNNING SCRIPT:') conn = nimble.getConnection() result = conn.runPythonScript(script, offset=20) print('\tRESULT:', result, type(result)) print('\tPAYLOAD:', result.payload) #--------------------------------------------------------------------------------------------------- print('RUNNING FILE:') result = conn.runPythonScriptFile(FileUtils.createPath(os.path.abspath( os.path.dirname(__file__)), 'pythonTestScript.py', isFile=True), offset=5) print('\tRESULT:', result, type(result)) print('\tPAYLOAD:', result.payload) print('Operation Complete')
def currentLocalAppResourcesPath(self): if not self.currentAppPath: return None return FileUtils.makeFolderPath(self.currentAppPath, 'resources', 'local', isDir=True)
# Check for PySide system dynamic libraries paths = [] for p in os.listdir(u'/usr/lib'): if p.endswith(u'.dylib') and p.startswith(u'libpyside-'): paths.append(p) printResult(u'PySide (Dynamic Libraries)', u'PASSED' if paths else u'FAILED') for p in paths: print u'\t', p result = SystemUtils.executeCommand('find /usr -name "libpyside-*.dylib"') print result['out'] # Check for PySide site package shared libraries foundLocation = None for p in sys.path: p = FileUtils.createPath(p, u'PySide', isDir=True) if not os.path.exists(p): continue if os.path.exists(FileUtils.createPath(p, u'QtCore.so', isFile=True)): foundLocation = p break printResult(u'PySide (Package Libraries)', u'PASSED' if foundLocation else u'FAILED') if foundLocation: print u'\t', foundLocation # Check for PySide try: from PySide import QtCore printResult(u'PySide', u'PASSED')