Last active
December 15, 2015 22:50
-
-
Save lyda/5336178 to your computer and use it in GitHub Desktop.
A simple script to automate shell history file merges.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
""" | |
historymerge: Merges a shell history file. | |
If you keep your shell history files in your hg repo, this script can be | |
useful for merging changes from various machines. Obviously you should | |
*never* check such things into public repos. This is for private repos | |
only (keep them on Dropbox or a code hoster that allows private repos - | |
and use two-factor auth or ssh keys to access). | |
To use this, add the following to your ~/.hgrc: | |
[merge-tools] | |
historymerge.priority = 100 | |
historymerge.executable = ~/bin/historymerge | |
historymerge.args = $local $other $output | |
[merge-patterns] | |
.bash_history = historymerge | |
and then place this script in ~/bin/historymerge | |
""" | |
local_file = open(sys.argv[1], 'r') | |
other_file = open(sys.argv[2], 'r') | |
output_file = open(sys.argv[3], 'w') | |
local_iter = iter(local_file) | |
other_iter = iter(other_file) | |
try: | |
for local_line in local_iter: | |
# This can cause a StopIteration | |
other_line = other_iter.next() | |
if local_line == other_line: | |
# Both files are the same here, print the line and move to next. | |
output_file.write(other_line) | |
else: | |
# The files have diverged. Print other_file lines until one matches | |
# the next local_file line. | |
output_file.write(local_line) | |
output_file.write(other_line) | |
# This can cause a StopIteration | |
local_line = local_iter.next() | |
for other_line in other_iter: | |
if local_line == other_line: | |
output_file.write(local_line) | |
break | |
else: | |
output_file.write(other_line) | |
output_file.write(local_line) | |
except StopIteration: | |
# One of the files is exhausted. Exit loop. | |
pass | |
# One of the files might still have lines. Try and print from both of them. | |
for other_line in other_iter: | |
output_file.write(other_line) | |
for local_line in local_iter: | |
output_file.write(local_line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment