-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit-profile
executable file
·206 lines (165 loc) · 5.36 KB
/
git-profile
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
#!/usr/bin/env python
# coding=utf-8
from __future__ import print_function
import errno
import json
import os
import re
import subprocess
import sys
class Profile(object):
def __init__(self, name, email):
super(Profile, self).__init__()
self.name = name
self.email = email
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.name == other.name and \
self.email == other.email
def __hash__(self):
return hash((self.name, self.email))
def __str__(self):
return "<Profile name={0} email={1}>".format(
self.name,
self.email,
)
class Config(object):
def __init__(self):
super(Config, self).__init__()
self.profiles = {}
def __str__(self):
profiles = {
key: str(profile)
for key, profile in self.profiles.items()
}
return "<Config profiles={0}>".format(profiles)
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, Config):
return o.profiles
elif isinstance(o, Profile):
return {
"name": o.name,
"email": o.email,
}
return super(JSONEncoder, self).default(o)
def git(*args):
return subprocess.check_output(["git", *args]).strip().decode("utf-8")
def get_config_root():
home = os.environ.get("HOME")
if not home:
raise RuntimeError("Failed to find a HOME environment variable")
return os.path.join(home, ".config", "git-tools")
def get_config_path():
return os.path.join(get_config_root(), "git-profile.json")
def create_config_dir():
path = get_config_root()
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST or not os.path.isdir(path):
raise
def load_config():
config = Config()
try:
with open(get_config_path()) as f:
config_data = json.load(f)
assert isinstance(config_data, dict)
config.profiles = {
key: Profile(p["name"], p["email"])
for key, p in config_data.items()
}
except IOError as e:
if e.errno != errno.ENOENT:
raise
return config
def save_config(config):
with open(get_config_path(), "w") as f:
json.dump(config, f, cls=JSONEncoder, indent=2)
def import_profile(config, name):
if name is True:
name = "default"
add_profile(config, name, git("config", "user.name"), git("config", "user.email"))
def add_profile(config, profile_name, name, email):
if profile_name in config.profiles:
raise RuntimeError("Profile '{0}' already exists.".format(profile_name))
config.profiles[profile_name] = Profile(name, email)
def rm_profile(config, profile_name):
if profile_name not in config.profiles:
raise RuntimeError("Profile '{0}' does not exist.".format(profile_name))
del config.profiles[profile_name]
def switch_profile(config, profile_name):
if profile_name not in config.profiles:
raise RuntimeError("Profile '{0}' does not exist.".format(profile_name))
profile = config.profiles[profile_name]
git("config", "user.name", profile.name)
git("config", "user.email", profile.email)
print("Switched to profile {0}: {1} <{2}>".format(
profile_name, profile.name, profile.email,
))
def list_profiles(config):
if not config.profiles:
print("No profiles!")
return
current_profile = Profile(
git("config", "user.name"),
git("config", "user.email"),
)
for key, profile in config.profiles.items():
prefix = "*" if profile == current_profile else " "
print("{0} {1} ({2} <{3}>)".format(
prefix, key, profile.name, profile.email,
))
if current_profile not in config.profiles.values():
print(f"Warning: no profile exists for current git config!", file=sys.stderr)
def print_usage():
usage = (
"usage: git profile [--switch] [KEY]\n"
" or: git profile --add KEY --name 'Your Name' --email '[email protected]'\n"
" or: git profile --rm KEY\n"
" or: git profile --import [KEY]"
)
print(usage)
def parse_args(args):
regex = re.compile(r"^--(\w+)$")
if len(args) == 1 and not regex.match(args[0]):
return {"switch": args[0]}
result = {}
key = None
for arg in args:
if key is None:
match = regex.match(arg)
if not match:
raise ValueError("Invalid value {0} for option {1}".format(arg, key))
key = match.group(1)
continue
result[key] = arg
key = None
if key:
result[key] = True
return result
def main(args):
create_config_dir()
config = load_config()
args = parse_args(args)
if "import" in args:
import_profile(config, args.pop("import"))
elif "add" in args:
add_profile(config, args.pop("add"), **args)
elif "rm" in args:
rm_profile(config, args.pop("rm"))
elif "switch" in args:
switch_profile(config, args.pop("switch"))
elif "help" in args:
print_usage()
else:
list_profiles(config)
save_config(config)
if __name__ == "__main__":
args = sys.argv[1:]
try:
main(args)
except RuntimeError as e:
print(e)
exit(1)