Exemplo n.º 1
0
    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
Exemplo n.º 2
0
    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
Exemplo n.º 3
0
    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
Exemplo n.º 4
0
    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)
Exemplo n.º 5
0
    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"])
Exemplo n.º 6
0
    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
Exemplo n.º 7
0
    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')
Exemplo n.º 8
0
    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')
Exemplo n.º 9
0
    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
Exemplo n.º 10
0
    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
Exemplo n.º 11
0
    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']
Exemplo n.º 12
0
    def _runClear(self):
        self._log.write(
            '<div style="font-size:24px">Clearing Android Logcat...</div>\n'
        )

        command = 'adb.exe' if OsUtils.isWindows() else 'adb'
        cmd = [
            '"%s"' % self.parent().mainWindow.getAndroidSDKPath('platform-tools', command),
            'logcat',
            '-c'
        ]

        return SystemUtils.executeCommand(cmd)
Exemplo n.º 13
0
    def _runFlashDebug(self):
        sets = self._projectData

        cmd = [
            'C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe',
            FileUtils.createPath(sets.platformBinPath, sets.contentTargetFilename + '.swf') ]

        result = SystemUtils.executeCommand(cmd)
        if result['code']:
            self._log.write(result['out'])
            return 1

        return 0
Exemplo n.º 14
0
    def _runImpl(self):
        """Doc..."""
        self._log.write('<div style="font-size:24px;">Deploying IOS Simulator</div>')

        sets = self._settings
        sets.setPlatform(FlexProjectData.IOS_PLATFORM)

        adtCommand = self.parent().mainWindow.getRootAIRPath(
            sets.airVersion, 'bin', 'adt', isFile=True)

        targetPath = FileUtils.createPath(
            sets.platformDistributionPath,
            sets.contentTargetFilename + '.' + sets.airExtension,
            isFile=True)

        cmd = [adtCommand, '-installApp', '-platform', 'ios', '-platformsdk',
            '"%s"' % sets.iosSimulatorSdkPath, '-device', 'ios-simulator',
            '-package', targetPath]

        result = SystemUtils.executeCommand(cmd)
        if result['code']:
            self._log.write('Failed simulator installation')
            return 1
        self._log.write('Application installed to simulator')

        cmd = [adtCommand, '-launchApp', '-platform', 'ios', '-platformsdk',
            '"%s"' % sets.iosSimulatorSdkPath, '-device', 'ios-simulator',
            '-appid', '"%s"' % sets.appId]

        self._log.write('Launching simulator')

        result = SystemUtils.executeCommand(cmd)
        if result['code']:
            print result
            self._log.write('Failed simulator execution')
            return 1
        self._log.write('Simulator execution complete')

        return 0
Exemplo n.º 15
0
    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
Exemplo n.º 16
0
    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
Exemplo n.º 17
0
    def _createWindowsInstaller(self, binPath):
        self._createNsisInstallerScript(binPath)

        nsisPath = 'C:\\Program Files (x86)\\NSIS\\makensis.exe'
        if os.path.exists(nsisPath):
            print 'PACKAGING: NSIS Installer'
            result = SystemUtils.executeCommand('"%s" "%s"' % (
                nsisPath, FileUtils.createPath(binPath, 'installer.nsi', isFile=True)))
            if result['code']:
                print 'PACKAGING ERROR:'
                print result['error']
                return False

        return True
Exemplo n.º 18
0
    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
Exemplo n.º 19
0
    def _runDump(self):
        self._log.write(u'<div style="font-size:24px">Retrieving Android Logcat...</div>\n')

        command = 'adb.exe' if OsUtils.isWindows() else 'adb'
        cmd = [
            '"%s"' % self.parent().mainWindow.getAndroidSDKPath('platform-tools', command),
            'logcat',
            '-d',
            '-v', 'long']

        result = SystemUtils.executeCommand(cmd)
        if 'out' in result:
            out = result['out']

            res = AndroidLogcatThread._LOGCAT_HEADER_RE.finditer(out)
            if res:
                entries = []
                for r in res:
                    if entries:
                        entries[-1]['value'] = out[entries[-1]['res'].end():r.start()].strip()
                    entries.append({
                        'res':r,
                        'level':r.groupdict()['level'],
                        'pid':r.groupdict()['pid'],
                        'time':r.groupdict()['time'],
                        'id':r.groupdict()['id'] })
                if entries:
                    entries[-1]['value'] = out[entries[-1]['res'].end():].strip()

                res = ''
                for item in entries:
                    if 'value' not in item:
                        continue

                    item = self._parseLogEntry(item)

                    if item.ignore:
                        res += u'<div style="color:#999999;font-size:10px;">' + item.value + u'</div>'
                        continue

                    res += u'<div style="font-size:5px;">.</div><div style="color:' + item.color \
                        + u';font-size:14px;">' \
                        + u'<span style="background-color:' + item.backColor \
                        + u';font-size:10px;">[' + item.id \
                        + u']</span> ' + item.value + u'</div><div style="font-size:5px;">.</div>'

                if res:
                    result['out'] = res

        return result
Exemplo n.º 20
0
    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])
Exemplo n.º 21
0
    def _runAirDebug(self):
        pd = self._projectData

        if OsUtils.isWindows() and pd.hasPlatform(FlexProjectData.WINDOWS_PLATFORM):
            pd.setPlatform(FlexProjectData.WINDOWS_PLATFORM)
        elif OsUtils.isMac() and pd.hasPlatform(FlexProjectData.MAC_PLATFORM):
            pd.setPlatform(FlexProjectData.MAC_PLATFORM)
        elif pd.hasPlatform(FlexProjectData.AIR_PLATFORM):
            pd.setPlatform(FlexProjectData.AIR_PLATFORM)

        if not pd.updateApplicationConfigFile():
            self._log.write([
                'ERROR: Unable to update the application descriptor file',
                'PATH: ' + pd.appDescriptorPath,
                'VERSION: ' + pd.airVersion,
                'ID: ' + pd.appId ])
            return 1


        adlCommand    = 'adl.exe' if PyGlassEnvironment.isWindows else 'adl'
        appDescriptor = FileUtils.createPath(pd.projectPath, 'application.xml', isFile=True)

        cmd = [
            self.parent().mainWindow.getRootAIRPath(pd.airVersion, 'bin', adlCommand),
            '-profile', 'extendedDesktop']

        aneDebugPath = AirUtils.deployDebugNativeExtensions(cmd, pd)

        cmd += [appDescriptor, pd.platformBinPath]

        deployment = AirUtils.deployExternalIncludes(self._projectData)
        code       = 0
        try:
            os.chdir(FileUtils.createPath(pd.projectPath, isDir=True))
            print 'PLATFORM:', pd.currentPlatformID
            print 'LOCATION:', os.path.abspath(os.curdir)
            print 'COMMAND:', cmd

            result = SystemUtils.executeCommand(cmd)
            if result['code']:
                self._log.write('RESULT ERROR CODE: ' + str(result['code']) + '\n' + result['out'])
                code = 1
        except Exception, err:
            self._log.writeError('DEBUG ATTEMPT FAILED', err)
            code = 1
Exemplo n.º 22
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()
Exemplo n.º 23
0
    def _runImpl(self):
        sets = self._settings

        if not self._settings.hasPlatform(FlexProjectData.ANDROID_PLATFORM):
            self._log.write('ERROR: No Android platform information found. Install aborted.')
            return 1

        self._settings.setPlatform(FlexProjectData.ANDROID_PLATFORM)

        self._log.write(
            '<div style="font-size:24px">Installing APK...</div>\n'
            + '(This can take a few minutes. Please stand by)'
        )

        command = 'adb.exe' if OsUtils.isWindows() else 'adb'
        cmd = [
            '"%s"' % self.parent().mainWindow.getAndroidSDKPath('platform-tools', command),
            'install',
            '-r',
            FileUtils.createPath(
                sets.platformDistributionPath, sets.contentTargetFilename + '.' + sets.airExtension)
        ]

        result = SystemUtils.executeCommand(cmd)

        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>'
            )

        return result['code']
Exemplo n.º 24
0
    def compileCss(cls, site, path):
        outPath = FileUtils.changePathRoot(
            path, site.sourceWebRootPath, site.targetWebRootPath)
        FileUtils.getDirectoryOf(outPath, createIfMissing=True)

        if site.isLocal:
            shutil.copy(path, outPath)
            site.writeLogSuccess(u'COPIED', unicode(path))
        else:
            cmd = cls.modifyNodeCommand([
                FileUtils.createPath(
                    StaticFlowEnvironment.nodePackageManagerPath, 'minify', isFile=True),
                '"%s"' % path,
                '"%s"' % outPath])

            iniDirectory = os.curdir
            os.chdir(os.path.dirname(path))
            result = SystemUtils.executeCommand(cmd)
            if result['code']:
                site.logger.write(unicode(result['error']))
                site.writeLogError(u'CSS compilation failure:', extras={
                    'PATH':path,
                    'ERROR':result['error']})
                os.chdir(iniDirectory)
                return False

            site.writeLogSuccess(u'COMPRESSED', unicode(path))
            os.chdir(iniDirectory)

        source = FileUtils.getContents(outPath)
        if not source:
            return False
        FileUtils.putContents(
            cls._CSS_CDN_IMAGE_RE.sub('url(\g<quote>' + site.cdnRootUrl + '/', source),
            outPath)

        lastModified = FileUtils.getUTCModifiedDatetime(path)
        SiteProcessUtils.createHeaderFile(outPath, lastModified)
        cls.copyToCdnFolder(outPath, site, lastModified)
        return True
Exemplo n.º 25
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()
Exemplo n.º 26
0
    def createFavicon(cls, site):
        sourceFilename = site.get('FAVICON_SOURCE')
        if not sourceFilename:
            return True

        sourcePath = FileUtils.createPath(
            site.sourceWebRootPath,
            sourceFilename.strip('/'), isFile=True)

        if not os.path.exists(sourcePath):
            site.writeLogWarning(u'Favicon source file not found "%s"' % sourceFilename)
            return False

        img = LocalImage(sourcePath, site)
        if not img.exists:
            return False

        targetPath = FileUtils.createPath(site.targetWebRootPath, 'favicon.ico')

        cmd = ['convert', '"%s"' % sourcePath, '-bordercolor', 'white', '-border', '0',
          '\( -clone 0 -resize 16x16 \)']

        if img.width >= 32:
          cmd.append('\( -clone 0 -resize 32x32 \)')
        if img.width >= 48:
          cmd.append('\( -clone 0 -resize 48x48 \)')
        if img.width >= 64:
          cmd.append('\( -clone 0 -resize 64x64 \)')

        cmd.extend(['-delete', '0', '-alpha', 'off', '-colors', '256', '"%s"' % targetPath])

        result = SystemUtils.executeCommand(cmd)
        if result['code']:
            site.writeLogWarning(u'Unable to create favicon.ico file')
            return False

        return True
Exemplo n.º 27
0
 def _getOsxDisplayInfo(cls):
     from pyaid.system.SystemUtils import SystemUtils
     return SystemUtils.executeCommand(['system_profiler', 'SPDisplaysDataType'])
Exemplo n.º 28
0
 def reopenServer(cls, path):
     os.chdir(path)
     return SystemUtils.executeCommand('nginx -s reopen')
Exemplo n.º 29
0
    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
Exemplo n.º 30
0
 def stopServer(cls, path, force =False):
     os.chdir(path)
     if force:
         return SystemUtils.executeCommand('nginx -s stop')
     return SystemUtils.executeCommand('nginx -s quit')
Exemplo n.º 31
0
        # this returns the path to the shared directory resources/apps/CadenceApplication
        # to get self.getAppResourcePath()

"""

sourceFile = fileName
destinationFile = 'testDELETEME.pdf'

cmd = [
    '/Applications/Inkscape.app/Contents/Resources/bin/inkscape',
    '-f',
    None,
    '-A',
    None]

cmd[2] = sourceFile
cmd[4] = destinationFile

print(cmd)
response = SystemUtils.executeCommand(cmd)





#==================================================================================================

session.close()
print 'Test Complete'
Exemplo n.º 32
0
            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, 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)
Exemplo n.º 33
0
 def stopServer(cls, path, force=False):
     os.chdir(path)
     if force:
         return SystemUtils.executeCommand('nginx -s stop')
     return SystemUtils.executeCommand('nginx -s quit')
Exemplo n.º 34
0
 def reopenServer(cls, path):
     os.chdir(path)
     return SystemUtils.executeCommand('nginx -s reopen')
Exemplo n.º 35
0
 def getExePath(cls):
     result = SystemUtils.executeCommand('where nginx')
     if result['code']:
         return None
     nginxExePath   = result['out'].strip()
     return os.path.dirname(nginxExePath)
Exemplo n.º 36
0
    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:
    print u'\t', foundLocation
Exemplo n.º 37
0
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:
Exemplo n.º 38
0
    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