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 _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 initialize(): path = FileUtils.makeFolderPath(MY_DIR, 'data') SystemUtils.remove(path) os.makedirs(path) tracks = DataLoadUtils.getTrackWithAnalysis() return tracks[['uid', 'site', 'width', 'sizeClass']]
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 initializeFolder(self, *args): """ Initializes a folder within the root analysis path by removing any existing contents and then creating a new folder if it does not already exist. """ path = self.getPath(*args, isDir=True) if os.path.exists(path): SystemUtils.remove(path) os.makedirs(path) return path
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 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 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 run(self): """Doc...""" # Create the bin directory where the output will be stored if it does not already exist binPath = self.getBinPath(isDir=True) if not os.path.exists(binPath): os.makedirs(binPath) # Remove any folders created by previous build attempts for d in self._CLEANUP_FOLDERS: path = os.path.join(binPath, d) if os.path.exists(path): shutil.rmtree(path) os.chdir(binPath) ResourceCollector(self, verbose=True).run() cmd = [ FileUtils.makeFilePath(sys.prefix, 'bin', 'python'), '"%s"' % self._createSetupFile(binPath), OsUtils.getPerOsValue('py2exe', 'py2app'), '>', '"%s"' % self.getBinPath('setup.log', isFile=True)] print('[COMPILING]: Executing %s' % OsUtils.getPerOsValue('py2exe', 'py2app')) print('[COMMAND]: %s' % ' '.join(cmd)) result = SystemUtils.executeCommand(cmd, remote=False, wait=True) if result['code']: print('COMPILATION ERROR:') print(result['out']) print(result['error']) return False if self.appFilename and OsUtils.isWindows(): name = self.applicationClass.__name__ source = FileUtils.createPath(binPath, 'dist', name + '.exe', isFile=True) dest = FileUtils.createPath(binPath, 'dist', self.appFilename + '.exe', isFile=True) os.rename(source, dest) if OsUtils.isWindows() and not self._createWindowsInstaller(binPath): print('Installer Creation Failed') return False elif OsUtils.isMac() and not self._createMacDmg(binPath): print('DMG Creation Failed') return False # Remove the resources path once compilation is complete resourcePath = FileUtils.createPath(binPath, 'resources', isDir=True) SystemUtils.remove(resourcePath) buildPath = FileUtils.createPath(binPath, 'build', isDir=True) SystemUtils.remove(buildPath) FileUtils.openFolderInSystemDisplay(binPath) return True
def _handleOpenDocumentsInFinder(self): snap = self._getLatestBuildSnapshot() data = FlexProjectData(**snap) path = FileUtils.createPath( os.path.expanduser('~'), 'Library', 'Application Support', 'iPhone Simulator', '7.0.3', 'Applications', data.appId, isDir=True) cmd = ['open', '"%s"' % path] print 'COMMAND:', cmd SystemUtils.executeCommand(cmd)
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 run(self): """Doc...""" # Create the bin directory where the output will be stored if it does not alread exist binPath = self.getBinPath(isDir=True) if not os.path.exists(binPath): os.makedirs(binPath) # Remove any folders created by previous build attempts for d in self._CLEANUP_FOLDERS: path = os.path.join(binPath, d) if os.path.exists(path): shutil.rmtree(path) os.chdir(binPath) ResourceCollector(self, verbose=True).run() cmd = 'python %s %s > %s' % ( self._createSetupFile(binPath), 'py2exe' if OsUtils.isWindows() else 'py2app', self.getBinPath('setup.log', isFile=True) ) result = SystemUtils.executeCommand(cmd, remote=False, wait=True) if result['code']: print 'COMPILATION ERROR:' print result['error'] return False if self.appFilename and OsUtils.isWindows(): name = self.applicationClass.__name__ source = FileUtils.createPath(binPath, 'dist', name + '.exe', isFile=True) dest = FileUtils.createPath(binPath, 'dist', self.appFilename + '.exe', isFile=True) os.rename(source, dest) if OsUtils.isWindows() and not self._createWindowsInstaller(binPath): print 'Installer Creation Failed' return False elif OsUtils.isMac() and not self._createMacDmg(binPath): print 'DMG Creation Failed' return False # Remove the resources path once compilation is complete resourcePath = FileUtils.createPath(binPath, 'resources', isDir=True) SystemUtils.remove(resourcePath) buildPath = FileUtils.createPath(binPath, 'build', isDir=True) SystemUtils.remove(buildPath) return True
def executeCommand(self, cmd, messageHeader =None, message =None): if isinstance(cmd, list): cmd = ' '.join(cmd) if messageHeader: self.printCommand(message if message else cmd, messageHeader) result = SystemUtils.executeCommand(cmd) self._commandBuffer.append([result['error'], result['out']]) out = '' if result['out']: out += '<br /><br />' \ + '<div style="color:#999999"><span style="font-size:16px">RESULTS:</span>\n' \ + 50*'- ' + '\n' + str(result['out']) + '</div>' if result['error']: out += '<br /><br />' \ + '<div style="color:#993333"><span style="font-size:16px">ERRORS:</span>\n' \ + 50*'- ' + '\n' + str(result['error']) + '</div>' if out: self._log.write(out + '\n\n') self._checkOutput(result['code'], result['out'], result['error']) if result['code']: return result['code'] return 0
def _download(self, url, target, httpsVerify =False, critical =None): print('Downloading %s -> %s' % (url, target)) try: result = SystemUtils.download( url=url, target=target, httpsVerify=httpsVerify, critical=critical, raiseExceptions=self._raiseCommandExceptions) except Exception as err: print('DOWNLOAD FAILED\n', err) if critical or (critical is None and self._raiseCommandExceptions): raise err else: print(err) return False if not result: if critical or (critical is None and self._raiseCommandExceptions): raise Exception('Download failed') else: print('DOWNLOAD FAILED') return False print('SUCCESS') return True
def _createEngineCss(self): resourcePath = StaticFlowEnvironment.rootResourcePath sourceFolder = FileUtils.createPath(resourcePath, '..', 'css', isDir=True) targetFolder = FileUtils.createPath(resourcePath, 'web', 'css', isDir=True) tempPath = FileUtils.createPath(targetFolder, 'engine.temp.css', isFile=True) SystemUtils.remove(tempPath) destF = open(tempPath, 'a') for item in FileUtils.getFilesOnPath(sourceFolder): try: f = open(item, 'r') destF.write('\n' + f.read()) f.close() except Exception , err: print 'ERROR: Failed to read CSS file:', item
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 _move(self, source, destination): if not SystemUtils.move(source, destination): print 'FAILED TO MOVE: %s -> %s' % (source, destination) return False print 'MOVED: %s -> %s' % (source, destination) return True
def run(self): """ Executes the site generation process """ try: if os.path.exists(self.targetWebRootPath): if not SystemUtils.remove(self.targetWebRootPath): # In unsuccessful wait a brief period and try again in case the OS delayed # the allowance for the removal because of an application conflict time.sleep(5) SystemUtils.remove(self.targetWebRootPath, throwError=True) os.makedirs(self.targetWebRootPath) except Exception, err: self.writeLogError( u'Unable to Remove Existing Deployment', error=err, throw=False) return False
def _copy(self, source, destination): result = SystemUtils.copy(source, destination) if not result: print 'FAILED TO COPY: %s -> %s' % (source, destination) return False print 'COPIED: %s -> %s' % (source, destination) return True
def _changePermissions( self, permissions ='777', path =None, owner =None, group =None, recursive =True ): return SystemUtils.changePermissions( permissions=permissions, path=path, owner=owner, group=group, recursive=recursive)
def startServer(cls, path): """ RUN NGINX NGinx is started as an active process. """ cls.initializeEnvironment(path) os.chdir(path) print 'STARTING SERVER AT:', path return SystemUtils.executeCommand('nginx')
def _7zip(self, zipTarget, fileList, append =False): """Don't use 7zip except for isolated files. It's not recursive.""" result = SystemUtils.do7zip(zipTarget=zipTarget, fileList=fileList, append=append) if not result: print 'FAILED TO ZIP: ' + str(zipTarget) return False print 'ZIPPED: ' + str(zipTarget) return True
def _getOutput(self, cmd, critical =None): self._commandIndex += 1 print '\n[%s EXECUTE<OUTPUT>]: %s' % (str(self._commandIndex), cmd) try: out = SystemUtils.executeForOutput(cmd, critical=critical) except Exception, err: print 'FAILED' if critical or (critical is None and self._raiseCommandExceptions): raise err return None
def _createEngineJs(self): cb = CoffeescriptBuilder( 'sflow.api.SFlowApi-exec', FileUtils.createPath(StaticFlowEnvironment.rootResourcePath, '..', 'js', isDir=True), buildOnly=True) target = cb.construct()[0] targetFolder = FileUtils.createPath( StaticFlowEnvironment.rootResourcePath, 'web', 'js', isDir=True) result = SiteProcessUtils.compileCoffeescriptFile(target.assembledPath, targetFolder) if result['code']: print 'ERROR: Failed compilation of the Static Flow engine' print result return False sourcePath = FileUtils.createPath(targetFolder, target.name + '.js', isFile=True) destPath = FileUtils.createPath(targetFolder, 'engine.js', isFile=True) SystemUtils.move(sourcePath, destPath) return True
def _runImpl(self): sets = self._settings if not self._settings.hasPlatform(FlexProjectData.IOS_PLATFORM): self._log.write('ERROR: No iOS platform information found. Install aborted.') return 1 self._settings.setPlatform(FlexProjectData.IOS_PLATFORM) self._log.write( '<div style="font-size:24px">Installing IPA...</div>\n' + '(This can take a few minutes. Please stand by)' ) if PyGlassEnvironment.isWindows: adtCommand = 'adt.bat' else: adtCommand = 'adt' cmd = [ '"%s"' % self.parent().mainWindow.getRootAIRPath( sets.airVersion, 'bin', adtCommand, isFile=True), '-installApp', '-platform', 'ios', '-package', FileUtils.createPath( sets.platformDistributionPath, sets.contentTargetFilename + '.' + sets.airExtension) ] self.log.write('<div style="color:#9999CC">' + '\n'.join(cmd) + '</div>') result = SystemUtils.executeCommand(cmd) print 'IPA Install:', result if result['out']: self._log.write( '<div style="color:#999999">' + '<div style="font-size:18px">Result:' + '</div>' + result['out'] + ('' if result['code'] else ('<br/>' + result['error'])) + '</div>' ) if result['code'] and result['error']: self._log.write( '<div style="color:#993333">' + '<div style="font-size:18px">Error:' + '</div>' + result['error'] + '</div>' ) self._log.write('Installation attempt complete') return result['code']
def emptyFolder(cls, folderPath): """ Recursively empties all elements within a folder, and returns a boolean specifying whether the operation succeeded. """ folderPath = cls.cleanupPath(folderPath, isDir=True) if not os.path.exists(folderPath): return False result = True for path in os.listdir(folderPath[:-1]): result = SystemUtils.remove(folderPath + path) and result return result
def _remove(self, path): if not os.path.exists(path): print 'NOTHING TO REMOVE: ' + path return False result = SystemUtils.remove(path) if not result: print 'FAILED TO REMOVE: ' + path return False print 'REMOVED PATH: ' + path return True
def _un7zip(self, zipSource, targetPath =None, overwriteAll =True): result = SystemUtils.un7zip( zipSource=zipSource, targetPath=targetPath, overwriteAll=overwriteAll) if not result: print 'FAILED TO UN7ZIP: ' + str(zipSource) return False print 'UN7ZIPPED: ' + str(zipSource) return True
def _untar(self, zipSource, overwriteAll =True, gzip =None): result = SystemUtils.untar( zipSource=zipSource, overwriteAll=overwriteAll, gzip=gzip) if not result: print 'FAILED TO UNTAR: ' + str(zipSource) return False print 'UNTARRED: ' + str(zipSource) return True
def commandExists(cls): """ DOES THE NGINX COMMAND EXIST? NGinx must be a recognized command on the user or system path to be accessible. If the command is not found the process is aborted. """ result = SystemUtils.executeCommand('where nginx') if result['code']: print 'ERROR: Unable to find the nginx command. Is it on your system path?' print result['error'].strip() return False return True
def isRunning(cls): """ NGINX ALREADY RUNNING? Only one NGinx server should be running at a time. """ result = SystemUtils.executeCommand('tasklist') if result['code']: print 'ERROR: Unable to access active process list.' print result['error'] return True for task in result['out'].strip().replace('\r', '').split('\n'): if task.startswith('nginx.exe'): return True return False
def _getWindowsDpi(cls): from pyaid.system.SystemUtils import SystemUtils result = SystemUtils.executeCommand([ 'wmic', 'DesktopMonitor', 'Get', 'PixelsPerXLogicalInch, PixelsPerYLogicalInch']) if result['code'] or not 'out' in result: return 72.0 data = result['out'].replace('\r', '').strip().split('\n')[-1].strip() if not data: return 72.0 if data.find(' ') == -1: return float(data) data = re.sub(r'\s{2,}', ' ', data).split(' ') return float(data[0])
def _compileToJavascript(self, target, assembledFile, jsIncludeOverrides=None): # Use the Coffeescript compiler to create a JS compilation of the assembled CS file result = SystemUtils.executeCommand( ['coffee', '-c', '--bare', assembledFile]) status = result['code'] output = result['out'] errors = 0 forceVerbose = False #------------------------------------------------------------------------------------------- # ERROR HANDLING # Check the error status of the compilation process and if a failure occurred parse the # error results for display and logging. if status: outputLines = str(output).replace('\r', '').split('\n') for line in outputLines: if line.startswith('Error:') or line.startswith( 'SyntaxError:'): errors += 1 result = CoffeescriptBuilder._parseError(line) if result: self._log.add(result) else: forceVerbose = True if forceVerbose: self._log.add(output) self._report[target.package] = errors if self._verbose: print("\n\n") if errors == 0 and status == 0: self._log.write('Compilation complete: ' + target.compiledPath) else: self._log.write('Compilation FAILED: ' + target.package) f = open(target.compiledPath, 'r') res = f.read() f.close()
def _getOsxDisplayInfo(cls): from pyaid.system.SystemUtils import SystemUtils return SystemUtils.executeCommand(['system_profiler', 'SPDisplaysDataType'])
def reopenServer(cls, path): os.chdir(path) return SystemUtils.executeCommand('nginx -s reopen')
def remove(self): """remove doc...""" return SystemUtils.remove(self.path)
for p in os.listdir(u'/usr/local/'): if p.startswith(u'Qt4.'): foundLocation = p printResult(u'Qt (%s)' % (foundLocation if foundLocation else u'4.x'), u'PASSED' if foundLocation else u'FAILED') # 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:
def _compressFile(self, target, directory): # Skip compiled files. if target.endswith('comp.js') or target.endswith('comp.css'): return False if target.endswith('.js'): fileType = IncludeCompressor.JS_TYPE elif target.endswith('.css'): fileType = IncludeCompressor.CSS_TYPE else: return False if not directory: directory = '' if not directory.endswith(os.sep) and not target.startswith(os.sep): directory += os.sep inFile = directory + target tempFile = directory + target + '.temp' try: fh = open(inFile, 'r') fileString = fh.read() fh.close() except Exception as err: self._log.writeError('FAILED: Unable to read ' + str(inFile), err) return False if fileType == IncludeCompressor.CSS_TYPE: fileString = fileString.replace('@charset "utf-8";', '') ofn = (target[0:-3] + 'comp.css') else: ofn = (target[0:-2] + 'comp.js') try: fh = open(tempFile, 'w') fh.write(fileString) fh.close() except Exception as err: self._log.writeError( 'FAILED: Unable to write temp file ' + str(tempFile), err) return False outFile = directory + '/' + ofn cmd = ['minify', '"%s"' % tempFile, '"%s"' % outFile] result = SystemUtils.executeCommand(cmd) if result['code']: self._log.write('FAILED: Unable to compress ' + str(inFile)) if os.path.exists(tempFile): os.remove(tempFile) if not os.path.exists(outFile): self._log.write('FAILED: ' + target + ' -> ' + ofn) return False elif fileType == IncludeCompressor.JS_TYPE: f = open(outFile, 'r') compressed = f.read() f.close() compressed = IncludeCompressor._REMOVE_COMMENT_RE.sub( '', compressed) compressed = IncludeCompressor._REMOVE_COMMENT_LINE_RE.sub( '', compressed) f = open(outFile, 'w') f.write(compressed.strip()) f.close() inSize = SizeUnits.SizeConversion.bytesToKilobytes(inFile, 2) outSize = SizeUnits.SizeConversion.bytesToKilobytes(outFile, 2) saved = SizeUnits.SizeConversion.convertDelta( inSize, outSize, SizeUnits.SIZES.KILOBYTES, 2) self._log.write( 'Compressed[%s]: %s -> %s [%sKB -> %sKB | Saved: %sKB]' % (fileType, target, ofn, inSize, outSize, saved)) return True
def stopServer(cls, path, force=False): os.chdir(path) if force: return SystemUtils.executeCommand('nginx -s stop') return SystemUtils.executeCommand('nginx -s quit')