Skip to content

diff

dev_tool.tools.diff

DiffResult

Bases: TypedDict

added instance-attribute

removed instance-attribute

modified instance-attribute

MergeChoice

Bases: StrEnum

An enum class for the ways a downloaded environment can be applied.

Ours is the local file and theirs is the portal, as in git.

CANCEL = 'cancel' class-attribute instance-attribute

OURS = 'ours' class-attribute instance-attribute

OVERWRITE = 'overwrite' class-attribute instance-attribute

THEIRS = 'theirs' class-attribute instance-attribute

EnvironmentDiff

A class for comparing and displaying environment variable differences.

This class provides static methods for parsing, comparing, and displaying differences between local and remote environment configurations.

compare staticmethod

A method that compares local and remote environment variables.

Parameters:

  • local (dict[str, str]) –

    The local environment variables.

  • remote (dict[str, str]) –

    The remote environment variables.

Returns:

  • DiffResult –

    A dictionary with added, removed, and modified variables.

Source code in dev_tool/tools/diff.py
@staticmethod
def compare(local: dict[str, str], remote: dict[str, str]) -> DiffResult:
    """
    A method that compares local and remote environment variables.

    :param local: The local environment variables.
    :param remote: The remote environment variables.
    :return: A dictionary with added, removed, and modified variables.
    """

    added = {k: v for k, v in remote.items() if k not in local}
    removed = {k: v for k, v in local.items() if k not in remote}
    modified = {k: {'local': local[k], 'remote': remote[k]} for k in local if k in remote and local[k] != remote[k]}

    return {
        'added': added,
        'removed': removed,
        'modified': modified
    }

display staticmethod

A method that displays differences between local and remote environment variables.

Parameters:

  • terminal (Terminal) –

    The blessed Terminal instance.

  • local (dict[str, str]) –

    The local environment variables.

  • remote (dict[str, str]) –

    The remote environment variables.

Source code in dev_tool/tools/diff.py
@staticmethod
def display(terminal: Terminal, local: dict[str, str], remote: dict[str, str]) -> None:
    """
    A method that displays differences between local and remote environment variables.

    :param terminal: The blessed Terminal instance.
    :param local: The local environment variables.
    :param remote: The remote environment variables.
    """

    differences = EnvironmentDiff.compare(local, remote)

    if not any(differences.values()):
        print('No differences found between local and remote environment variables.')  # noqa: T201
        return

    print('\n' + terminal.bold('Environment Variable Changes:') + '\n')  # noqa: T201

    if differences['added']:
        print(terminal.color_rgb(40, 167, 69)('Added variables:'))  # noqa: T201

        for key, value in sorted(differences['added'].items()):
            truncated = value[:60] + '...' if len(value) > 60 else value
            print(terminal.color_rgb(40, 167, 69)(f'  + {key} = {truncated}'))  # noqa: T201

        print()  # noqa: T201

    if differences['removed']:
        print(terminal.color_rgb(220, 53, 69)('Removed variables:'))  # noqa: T201

        for key in sorted(differences['removed'].keys()):
            print(terminal.color_rgb(220, 53, 69)(f'  - {key}'))  # noqa: T201

        print()  # noqa: T201

    if differences['modified']:
        print(terminal.color_rgb(255, 193, 7)('Modified variables:'))  # noqa: T201

        for key, modification in sorted(differences['modified'].items()):
            local_value = modification['local'][:40] + '...' if len(modification['local']) > 40 else modification['local']
            remote_value = modification['remote'][:40] + '...' if len(modification['remote']) > 40 else modification['remote']

            print(terminal.color_rgb(255, 193, 7)(f'  ~ {key}'))  # noqa: T201
            print(f'      Local:  {local_value}')  # noqa: T201
            print(f'      Remote: {remote_value}')  # noqa: T201

        print()  # noqa: T201

has_differences staticmethod

A method that checks if there are differences between environments.

Parameters:

  • local (dict[str, str]) –

    The local environment variables.

  • remote (dict[str, str]) –

    The remote environment variables.

Returns:

  • bool –

    True if differences exist, False otherwise.

Source code in dev_tool/tools/diff.py
@staticmethod
def has_differences(local: dict[str, str], remote: dict[str, str]) -> bool:
    """
    A method that checks if there are differences between environments.

    :param local: The local environment variables.
    :param remote: The remote environment variables.
    :return: True if differences exist, False otherwise.
    """

    differences = EnvironmentDiff.compare(local, remote)
    return any(differences.values())

merge staticmethod

A method that merges local environment variables into the portal's text.

The portal's ordering, comments, and blank lines are kept. A key both sides define with different values takes the local value when local is preferred and the portal's value otherwise. Keys only the local file defines are appended at the end.

Parameters:

  • remote_values (str) –

    The environment values string from the portal.

  • local (dict[str, str]) –

    The local environment variables.

  • prefer_local (bool) –

    Whether the local value wins where the two differ.

Returns:

  • str –

    The merged environment values string.

Source code in dev_tool/tools/diff.py
@staticmethod
def merge(remote_values: str, local: dict[str, str], *, prefer_local: bool) -> str:
    """
    A method that merges local environment variables into the portal's text.

    The portal's ordering, comments, and blank lines are kept. A key both sides
    define with different values takes the local value when local is preferred
    and the portal's value otherwise. Keys only the local file defines are
    appended at the end.

    :param remote_values: The environment values string from the portal.
    :param local: The local environment variables.
    :param prefer_local: Whether the local value wins where the two differ.
    :return: The merged environment values string.
    """

    lines = []
    seen = set()

    for line in remote_values.splitlines():
        stripped = line.strip()

        if not stripped or stripped.startswith('#') or '=' not in stripped:
            lines.append(line)
            continue

        key, value = (part.strip() for part in stripped.split('=', 1))
        seen.add(key)

        if prefer_local and key in local and local[key] != value:
            lines.append(f'{key}={local[key]}')
            continue

        lines.append(line)

    lines.extend(f'{key}={value}' for key, value in local.items() if key not in seen)

    return '\n'.join(lines) + '\n'

parse_file staticmethod

A method that parses an environment file into a dictionary.

Parameters:

  • path (Path) –

    The path to the environment file.

Returns:

  • dict[str, str] –

    A dictionary of environment variables.

Source code in dev_tool/tools/diff.py
@staticmethod
def parse_file(path: Path) -> dict[str, str]:
    """
    A method that parses an environment file into a dictionary.

    :param path: The path to the environment file.
    :return: A dictionary of environment variables.
    """

    variables = {}

    if not path.exists():
        return variables

    with open(path, 'r', encoding='utf-8') as handle:
        for line in handle:
            line = line.strip()

            if not line or line.startswith('#') or '=' not in line:
                continue

            key, value = line.split('=', 1)
            key = key.strip()
            value = value.strip()

            if key:
                variables[key] = value

    return variables

parse_string staticmethod

A method that parses environment variable values from a string.

Parameters:

  • values (str) –

    The environment values string with newline-separated key=value pairs.

Returns:

  • dict[str, str] –

    A dictionary of environment variables.

Source code in dev_tool/tools/diff.py
@staticmethod
def parse_string(values: str) -> dict[str, str]:
    """
    A method that parses environment variable values from a string.

    :param values: The environment values string with newline-separated key=value pairs.
    :return: A dictionary of environment variables.
    """

    variables = {}

    for line in values.splitlines():
        line = line.strip()

        if not line or line.startswith('#') or '=' not in line:
            continue

        key, value = line.split('=', 1)
        key = key.strip()
        value = value.strip()

        if key:
            variables[key] = value

    return variables