Example #1
0
    def __init__(self, root, source):
        super(Application, self).__init__(sys.argv)
        self.setWindowIcon(QtGui.QIcon(ICON_PATH))

        engine = QtQml.QQmlApplicationEngine()
        engine.objectCreated.connect(self.on_object_created)
        engine.warnings.connect(self.on_warnings)
        engine.addImportPath(QML_IMPORT_DIR)

        try:
            io.install()
        except IOError:
            raise  # Server refused to connect

        # Install actions
        from . import install
        install()

        terminal.init()

        controller = control.Controller(root, self)
        engine.rootContext().setContextProperty("controller", controller)
        engine.rootContext().setContextProperty("terminal", terminal.model)

        self._tray = None
        self.window = None
        self.engine = engine
        self.controller = controller

        engine.load(QtCore.QUrl.fromLocalFile(source))

        self.setQuitOnLastWindowClosed(False)
    def process(self, context):
        # processing starts here
        if "hierarchyContext" not in context.data:
            self.log.info("skipping IntegrateHierarchyToAvalon")
            return
        hierarchy_context = deepcopy(context.data["hierarchyContext"])

        if not io.Session:
            io.install()

        active_assets = []
        # filter only the active publishing insatnces
        for instance in context:
            if instance.data.get("publish") is False:
                continue

            if not instance.data.get("asset"):
                continue

            active_assets.append(instance.data["asset"])

        # remove duplicity in list
        self.active_assets = list(set(active_assets))
        self.log.debug("__ self.active_assets: {}".format(self.active_assets))

        hierarchy_context = self._get_assets(hierarchy_context)

        self.log.debug("__ hierarchy_context: {}".format(hierarchy_context))
        input_data = context.data["hierarchyContext"] = hierarchy_context

        self.project = None
        self.import_to_avalon(input_data)
Example #3
0
    def process(self, context):
        self.log.info("registred_hosts: `{}`".format(
            pyblish.api.registered_hosts()))
        io.install()
        # get json paths from data
        input_json_path = os.environ.get("AC_PUBLISH_INPATH")
        output_json_path = os.environ.get("AC_PUBLISH_OUTPATH")

        rqst_json_data_path = Path(input_json_path)
        post_json_data_path = Path(output_json_path)

        context.data['post_json_data_path'] = str(post_json_data_path)

        # get avalon session data and convert \ to /
        _S = avalon.session

        asset = _S["AVALON_ASSET"]
        workdir = Path(_S["AVALON_WORKDIR"]).resolve()
        _S["AVALON_WORKDIR"] = str(workdir)

        context.data["avalonSession"] = _S
        self.log.info(f"__ avalonSession: `{_S}`")

        # get stagin directory from recieved path to json
        context.data["stagingDir"] = post_json_data_path.parent

        # get data from json file recieved
        with rqst_json_data_path.open(mode='r') as f:
            context.data["jsonData"] = json_data = json.load(f)
        assert json_data, "No `data` in json file"

        # get and check host type
        host = json_data.get("host", None)
        host_version = json_data.get("hostVersion", None)
        assert host, "No `host` data in json file"
        assert host_version, "No `hostVersion` data in json file"
        context.data["host"] = _S["AVALON_APP"] = host
        context.data["hostVersion"] = \
            _S["AVALON_APP_VERSION"] = host_version

        # get current file
        current_file = json_data.get("currentFile", None)
        assert current_file, "No `currentFile` data in json file"
        context.data["currentFile"] = str(Path(current_file).resolve())

        # get project data from avalon
        project_data = io.find_one({'type': 'project'})
        assert project_data, "No `project_data` data in avalon db"
        context.data["projectData"] = project_data
        self.log.debug("project_data: {}".format(project_data))

        # get asset data from avalon and fix all paths
        asset_data = io.find_one({"type": 'asset', "name": asset})["data"]
        assert asset_data, "No `asset_data` data in avalon db"

        context.data["assetData"] = asset_data

        self.log.debug("asset_data: {}".format(asset_data))
        self.log.info("rqst_json_data_path is: {}".format(rqst_json_data_path))
        self.log.info("post_json_data_path is: {}".format(post_json_data_path))
    def process(self, context):
        self.context = context
        if "hierarchyContext" not in self.context.data:
            return

        hierarchy_context = self.context.data["hierarchyContext"]

        self.session = self.context.data["ftrackSession"]
        project_name = self.context.data["projectEntity"]["name"]
        query = 'Project where full_name is "{}"'.format(project_name)
        project = self.session.query(query).one()
        auto_sync_state = project[
            "custom_attributes"][CUST_ATTR_AUTO_SYNC]

        if not io.Session:
            io.install()

        self.ft_project = None

        input_data = hierarchy_context

        # disable termporarily ftrack project's autosyncing
        if auto_sync_state:
            self.auto_sync_off(project)

        try:
            # import ftrack hierarchy
            self.import_to_ftrack(input_data)
        except Exception:
            raise
        finally:
            if auto_sync_state:
                self.auto_sync_on(project)
Example #5
0
def preflight_check(script, project):
    missing_apps = set()
    missing_resources = set()

    for job in script:
        app = job["session"]["app"]
        if not lib.which(app):
            missing_apps.add(app)

        for resource in job["resources"]:
            resourcepath = os.path.join(cd, "resources", project, resource)
            if not os.path.exists(resourcepath):
                missing_resources.add(resourcepath)

    if missing_apps:
        sys.stderr.write("ERROR: Some applications were not found.\n")
        sys.stderr.write("\n".join("- %s" % app for app in missing_apps))
        sys.stderr.write("\n")
        raise MissingApps()

    if missing_resources:
        sys.stderr.write("ERROR: Some resources were not found.\n")
        sys.stderr.write("\n".join("- %s" % resource
                                   for resource in missing_resources))
        sys.stderr.write("\n")
        raise MissingResources()

    # Look for existing project
    io.install()
    io.activate_project(project)

    if not io.find_one({"type": "project", "name": project}):
        raise MissingProject()
Example #6
0
def avalon_api_publish(data, gui=True):
    ''' Launches Pyblish (GUI by default)
    :param data: Should include data for pyblish and standalone collector
    :type data: dict
    :param gui: Pyblish will be launched in GUI mode if set to True
    :type gui: bool
    '''
    io.install()

    # Create hash name folder in temp
    chars = "".join([random.choice(string.ascii_letters) for i in range(15)])
    staging_dir = tempfile.mkdtemp(chars)

    # create also json and fill with data
    json_data_path = staging_dir + os.path.basename(staging_dir) + '.json'
    with open(json_data_path, 'w') as outfile:
        json.dump(data, outfile)

    args = ["-pp", os.pathsep.join(pyblish.api.registered_paths())]

    envcopy = os.environ.copy()
    envcopy["PYBLISH_HOSTS"] = "standalonepublisher"
    envcopy["SAPUBLISH_INPATH"] = json_data_path

    if gui:
        av_publish.show()
    else:
        returncode = execute([sys.executable, "-u", "-m", "pyblish"] + args,
                             env=envcopy)

    io.uninstall()
Example #7
0
def _prepare_publish_environments():
    """Prepares environments based on request data."""
    env = copy.deepcopy(os.environ)

    project_name = os.getenv("AVALON_PROJECT")
    asset_name = os.getenv("AVALON_ASSET")

    io.install()
    project_doc = io.find_one({
        "type": "project"
    })
    av_asset = io.find_one({
        "type": "asset",
        "name": asset_name
    })
    parents = av_asset["data"]["parents"]
    hierarchy = ""
    if parents:
        hierarchy = "/".join(parents)

    env["AVALON_PROJECT"] = project_name
    env["AVALON_ASSET"] = asset_name
    env["AVALON_TASK"] = os.getenv("AVALON_TASK")
    env["AVALON_WORKDIR"] = os.getenv("AVALON_WORKDIR")
    env["AVALON_HIERARCHY"] = hierarchy
    env["AVALON_PROJECTCODE"] = project_doc["data"].get("code", "")
    env["AVALON_APP"] = f"hosts.{publish_host}"
    env["AVALON_APP_NAME"] = "celaction_local"

    env["PYBLISH_HOSTS"] = publish_host

    os.environ.update(env)
Example #8
0
 def show_launcher(self):
     # if app_launcher don't exist create it/otherwise only show main window
     if self.app_launcher is None:
         io.install()
         APP_PATH = launcher_lib.resource("qml", "main.qml")
         self.app_launcher = launcher_widget.Launcher(APP_PATH)
     self.app_launcher.window.show()
Example #9
0
def _cli():
    import argparse

    parser = argparse.ArgumentParser(__doc__)

    parser.add_argument("--silo",
                        help="Optional container of silos",
                        action="append",
                        default=["assets", "film"])
    parser.add_argument("--silo-parent", help="Optional silo silo_parent")
    parser.add_argument("--init",
                        action="store_true",
                        help="Start a new project")
    parser.add_argument("--save",
                        action="store_true",
                        help="Save inventory from disk to database")
    parser.add_argument("--load",
                        action="store_true",
                        help="Load inventory from database to disk")
    parser.add_argument("--extract",
                        action="store_true",
                        help="Generate config and inventory "
                             "from assets already on disk.")
    parser.add_argument("--overwrite",
                        action="store_true",
                        help="Overwrite exitsing assets on upload")
    parser.add_argument("--upload",
                        action="store_true",
                        help="Upload generated project to database.")
    parser.add_argument("--root", help="Absolute path to project.")

    kwargs = parser.parse_args()

    root = kwargs.root or os.getcwd()
    name = os.path.basename(root)

    if any([kwargs.load, kwargs.save, kwargs.upload, kwargs.init]):
        os.environ["AVALON_PROJECT"] = name
        io.install()

    if kwargs.init:
        config, inventory = init(name)
        _write(root, "config", config)
        _write(root, "inventory", inventory)
        print("Success!")

    elif kwargs.load:
        config, inventory = load(name)
        _write(root, "config", config)
        _write(root, "inventory", inventory)
        print("Success!")

    elif kwargs.save:
        inventory = _read(root, "inventory")
        config = _read(root, "config")
        save(name, config, inventory)
        print("Successfully saved to %s" % os.getenv("AVALON_MONGO"))

    else:
        print(__doc__)
Example #10
0
    def process(self, context):
        # get json paths from os and load them
        io.install()

        # get json file context
        input_json_path = os.environ.get("SAPUBLISH_INPATH")

        with open(input_json_path, "r") as f:
            in_data = json.load(f)
        self.log.debug(f"_ in_data: {pformat(in_data)}")

        self.add_files_to_ignore_cleanup(in_data, context)
        # exception for editorial
        if in_data["family"] == "render_mov_batch":
            in_data_list = self.prepare_mov_batch_instances(in_data)

        elif in_data["family"] in ["editorial", "background_batch"]:
            in_data_list = self.multiple_instances(context, in_data)

        else:
            in_data_list = [in_data]

        self.log.debug(f"_ in_data_list: {pformat(in_data_list)}")

        for in_data in in_data_list:
            # create instance
            self.create_instance(context, in_data)
Example #11
0
    def get_anatomy_filled(self):
        root_path = api.registered_root()
        project_name = self._S["AVALON_PROJECT"]
        asset_name = self._S["AVALON_ASSET"]

        io.install()
        project_entity = io.find_one({
            "type": "project",
            "name": project_name
        })
        assert project_entity, (
            "Project '{0}' was not found."
        ).format(project_name)
        log.debug("Collected Project \"{}\"".format(project_entity))

        asset_entity = io.find_one({
            "type": "asset",
            "name": asset_name,
            "parent": project_entity["_id"]
        })
        assert asset_entity, (
            "No asset found by the name '{0}' in project '{1}'"
        ).format(asset_name, project_name)

        project_name = project_entity["name"]

        log.info(
            "Anatomy object collected for project \"{}\".".format(project_name)
        )

        hierarchy_items = asset_entity["data"]["parents"]
        hierarchy = ""
        if hierarchy_items:
            hierarchy = os.path.join(*hierarchy_items)

        template_data = {
            "root": root_path,
            "project": {
                "name": project_name,
                "code": project_entity["data"].get("code")
            },
            "asset": asset_entity["name"],
            "hierarchy": hierarchy.replace("\\", "/"),
            "task": self._S["AVALON_TASK"],
            "ext": self.workfile_ext,
            "version": 1,
            "username": os.getenv("PYPE_USERNAME", "").strip()
        }

        avalon_app_name = os.environ.get("AVALON_APP_NAME")
        if avalon_app_name:
            application_def = lib.get_application(avalon_app_name)
            app_dir = application_def.get("application_dir")
            if app_dir:
                template_data["app"] = app_dir

        anatomy = Anatomy(project_name)
        anatomy_filled = anatomy.format_all(template_data).get_solved()

        return anatomy_filled
    def __init__(self, source, root=None):
        super(Launcher, self).__init__()

        engine = QtQml.QQmlApplicationEngine()
        engine.objectCreated.connect(self.on_object_created)
        # engine.warnings.connect(self.on_warnings)
        engine.addImportPath(QML_IMPORT_DIR)

        try:
            io.install()
        except IOError:
            raise  # Server refused to connect

        # Install actions
        from . import install
        install()

        terminal.init()
        app_root = os.path.dirname(__file__).replace('\\', '/')
        res_path = "file:///{}/res/".format(app_root)

        controller = control.Controller(root, self)
        engine.rootContext().setContextProperty("controller", controller)
        engine.rootContext().setContextProperty("terminal", terminal.model)
        engine.rootContext().setContextProperty("res_path", res_path)

        self._icon = QtGui.QIcon(ICON_PATH)
        self._tray = None
        self.window = None
        self.engine = engine
        self.controller = controller
        # self.window = object
        self.controller.init()
        engine.load(QtCore.QUrl.fromLocalFile(source))
