1153 lines
38 KiB
Python
Executable File
1153 lines
38 KiB
Python
Executable File
#!/usr/bin/env python
|
|
|
|
# Josh's SVN wrapper script
|
|
#
|
|
# Please view the README file from the jsvn repository or online at
|
|
# https://github.com/holtrop/jsvn
|
|
|
|
import sys
|
|
import os
|
|
import re
|
|
import time
|
|
from subprocess import *
|
|
import traceback
|
|
import datetime
|
|
import types
|
|
|
|
STATUS_LINE_REGEX = r'[ACDIMRX?!~ ][CM ][L ][+ ][SX ][KOTB ]..(.+)'
|
|
|
|
###########################################################################
|
|
# Subcommand Handler Return Values #
|
|
###########################################################################
|
|
RET_OK = 0
|
|
RET_ERR = 1
|
|
RET_REEXEC = 2
|
|
|
|
###########################################################################
|
|
# ANSI escape color code values #
|
|
###########################################################################
|
|
COLORS = {
|
|
'black': 0,
|
|
'red': 1,
|
|
'green': 2,
|
|
'yellow': 3,
|
|
'blue': 4,
|
|
'magenta': 5,
|
|
'cyan': 6,
|
|
'white': 7,
|
|
}
|
|
using_color = False
|
|
|
|
###########################################################################
|
|
# Configuration #
|
|
###########################################################################
|
|
def read_config_file(config, path):
|
|
if os.path.exists(path):
|
|
fh = open(path, 'r')
|
|
script = fh.read()
|
|
fh.close()
|
|
try:
|
|
exec(script, config)
|
|
except:
|
|
sys.stderr.write('Configuration file error in "%s":\n' % path)
|
|
traceback.print_exception(sys.exc_info()[0], sys.exc_info()[1],
|
|
None)
|
|
tb = traceback.extract_tb(sys.exc_info()[2])
|
|
for ent in tb[1:]:
|
|
lineno, fn = ent[1:3]
|
|
sys.stderr.write(' File "%s", line %d, in %s\n'
|
|
% (path, lineno, fn))
|
|
|
|
def get_config(svn):
|
|
config = {
|
|
'pager': '',
|
|
'use_pager': True,
|
|
'use_color': True,
|
|
'aliases': {
|
|
# default jsvn aliases
|
|
'tags': 'tag',
|
|
'branches': 'branch'},
|
|
'svn': '',
|
|
}
|
|
|
|
global_user_config_fname = os.path.expanduser('~/.jsvn')
|
|
read_config_file(config, global_user_config_fname)
|
|
|
|
wc_user_config_fname = get_svn_wc_root(svn) + '/.svn/jsvn'
|
|
read_config_file(config, wc_user_config_fname)
|
|
|
|
return config
|
|
|
|
###########################################################################
|
|
# Utility Functions #
|
|
###########################################################################
|
|
def ansi_color(out, fg=None, bg=None, bold=False):
|
|
if using_color:
|
|
bc = 1 if bold else 0
|
|
if fg is not None:
|
|
out.write('\033[%d;%dm' % (bc, 30 + COLORS[fg]))
|
|
if bg is not None:
|
|
out.write('\033[%d;%dm' % (bc, 40 + COLORS[bg]))
|
|
|
|
def ansi_reset(out):
|
|
if using_color:
|
|
out.write('\033[0m')
|
|
|
|
def colordiff(out, line):
|
|
line = line.rstrip()
|
|
if re.match(r'Index:\s', line):
|
|
ansi_color(out, 'yellow')
|
|
out.write(line)
|
|
ansi_reset(out)
|
|
out.write('\n')
|
|
return
|
|
if re.match(r'={67}', line):
|
|
ansi_color(out, 'yellow')
|
|
out.write(line)
|
|
ansi_reset(out)
|
|
out.write('\n')
|
|
return
|
|
if re.match(r'-', line):
|
|
ansi_color(out, 'red')
|
|
out.write(line)
|
|
ansi_reset(out)
|
|
out.write('\n')
|
|
return
|
|
elif re.match(r'\+', line):
|
|
ansi_color(out, 'green')
|
|
out.write(line)
|
|
ansi_reset(out)
|
|
out.write('\n')
|
|
return
|
|
m = re.match(r'(@@.*@@)(.*)', line)
|
|
if m is None:
|
|
m = re.match(r'(##.*##)(.*)', line)
|
|
if m is not None:
|
|
ansi_color(out, 'cyan')
|
|
out.write(m.group(1))
|
|
ansi_reset(out)
|
|
out.write(m.group(2))
|
|
out.write('\n')
|
|
return
|
|
out.write(line)
|
|
out.write('\n')
|
|
|
|
def find_in_path(cmd):
|
|
path_entries = os.environ['PATH'].split(os.pathsep)
|
|
for p in path_entries:
|
|
full_path = os.path.join(p, cmd)
|
|
if os.path.exists(full_path):
|
|
return full_path
|
|
return ''
|
|
|
|
def get_svn_url(svn):
|
|
for line in Popen([svn, 'info'], stdout=PIPE).communicate()[0].split('\n'):
|
|
m = re.match(r'^URL:\s*(.*?)\s*$', line)
|
|
if m is not None:
|
|
return m.group(1)
|
|
return ''
|
|
|
|
def get_svn_root_url(svn):
|
|
url = get_svn_url(svn)
|
|
parts = url.split('/')
|
|
for i in range(0, len(parts)):
|
|
if parts[i] in ('trunk', 'tags', 'branches'):
|
|
return '/'.join(parts[:i])
|
|
return ''
|
|
|
|
def get_svn_wc_root(svn):
|
|
proc = Popen([svn, 'info'], stdout=PIPE, stderr=PIPE)
|
|
for line in proc.communicate()[0].split('\n'):
|
|
m = re.match(r'Working Copy Root Path: (.*)$', line)
|
|
if m is not None:
|
|
return m.group(1)
|
|
return ''
|
|
|
|
def get_svn_wc_revision(svn):
|
|
for line in Popen([svn, 'info'], stdout=PIPE).communicate()[0].split('\n'):
|
|
m = re.match(r'Revision: (\d+)$', line)
|
|
if m is not None:
|
|
return int(m.group(1))
|
|
return 0
|
|
|
|
def get_svn_rel_path(svn):
|
|
url = get_svn_url(svn)
|
|
parts = url.split('/')
|
|
for i in range(0, len(parts) - 1):
|
|
if parts[i] == 'trunk' or i > 0 and parts[i-1] in ('tags', 'branches'):
|
|
return '/' + '/'.join(parts[i+1:])
|
|
return '/'
|
|
|
|
def get_svn_top_level(svn):
|
|
url = get_svn_url(svn)
|
|
parts = url.split('/')
|
|
for i in range(0, len(parts)):
|
|
if parts[i] == 'trunk' or i > 0 and parts[i-1] in ('tags', 'branches'):
|
|
return '/'.join(parts[:i+1])
|
|
return ''
|
|
|
|
def get_svn_branch_list(svn):
|
|
colist = []
|
|
root = get_svn_root_url(svn)
|
|
lines = Popen([svn, 'ls', root + '/branches'],
|
|
stdout=PIPE, stderr=PIPE).communicate()[0].split('\n')
|
|
for line in lines:
|
|
if re.match(r'^\s*$', line) is None:
|
|
colist.append(re.sub(r'/$', '', line))
|
|
return colist
|
|
|
|
def get_svn_tag_list(svn):
|
|
colist = []
|
|
root = get_svn_root_url(svn)
|
|
lines = Popen([svn, 'ls', root + '/tags'],
|
|
stdout=PIPE, stderr=PIPE).communicate()[0].split('\n')
|
|
for line in lines:
|
|
if re.match(r'^\s*$', line) is None:
|
|
colist.append(re.sub(r'/$', '', line))
|
|
return colist
|
|
|
|
def get_svn_property(svn, prop, path):
|
|
return Popen([svn, 'propget', prop, path], stdout=PIPE).communicate()[0]
|
|
|
|
def set_svn_property(svn, prop, val, path):
|
|
Popen([svn, 'propset', prop, val, path], stdout=PIPE).wait()
|
|
|
|
def del_svn_property(svn, prop, path):
|
|
Popen([svn, 'propdel', prop, path], stdout=PIPE).wait()
|
|
|
|
def filter_update(pout, out):
|
|
external = ''
|
|
external_printed = True
|
|
any_external_printed = False
|
|
for line in iter(pout.readline, ''):
|
|
m = re.match(r"Fetching external item into '(.*)':", line)
|
|
if m is not None:
|
|
external = m.group(1)
|
|
external_printed = False
|
|
continue
|
|
if re.match(r'\s*$', line):
|
|
continue
|
|
if re.match(r'External at revision ', line):
|
|
if external_printed:
|
|
out.write(line)
|
|
continue
|
|
if re.match(r'(Updated.to|At) revision', line):
|
|
if any_external_printed:
|
|
out.write('\n')
|
|
out.write(line)
|
|
continue
|
|
|
|
# anything not matched yet will cause an external to be shown
|
|
if not external_printed:
|
|
out.write("\nExternal '%s':\n" % external)
|
|
external_printed = True
|
|
any_external_printed = True
|
|
if re.match(r'[ADUCGER ]{2}[B ][C ] ', line):
|
|
action = line[0]
|
|
prop_action = line[1]
|
|
if action == 'A':
|
|
ansi_color(out, 'green')
|
|
elif action == 'D':
|
|
ansi_color(out, 'red')
|
|
elif action == 'U':
|
|
ansi_color(out, 'cyan')
|
|
elif action == 'C':
|
|
ansi_color(out, 'yellow')
|
|
elif action == 'G':
|
|
ansi_color(out, 'magenta')
|
|
elif action == ' ':
|
|
if prop_action == 'U':
|
|
ansi_color(out, 'cyan')
|
|
out.write(line.rstrip())
|
|
ansi_reset(out)
|
|
out.write('\n')
|
|
continue
|
|
out.write(line)
|
|
|
|
def get_unknowns(svn):
|
|
unknowns = []
|
|
pout = Popen([svn, 'status'], stdout=PIPE).stdout
|
|
for line in iter(pout.readline, ''):
|
|
m = re.match(r'\? (.*)$', line)
|
|
if m is not None:
|
|
unknowns.append(m.group(1))
|
|
return unknowns
|
|
|
|
def descendant_path(child, parent):
|
|
if child[0] != '/' and parent[0] == '/':
|
|
child = os.getcwd() + '/' + child
|
|
elif child[0] == '/' and parent[0] != '/':
|
|
parent = os.getcwd() + '/' + parent
|
|
if child == parent:
|
|
return True
|
|
if child.startswith(parent):
|
|
if child[len(parent)] == '/':
|
|
return True
|
|
return False
|
|
|
|
def get_stashes_dir(svn):
|
|
stashes_dir = get_svn_wc_root(svn) + '/.svn/stashes'
|
|
if not os.path.isdir(stashes_dir):
|
|
os.mkdir(stashes_dir)
|
|
return stashes_dir
|
|
|
|
def get_stash_ids(svn):
|
|
stashes_dir = get_stashes_dir(svn)
|
|
stash_files = os.listdir(stashes_dir)
|
|
stash_ids = {}
|
|
for sf in stash_files:
|
|
m = re.match('stash\.(\d+)$', sf)
|
|
if m is not None:
|
|
stash_ids[int(m.group(1))] = 1
|
|
return sorted(stash_ids.keys())
|
|
|
|
def get_stash_fname(svn, idx):
|
|
return get_stashes_dir(svn) + '/stash.%d' % idx
|
|
|
|
def get_next_stash_idx(svn):
|
|
stash_ids = get_stash_ids(svn)
|
|
idx = 1
|
|
if len(stash_ids) > 0:
|
|
idx = stash_ids[-1] + 1
|
|
return idx
|
|
|
|
###########################################################################
|
|
# Subcommand Handlers #
|
|
###########################################################################
|
|
def add(argv, svn, out):
|
|
if len(argv) < 2:
|
|
# do not handle if no targets are passed
|
|
return RET_REEXEC
|
|
if len(filter(lambda x: x.startswith('-'), argv)) != 0:
|
|
# do not handle if any options are passed
|
|
return RET_REEXEC
|
|
# for each target specified, check if there are unversioned items
|
|
# underneath it (for directories) and add them as well
|
|
# if none are found, fall back to the native svn add
|
|
unknowns = get_unknowns(svn)
|
|
for path in argv[1:]:
|
|
if path == '.':
|
|
path = os.getcwd()
|
|
if path.endswith('/'):
|
|
path = path[:-1]
|
|
found_one = False
|
|
for u in unknowns:
|
|
if descendant_path(u, path):
|
|
Popen([svn, 'add', u], stdout=out).wait()
|
|
found_one = True
|
|
if not found_one:
|
|
Popen([svn, 'add', path], stdout=out).wait()
|
|
return RET_OK
|
|
|
|
def bisect(argv, svn, out):
|
|
def usage():
|
|
sys.stderr.write('''Usage: bisect <operation>
|
|
Operations:
|
|
init initialize a new bisect operation
|
|
bad mark the current revision as bad - containing the change sought
|
|
good mark the current revision as good - older than the change sought
|
|
reset terminate the bisect operation and return to the original revision
|
|
''')
|
|
return RET_ERR
|
|
if len(argv) < 2:
|
|
return usage()
|
|
action = argv[1]
|
|
if action not in ('init', 'bad', 'good', 'reset'):
|
|
return usage()
|
|
wc_root = get_svn_wc_root(svn)
|
|
bisect_dir = '%s/.svn/bisect' % wc_root
|
|
def get_rev_from_file(fname):
|
|
path = '%s/%s' % (bisect_dir, fname)
|
|
if not os.path.exists(path):
|
|
return -1
|
|
fh = open(path, 'r')
|
|
line = fh.readline()
|
|
fh.close()
|
|
m = re.match('(\d+)$', line)
|
|
if m is None:
|
|
return -2
|
|
return int(m.group(1))
|
|
def write_rev_to_file(fname, rev):
|
|
fh = open('%s/%s' % (bisect_dir, fname), 'w')
|
|
fh.write(str(rev) + '\n')
|
|
fh.close()
|
|
def rm_bisect_files():
|
|
for f in os.listdir(bisect_dir):
|
|
os.unlink('%s/%s' % (bisect_dir, f))
|
|
def get_revs_between(start, end):
|
|
revs = []
|
|
proc = Popen([svn, 'log', '-r%d:%d' % (start, end)], stdout=PIPE)
|
|
for line in iter(proc.stdout.readline, ''):
|
|
m = re.match(r'r(\d+).*\|.*\|.*\|', line)
|
|
if m is not None:
|
|
rev = int(m.group(1))
|
|
if rev > start and rev < end:
|
|
revs.append(rev)
|
|
return revs
|
|
def do_bisect():
|
|
good_rev = get_rev_from_file('good')
|
|
bad_rev = get_rev_from_file('bad')
|
|
if good_rev < 0 or bad_rev < 0:
|
|
return
|
|
revs = get_revs_between(good_rev, bad_rev)
|
|
if len(revs) < 1:
|
|
if get_svn_wc_revision(svn) != bad_rev:
|
|
update(['update', '-r%d' % bad_rev], svn, out)
|
|
out.write('The first bad revision is %d\n' % get_svn_wc_revision(svn))
|
|
return
|
|
rev = revs[len(revs) / 2]
|
|
update(['update', '-r%d' % rev], svn, out)
|
|
out.write('Bisect: inspecting revision %d, %d revisions remaining\n'
|
|
% (rev, len(revs)))
|
|
def init_err():
|
|
sys.stderr.write('Error: did you bisect init first?\n')
|
|
return RET_ERR
|
|
if action == 'init':
|
|
if not os.path.exists(bisect_dir):
|
|
os.mkdir(bisect_dir)
|
|
rm_bisect_files()
|
|
write_rev_to_file('start', get_svn_wc_revision(svn))
|
|
out.write('Initialized for bisect\n')
|
|
elif action == 'bad':
|
|
if get_rev_from_file('start') < 0:
|
|
return init_err()
|
|
write_rev_to_file('bad', get_svn_wc_revision(svn))
|
|
do_bisect()
|
|
elif action == 'good':
|
|
if get_rev_from_file('start') < 0:
|
|
return init_err()
|
|
write_rev_to_file('good', get_svn_wc_revision(svn))
|
|
do_bisect()
|
|
elif action == 'reset':
|
|
rev = get_rev_from_file('start')
|
|
if rev < 0:
|
|
return init_err()
|
|
rm_bisect_files()
|
|
update(['update', '-r%d' % rev], svn, out)
|
|
return RET_OK
|
|
|
|
def branch(argv, svn, out):
|
|
origin = get_svn_top_level(svn)
|
|
root = get_svn_root_url(svn)
|
|
if origin == '' or root == '':
|
|
sys.stderr.write("Could not determine origin/root URL\n")
|
|
return RET_ERR
|
|
if len(argv) < 2:
|
|
bl = ['trunk'] + get_svn_branch_list(svn)
|
|
current = get_svn_top_level(svn).split('/')[-1]
|
|
bl.sort()
|
|
for b in bl:
|
|
if b == current:
|
|
out.write('*')
|
|
ansi_color(out, 'green')
|
|
else:
|
|
out.write(' ')
|
|
out.write(b)
|
|
if b == current:
|
|
ansi_reset(out)
|
|
out.write('\n')
|
|
return RET_OK
|
|
branch_name = argv[-1]
|
|
if len(argv) >= 3 and argv[1] == "-d":
|
|
# delete branch in argv[2]
|
|
Popen([svn, 'rm', root + '/branches/' + argv[2], '-m',
|
|
"Removed branch '%s'" % branch_name], stdout=out).wait()
|
|
return RET_OK
|
|
comment = "Created '%s' branch" % branch_name
|
|
branch_path = root + '/branches/' + branch_name
|
|
Popen([svn, 'copy', origin, branch_path, '-m', comment], stdout=out).wait()
|
|
return RET_OK
|
|
|
|
def tag(argv, svn, out):
|
|
origin = get_svn_top_level(svn)
|
|
root = get_svn_root_url(svn)
|
|
if origin == '' or root == '':
|
|
sys.stderr.write("Could not determine origin/root URL\n")
|
|
return RET_ERR
|
|
tl = get_svn_tag_list(svn)
|
|
if len(argv) < 2:
|
|
tl.sort()
|
|
for t in tl:
|
|
out.write(t + '\n')
|
|
return RET_OK
|
|
tag_name = argv[-1]
|
|
if len(argv) == 4 and argv[1] == '-m':
|
|
old_tag_name = argv[2]
|
|
if not old_tag_name in tl:
|
|
sys.stderr.write('Tag %s not found!\n' % old_tag_name)
|
|
return RET_ERR
|
|
Popen([svn, 'mv',
|
|
root + '/tags/' + old_tag_name, root + '/tags/' + tag_name,
|
|
'-m', "Renamed tag '%s' to '%s'" % (old_tag_name, tag_name)],
|
|
stdout=out).wait()
|
|
return RET_OK
|
|
if len(argv) >= 3 and argv[1] == "-d":
|
|
if not tag_name in tl:
|
|
sys.stderr.write('Tag %s not found!\n' % tag_name)
|
|
return RET_ERR
|
|
# delete tag in argv[2]
|
|
Popen([svn, 'rm', root + '/tags/' + tag_name, '-m',
|
|
"Removed tag '%s'" % tag_name], stdout=out).wait()
|
|
return RET_OK
|
|
comment = "Created '%s' tag" % tag_name
|
|
tag_path = root + '/tags/' + tag_name
|
|
Popen([svn, 'copy', origin, tag_path, '-m', comment], stdout=out).wait()
|
|
return RET_OK
|
|
|
|
def switch(argv, svn, out):
|
|
if len(argv) < 2:
|
|
return RET_REEXEC
|
|
switched = False
|
|
root = get_svn_root_url(svn)
|
|
path = get_svn_rel_path(svn)
|
|
while True:
|
|
if argv[1] == 'trunk':
|
|
pout = Popen([svn, 'switch', root + '/trunk' + path],
|
|
stdout=PIPE).stdout
|
|
filter_update(pout, out)
|
|
switched = True
|
|
break
|
|
bl = get_svn_branch_list(svn)
|
|
if argv[1] in bl:
|
|
pout = Popen([svn, 'switch', root + '/branches/' + argv[1] + path],
|
|
stdout=PIPE).stdout
|
|
filter_update(pout, out)
|
|
switched = True
|
|
break
|
|
tl = get_svn_tag_list(svn)
|
|
if argv[1] in tl:
|
|
pout = Popen([svn, 'switch', root + '/tags/' + argv[1] + path],
|
|
stdout=PIPE).stdout
|
|
filter_update(pout, out)
|
|
switched = True
|
|
break
|
|
# argument is not a tag/branch name
|
|
break
|
|
if switched:
|
|
url = get_svn_url(svn)
|
|
out.write('URL: %s\n' % url)
|
|
return RET_OK
|
|
pout = Popen([svn] + argv, stdout=PIPE).stdout
|
|
filter_update(pout, out)
|
|
return RET_OK
|
|
|
|
def merge(argv, svn, out):
|
|
if len(argv) < 2:
|
|
return RET_REEXEC
|
|
root = get_svn_root_url(svn)
|
|
branches = get_svn_branch_list(svn)
|
|
if not argv[1] in branches:
|
|
return RET_REEXEC
|
|
lines = Popen([svn, 'log', '--stop-on-copy', root + '/branches/' + argv[1]],
|
|
stdout=PIPE).communicate()[0].split('\n')
|
|
rev = 0
|
|
for line in lines:
|
|
m = re.match(r'^r(\d+)\s', line)
|
|
if m is not None:
|
|
rev = m.group(1)
|
|
if rev == 0:
|
|
sys.stderr.write('Could not get first branch revision\n')
|
|
return RET_ERR
|
|
path = get_svn_rel_path(svn)
|
|
Popen([svn, 'merge', '-r%s:HEAD' % rev,
|
|
root + '/branches/' + argv[1] + path, '.'], stdout=out).wait()
|
|
return RET_OK
|
|
|
|
def watch_lock(argv, svn, out):
|
|
if len(argv) < 2:
|
|
return RET_ERR
|
|
path = argv[1]
|
|
if os.path.exists(path):
|
|
# Get the repository URL of the file being watched
|
|
p = Popen([svn, 'info', path], stdout=PIPE)
|
|
lines = p.communicate()[0].split('\n')
|
|
for line in lines:
|
|
m = re.match(r'URL: (.*)', line)
|
|
if m is not None:
|
|
path = m.group(1)
|
|
break
|
|
|
|
last_lock_owner = ''
|
|
while True:
|
|
lock_owner = ''
|
|
p = Popen([svn, 'info', path], stdout=PIPE)
|
|
lines = p.communicate()[0].split('\n')
|
|
for line in lines:
|
|
m = re.match(r'Lock\sOwner:\s*(.*)', line)
|
|
if m is not None:
|
|
lock_owner = m.group(1)
|
|
break
|
|
if lock_owner == '':
|
|
break
|
|
if lock_owner != last_lock_owner:
|
|
out.write('Locked by: %s\n' % lock_owner)
|
|
last_lock_owner = lock_owner
|
|
time.sleep(60)
|
|
|
|
out.write('''
|
|
_ _ _ _ _ _
|
|
| | | |_ __ | | ___ ___| | _____ __| | |
|
|
| | | | '_ \| |/ _ \ / __| |/ / _ \/ _` | |
|
|
| |_| | | | | | (_) | (__| < __/ (_| |_|
|
|
\___/|_| |_|_|\___/ \___|_|\_\___|\__,_(_)
|
|
|
|
''')
|
|
return RET_OK
|
|
|
|
def users(argv, svn, out):
|
|
path = '.'
|
|
if len(argv) > 1:
|
|
path = argv[1]
|
|
users = {}
|
|
p = Popen([svn, 'log', '-q', path], stdout=PIPE)
|
|
for line in iter(p.stdout.readline, ''):
|
|
m = re.match('r\d+\s*\|([^|]+)\|', line)
|
|
if m is not None:
|
|
user = m.group(1).strip()
|
|
if not user.lower() in users:
|
|
users[user.lower()] = [user, 1]
|
|
else:
|
|
users[user.lower()][1] += 1
|
|
values = users.values()
|
|
values.sort(key = lambda x: x[1], reverse = True)
|
|
for v in values:
|
|
out.write("%8d %s\n" % (v[1], v[0]))
|
|
return RET_OK
|
|
|
|
def binaries(argv, svn, out, base_path = '.'):
|
|
for ent in os.listdir(base_path):
|
|
if ent in ('.', '..', '.svn'):
|
|
continue
|
|
ent_path = os.sep.join([base_path, ent])
|
|
if os.path.isfile(ent_path):
|
|
mime_type = get_svn_property(svn, 'svn:mime-type', ent_path)
|
|
if mime_type != '' and not re.match(r'text/.*', mime_type):
|
|
# we found a binary file
|
|
needs_lock = get_svn_property(svn, 'svn:needs-lock', ent_path)
|
|
if needs_lock:
|
|
out.write('* ')
|
|
elif len(argv) >= 2 and argv[1] == '--set-lock':
|
|
set_svn_property(svn, 'svn:needs-lock', '*', ent_path)
|
|
out.write('S ')
|
|
else:
|
|
out.write(' ')
|
|
out.write(ent_path)
|
|
out.write('\n')
|
|
elif os.path.isdir(ent_path):
|
|
binaries(argv, svn, out, os.sep.join([base_path, ent]))
|
|
return RET_OK
|
|
|
|
def lockable(argv, svn, out):
|
|
if len(argv) >= 2 and argv[1] == '--status':
|
|
for ob in argv[2:]:
|
|
ob_path = os.sep.join([base_path, ob])
|
|
|
|
needs_lock = get_svn_property(svn, 'svn:needs-lock', ob_path)
|
|
if needs_lock:
|
|
out.write('* ')
|
|
else:
|
|
out.write(' ')
|
|
out.write(ob_path)
|
|
out.write('\n')
|
|
|
|
elif len(argv) >= 2 and argv[1] == '--remove':
|
|
for ob in argv[2:]:
|
|
ob_path = os.sep.join([base_path, ob])
|
|
del_svn_property(svn, 'svn:needs-lock', ob_path)
|
|
|
|
else:
|
|
# note this is the default assumed operation
|
|
for ob in argv[1:]:
|
|
ob_path = os.sep.join([base_path, ob])
|
|
set_svn_property(svn, 'svn:needs-lock', '*', ob_path)
|
|
return RET_OK
|
|
|
|
def diff(argv, svn, out):
|
|
pout = Popen([svn] + argv, stdout=PIPE).stdout
|
|
for line in iter(pout.readline, ''):
|
|
colordiff(out, line)
|
|
return RET_OK
|
|
|
|
def log(argv, svn, out):
|
|
mode = 'normal'
|
|
pout = Popen([svn] + argv, stdout=PIPE).stdout
|
|
for line in iter(pout.readline, ''):
|
|
line = line.rstrip()
|
|
if mode == 'normal' and re.match(r'(r\d+)\s+\|', line):
|
|
parts = line.split('|')
|
|
if len(parts) == 4:
|
|
ansi_color(out, 'blue', bold=True)
|
|
out.write(parts[0])
|
|
ansi_reset(out)
|
|
out.write('|')
|
|
ansi_color(out, 'cyan')
|
|
out.write(parts[1])
|
|
ansi_reset(out)
|
|
out.write('|')
|
|
ansi_color(out, 'magenta')
|
|
out.write(parts[2])
|
|
ansi_reset(out)
|
|
out.write('|')
|
|
out.write(parts[3])
|
|
out.write('\n')
|
|
else:
|
|
out.write(line)
|
|
out.write('\n')
|
|
elif mode == 'normal' and re.match(r'Changed.paths:', line):
|
|
out.write(line)
|
|
out.write('\n')
|
|
mode = 'cp'
|
|
elif mode == 'cp' and re.match(r' [ADM] ', line):
|
|
action = line[3]
|
|
if action == 'A':
|
|
ansi_color(out, 'green')
|
|
elif action == 'D':
|
|
ansi_color(out, 'red')
|
|
elif action == 'M':
|
|
ansi_color(out, 'yellow')
|
|
out.write(line)
|
|
ansi_reset(out)
|
|
out.write('\n')
|
|
elif re.match(r'-{72}', line):
|
|
ansi_color(out, 'yellow')
|
|
out.write(line)
|
|
ansi_reset(out)
|
|
out.write('\n')
|
|
mode = 'normal'
|
|
elif re.match(r'={67}', line):
|
|
ansi_color(out, 'yellow')
|
|
out.write(line)
|
|
ansi_reset(out)
|
|
out.write('\n')
|
|
mode = 'diff'
|
|
elif mode == 'diff':
|
|
colordiff(out, line)
|
|
elif re.match(r'Index:\s', line):
|
|
ansi_color(out, 'yellow')
|
|
out.write(line)
|
|
ansi_reset(out)
|
|
out.write('\n')
|
|
else:
|
|
out.write(line)
|
|
out.write('\n')
|
|
return RET_OK
|
|
|
|
def update(argv, svn, out):
|
|
pout = Popen([svn] + argv, stdout=PIPE).stdout
|
|
filter_update(pout, out)
|
|
return RET_OK
|
|
|
|
def status(argv, svn, out):
|
|
external = ''
|
|
external_printed = True
|
|
something_printed = False
|
|
pout = Popen([svn] + argv, stdout=PIPE).stdout
|
|
for line in iter(pout.readline, ''):
|
|
line = line.rstrip()
|
|
m = re.match(r"Performing status on external item at '(.*)':", line)
|
|
if m is not None:
|
|
external = m.group(1)
|
|
external_printed = False
|
|
continue
|
|
if re.match(r'\s*$', line):
|
|
continue
|
|
|
|
# anything not matched yet will cause an external to be shown
|
|
if not external_printed:
|
|
if something_printed:
|
|
out.write('\n')
|
|
out.write("External '%s':\n" % external)
|
|
external_printed = True
|
|
if re.match(STATUS_LINE_REGEX, line):
|
|
action = line[0]
|
|
prop_action = line[1]
|
|
if action == 'A':
|
|
ansi_color(out, 'green')
|
|
elif action == 'M':
|
|
ansi_color(out, 'cyan')
|
|
elif action == 'C':
|
|
ansi_color(out, 'yellow')
|
|
elif action == 'D':
|
|
ansi_color(out, 'red')
|
|
elif action == 'R':
|
|
ansi_color(out, 'magenta')
|
|
elif action == ' ' and prop_action == 'M':
|
|
ansi_color(out, 'cyan')
|
|
elif action == 'X':
|
|
continue # don't print externals
|
|
out.write(line)
|
|
ansi_reset(out)
|
|
out.write('\n')
|
|
something_printed = True
|
|
continue
|
|
out.write(line)
|
|
out.write('\n')
|
|
something_printed = True
|
|
return RET_OK
|
|
|
|
def externals(argv, svn, out):
|
|
pout = Popen([svn, 'status'], stdout=PIPE).stdout
|
|
for line in iter(pout.readline, ''):
|
|
if re.match(STATUS_LINE_REGEX, line):
|
|
if line[0] == 'X':
|
|
out.write(line[8:])
|
|
return RET_OK
|
|
|
|
def stash(argv, svn, out):
|
|
action = 'save'
|
|
if len(argv) >= 2:
|
|
if not argv[1].startswith('-'):
|
|
action = argv[1]
|
|
if action == 'save':
|
|
owd = os.getcwd()
|
|
wc_dir = get_svn_wc_root(svn)
|
|
os.chdir(wc_dir)
|
|
stash_idx = get_next_stash_idx(svn)
|
|
stash_fname = get_stash_fname(svn, stash_idx)
|
|
fh = open(stash_fname, 'w')
|
|
proc = Popen([svn, 'diff'], stdout=PIPE)
|
|
wrote_something = False
|
|
found_binary_file = False
|
|
n_insertions = 0
|
|
n_deletions = 0
|
|
for line in iter(proc.stdout.readline, ''):
|
|
if re.match(r'Cannot.display..file.marked.as.a.binary.type',
|
|
line, flags=re.I):
|
|
found_binary_file = True
|
|
if line.startswith('-') and not line.startswith('---'):
|
|
n_deletions += 1
|
|
if line.startswith('+') and not line.startswith('+++'):
|
|
n_insertions += 1
|
|
fh.write(line)
|
|
wrote_something = True
|
|
proc.wait()
|
|
if found_binary_file:
|
|
out.write('Error: cannot stash with changes to binary files\n')
|
|
fh.close()
|
|
os.unlink(stash_fname)
|
|
elif not wrote_something:
|
|
out.write('Error: no changes to stash!\n')
|
|
fh.close()
|
|
os.unlink(stash_fname)
|
|
else:
|
|
# the stash is good, now revert the working copy changes
|
|
status_lines = Popen([svn, 'status', '--ignore-externals'],
|
|
stdout=PIPE).communicate()[0].split('\n')
|
|
files_changed = {}
|
|
for line in reversed(status_lines):
|
|
m = re.match(STATUS_LINE_REGEX, line)
|
|
if m is not None:
|
|
target = m.group(1)
|
|
action = line[0]
|
|
prop_action = line[1]
|
|
if (action in ('A', 'M', 'D')
|
|
or prop_action == 'M'):
|
|
if action != ' ':
|
|
files_changed[target] = action
|
|
else:
|
|
files_changed[target] = prop_action
|
|
Popen([svn, 'revert', target], stdout=PIPE).wait()
|
|
if action == 'A':
|
|
# a file was added, so to stash it we must remove
|
|
# it in addition to reverting the add
|
|
if os.path.isfile(target):
|
|
os.unlink(target)
|
|
elif os.path.isdir(target):
|
|
if len(os.listdir(target)) == 0:
|
|
os.rmdir(target)
|
|
else:
|
|
raise ValueError('unhandled target type')
|
|
# write stash info
|
|
if len(files_changed) == 1:
|
|
fname = files_changed.keys()[0]
|
|
fh.write('#info: %s: %s\n' % (files_changed[fname], fname))
|
|
else:
|
|
num_actions = {'A': 0, 'M': 0, 'D': 0}
|
|
for k in files_changed:
|
|
if files_changed[k] in num_actions:
|
|
num_actions[files_changed[k]] += 1
|
|
for a in num_actions:
|
|
if num_actions[a] > 0:
|
|
fh.write('#info: %s: %d\n' % (a, num_actions[a]))
|
|
if n_deletions > 0:
|
|
fh.write('#info: -%d\n' % n_deletions)
|
|
if n_insertions > 0:
|
|
fh.write('#info: +%d\n' % n_insertions)
|
|
now = datetime.datetime.now()
|
|
fh.write('#info: @%04d-%02d-%02d %02d:%02d\n' %
|
|
(now.year, now.month, now.day, now.hour, now.minute))
|
|
fh.close()
|
|
out.write('Created stash %d\n' % stash_idx)
|
|
os.chdir(owd)
|
|
elif action == 'list':
|
|
stash_ids = get_stash_ids(svn)
|
|
for si in reversed(stash_ids):
|
|
ins_text = ''
|
|
del_text = ''
|
|
add_text = ''
|
|
modify_text = ''
|
|
delete_text = ''
|
|
date = ''
|
|
stash_fname = get_stash_fname(svn, si)
|
|
fh = open(stash_fname, 'r')
|
|
for line in iter(fh.readline, ''):
|
|
m = re.match(r'#info: (.*)$', line)
|
|
if m is not None:
|
|
info = m.group(1)
|
|
if info.startswith('A:'):
|
|
add_text = info
|
|
elif info.startswith('M:'):
|
|
modify_text = info
|
|
elif info.startswith('D:'):
|
|
delete_text = info
|
|
elif info.startswith('-'):
|
|
del_text = info
|
|
elif info.startswith('+'):
|
|
ins_text = info
|
|
elif info.startswith('@'):
|
|
date = info[1:]
|
|
fh.close()
|
|
out.write('%-3d' % si)
|
|
elements = [
|
|
(date, 'cyan'),
|
|
(add_text, 'green'),
|
|
(modify_text, 'yellow'),
|
|
(delete_text, 'red'),
|
|
]
|
|
for elem, color in elements:
|
|
if elem != '':
|
|
out.write(' ')
|
|
ansi_color(out, color)
|
|
out.write(elem)
|
|
ansi_reset(out)
|
|
if del_text != '' or ins_text != '':
|
|
out.write(' (')
|
|
if del_text != '':
|
|
ansi_color(out, 'red')
|
|
out.write(del_text)
|
|
ansi_reset(out)
|
|
if ins_text != '':
|
|
if del_text != '':
|
|
out.write(' ')
|
|
ansi_color(out, 'green')
|
|
out.write(ins_text)
|
|
ansi_reset(out)
|
|
out.write(')')
|
|
out.write('\n')
|
|
elif action == 'pop':
|
|
owd = os.getcwd()
|
|
wc_dir = get_svn_wc_root(svn)
|
|
os.chdir(wc_dir)
|
|
stash_ids = get_stash_ids(svn)
|
|
if len(stash_ids) > 0:
|
|
stash_idx = stash_ids[-1]
|
|
if len(argv) >= 3:
|
|
stash_idx = int(argv[2])
|
|
stash_fname = get_stash_fname(svn, stash_idx)
|
|
p = Popen([svn, 'patch', stash_fname], stdout=PIPE)
|
|
filter_update(p.stdout, out)
|
|
rc = p.wait()
|
|
if rc == 0:
|
|
os.unlink(stash_fname)
|
|
out.write('Popped stash %d\n' % stash_idx)
|
|
else:
|
|
out.write('Error popping stash %d\n' % stash_idx)
|
|
else:
|
|
out.write('No stashes to pop\n')
|
|
os.chdir(owd)
|
|
elif action == 'show':
|
|
stash_ids = get_stash_ids(svn)
|
|
if len(stash_ids) > 0:
|
|
stash_id = stash_ids[-1]
|
|
if len(argv) >= 3:
|
|
stash_id = int(argv[2])
|
|
if stash_id in stash_ids:
|
|
stash_fname = get_stash_fname(svn, stash_id)
|
|
fd = open(stash_fname, 'r')
|
|
for line in iter(fd.readline, ''):
|
|
colordiff(out, line)
|
|
fd.close()
|
|
else:
|
|
out.write('Invalid stash ID\n')
|
|
else:
|
|
out.write('No stashes to show\n')
|
|
elif action == 'drop':
|
|
stash_ids = get_stash_ids(svn)
|
|
if len(stash_ids) > 0:
|
|
stash_id = stash_ids[-1]
|
|
if len(argv) >= 3:
|
|
stash_id = int(argv[2])
|
|
stash_fname = get_stash_fname(svn, stash_id)
|
|
os.unlink(stash_fname)
|
|
out.write('Dropped stash %d\n' % stash_id)
|
|
else:
|
|
out.write('No stashes to drop\n')
|
|
else:
|
|
out.write('Unknown action "%s"\n' % action)
|
|
return RET_OK
|
|
|
|
def root(argv, svn, out):
|
|
out.write(get_svn_root_url(svn) + '\n')
|
|
return RET_OK
|
|
|
|
def url(argv, svn, out):
|
|
out.write(get_svn_url(svn) + '\n')
|
|
return RET_OK
|
|
|
|
###########################################################################
|
|
# Main #
|
|
###########################################################################
|
|
def do_cmd(argv, realsvn, config, expand=True):
|
|
global using_color
|
|
|
|
if len(argv) == 0:
|
|
Popen([realsvn]).wait()
|
|
return
|
|
|
|
if expand and (argv[0] in config['aliases']):
|
|
# expand aliases
|
|
orig_subcommand = argv[0]
|
|
alias = config['aliases'][argv[0]]
|
|
if hasattr(alias, '__call__'):
|
|
# alias is a python function, call it
|
|
alias(argv)
|
|
return
|
|
elif type(alias) == types.StringType:
|
|
argv = [alias] + argv[1:]
|
|
elif type(alias) == types.ListType:
|
|
argv = alias + argv[1:]
|
|
else:
|
|
sys.stderr.write('Unsupported type for alias "%s"\n' % alias)
|
|
|
|
# after expanding the alias, check if it is an external
|
|
# command to launch
|
|
if argv[0].startswith('!'):
|
|
# execute an external program
|
|
argv[0] = argv[0][1:] # strip leading '!'
|
|
argv = [argv[0], orig_subcommand] + argv[1:]
|
|
Popen(argv, shell=True).wait()
|
|
return
|
|
|
|
# after processing user aliases, apply default Subversion aliases
|
|
svn_aliases = {
|
|
'praise': 'blame',
|
|
'annotate': 'blame',
|
|
'ann': 'blame',
|
|
'cl': 'changelist',
|
|
'co': 'checkout',
|
|
'ci': 'commit',
|
|
'cp': 'copy',
|
|
'del': 'delete',
|
|
'remove': 'delete',
|
|
'rm': 'delete',
|
|
'di': 'diff',
|
|
'?': 'help',
|
|
'h': 'help',
|
|
'ls': 'list',
|
|
'mv': 'move',
|
|
'rename': 'move',
|
|
'ren': 'move',
|
|
'pdel': 'propdel',
|
|
'pd': 'propdel',
|
|
'pedit': 'propedit',
|
|
'pe': 'propedit',
|
|
'pget': 'propget',
|
|
'pg': 'propget',
|
|
'plist': 'proplist',
|
|
'pl': 'proplist',
|
|
'pset': 'propset',
|
|
'ps': 'propset',
|
|
'stat': 'status',
|
|
'st': 'status',
|
|
'sw': 'switch',
|
|
'up': 'update',
|
|
}
|
|
if argv[0] in svn_aliases:
|
|
argv[0] = svn_aliases[argv[0]]
|
|
|
|
out = sys.stdout
|
|
using_pager = False
|
|
using_color = sys.stdout.isatty() and config['use_color']
|
|
if sys.stdout.isatty() and config['use_pager']:
|
|
if (len(argv) >= 1 and argv[0] in
|
|
('blame', 'cat', 'diff', 'help', 'list', 'log',
|
|
'propget', 'proplist')):
|
|
if config['pager'] != '':
|
|
pager = config['pager']
|
|
elif 'PAGER' in os.environ and os.environ['PAGER'] != '':
|
|
pager = os.environ['PAGER']
|
|
else:
|
|
pager = 'less -FRX'
|
|
pager_proc = Popen(pager, shell=True, stdin=PIPE)
|
|
out = pager_proc.stdin
|
|
using_pager = True
|
|
|
|
if realsvn == '':
|
|
sys.stderr.write("Error: 'svn' not found in path\n")
|
|
return 1
|
|
|
|
handlers = {
|
|
'add': add,
|
|
'bisect': bisect,
|
|
'branch': branch,
|
|
'externals': externals,
|
|
'switch': switch,
|
|
'merge': merge,
|
|
'tag': tag,
|
|
'diff': diff,
|
|
'log': log,
|
|
'root': root,
|
|
'update': update,
|
|
'url' : url,
|
|
'watch-lock': watch_lock,
|
|
'users': users,
|
|
'binaries': binaries,
|
|
'lockable': lockable,
|
|
'status': status,
|
|
'stash': stash,
|
|
}
|
|
|
|
do_native_exec = True
|
|
if argv[0] in handlers:
|
|
r = handlers[argv[0]](argv, realsvn, out)
|
|
if r == RET_OK or r == RET_ERR:
|
|
do_native_exec = False
|
|
elif argv[0].startswith('__'):
|
|
# allow double-underscore commands to execute the native
|
|
# subversion command (e.g. "__st")
|
|
argv[0] = argv[0][2:]
|
|
|
|
if do_native_exec:
|
|
Popen([realsvn] + argv, stdout=out).wait()
|
|
|
|
if using_pager:
|
|
out.close()
|
|
pager_proc.wait()
|
|
|
|
def main(argv):
|
|
realsvn = find_in_path('svn')
|
|
config = get_config(realsvn)
|
|
if config['svn']:
|
|
realsvn = config['svn']
|
|
|
|
# set up execution environment for user-defined function aliases
|
|
def do(cmd, expand=True):
|
|
if type(cmd) == types.StringType:
|
|
cmd = [cmd]
|
|
do_cmd(cmd, realsvn, config, expand)
|
|
config['do'] = do
|
|
config['Popen'] = Popen
|
|
config['PIPE'] = PIPE
|
|
|
|
do_cmd(argv, realsvn, config)
|
|
|
|
return 0
|
|
|
|
if __name__ == "__main__":
|
|
rc = 0
|
|
try:
|
|
rc = main(sys.argv[1:])
|
|
except IOError:
|
|
pass
|
|
sys.exit(rc)
|