Compare commits

..

No commits in common. "master" and "v1.4" have entirely different histories.
master ... v1.4

2 changed files with 267 additions and 707 deletions

99
README
View File

@ -27,31 +27,11 @@ Implemented subcommands:
- bad mark the current revision as bad - containing the change sought - bad mark the current revision as bad - containing the change sought
- good mark the current revision as good - older than 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 - reset terminate the bisect operation and return to the original revision
branch[es] branch[es] [-d] [-s] [<branch_name>]
- branch: list branches with '*' by the current one - with no arguments, list branches with '*' by the current one
- branch -d name: delete branch <name> - with -d, delete <branch>
- branch [-s] name [source[@rev]]: create branch <name> - otherwise, create a new branch from the current one
- if <source> is given it is resolved as a reference name (can be 'trunk',
or a tag or branch name)
- if <source> is not given the HEAD of the current working-copy URL is used.
- also switch to the new branch if -s is given - also switch to the new branch if -s is given
checkout [options] [url] [wc_path]
- if a URL is given that ends with /trunk and no working copy path is given,
then the last directory component before "/trunk" is used as the working
copy path
clean [-x] {-n|-f} [path...]
- remove (or list) unversioned items
options:
-x, --ignore-ignores
- remove/list unversioned items that are ignored by Subversion
-n, --dry-run
- perform a dry-run, i.e. list files that would be removed but do not
actually remove them
-f, --force
- perform the actual removal of unversioned files
commit
- removes trailing whitespace (including end-of-line characters) from commit
messages before committing if neither -m nor -F arguments are given
diff diff
- allow specifying ref1..ref2 syntax to show the diff between two references - allow specifying ref1..ref2 syntax to show the diff between two references
- references can be tag names, branch names, or 'trunk' - references can be tag names, branch names, or 'trunk'
@ -69,57 +49,43 @@ Implemented subcommands:
merge <branch> merge <branch>
- merge branch <branch> into the current WC path - merge branch <branch> into the current WC path
- falls back to Subversion "merge" if <branch> doesn't exist - falls back to Subversion "merge" if <branch> doesn't exist
revert <path[s]>
- revert all affected files under given target path(s)
root root
- output root URL (for use on shell such as "svn log $(svn root)/tags") - output root URL (for use on shell such as "svn log $(svn root)/tags")
stash [options] [file...] stash [command]
- allow temporarily saving changes to the working copy without committing - allow temporarily saving changes to the working copy without committing
- the stashes behaves as a "stack" where stashing pushes a new stash object - the stashes behaves as a "stack" where "save" pushes a new stash object
and popping removes the newest one from the top of the stack and "pop" pops the newest one from the top of the stack
- binary files are ignored (a warning is printed) and not stashed commands:
options: save [-k] (default if not specified):
-e, --externals - save changes as a "stash" object
- also stash changes in externals (if no explicit targets given) - revert changes from working copy unless -k (keep working copy) given
- this option is implicitly on if the configuration value - this only works with text files, not binary files
'stash_externals' is set to True list:
--noexternals
- reverse --externals (or the configuration value 'stash_externals')
-k, --keep
- create the stash object, but keep the changes locally as well
- with --pop, do not remove the stash object after reapplying it
-p, --patch
- interactively prompt for whether to stash each hunk
--list
- show a list of all stash objects - show a list of all stash objects
--pop [id] pop [-k] [id]:
- apply the stash object <id> back to the working copy - apply the stash object <id> back to the working copy
- the stash object is removed unless -k (keep) given - the stash object is removed unless -k (keep) given
- <id> defaults to the newest stash object created - <id> defaults to the newest stash object created
--show [id] show [id]:
- display the diff stored in stash with ID <id> - display the diff stored in stash with ID <id>
- <id> defaults to the newest stash object created - <id> defaults to the newest stash object created
--drop [id] drop [id]:
- delete stash object <id> - delete stash object <id>
- <id> defaults to the newest stash object created - <id> defaults to the newest stash object created
- if none of --list, --pop, --show, or --drop is given, a new stash object
is created containing the chosen differences
- if file is given, only the changes from the listed files will be stashed
switch <short_name> switch <short_name>
- switch to 'trunk', branch name, or tag name without having to specify - switch to 'trunk', branch name, or tag name without having to specify
the full URL the full URL
- falls back to Subversion "switch" if <short_name> doesn't exist - falls back to Subversion "switch" if <short_name> doesn't exist
tag[s] tag[s]
- tag [-v]: list tags - tag: list tags
- with -v (verbose), lists tag origin and creation date - tag -d <name>: delete tag <name>
- tag -d name: delete tag <name> - tag -m <old> <new>: rename tag <old> to <new>
- tag -m old new: rename tag <old> to <new> - tag <name> [source_ref[@rev]]: create tag <name>; if source_ref is given
- tag name [source[@rev]]: create tag <name> it is resolved as a reference name (can be 'trunk', or another tag or a
- if <source> is given it is resolved as a reference name (can be 'trunk', branch name); if source is not given the HEAD of the current working-
or another tag or a branch name) copy URL is used
- if <source> is not given the HEAD of the current working-copy URL is used. url
url [file] - output repository URL of current working directory
- output repository URL of file [default: '.' (current working directory)]
users users
- show a list of contributing users to a SVN path - show a list of contributing users to a SVN path
watch-lock watch-lock
@ -172,10 +138,6 @@ Available configuration variables:
for newly added files which should not automatically have the for newly added files which should not automatically have the
svn:executable property added for them even if the files are svn:executable property added for them even if the files are
executable. The default value is ['.c', '.cc', '.h', '.txt']. executable. The default value is ['.c', '.cc', '.h', '.txt'].
ignore_symlinks: True or False to hide unversioned symlinks from appearing
in status output (default: False)
stash_externals: True or False to enable/disable whether '-e' is implicitly
on for 'stash' subcommand. Defaults to False.
Configuration Examples: Configuration Examples:
pager = 'less -FRXi' # enable case-insensitive searching in less pager = 'less -FRXi' # enable case-insensitive searching in less
@ -191,17 +153,6 @@ Configuration Examples:
Author: Josh Holtrop Author: Josh Holtrop
History: History:
v1.7 - 2013-08-16
- add "clean" subcommand handler
- bugfix: revert subcommand handler: revert deleted items
v1.6 - 2013-07-24
- rework 'stash' subcommand to operate on individual hunks
- add 'revert' subcommand handler
v1.5 - 2012-11-08
- add -v (verbose) flag to 'tag' subcommand
- allow optional source argument to 'branch' subcommand
- remove repository prefix URL from diff --summarize output
- Add .exe extension to svn binary name if platform is Windows (not cygwin)
v1.4 - 2012-08-23 v1.4 - 2012-08-23
- allow optional source/revision argument when creating a tag - allow optional source/revision argument when creating a tag
- handle ctrl+c better when interacting with a pager - handle ctrl+c better when interacting with a pager

633
jsvn
View File

@ -1,4 +1,4 @@
#!/usr/bin/env python2 #!/usr/bin/env python
# Josh's SVN wrapper script # Josh's SVN wrapper script
# #
@ -15,12 +15,8 @@ import datetime
import types import types
import getopt import getopt
import signal import signal
import platform
import tempfile
import shutil
STATUS_LINE_REGEX = r'[ACDIMRX?!~ ][CM ][L ][+ ][SX ][KOTB ]..(.+)' STATUS_LINE_REGEX = r'[ACDIMRX?!~ ][CM ][L ][+ ][SX ][KOTB ]..(.+)'
COMMIT_IGNORE_LINE = "--This line, and those below, will be ignored--"
########################################################################### ###########################################################################
# Subcommand Handler Return Values # # Subcommand Handler Return Values #
@ -69,15 +65,13 @@ def get_config(svn):
'pager': '', 'pager': '',
'use_pager': True, 'use_pager': True,
'use_color': True, 'use_color': True,
'ignore_symlinks': False,
'aliases': { 'aliases': {
# default jsvn aliases # default jsvn aliases
'tags': 'tag', 'tags': 'tag',
'branches': 'branch'}, 'branches': 'branch'},
'svn': '', 'svn': '',
'ignore_executable_extensions': 'ignore_executable_extensions':
['.c', '.cc', '.h', '.txt'], ['.c', '.cc', '.h', '.txt']
'stash_externals': False,
} }
global_user_config_fname = os.path.expanduser('~/.jsvn') global_user_config_fname = os.path.expanduser('~/.jsvn')
@ -96,7 +90,7 @@ class LogEntry(object):
self.revision = 0 self.revision = 0
self.user = '' self.user = ''
self.date = '' self.date = ''
self.lines_text = '' self.lines = ''
self.message_lines = 0 self.message_lines = 0
self.changed_paths = [] self.changed_paths = []
self.message = [] self.message = []
@ -403,7 +397,7 @@ def filter_update(pout, out):
continue continue
if re.match(r'\s*$', line): if re.match(r'\s*$', line):
continue continue
if re.match(r'(External at|Updated external to) revision ', line): if re.match(r'External at revision ', line):
if external_printed: if external_printed:
out.write(line) out.write(line)
continue continue
@ -412,9 +406,6 @@ def filter_update(pout, out):
out.write('\n') out.write('\n')
out.write(line) out.write(line)
continue continue
if re.match(r'^Removed external ', line):
out.write(line)
continue
# anything not matched yet will cause an external to be shown # anything not matched yet will cause an external to be shown
if not external_printed: if not external_printed:
@ -463,19 +454,16 @@ def filter_status(line, out):
ansi_reset(out) ansi_reset(out)
out.write('\n') out.write('\n')
def get_unknowns(svn, config): def get_unknowns(svn):
unknowns = [] unknowns = []
pout = Popen([svn, 'status'], stdout=PIPE).stdout pout = Popen([svn, 'status'], stdout=PIPE).stdout
for line in iter(pout.readline, ''): for line in iter(pout.readline, ''):
m = re.match(r'\? (.*)$', line) m = re.match(r'\? (.*)$', line)
if m is not None: if m is not None:
if not (config['ignore_symlinks'] and os.path.islink(m.group(1))):
unknowns.append(m.group(1)) unknowns.append(m.group(1))
return unknowns return unknowns
def descendant_path(child, parent): def descendant_path(child, parent):
if parent == '.':
parent = os.getcwd()
if child[0] != '/' and parent[0] == '/': if child[0] != '/' and parent[0] == '/':
child = os.getcwd() + '/' + child child = os.getcwd() + '/' + child
elif child[0] == '/' and parent[0] != '/': elif child[0] == '/' and parent[0] != '/':
@ -546,10 +534,7 @@ def find_branched_revision(svn, branch_url, branch_path, base_path):
new_path, old_path, rev = m.group(1, 2, 3) new_path, old_path, rev = m.group(1, 2, 3)
if new_path == search_path: if new_path == search_path:
if old_path == base_path: if old_path == base_path:
try:
p.kill() p.kill()
except OSError:
pass
return (int(rev), old_path) return (int(rev), old_path)
search_path = old_path search_path = old_path
return (-1, '') return (-1, '')
@ -572,21 +557,6 @@ def filter_add_output(fh, out, svn, config):
out.write(line) out.write(line)
out.write('\n') out.write('\n')
def relpath(path):
cwdprefix = os.getcwd() + '/'
if path.startswith(cwdprefix):
return path[len(cwdprefix):]
return path
def get_editor():
if 'EDITOR' in os.environ and os.environ['EDITOR'] != '':
return os.environ['EDITOR']
for p_ent in os.environ['PATH'].split(':'):
editor_path = os.path.join(p_ent, 'editor')
if os.path.isfile(editor_path):
return editor_path
return 'vim'
########################################################################### ###########################################################################
# Subcommand Handlers # # Subcommand Handlers #
########################################################################### ###########################################################################
@ -604,7 +574,7 @@ def add_h(argv, svn, out, config):
# for each target specified, check if there are unversioned items # for each target specified, check if there are unversioned items
# underneath it (for directories) and add them as well # underneath it (for directories) and add them as well
# if none are found, fall back to the native svn add # if none are found, fall back to the native svn add
unknowns = get_unknowns(svn, config) unknowns = get_unknowns(svn)
for path in argv: for path in argv:
if path == '.': if path == '.':
path = os.getcwd() path = os.getcwd()
@ -708,9 +678,6 @@ Operations:
update_h(['update', '-r%d' % rev], svn, out, config) update_h(['update', '-r%d' % rev], svn, out, config)
return RET_OK return RET_OK
# branch # list branches
# branch -d name # delete branch <name>
# branch [-s] name [source[@rev]] # create branch <name> [from <source> [at revision <rev>]]
def branch_h(argv, svn, out, config): def branch_h(argv, svn, out, config):
argv = argv[1:] # strip 'branch' command argv = argv[1:] # strip 'branch' command
options, args = getopt.getopt(argv, 'ds') options, args = getopt.getopt(argv, 'ds')
@ -719,19 +686,7 @@ def branch_h(argv, svn, out, config):
if origin == '' or root == '': if origin == '' or root == '':
sys.stderr.write("Could not determine origin/root URL\n") sys.stderr.write("Could not determine origin/root URL\n")
return RET_ERR return RET_ERR
do_switch = False if len(options) == 0 and len(args) == 0:
for opt, val in options:
if opt == '-d':
# delete branch
if len(args) < 1:
sys.stderr.write('Must supply branch name\n')
return RET_ERR
Popen([svn, 'rm', root + '/branches/' + args[0], '-m',
"Removed branch '%s'" % args[0]], stdout=out).wait()
return RET_OK
elif opt == '-s':
do_switch = True
if len(args) == 0:
bl = ['trunk'] + get_svn_branch_list(svn) bl = ['trunk'] + get_svn_branch_list(svn)
current = origin.split('/')[-1] current = origin.split('/')[-1]
bl.sort() bl.sort()
@ -746,27 +701,26 @@ def branch_h(argv, svn, out, config):
ansi_reset(out) ansi_reset(out)
out.write('\n') out.write('\n')
return RET_OK return RET_OK
if len(args) == 0:
sys.stderr.write('Error: must supply branch name\n')
return RET_ERR
branch_name = args[0] branch_name = args[0]
do_switch = False
for opt, val in options:
if opt == '-d':
# delete branch
Popen([svn, 'rm', root + '/branches/' + branch_name, '-m',
"Removed branch '%s'" % branch_name], stdout=out).wait()
return RET_OK
elif opt == '-s':
do_switch = True
bl = get_svn_branch_list(svn) bl = get_svn_branch_list(svn)
if branch_name in bl: if branch_name in bl:
sys.stderr.write('Error: branch %s already exists\n' % branch_name) sys.stderr.write('Error: branch %s already exists\n' % branch_name)
return RET_ERR return RET_ERR
comment = "Created '%s' branch" % branch_name comment = "Created '%s' branch" % branch_name
branch_path = root + '/branches/' + branch_name branch_path = root + '/branches/' + branch_name
branch_source = origin Popen([svn, 'copy', origin, branch_path, '-m', comment], stdout=out).wait()
if len(args) >= 2:
source = args[1]
m = re.match(r'(.*?)(@\d+)?$', source)
if m is not None:
ref_name, rev_str = m.group(1, 2)
url, path = resolve_reference(svn, ref_name)
if url != '':
branch_source = url
if rev_str is not None:
branch_source += rev_str
else:
branch_source = source
Popen([svn, 'copy', branch_source, branch_path, '-m', comment], stdout=out).wait()
if do_switch: if do_switch:
return switch_h(['switch', branch_name], svn, out, config) return switch_h(['switch', branch_name], svn, out, config)
return RET_OK return RET_OK
@ -777,10 +731,9 @@ def branch_h(argv, svn, out, config):
# tag name [source[@rev]] # create tag <name> [from source [at revision rev]] # tag name [source[@rev]] # create tag <name> [from source [at revision rev]]
def tag_h(argv, svn, out, config): def tag_h(argv, svn, out, config):
argv = argv[1:] # strip command argv = argv[1:] # strip command
options, args = getopt.getopt(argv, 'dmv') options, args = getopt.getopt(argv, 'dm')
origin = get_svn_top_level(svn) origin = get_svn_top_level(svn)
root = get_svn_root_url(svn) root = get_svn_root_url(svn)
verbose = False
if origin == '' or root == '': if origin == '' or root == '':
sys.stderr.write("Could not determine origin/root URL\n") sys.stderr.write("Could not determine origin/root URL\n")
return RET_ERR return RET_ERR
@ -811,50 +764,13 @@ def tag_h(argv, svn, out, config):
'-m', "Renamed tag '%s' to '%s'" % (old_tag_name, tag_name)], '-m', "Renamed tag '%s' to '%s'" % (old_tag_name, tag_name)],
stdout=out).wait() stdout=out).wait()
return RET_OK return RET_OK
elif opt == '-v':
verbose = True
else: else:
sys.stderr.write('Unrecognized option to "tag" command\n') sys.stderr.write('Unrecognized option to "tag" command\n')
return RET_ERR return RET_ERR
if len(args) == 0: if len(args) == 0:
tag_list.sort() tag_list.sort()
max_tagname_length = 0
if verbose:
for t in tag_list: for t in tag_list:
if len(t) > max_tagname_length: out.write(t + '\n')
max_tagname_length = len(t)
for t in tag_list:
if verbose:
out.write(('%%-%ds' % max_tagname_length) % t)
date = ''
origin = ''
rev = ''
pout = Popen([svn, 'log', '-v', '--stop-on-copy', '%s/tags/%s' % (root, t)],
stdout=PIPE).stdout
for line in iter(pout.readline, ''):
m = re.match(r'r\d+\s*\|[^|]+\|\s*(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})', line)
if m is not None:
date = m.group(1)
m = re.match(r'\s\s\sA\s.*\/tags\/%s\s\(from\s(.*):(\d+)' % t, line)
if m is not None:
origin = re.sub(r'.*\/(trunk|tags|branches)\b', r'\1', m.group(1))
rev = m.group(2)
if date != '':
out.write(' ')
ansi_color(out, 'magenta')
out.write(date)
ansi_reset(out)
if origin != '':
out.write(' ')
ansi_color(out, 'yellow')
out.write(origin)
ansi_reset(out)
ansi_color(out, 'blue', bold=True)
out.write('@' + rev)
ansi_reset(out)
else:
out.write(t)
out.write('\n')
return RET_OK return RET_OK
tag_name = args[0] tag_name = args[0]
if tag_name in tag_list: if tag_name in tag_list:
@ -1073,10 +989,8 @@ def diff_h(argv, svn, out, config):
argv = argv[:i] + [url1, url2] + argv[i + 1:] argv = argv[:i] + [url1, url2] + argv[i + 1:]
break break
pout = Popen([svn] + argv, stdout=PIPE).stdout pout = Popen([svn] + argv, stdout=PIPE).stdout
root_url = get_svn_root_url(svn)
for line in iter(pout.readline, ''): for line in iter(pout.readline, ''):
if doing_summarize: if doing_summarize:
line = line.replace(root_url, '')
filter_status(line, out) filter_status(line, out)
else: else:
colordiff(out, line) colordiff(out, line)
@ -1153,9 +1067,6 @@ def log_h(argv, svn, out, config):
if match != target: if match != target:
return False return False
return True return True
if pretty not in ("default", "oneline"):
sys.stderr.write("Error: unknown --pretty option: '%s'\n" % pretty)
return RET_ERR
pout = Popen([svn] + argv, stdout=PIPE).stdout pout = Popen([svn] + argv, stdout=PIPE).stdout
while True: while True:
le = LogEntry(pout) le = LogEntry(pout)
@ -1196,15 +1107,12 @@ def status_h(argv, svn, out, config):
continue continue
# look for lines that should be ignored # look for lines that should be ignored
m = re.match(STATUS_LINE_REGEX, line) if re.match(STATUS_LINE_REGEX, line):
if m is not None:
action = line[0] action = line[0]
if action == 'X': if action == 'X':
continue # don't print directory externals continue # don't print directory externals
elif line.startswith(' X '): elif line.startswith(' X '):
continue # don't print unmodified file externals continue # don't print unmodified file externals
elif action == '?' and config['ignore_symlinks'] and os.path.islink(m.group(1)):
continue
# anything not matched yet will cause an external to be shown # anything not matched yet will cause an external to be shown
if not external_printed: if not external_printed:
@ -1213,14 +1121,6 @@ def status_h(argv, svn, out, config):
out.write("External '%s':\n" % external) out.write("External '%s':\n" % external)
external_printed = True external_printed = True
# trim working directory from paths in externals
if external != '':
m = re.match(STATUS_LINE_REGEX, line)
if m is not None:
path = m.group(1)
if path.startswith(os.getcwd() + os.sep):
line = line[:8] + path[len(os.getcwd() + os.sep):]
# look for lines to highlight # look for lines to highlight
if re.match(STATUS_LINE_REGEX, line): if re.match(STATUS_LINE_REGEX, line):
filter_status(line, out) filter_status(line, out)
@ -1239,251 +1139,103 @@ def externals_h(argv, svn, out, config):
out.write(line[8:]) out.write(line[8:])
return RET_OK return RET_OK
def revert_h(argv, svn, out, config): def stash_h(argv, svn, out, config):
argv = argv[1:] # strip off command argv = argv[1:] # strip 'stash' command
if len(argv) == 0: action = 'save'
# do not handle if no targets are passed if len(argv) >= 1:
return RET_REEXEC if not argv[0].startswith('-'):
if len(filter(lambda x: x.startswith('-'), argv)) != 0: action = argv[0]
# do not handle if any options are passed argv = argv[1:]
Popen([svn, 'revert'] + argv).wait() # now argv only contains options/arguments to the stash subcommand itself
return RET_OK if action == 'save':
did_something = False keep_wc = False
for i, target in enumerate(argv): options, args = getopt.getopt(argv, 'k')
if target.endswith('/'): for opt, val in options:
argv[i] = target[:-1] if opt == '-k':
p = Popen([svn, 'status'], stdout=PIPE) keep_wc = True
modified_files = []
for line in iter(p.stdout.readline, ''):
m = re.match(STATUS_LINE_REGEX, line)
if m is not None:
action = line[0]
prop_action = line[1]
if action in ('A', 'M', 'C', 'D', '!') or prop_action == 'M':
fname = m.group(1)
if action in ('D', '!'):
modified_files.append((action, fname))
else:
modified_files.insert(0, (action, fname))
for action, fname in modified_files:
for target in argv:
if fname.startswith(os.getcwd() + os.sep):
fname = fname[len(os.getcwd() + os.sep):]
if target == '.' or target == fname or fname.startswith(target + os.sep):
cmd = [svn, "revert"]
if action == 'A':
cmd += ["--depth", "infinity"]
cmd.append(fname)
Popen(cmd).wait()
did_something = True
break
return RET_OK if did_something else RET_REEXEC
def get_svn_contents_to_stash(targets, svn, out, keep, patch, externals):
s_fd, s_fname = tempfile.mkstemp(prefix = 'svn.stash.')
r_fd, r_fname = tempfile.mkstemp(prefix = 'svn.stash.')
os.close(s_fd)
os.close(r_fd)
s_fh = open(s_fname, 'w')
r_fh = open(r_fname, 'w')
external_list = []
directories_added = []
status_cmd = [svn, 'status']
if not externals:
status_cmd += ['--ignore-externals']
status_proc = Popen(status_cmd, stdout=PIPE)
for line in iter(status_proc.stdout.readline, ''):
m = re.match(r"Performing status on external item at '(.*)':", line)
if m is not None:
external_list.append(m.group(1))
m = re.match(STATUS_LINE_REGEX, line)
if m is not None:
path = m.group(1)
if line[0] == 'A':
if os.path.isdir(path):
directories_added.append(relpath(path))
if externals and len(targets) == 0:
targets = ['.'] + external_list
svars = {
'revert_list': [],
'skip_all': not patch,
'skip_file': True,
'answer': 'y',
'index_header': '',
'hunk_buildup': '',
'index_fname': '',
'prompted_for_index': False,
'quit': False,
'wrote_index_sf': False,
'wrote_index_rf': False,
'binary_file': False,
'n_insertions': 0,
'n_deletions': 0,
}
def update_answer():
if not patch:
svars['answer'] = 'y'
return
if svars['skip_file'] or svars['skip_all']:
return
if not svars['prompted_for_index']:
for line in svars['index_header'].rstrip().split('\n'):
colordiff(out, line)
svars['prompted_for_index'] = True
for li in svars['hunk_buildup'].rstrip().split('\n'):
colordiff(out, li)
answer = ''
answers = ('y', 'n', 'yf', 'nf', 'ya', 'na', 'q', '?')
while answer not in answers:
ansi_color(out, 'magenta', bold=True)
out.write('Stash this hunk (%s)? ' % ','.join(answers))
ansi_reset(out)
answer = sys.stdin.readline().rstrip().lower()
if answer == '?':
out.write('''y: yes, stash this hunk
n: no, do not stash this hunk
yf: yes, and stash every hunk from the rest of this file
nf: no, and do not stash any hunk from the rest of this file
ya: yes, and stash every remaining hunk
na: no, and do not stash any remaining hunks
q: quit and abort stash
?: show this help
''')
answer = ''
if answer == 'q':
svars['quit'] = True
elif answer[1:] == 'a':
svars['skip_all'] = True
elif answer[1:] == 'f':
svars['skip_file'] = True
svars['answer'] = answer[:1]
def flush_hunk():
if svars['hunk_buildup'] != '':
update_answer()
if svars['answer'] == 'y':
if not svars['wrote_index_sf']:
s_fh.write(svars['index_header'])
svars['wrote_index_sf'] = True
s_fh.write(svars['hunk_buildup'])
elif svars['answer'] == 'n':
if not svars['wrote_index_rf']:
r_fh.write(svars['index_header'])
svars['wrote_index_rf'] = True
r_fh.write(svars['hunk_buildup'])
svars['hunk_buildup'] = ''
def flush_file(new_file_name):
if svars['binary_file']:
ansi_color(out, 'yellow', bold=True)
out.write('Warning: not stashing binary file %s' % svars['index_fname'])
ansi_reset(out)
out.write('\n')
else:
flush_hunk()
if svars['wrote_index_sf']:
svars['revert_list'].append(svars['index_fname'])
svars['skip_file'] = False
svars['hunk_buildup'] = ''
svars['index_fname'] = new_file_name
svars['binary_file'] = False
svars['wrote_index_sf'] = False
svars['wrote_index_rf'] = False
svars['prompted_for_index'] = False
diff_proc = Popen([svn, 'diff'] + targets, stdout=PIPE)
for line in iter(diff_proc.stdout.readline, ''):
m = re.match(r'Index: (.*)', line)
if m is not None:
flush_file(m.group(1))
svars['index_header'] = line
elif (re.match(r'=+$', line) or
re.match(r'--- ', line) or
re.match(r'\+\+\+ ', line)):
svars['index_header'] += line
elif (re.match(r'@@ ', line) or re.match(r'Property.changes.on:', line)):
flush_hunk()
svars['hunk_buildup'] = line
elif re.match(r'Cannot display: file.marked.as.a.binary.type', line):
svars['binary_file'] = True
else:
svars['hunk_buildup'] += line
if line.startswith('+'):
svars['n_insertions'] += 1
elif line.startswith('-'):
svars['n_deletions'] += 1
if svars['quit']:
break
if not svars['quit']:
flush_file('')
for da in directories_added:
stash_da = len(targets) == 0
for t in targets:
if descendant_path(da, t):
stash_da = True
break
if stash_da:
s_fh.write('#dir: %s\n' % da)
if not da in svars['revert_list']:
svars['revert_list'].append(da)
s_fh.close()
r_fh.close()
if svars['quit']:
svars['revert_list'] = []
return s_fname, r_fname, svars['revert_list'], svars['n_insertions'], svars['n_deletions'], directories_added
def stash_save_h(args, svn, out, config, keep, patch, externals):
owd = os.getcwd() owd = os.getcwd()
wc_dir = get_svn_wc_root(svn) wc_dir = get_svn_wc_root(svn)
os.chdir(wc_dir) os.chdir(wc_dir)
s_fname, r_fname, revert_list, n_insertions, n_deletions, directories_added = \
get_svn_contents_to_stash(args, svn, out, keep, patch, externals)
if len(revert_list) == 0:
out.write('No changes stashed.\n')
else:
if not keep:
for rf in reversed(revert_list):
Popen([svn, 'revert', rf], stdout=PIPE).wait()
if rf in directories_added and len(os.listdir(rf)) == 0:
os.rmdir(rf)
if r_fname != '':
Popen([svn, 'patch', r_fname], stdout=PIPE).wait()
if s_fname != '':
stash_idx = get_next_stash_idx(svn) stash_idx = get_next_stash_idx(svn)
stash_fname = get_stash_fname(svn, stash_idx) stash_fname = get_stash_fname(svn, stash_idx)
stash_fh = open(stash_fname, 'w') fh = open(stash_fname, 'w')
s_fh = open(s_fname, 'r') proc = Popen([svn, 'diff'], stdout=PIPE)
for line in iter(s_fh.readline, ''): wrote_something = False
stash_fh.write(line) found_binary_file = False
s_fh.close() n_insertions = 0
# write stash info n_deletions = 0
if n_deletions > 0: for line in iter(proc.stdout.readline, ''):
stash_fh.write('#info: -%d\n' % n_deletions) if re.match(r'Cannot.display..file.marked.as.a.binary.type',
if n_insertions > 0: line, flags=re.I):
stash_fh.write('#info: +%d\n' % n_insertions) found_binary_file = True
if len(revert_list) == 1: if line.startswith('-') and not line.startswith('---'):
stash_fh.write('#info: F: %s\n' % revert_list[0]) 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: else:
stash_fh.write('#info: F: %d files\n' % len(revert_list)) # 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
if not keep_wc:
# do the actual revert if -k not given
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() now = datetime.datetime.now()
stash_fh.write('#info: @%04d-%02d-%02d %02d:%02d\n' % fh.write('#info: @%04d-%02d-%02d %02d:%02d\n' %
(now.year, now.month, now.day, now.hour, now.minute)) (now.year, now.month, now.day, now.hour, now.minute))
stash_fh.close() fh.close()
out.write('Created stash %d\n' % stash_idx) out.write('Created stash %d\n' % stash_idx)
if s_fname != '':
os.unlink(s_fname)
if r_fname != '':
os.unlink(r_fname)
os.chdir(owd) os.chdir(owd)
return RET_OK elif action == 'list':
def stash_list_h(argv, svn, out, config):
stash_ids = get_stash_ids(svn) stash_ids = get_stash_ids(svn)
for si in reversed(stash_ids): for si in reversed(stash_ids):
ins_text = '' ins_text = ''
@ -1491,7 +1243,6 @@ def stash_list_h(argv, svn, out, config):
add_text = '' add_text = ''
modify_text = '' modify_text = ''
delete_text = '' delete_text = ''
summary_text = ''
date = '' date = ''
stash_fname = get_stash_fname(svn, si) stash_fname = get_stash_fname(svn, si)
fh = open(stash_fname, 'r') fh = open(stash_fname, 'r')
@ -1505,8 +1256,6 @@ def stash_list_h(argv, svn, out, config):
modify_text = info modify_text = info
elif info.startswith('D:'): elif info.startswith('D:'):
delete_text = info delete_text = info
elif info.startswith('F:'):
summary_text = info[3:]
elif info.startswith('-'): elif info.startswith('-'):
del_text = info del_text = info
elif info.startswith('+'): elif info.startswith('+'):
@ -1520,7 +1269,6 @@ def stash_list_h(argv, svn, out, config):
(add_text, 'green'), (add_text, 'green'),
(modify_text, 'yellow'), (modify_text, 'yellow'),
(delete_text, 'red'), (delete_text, 'red'),
(summary_text, 'magenta'),
] ]
for elem, color in elements: for elem, color in elements:
if elem != '': if elem != '':
@ -1542,9 +1290,12 @@ def stash_list_h(argv, svn, out, config):
ansi_reset(out) ansi_reset(out)
out.write(')') out.write(')')
out.write('\n') out.write('\n')
return RET_OK elif action == 'pop':
keep = False
def stash_pop_h(args, svn, out, config, keep): options, args = getopt.getopt(argv, 'k')
for opt, val in options:
if opt == '-k':
keep = True
owd = os.getcwd() owd = os.getcwd()
wc_dir = get_svn_wc_root(svn) wc_dir = get_svn_wc_root(svn)
os.chdir(wc_dir) os.chdir(wc_dir)
@ -1554,12 +1305,6 @@ def stash_pop_h(args, svn, out, config, keep):
if len(args) >= 1: if len(args) >= 1:
stash_idx = int(args[0]) stash_idx = int(args[0])
stash_fname = get_stash_fname(svn, stash_idx) stash_fname = get_stash_fname(svn, stash_idx)
fh = open(stash_fname, 'r')
for line in iter(fh.readline, ''):
m = re.match('#dir: (.*)', line)
if m is not None:
Popen([svn, 'mkdir', m.group(1)]).wait()
fh.close()
p = Popen([svn, 'patch', stash_fname], stdout=PIPE) p = Popen([svn, 'patch', stash_fname], stdout=PIPE)
filter_update(p.stdout, out) filter_update(p.stdout, out)
rc = p.wait() rc = p.wait()
@ -1572,9 +1317,7 @@ def stash_pop_h(args, svn, out, config, keep):
else: else:
out.write('No stashes to pop\n') out.write('No stashes to pop\n')
os.chdir(owd) os.chdir(owd)
return RET_OK elif action == 'show':
def stash_show_h(argv, svn, out, config):
stash_ids = get_stash_ids(svn) stash_ids = get_stash_ids(svn)
if len(stash_ids) > 0: if len(stash_ids) > 0:
stash_id = stash_ids[-1] stash_id = stash_ids[-1]
@ -1584,13 +1327,6 @@ def stash_show_h(argv, svn, out, config):
stash_fname = get_stash_fname(svn, stash_id) stash_fname = get_stash_fname(svn, stash_id)
fd = open(stash_fname, 'r') fd = open(stash_fname, 'r')
for line in iter(fd.readline, ''): for line in iter(fd.readline, ''):
m = re.match('#dir: (.*)', line)
if m is not None:
ansi_color(out, 'magenta', bold=True)
out.write('New Directory: %s' % m.group(1))
ansi_reset(out)
out.write('\n')
continue
if not re.match('#info:', line): if not re.match('#info:', line):
colordiff(out, line) colordiff(out, line)
fd.close() fd.close()
@ -1598,9 +1334,7 @@ def stash_show_h(argv, svn, out, config):
out.write('Invalid stash ID\n') out.write('Invalid stash ID\n')
else: else:
out.write('No stashes to show\n') out.write('No stashes to show\n')
return RET_OK elif action == 'drop':
def stash_drop_h(argv, svn, out, config):
stash_ids = get_stash_ids(svn) stash_ids = get_stash_ids(svn)
if len(stash_ids) > 0: if len(stash_ids) > 0:
stash_id = stash_ids[-1] stash_id = stash_ids[-1]
@ -1611,44 +1345,10 @@ def stash_drop_h(argv, svn, out, config):
out.write('Dropped stash %d\n' % stash_id) out.write('Dropped stash %d\n' % stash_id)
else: else:
out.write('No stashes to drop\n') out.write('No stashes to drop\n')
else:
out.write('Unknown action "%s"\n' % action)
return RET_OK return RET_OK
def stash_h(argv, svn, out, config):
argv = argv[1:] # strip 'stash' command
opts, args = getopt.getopt(argv, 'ekp',
['list', 'pop', 'show', 'drop', 'externals', 'noexternals',
'keep', 'patch'])
keep = False
patch = False
externals = config['stash_externals']
operation = 'save'
for opt, arg in opts:
if opt == '--list':
operation = 'list'
elif opt == '--pop':
operation = 'pop'
elif opt == '--show':
operation = 'show'
elif opt == '--drop':
operation = 'drop'
elif opt in ('-k', '--keep'):
keep = True
elif opt in ('-p', '--patch'):
patch = True
elif opt in ('-e', '--externals'):
externals = True
elif opt == '--noexternals':
externals = False
if operation == 'list':
return stash_list_h(args, svn, out, config)
elif operation == 'pop':
return stash_pop_h(args, svn, out, config, keep)
elif operation == 'show':
return stash_show_h(args, svn, out, config)
elif operation == 'drop':
return stash_drop_h(args, svn, out, config)
return stash_save_h(args, svn, out, config, keep, patch, externals)
def root_h(argv, svn, out, config): def root_h(argv, svn, out, config):
out.write(get_svn_root_url(svn) + '\n') out.write(get_svn_root_url(svn) + '\n')
return RET_OK return RET_OK
@ -1660,89 +1360,6 @@ def url_h(argv, svn, out, config):
out.write(get_svn_url(svn, path) + '\n') out.write(get_svn_url(svn, path) + '\n')
return RET_OK return RET_OK
def checkout_h(argv, svn, out, config):
co_url = argv[-1].rstrip('/')
if re.search(r'://.*/trunk$', co_url):
argv += [co_url.split("/")[-2]]
Popen([svn] + argv, stdout=out).wait()
return RET_OK
def clean_h(argv, svn, out, config):
argv = argv[1:] # strip command
opts, args = getopt.getopt(argv, 'fnx',
['force', 'dry-run', 'ignore-ignores'])
force = False
dry_run = False
ignore_ignores = False
for opt, arg in opts:
if opt in ('-f', '--force'):
force = True
elif opt in ('-n', '--dry-run'):
dry_run = True
elif opt in ('-x', '--ignore-ignores'):
ignore_ignores = True
if not force and not dry_run:
sys.stderr.write('Error: specify either -n or -f\n')
return RET_ERR
if force and dry_run:
sys.stderr.write('Error: specify only one of -n or -f\n')
return RET_ERR
status_args = args
if ignore_ignores:
status_args.append('--no-ignore')
clean_paths = []
pout = Popen([svn, 'status'] + status_args, stdout=PIPE).stdout
for line in iter(pout.readline, ''):
m = re.match(STATUS_LINE_REGEX, line)
if m is not None:
action = line[0]
if action in ('?', 'I'):
clean_paths.append(m.group(1))
for cp in clean_paths:
if dry_run:
out.write("Would remove %s\n" % cp)
if force:
if os.path.islink(cp):
os.unlink(cp)
elif os.path.isdir(cp):
shutil.rmtree(cp)
elif os.path.isfile(cp):
os.unlink(cp)
return RET_OK
def commit_h(argv, svn, out, config):
argv = argv[1:] # strip command
for arg in argv:
if re.search(r'^-[Fm]', arg):
# Do not handle the commit if the user supplied a -m or -F.
return RET_REEXEC
commit_file_fd, commit_file_fname = tempfile.mkstemp('.tmp', 'svn-commit')
os.close(commit_file_fd)
commit_file_fh = open(commit_file_fname, 'w')
commit_file_fh.write("\n%s\n\n" % COMMIT_IGNORE_LINE)
pout = Popen([svn, 'status'], stdout=PIPE).stdout
commit_file_fh.write(pout.read())
commit_file_fh.close()
Popen([get_editor(), commit_file_fname]).wait()
commit_file_fh = open(commit_file_fname, 'r')
commit_file_contents = commit_file_fh.read()
commit_file_fh.close()
commit_message = ""
for line in commit_file_contents.splitlines():
if line == COMMIT_IGNORE_LINE:
break
commit_message += line + "\n"
commit_message = commit_message.rstrip()
if commit_message == "":
out.write("Aborting commit due to empty commit message.\n")
else:
commit_file_fh = open(commit_file_fname, 'w')
commit_file_fh.write(commit_message)
commit_file_fh.close()
Popen([svn, 'commit'] + argv + ['-F', commit_file_fname]).wait()
os.unlink(commit_file_fname)
return RET_OK
########################################################################### ###########################################################################
# Main # # Main #
########################################################################### ###########################################################################
@ -1839,9 +1456,6 @@ def do_cmd(argv, realsvn, config, expand=True):
'add': add_h, 'add': add_h,
'bisect': bisect_h, 'bisect': bisect_h,
'branch': branch_h, 'branch': branch_h,
'checkout': checkout_h,
'clean': clean_h,
'commit': commit_h,
'externals': externals_h, 'externals': externals_h,
'switch': switch_h, 'switch': switch_h,
'merge': merge_h, 'merge': merge_h,
@ -1857,7 +1471,6 @@ def do_cmd(argv, realsvn, config, expand=True):
'lockable': lockable_h, 'lockable': lockable_h,
'status': status_h, 'status': status_h,
'stash': stash_h, 'stash': stash_h,
'revert': revert_h,
} }
do_native_exec = True do_native_exec = True
@ -1878,12 +1491,8 @@ def do_cmd(argv, realsvn, config, expand=True):
pager_proc.wait() pager_proc.wait()
def main(argv): def main(argv):
# Determine the name of the real svn binary
svn_bin_name = 'svn'
if platform.system() == 'Windows':
svn_bin_name = 'svn.exe'
signal.signal(signal.SIGINT, signal.SIG_IGN) signal.signal(signal.SIGINT, signal.SIG_IGN)
realsvn = find_in_path( svn_bin_name ) realsvn = find_in_path('svn')
config = get_config(realsvn) config = get_config(realsvn)
if config['svn']: if config['svn']:
realsvn = config['svn'] realsvn = config['svn']