Example #13
0
    def process(self, instance):
        version = int(instance.data.get("version", 0))
        asset_name = instance.data.get("asset", None)
        subset_name = instance.data.get("subset", None)

        assert version, "The file is missing version string! example: filename_v001.hrox `{}`"

        self.log.debug("Collected version: `{0}`".format(version))

        found_v = 0
        try:
            io.install()
            project = io.find_one({"type": "project"})

            asset = io.find_one({"type": "asset",
                                 "name": asset_name,
                                 "parent": project["_id"]})

            subset = io.find_one({"type": "subset",
                                  "parent": asset["_id"],
                                  "name": subset_name})

            version_db = io.find_one({
                'type': 'version',
                'parent': subset["_id"],
                'name': version
            }) or {}
            found_v = version_db.get("name", 0)
            self.log.debug("Found version: `{0}`".format(found_v))
        except Exception as e:
            self.log.debug("Problem to get data from database for asset `{0}` subset `{1}`. Error: `{2}`".format(asset_name, subset_name, e))

        assert (found_v != version), "Version must not be the same as in database `{0}`, Versions file: `{1}`, db: `{2}`".format(asset_name, version, found_v)
Example #14
0
 def show_launcher(self):
     # if app_launcher don't exist create it/otherwise only show main window
     if self.app_launcher is None:
         root = os.path.realpath(os.environ["AVALON_PROJECTS"])
         io.install()
         APP_PATH = launcher_lib.resource("qml", "main.qml")
         self.app_launcher = launcher_widget.Launcher(root, APP_PATH)
     self.app_launcher.window.show()
Example #15
0
def show(session=None):

    io.install()

    with toolslib.application():
        window = Window(session)
        window.setStyleSheet(style.load_stylesheet())
        window.show()
Example #16
0
File: lib.py Project: 81819152/pype
def set_io_database():
    project = os.environ.get('AVALON_PROJECT', '')
    asset = os.environ.get('AVALON_ASSET', '')
    silo = os.environ.get('AVALON_SILO', '')
    os.environ['AVALON_PROJECT'] = project
    os.environ['AVALON_ASSET'] = asset
    os.environ['AVALON_SILO'] = silo
    io.install()
