-
Notifications
You must be signed in to change notification settings - Fork 266
Expand file tree
/
Copy pathgitproject.py
More file actions
416 lines (366 loc) · 14.7 KB
/
gitproject.py
File metadata and controls
416 lines (366 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
"""Module for git related operations."""
from __future__ import annotations
from contextlib import nullcontext
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING
from git import GitCommandError, Repo
from semantic_release.cli.masking_filter import MaskingFilter
from semantic_release.cli.util import indented, noop_report
from semantic_release.errors import (
DetachedHeadGitError,
GitAddError,
GitCommitEmptyIndexError,
GitCommitError,
GitFetchError,
GitPushError,
GitTagError,
LocalGitError,
UnknownUpstreamBranchError,
UpstreamBranchChangedError,
)
from semantic_release.globals import logger
if TYPE_CHECKING: # pragma: no cover
from contextlib import _GeneratorContextManager
from logging import Logger
from typing import Sequence
from git import Actor
class GitProject:
def __init__(
self,
directory: Path | str = ".",
commit_author: Actor | None = None,
credential_masker: MaskingFilter | None = None,
) -> None:
self._project_root = Path(directory).resolve()
self._logger = logger
self._cred_masker = credential_masker or MaskingFilter()
self._commit_author = commit_author
@property
def project_root(self) -> Path:
return self._project_root
@property
def logger(self) -> Logger:
return self._logger
def _get_custom_environment(
self,
repo: Repo,
custom_vars: dict[str, str] | None = None,
) -> nullcontext[None] | _GeneratorContextManager[None]:
"""
git.custom_environment is a context manager but
is not reentrant, so once we have "used" it
we need to throw it away and re-create it in
order to use it again
"""
author_vars = (
{
"GIT_AUTHOR_NAME": self._commit_author.name,
"GIT_AUTHOR_EMAIL": self._commit_author.email,
"GIT_COMMITTER_NAME": self._commit_author.name,
"GIT_COMMITTER_EMAIL": self._commit_author.email,
}
if self._commit_author
else {}
)
custom_env_vars = {
**author_vars,
**(custom_vars or {}),
}
return (
nullcontext()
if not custom_env_vars
else repo.git.custom_environment(**custom_env_vars)
)
def is_dirty(self) -> bool:
with Repo(str(self.project_root)) as repo:
return repo.is_dirty()
def is_shallow_clone(self) -> bool:
"""
Check if the repository is a shallow clone.
:return: True if the repository is a shallow clone, False otherwise
"""
with Repo(str(self.project_root)) as repo:
shallow_file = Path(repo.git_dir, "shallow")
return shallow_file.exists()
def git_unshallow(self, noop: bool = False) -> None:
"""
Convert a shallow clone to a full clone by fetching the full history.
:param noop: Whether or not to actually run the unshallow command
"""
if noop:
noop_report("would have run:\n" " git fetch --unshallow")
return
with Repo(str(self.project_root)) as repo:
try:
self.logger.info("Converting shallow clone to full clone...")
repo.git.fetch("--unshallow")
self.logger.info("Repository unshallowed successfully")
except GitCommandError as err:
# If the repository is already a full clone, git fetch --unshallow will fail
# with "fatal: --unshallow on a complete repository does not make sense"
# We can safely ignore this error by checking the stderr message
stderr = str(err.stderr) if err.stderr else ""
if "does not make sense" in stderr or "complete repository" in stderr:
self.logger.debug("Repository is already a full clone")
else:
self.logger.exception(str(err))
raise
def git_add(
self,
paths: Sequence[Path | str],
force: bool = False,
strict: bool = False,
noop: bool = False,
) -> None:
if noop:
noop_report(
indented(
f"""\
would have run:
git add {str.join(" ", [str(Path(p)) for p in paths])}
"""
)
)
return
git_args = dict(
filter(
lambda k_v: k_v[1], # if truthy
{
"force": force,
}.items(),
)
)
with Repo(str(self.project_root)) as repo:
# TODO: in future this loop should be 1 line:
# repo.index.add(all_paths_to_add, force=False) # noqa: ERA001
# but since 'force' is deliberately ineffective (as in docstring) in gitpython 3.1.18
# we have to do manually add each filepath, and catch the exception if it is an ignored file
for updated_path in paths:
try:
repo.git.add(str(Path(updated_path)), **git_args)
except GitCommandError as err: # noqa: PERF203, acceptable performance loss
err_msg = f"Failed to add path ({updated_path}) to index"
if strict:
self.logger.exception(str(err))
raise GitAddError(err_msg) from err
self.logger.warning(err_msg)
def git_commit(
self,
message: str,
date: int | None = None,
commit_all: bool = False,
no_verify: bool = False,
noop: bool = False,
) -> None:
git_args = dict(
filter(
lambda k_v: k_v[1], # if truthy
{
"a": commit_all,
"m": message,
"date": date,
"no_verify": no_verify,
}.items(),
)
)
if noop:
command = (
f"""\
GIT_AUTHOR_NAME={self._commit_author.name} \\
GIT_AUTHOR_EMAIL={self._commit_author.email} \\
GIT_COMMITTER_NAME={self._commit_author.name} \\
GIT_COMMITTER_EMAIL={self._commit_author.email} \\
"""
if self._commit_author
else ""
)
# Indents the newlines so that terminal formatting is happy - note the
# git commit line of the output is 24 spaces indented too
# Only this message needs such special handling because of the newlines
# that might be in a commit message between the subject and body
indented_commit_message = message.replace("\n\n", "\n\n" + " " * 24)
command += f"git commit -m '{indented_commit_message}'"
command += "--all" if commit_all else ""
command += "--no-verify" if no_verify else ""
noop_report(
indented(
f"""\
would have run:
{command}
"""
)
)
return
with Repo(str(self.project_root)) as repo:
has_index_changes = bool(repo.index.diff("HEAD"))
has_working_changes = self.is_dirty()
will_commit_files = has_index_changes or (
has_working_changes and commit_all
)
if not will_commit_files:
raise GitCommitEmptyIndexError("No changes to commit!")
with self._get_custom_environment(repo):
try:
repo.git.commit(**git_args)
except GitCommandError as err:
self.logger.exception(str(err))
raise GitCommitError("Failed to commit changes") from err
def git_tag(
self, tag_name: str, message: str, isotimestamp: str, noop: bool = False
) -> None:
try:
datetime.fromisoformat(isotimestamp)
except ValueError as err:
raise ValueError("Invalid timestamp format") from err
if noop:
command = str.join(
" ",
[
f"GIT_COMMITTER_DATE={isotimestamp}",
*(
[
f"GIT_AUTHOR_NAME={self._commit_author.name}",
f"GIT_AUTHOR_EMAIL={self._commit_author.email}",
f"GIT_COMMITTER_NAME={self._commit_author.name}",
f"GIT_COMMITTER_EMAIL={self._commit_author.email}",
]
if self._commit_author
else [""]
),
f"git tag -a {tag_name} -m '{message}'",
],
)
noop_report(
indented(
f"""\
would have run:
{command}
"""
)
)
return
with Repo(str(self.project_root)) as repo, self._get_custom_environment(
repo,
{"GIT_COMMITTER_DATE": isotimestamp},
):
try:
repo.git.tag("-a", tag_name, m=message)
except GitCommandError as err:
self.logger.exception(str(err))
raise GitTagError(f"Failed to create tag ({tag_name})") from err
def git_push_branch(self, remote_url: str, branch: str, noop: bool = False) -> None:
if noop:
noop_report(
indented(
f"""\
would have run:
git push {self._cred_masker.mask(remote_url)} {branch}
"""
)
)
return
with Repo(str(self.project_root)) as repo:
try:
repo.git.push(remote_url, branch)
except GitCommandError as err:
self.logger.exception(str(err))
raise GitPushError(
f"Failed to push branch ({branch}) to remote"
) from err
def git_push_tag(self, remote_url: str, tag: str, noop: bool = False) -> None:
if noop:
noop_report(
indented(
f"""\
would have run:
git push {self._cred_masker.mask(remote_url)} tag {tag}
""" # noqa: E501
)
)
return
with Repo(str(self.project_root)) as repo:
try:
repo.git.push(remote_url, "tag", tag)
except GitCommandError as err:
self.logger.exception(str(err))
raise GitPushError(f"Failed to push tag ({tag}) to remote") from err
def verify_upstream_unchanged(
self, local_ref: str = "HEAD", noop: bool = False
) -> None:
"""
Verify that the upstream branch has not changed since the given local reference.
:param local_ref: The local reference to compare against upstream (default: HEAD)
:param noop: Whether to skip the actual verification (for dry-run mode)
:raises UpstreamBranchChangedError: If the upstream branch has changed
"""
if noop:
noop_report(
indented(
"""\
would have verified that upstream branch has not changed
"""
)
)
return
with Repo(str(self.project_root)) as repo:
# Get the current active branch
try:
active_branch = repo.active_branch
except TypeError:
# When in detached HEAD state, active_branch raises TypeError
err_msg = (
"Repository is in detached HEAD state, cannot verify upstream state"
)
raise DetachedHeadGitError(err_msg) from None
# Get the tracking branch (upstream branch)
if (tracking_branch := active_branch.tracking_branch()) is None:
err_msg = f"No upstream branch found for '{active_branch.name}'; cannot verify upstream state!"
raise UnknownUpstreamBranchError(err_msg)
upstream_full_ref_name = tracking_branch.name
self.logger.info("Upstream branch name: %s", upstream_full_ref_name)
# Extract the remote name from the tracking branch
# tracking_branch.name is in the format "remote/branch"
remote_name, remote_branch_name = upstream_full_ref_name.split(
"/", maxsplit=1
)
remote_ref_obj = repo.remotes[remote_name]
# Fetch the latest changes from the remote
self.logger.info("Fetching latest changes from remote '%s'", remote_name)
try:
remote_ref_obj.fetch()
except GitCommandError as err:
self.logger.exception(str(err))
err_msg = f"Failed to fetch from remote '{remote_name}'"
raise GitFetchError(err_msg) from err
# Get the SHA of the upstream branch
try:
upstream_commit_ref = remote_ref_obj.refs[remote_branch_name].commit
upstream_sha = upstream_commit_ref.hexsha
except AttributeError as err:
self.logger.exception(str(err))
err_msg = f"Unable to determine upstream branch SHA for '{upstream_full_ref_name}'"
raise GitFetchError(err_msg) from err
# Get the SHA of the specified ref (default: HEAD)
try:
local_commit = repo.commit(repo.git.rev_parse(local_ref))
except GitCommandError as err:
self.logger.exception(str(err))
err_msg = f"Unable to determine the SHA for local ref '{local_ref}'"
raise LocalGitError(err_msg) from err
# Compare the two SHAs
if local_commit.hexsha != upstream_sha and not any(
commit.hexsha == upstream_sha for commit in local_commit.iter_parents()
):
err_msg = str.join(
"\n",
(
f"[LOCAL SHA] {local_commit.hexsha} != {upstream_sha} [UPSTREAM SHA].",
f"Upstream branch '{upstream_full_ref_name}' has changed!",
),
)
raise UpstreamBranchChangedError(err_msg)
self.logger.info(
"Verified upstream branch '%s' has not changed",
upstream_full_ref_name,
)