Skip to content

Instantly share code, notes, and snippets.

@csivanich
Last active September 30, 2022 22:45

Revisions

  1. csivanich renamed this gist Sep 30, 2022. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. csivanich created this gist Sep 30, 2022.
    85 changes: 85 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,85 @@
    #!/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)
    6 changes: 6 additions & 0 deletions m.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    M
    ======

    1) Put `m.py` in your path somewhere
    2) Add `m.sh` to your bashrc or similar
    3) Run with `m [+-]mark`
    10 changes: 10 additions & 0 deletions m.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    #!/usr/bin/env bash

    m () {
    out=$(m.py "$@")
    case $? in
    (0) pushd $out ;;
    (2) echo $out ;;
    (*) echo "ERROR: $out" ;;
    esac
    }