-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpublisher.py
65 lines (53 loc) · 2.49 KB
/
publisher.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
import git
class Publisher:
def __init__(self, repo="./"): # XXX
self.repo = git.Repo(repo)
def push_to_github(self, file_or_file_list, commit_message, **kwargs):
author = kwargs.get("author", None)
# the file_or_file_list can be a string or a list of strings
if isinstance(file_or_file_list, str):
file_list = [file_or_file_list]
else:
file_list = file_or_file_list
with AutoStash(self.repo):
# Stage the changes you want to commit
print(f"Adding files: {file_list}")
self.repo.git.add(file_list)
# Commit the changes with a message
print(f"Committing with message: {commit_message}")
self.repo.git.commit(m=commit_message)
if author:
self.repo.git.commit("--amend", "--author", author, "--reuse-message", "HEAD")
try:
# Push the changes to the remote repository
print("Pushing to GitHub...")
self.repo.git.push()
# If everything was successful, print the commit message
# TODO check if the commit & push were successful
print(f"Successfully pushed to GitHub: {commit_message}")
except git.exc.GitCommandError as e:
# print stderr line by line prefixed with 'stderr: '
for line in e.stderr.splitlines():
print(f"stderr: {line}")
print (f"Cannot push to GitHub at the moment. Stuff is in the local repo: {str(file_list)}")
print (f"Commit message:\n{commit_message}")
# XXX we are still somehow getting PROBLEM <number>: ERROR in MASTER_LOG.TXT, even though we have caught the exception here
class AutoStash:
def __init__(self, repo):
self.repo = repo
self.old_branch = None
self.is_dirty = False
def __enter__(self):
# If branch is not main save it and change to main
if self.repo.active_branch.name != "main":
if self.repo.is_dirty():
self.was_dirty = True
self.repo.git.stash("save")
self.old_branch = self.repo.active_branch.name
self.repo.git.checkout("main")
def __exit__(self, exc_type, exc_value, exc_traceback):
# Roll back
if self.old_branch:
self.repo.git.checkout(self.old_branch)
if self.is_dirty:
self.repo.git.stash("pop")