示例#1
0
    def process(self, session, **kwargs):
        """Implement the behavior for when the action is triggered

        Args:
            session (dict): environment dictionary

        Returns:
            Popen instance of newly spawned process

        """

        with pype.modified_environ(**session):
            # Get executable by name
            app = lib.get_application(self.name)
            executable = lib.which(app["executable"])

            # Run as server
            arguments = []

            tools_env = acre.get_tools([self.name])
            env = acre.compute(tools_env)
            env = acre.merge(env, current_env=dict(os.environ))

            if not env.get('AVALON_WORKDIR', None):
                pype.load_data_from_templates()
                os.environ["AVALON_WORKDIR"] = pype.get_workdir_template(
                    pype.Anatomy)
                pype.reset_data_from_templates()

            env.update(dict(os.environ))

            lib.launch(executable=executable, args=arguments, environment=env)
            return
示例#2
0
    def process(self, session, **kwargs):
        """Implement the behavior for when the action is triggered

        Args:
            session (dict): environment dictionary

        Returns:
            Popen instance of newly spawned process

        """

        with pype.modified_environ(**session):
            # Get executable by name
            app = lib.get_application(self.name)
            executable = lib.which(app["executable"])

            # Run as server
            arguments = []

            tools_env = acre.get_tools([self.name])
            env = acre.compute(tools_env)
            env = acre.merge(env, current_env=dict(os.environ))

            if not env.get('AVALON_WORKDIR', None):
                project_name = env.get("AVALON_PROJECT")
                anatomy = Anatomy(project_name)
                os.environ['AVALON_PROJECT'] = project_name
                io.Session['AVALON_PROJECT'] = project_name

                task_name = os.environ.get("AVALON_TASK",
                                           io.Session["AVALON_TASK"])
                asset_name = os.environ.get("AVALON_ASSET",
                                            io.Session["AVALON_ASSET"])
                application = lib.get_application(
                    os.environ["AVALON_APP_NAME"])

                project_doc = io.find_one({"type": "project"})
                data = {
                    "task": task_name,
                    "asset": asset_name,
                    "project": {
                        "name": project_doc["name"],
                        "code": project_doc["data"].get("code", '')
                    },
                    "hierarchy": pype.get_hierarchy(),
                    "app": application["application_dir"]
                }
                anatomy_filled = anatomy.format(data)
                workdir = anatomy_filled["work"]["folder"]

                os.environ["AVALON_WORKDIR"] = workdir

            env.update(dict(os.environ))

            lib.launch(executable=executable, args=arguments, environment=env)
            return
示例#3
0
    def process(self, session, **kwargs):
        """Implement the behavior for when the action is triggered

        Args:
            session (dict): environment dictionary

        Returns:
            Popen instance of newly spawned process

        """

        # Update environment with session
        env = os.environ.copy()
        env.update(session)

        # Get executable by name
        app = lib.get_application(self.name)
        env.update(app["environment"])
        executable = lib.which(app["executable"])

        # Run as server
        arguments = ["-server", "-portNumber=20207"]

        return lib.launch(executable=executable,
                          args=arguments,
                          environment=env)
示例#4
0
 def process(self, session, **kwargs):
     asset = ''
     if 'AVALON_ASSET' in session:
         asset = session['AVALON_ASSET']
     return lib.launch(
         executable="python",
         args=[
             "-u", "-m", "pype.tools.assetcreator",
             session['AVALON_PROJECT'], asset
         ]
     )
    def launch(self, environment):

        executable = lib.which(self.config["executable"])
        if executable is None:
            raise ValueError("'%s' not found on your PATH\n%s" %
                             (self.config["executable"], os.getenv("PATH")))

        args = self.config.get("args", [])
        return lib.launch(executable=executable,
                          args=args,
                          environment=environment)
示例#6
0
    def process(self, session, **kwargs):
        environ = os.environ.copy()
        environ.update(session)

        if environ.get("AVALON_SILO") == "placeholder":
            environ["AVALON_SILO"] = ""
        if environ.get("AVALON_ASSET") == "placeholder":
            environ["AVALON_ASSET"] = ""

        return lib.launch(executable="python",
                          args=["-u", "-m", "reveries.tools.modeldiffer"],
                          environment=environ)
