| 1 | #!/usr/bin/env python3 |
| 2 | """Serialize Jujutsu commands across workspaces and NFS clients.""" |
| 3 | |
| 4 | import errno |
| 5 | import fcntl |
| 6 | import json |
| 7 | import os |
| 8 | from pathlib import Path |
| 9 | import subprocess |
| 10 | import sys |
| 11 | |
| 12 | sys.path.insert(0, str(Path(__file__).resolve().parent)) |
| 13 | import client |
| 14 | |
| 15 | |
| 16 | def remote(executable, args, path): |
| 17 | if not client.host(): |
| 18 | return False |
| 19 | words, options, config_args = client.jj_arguments(args) |
| 20 | shared = path.is_relative_to(client.ROOT) |
| 21 | if Path.cwd().is_relative_to(client.ROOT) or shared: |
| 22 | for name, value in options: |
| 23 | if name in ("-R", "--repository", "--config-file"): |
| 24 | client.inside(value) |
| 25 | if not shared: |
| 26 | return False |
| 27 | client.inside(path) |
| 28 | if not words or words[0] in ("config", "git", "util", "help"): |
| 29 | return False |
| 30 | command = tuple(words[:2]) if words[0] in ("workspace", "file", "bookmark", "op", "sparse") else (words[0],) |
| 31 | safe = {("rebase",), ("status",), ("st",), ("log",), ("diff",), ("show",), ("edit",), |
| 32 | ("new",), ("abandon",), ("restore",), ("describe",), ("desc",), ("commit",), ("squash",), |
| 33 | ("workspace", "add"), ("workspace", "list"), ("workspace", "root"), |
| 34 | ("workspace", "forget"), ("workspace", "update-stale"), |
| 35 | ("file", "list"), ("file", "show"), ("file", "track"), ("file", "untrack"), |
| 36 | ("bookmark", "list"), ("bookmark", "create"), ("bookmark", "set"), |
| 37 | ("bookmark", "move"), ("bookmark", "delete"), ("bookmark", "forget"), |
| 38 | ("bookmark", "rename"), ("op", "log"), ("sparse", "list"), ("sparse", "set")} |
| 39 | if command not in safe: |
| 40 | return False |
| 41 | flags = {name for name, _ in options} |
| 42 | if flags & {"-i", "--interactive", "--tool", "--editor", "--edit", "--stdin", "--help", "-h"}: |
| 43 | return False |
| 44 | if command[0] in ("describe", "desc", "commit", "squash") and not flags & { |
| 45 | "-m", "--message", "--no-edit", "--use-destination-message"}: |
| 46 | return False |
| 47 | paths = client.jj_paths(words, options) |
| 48 | for value in paths: |
| 49 | if any(c in value for c in ':"|&~()'): |
| 50 | return False |
| 51 | client.inside(value) |
| 52 | base = [str(executable), *config_args, "--ignore-working-copy", "--no-pager", "config", "list"] |
| 53 | rows = subprocess.check_output([*base, "-T", 'json(self) ++ "\\n"'], text=True) |
| 54 | settings = {row["name"]: row["value"] for row in map(json.loads, rows.splitlines())} |
| 55 | if settings.get("signing.behavior", "drop") != "drop" or settings.get("snapshot.fsmonitor", "none") != "none": |
| 56 | return False |
| 57 | if command[0] in ("diff", "show", "log") and not flags & {"--git", "--summary", "--stat", "--types", "--name-only"}: |
| 58 | formatter = settings.get("ui.diff-formatter", ":color-words") |
| 59 | if not isinstance(formatter, str) or not formatter.startswith(":"): |
| 60 | return False |
| 61 | if sys.stdout.isatty() and "--no-pager" not in flags and settings.get("ui.paginate", "auto") != "never": |
| 62 | return False |
| 63 | config = subprocess.check_output([*base, "-T", 'name ++ " = " ++ value ++ "\\n"'], text=True) |
| 64 | version = subprocess.check_output([str(executable), "--version"], text=True).strip() |
| 65 | ignore = Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))) / "git/ignore" |
| 66 | cwd = Path.cwd() |
| 67 | if not cwd.is_relative_to(client.ROOT): |
| 68 | if any(not Path(value).is_absolute() for value in paths): |
| 69 | raise ValueError("Run commands with file paths from inside the project share.") |
| 70 | cwd = path |
| 71 | forwarded = ["-R", str(path)] |
| 72 | original = iter(args) |
| 73 | for arg in original: |
| 74 | if arg == "--": |
| 75 | forwarded.extend((arg, *original)) |
| 76 | break |
| 77 | if arg in ("-R", "--repository", "--config-file", "--config"): |
| 78 | next(original) |
| 79 | elif arg.startswith(("-R", "--repository=", "--config-file=", "--config=")): |
| 80 | continue |
| 81 | else: |
| 82 | forwarded.append(arg) |
| 83 | if arg in client.VALUES: |
| 84 | forwarded.append(next(original)) |
| 85 | result = client.request(dict(command="jj", cwd=str(cwd), args=forwarded, config=config, version=version, |
| 86 | ignore=ignore.read_text() if ignore.is_file() else ""), capture=False) |
| 87 | if result.returncode == 0 and command == ("workspace", "add") and len(paths) == 1: |
| 88 | client.wait_workspace(Path(paths[0]).absolute()) |
| 89 | sys.exit(result.returncode) |
| 90 | |
| 91 | |
| 92 | def main(): |
| 93 | executable = Path(sys.argv[0]).absolute().with_name("jj-real") |
| 94 | path = Path.cwd() |
| 95 | _, options, _ = client.jj_arguments(sys.argv[1:]) |
| 96 | for name, value in options: |
| 97 | if name in ("-R", "--repository"): |
| 98 | path = Path(value) |
| 99 | path = path.resolve() |
| 100 | remote(executable, sys.argv[1:], path) |
| 101 | for parent in (path, *path.parents): |
| 102 | metadata = parent / ".jj" |
| 103 | if not metadata.is_dir(): |
| 104 | continue |
| 105 | repository = metadata / "repo" |
| 106 | if repository.is_file(): |
| 107 | repository = (metadata / repository.read_text()).resolve(strict=True) |
| 108 | # Never unlink this inode: existing waiters must keep using the same lock. |
| 109 | descriptor = os.open(repository / "command.lock", os.O_CREAT | os.O_RDWR, 0o600) |
| 110 | # macOS NFS drops lockf across exec; flock maps to the server's POSIX lock. |
| 111 | lock = fcntl.flock if sys.platform == "darwin" else fcntl.lockf |
| 112 | try: |
| 113 | lock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| 114 | except OSError as error: |
| 115 | if error.errno not in (errno.EACCES, errno.EAGAIN): |
| 116 | raise |
| 117 | print("jj: Waiting for another command in this repository…", file=sys.stderr, flush=True) |
| 118 | lock(descriptor, fcntl.LOCK_EX) |
| 119 | # jj owns the lock even if its caller dies. |
| 120 | os.set_inheritable(descriptor, True) |
| 121 | break |
| 122 | os.execv(executable, ["jj", *sys.argv[1:]]) |
| 123 | |
| 124 | |
| 125 | if __name__ == "__main__": |
| 126 | try: |
| 127 | main() |
| 128 | except StopIteration: |
| 129 | os.execv(Path(sys.argv[0]).absolute().with_name("jj-real"), ["jj", *sys.argv[1:]]) |
| 130 | except KeyboardInterrupt: |
| 131 | sys.exit(130) |
| 132 | except subprocess.CalledProcessError as error: |
| 133 | sys.exit(error.returncode) |
| 134 | except (OSError, ValueError) as error: |
| 135 | print(f"jj: {error}", file=sys.stderr) |
| 136 | sys.exit(1) |