-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgit_plugin.py
380 lines (309 loc) · 13.2 KB
/
git_plugin.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
'''git:
Git commands for Shellista
usage: git help
'''
import os
import sys
import argparse
import urlparse
import urllib2
import getpass
alias = []
from ... tools.toolbox import bash
#iOS-specific
try:
import console
except:
from ... tools import ios_console as console
try:
import keychain
except:
from ... tools import ios_keychain as keychain
shellista = sys.modules['__main__']
SAVE_PASSWORDS = shellista.Shellista.settings.get('save_passwords', True)
DULWICH_URL='https://github.com/transistor1/dulwich/archive/master.tar.gz#module_name=dulwich&module_path=dulwich-master/dulwich&move_to=local-modules'
GITTLE_URL='https://github.com/FriendCode/gittle/archive/522ce011851aee28fd6bb11b502978c9352fd137.tar.gz#module_name=gittle&module_path=gittle-*/gittle&move_to=local-modules'
FUNKY_URL='https://github.com/FriendCode/funky/tarball/e89cb2ce4374bf2069c7f669e52e046f63757241#module_name=funky&module_path=Friend*/funky&move_to=local-modules&save_as=funky.tar.gz'
MIMER_URL='https://github.com/FriendCode/mimer/tarball/a812e5f631b9b5c969df5a2ea84b635490a96ced#module_name=mimer&module_path=Friend*/mimer&move_to=local-modules&save_as=mimer.tar.gz'
def _progress(tot):
print 'Downloaded {0} bytes'.format(tot)
#Make sure you order these in terms of what is needed first
for i in [FUNKY_URL, MIMER_URL, DULWICH_URL, GITTLE_URL]:
installer = shellista.ModuleInstaller(i, root_dir=os.path.dirname(os.path.abspath(__file__)))
print "Importing " + installer.module_name
installer.try_import_or_install(overwrite_existing=True, progress_func=_progress)
#Dulwich imports can now be done, since we've downloaded the modules
from dulwich.client import default_user_agent_string
from dulwich import porcelain
from gittle import Gittle
def main(self, line):
do_git(line)
#TODO: This might be better as a class, play around with it
def do_git(line):
"""Very basic Git commands: init, stage, commit, clone, modified, branch"""
#TODO: Clean up this code
#TODO: git functions should probably all use parseargs, like git push
#TODO: These git functions all follow the same pattern.
# Refactor these so they only contain their unique logic
#TODO: Add jsbain's keychain addition. Need to figure out how to
# Add ipad-specific modules without breaking Shellista everywhere
#TODO: If there is no ~/.gitconfig file, set up the username and passworde
#Find a git repo dir
def _find_repo(path):
subdirs = os.walk(path).next()[1]
if '.git' in subdirs:
return path
else:
parent = os.path.dirname(path)
if parent == path:
return None
else:
return _find_repo(parent)
#Get the parent git repo, if there is one
def _get_repo():
return Gittle(_find_repo(os.getcwd()))
def git_init(args):
if len(args) == 1:
Gittle.init(args[0])
else:
print command_help['init']
def git_status(args):
if len(args) == 0:
repo = _get_repo()
status = porcelain.status(repo.repo)
print status
else:
print command_help['git_staged']
def git_remote(args):
'''List remote repos'''
if len(args) == 0:
repo = _get_repo()
for key, value in repo.remotes.items():
print key, value
else:
print command_help['remote']
def git_add(args):
if len(args) > 0:
repo = _get_repo()
cwd = os.getcwd()
args = [os.path.join(os.path.relpath(cwd, repo.path), x)
if not os.path.samefile(cwd, repo.path) else x for x in args]
for file in args:
print 'Adding {0}'.format(file)
#repo.stage(args)
porcelain.add(repo.repo, args)
else:
print command_help['add']
def git_rm(args):
if len(args) > 0:
repo = _get_repo()
cwd = os.getcwd()
args = [os.path.join(os.path.relpath(cwd, repo.path), x)
if not os.path.samefile(cwd, repo.path) else x for x in args]
for file in args:
print 'Removing {0}'.format(file)
#repo.rm(args)
porcelain.rm(repo.repo, args)
else:
print command_help['rm']
def git_branch(args):
if len(args) == 0:
repo = _get_repo()
active = repo.active_branch
for key, value in repo.branches.items():
print ('* ' if key == active else '') + key, value
else:
print command_help['branch']
def git_reset(args):
if len(args) == 0:
repo = _get_repo()
porcelain.reset(repo.repo, 'hard')
else:
print command_help['reset']
def git_commit(args):
if len(args) == 3:
try:
repo = _get_repo()
#print repo.commit(name=args[1],email=args[2],message=args[0])
author = "{0} <{1}>".format(args[1], args[2])
print porcelain.commit(repo.repo, args[0], author, author )
except:
print 'Error: {0}'.format(sys.exc_value)
else:
print command_help['commit']
def git_clone(args):
if len(args) > 0:
url = args[0]
repo = Gittle.clone(args[0], args[1] if len(args)>1 else '.', bare=False)
#Set the origin
config = repo.repo.get_config()
config.set(('remote','origin'),'url',url)
config.write_to_path()
else:
print command_help['clone']
def git_pull(args):
if len(args) <= 1:
repo = _get_repo()
url = args[0] if len(args)==1 else repo.remotes.get('origin','')
if url:
repo.pull(origin_uri=url)
else:
print 'No pull URL.'
else:
print command_help['git pull']
def git_push(args):
parser = argparse.ArgumentParser(prog='git push'
, usage='git push [http(s)://<remote repo>] [-u username[:password]]'
, description="Push to a remote repository")
parser.add_argument('url', type=str, nargs='?', help='URL to push to')
parser.add_argument('-u', metavar='username[:password]', type=str, required=False, help='username[:password]')
result = parser.parse_args(args)
user, sep, pw = result.u.partition(':') if result.u else (None,None,None)
repo = _get_repo()
#Try to get the remote origin
if not result.url:
result.url = repo.remotes.get('origin','')
branch_name = os.path.join('refs','heads', repo.active_branch) #'refs/heads/%s' % repo.active_branch
print "Attempting to push to: {0}, branch: {1}".format(result.url, branch_name)
netloc = urlparse.urlparse(result.url).netloc
keychainservice = 'shellista.git.{0}'.format(netloc)
if sep and not user:
# -u : clears keychain for this server
for service in keychain.get_services():
if service[0]==keychainservice:
keychain.delete_password(*service)
#Attempt to retrieve user
if not user and SAVE_PASSWORDS:
try:
user = dict(keychain.get_services())[keychainservice]
except KeyError:
user, pw = console.login_alert('Enter credentials for {0}'.format(netloc))
if user:
if not pw and SAVE_PASSWORDS:
pw = keychain.get_password(keychainservice, user)
#Check again, did we retrieve a password?
if not pw:
user, pw = console.login_alert('Enter credentials for {0}'.format(netloc), login=user)
#pw = getpass.getpass('Enter password for {0}: '.format(user))
opener = auth_urllib2_opener(None, result.url, user, pw)
porcelain.push(repo.repo, result.url, branch_name, opener=opener)
keychain.set_password(keychainservice, user, pw)
else:
porcelain.push(repo.repo, result.url, branch_name)
def git_modified(args):
repo = _get_repo()
for mod_file in repo.modified_files:
print mod_file
def git_log(args):
parser = argparse.ArgumentParser(description='git log arg parser')
parser.add_argument('-f','--format',
action='store',
dest='format',
default=False)
parser.add_argument('-o','--output',
action='store',
dest='output',
type=argparse.FileType('w'),
default=sys.stdout)
parser.add_argument('-l','--length',
action='store',
type=int,
dest='max_entries',
default=None)
results = parser.parse_args(args)
try:
repo = _get_repo()
porcelain.log(repo.repo, max_entries=results.max_entries,format=results.format,outstream=results.output)
except ValueError:
print command_help['log']
def git_checkout(args):
if len(args) in [1,2]:
repo = _get_repo()
if len(args) == 1:
repo.clean_working()
repo.switch_branch('{0}'.format(args[0]))
#Temporary hack to get create branch into source
#TODO: git functions should probably all user parseargs, like git push
if len(args) == 2:
if args[0] == '-b':
#TODO: Add tracking as a parameter
print "Creating branch {0}".format(args[1])
repo.create_branch(repo.active_branch, args[1], tracking=None)
#Recursive call to checkout the branch we just created
git_checkout([args[1]])
else:
print command_help['checkout']
def git_help(args):
print 'help:'
for key, value in command_help.items():
print value
#TODO: Alphabetize
commands = {
'init': git_init
,'add': git_add
,'rm': git_rm
,'commit': git_commit
,'clone': git_clone
,'modified': git_modified
,'log': git_log
,'push': git_push
,'pull': git_pull
,'branch': git_branch
,'checkout': git_checkout
,'remote': git_remote
,'reset': git_reset
,'status': git_status
,'help': git_help
}
command_help = {
'init': 'git init <directory> - initialize a new Git repository'
,'add': 'git add <file1> .. [file2] .. - stage one or more files'
,'rm': 'git rm <file1> .. [file2] .. - unstage one or more files'
,'commit': 'git commit <message> <name> <email> - commit staged files'
,'clone': 'git clone <url> [path] - clone a remote repository'
,'modified': 'git modified - show what files have been modified'
,'log': 'git log - Options:\n\t[-l|--length numner_of _results]\n\t[-f|--format format string can use {message},{author},{author_email},{committer},{committer_email},{merge},{commit}]\n\t[-o|--output] file_name'
,'push': 'git push [http(s)://<remote repo>] [-u username[:password]] - push changes back to remote'
,'pull': 'git pull [http(s)://<remote repo>] - pull changes from a remote repository'
,'checkout': 'git checkout <branch> - check out a particular branch in the Git tree'
,'branch': 'git branch - show branches'
,'status': 'git status - show status of files (staged, unstaged, untracked)'
,'reset': 'git reset - reset a repo to its pre-change state'
,'help': 'git help'
}
#git_init.__repr__ = "git init abc"
args = bash(line)
try:
#Call the command and pass args
cmd = commands.get(args[0] if len(args) > 0 else 'help','help')
cmd(args[1:])
except:
#import traceback
#traceback.print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)
#traceback.print_tb(sys.exc_traceback)
print 'Error: {0}'.format(sys.exc_value)
#Urllib2 opener for dulwich
def auth_urllib2_opener(config, top_level_url, username, password):
if config is not None:
proxy_server = config.get("http", "proxy")
else:
proxy_server = None
# create a password manager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of None.
#top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
handlers = [handler]
if proxy_server is not None:
handlers.append(urllib2.ProxyHandler({"http": proxy_server}))
opener = urllib2.build_opener(*handlers)
if config is not None:
user_agent = config.get("http", "useragent")
else:
user_agent = None
if user_agent is None:
user_agent = default_user_agent_string()
opener.addheaders = [('User-agent', user_agent)]
return opener