Skip to content

Instantly share code, notes, and snippets.

@u2takey
Created January 9, 2019 05:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save u2takey/7427907c21660373f221789abe5d248c to your computer and use it in GitHub Desktop.
Save u2takey/7427907c21660373f221789abe5d248c to your computer and use it in GitHub Desktop.
#!env python
# -*- coding: utf-8 -*-
import os
import collections
import argparse
from pathlib import Path
class Node:
def __init__(self):
self.count, self.key = 0, ""
self.children = collections.defaultdict(Node)
def collect(file, root):
isZshHistory = True if "zsh" in file else False
with open(file, 'rb') as f:
for line in f:
try:
line = line.decode()
if isZshHistory:
index = line.strip().find(";")
line = line[index+1:]
l = line.split()
node = root
node.count += 1
for i in range(min(4, len(l))):
node = node.children[l[i]]
node.key = " ".join(l[:i+1])
node.count += 1
except Exception as e:
continue
def printNode(node, root, maxl, level):
if node == root:
print(('{0: <' + str(maxl) + "}").format("TOTAL " + str(root.count))[:maxl], "="*100)
sortedChildren = sorted(node.children.values(), key=lambda x:x.count, reverse = True)
for child in sortedChildren:
if child.count/root.count > 0.01:
l = " "*level + " " + child.key + " " + str(child.count)
l = ('{0: <' + str(maxl) + "}").format(l)[:maxl]
print(l, "="*int(child.count/root.count*100))
printNode(child, root, maxl, level+1)
if __name__ == '__main__':
# params
parser = argparse.ArgumentParser(description='analyze command history.')
parser.add_argument('--history-file', action="store", dest="historyFile", default=str(Path.home())+"/.zsh_history")
args = parser.parse_args()
root = Node()
collect(args.historyFile, root)
printNode(root, root, 40, 0)
@u2takey
Copy link
Author

u2takey commented Jan 9, 2019

image

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