Skip to content

Instantly share code, notes, and snippets.

@HandcartCactus
Last active March 19, 2021 15:34
Show Gist options
  • Save HandcartCactus/3e5878074f52d1e3ad0f7e954a528637 to your computer and use it in GitHub Desktop.
Save HandcartCactus/3e5878074f52d1e3ad0f7e954a528637 to your computer and use it in GitHub Desktop.
Repo to json spec, json spec to repo. Take safe code anywhere you can run python.
import os, json
def tree2dict(abs2rel, rel2dir, exclude_dirs):
"""
abs2rel: absolute path to the relative location ('C:\\User\\MyUsername\\Documents\\')
rel2dir: relative path to the dict to copy ('myproject\\')
exclude_dirs: directories to exclude (['myproject\\.git','myproject\\secretfiles')
"""
os.chdir(abs2rel)
wanted_dir = lambda thisdir, exclude_dirs: not any(p in thisdir for p in exclude_dirs)
dirs = [path for path,_,_, in os.walk(rel2dir) if wanted_dir(path, exclude_dirs)]
fnames = [files for path,_,files in os.walk(rel2dir) if wanted_dir(path, exclude_dirs)]
filecontent = {}
for idx_dir, dir_ in enumerate(dirs):
for f in fnames[idx_dir]:
key = os.path.join(dir_, f)
with open(key, 'r') as thisfile:
filecontent[key] = thisfile.readlines()
return {'dirs':dirs, 'files':filecontent, 'rel':rel2dir}
def dict2txt(fpath, d):
with open(fpath, 'w') as file:
json.dump(d, file)
def txt2dict(fpath):
with open(fpath, 'r') as file:
return json.load(file)
def build_rel(rel):
loc = ''
for p in rel.split('\\')[:-1]:
loc += p
try:
os.mkdir(loc)
except FileExistsError:
pass
def build_dirs(dirs):
for d in dirs:
os.mkdir(d)
def build_files(filecontent):
for fpath, fcontent in filecontent.items():
with open(fpath, 'w') as file:
file.writelines(fcontent)
def dict2tree(d, fpath_write):
dirs = d['dirs']
filecontent = d['files']
rel = d['rel']
os.chdir(fpath_write)
#build_rel(rel)
build_dirs(dirs)
build_files(filecontent)
def packrepo(abs2rel, rel2dir, exclude_dirs, out_fpath):
d = tree2dict(abs2rel, rel2dir, exclude_dirs)
dict2txt(out_fpath, d)
def unpackrepo(input_fpath, output_fpath):
d = txt2dict(input_fpath)
dict2tree(d, output_fpath)
if __name__ == '__main__':
PACK_DIR = "myrepo\\"
packrepo(
abs2rel = "C:\\Users\\me\\Documents\\",
rel2dir = PACK_DIR,
exclude_dirs = [PACK_DIR + '.git', PACK_DIR + '.vscode'],
out_fpath="C:\\Users\\me\\Documents\\myrepospecs.json"
)
unpackrepo(
"C:\\Users\\me\\Documents\\myrepospecs.json",
"C:\\Users\\me\\Documents\\repo-copy\\",
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment