Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import dircache, os, re, shutil
- dir1 = 'english/'
- dir2 = 'icelandic/'
- dest = 'merged/'
- # Stole this class from here: http://stackoverflow.com/questions/1165352/fast-comparison-between-two-python-dictionary
- class DictDiffer(object):
- """
- Calculate the difference between two dictionaries as:
- (1) items added
- (2) items removed
- (3) keys same in both but changed values
- (4) keys same in both and unchanged values
- """
- def __init__(self, current_dict, past_dict):
- self.current_dict, self.past_dict = current_dict, past_dict
- self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys())
- self.intersect = self.set_current.intersection(self.set_past)
- def added(self):
- return self.set_current - self.intersect
- def removed(self):
- return self.set_past - self.intersect
- def changed(self):
- return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])
- def unchanged(self):
- return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o])
- # Gets lines from translation files and creates a dict
- def getLines(file):
- fh = open(file, 'r')
- lines = {}
- for l in fh.readlines():
- if l[:1] != '$':
- continue
- try:
- v = re.match("\$_\['(.*)'\].* '(.*?)';", l).groups()
- lines[v[0]] = v[1]
- except:
- continue
- fh.close()
- return lines
- # Merge the contents of the files and return. file2 items will prevail if items exist in both files.
- def mergeFiles(file1, file2):
- lines1, lines2 = getLines(file1), getLines(file2)
- merged = dict(lines1.items() + lines2.items())
- dd = DictDiffer(lines1, lines2)
- # Remove lines that are no longer in the new translation
- for k in dd.removed():
- merged.pop(k)
- if len(dd.added()) > 0:
- print "New lines: %s" % dd.added()
- return merged
- # Creates a new language file
- def writeFile(filename, contents):
- lines = ["<?php\n"]
- for k in contents.keys():
- lines.append("$_['%s'] = '%s';\n" % (k, contents[k]))
- lines.append("?>\n")
- fh = open(filename, 'w')
- fh.writelines(lines)
- fh.close()
- # Duplicate the directory tree
- shutil.copytree(dir1, dest)
- for f in dircache.listdir(dir1):
- if os.path.isdir(dir1+f):
- # Go through subdirectories
- for file in dircache.listdir(dir1 + f):
- filename = str(f) + '/' + str(file)
- print filename
- if not os.path.exists(dir2 + filename):
- # Need to copy dir1 file to dest
- shutil.copyfile(dir1 + filename, dest + filename)
- else:
- # Compare contents (translation strings)
- merged = mergeFiles(dir1 + filename, dir2 + filename)
- writeFile(dest+filename, merged)
- else:
- # Is a file, probably <language>.php in the root folder.
- merged = mergeFiles(dir1 + f, dir2 + dir2[:-1] + '.php')
- writeFile(dest+dir2[:-1] + '.php',merged)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement