Ejemplo n.º 1
0
def apply_project_environments_value(project_name, env, project_settings=None):
    """Apply project specific environments on passed environments.

    Args:
        project_name (str): Name of project for which environemnts should be
            received.
        env (dict): Environment values on which project specific environments
            will be applied.
        project_settings (dict): Project settings for passed project name.
            Optional if project settings are already prepared.

    Raises:
        KeyError: If project settings do not contain keys for project specific
            environments.
    """
    import acre

    if project_settings is None:
        project_settings = get_project_settings(project_name)

    env_value = project_settings["global"]["project_environments"]
    if not env_value:
        return env
    parsed = acre.parse(env_value)
    return _merge_env(parsed, env)
Ejemplo n.º 2
0
    def get_build_presets(self, task_name):
        """ Returns presets to build workfile for task name.

        Presets are loaded for current project set in
        io.Session["AVALON_PROJECT"], filtered by registered host
        and entered task name.

        Args:
            task_name (str): Task name used for filtering build presets.

        Returns:
            (dict): preset per entered task name
        """
        host_name = avalon.api.registered_host().__name__.rsplit(".", 1)[-1]
        presets = get_project_settings(avalon.io.Session["AVALON_PROJECT"])
        # Get presets for host
        build_presets = (
            presets.get(host_name, {})
            .get("workfile_build")
            .get("profiles")
        )
        if not build_presets:
            return

        task_name_low = task_name.lower()
        per_task_preset = None
        for preset in build_presets:
            preset_tasks = preset.get("tasks") or []
            preset_tasks_low = [task.lower() for task in preset_tasks]
            if task_name_low in preset_tasks_low:
                per_task_preset = preset
                break

        return per_task_preset
Ejemplo n.º 3
0
def filter_pyblish_plugins(plugins):
    """Filter pyblish plugins by presets.

    This servers as plugin filter / modifier for pyblish. It will load plugin
    definitions from presets and filter those needed to be excluded.

    Args:
        plugins (dict): Dictionary of plugins produced by :mod:`pyblish-base`
            `discover()` method.

    """
    from pyblish import api

    host = api.current_host()

    presets = get_project_settings(os.environ['AVALON_PROJECT']) or {}
    # skip if there are no presets to process
    if not presets:
        return

    # iterate over plugins
    for plugin in plugins[:]:

        file = os.path.normpath(inspect.getsourcefile(plugin))
        file = os.path.normpath(file)

        # host determined from path
        host_from_file = file.split(os.path.sep)[-4:-3][0]
        plugin_kind = file.split(os.path.sep)[-2:-1][0]

        # TODO: change after all plugins are moved one level up
        if host_from_file == "pype":
            host_from_file = "global"

        try:
            config_data = presets[host]["publish"][plugin.__name__]
        except KeyError:
            try:
                config_data = presets[host_from_file][plugin_kind][
                    plugin.__name__]  # noqa: E501
            except KeyError:
                continue

        for option, value in config_data.items():
            if option == "enabled" and value is False:
                log.info('removing plugin {}'.format(plugin.__name__))
                plugins.remove(plugin)
            else:
                log.info('setting {}:{} on plugin {}'.format(
                    option, value, plugin.__name__))

                setattr(plugin, option, value)
Ejemplo n.º 4
0
    def get_project_settings_from_event(self, event, project_name):
        """Load or fill pype's project settings from event data.

        Project data are stored by ftrack id because in most cases it is
        easier to access project id than project name.

        Args:
            event (ftrack_api.Event): Processed event by session.
            project_entity (ftrack_api.Entity): Project entity.
        """
        project_settings_by_id = event["data"].get("project_settings")
        if not project_settings_by_id:
            project_settings_by_id = {}
            event["data"]["project_settings"] = project_settings_by_id

        project_settings = project_settings_by_id.get(project_name)
        if not project_settings:
            project_settings = get_project_settings(project_name)
            event["data"]["project_settings"][project_name] = project_settings
        return project_settings
Ejemplo n.º 5
0
def get_subset_name(family,
                    variant,
                    task_name,
                    asset_id,
                    project_name=None,
                    host_name=None,
                    default_template=None):
    if not family:
        return ""

    if not host_name:
        host_name = os.environ["AVALON_APP"]

    # Use only last part of class family value split by dot (`.`)
    family = family.rsplit(".", 1)[-1]

    # Get settings
    tools_settings = get_project_settings(project_name)["global"]["tools"]
    profiles = tools_settings["creator"]["subset_name_profiles"]
    filtering_criteria = {
        "families": family,
        "hosts": host_name,
        "tasks": task_name
    }

    matching_profile = filter_profiles(profiles, filtering_criteria)
    template = None
    if matching_profile:
        template = matching_profile["template"]

    # Make sure template is set (matching may have empty string)
    if not template:
        template = default_template or DEFAULT_SUBSET_TEMPLATE

    # Simple check of task name existence for template with {task} in
    #   - missing task should be possible only in Standalone publisher
    if not task_name and "{task" in template.lower():
        raise TaskNotSetError()

    fill_pairs = (("variant", variant), ("family", family), ("task",
                                                             task_name))
    fill_data = {}
    for key, value in fill_pairs:
        # Handle cases when value is `None` (standalone publisher)
        if value is None:
            continue
        # Keep value as it is
        fill_data[key] = value
        # Both key and value are with upper case
        fill_data[key.upper()] = value.upper()

        # Capitalize only first char of value
        # - conditions are because of possible index errors
        capitalized = ""
        if value:
            # Upper first character
            capitalized += value[0].upper()
            # Append rest of string if there is any
            if len(value) > 1:
                capitalized += value[1:]
        fill_data[key.capitalize()] = capitalized

    return template.format(**fill_data)
Ejemplo n.º 6
0
def should_start_last_workfile(project_name,
                               host_name,
                               task_name,
                               default_output=False):
    """Define if host should start last version workfile if possible.

    Default output is `False`. Can be overriden with environment variable
    `AVALON_OPEN_LAST_WORKFILE`, valid values without case sensitivity are
    `"0", "1", "true", "false", "yes", "no"`.

    Args:
        project_name (str): Name of project.
        host_name (str): Name of host which is launched. In avalon's
            application context it's value stored in app definition under
            key `"application_dir"`. Is not case sensitive.
        task_name (str): Name of task which is used for launching the host.
            Task name is not case sensitive.

    Returns:
        bool: True if host should start workfile.

    """

    project_settings = get_project_settings(project_name)
    startup_presets = (project_settings["global"]["tools"]["Workfiles"]
                       ["last_workfile_on_startup"])

    if not startup_presets:
        return default_output

    host_name_lowered = host_name.lower()
    task_name_lowered = task_name.lower()

    max_points = 2
    matching_points = -1
    matching_item = None
    for item in startup_presets:
        hosts = item.get("hosts") or tuple()
        tasks = item.get("tasks") or tuple()

        hosts_lowered = tuple(_host_name.lower() for _host_name in hosts)
        # Skip item if has set hosts and current host is not in
        if hosts_lowered and host_name_lowered not in hosts_lowered:
            continue

        tasks_lowered = tuple(_task_name.lower() for _task_name in tasks)
        # Skip item if has set tasks and current task is not in
        if tasks_lowered:
            task_match = False
            for task_regex in compile_list_of_regexes(tasks_lowered):
                if re.match(task_regex, task_name_lowered):
                    task_match = True
                    break

            if not task_match:
                continue

        points = int(bool(hosts_lowered)) + int(bool(tasks_lowered))
        if points > matching_points:
            matching_item = item
            matching_points = points

        if matching_points == max_points:
            break

    if matching_item is not None:
        output = matching_item.get("enabled")
        if output is None:
            output = default_output
        return output
    return default_output