-
Notifications
You must be signed in to change notification settings - Fork 252
/
git.py
385 lines (314 loc) · 11 KB
/
git.py
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
from __future__ import annotations
import re
import subprocess
from collections import namedtuple
from pathlib import Path
from typing import Any
from poetry.core.utils._compat import WINDOWS
PROTOCOL = r"\w+"
USER = r"[a-zA-Z0-9_.-]+"
RESOURCE = r"[a-zA-Z0-9_.-]+"
PORT = r"\d+"
PATH = r"[%\w~.\-/\\\$]+"
NAME = r"[%\w~.\-]+"
REV = r"[^@#]+?"
SUBDIR = r"[\w\-/\\]+"
PATTERNS = [
re.compile(
r"^(git\+)?"
r"(?P<protocol>https?|git|ssh|rsync|file)://"
rf"(?:(?P<user>{USER})@)?"
rf"(?P<resource>{RESOURCE})?"
rf"(:(?P<port>{PORT}))?"
rf"(?P<pathname>[:/\\]({PATH}[/\\])?"
rf"((?P<name>{NAME}?)(\.git|[/\\])?)?)"
r"(?:"
rf"#(?:egg=.+?&subdirectory=|subdirectory=)(?P<subdirectory>{SUBDIR})"
r"|"
r"#egg=?.+"
r"|"
rf"[@#](?P<rev>{REV})(?:[&#](?:(?:egg=.+?&subdirectory=|subdirectory=)(?P<rev_subdirectory>{SUBDIR})|egg=.+?))?"
r")?"
r"$"
),
re.compile(
r"(git\+)?"
rf"((?P<protocol>{PROTOCOL})://)"
rf"(?:(?P<user>{USER})@)?"
rf"(?P<resource>{RESOURCE}:?)"
rf"(:(?P<port>{PORT}))?"
rf"(?P<pathname>({PATH})"
rf"(?P<name>{NAME})(\.git|/)?)"
r"(?:"
rf"#(?:egg=.+?&subdirectory=|subdirectory=)(?P<subdirectory>{SUBDIR})"
r"|"
r"#egg=?.+"
r"|"
rf"[@#](?P<rev>{REV})(?:[&#](?:(?:egg=.+?&subdirectory=|subdirectory=)(?P<rev_subdirectory>{SUBDIR})|egg=.+?))?"
r")?"
r"$"
),
re.compile(
rf"^(?:(?P<user>{USER})@)?"
rf"(?P<resource>{RESOURCE})"
rf"(:(?P<port>{PORT}))?"
rf"(?P<pathname>([:/]{PATH}/)"
rf"(?P<name>{NAME})(\.git|/)?)"
r"(?:"
rf"#(?:egg=.+?&subdirectory=|subdirectory=)(?P<subdirectory>{SUBDIR})"
r"|"
r"#egg=?.+"
r"|"
rf"[@#](?P<rev>{REV})(?:[&#](?:(?:egg=.+?&subdirectory=|subdirectory=)(?P<rev_subdirectory>{SUBDIR})|egg=.+?))?"
r")?"
r"$"
),
re.compile(
rf"((?P<user>{USER})@)?"
rf"(?P<resource>{RESOURCE})"
r"[:/]{{1,2}}"
rf"(?P<pathname>({PATH})"
rf"(?P<name>{NAME})(\.git|/)?)"
r"(?:"
rf"#(?:egg=.+?&subdirectory=|subdirectory=)(?P<subdirectory>{SUBDIR})"
r"|"
r"#egg=?.+"
r"|"
rf"[@#](?P<rev>{REV})(?:[&#](?:(?:egg=.+?&subdirectory=|subdirectory=)(?P<rev_subdirectory>{SUBDIR})|egg=.+?))?"
r")?"
r"$"
),
]
class GitError(RuntimeError):
pass
class ParsedUrl:
def __init__(
self,
protocol: str | None,
resource: str | None,
pathname: str | None,
user: str | None,
port: str | None,
name: str | None,
rev: str | None,
subdirectory: str | None = None,
) -> None:
self.protocol = protocol
self.resource = resource
self.pathname = pathname
self.user = user
self.port = port
self.name = name
self.rev = rev
self.subdirectory = subdirectory
@classmethod
def parse(cls, url: str) -> ParsedUrl:
for pattern in PATTERNS:
m = pattern.match(url)
if m:
groups = m.groupdict()
return ParsedUrl(
groups.get("protocol", "ssh"),
groups.get("resource"),
groups.get("pathname"),
groups.get("user"),
groups.get("port"),
groups.get("name"),
groups.get("rev"),
groups.get("rev_subdirectory") or groups.get("subdirectory"),
)
raise ValueError(f'Invalid git url "{url}"')
@property
def url(self) -> str:
protocol = f"{self.protocol}://" if self.protocol else ""
user = f"{self.user}@" if self.user else ""
port = f":{self.port}" if self.port else ""
path = "/" + (self.pathname or "").lstrip(":/")
return f"{protocol}{user}{self.resource}{port}{path}"
def format(self) -> str:
return self.url
def __str__(self) -> str:
return self.format()
GitUrl = namedtuple("GitUrl", ["url", "revision", "subdirectory"])
_executable: str | None = None
def executable() -> str:
global _executable
if _executable is not None:
return _executable
if WINDOWS:
# Finding git via where.exe
where = "%WINDIR%\\System32\\where.exe"
paths = subprocess.check_output(
[where, "git"], shell=True, encoding="oem"
).split("\n")
for path in paths:
if not path:
continue
_path = Path(path.strip())
try:
_path.relative_to(Path.cwd())
except ValueError:
_executable = str(_path)
break
else:
_executable = "git"
if _executable is None:
raise RuntimeError("Unable to find a valid git executable")
return _executable
def _reset_executable() -> None:
global _executable
_executable = None
class GitConfig:
def __init__(self, requires_git_presence: bool = False) -> None:
self._config = {}
try:
config_list = subprocess.check_output(
[executable(), "config", "-l"], stderr=subprocess.STDOUT
).decode()
m = re.findall("(?ms)^([^=]+)=(.*?)$", config_list)
if m:
for group in m:
self._config[group[0]] = group[1]
except (subprocess.CalledProcessError, OSError):
if requires_git_presence:
raise
def get(self, key: Any, default: Any | None = None) -> Any:
return self._config.get(key, default)
def __getitem__(self, item: Any) -> Any:
return self._config[item]
class Git:
def __init__(self, work_dir: Path | None = None) -> None:
self._config = GitConfig(requires_git_presence=True)
self._work_dir = work_dir
@classmethod
def normalize_url(cls, url: str) -> GitUrl:
parsed = ParsedUrl.parse(url)
formatted = re.sub(r"^git\+", "", url)
if parsed.rev:
formatted = re.sub(rf"[#@]{parsed.rev}(?=[#&]?)(?!\=)", "", formatted)
if parsed.subdirectory:
formatted = re.sub(
rf"[#&]subdirectory={parsed.subdirectory}$", "", formatted
)
altered = parsed.format() != formatted
if altered:
if re.match(r"^git\+https?", url) and re.match(
r"^/?:[^0-9]", parsed.pathname or ""
):
normalized = re.sub(r"git\+(.*:[^:]+):(.*)", "\\1/\\2", url)
elif re.match(r"^git\+file", url):
normalized = re.sub(r"git\+", "", url)
else:
normalized = re.sub(r"^(?:git\+)?ssh://", "", url)
else:
normalized = parsed.format()
return GitUrl(
re.sub(r"#[^#]*$", "", normalized), parsed.rev, parsed.subdirectory
)
@property
def config(self) -> GitConfig:
return self._config
@property
def version(self) -> tuple[int, int, int]:
output = self.run("version")
version = re.search(r"(\d+)\.(\d+)\.(\d+)", output)
if not version:
return (0, 0, 0)
return int(version.group(1)), int(version.group(2)), int(version.group(3))
def clone(self, repository: str, dest: Path) -> str:
self._check_parameter(repository)
cmd = [
"clone",
"--filter=blob:none",
"--recurse-submodules",
"--",
repository,
str(dest),
]
# Blobless clones introduced in Git 2.17
if self.version < (2, 17):
cmd.remove("--filter=blob:none")
return self.run(*cmd)
def checkout(self, rev: str, folder: Path | None = None) -> str:
args = []
if folder is None and self._work_dir:
folder = self._work_dir
if folder:
args += [
"--git-dir",
(folder / ".git").as_posix(),
"--work-tree",
folder.as_posix(),
]
self._check_parameter(rev)
args += ["checkout", "--recurse-submodules", rev]
return self.run(*args)
def rev_parse(self, rev: str, folder: Path | None = None) -> str:
args = []
if folder is None and self._work_dir:
folder = self._work_dir
self._check_parameter(rev)
# We need "^0" (an alternative to "^{commit}") to ensure that the
# commit SHA of the commit the tag points to is returned, even in
# the case of annotated tags.
#
# We deliberately avoid the "^{commit}" syntax itself as on some
# platforms (cygwin/msys to be specific), the braces are interpreted
# as special characters and would require escaping, while on others
# they should not be escaped.
args += ["rev-parse", rev + "^0"]
return self.run(*args, folder=folder)
def get_current_branch(self, folder: Path | None = None) -> str:
if folder is None and self._work_dir:
folder = self._work_dir
output = self.run("symbolic-ref", "--short", "HEAD", folder=folder)
return output.strip()
def get_ignored_files(self, folder: Path | None = None) -> list[str]:
args = []
if folder is None and self._work_dir:
folder = self._work_dir
if folder:
args += [
"--git-dir",
(folder / ".git").as_posix(),
"--work-tree",
folder.as_posix(),
]
args += ["ls-files", "--others", "-i", "--exclude-standard"]
output = self.run(*args)
return output.strip().split("\n")
def remote_urls(self, folder: Path | None = None) -> dict[str, str]:
output = self.run(
"config", "--get-regexp", r"remote\..*\.url", folder=folder
).strip()
urls = {}
for url in output.splitlines():
name, url = url.split(" ", 1)
urls[name.strip()] = url.strip()
return urls
def remote_url(self, folder: Path | None = None) -> str:
urls = self.remote_urls(folder=folder)
return urls.get("remote.origin.url", urls[next(iter(urls.keys()))])
def run(self, *args: Any, **kwargs: Any) -> str:
folder = kwargs.pop("folder", None)
if folder:
args = (
"--git-dir",
(folder / ".git").as_posix(),
"--work-tree",
folder.as_posix(),
*args,
)
return (
subprocess.check_output(
[executable(), *list(args)], stderr=subprocess.STDOUT
)
.decode()
.strip()
)
def _check_parameter(self, parameter: str) -> None:
"""
Checks a git parameter to avoid unwanted code execution.
"""
if parameter.strip().startswith("-"):
raise GitError(f"Invalid Git parameter: {parameter}")