Esempio n. 1
0
    def clearProjectGeneratedFiles(self, projectName, addHeading = True):

        if addHeading:
            self._log.heading('Clearing generated files for project {0}'.format(projectName))

        self._junctionHelper.removeJunctionsInDirectory('[UnityProjectsDir]/{0}'.format(projectName), True)

        for platform in Platforms.All:
            self.setPathsForProject(projectName, platform)

            if os.path.exists(self._varMgr.expandPath('[ProjectPlatformRoot]')):
                platformRootPath = self._varMgr.expand('[ProjectPlatformRoot]')

                try:
                    shutil.rmtree(platformRootPath)
                except:
                    self._log.warn('Unable to remove path {0}.  Trying to kill adb.exe to see if that will help...'.format(platformRootPath))
                    MiscUtil.tryKillAdbExe(self._sys)

                    try:
                        shutil.rmtree(platformRootPath)
                    except:
                        self._log.error('Still unable to remove path {0}!  A running process may have one of the files locked.  Ensure you have closed down unity / visual studio / etc.'.format(platformRootPath))
                        raise

                self._log.debug('Removed project directory {0}'.format(platformRootPath))
                self._log.good('Successfully deleted project {0} ({1})'.format(projectName, platform))
            else:
                self._log.debug('Project {0} ({1}) already deleted'.format(projectName, platform))

            # Remove the solution files and the suo files etc.
            self._sys.removeByRegex('[ProjectRoot]/[ProjectName]-[Platform].*')
Esempio n. 2
0
    def _installReleaseInternal(self,
                                releaseInfo,
                                releaseSource,
                                suppressPrompts=False):

        self._log.heading("Installing release '{0}' (version {1})",
                          releaseInfo.name, releaseInfo.version)

        installDirName = None

        for packageInfo in self._packageManager.getAllPackageInfos():
            installInfo = packageInfo.installInfo

            if installInfo and installInfo.releaseInfo and installInfo.releaseInfo.id == releaseInfo.id:
                if installInfo.releaseInfo.versionCode == releaseInfo.versionCode:
                    if not suppressPrompts:
                        shouldContinue = MiscUtil.confirmChoice(
                            "Release '{0}' (version {1}) is already installed.  Would you like to re-install anyway?  Note that this will overwrite any local changes you've made to it."
                            .format(releaseInfo.name, releaseInfo.version))

                        assertThat(shouldContinue, 'User aborted')
                else:
                    print(
                        "\nFound release '{0}' already installed with version '{1}'"
                        .format(releaseInfo.name, releaseInfo.version),
                        end='')

                    installDirection = 'UPGRADE' if releaseInfo.versionCode > installInfo.releaseInfo.versionCode else 'DOWNGRADE'

                    if not suppressPrompts:
                        shouldContinue = MiscUtil.confirmChoice(
                            "Are you sure you want to {0} '{1}' from version '{2}' to version '{3}'? (y/n)"
                            .format(installDirection, releaseInfo.name,
                                    installInfo.releaseInfo.version,
                                    releaseInfo.version))
                        assertThat(shouldContinue, 'User aborted')

                self._packageManager.deletePackage(packageInfo.name)
                # Retain original directory name in case it is referenced by other packages
                installDirName = packageInfo.name

        installDirName = releaseSource.installRelease(releaseInfo,
                                                      installDirName)

        destDir = self._varMgr.expand(
            '[UnityPackagesDir]/{0}'.format(installDirName))

        assertThat(self._sys.directoryExists(destDir),
                   'Expected dir "{0}" to exist', destDir)

        newInstallInfo = PackageInstallInfo()
        newInstallInfo.releaseInfo = releaseInfo
        newInstallInfo.installDate = datetime.utcnow()

        yamlStr = YamlSerializer.serialize(newInstallInfo)
        self._sys.writeFileAsText(os.path.join(destDir, InstallInfoFileName),
                                  yamlStr)

        self._log.info("Successfully installed '{0}' (version {1})",
                       releaseInfo.name, releaseInfo.version)
Esempio n. 3
0
    def run(self, project, platform, requestId, param1, param2):
        self._log.debug("Started EditorApi with arguments: {0}".format(" ".join(sys.argv[1:])))

        self._project = project
        self._platform = platform
        self._requestId = requestId
        self._param1 = param1
        self._param2 = param2

        succeeded = True

        # This is repeated in __main__ but this is better because
        # it will properly log detailed errors to the file log instead of to the console
        try:
            self._runInternal()
        except Exception as e:
            sys.stderr.write(str(e))
            self._log.error(str(e))

            if not MiscUtil.isRunningAsExe():
                self._log.error('\n' + traceback.format_exc())

            succeeded = False

        if not succeeded:
            sys.exit(1)
