Created
January 27, 2015 10:04
-
-
Save Vostbur/6fddb02bd46dd9270a7a to your computer and use it in GitHub Desktop.
Generate json with changes in WebDAV folder (or other folder)
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 | |
#################### | |
# Generate json with changes in WebDAV folder (or other folder) | |
# | |
# used some code from: http://thomassileo.com/blog/2013/12/12/tracking-changes-in-directories-with-python/ | |
# tested with python 2.7 | |
# | |
# edit crontab: sudo crontab -e | |
# example: */1 * * * * /path-to-script/main.py | |
# check permissions /var/www/html/index.html | |
#################### | |
import os | |
import hashlib | |
import json | |
def json_load(fname): | |
with open(fname, mode='r') as f: | |
data = json.load(f) | |
return data | |
def json_save(fname, data): | |
with open(fname, mode='w') as f: | |
json.dump(data, f) | |
def compute_dir_index(path): | |
files = [] | |
subdirs = [] | |
for root, dirs, filenames in os.walk(path): | |
for subdir in dirs: | |
subdirs.append(os.path.relpath(os.path.join(root,subdir), path)) | |
for f in filenames: | |
files.append(os.path.relpath(os.path.join(root, f), path)) | |
index = {} | |
for f in files: | |
index[f] = os.path.getmtime(os.path.join(path, files[0])) | |
return dict(files=files, subdirs=subdirs, index=index) | |
def compute_diff(dir_base, dir_cmp): | |
data = {} | |
data['deleted'] = list(set(dir_cmp['files']) - set(dir_base['files'])) | |
data['created'] = list(set(dir_base['files']) - set(dir_cmp['files'])) | |
data['updated'] = [] | |
data['deleted_dirs'] = list(set(dir_cmp['subdirs']) - set(dir_base['subdirs'])) | |
for f in set(dir_cmp['files']).intersection(set(dir_base['files'])): | |
if dir_base['index'][f] != dir_cmp['index'][f]: | |
data['updated'].append(f) | |
return data | |
if __name__ == "__main__": | |
path = '/var/www/webdav/' | |
fname = '/var/www/html/index.html' | |
diff = compute_dir_index(path) | |
if os.path.exists(fname): | |
if os.path.isfile(fname): | |
diff2 = json_load(fname) | |
from pprint import pprint | |
pprint(compute_diff(diff, diff2)) | |
json_save(fname, diff) | |
else: | |
raise ValueError("%s isn't a file!" % fname) | |
else: | |
json_save(fname, diff) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment