-
Notifications
You must be signed in to change notification settings - Fork 3
/
vcprompt
executable file
·685 lines (567 loc) · 20.3 KB
/
vcprompt
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
#!/usr/bin/env python
"""
Usage: vcprompt [options]
Version control information in your prompt.
Options:
-f, --format FORMAT The format string to use.
-p, --path PATH The path to run vcprompt on.
-s, --systems Print all known VCSs and exit
-v, --version Show program's version number and exit
-h, --help Show this help message and exit
Formatting options:
-u, --unknown UNKNOWN The "unknown" value. Default is "(unknown)"
-A, --staged UNKNOWN The "staged" symbol. Default is '*'
-M, --modified UNKNOWN The "modified" symbol. Default is '+'
-U, --untracked UNKNOWN The "untracked" symbol. Default is '?'
VCS-specific formatting:
These options can be used for VCS-specific prompt formatting.
--format-bzr FORMAT Bazaar
--format-cvs FORMAT CVS
--format-darcs FORMAT Darcs
--format-fossil FORMAT Fossil
--format-git FORMAT Git
--format-hg FORMAT Mercurial
--format-svn FORMAT Subversion
Format tokens:
%s, %n The VCS "short name" (e.g. git, hg)
%h The hash (or revision number)
%r The revision number (or hash)
%b The currently checked out branch
%a Prints an asterisk if the repo has staged changes
%m Prints plus symbol if the repo is modified
%u Prints question mark if repo has new files
%P The name of the repository root directory
%p The relative path to the repository from cwd
"""
__version__ = '1.0.0-dev'
from subprocess import call, Popen, PIPE
from xml.dom.minidom import parseString
import optparse
import os
import re
import sys
try:
import sqlite3
has_sqlite3 = True
except ImportError:
try:
from pysqlite2 import dbapi2 as sqlite3
except ImportError:
has_sqlite3 = False
# check to make sure the '--without-environment' flag is called first
# this could be done in a callback, but we'd have to keep a note of every
# option which is affected by this flag
if '--without-environment' in sys.argv and \
sys.argv[1] != '--without-environment':
output = "The '--without-environment' option must come before any "
sys.stderr.write('%s other options.\n' % output)
sys.exit(1)
# we need to get this in early because callbacks are always called after
# every other option is already set, regardless of when the callback option
# is actually used in the script
if len(sys.argv) > 1 and sys.argv[1] == '--without-environment':
for k in os.environ.keys():
if k.startswith('VCPROMPT'):
del os.environ[k]
del sys.argv[1]
# user editable options
FORMAT = os.environ.get('VCPROMPT_FORMAT', '%s:%b')
UNKNOWN = os.environ.get('VCPROMPT_UNKNOWN', '(unknown)')
SYSTEMS = []
# status indicators
STAGED = os.environ.get('VCPROMPT_STAGED', '*')
MODIFIED = os.environ.get('VCPROMPT_MODIFIED', '+')
UNTRACKED = os.environ.get('VCPROMPT_UNTRACKED', '?')
def helper(*args, **kwargs):
"""
Prints the help message to stderr.
"""
sys.stderr.write(__doc__.lstrip())
sys.exit(0)
def systems(*args, **kwargs):
"""Prints all available systems to stdout."""
for system in SYSTEMS:
sys.stdout.write(system.func_name + '\n')
sys.exit(0)
def vcs(file):
"""
A convenience decorator.
Wraps a VCS function, appending it to ``SYSTEMS`` and sets the ``file``
attribute.
"""
def wrapper(function):
SYSTEMS.append(function)
function.file = file
return function
return wrapper
def version(*args):
"""
Convenience function for printing a version number.
"""
sys.stdout.write('vcprompt %s\n' % __version__)
sys.exit(0)
def vcprompt(options):
"""
Returns a formatted version control string for use in a shell prompt
or elsewhere.
Arguments:
``options``
An optparse.Values instance.
"""
options.path = os.path.abspath(os.path.expanduser(options.path))
original_path = options.path
prompt = None
while options.path:
# bail out on non-existant paths
if not os.path.exists(options.path):
break
# We need to change the current working directory or the '--path'
# flag might not work correctly with some formatting args.
# It's easier to do this here, rather than in every VCS function
if options.path != os.getcwd():
os.chdir(options.path)
for vcs in SYSTEMS:
if not os.path.exists(vcs.file):
continue
# set up custom formatting
vcs_format = getattr(options, 'format-' + vcs.__name__, None)
if vcs_format:
options.format = vcs_format
# the "vcs" file
options.file = vcs.file
prompt = vcs(options)
if prompt is not None:
prompt = prompt.replace("%P", os.path.basename(options.path))
prompt = prompt.replace("%p", os.path.relpath(original_path,
options.path))
return prompt
options.path = options.path.rsplit('/', 1)[0]
return ''
def main():
# parser
parser = optparse.OptionParser()
# dump the provided --help option
parser.remove_option('--help')
# our own --help flag
parser.add_option('-h', '--help', action='callback', callback=helper)
# format
parser.add_option('-f', '--format', dest='format', default=FORMAT)
# path
parser.add_option('-p', '--path', dest='path', default='.')
# systems
parser.add_option('-s', '--systems', action='callback', callback=systems)
# staged
parser.add_option('-A', '--staged', dest='staged', default=STAGED)
# modified
parser.add_option('-M', '--modified', dest='modified', default=MODIFIED)
# untracked
parser.add_option('-U', '--untracked', dest='untracked', default=UNTRACKED)
# unknown
parser.add_option('-u', '--unknown', dest='unknown', default=UNKNOWN)
# version
parser.add_option('-v', '--version', action='callback', callback=version)
# vcs-specific formatting
for system in SYSTEMS:
default = 'VCPROMPT_FORMAT_%s' % system.__name__.upper()
default = os.environ.get(default, None)
dest = 'format-%s' % system.__name__
flag = '--%s' % dest
parser.add_option(flag, dest=dest, default=default)
options, args = parser.parse_args()
output = vcprompt(options)
return output
@vcs(file=".bzr/branch/last-revision")
def bzr(options):
"""
Bazaar
The Bazaar version control system
"""
branch = revision = sha = modified = untracked = options.unknown
# local revision or global sha
if re.search('%(r|h)', options.format):
try:
fh = open(options.file, 'r')
for line in fh:
line = line.strip()
revision, sha = line.split(' ', 1)
# compensate for empty Bazaar repositories
if sha == 'null:':
sha = unknown
else:
sha = sha.rsplit('-', 1)[-1][:7]
break
except IOError:
pass
# status (modified/untracked)
if re.search('%[mu]', options.format):
command = 'bzr status --short'
process = Popen(command.split(), stdout=PIPE)
output = process.communicate()[0].strip()
returncode = process.returncode
if returncode == 0:
if output == '':
modified = ''
untracked = ''
else:
for line in output.split('\n'):
if line.startswith('M'):
modified = options.modified
elif line.startswith('?'):
untracked = options.untracked
# formatting
output = options.format
output = output.replace('%b', os.path.basename(options.path))
output = output.replace('%h', sha)
output = output.replace('%r', revision)
output = output.replace('%m', modified)
output = output.replace('%u', untracked)
output = output.replace('%s', 'bzr')
output = output.replace('%n', 'bzr')
return output
@vcs(file="CVS")
def cvs(options):
"""
CVS
Concurrent Versions System.
"""
output = options.format
output = output.replace('%b', options.unknown)
output = output.replace('%h', options.unknown)
output = output.replace('%r', options.unknown)
output = output.replace('%m', options.unknown)
output = output.replace('%u', options.unknown)
output = output.replace('%s', 'cvs')
output = output.replace('%n', 'cvs')
return output
@vcs(file="_darcs/hashed_inventory")
def darcs(options):
"""
Darcs
Distributed. Interactive. Smart.
"""
branch = sha = modified = untracked = options.unknown
# sha
if re.search('%(h|r)', options.format):
command = 'darcs changes --last 1 --xml'
process = Popen(command.split(), stdout=PIPE, stderr=PIPE)
output = process.communicate()[0]
returncode = process.returncode
if returncode == 0:
dom = parseString(output)
patch = dom.getElementsByTagName("patch")[0].getAttribute("hash")
sha = patch.rsplit('-', 1)[-1].split('.')[0][:7]
# branch
# darcs doesn't have in-repo local branching (yet), so just use
# the directory name for now
# see also: http://bugs.darcs.net/issue555
branch = os.path.basename(options.path)
# modified
if re.search('%[mu]', options.format):
command = 'darcs whatsnew -l -s'
process = Popen(command.split(), stdout=PIPE, stderr=PIPE)
output = process.communicate()[0]
returncode = process.returncode
if returncode == 1:
modified = ''
untracked = ''
elif returncode == 0:
for line in output:
line = line.strip()
if line.startswith('M'):
modified = options.modified
elif line.startswith('a'):
untracked = options.untracked
# formatting
output = options.format
output = output.replace('%b', branch)
output = output.replace('%h', sha)
output = output.replace('%r', sha)
output = output.replace('%m', modified)
output = output.replace('%u', untracked)
output = output.replace('%s', 'darcs')
output = output.replace('%n', 'darcs')
return output
@vcs(file="_FOSSIL_")
def fossil(options):
"""
Fossil
The Fossil version control system.
"""
branch = sha = modified = untracked = options.unknown
# all this just to get the repository file :(
repository = None
if has_sqlite3:
try:
conn = None
try:
query = "SELECT value FROM vvar where name = 'repository'"
conn = sqlite3.connect(options.file)
c = conn.cursor()
c.execute(query)
repository = c.fetchone()[0]
except sqlite3.OperationalError:
pass
finally:
if conn:
conn.close()
# grab the sha from the repo
if repository is not None and has_sqlite3:
try:
conn = None
try:
query = "SELECT uuid from blob ORDER BY rid DESC LIMIT 1"
conn = sqlite3.connect(repository)
c = conn.cursor()
c.execute(query)
sha = c.fetchone()[0][:7]
except sqlite3.OperationalError:
pass
finally:
if conn:
conn.close()
# branch
if sha != options.unknown and has_sqlite3:
try:
conn = None
try:
query = """SELECT value FROM tagxref WHERE rid =
(SELECT rid FROM blob WHERE uuid LIKE '%s%%')
AND value is not NULL LIMIT 1 """ % sha
conn = sqlite3.connect(repository)
c = conn.cursor()
c.execute(query)
branch = c.fetchone()[0]
except (sqlite3.OperationalError, TypeError):
pass
finally:
if conn:
conn.close()
# modified
if '%m' in options.format:
command = 'fossil changes'
process = Popen(command.split(), stdout=PIPE)
output = process.communicate()[0]
returncode = process.returncode
if returncode == 0:
if output:
modified = options.modified
else:
modified = ''
# untracked files
if '%u' in options.format:
command = 'fossil extras'
process = Popen(command.split(), stdout=PIPE)
output = process.communicate()[0]
returncode = process.returncode
if returncode == 0:
if output:
untracked = options.untracked
else:
untracked = ''
# parse out formatting string
output = options.format
output = output.replace('%b', branch)
output = output.replace('%h', sha)
output = output.replace('%r', sha)
output = output.replace('%m', modified)
output = output.replace('%u', untracked)
output = output.replace('%s', 'fossil')
output = output.replace('%n', 'fossil')
return output
@vcs(file=".git")
def git(options):
"""
Git
The fast version control system.
"""
staged = branch = sha = modified = untracked = options.unknown
if os.path.isfile(options.file):
options.file = open(options.file, "r").read().rstrip('\n').split(" ", 1)[1]
def revstring(ref, chars=7):
if not os.path.exists(ref):
return ''
try:
fh = open(ref, 'r')
for line in fh:
return line.strip()[0:chars]
except IOError:
pass
return ''
# the current branch is required to get the sha
if re.search('%(b|r|h)', options.format):
branch_file = os.path.join(options.file, 'HEAD')
try:
fh = open(branch_file, 'r')
for line in fh:
line = line.strip()
if line.startswith('ref: refs/heads/'):
branch = (line.split('/', 2)[-1] or options.unknown)
break
if branch == options.unknown:
command = 'git describe --always'
process = Popen(command.split(), stdout=PIPE, stderr=PIPE)
output = process.communicate()[0]
returncode = process.returncode
if returncode == 0:
branch = "(%s)" % (output.strip())
else:
branch = options.unknown
except IOError:
pass
# sha/revision
if re.search('%(r|h)', options.format) and branch != options.unknown:
sha_file = os.path.join(options.file, 'refs/heads/%s' % branch)
sha = revstring(sha_file)
# modified
if '%m' in options.format:
command = 'git diff --quiet --exit-code'
returncode = call(command, stdout=PIPE, stderr=PIPE, shell=True)
if returncode == 1:
modified = options.modified
else:
modified = ''
# untracked files
if '%u' in options.format:
command = 'git ls-files --other --exclude-standard'
process = Popen(command.split(), stdout=PIPE, stderr=PIPE)
output = process.communicate()[0]
returncode = process.returncode
if returncode == 0:
if output == '':
untracked = ''
else:
untracked = options.untracked
# staged files
if '%a' in options.format:
command = 'git diff --quiet --cached --exit-code'
returncode = call(command, stdout=PIPE, stderr=PIPE, shell=True)
if returncode == 1:
staged = options.staged
else:
staged = ''
# formatting
output = options.format
output = output.replace('%b', branch)
output = output.replace('%h', sha)
output = output.replace('%r', sha)
output = output.replace('%m', modified)
output = output.replace('%u', untracked)
output = output.replace('%a', staged)
output = output.replace('%s', 'git')
output = output.replace('%n', 'git')
return output
@vcs(file=".hg")
def hg(options):
"""
Mercurial
The Mercurial version control system.
"""
branch = revision = sha = modified = untracked = options.unknown
# changeset ID or global sha
if re.search('%(r|h)', options.format):
try:
fh = open(os.path.join(options.file, 'cache/branchheads'), 'r')
line = fh.readline()
sha, revision = line.strip().split()
sha = sha[:7]
except IOError:
pass
# branch
if '%b' in options.format:
file = os.path.join(options.file, 'undo.branch')
try:
fh = open(file, 'r')
line = fh.readline()
branch = line.strip()
except IOError:
pass
# modified
if '%m' in options.format:
command = 'hg status --modified'
process = Popen(command.split(), stdout=PIPE, stderr=PIPE)
output = process.communicate()[0].strip()
returncode = process.returncode
if returncode == 0:
if output == '':
modified = ''
else:
modified = options.modified
# untracked
if '%u' in options.format:
command = 'hg status --unknown'
process = Popen(command.split(), stdout=PIPE, stderr=PIPE)
output = process.communicate()[0]
returncode = process.returncode
if output == '':
untracked = ''
else:
untracked = options.untracked
output = options.format
output = output.replace('%b', branch)
output = output.replace('%h', sha)
output = output.replace('%r', revision)
output = output.replace('%m', modified)
output = output.replace('%u', untracked)
output = output.replace('%s', 'hg')
output = output.replace('%n', 'hg')
return output
@vcs(file=".svn/entries")
def svn(options):
"""
Subversion
The Subversion version control system.
"""
branch = revision = modified = untracked = options.unknown
# branch
command = 'svn info %s' % options.path
process = Popen(command.split(), stdout=PIPE, stderr=PIPE)
output = process.communicate()[0]
returncode = process.returncode
if returncode == 0:
# compile some regexes
branch_regex = re.compile('((tags|branches)/([^/]*)|trunk)')
revision_regex = re.compile('^Revision: (?P<revision>\d+)')
for line in output.split('\n'):
# branch
if '%b' in options.format:
if re.match('URL', line):
matches = re.search(branch_regex, line)
if matches:
branch = matches.groups(0)[0]
# revision/sha
if re.search('%(r|h)', options.format):
if re.match('Revision:', line):
matches = re.search(revision_regex, line)
if 'revision' in matches.groupdict():
revision = matches.group('revision')
# modified
if re.search('%[mu]', options.format):
command = 'svn status'
process = Popen(command, shell=True, stdout=PIPE)
output = process.communicate()[0]
returncode = process.returncode
if returncode == 0:
modified = ''
untracked = ''
if output:
codes = [line[0] for line in output.split('\n') if line]
if 'M' in codes:
modified = options.modified
if '?' in codes:
untracked = options.untracked
# formatting
output = options.format
output = output.replace('%r', revision)
output = output.replace('%h', revision)
output = output.replace('%b', branch)
output = output.replace('%m', modified)
output = output.replace('%u', untracked)
output = output.replace('%s', 'svn')
output = output.replace('%n', 'svn')
return output
if __name__ == '__main__':
prompt = main()
if prompt:
sys.stdout.write(prompt + '\n')
else:
sys.exit(1)