Esempio n. 4
0
    def run(self, project, platform, requestId, param1, param2):
        self._log.debug("Started EditorApi with arguments: {0}".format(
            " ".join(sys.argv[1:])))

        self._project = project
        self._platform = platform
        self._requestId = requestId
        self._param1 = param1
        self._param2 = param2

        succeeded = True

        # This is repeated in __main__ but this is better because
        # it will properly log detailed errors to the file log instead of to the console
        try:
            self._runInternal()
        except Exception as e:
            sys.stderr.write(str(e))
            self._log.error(str(e))

            if not MiscUtil.isRunningAsExe():
                self._log.error('\n' + traceback.format_exc())

            succeeded = False

        if not succeeded:
            sys.exit(1)
Esempio n. 5
0
    def _installReleaseInternal(self, releaseInfo, releaseSource, suppressPrompts = False):

        self._log.heading("Installing release '{0}' (version {1})", releaseInfo.name, releaseInfo.version)

        installDirName = None

        for packageInfo in self._packageManager.getAllPackageInfos():
            installInfo = packageInfo.installInfo

            if installInfo and installInfo.releaseInfo and installInfo.releaseInfo.id == releaseInfo.id:
                if installInfo.releaseInfo.versionCode == releaseInfo.versionCode:
                    if not suppressPrompts:
                        shouldContinue = MiscUtil.confirmChoice(
                            "Release '{0}' (version {1}) is already installed.  Would you like to re-install anyway?  Note that this will overwrite any local changes you've made to it.".format(releaseInfo.name, releaseInfo.version))

                        assertThat(shouldContinue, 'User aborted')
                else:
                    print("\nFound release '{0}' already installed with version '{1}'".format(releaseInfo.name, releaseInfo.version), end='')

                    installDirection = 'UPGRADE' if releaseInfo.versionCode > installInfo.releaseInfo.versionCode else 'DOWNGRADE'

                    if not suppressPrompts:
                        shouldContinue = MiscUtil.confirmChoice("Are you sure you want to {0} '{1}' from version '{2}' to version '{3}'? (y/n)".format(installDirection, releaseInfo.name, installInfo.releaseInfo.version, releaseInfo.version))
                        assertThat(shouldContinue, 'User aborted')

                self._packageManager.deletePackage(packageInfo.name)
                # Retain original directory name in case it is referenced by other packages
                installDirName = packageInfo.name

        installDirName = releaseSource.installRelease(releaseInfo, installDirName)

        destDir = self._varMgr.expand('[UnityPackagesDir]/{0}'.format(installDirName))

        assertThat(self._sys.directoryExists(destDir), 'Expected dir "{0}" to exist', destDir)

        newInstallInfo = PackageInstallInfo()
        newInstallInfo.releaseInfo = releaseInfo
        newInstallInfo.installDate = datetime.utcnow()

        yamlStr = YamlSerializer.serialize(newInstallInfo)
        self._sys.writeFileAsText(os.path.join(destDir, InstallInfoFileName), yamlStr)

        self._log.info("Successfully installed '{0}' (version {1})", releaseInfo.name, releaseInfo.version)
Esempio n. 6
0
    def __init__(self, initialParams = None):
        self._params = initialParams if initialParams else {}
        self._params['StartCurrentDir'] = os.getcwd()
        self._params['ExecDir'] = MiscUtil.getExecDirectory().replace('\\', '/')

        # We could just call self._config.getDictionary('PathVars') here but
        # then we wouldn't be able to use fallback (?) and override (!) characters in
        # our config

        self._regex = re.compile('^([^\[]*)(\[[^\]]*\])(.*)$')
Esempio n. 7
0
    def __init__(self, initialParams=None):
        self._params = initialParams if initialParams else {}
        self._params['StartCurrentDir'] = os.getcwd()
        self._params['ExecDir'] = MiscUtil.getExecDirectory().replace(
            '\\', '/')

        # We could just call self._config.getDictionary('PathVars') here but
        # then we wouldn't be able to use fallback (?) and override (!) characters in
        # our config

        self._regex = re.compile('^([^\[]*)(\[[^\]]*\])(.*)$')
Esempio n. 8
0
    def _runPreBuild(self):
        if self._args.openDocumentation:
            self._openDocumentation()

        if self._args.clearProjectGeneratedFiles:
            self._packageMgr.clearProjectGeneratedFiles(self._project)

        if self._args.clearAllProjectGeneratedFiles:
            self._packageMgr.clearAllProjectGeneratedFiles()

        if self._args.deleteAllLinks:
            self._packageMgr.deleteAllLinks()

        if self._args.deletePackage:
            if not self._args.suppressPrompts:
                if not MiscUtil.confirmChoice("Are you sure you want to delete package '{0}'? (y/n)  \nNote that this change is non-recoverable!  (unless you are using source control)  ".format(self._args.deletePackage)):
                    assertThat(False, "User aborted operation")

            self._packageMgr.deletePackage(self._args.deletePackage)

        if self._args.deleteProject:
            if not self._args.suppressPrompts:
                if not MiscUtil.confirmChoice("Are you sure you want to delete project '{0}'? (y/n)  \nNote that this will only delete your unity project settings and the {1} for this project.  \nThe rest of the content for your project will remain in the UnityPackages folder  ".format(self._args.deleteProject, ProjectConfigFileName)):
                    assertThat(False, "User aborted operation")
            self._packageMgr.deleteProject(self._args.deleteProject)

        if self._args.installRelease:
            releaseName, releaseVersion = self._args.installRelease
            self._releaseSourceManager.installReleaseByName(releaseName, releaseVersion)

        if self._args.init:
            self._packageMgr.updateLinksForAllProjects()

        if self._args.updateLinks:
            self._packageMgr.updateProjectJunctions(self._project, self._platform)

        if self._args.updateUnitySolution:
            self._vsSolutionHelper.updateUnitySolution(self._project, self._platform)

        if self._args.updateCustomSolution:
            self._vsSolutionHelper.updateCustomSolution(self._project, self._platform)
Esempio n. 9
0
    def openFile(self, filePath, lineNo, project, platform):
        if not lineNo or lineNo <= 0:
            lineNo = 1

        if MiscUtil.doesProcessExist('^devenv\.exe$'):
            self.openFileInExistingVisualStudioInstance(filePath, lineNo)

            # This works too but doesn't allow going to a specific line
            #self._sys.executeNoWait('[VisualStudioCommandLinePath] /edit "{0}"'.format(filePath))
        else:
            # Unfortunately, in this case we can't pass in the line number
            self.openCustomSolution(project, platform, filePath)
Esempio n. 10
0
def installPlugins():

    if MiscUtil.isRunningAsExe():
        # Must be running from source for plugins
        return

    import importlib

    pluginDir = getPluginDirPath()

    for filePath in findFilesByPattern(pluginDir, '*.py'):
        basePath = filePath[len(pluginDir) + 1:]
        basePath = os.path.splitext(basePath)[0]
        basePath = basePath.replace('\\', '.')
        importlib.import_module('plugins.' + basePath)
Esempio n. 11
0
    def _updateDirLinksForSchema(self, schema):
        self._removePackageJunctions()

        self._sys.deleteDirectoryIfExists('[PluginsDir]/Projeny')

        if self._config.getBool('LinkToProjenyEditorDir') and not MiscUtil.isRunningAsExe():
            self._junctionHelper.makeJunction('[ProjenyDir]/UnityPlugin/Projeny', '[PluginsDir]/Projeny/Editor/Source')
        else:
            dllOutPath = '[PluginsDir]/Projeny/Editor/Projeny.dll'
            self._sys.copyFile('[ProjenyUnityEditorDllPath]', dllOutPath)
            self._sys.copyFile('[ProjenyUnityEditorDllMetaFilePath]', dllOutPath + '.meta')

            self._sys.copyFile('[YamlDotNetDllPath]', '[PluginsDir]/Projeny/Editor/YamlDotNet.dll')

            assetsOutPath = '[PluginsDir]/Projeny/Editor/Assets'
            self._sys.copyDirectory('[ProjenyUnityEditorAssetsDirPath]', assetsOutPath)
            settingsFileOutPath = os.path.join(assetsOutPath, 'Resources/Projeny/PmSettings.asset')
            self._sys.writeFileAsText(settingsFileOutPath, self._sys.readFileAsText(settingsFileOutPath).replace(
                'm_Script: {fileID: 11500000, guid: 01fe9b81f68762b438dd4eecbcfe2900, type: 3}',
                'm_Script: {fileID: 1582608718, guid: b7b2ba04b543d234aa4225d91c60af2b, type: 3}'))

        self._createSwitchProjectMenuScript(schema.name, '[PluginsDir]/Projeny/Editor/ProjenyChangeProjectMenu.cs')

        self._createPlaceholderCsFile('[PluginsDir]/Projeny/Placeholder.cs')
        self._createPlaceholderCsFile('[PluginsDir]/Projeny/Editor/Placeholder.cs')

        for packageInfo in schema.packages.values():

            self._log.debug('Processing package "{0}"'.format(packageInfo.name))

            sourceDir = self._varMgr.expandPath('[UnityPackagesDir]/{0}'.format(packageInfo.name))

            self._validateDirForFolderType(packageInfo, sourceDir)

            assertThat(os.path.exists(sourceDir),
               "Could not find package with name '{0}' while processing schema '{1}'.  See build log for full object graph to see where it is referenced".format(packageInfo.name, schema.name))

            outputPackageDir = self._varMgr.expandPath(packageInfo.outputDirVar)

            linkDir = os.path.join(outputPackageDir, packageInfo.name)

            assertThat(not os.path.exists(linkDir), "Did not expect this path to exist: '{0}'".format(linkDir))

            self._junctionHelper.makeJunction(sourceDir, linkDir)
Esempio n. 12
0
def installBindings(mainConfigPath = None):

    projenyDir = getProjenyDir()
    projenyConfigPath = os.path.join(projenyDir, ConfigFileName)

    # Put the standard config first so it can be over-ridden by user settings
    configPaths = [projenyConfigPath]

    if mainConfigPath:
        assertThat(os.path.isfile(mainConfigPath), 'Could not find file at "{0}"', mainConfigPath)
        configPaths += [mainConfigPath]

    configPaths += getExtraUserConfigPaths()

    Container.bind('Config').toSingle(Config, loadYamlFilesThatExist(*configPaths))

    initialVars = { 'ProjenyDir': projenyDir, }

    if mainConfigPath:
        initialVars['ConfigDir'] = os.path.dirname(mainConfigPath)

    if not MiscUtil.isRunningAsExe():
        initialVars['PythonPluginDir'] = getPluginDirPath()

    Container.bind('VarManager').toSingle(VarManager, initialVars)
    Container.bind('SystemHelper').toSingle(SystemHelper)
    Container.bind('Logger').toSingle(Logger)
    Container.bind('UnityHelper').toSingle(UnityHelper)
    Container.bind('ScriptRunner').toSingle(ScriptRunner)
    Container.bind('PackageManager').toSingle(PackageManager)
    Container.bind('ProcessRunner').toSingle(ProcessRunner)
    Container.bind('JunctionHelper').toSingle(JunctionHelper)
    Container.bind('VisualStudioSolutionGenerator').toSingle(VisualStudioSolutionGenerator)
    Container.bind('VisualStudioHelper').toSingle(VisualStudioHelper)
    Container.bind('ProjectSchemaLoader').toSingle(ProjectSchemaLoader)
    Container.bind('CommonSettings').toSingle(CommonSettings)
    Container.bind('UnityPackageExtractor').toSingle(UnityPackageExtractor)
    Container.bind('ZipHelper').toSingle(ZipHelper)
    Container.bind('UnityPackageAnalyzer').toSingle(UnityPackageAnalyzer)

    Container.bind('ReleaseSourceManager').toSingle(ReleaseSourceManager)
Esempio n. 13
0
def getProjenyDir():
    # This works for both exe builds (Bin/Prj/Data/Prj.exe) and running from source (Source/prj/main/Prj.py) by coincidence
    return os.path.join(MiscUtil.getExecDirectory(), '../../..')
Esempio n. 14
0
def getPluginDirPath():
    return os.path.join(MiscUtil.getExecDirectory(), '../../plugins')
Esempio n. 15
0
    installBindings(tryGetMainConfigPath(args))
    installPlugins()

    PrjRunner().run(args)

if __name__ == '__main__':

    if (sys.version_info < (3, 0)):
        print('Wrong version of python!  Install python 3 and try again')
        sys.exit(2)

    succeeded = True

    try:
        main()

    except KeyboardInterrupt as e:
        print('Operation aborted by user by hitting CTRL+C')
        succeeded = False

    except Exception as e:
        sys.stderr.write(str(e))

        if not MiscUtil.isRunningAsExe():
            sys.stderr.write('\n' + traceback.format_exc())

        succeeded = False

    if not succeeded:
        sys.exit(1)