Skip to content

Instantly share code, notes, and snippets.

@FusionX9000
Last active August 3, 2023 21:24
Show Gist options
  • Select an option

  • Save FusionX9000/3443081a7e17245882422003a82643a4 to your computer and use it in GitHub Desktop.

Select an option

Save FusionX9000/3443081a7e17245882422003a82643a4 to your computer and use it in GitHub Desktop.
Rclone lsjson to ncdu import file - Export or save rclone ncdu output
#!/usr/bin/env python3
import datetime
import json
from pathlib import Path
import sys
# Exporting rclone lsjson:
# > rclone lsjson -R remote: > rclone-lsjson-dump
try:
with Path(sys.argv[1]).expanduser().open("r") as f:
data = json.load(f)
except:
print("Usage: rclone-ncdu-export.py <rclone-json-file> [ncdu-json-file]")
sys.exit(1)
root_tree_node = {"name": "root", "size": 0, "mtime": 0, "children": {}}
# Converting from flat to tree structure for easy parsing
for row in data:
path_entries = row["Path"].split("/")
tree_node = root_tree_node
for entry in path_entries:
if entry not in tree_node["children"]:
tree_node["children"][entry] = {"children": {}}
tree_node = tree_node["children"][entry]
tree_node.update(
{
"name": path_entries[-1],
"size": max(0, row["Size"]),
"mtime": datetime.datetime.strptime(
row["ModTime"], "%Y-%m-%dT%H:%M:%S%z"
).timestamp(),
}
)
# https://dev.yorhel.nl/ncdu/jsonfmt
def tree_to_ncdu(tree_node):
directory = []
infoblock = {
"name": tree_node["name"],
"asize": tree_node["size"],
"dsize": tree_node["size"],
"mtime": tree_node["mtime"],
}
for child_node in tree_node["children"].values():
directory.append(tree_to_ncdu(child_node))
if directory:
return [infoblock] + directory
else:
return infoblock
ncdu_base = [1, 0, {"progname": "ncdu", "progver": "1.9", "timestamp": 1354477149}]
ncdu = ncdu_base + [tree_to_ncdu(root_tree_node)]
# Importing to ncdu
# > python3 rclone-lsjon-to-ncdu.py rclone-lsjson-dump
# > ncdu --apparent-size -ef rclone-ls-json-dump
if len(sys.argv) == 3:
with Path(sys.argv[2]).open("w") as f:
json.dump(ncdu, f)
else:
print(json.dumps(ncdu))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment