Skip to content

Instantly share code, notes, and snippets.

@jlecour
Last active July 25, 2023 15:01
Show Gist options
  • Save jlecour/9ac7d7d3705a022c72133c20ae433ac5 to your computer and use it in GitHub Desktop.
Save jlecour/9ac7d7d3705a022c72133c20ae433ac5 to your computer and use it in GitHub Desktop.
A script to transform a filesystem tree into a JSON structure, a little like an inverse procfs/sysfs.
#!/bin/env python
import sys
import os
import json
def clean_lines(lines):
clean_lines=[]
# TODO: a map/reduce or a comprehension might be better
for line in lines:
# remove linebreaks
# TODO: see if a proper regex is needed
clean_line = line.replace("\n","")
# don't return empty lines
if len(clean_line) > 0:
clean_lines.append(clean_line)
return clean_lines
def read_entry(path):
f = open(path,"r")
lines = clean_lines(f.readlines())
if len(lines) > 1:
# return multiple lines as array
return lines
else:
# return single lines as string
return lines[0]
def build_dict(dir):
data = {}
for path in os.listdir(dir):
if os.path.isfile(os.path.join(dir, path)):
# if entry is a file, the value is the content of the file
data[path] = read_entry(os.path.join(dir, path))
elif os.path.isdir(os.path.join(dir, path)):
# is entry is a directory, add recursively
data[path] = build_dict(os.path.join(dir, path))
return data
def main():
if len(sys.argv) > 1:
basedir = sys.argv[1]
else:
print("You must provide a base directory", file=sys.stderr)
sys.exit(2)
if os.path.isdir(basedir):
data = build_dict(basedir)
print(json.dumps(data, sort_keys=True))
sys.exit(0)
else:
print("Directory "+basedir+" not found", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
sys.exit(0)
{
"client_hostname": "foo.example.com",
"client_number": "FOOBAR",
"dir1": {
"dir2": {
"baz": [
"1",
"2",
"3",
"4",
"5"
],
"foo-ln": "bar"
},
"foo": "bar"
},
"dir3": {
"hook_db": "0",
"mail": "foo@example.com"
},
"monitoring": "everytime"
}
├── client_hostname
├── client_number
├── dir1
│   ├── dir2
│   │   ├── baz
│   │   └── foo-ln -> ../foo
│   └── foo
├── dir3
│   ├── hook_db
│   └── mail
└── monitoring
@jlecour
Copy link
Author

jlecour commented Jul 25, 2023

This can be used as-is, but the final intent is tu use this in combination with Ansible local facts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment