def rewrite_nix_paths()

in pkgs/rewrite-nix-paths-macho/rewrite-nix-paths-macho.py [0:0]


def rewrite_nix_paths(file_path: Path):
    """
    Finds and rewrites Nix store paths in a binary's dependencies
    to be @rpath-relative.
    """
    if not file_path.exists():
        raise FileNotFoundError(f"Error: File not found at {file_path}")

    dependencies = get_dependencies(file_path)

    for old_path in dependencies:
        if old_path.startswith("/nix/store/"):
            lib_name = os.path.basename(old_path)

            # Hmpf, since the Big Sur dynamic linker cache, we cannot
            # simply test for the existence of system libraries. So
            # use a table instead.
            if lib_name in _SYSTEM_LIBS:
                new_path = _SYSTEM_LIBS[lib_name]
            else:
                new_path = f"@rpath/{lib_name}"

            print(f"{old_path} -> {new_path}")

            command = [
                "install_name_tool",
                "-change",
                old_path,
                new_path,
                str(file_path),
            ]
            run_command(command)