Example #17
0
def cli_publish(data, gui=True):
    io.install()

    pyblish.api.deregister_all_plugins()
    # Registers Global pyblish plugins
    pype.install()
    # Registers Standalone pyblish plugins
    for path in PUBLISH_PATHS:
        pyblish.api.register_plugin_path(path)

    project_plugins_paths = os.environ.get("PYPE_PROJECT_PLUGINS")
    project_name = os.environ["AVALON_PROJECT"]
    if project_plugins_paths and project_name:
        for path in project_plugins_paths.split(os.pathsep):
            if not path:
                continue
            plugin_path = os.path.join(path, project_name, "plugins")
            if os.path.exists(plugin_path):
                pyblish.api.register_plugin_path(plugin_path)
                api.register_plugin_path(api.Loader, plugin_path)
                api.register_plugin_path(api.Creator, plugin_path)

    # Create hash name folder in temp
    chars = "".join([random.choice(string.ascii_letters) for i in range(15)])
    staging_dir = tempfile.mkdtemp(chars)

    # create json for return data
    return_data_path = (staging_dir + os.path.basename(staging_dir) +
                        'return.json')
    # create also json and fill with data
    json_data_path = staging_dir + os.path.basename(staging_dir) + '.json'
    with open(json_data_path, 'w') as outfile:
        json.dump(data, outfile)

    args = ["-pp", os.pathsep.join(pyblish.api.registered_paths())]

    if gui:
        args += ["gui"]

    envcopy = os.environ.copy()
    envcopy["PYBLISH_HOSTS"] = "standalonepublisher"
    envcopy["SAPUBLISH_INPATH"] = json_data_path
    envcopy["SAPUBLISH_OUTPATH"] = return_data_path
    envcopy["PYBLISH_GUI"] = "pyblish_pype"

    returncode = execute([sys.executable, "-u", "-m", "pyblish"] + args,
                         env=envcopy)

    result = {}
    if os.path.exists(json_data_path):
        with open(json_data_path, "r") as f:
            result = json.load(f)

    io.uninstall()
    # TODO: check if was pyblish successful
    # if successful return True
    print('Check result here')
    return False
Example #18
0
 def on_profile_changed(self, package):
     # TODO: should not be touching os.environ
     os.environ["AVALON_PROJECT"] = package.name
     io.uninstall()
     io.install()
     self._widgets["task"].get_task_icons()
     self._widgets["asset"].refresh()
     self._env.clear()
     self.clear_env()
     self.reveal()
Example #19
0
    def get_file_paths(self, session, event):
        """Get file paths from selected components."""

        link = session.get("Component",
                           list(event["data"]["values"].values())
                           [0])["version"]["asset"]["parent"]["link"][0]
        project = session.get(link["type"], link["id"])
        os.environ["AVALON_PROJECT"] = project["name"]
        api.Session["AVALON_PROJECT"] = project["name"]
        io.install()

        location = ftrack_api.Session().pick_location()

        paths = []
        for parent_name in sorted(event["data"]["values"].keys()):
            component = session.get("Component",
                                    event["data"]["values"][parent_name])

            # Newer publishes have the source referenced in Ftrack.
            online_source = False
            for neighbour_component in component["version"]["components"]:
                if neighbour_component["name"] != "ftrackreview-mp4_src":
                    continue

                paths.append(location.get_filesystem_path(neighbour_component))
                online_source = True

            if online_source:
                continue

            asset = io.find_one({"type": "asset", "name": parent_name})
            subset = io.find_one({
                "type": "subset",
                "name": component["version"]["asset"]["name"],
                "parent": asset["_id"]
            })
            version = io.find_one({
                "type": "version",
                "name": component["version"]["version"],
                "parent": subset["_id"]
            })
            representation = io.find_one({
                "type": "representation",
                "parent": version["_id"],
                "name": component["file_type"][1:]
            })
            if representation is None:
                representation = io.find_one({
                    "type": "representation",
                    "parent": version["_id"],
                    "name": "preview"
                })
            paths.append(api.get_representation_path(representation))

        return paths
Example #20
0
    def process(self, context):
        if "hierarchyContext" not in context.data:
            self.log.info("skipping IntegrateHierarchyToAvalon")
            return

        if not io.Session:
            io.install()

        input_data = context.data["hierarchyContext"]
        self.project = None
        self.import_to_avalon(input_data)
Example #21
0
    def process(self, context):
        io.install()
        project_name = api.Session["AVALON_PROJECT"]
        asset_name = api.Session["AVALON_ASSET"]

        project_entity = io.find_one({"type": "project", "name": project_name})
        assert project_entity, (
            "Project '{0}' was not found.").format(project_name)
        self.log.debug("Collected Project \"{}\"".format(project_entity))

        asset_entity = io.find_one({
            "type": "asset",
            "name": asset_name,
            "parent": project_entity["_id"]
        })
        assert asset_entity, (
            "No asset found by the name '{0}' in project '{1}'").format(
                asset_name, project_name)

        self.log.debug("Collected Asset \"{}\"".format(asset_entity))

        context.data["projectEntity"] = project_entity
        context.data["assetEntity"] = asset_entity

        data = asset_entity['data']

        context.data["frameStart"] = data.get("frameStart")
        context.data["frameEnd"] = data.get("frameEnd")

        handles = data.get("handles") or 0
        handle_start = data.get("handleStart")
        if handle_start is None:
            handle_start = handles
            self.log.info(
                ("Key \"handleStart\" is not set."
                 " Using value from \"handles\" key {}.").format(handle_start))

        handle_end = data.get("handleEnd")
        if handle_end is None:
            handle_end = handles
            self.log.info(
                ("Key \"handleEnd\" is not set."
                 " Using value from \"handles\" key {}.").format(handle_end))

        context.data["handles"] = int(handles)
        context.data["handleStart"] = int(handle_start)
        context.data["handleEnd"] = int(handle_end)

        frame_start_h = data.get("frameStart") - context.data["handleStart"]
        frame_end_h = data.get("frameEnd") + context.data["handleEnd"]
        context.data["frameStartHandle"] = frame_start_h
        context.data["frameEndHandle"] = frame_end_h
Example #22
0
def setup():
    assert_equals.__self__.maxDiff = None
    os.environ["AVALON_PROJECT"] = PROJECT_NAME

    # Fill in other required keys for the Session schema to avoid warnings
    # todo: figure out why these are actually required in the schema here
    for key in [
            "AVALON_PROJECTS", "AVALON_ASSET", "AVALON_SILO", "AVALON_CONFIG"
    ]:
        os.environ[key] = "placeholder"

    io.install()
    self._tempdir = tempfile.mkdtemp()
Example #23
0
    def process(self, context):
        self.context = context
        if "hierarchyContext" not in context.data:
            return

        if not io.Session:
            io.install()

        self.ft_project = None
        self.session = context.data["ftrackSession"]

        input_data = context.data["hierarchyContext"]

        self.import_to_ftrack(input_data)
Example #24
0
def cli(args):
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("project")
    parser.add_argument("asset")

    args = parser.parse_args(args)
    project = args.project
    asset = args.asset
    io.install()

    api.Session["AVALON_PROJECT"] = project
    if asset != '':
        api.Session["AVALON_ASSET"] = asset

    show()
Example #25
0
    def __init__(self, root, source):
        super(Application, self).__init__(sys.argv)
        self.setWindowIcon(QtGui.QIcon(ICON_PATH))

        pixmap = QtGui.QPixmap(SPLASH_PATH)
        splash = QtWidgets.QSplashScreen(pixmap)
        splash.show()
        self._splash = splash

        engine = QtQml.QQmlApplicationEngine()
        engine.objectCreated.connect(self.on_object_created)
        engine.warnings.connect(self.on_warnings)
        engine.addImportPath(QML_IMPORT_DIR)

        self._splash.showMessage("Connecting database...",
                                 QtCore.Qt.AlignBottom, QtCore.Qt.black)

        try:
            io.install()
        except IOError:
            raise  # Server refused to connect

        # Install actions
        from . import install

        install()

        self._splash.showMessage("Starting Studio Launcher...",
                                 QtCore.Qt.AlignBottom, QtCore.Qt.black)

        terminal.init()

        controller = control.Controller(root, self)
        engine.rootContext().setContextProperty("controller", controller)
        engine.rootContext().setContextProperty("terminal", terminal.model)

        self._tray = None
        self.window = None
        self.engine = engine
        self.controller = controller

        engine.load(QtCore.QUrl.fromLocalFile(source))

        self.setQuitOnLastWindowClosed(False)
Example #26
0
def cli_publish(data, gui=True):
    io.install()

    # Create hash name folder in temp
    chars = "".join( [random.choice(string.ascii_letters) for i in range(15)] )
    staging_dir = tempfile.mkdtemp(chars)

    # create json for return data
    return_data_path = (
        staging_dir + os.path.basename(staging_dir) + 'return.json'
    )
    # create also json and fill with data
    json_data_path = staging_dir + os.path.basename(staging_dir) + '.json'
    with open(json_data_path, 'w') as outfile:
        json.dump(data, outfile)

    args = [
        "-pp", os.pathsep.join(pyblish.api.registered_paths())
    ]

    if gui:
        args += ["gui"]

    envcopy = os.environ.copy()
    envcopy["PYBLISH_HOSTS"] = "standalonepublisher"
    envcopy["SAPUBLISH_INPATH"] = json_data_path
    envcopy["SAPUBLISH_OUTPATH"] = return_data_path
    envcopy["PYBLISH_GUI"] = "pyblish_lite"

    returncode = execute([
        sys.executable, "-u", "-m", "pyblish"
    ] + args, env=envcopy)

    result = {}
    if os.path.exists(json_data_path):
        with open(json_data_path, "r") as f:
            result = json.load(f)

    io.uninstall()
    # TODO: check if was pyblish successful
    # if successful return True
    print('Check result here')
    return False
Example #27
0
def set_context(project, asset, task, app):
    ''' Sets context for pyblish (must be done before pyblish is launched)
    :param project: Name of `Project` where instance should be published
    :type project: str
    :param asset: Name of `Asset` where instance should be published
    :type asset: str
    '''
    os.environ["AVALON_PROJECT"] = project
    io.Session["AVALON_PROJECT"] = project
    os.environ["AVALON_ASSET"] = asset
    io.Session["AVALON_ASSET"] = asset
    if not task:
        task = ''
    os.environ["AVALON_TASK"] = task
    io.Session["AVALON_TASK"] = task


    io.install()

    av_project = io.find_one({'type': 'project'})
    av_asset = io.find_one({
        "type": 'asset',
        "name": asset
    })

    parents = av_asset['data']['parents']
    hierarchy = ''
    if parents and len(parents) > 0:
        hierarchy = os.path.sep.join(parents)

    os.environ["AVALON_HIERARCHY"] = hierarchy
    io.Session["AVALON_HIERARCHY"] = hierarchy

    os.environ["AVALON_PROJECTCODE"] = av_project['data'].get('code', '')
    io.Session["AVALON_PROJECTCODE"] = av_project['data'].get('code', '')

    io.Session["current_dir"] = os.path.normpath(os.getcwd())

    os.environ["AVALON_APP"] = app
    io.Session["AVALON_APP"] = app

    io.uninstall()
Example #28
0
    def process(self, context):
        self.context = context
        if "hierarchyContext" not in context.data:
            return

        if not io.Session:
            io.install()

        self.ft_project = None
        self.session = context.data["ftrackSession"]

        input_data = context.data["hierarchyContext"]

        # self.import_to_ftrack(input_data)

        try:
            self.import_to_ftrack(input_data)
        except Exception as exc:
            import sys
            import traceback
            self.log.info(traceback.format_exc(sys.exc_info()))
            raise Exception("failed")
Example #29
0
def cli_publish(data, publish_paths, gui=True):
    PUBLISH_SCRIPT_PATH = os.path.join(
        os.path.dirname(os.path.dirname(__file__)), "publish.py")
    io.install()

    # Create hash name folder in temp
    chars = "".join([random.choice(string.ascii_letters) for i in range(15)])
    staging_dir = tempfile.mkdtemp(chars)

    # create also json and fill with data
    json_data_path = staging_dir + os.path.basename(staging_dir) + '.json'
    with open(json_data_path, 'w') as outfile:
        json.dump(data, outfile)

    envcopy = os.environ.copy()
    envcopy["PYBLISH_HOSTS"] = "standalonepublisher"
    envcopy["SAPUBLISH_INPATH"] = json_data_path
    envcopy["PYBLISHGUI"] = "pyblish_pype"
    envcopy["PUBLISH_PATHS"] = os.pathsep.join(publish_paths)
    if data.get("family", "").lower() == "editorial":
        envcopy["PYBLISH_SUSPEND_LOGS"] = "1"

    project_name = os.environ["AVALON_PROJECT"]
    env_copy = apply_project_environments_value(project_name, envcopy)

    args = get_pype_execute_args("run", PUBLISH_SCRIPT_PATH)
    result = execute(args, env=envcopy)

    result = {}
    if os.path.exists(json_data_path):
        with open(json_data_path, "r") as f:
            result = json.load(f)

    log.info(f"Publish result: {result}")

    io.uninstall()

    return False
Example #30
0
def build(location=None):
    ozark_util.build(location)

    # write project config into avalon db
    #
    def _read(path):
        try:
            with open(path) as f:
                data = toml.load(f)
        except IOError:
            raise

        return data

    res_dir = os.path.join(os.getcwd(), "resources")

    project = os.path.basename(os.getcwd())
    config = _read(os.path.join(res_dir, ".config.toml"))
    inventory = _read(os.path.join(res_dir, ".inventory.toml"))

    io.install()
    api.Session["AVALON_PROJECT"] = project
    inventory_io.save(project, config, inventory)