New options added, sync.py almost done
[mydotfiles.git] / sync.py
blob47ea474f026441695aac003beb2b58f141d1c1e6
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """
4 This app performs the synchonization with the system.
6 Python 2.5+
7 """
8 from __future__ import with_statement
9 import os.path
10 import re
11 import filecmp
12 import getopt
13 import sys
14 import shutil
15 import itertools
17 def usage(app_name):
18 """Usage message."""
19 print """Syncpy - synchronization tool by rlazo
21 This system was originally designed to work with data stored on a
22 versioning system, as git. If so _please_ update your copy before
23 doing anything else.
25 %s [option]
26 Options:
27 -h Shows this message
28 -c Diff between files stored and those in use.
29 -u Overrides files in use using those stored. If some files
30 are missing they are created.""" % app_name
32 def diff_files(index):
33 """Check for differences between the actual files and the
34 reference ones. """
35 issues = {'missing' : [], 'diff' : [], 'count' : 0}
36 for value in index:
37 path = os.path.expanduser("~/%s" % value)
38 if not os.path.exists(path):
39 issues['missing'].append(value)
40 elif not filecmp.cmp(path, value, shallow=False):
41 issues['diff'].append(value)
42 issues['count'] = len(issues['missing']) + len(issues['diff'])
43 return issues
45 def load_index(filename="index.txt"):
46 """Load the index file. Lines starting with \# are considered
47 comments.
49 Arguments:
50 - `filename`: index filename (path optional)
51 """
52 index = []
53 with open(filename, 'r') as fd:
54 ignore_regexp = re.compile(r"^ *(#.*| *)$")
55 for line in fd:
56 if ignore_regexp.match(line) is None:
57 index.append(line.replace("\n", ""))
58 return index
60 if __name__ == "__main__":
61 try:
62 opts, args = getopt.getopt(sys.argv[1:], "cuh",[])
63 except getopt.GetoptError, err:
64 print str(err)
65 usage(sys.argv[0])
66 sys.exit(2)
68 file_index = load_index()
69 for o,a in opts:
70 if o == "-c":
71 res = diff_files(file_index)
72 if res["count"] == 0:
73 print "Everything is ok"
74 else:
75 for issue in res['missing']:
76 print "File %s missing." % issue
77 for issue in res['diff']:
78 print "File %s is different." % issue
79 elif o == "-u":
80 ans = str(raw_input("Are you sure you want to override your files?[y/n] "))
81 if ans.find("y") != -1:
82 issues = diff_files(file_index)
83 for dotfile in itertools.chain(issues['missing'], issues['diff']):
84 print "Copying %s ..." % dotfile
85 shutil.copy(dotfile, os.path.expanduser("~/%s" % dotfile))
86 print "Done."
87 elif o == "-s":
88 print "Updating the repo..."
89 issues = diff_files(file_index)
90 for dotfile in issues['diff']:
91 print "Copying %s ..." % dotfile
92 shutil.copy(os.path.expanduser("~/%s" % dotfile), dotfile)
93 print "Done."
94 elif o == "-h":
95 usage(sys.argv[0])
96 else:
97 usage(sys.argv[0])