Skip to content

Instantly share code, notes, and snippets.

@csivanich
Last active September 30, 2022 22:45
Show Gist options
  • Save csivanich/3844c0be16945c6ecb81b4e17e799470 to your computer and use it in GitHub Desktop.
Save csivanich/3844c0be16945c6ecb81b4e17e799470 to your computer and use it in GitHub Desktop.
m.py

M

  1. Put m.py in your path somewhere
  2. Add m.sh to your bashrc or similar
  3. Run with m [+-]mark
#!/usr/bin/env python
from sys import argv
from os import environ
import yaml
"""
A VIM-inspired filesystem mark setter
Allows adding/removing/reading marks from a persisted file
Returns 0 if mark successfully looked up and printed to stdout
Returns 1 if error
Returns 2 if mark successfully added/removed and printed to stdout
Generally, this is written with a wrapping shell-script in mind.
RC should tell it which behavior to do, and stdout provides the data.
"""
HOME = environ["HOME"]
MARK_FILE = f"{HOME}/.m"
marks = {}
def usage():
print("USAGE: m [[+-]mark]")
def read_marks():
global marks
try:
with open(MARK_FILE, "r") as f:
marks = yaml.load(f, Loader=yaml.Loader)
except FileNotFoundError:
marks = {}
return marks
def save_marks():
with open(MARK_FILE, "w") as f:
f.write(yaml.dump(marks))
def delete(mark):
return marks.pop(mark, None)
def add(mark):
pwd = environ["PWD"]
marks[mark] = pwd
return pwd
if __name__ == "__main__":
name = argv[1] if argv[1:] else None
read_marks()
if name is None:
print(yaml.dump(marks))
exit(2)
if name == "--help":
usage()
exit(2)
if name.startswith("-"):
print(delete(name[1:]))
save_marks()
exit(2)
if name.startswith("+"):
print(add(name[1:]))
save_marks()
exit(0)
result = marks.get(name, None)
if result is None:
print(f"mark {name} not set")
exit(1)
else:
print(result)
exit(0)
#!/usr/bin/env bash
m () {
out=$(m.py "$@")
case $? in
(0) pushd $out ;;
(2) echo $out ;;
(*) echo "ERROR: $out" ;;
esac
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment