githost 2024.3.14.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- githost/__init__.py +0 -0
- githost/githost.py +336 -0
- githost-2024.3.14.0.dist-info/METADATA +27 -0
- githost-2024.3.14.0.dist-info/RECORD +8 -0
- githost-2024.3.14.0.dist-info/WHEEL +5 -0
- githost-2024.3.14.0.dist-info/entry_points.txt +5 -0
- githost-2024.3.14.0.dist-info/licenses/LICENSE +9 -0
- githost-2024.3.14.0.dist-info/top_level.txt +1 -0
githost/__init__.py
ADDED
|
File without changes
|
githost/githost.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
#!/usr/bin/python3
|
|
2
|
+
|
|
3
|
+
"""A command-line interface to git repository hosting services"""
|
|
4
|
+
|
|
5
|
+
from __future__ import absolute_import
|
|
6
|
+
from __future__ import print_function
|
|
7
|
+
|
|
8
|
+
from six.moves import input
|
|
9
|
+
from six.moves.urllib.parse import urlparse
|
|
10
|
+
import argparse
|
|
11
|
+
import getpass
|
|
12
|
+
import importlib.metadata
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
import platform
|
|
17
|
+
import re
|
|
18
|
+
import requests
|
|
19
|
+
import subprocess
|
|
20
|
+
import sys
|
|
21
|
+
import traceback
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
logging.basicConfig()
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
__version__ = importlib.metadata.version('githost')
|
|
28
|
+
except:
|
|
29
|
+
__version__ = f"unknown: {traceback.format_exc()}"
|
|
30
|
+
|
|
31
|
+
def interactive_edit(initial_contents):
|
|
32
|
+
"""Open an editor to interactively edit a text template."""
|
|
33
|
+
tmp = os.path.expanduser("~/.githost.tmp")
|
|
34
|
+
editor = os.getenv("VISUAL") or os.getenv("EDITOR") or "vi"
|
|
35
|
+
with open(tmp, "w") as stream:
|
|
36
|
+
print(initial_contents, file=stream)
|
|
37
|
+
|
|
38
|
+
subprocess.call([editor, tmp])
|
|
39
|
+
|
|
40
|
+
contents = open(tmp, "r").read()
|
|
41
|
+
return contents
|
|
42
|
+
|
|
43
|
+
def read_choice(choices, prompt="select: "):
|
|
44
|
+
"""Prompt user for the index of their selection."""
|
|
45
|
+
while True:
|
|
46
|
+
print ("\n".join("{}: {}".format(i, choice)
|
|
47
|
+
for (i, choice) in enumerate(choices)))
|
|
48
|
+
resp = input(prompt)
|
|
49
|
+
try:
|
|
50
|
+
idx = int(resp)
|
|
51
|
+
return choices[idx]
|
|
52
|
+
except:
|
|
53
|
+
pass
|
|
54
|
+
|
|
55
|
+
def call(cmd):
|
|
56
|
+
ret = subprocess.call(cmd)
|
|
57
|
+
if ret != 0:
|
|
58
|
+
raise Exception("non-zero exit: {}".format(" ".join(cmd)))
|
|
59
|
+
|
|
60
|
+
def x_www_browser(url):
|
|
61
|
+
try:
|
|
62
|
+
call(["x-www-browser", url])
|
|
63
|
+
except Exception as ex:
|
|
64
|
+
logging.error("failed to open x browser: ", ex)
|
|
65
|
+
|
|
66
|
+
class Auth(object):
|
|
67
|
+
def __init__(self, user=None, passwd=None, authinfo=None):
|
|
68
|
+
self.user = user
|
|
69
|
+
self.passwd = passwd
|
|
70
|
+
self.authinfo = authinfo
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Service(object):
|
|
74
|
+
name = None
|
|
75
|
+
base = None
|
|
76
|
+
def __init__(self, auth):
|
|
77
|
+
self.auth = auth
|
|
78
|
+
|
|
79
|
+
def read_authinfo(self):
|
|
80
|
+
auth = self.auth
|
|
81
|
+
authinfo = auth.authinfo
|
|
82
|
+
if authinfo and os.path.exists(authinfo):
|
|
83
|
+
machine = self.api_host()
|
|
84
|
+
# TODO(ealfonso) support changing token order
|
|
85
|
+
pat = re.compile("^machine {} login (.*) password (.*)"
|
|
86
|
+
.format(re.escape(machine)))
|
|
87
|
+
try:
|
|
88
|
+
lines = open(authinfo).read().split("\n")
|
|
89
|
+
except IOError as ex:
|
|
90
|
+
logger.error("failed to read .autinfo: %s", str(ex))
|
|
91
|
+
return None
|
|
92
|
+
for line in lines:
|
|
93
|
+
m = pat.match(line)
|
|
94
|
+
if m:
|
|
95
|
+
auth.user = m.group(1)
|
|
96
|
+
auth.passwd = m.group(2)
|
|
97
|
+
print(f"found {machine} password in {authinfo}")
|
|
98
|
+
return auth
|
|
99
|
+
|
|
100
|
+
def api_host(self):
|
|
101
|
+
return urlparse(self.base).netloc
|
|
102
|
+
|
|
103
|
+
def write_authinfo(self, authinfo):
|
|
104
|
+
user, passwd=self.user(), self.password()
|
|
105
|
+
assert authinfo
|
|
106
|
+
machine = self.api_host()
|
|
107
|
+
with open(authinfo, "a") as fh:
|
|
108
|
+
print("machine {} login {} password {}"
|
|
109
|
+
.format(machine, user, passwd),
|
|
110
|
+
file = fh)
|
|
111
|
+
|
|
112
|
+
def user(self, prompt="enter username: "):
|
|
113
|
+
if not self.auth.user and not self.read_authinfo():
|
|
114
|
+
self.auth.user = input(prompt)
|
|
115
|
+
return self.auth.user
|
|
116
|
+
|
|
117
|
+
def password(self, prompt="enter password: "):
|
|
118
|
+
if not self.auth.passwd and not self.read_authinfo():
|
|
119
|
+
self.auth.passwd = getpass.getpass(prompt)
|
|
120
|
+
authinfo = self.auth.authinfo
|
|
121
|
+
passwd = self.auth.passwd
|
|
122
|
+
if read_choice(["yes", "no"],
|
|
123
|
+
prompt="write to {}? ".format(authinfo)):
|
|
124
|
+
self.write_authinfo(authinfo)
|
|
125
|
+
self.auth.passwd = passwd
|
|
126
|
+
return self.auth.passwd
|
|
127
|
+
|
|
128
|
+
def req_auth(self, req, prompt=None):
|
|
129
|
+
kwargs = {"prompt": prompt} if prompt else {}
|
|
130
|
+
req.auth = (self.user(), self.password(**kwargs))
|
|
131
|
+
|
|
132
|
+
def req_send(self, req, add_auth=True):
|
|
133
|
+
if not urlparse(req.url).netloc:
|
|
134
|
+
req.url = self.base + req.url
|
|
135
|
+
if add_auth:
|
|
136
|
+
self.req_auth(req)
|
|
137
|
+
logger.debug("%s %s:\n%s\n%s\n%s", req.method, req.url, req.json, req.data, req.params)
|
|
138
|
+
resp = requests.Session().send(req.prepare())
|
|
139
|
+
if not resp.ok:
|
|
140
|
+
print (resp.text)
|
|
141
|
+
resp.raise_for_status()
|
|
142
|
+
else:
|
|
143
|
+
data = json.loads(resp.text)
|
|
144
|
+
print (json.dumps(data, indent=4))
|
|
145
|
+
return resp
|
|
146
|
+
|
|
147
|
+
def git_add_remote(self, name, url):
|
|
148
|
+
cmd = ["git", "remote", "add", name, url]
|
|
149
|
+
call(cmd)
|
|
150
|
+
|
|
151
|
+
def repo_name(self):
|
|
152
|
+
cand = os.path.basename(os.getcwd())
|
|
153
|
+
repo_name = input("repo name (default {}): ".format(cand))
|
|
154
|
+
return repo_name or cand
|
|
155
|
+
|
|
156
|
+
class Github(Service):
|
|
157
|
+
name = "github"
|
|
158
|
+
base = "https://api.github.com"
|
|
159
|
+
|
|
160
|
+
def __init__(self, auth):
|
|
161
|
+
super(Github, self).__init__(auth)
|
|
162
|
+
self.fingerprints = """
|
|
163
|
+
These are GitHub's public key fingerprints (in hexadecimal format):
|
|
164
|
+
|
|
165
|
+
16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48 (RSA)
|
|
166
|
+
ad:1c:08:a4:40:e3:6f:9c:f5:66:26:5d:4b:33:5d:8c (DSA)
|
|
167
|
+
These are the SHA256 hashes shown in OpenSSH 6.8 and newer (in base64 format):
|
|
168
|
+
|
|
169
|
+
SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8 (RSA)
|
|
170
|
+
SHA256:br9IjFspm1vxR3iA35FWE+4VTyz1hYVLIE2t1/CeyWQ (DSA)
|
|
171
|
+
"""
|
|
172
|
+
self.TOKEN_URL = "https://github.com/settings/tokens"
|
|
173
|
+
|
|
174
|
+
def req_auth(self, req):
|
|
175
|
+
super(Github, self).req_auth(
|
|
176
|
+
req,
|
|
177
|
+
prompt=f"enter github token ({self.TOKEN_URL}): ")
|
|
178
|
+
req.headers["User-Agent"] = "anon"
|
|
179
|
+
req.headers["Authorization"] = f"token {self.auth.passwd}"
|
|
180
|
+
|
|
181
|
+
# TODO(ealfonso) rename to key_post
|
|
182
|
+
def post_key(self, pubkey_path, pubkey_label, **kwargs):
|
|
183
|
+
del kwargs
|
|
184
|
+
pubkey = open(pubkey_path).read()
|
|
185
|
+
data = {"key": pubkey, "title": pubkey_label}
|
|
186
|
+
url = "/user/keys"
|
|
187
|
+
req = requests.Request("POST", url, json=data)
|
|
188
|
+
self.req_send(req)
|
|
189
|
+
|
|
190
|
+
def repo_create(self, repo_name, description, private=True, **kwargs):
|
|
191
|
+
del kwargs
|
|
192
|
+
self.ensure_on_git_repo_directory()
|
|
193
|
+
repo_name = self.repo_name()
|
|
194
|
+
if not description:
|
|
195
|
+
description = interactive_edit("# enter {} description".format(repo_name)).strip()
|
|
196
|
+
|
|
197
|
+
data = {"name": repo_name,
|
|
198
|
+
"description": description,
|
|
199
|
+
"private": private,
|
|
200
|
+
"has_issues": True,
|
|
201
|
+
"has_projects": True,
|
|
202
|
+
"has_wiki": True}
|
|
203
|
+
url = "/user/repos"
|
|
204
|
+
req = requests.Request("POST", url, json=data)
|
|
205
|
+
resp = self.req_send(req)
|
|
206
|
+
# TODO(ejalfonso) get clone_url from resp
|
|
207
|
+
clone_url = "ssh://git@github.com/{}/{}".format(self.user(), repo_name)
|
|
208
|
+
self.git_add_remote("github", clone_url)
|
|
209
|
+
|
|
210
|
+
@staticmethod
|
|
211
|
+
def ensure_on_git_repo_directory():
|
|
212
|
+
subprocess.check_output(["git", "status"])
|
|
213
|
+
|
|
214
|
+
def list_repos(self, **kwargs):
|
|
215
|
+
del kwargs
|
|
216
|
+
self.req_send(requests.Request("GET", "/user/repos"))
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
class Bitbucket(Service):
|
|
220
|
+
name = "bitbucket"
|
|
221
|
+
base = "https://api.bitbucket.org/2.0"
|
|
222
|
+
# base = "http://localhost:1231"
|
|
223
|
+
|
|
224
|
+
def __init__(self, auth):
|
|
225
|
+
super(Bitbucket, self).__init__(auth)
|
|
226
|
+
|
|
227
|
+
def post_key(self, pubkey_path, pubkey_label, key_type=None, repo_name=None, **kwargs):
|
|
228
|
+
del kwargs
|
|
229
|
+
pubkey = open(pubkey_path).read().strip()
|
|
230
|
+
|
|
231
|
+
key_types = ("deploy", "ssh")
|
|
232
|
+
key_type = key_type or read_choice(key_types)
|
|
233
|
+
if not key_type in key_types:
|
|
234
|
+
raise Exception("Must specificy key type: {{}}".format(",".join(key_types)))
|
|
235
|
+
|
|
236
|
+
data = {"key": pubkey, "label": pubkey_label}
|
|
237
|
+
if key_type == "deploy":
|
|
238
|
+
repo_name = self.repo_name()
|
|
239
|
+
# if not repo_name:
|
|
240
|
+
# raise Exception("Must specify repo name for deploy key post")
|
|
241
|
+
url = "/repositories/{}/{}/deploy-keys".format(self.user(), repo_name)
|
|
242
|
+
elif key_type == "ssh":
|
|
243
|
+
url = "/users/{}/ssh-keys".format(self.user())
|
|
244
|
+
|
|
245
|
+
req = requests.Request("POST", url, json=data)
|
|
246
|
+
self.req_send(req)
|
|
247
|
+
|
|
248
|
+
def list_repos(self, **kwargs):
|
|
249
|
+
del kwargs
|
|
250
|
+
url = "/repositories/{}".format(self.user())
|
|
251
|
+
req = requests.Request("GET", url)
|
|
252
|
+
self.req_send(req)
|
|
253
|
+
|
|
254
|
+
def repo_create(self, repo_name, description, private=True, **kwargs):
|
|
255
|
+
del kwargs
|
|
256
|
+
repo_name = self.repo_name()
|
|
257
|
+
if not description:
|
|
258
|
+
description = interactive_edit("# enter {} description".format(repo_name)).strip()
|
|
259
|
+
|
|
260
|
+
data = {
|
|
261
|
+
# "project": {"key": repo_name},
|
|
262
|
+
"description": description,
|
|
263
|
+
"scm": "git",
|
|
264
|
+
"private": private}
|
|
265
|
+
url = "/repositories/{}/{}".format(self.user(), repo_name)
|
|
266
|
+
req = requests.Request("POST", url, json=data)
|
|
267
|
+
resp = self.req_send(req)
|
|
268
|
+
# TODO(ejalfonso) get url from resp
|
|
269
|
+
clone_url = "ssh://git@bitbucket.com/{}/{}".format(self.user(), repo_name)
|
|
270
|
+
self.git_add_remote("bitbucket", clone_url)
|
|
271
|
+
|
|
272
|
+
SERVICES = dict((service.name, service)
|
|
273
|
+
for service in
|
|
274
|
+
[Github, Bitbucket])
|
|
275
|
+
|
|
276
|
+
def main():
|
|
277
|
+
parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
|
|
278
|
+
parser.add_argument("service", choices=list(SERVICES.keys()))
|
|
279
|
+
# help = "one of {}".format(" ".join(SERVICES.keys())))
|
|
280
|
+
parser.add_argument("-a", "--authinfo", help=".authinfo or .netrc file path",
|
|
281
|
+
default=os.path.expanduser("~/.authinfo"))
|
|
282
|
+
parser.add_argument("-u", "--username", help="user name for the selected service")
|
|
283
|
+
parser.add_argument("-f", "--fingerprints",
|
|
284
|
+
help="display fingerprints of the selected service")
|
|
285
|
+
parser.add_argument("-v", "--verbose", action="store_true")
|
|
286
|
+
parser.add_argument("--version", action="version", version=__version__)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
subparsers = parser.add_subparsers(help="")
|
|
290
|
+
|
|
291
|
+
parser_postkey = subparsers.add_parser("key-post", help="post an ssh key")
|
|
292
|
+
parser_postkey.add_argument("-p", "--pubkey-path",
|
|
293
|
+
default=os.path.expanduser("~/.ssh/id_rsa.pub"),
|
|
294
|
+
help="path to ssh public key file")
|
|
295
|
+
parser_postkey.add_argument("-l", "--pubkey-label",
|
|
296
|
+
default="githost-{}".format(platform.node()),
|
|
297
|
+
help="label for the public key")
|
|
298
|
+
parser_postkey.add_argument("-k", "--key-type", help="bitbucket key type")
|
|
299
|
+
parser_postkey.set_defaults(func="post_key")
|
|
300
|
+
|
|
301
|
+
parser_listrepos = subparsers.add_parser("repo-list", help="list available repositories")
|
|
302
|
+
parser_listrepos.set_defaults(func="list_repos")
|
|
303
|
+
|
|
304
|
+
parser_repocreate = subparsers.add_parser("repo-create", help="create a new repository")
|
|
305
|
+
parser_repocreate.add_argument("-d", "--description", help="repo description")
|
|
306
|
+
parser_repocreate.add_argument("-r", "--repo-name", default=os.path.basename(os.getcwd()),
|
|
307
|
+
help="repository name")
|
|
308
|
+
parser_repocreate.set_defaults(func="repo_create")
|
|
309
|
+
|
|
310
|
+
if len(sys.argv) == 1:
|
|
311
|
+
parser.print_help(sys.stderr)
|
|
312
|
+
return 0
|
|
313
|
+
args = parser.parse_args()
|
|
314
|
+
|
|
315
|
+
logger.setLevel(logging.DEBUG if args.verbose else logging.INFO)
|
|
316
|
+
|
|
317
|
+
if args.verbose:
|
|
318
|
+
requests_log = logging.getLogger("requests.packages.urllib3")
|
|
319
|
+
requests_log.setLevel(logging.DEBUG)
|
|
320
|
+
requests_log.propagate = True
|
|
321
|
+
|
|
322
|
+
auth = Auth(user=args.username, authinfo=args.authinfo)
|
|
323
|
+
service_fn = SERVICES.get(args.service)
|
|
324
|
+
if not service_fn:
|
|
325
|
+
raise ValueError(f"Invalid service: {args.service}")
|
|
326
|
+
service = service_fn(auth=auth)
|
|
327
|
+
fn = getattr(service, args.func)
|
|
328
|
+
logger.debug(args)
|
|
329
|
+
fn(**vars(args))
|
|
330
|
+
|
|
331
|
+
if __name__ == "__main__":
|
|
332
|
+
main()
|
|
333
|
+
|
|
334
|
+
# Local Variables:
|
|
335
|
+
# compile-command: "./githost.py -s bitbucket -v listrepos"
|
|
336
|
+
# End:
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: githost
|
|
3
|
+
Version: 2024.3.14.0
|
|
4
|
+
Summary: A command-line client to various git repository hosting APIs
|
|
5
|
+
Home-page: https://github.com/erjoalgo/githost
|
|
6
|
+
Author: Ernesto Alfonso
|
|
7
|
+
Author-email: Ernesto Alfonso <erjoalgo@gmail.com>
|
|
8
|
+
Maintainer-email: Ernesto Alfonso <erjoalgo@gmail.com>
|
|
9
|
+
License-Expression: GPL-3.0-or-later
|
|
10
|
+
Project-URL: Homepage, https://github.com/erjoalgo/githost/
|
|
11
|
+
Project-URL: Documentation, https://github.com/erjoalgo/githost/
|
|
12
|
+
Project-URL: Repository, https://github.com/erjoalgo/githost/
|
|
13
|
+
Project-URL: Bug Tracker, https://github.com/erjoalgo/githost/issues
|
|
14
|
+
Keywords: git,github,bitbucket,client
|
|
15
|
+
Classifier: Development Status :: 4 - Beta
|
|
16
|
+
Classifier: Programming Language :: Python
|
|
17
|
+
Requires-Python: >=3.7
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: requests
|
|
21
|
+
Requires-Dist: six
|
|
22
|
+
Dynamic: author
|
|
23
|
+
Dynamic: home-page
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
: pip install githost
|
|
27
|
+
: githost -h
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
githost/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
githost/githost.py,sha256=7vd-bX0K5FlU6ekj3fVW4kmbn0iaPrxYQarXu67jAVg,11889
|
|
3
|
+
githost-2024.3.14.0.dist-info/licenses/LICENSE,sha256=yTlJa6knwqxmPqVBjEXy4YUHLFt8uFD7MlLeFjNQVcM,474
|
|
4
|
+
githost-2024.3.14.0.dist-info/METADATA,sha256=YDVG1sn2DO1wIG_XYgl8gdt6Pl_FFpSnP6ui1H9mI5w,942
|
|
5
|
+
githost-2024.3.14.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
6
|
+
githost-2024.3.14.0.dist-info/entry_points.txt,sha256=3t5UoE0R_UMmHyNZwiwmOpDiThIpIVqDt3HMTkhs4I0,99
|
|
7
|
+
githost-2024.3.14.0.dist-info/top_level.txt,sha256=ZAmoDsBfBet9j_tVDeQusuQssCv5sVlllf9xBX_IqV4,8
|
|
8
|
+
githost-2024.3.14.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
This program is free software: you can redistribute it and/or modify
|
|
2
|
+
it under the terms of the GNU General Public License as published by
|
|
3
|
+
the Free Software Foundation, either version 3 of the License, or (at
|
|
4
|
+
your option) any later version.
|
|
5
|
+
|
|
6
|
+
This program is distributed in the hope that it will be useful, but
|
|
7
|
+
WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
8
|
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
|
9
|
+
General Public License for more details.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
githost
|