-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathutil.py
219 lines (172 loc) · 4.48 KB
/
util.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
import json
import getpass
import git
import os.path
import os
import sys
import signal
import subprocess
import tempfile
import logging
logging.basicConfig(format='%(message)s', level=logging.INFO)
# Silences Traceback on Ctrl-C
signal.signal(signal.SIGINT, lambda x,y: os._exit(1))
BOLD = '\033[1m'
ITALIC = '\033[3m'
UNDERLINE = '\033[4m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
RESET = '\033[0m'
def main_branch_name(repo):
"""
Returns the name of the 'main' branch.
Git defaults to 'master', but it doesn't have to be!
"""
ref = git.refs.symbolic.SymbolicReference(repo, 'refs/remotes/origin/HEAD')
name = ref.ref.name
return name[len('origin/'):]
def fatal_if_dirty(repo):
"""
Checks whether there are pending changes and exits the program if there are.
"""
info('Checking for pending changes')
if repo.is_dirty():
warn('You have uncommitted changes, proceeding automatically would be dangerous.')
info(repo.git.status('-s'))
exit(1)
def update_main(repo, initial_branch):
"""
Switches to the main branch and pulls from origin. If an exception occurs
it switches back to the initial branch and exits.
"""
main = main_branch_name(repo)
info('Switching to %s branch' % main)
try:
repo.heads[main].checkout()
except BaseException as e:
fatal('Could not checkout %s: %s' % (main, e))
info('Pulling updates for %s branch' % main)
try:
repo.git.remote('update', '--prune')
repo.remotes.origin.pull('--no-tags')
except BaseException as e:
warn('Failed to update %s: %s' % (main, e))
initial_branch.checkout()
c = prompt_y_n('Continue anyway?')
if not c:
exit(1)
def get_branch_name(name):
"""
Returns the full, prefixed branch name.
"""
username = get_github_creds()['username']
return '%s/%s' % (username, name)
def get_auth_filename():
"""
Returns the full path to ~/.github-auth.
"""
return os.path.join(os.path.expanduser('~'), '.github-auth')
def get_github_creds():
"""
Returns a dict containing GitHub auth details. Exits with an error if the
file does not exist.
"""
fn = get_auth_filename()
if not os.path.isfile(fn):
fatal("Missing GitHub credentials. Did you run `git github-login`?")
with open(fn) as auth_file:
return json.load(auth_file)
def get_script_path():
"""
Returns the location of the current script.
"""
return os.path.dirname(os.path.realpath(sys.argv[0]))
def get_editor(repo):
"""
Returns the editor from env vars.
"""
return (repo.git.config("core.editor") or
os.environ.get("GIT_EDITOR") or
os.environ.get("VISUAL") or
os.environ.get("EDITOR", "vi"))
def edit(repo, text):
"""
Opens the user's editor with predefined text and returns the edited copy.
"""
(fd, name) = tempfile.mkstemp(prefix="git-workflow-", suffix=".txt", text=True)
try:
f = os.fdopen(fd, "w")
f.write(text)
f.close()
cmd = "%s \"%s\"" % (get_editor(repo), name)
rc = subprocess.call(cmd, shell=True)
if rc:
fatal('Edit failed (%s)' % cmd)
f = open(name)
t = f.read()
f.close()
finally:
os.unlink(name)
return t
def prompt(msg, default='', password=False):
"""
Wrapper around raw_input and getpass.getpass.
"""
suffix = ''
if default != '':
suffix = '[%s] ' % default
msg = '%s: %s' % (msg, suffix)
if password:
answer = getpass.getpass(msg)
else:
# raw_input in python2, input in python3
try:
answer = raw_input(msg)
except NameError:
answer = input(msg)
return answer or default
def prompt_y_n(msg, default=False):
"""
Prompt user with given message for a yes/no answer (returning a boolean).
If user hits 'enter' w/o supplying an answer, return 'default' value.
"""
suffix = ' [y/N]' # default answer is 'No'
if default:
suffix = ' [Y/n]' # default answer is 'Yes'
answer = prompt(msg + suffix)
if answer.lower() in ['y', 'yes']:
return True
elif answer == '':
return default
else:
return False
def fatal(msg, code=1):
"""
Prints a red error message and then exits the program.
"""
error(msg)
sys.exit(code)
def error(msg):
"""
Prints a red error message.
"""
logging.error(RED + BOLD + msg + RESET)
def info(msg):
"""
Prints an info message in blue.
"""
logging.info(BLUE + ITALIC + '> ' + msg + RESET)
def success(msg):
"""
Prints a message in green.
"""
logging.error(GREEN + '> ' + msg + RESET)
def warn(msg):
"""
Prints a warning in yellow.
"""
logging.warning(YELLOW + '> ' + msg + RESET)