forked from commitizen-tools/commitizen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.py
More file actions
166 lines (126 loc) · 4.2 KB
/
git.py
File metadata and controls
166 lines (126 loc) · 4.2 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
import os
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import List, Optional
from commitizen import cmd
class GitObject:
rev: str
name: str
date: str
def __eq__(self, other) -> bool:
if not hasattr(other, "rev"):
return False
return self.rev == other.rev
class GitCommit(GitObject):
def __init__(
self, rev, title, body: str = "", author: str = "", author_email: str = ""
):
self.rev = rev.strip()
self.title = title.strip()
self.body = body.strip()
self.author = author.strip()
self.author_email = author_email.strip()
@property
def message(self):
return f"{self.title}\n\n{self.body}".strip()
def __repr__(self):
return f"{self.title} ({self.rev})"
class GitTag(GitObject):
def __init__(self, name, rev, date):
self.rev = rev.strip()
self.name = name.strip()
self.date = date.strip()
def __repr__(self):
return f"GitTag('{self.name}', '{self.rev}', '{self.date}')"
@classmethod
def from_line(cls, line: str, inner_delimiter: str) -> "GitTag":
name, objectname, date, obj = line.split(inner_delimiter)
if not obj:
obj = objectname
return cls(name=name, rev=obj, date=date)
def tag(tag: str, annotated: bool = False):
c = cmd.run(f"git tag -a {tag} -m {tag}" if annotated else f"git tag {tag}")
return c
def commit(message: str, args: str = ""):
f = NamedTemporaryFile("wb", delete=False)
f.write(message.encode("utf-8"))
f.close()
c = cmd.run(f"git commit {args} -F {f.name}")
os.unlink(f.name)
return c
def get_commits(
start: Optional[str] = None,
end: str = "HEAD",
*,
log_format: str = "%H%n%s%n%an%n%ae%n%b",
delimiter: str = "----------commit-delimiter----------",
args: str = "",
) -> List[GitCommit]:
"""Get the commits between start and end."""
git_log_cmd = (
f"git -c log.showSignature=False log --pretty={log_format}{delimiter} {args}"
)
if start:
c = cmd.run(f"{git_log_cmd} {start}..{end}")
else:
c = cmd.run(f"{git_log_cmd} {end}")
if not c.out:
return []
git_commits = []
for rev_and_commit in c.out.split(f"{delimiter}\n"):
if not rev_and_commit:
continue
rev, title, author, author_email, *body_list = rev_and_commit.split("\n")
if rev_and_commit:
git_commit = GitCommit(
rev=rev.strip(),
title=title.strip(),
body="\n".join(body_list).strip(),
author=author,
author_email=author_email,
)
git_commits.append(git_commit)
return git_commits
def get_tags(dateformat: str = "%Y-%m-%d") -> List[GitTag]:
inner_delimiter = "---inner_delimiter---"
formatter = (
f'"%(refname:lstrip=2){inner_delimiter}'
f"%(objectname){inner_delimiter}"
f"%(creatordate:format:{dateformat}){inner_delimiter}"
f'%(object)"'
)
c = cmd.run(f"git tag --format={formatter} --sort=-creatordate")
if c.err or not c.out:
return []
git_tags = [
GitTag.from_line(line=line, inner_delimiter=inner_delimiter)
for line in c.out.split("\n")[:-1]
]
return git_tags
def tag_exist(tag: str) -> bool:
c = cmd.run(f"git tag --list {tag}")
return tag in c.out
def get_latest_tag_name() -> Optional[str]:
c = cmd.run("git describe --abbrev=0 --tags")
if c.err:
return None
return c.out.strip()
def get_tag_names() -> List[Optional[str]]:
c = cmd.run("git tag --list")
if c.err:
return []
return [tag.strip() for tag in c.out.split("\n") if tag.strip()]
def find_git_project_root() -> Optional[Path]:
c = cmd.run("git rev-parse --show-toplevel")
if not c.err:
return Path(c.out.strip())
return None
def is_staging_clean() -> bool:
"""Check if staging is clean."""
c = cmd.run("git diff --no-ext-diff --cached --name-only")
return not bool(c.out)
def is_git_project() -> bool:
c = cmd.run("git rev-parse --is-inside-work-tree")
if c.out.strip() == "true":
return True
return False