Skip to content

Instantly share code, notes, and snippets.

@jaredyam
Last active November 6, 2020 08:59
Show Gist options
  • Save jaredyam/7da912ceaf31f9e9887166fcaeffe9e9 to your computer and use it in GitHub Desktop.
Save jaredyam/7da912ceaf31f9e9887166fcaeffe9e9 to your computer and use it in GitHub Desktop.
Create the target directory tree structure based on an indent-aligned text file.
#!/usr/bin/env python3
"""Create the target directory tree structure based on an indent-aligned text file.
Usage
-----
python mktree.py tree[.txt]
Test demo
-----------------
$ cat tree
---------------------------------
# This is a comment line
parent
children # Ha, I'm a comment
test1
test2
another-one
test3
test4
file.py
test5
---------------------------------
$ [python] ./mktree.py tree
Notes
-----
The default accepted indent width is four spaces or a tab.
"""
from pathlib import Path
import re
import sys
def mktree(file):
tree = []
depth_upperbound = -1
lines = open(file, 'r').readlines()
for line in lines:
matched = re.search('^ *', line)
num_spaces = len(matched.group(0))
depth = int(num_spaces // 4)
basename = line.strip()
if depth == depth_upperbound + 1:
tree.append([])
depth_upperbound = depth
# Handle the comment line case
basename = basename.split('#')[0]
if basename: # Ignore if it's a comment line
basename = Path(basename.strip())
tree[depth].append(basename)
while depth:
basename = Path(f'{tree[depth - 1][-1]}/{basename}')
depth -= 1
print(basename)
if basename.suffix:
basename.touch()
else:
basename.mkdir(exist_ok=True)
print(tree)
if __name__ == '__main__':
file = sys.argv[1]
mktree(file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment