Debian Codegraph @

cylc/flow/install_plugins/log_vc_info.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """Record version control information to the workflow log directory on
18 installation.
19
20 If the workflow source directory is a supported repository/working copy
21 (git or svn), information about the working copy will be saved in
22 ``<run-dir>/log/version/vcs.json``.
23
24 An example of this information for a git repo:
25
26 .. code-block:: json
27
28 {
29 "version control system": "git",
30 "repository version": "2.8.0-dirty",
31 "commit": "e5dc6573dd70cabd8f973d1535c17c29c026d553",
32 "working copy root path": "~/cylc-src/my-workflow-git",
33 "status": [
34 " M flow.cylc",
35 "M bin/thing.sh"
36 ]
37 }
38
39 And for an svn working copy:
40
41 .. code-block:: json
42
43 {
44 "version control system": "svn",
45 "working copy root path": "~/cylc-src/my-workflow-svn",
46 "url": "file:///home/my-workflow-svn/trunk",
47 "repository uuid": "219f5687-8eb8-44b1-beb6-e8220fa964d3",
48 "revision": "14",
49 "status": [
50 "M readme.txt"
51 ]
52 }
53
54 Any uncommitted changes will also be saved as a diff in
55 ``<run-dir>/log/version/uncommitted.diff``.
56
57 .. note::
58
59 Git does not include untracked files in the diff.
60 """
61
62 import json
63 from pathlib import Path
64 from subprocess import Popen, DEVNULL, PIPE
65 from typing import (
66 Any,
67 Dict,
68 Iterable,
69 List,
70 Optional,
71 TYPE_CHECKING,
72 TextIO,
73 Union,
74 cast,
75 overload,
76 )
77
78 from cylc.flow import LOG as _LOG, LoggerAdaptor
79 from cylc.flow.exceptions import CylcError
80 import cylc.flow.flags
81 from cylc.flow.pipe_poller import pipe_poller
82 from cylc.flow.util import format_cmd
83 from cylc.flow.workflow_files import WorkflowFiles
84
85 if TYPE_CHECKING:
86 from optparse import Values
87
88 LOG = LoggerAdaptor(_LOG, {'prefix': __name__})
89
90
91 SVN = 'svn'
92 GIT = 'git'
93
94 INFO_COMMANDS: Dict[str, List[str]] = {
95 SVN: ['info', '--non-interactive'],
96 GIT: ['describe', '--always', '--dirty']
97 }
98
99 STATUS_COMMANDS: Dict[str, List[str]] = {
100 SVN: ['status', '--non-interactive'],
101 GIT: ['status', '--short']
102 }
103
104 DIFF_COMMANDS: Dict[str, List[str]] = {
105 SVN: ['diff', '--internal-diff', '--non-interactive'],
106 GIT: ['diff', 'HEAD']
107 # ['diff', '--no-index', '/dev/null', '{0}'] # untracked files
108 }
109
110 GIT_REV_PARSE_COMMAND: List[str] = ['rev-parse', 'HEAD']
111
112 NOT_REPO_ERRS: Dict[str, List[str]] = {
113 SVN: ['svn: e155007:',
114 'svn: warning: w155007:'],
115 GIT: ['fatal: not a git repository',
116 'warning: not a git repository']
117 }
118
119 NO_BASE_ERRS: Dict[str, List[str]] = {
120 SVN: [], # Not possible for svn working copy to have no base commit?
121 GIT: ['fatal: bad revision \'head\'',
122 'fatal: ambiguous argument \'head\': unknown revision']
123 }
124
125 SVN_INFO_KEYS: List[str] = [
126 'revision', 'url', 'working copy root path', 'repository uuid'
127 ]
128
129 DIFF_FILENAME = 'uncommitted.diff'
130 INFO_FILENAME = 'vcs.json'
131 JSON_INDENT = 4
132
133
134 class VCSNotInstalledError(CylcError):
135 """Exception to be raised if an attempted VCS command is not installed.
136
137 Args:
138 vcs: The version control system command.
139 exc: The exception that was raised when attempting to run the command.
140 """
141 def __init__(self, vcs: str, exc: Exception) -> None:
142 self.vcs = vcs
143 self.exc = exc
144
145 def __str__(self) -> str:
146 return f"{self.vcs} does not appear to be installed ({self.exc})"
147
148
149 class VCSMissingBaseError(CylcError):
150 """Exception to be raised if a repository is missing a base commit.
151
152 Args:
153 vcs: The version control system command.
154 repo_path: The path to the working copy.
155 """
156 def __init__(self, vcs: str, repo_path: Union[Path, str]) -> None:
157 self.vcs = vcs
158 self.path = repo_path
159
160 def __str__(self) -> str:
161 return f"{self.vcs} repository at {self.path} is missing a base commit"
162
163
164 def get_vc_info(path: Union[Path, str]) -> Optional[Dict[str, Any]]:
165 """Return the version control information for a repository, given its path.
166 """
167 info: Dict[str, Any] = {}
168 missing_base = False
169 for vcs, args in INFO_COMMANDS.items():
170 try:
171 out = _run_cmd(vcs, args, cwd=path)
172 except VCSNotInstalledError as exc:
173 LOG.debug(exc)
174 continue
175 except VCSMissingBaseError as exc:
176 missing_base = True
177 LOG.debug(exc)
178 except OSError as exc:
179 if any(
180 exc.strerror and exc.strerror.lower().startswith(err)
181 for err in NOT_REPO_ERRS[vcs]
182 ):
183 LOG.debug(f"Source dir {path} is not a {vcs} repository")
184 elif cylc.flow.flags.verbosity > -1:
185 LOG.warning(f"$ {vcs} {format_cmd(args)}\n{exc}")
186 continue
187
188 info['version control system'] = vcs
189 if vcs == SVN:
190 info.update(_parse_svn_info(out))
191 elif vcs == GIT:
192 if not missing_base:
193 info['repository version'] = out.splitlines()[0]
194 info['commit'] = _get_git_commit(path)
195 info['working copy root path'] = str(path)
196 info['status'] = get_status(vcs, path)
197
198 LOG.debug(f"{vcs} repository detected")
199 return info
200
201 return None
202
203
204 @overload
205 def _run_cmd(
206 vcs: str, args: Iterable[str], cwd: Union[Path, str], stdout: int = PIPE
207 ) -> str:
208 ...
209
210
211 @overload
212 def _run_cmd(
213 vcs: str, args: Iterable[str], cwd: Union[Path, str], stdout: TextIO
214 ) -> None:
215 ...
216
217
218 def _run_cmd(
219 vcs: str,
220 args: Iterable[str],
221 cwd: Union[Path, str],
222 stdout: Union[TextIO, int] = PIPE
223 ) -> Optional[str]:
224 """Run a VCS command.
225
226 Args:
227 vcs: The version control system.
228 args: The args to pass to the version control command.
229 cwd: Directory to run the command in.
230 stdout: Where to redirect output (either PIPE or a
231 text stream/file object).
232
233 Returns:
234 Stdout output if stdout=PIPE, else None as the output has been
235 written directly to the specified file.
236
237 Raises:
238 VCSNotInstalledError: The VCS is not found.
239 VCSMissingBaseError: There is no base commit in the repo.
240 OSError: Non-zero return code for VCS command.
241 """
242 cmd = [vcs, *args]
243 LOG.debug(f'$ {format_cmd(cmd)}')
244 try:
245 proc = Popen( # nosec
246 cmd,
247 cwd=cwd,
248 stdin=DEVNULL,
249 stdout=stdout,
250 stderr=PIPE,
251 text=True,
252 )
253 # (nosec because commands are defined in constants at top of module)
254 except FileNotFoundError as exc:
255 # This will only be raised if the VCS command is not installed,
256 # otherwise Popen() will succeed with a non-zero return code
257 raise VCSNotInstalledError(vcs, exc) from None
258 if stdout == PIPE:
259 out, err = pipe_poller(
260 proc, cast('TextIO', proc.stdout), cast('TextIO', proc.stderr)
261 )
262 else:
263 out, err = proc.communicate()
264 if proc.returncode:
265 if any(err.lower().startswith(msg) for msg in NO_BASE_ERRS[vcs]):
266 # No base commit in repo
267 raise VCSMissingBaseError(vcs, cwd)
268 raise OSError(proc.returncode, err)
269 return out
270
271
272 def write_vc_info(
273 info: Dict[str, Any], run_dir: Union[Path, str]
274 ) -> None:
275 """Write version control info to the workflow's vcs log dir.
276
277 Args:
278 info: The vcs info.
279 run_dir: The workflow run directory.
280 """
281 if not info:
282 raise ValueError("Nothing to write")
283 info_file = Path(
284 run_dir,
285 WorkflowFiles.LogDir.DIRNAME,
286 WorkflowFiles.LogDir.VERSION,
287 INFO_FILENAME
288 )
289 info_file.parent.mkdir(exist_ok=True, parents=True)
290 with open(info_file, 'w') as f:
291 print(
292 json.dumps(info, indent=JSON_INDENT), file=f
293 )
294
295
296 def _get_git_commit(path: Union[Path, str]) -> str:
297 """Return the hash of the HEAD of the repo at path."""
298 args = GIT_REV_PARSE_COMMAND
299 return _run_cmd(GIT, args, cwd=path).splitlines()[0]
300
301
302 def get_status(vcs: str, path: Union[Path, str]) -> List[str]:
303 """Return the short status of a repo, as a list of lines.
304
305 Args:
306 vcs: The version control system.
307 path: The path to the repository.
308 """
309 args = STATUS_COMMANDS[vcs]
310 return _run_cmd(vcs, args, cwd=path).rstrip('\n').split('\n')
311
312
313 def _parse_svn_info(info_text: str) -> Dict[str, Any]:
314 """Return OrderedDict of certain info parsed from svn info raw output."""
315 ret: Dict[str, Any] = {}
316 for line in info_text.splitlines():
317 if line:
318 key, value = (ln.strip() for ln in line.split(':', 1))
319 key = key.lower()
320 if key in SVN_INFO_KEYS:
321 ret[key] = value
322 return ret
323
324
325 def write_diff(
326 vcs: str, repo_path: Union[Path, str], run_dir: Union[Path, str]
327 ) -> Path:
328 """Get and write the diff of uncommitted changes for a repository to the
329 workflow's vcs log dir.
330
331 Args:
332 vcs: The version control system.
333 repo_path: The path to the repo.
334 run_dir: The workflow run directory.
335
336 Returns the path to diff file.
337 """
338 args = DIFF_COMMANDS[vcs]
339 args.append(
340 str(repo_path) if Path(repo_path).is_absolute() else
341 str(Path().cwd() / repo_path)
342 )
343
344 diff_file = Path(
345 run_dir,
346 WorkflowFiles.LogDir.DIRNAME,
347 WorkflowFiles.LogDir.VERSION,
348 DIFF_FILENAME
349 )
350 diff_file.parent.mkdir(exist_ok=True)
351
352 with open(diff_file, 'a') as f:
353 f.write(
354 "# Auto-generated diff of uncommitted changes in the Cylc "
355 "workflow repository:\n"
356 f"# {repo_path}\n"
357 )
358 f.flush()
359 try:
360 _run_cmd(vcs, args, repo_path, stdout=f)
361 except VCSMissingBaseError as exc:
362 print(f"# No diff - {exc}", file=f)
363 return diff_file
364
365
366 # Entry point:
367 def main(
368 srcdir: Union[Path, str], opts: 'Values', rundir: Union[Path, str]
369 ) -> bool:
370 """Entry point for this plugin. Write version control info and any
371 uncommmited diff to the workflow log dir.
372
373 Args:
374 srcdir: Workflow source dir for cylc install.
375 opts: CLI options (requirement for post_install entry point, but
376 not used here)
377 rundir: Workflow run dir.
378
379 Return True if source dir is a supported repo, else False.
380 """
381 vc_info = get_vc_info(srcdir)
382 if vc_info is None:
383 return False
384 vcs = vc_info['version control system']
385 write_vc_info(vc_info, rundir)
386 write_diff(vcs, srcdir, rundir)
387 return True