Skip to content

Instantly share code, notes, and snippets.

@sapslaj
Last active July 21, 2022 02:26
Show Gist options
  • Save sapslaj/15dfca529d90066515370ddcc4a2c7fc to your computer and use it in GitHub Desktop.
Save sapslaj/15dfca529d90066515370ddcc4a2c7fc to your computer and use it in GitHub Desktop.
Standalone script to help manage notes
  1. Create git repo mkdir notes && cd notes && git init
  2. Copy note.py (with or without the .py file extension) into git repo
  3. Run ./note --new My First Note to create a new note
  4. Run ./note --save to commit.

Optional steps:

  • Set EDITOR and do ./note --new --open ... to immediate open the new note in your editor
  • Create a private repo on git remote service (e.g. GitHub, GitLab, etc.) and set that as remote origin.
    • This means you can do ./note --save --push to immediately commit and push the new commit to the remote.
  • Observe ./note --help for more quirks and features.
#!/usr/bin/env python3
import argparse
from datetime import date
import time
import os
import re
parser = argparse.ArgumentParser(description="Manage Notes")
parser.add_argument(
"--new",
"-n",
action="store_true",
help="Add new note",
)
parser.add_argument(
"--open",
"-o",
action="store_true",
help="For --new, open file in $EDITOR",
)
parser.add_argument(
"--copy-last",
"-c",
action="store_true",
help="For --new, copy contents from last note with same name"
)
parser.add_argument(
"--date",
"-d",
help="For --new, set date explicitly instead of using today's date"
)
def new(args):
title = ''
slug = str(int(time.time()))
previous = None
if args.rest:
# has title
title = ' '.join(args.rest)
slug = re.sub(r"[!@#$%^&\*\(\)\[\]\{\};:\,\./<>\?\|`~=_+ ]", "-", '-'.join(args.rest).lower())
if slug.startswith("-") or slug.endswith("-"):
try:
slug = re.match(r"^\-*(.*?)\-*$", slug)[1]
except Exception:
pass
if args.copy_last:
previous_files = {}
for dirpath, dirs, files in os.walk("."):
for filename in files:
if slug in filename:
previous_files[filename] = os.path.join(dirpath, filename)
if previous_files:
previous = previous_files[sorted(previous_files.keys())[-1]]
ts = args.date or date.today().strftime("%Y-%m-%d")
filename = f"{ts}-{slug}.md"
if os.path.exists(filename):
reply = input(f"A note at {filename} already exists! Overwrite? [y/N]: ").lower().strip()
if not reply or reply[0] == 'n':
print("Leaving note alone.")
exit(0)
with open(filename, "w") as f:
if args.copy_last and previous:
print(f"Copying contents from last note at {previous}")
with open(previous, "r") as previous_file:
f.write(previous_file.read())
elif title:
f.write(f"# {title}\n")
print(f"created new note at ./{filename}")
if args.open:
editor = os.environ.get("NOTE_EDITOR", os.environ.get("EDITOR", "vi"))
os.system(f"{editor} {filename}")
parser.add_argument(
"--save",
"-s",
action="store_true",
help="Commit and push all changes",
)
parser.add_argument(
"--push",
"-p",
action="store_true",
help="For --save, push changes to git remote origin",
)
def save(args):
os.system("git add -A")
os.system("git rm $(git ls-files --deleted) 2> /dev/null")
message = f'Note Save {date.today().strftime("%Y-%m-%d")}'
if args.rest:
message = ' '.join(args.rest)
os.system(f'git commit --no-verify --no-gpg-sign -m "{message}"')
if args.push:
os.system("git rebase origin")
os.system("git push origin")
parser.add_argument(
"rest",
nargs="*"
)
if __name__ == "__main__":
args = parser.parse_args()
if args.new:
new(args)
elif args.save:
save(args)
else:
parser.exit("You must specify an action. Seek --help.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment