Skip to content

Instantly share code, notes, and snippets.

@antlauzon
Last active January 11, 2023 04:00
Show Gist options
  • Save antlauzon/57068425f7249d7fd1981899bae80b1f to your computer and use it in GitHub Desktop.
Save antlauzon/57068425f7249d7fd1981899bae80b1f to your computer and use it in GitHub Desktop.
create shortened command aliases based on use frequency
import os
import re
import shutil
import sys
cmd_re = re.compile('(\w+)\s+.*')
if 'zsh' in sys.argv[1]:
cmd_re = re.compile(".*;(\w+)\s+.*")
history= open(sys.argv[1], 'rb').read()
history = history.decode('utf-8', 'ignore')
history=[s.strip() for s in history.split('\n')]
if len(sys.argv) == 3:
cmd_re = re.compile(sys.argv[2])
cmd_freq = {}
for line in history:
m = cmd_re.match(line)
if m:
cmd = os.path.basename(m.group(1)).lower()
cmd_path = shutil.which(cmd)
if cmd_path and os.path.exists(cmd_path):
cmd_freq[cmd] = cmd_freq.get(cmd, 0) + 1
cmd_tuples = sorted([(c, n) for c, n in cmd_freq.items()], key=lambda t: -t[1])
compressed = {}
for cmd_tuple in cmd_tuples:
cmd = cmd_tuple[0]
for i in range(len(cmd)):
compressed_cmd = cmd[:i+1]
if not shutil.which(compressed_cmd) and \
compressed.get(compressed_cmd) is None:
compressed[compressed_cmd] = cmd
break
compressed_tuples = sorted([(c1, c2, len(c1)) for c1, c2 in compressed.items()])
compressed_tuples = sorted(compressed_tuples, key=lambda t: t[2])
[print("alias {}={}".format(c1, c2)) for c1, c2, _ in compressed_tuples]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment