Coverage for collectra/gui/source_control.py: 77.24%
123 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1"""Run the GUI's fixed Git operations in the active results repository.
3Everything returned to the page is worded for people who do not know Git.
4"""
6import os
7import re
8import subprocess
9from pathlib import Path
11ACTIONS = ("status", "pull", "save", "push")
12MAX_LISTED_FILES = 50
14NOT_LINKED = "This project is not linked to a shared copy yet."
15CANNOT_REACH = "Could not reach the shared copy. Check your internet connection."
16CANNOT_SIGN_IN = "Could not sign in to the shared copy."
19def run_git(
20 directory: Path, action: str, message: str = "", repository: str = ""
21) -> dict:
22 if action not in ACTIONS:
23 return _failure("Unknown action")
24 if action == "save" and not message.strip():
25 return _failure("Enter a message first.")
26 environment = dict(os.environ, GIT_TERMINAL_PROMPT="0", GCM_INTERACTIVE="never")
27 environment.setdefault("GIT_SSH_COMMAND", "ssh -oBatchMode=yes")
28 try:
29 root_result = subprocess.run(
30 ["git", "-C", str(directory), "rev-parse", "--show-toplevel"],
31 capture_output=True,
32 text=True,
33 timeout=10,
34 env=environment,
35 )
36 if root_result.returncode:
37 return _failure("This folder is not set up for saving versions.")
38 root = Path(root_result.stdout.strip()).resolve()
39 if repository and root != Path(repository).resolve():
40 return _failure(
41 "The project changed. Close and reopen History and Changes before going on."
42 )
44 def git(*arguments):
45 result = subprocess.run(
46 ["git", "-C", str(root), *arguments],
47 capture_output=True,
48 text=True,
49 timeout=120,
50 env=environment,
51 )
52 output = "\n".join(
53 part.strip() for part in [result.stdout, result.stderr] if part.strip()
54 )
55 return result.returncode, output
57 if action == "status":
58 code, output = git("status", "--porcelain=v1", "--branch", "-z")
59 if code:
60 return _failure(_plain_failure(output), root)
61 return _success(_describe_status(output), root)
62 if action == "save":
63 code, output = git("add", ".")
64 if code:
65 return _failure(_plain_failure(output), root)
66 code, output = git("commit", "-m", message)
67 if code and "nothing to commit" in output:
68 return _failure("There are no changes to save.", root)
69 if code:
70 return _failure(_plain_failure(output), root)
71 return _success("Changes saved.", root)
72 if action == "pull":
73 code, output = git("pull", "--no-rebase", "--no-edit")
74 if code and ("CONFLICT" in output or "Automatic merge failed" in output):
75 git("merge", "--abort")
76 return _failure(
77 "Your changes and the updates are in the same place, so nothing "
78 "was changed. Ask for help before going on.",
79 root,
80 )
81 if code:
82 return _failure(_plain_failure(output), root)
83 if "Already up to date" in output:
84 return _success("Already up to date.", root)
85 return _success("Updates received.", root)
86 code, output = git("push")
87 if code:
88 return _failure(_plain_failure(output), root)
89 if "up-to-date" in output or "up to date" in output:
90 return _success("Nothing new to share.", root)
91 return _success("Changes shared.", root)
92 except FileNotFoundError:
93 return _failure(
94 "Saving versions needs Git, which is not installed on this computer."
95 )
96 except subprocess.TimeoutExpired:
97 return _failure(
98 "That took too long. Check what has changed before trying again."
99 )
100 except OSError as error:
101 return _failure(str(error))
104def _success(text: str, root: Path) -> dict:
105 return {"success": True, "repository": str(root), "output": text, "error": ""}
108def _failure(text: str, root: Path | None = None) -> dict:
109 result = {"success": False, "output": text, "error": text}
110 if root is not None:
111 result["repository"] = str(root)
112 return result
115def _plain_failure(output: str) -> str:
116 """Git's own message turned into plain words where we know the cause."""
117 if "would be overwritten" in output:
118 return "Save your changes first, then get updates."
119 if "rejected" in output or "fetch first" in output:
120 return "Others have shared changes. Get updates first."
121 if "no tracking information" in output or "no upstream" in output:
122 return NOT_LINKED
123 if (
124 "No configured push destination" in output
125 or "does not appear to be a git repository" in output
126 ):
127 return NOT_LINKED
128 if "Could not resolve host" in output or "unable to access" in output:
129 return CANNOT_REACH
130 if re.search(
131 r"Authentication failed|could not read Username|Permission denied", output
132 ):
133 return CANNOT_SIGN_IN
134 return output or "Something went wrong."
137def _describe_status(porcelain: str) -> str:
138 entries = porcelain.split("\0")
139 branch = entries[0] if entries and entries[0].startswith("## ") else ""
140 changes = {"Edited": [], "New": [], "Deleted": []}
141 skip_next = False
142 for entry in entries[1:]:
143 if skip_next: # the old name of a renamed file
144 skip_next = False
145 continue
146 if len(entry) < 4:
147 continue
148 codes, path = entry[:2], entry[3:]
149 skip_next = codes[0] in "RC"
150 if codes == "??" or "A" in codes:
151 changes["New"].append(path)
152 elif "D" in codes:
153 changes["Deleted"].append(path)
154 else:
155 changes["Edited"].append(path)
156 lines = []
157 listed = [(kind, path) for kind, paths in changes.items() for path in paths]
158 if listed:
159 lines.append("Not saved yet:")
160 lines.extend(f" {kind}: {path}" for kind, path in listed[:MAX_LISTED_FILES])
161 if len(listed) > MAX_LISTED_FILES:
162 lines.append(f" ...and {len(listed) - MAX_LISTED_FILES} more")
163 ahead = re.search(r"ahead (\d+)", branch)
164 behind = re.search(r"behind (\d+)", branch)
165 notes = []
166 if ahead:
167 count = int(ahead.group(1))
168 notes.append(
169 f"{count} saved version has not been shared yet."
170 if count == 1
171 else f"{count} saved versions have not been shared yet."
172 )
173 if behind:
174 count = int(behind.group(1))
175 notes.append(
176 "1 update is waiting to be received."
177 if count == 1
178 else f"{count} updates are waiting to be received."
179 )
180 if lines and notes:
181 lines.append("")
182 lines.extend(notes)
183 return "\n".join(lines) or "Everything is saved and up to date."