munyal-client/munyal/dir_to_json.py

54 lines
1.5 KiB
Python
Raw Permalink Normal View History

2019-07-28 16:18:49 +00:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
2019-11-27 23:24:04 +00:00
import os
from hashlib import md5
2020-12-19 22:48:55 +00:00
from munyal.misc import path_join
2019-07-28 16:18:49 +00:00
def md5sum(filename):
try:
hash = md5()
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(128 * hash.block_size), b""):
hash.update(chunk)
return hash.hexdigest()
2019-11-27 23:24:04 +00:00
except Exception:
2019-07-28 16:18:49 +00:00
return None
2019-11-27 23:24:04 +00:00
2019-07-28 16:18:49 +00:00
def get_json(path):
out = []
items = os.listdir(path)
try:
for item in items:
if item[0] != "." and not item.endswith("tmp"):
2019-11-27 23:24:04 +00:00
item_json = {"name": item}
2020-12-09 03:37:51 +00:00
route = path_join(path, item)
2019-07-28 16:18:49 +00:00
if os.path.isdir(route):
item_json["is_file"] = False
item_json["content"] = get_json(route)
elif os.path.isfile(route):
item_json["is_file"] = True
item_json["size"] = os.path.getsize(route)
item_json["last_modified"] = os.path.getmtime(route)
item_json["created_at"] = os.path.getctime(route)
checksum = md5sum(route)
if checksum:
item_json["checksum"] = checksum
else:
item = None
2019-11-27 23:24:04 +00:00
else:
continue
2019-07-28 16:18:49 +00:00
out.append(item_json)
2019-11-27 23:24:04 +00:00
except Exception:
2019-07-28 16:18:49 +00:00
return get_json(path)
return out
2019-11-27 23:24:04 +00:00
2019-07-28 16:18:49 +00:00
if __name__ == "__main__":
2020-12-08 20:45:42 +00:00
import sys
output = get_json(sys.argv[1])
2019-07-28 16:18:49 +00:00
print(json.dumps(output, indent=4))