示例#7
0
    def process(self, session, **kwargs):
        """Implement the behavior for when the action is triggered

        Args:
            session (dict): environment dictionary

        Returns:
            Popen instance of newly spawned process

        """
        APP = "shell"

        app_definition = lib.get_application(APP)
        self.config = app_definition

        session = session.copy()
        session["AVALON_APP"] = APP
        session["AVALON_APP_NAME"] = self.name

        env = self.environ(session)

        # Get executable by name
        executable = lib.which(self.config["executable"])

        #
        # (NOTE): The result CWD path may not be accurate since the
        #         Launcher did not clean up the entry while changing
        #         frames.
        #         For example:
        #             if you were in 'ProjA > Char > Boy > modeling'
        #             and jump to 'ProjB > Prop' then launch action,
        #             you will find the CWD path is:
        #                 'ProjB > Prop > Boy > modeling'
        #             not just:
        #                 'ProjB > Prop'
        #
        cwd = env.get("AVALON_SHELL_CWD", session.get("AVALON_PROJECTS", ""))

        if cwd and not os.path.isdir(cwd):
            self.log.error("The path of `cwd` is not a directory: "
                           "{!r}".format(cwd))
            cwd = None

        return lib.launch(executable=executable,
                          args=[],
                          environment=env,
                          cwd=cwd)
    def process(self, session, **kwargs):
        from reveries import filesys

        environ = os.environ.copy()
        environ.update(session)

        app = filesys.Filesys()
        env = app.environ(session)
        environ["AVALON_WORKDIR"] = env["AVALON_WORKDIR"].replace("\\", "/")

        return lib.launch(executable="python",
                          args=[
                              "-m",
                              "reveries.tools.seqparser",
                              "--publish",
                          ],
                          environment=environ)
示例#9
0
 def process(self, session, **kwargs):
     return lib.launch(executable="python",
                       args=[
                           "-u", "-m", "avalon.tools.loader",
                           session['AVALON_PROJECT']
                       ])
示例#10
0
    def launch(self, session, entities, event):
        '''Callback method for the custom action.

        return either a bool ( True if successful or False if the action failed )
        or a dictionary with they keys `message` and `success`, the message should be a
        string and will be displayed as feedback to the user, success should be a bool,
        True if successful or False if the action failed.

        *session* is a `ftrack_api.Session` instance

        *entities* is a list of tuples each containing the entity type and the entity id.
        If the entity is a hierarchical you will always get the entity
        type TypedContext, once retrieved through a get operation you
        will have the "real" entity type ie. example Shot, Sequence
        or Asset Build.

        *event* the unmodified original event

        '''

        entity = entities[0]
        project_name = entity['project']['full_name']

        database = pypelib.get_avalon_database()

        # Get current environments
        env_list = [
            'AVALON_PROJECT', 'AVALON_SILO', 'AVALON_ASSET', 'AVALON_TASK',
            'AVALON_APP', 'AVALON_APP_NAME'
        ]
        env_origin = {}
        for env in env_list:
            env_origin[env] = os.environ.get(env, None)

        # set environments for Avalon
        os.environ["AVALON_PROJECT"] = project_name
        os.environ["AVALON_SILO"] = entity['ancestors'][0]['name']
        os.environ["AVALON_ASSET"] = entity['parent']['name']
        os.environ["AVALON_TASK"] = entity['name']
        os.environ["AVALON_APP"] = self.identifier.split("_")[0]
        os.environ["AVALON_APP_NAME"] = self.identifier

        anatomy = Anatomy()

        hierarchy = ""
        parents = database[project_name].find_one({
            "type":
            'asset',
            "name":
            entity['parent']['name']
        })['data']['parents']

        if parents:
            hierarchy = os.path.join(*parents)

        application = avalonlib.get_application(os.environ["AVALON_APP_NAME"])

        data = {
            "root": os.environ.get("PYPE_STUDIO_PROJECTS_MOUNT"),
            "project": {
                "name": entity['project']['full_name'],
                "code": entity['project']['name']
            },
            "task": entity['name'],
            "asset": entity['parent']['name'],
            "app": application["application_dir"],
            "hierarchy": hierarchy,
        }

        av_project = database[project_name].find_one({"type": 'project'})
        templates = None
        if av_project:
            work_template = av_project.get('config',
                                           {}).get('template',
                                                   {}).get('work', None)
        work_template = None
        try:
            work_template = work_template.format(**data)
        except Exception:
            try:
                anatomy = anatomy.format(data)
                work_template = anatomy["work"]["folder"]

            except Exception as exc:
                msg = "{} Error in anatomy.format: {}".format(
                    __name__, str(exc))
                self.log.error(msg, exc_info=True)
                return {'success': False, 'message': msg}

        workdir = os.path.normpath(work_template)
        os.environ["AVALON_WORKDIR"] = workdir
        try:
            os.makedirs(workdir)
        except FileExistsError:
            pass

        # collect all parents from the task
        parents = []
        for item in entity['link']:
            parents.append(session.get(item['type'], item['id']))

        # collect all the 'environment' attributes from parents
        tools_attr = [os.environ["AVALON_APP"], os.environ["AVALON_APP_NAME"]]
        for parent in reversed(parents):
            # check if the attribute is empty, if not use it
            if parent['custom_attributes']['tools_env']:
                tools_attr.extend(parent['custom_attributes']['tools_env'])
                break

        tools_env = acre.get_tools(tools_attr)
        env = acre.compute(tools_env)
        env = acre.merge(env, current_env=dict(os.environ))
        env = acre.append(dict(os.environ), env)

        #
        # tools_env = acre.get_tools(tools)
        # env = acre.compute(dict(tools_env))
        # env = acre.merge(env, dict(os.environ))
        # os.environ = acre.append(dict(os.environ), env)
        # os.environ = acre.compute(os.environ)

        # Get path to execute
        st_temp_path = os.environ['PYPE_CONFIG']
        os_plat = platform.system().lower()

        # Path to folder with launchers
        path = os.path.join(st_temp_path, 'launchers', os_plat)
        # Full path to executable launcher
        execfile = None

        if sys.platform == "win32":

            for ext in os.environ["PATHEXT"].split(os.pathsep):
                fpath = os.path.join(path.strip('"'), self.executable + ext)
                if os.path.isfile(fpath) and os.access(fpath, os.X_OK):
                    execfile = fpath
                    break
                pass

            # Run SW if was found executable
            if execfile is not None:
                avalonlib.launch(executable=execfile, args=[], environment=env)
            else:
                return {
                    'success':
                    False,
                    'message':
                    "We didn't found launcher for {0}".format(self.label)
                }
                pass

        if sys.platform.startswith('linux'):
            execfile = os.path.join(path.strip('"'), self.executable)
            if os.path.isfile(execfile):
                try:
                    fp = open(execfile)
                except PermissionError as p:
                    self.log.exception('Access denied on {0} - {1}'.format(
                        execfile, p))
                    return {
                        'success':
                        False,
                        'message':
                        "Access denied on launcher - {}".format(execfile)
                    }
                fp.close()
                # check executable permission
                if not os.access(execfile, os.X_OK):
                    self.log.error(
                        'No executable permission on {}'.format(execfile))
                    return {
                        'success': False,
                        'message':
                        "No executable permission - {}".format(execfile)
                    }
                    pass
            else:
                self.log.error('Launcher doesn\'t exist - {}'.format(execfile))
                return {
                    'success': False,
                    'message': "Launcher doesn't exist - {}".format(execfile)
                }
                pass
            # Run SW if was found executable
            if execfile is not None:
                avalonlib.launch('/usr/bin/env',
                                 args=['bash', execfile],
                                 environment=env)
            else:
                return {
                    'success':
                    False,
                    'message':
                    "We didn't found launcher for {0}".format(self.label)
                }
                pass

        # Change status of task to In progress
        presets = config.get_presets()["ftrack"]["ftrack_config"]

        if 'status_update' in presets:
            statuses = presets['status_update']

            actual_status = entity['status']['name'].lower()
            next_status_name = None
            for key, value in statuses.items():
                if actual_status in value or '_any_' in value:
                    if key != '_ignore_':
                        next_status_name = key
                    break

            if next_status_name is not None:
                try:
                    query = 'Status where name is "{}"'.format(
                        next_status_name)
                    status = session.query(query).one()
                    entity['status'] = status
                    session.commit()
                except Exception:
                    msg = ('Status "{}" in presets wasn\'t found on Ftrack'
                           ).format(next_status_name)
                    self.log.warning(msg)

        # Set origin avalon environments
        for key, value in env_origin.items():
            if value == None:
                value = ""
            os.environ[key] = value

        return {'success': True, 'message': "Launching {0}".format(self.label)}
示例#11
0
文件: actions.py 项目: jrsndl/pype
 def process(self, session, **kwargs):
     return lib.launch(executable="python",
                       args=["-u", "-m", "avalon.tools.libraryloader"])
 def process(self, session, **kwargs):
     return lib.launch(executable="python",
                       args=["-u", "-m", "reveries.tools.projectmember"])
示例#13
0
 def process(self, session, **kwargs):
     env = os.environ.copy()
     env.update(session)
     return lib.launch(executable="python",
                       environment=env,
                       args=[__file__])