Projet

Général

Profil

Demande #2795 » merge.py

Loïc Dachary, 02/10/2019 13:41

 
import collections
import copy
import os
from shutil import copyfile
import re
import sys

def read_vcard(path):
lines = collections.OrderedDict()
content = ''
for line in open(path).readlines():
if line.startswith(' '):
content = content[:-1] + line[1:]
else:
if content:
lines[key] = content
content = line
key = re.match(r'.*?:', line).group(0)
if content:
lines[key] = content
return lines

def merge(p1, p2, p3):
v1 = read_vcard(p1)
v2 = read_vcard(p2)
v3 = copy.deepcopy(v1)
for k, v in v2.items():
if k not in v1:
# add new fields regardless
sys.stdout.write(f' ADD {v}')
v3[k] = v
continue
# ; and whitespaces are not significant, remove them for comparison purposes
a1 = re.sub('[;\W]+', '', v1[k].strip())
a2 = re.sub('[;\W]+', '', v.strip())
if len(a2) > len(a1) and a2.startswith(a1):
# always prefer the longer field
sys.stdout.write(f' LONGEST {v1[k].strip()} => {v}')
v3[k] = v1[k]
elif v != v1[k] and a1.lower() == a2.lower():
# ignore differences that are not significant
print(f' WHITESPACE/SEMICOLON/CASE {k}')
elif v != v1[k]:
sys.stdout.write(f' DIFFERENCE\n USE {v1[k]} NOT {v}')
open(p3, 'w').write(''.join(v3.values()))
d1 = sys.argv[1]
d2 = sys.argv[2]
d3 = sys.argv[3]

for f in os.listdir(d1):
if not os.path.exists(f'{d2}/{f}'):
copyfile(f'{d1}/{f}', f'{d3}/{f}')
print(f'COPYING {d1}/{f}')
else:
print(f'MERGING {f}')
merge(f'{d1}/{f}', f'{d2}/{f}', f'{d3}/{f}')

for f in os.listdir(d2):
if not os.path.exists(f'{d1}/{f}'):
copyfile(f'{d2}/{f}', f'{d3}/{f}')
print(f'COPYING {d2}/{f}')
(1-1/2)