Skip to content

Instantly share code, notes, and snippets.

@jceloria
Last active July 6, 2021 13:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jceloria/6d655ddaa2fe0807e5fe45cd7582614a to your computer and use it in GitHub Desktop.
Save jceloria/6d655ddaa2fe0807e5fe45cd7582614a to your computer and use it in GitHub Desktop.
write down time stamped notes from the command line
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------------------------------------------- #
"""
Write Down, take quick notes from the command line
The MIT License (MIT)
Copyright © 2019 by John Celoria.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
# -------------------------------------------------------------------------------------------------------------------- #
# Library imports
from datetime import datetime
from pathlib import Path
import argparse
import os
import re
import sys
try:
import yaml
import texteditor
except ImportError as e:
print('try: pip install pyyaml texteditor', file=sys.stderr)
sys.exit(-1)
# -------------------------------------------------------------------------------------------------------------------- #
# Set some defaults
__author__ = 'John Celoria'
__version__ = '0.14'
WD_STORAGE = os.environ.get('WD_STORAGE', Path('~/.writedown').expanduser())
# -------------------------------------------------------------------------------------------------------------------- #
class Color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
class YAMLStore(object):
def __init__(self, filename):
self.filename = filename
def str_presenter(self, dumper, data):
# check for multiline strings
if len(data.splitlines()) == 1 and data[-1] == '\n':
return dumper.represent_scalar(
'tag:yaml.org,2002:str', data, style='>')
if len(data.splitlines()) > 1:
return dumper.represent_scalar(
'tag:yaml.org,2002:str', data, style='|')
return dumper.represent_scalar(
'tag:yaml.org,2002:str', data.strip())
def load(self):
if os.path.exists(self.filename):
try:
with open(self.filename) as f:
data = yaml.safe_load(f)
except Exception as e:
print(e, file=sys.stderr)
raise SystemExit(99)
else:
data = []
return data
def dump(self, data):
yaml.add_representer(str, self.str_presenter)
return yaml.dump(data, indent=2, explicit_start=True, allow_unicode=True)
def write(self, data):
Path(os.path.dirname(self.filename)).mkdir(parents=True, exist_ok=True)
with open(self.filename, 'w') as f:
f.write(self.dump(data))
return
# -------------------------------------------------------------------------------------------------------------------- #
def to_time(epoch):
try:
return datetime.fromtimestamp(int(epoch)).strftime('%Y%m%d %H:%M')
except Exception as e:
print(e, file=sys.stderr)
raise SystemExit(88)
def menu(opts):
while True:
action_list(opts)
try:
select = int(input('>> ')) - 1
if select < 0:
raise ValueError
return WD_NOTES[select]
except (ValueError, IndexError):
print(Color.RED + 'Invalid selection!' + Color.END)
pass
def action_list(opts):
if len(WD_NOTES) > 0:
print(Color.UNDERLINE + 'Existing notes:' + Color.END)
for n, i in enumerate(WD_NOTES):
num = n + 1
num = Color.GREEN + str(num) + Color.END
print(' {}) {}'.format(num, i))
else:
print("create a new note and it'll be listed here...")
return
def action_finish(opts):
if len(config.load()) > 0:
active = config.load().get('active')
else:
active = None
if active is not None:
optional = input("Enter an optional note: ")
if optional:
opts['note'] = optional
writedown(opts)
config.write({'active': None})
else:
print("you're not working on anything...")
return
def action_edit(opts):
if len(config.load()) > 0:
active = config.load().get('active')
else:
active = None
if active is None:
if opts['active'] is not None:
active = opts['active']
if opts['active'].isdigit():
try:
active = WD_NOTES[int(opts['active']) - 1]
except Exception:
active = menu(opts)
else:
active = menu(opts)
note = YAMLStore(Path(WD_STORAGE / active))
data = note.load()
epoch = int(datetime.now().strftime('%s'))
yaml_data = texteditor.open(text=note.dump(data), extension='yaml')
try:
edited = yaml.safe_load(yaml_data)
for entry in edited:
entry.setdefault('timestamp', epoch)
except Exception as e:
print(e, file=sys.stderr)
raise SystemExit(99)
else:
if edited != data:
note.write(edited)
return
def action_delete(opts):
if len(config.load()) > 0:
current = config.load().get('active')
else:
current = None
if opts['active'] is not None:
if opts['active'].isdigit():
try:
active = WD_NOTES[int(opts['active']) - 1]
except Exception:
active = menu(opts)
else:
active = opts['active']
elif current is not None:
active = current
else:
active = menu(opts)
note = Path(WD_STORAGE / active)
answer = input("Remove `{}` [y/N]?: ".format(active)).lower()
if re.search(r'^y.*', answer):
try:
note.unlink()
print("{} has been deleted".format(active))
except OSError:
pass
return
def action_report(opts):
if len(config.load()) > 0:
current = config.load().get('active')
else:
current = None
if opts['active'] is not None:
if opts['active'].isdigit():
try:
active = WD_NOTES[int(opts['active']) - 1]
except Exception:
active = menu(opts)
else:
active = opts['active']
elif current is not None:
active = current
else:
active = menu(opts)
note = YAMLStore(Path(WD_STORAGE / active))
data = note.load()
for entry in data:
msg = entry.get('note')
if opts['no_timestamp'] is False:
msg = "{} - {}".format(to_time(entry.get('timestamp')), msg)
print(msg)
return
def action_status(opts):
if len(config.load()) > 0:
active = config.load().get('active')
else:
active = None
if active is not None:
print("active note: {}".format(Color.RED + str(active) + Color.END))
return
def action_change(opts):
if opts['active'] is not None:
active = opts['active']
else:
active = menu(opts)
config.write({'active': active})
return
def writedown(opts):
if len(config.load()) > 0:
active = config.load().get('active')
else:
active = None
if active is None:
active = input("Enter the name of your note: ")
config.write({'active': active})
if type(opts['note']) is list:
opts['note'] = ' '.join(opts['note'])
note = YAMLStore(Path(WD_STORAGE / active))
data = note.load()
entry = {
'timestamp': int(datetime.now().strftime('%s')),
'note': opts['note']
}
data.append(entry)
note.write(data)
return
def parse_args():
p = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter
)
sp = p.add_subparsers(dest='action', metavar='{l,f,e,d,r,s,c,n}')
plist = sp.add_parser('list', aliases=['l'], help='list existing notes')
plist.set_defaults(func=action_list)
pfinish = sp.add_parser('finish', aliases=['f'], help='finish working on active note')
pfinish.set_defaults(func=action_finish)
pedit = sp.add_parser('edit', aliases=['e'], help='edit an existing note')
pedit.add_argument('active', nargs='?')
pedit.set_defaults(func=action_edit)
pdelete = sp.add_parser('delete', aliases=['d'], help='delete an existing note')
pdelete.add_argument('active', nargs='?')
pdelete.set_defaults(func=action_delete)
preport = sp.add_parser('report', aliases=['r'], help='display an existing note')
preport.add_argument('active', nargs='?')
preport.add_argument("--no-timestamp", action="store_true")
preport.set_defaults(func=action_report)
pstatus = sp.add_parser('status', aliases=['s'], help='display current status')
pstatus.set_defaults(func=action_status)
pedit = sp.add_parser('change', aliases=['c'], help='change active note')
pedit.add_argument('active', nargs='?')
pedit.set_defaults(func=action_change)
pnote = sp.add_parser('note', aliases=['n'], help='write down a note')
pnote.add_argument('note', nargs='+')
pnote.set_defaults(func=writedown)
return p.parse_args()
def main():
args = parse_args()
opts = vars(args)
if hasattr(args, 'func'):
args.func(opts)
return
print("try: wd -h")
sys.exit(1)
if __name__ == '__main__':
if not os.path.isdir(WD_STORAGE):
try:
os.mkdir(WD_STORAGE)
except OSError as error:
print(error)
WD_NOTES = sorted([f for f in os.listdir(WD_STORAGE) if not f.startswith('.')], key=str.lower)
config = YAMLStore(str(Path(WD_STORAGE)) + '.yaml')
try:
main()
except KeyboardInterrupt:
print('Interrupted!')
try:
sys.exit(0)
except SystemExit:
os._exit(0)
# -------------------------------------------------------------------------------------------------------------------- #
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment