#!/usr/bin/env python3 import os import sys import re import subprocess import tempfile suffixes = {"sub": ".txt", "note": ".md"} def getItem(num): with open(os.getenv("TODO_FILE"), "r") as todoFile: return todoFile.readlines()[num-1] def getSub(item): if "/:" not in item: return None try: sub = re.findall("[^ ]+/:[.A-Za-z0-9_]+", item)[0] except IndexError: return None return sub.split("/:") def addSub(num, sub, edit=True): with open(os.getenv("TODO_FILE"), "r") as todoFile: lines = todoFile.readlines() print(getSub(lines[num-1])) if getSub(lines[num-1]) is not None and getSub(lines[num-1])[0] == sub: sys.exit("The item already has a sub \"" + sub + "\":" + "\n" + lines[num-1][:-1]) if not os.path.exists(os.path.join(os.getenv("TODO_DIR"), sub)): os.mkdir(os.path.join(os.getenv("TODO_DIR"), sub)) f, name = tempfile.mkstemp(suffixes[sub], "", os.path.join(os.getenv("TODO_DIR"), sub)) lines[num-1] = lines[num-1][:-1] + " " + sub + "/:" + os.path.basename(name) + "\n" with open(os.getenv("TODO_FILE"), "w") as todoFile: todoFile.writelines(lines) if edit: editSub(num) def editSub(num): sub = getSub(getItem(num)) if sub is None: sys.exit("This item does not have a sub") editor = os.getenv("EDITOR") if editor is not None and editor != "": editor = editor.split() else: sys.exit("$EDITOR is unset, cannot edit") subprocess.call(editor + [os.path.join(os.getenv("TODO_DIR"), sub[0], sub[1])]) def showSub(item, indent=0, color=True): sub = getSub(item) if sub is None: sys.exit("This item does not have a sub") command = ["todo.sh", "listfile", os.path.join(sub[0], sub[1])] if not color: command.insert(1, "-p") p = subprocess.Popen(command, stdout=subprocess.PIPE) output = p.communicate()[0].decode("utf-8") output = '\n'.join(" "*indent + i for i in output.splitlines()[:-2]) + "\n" return output def showAll(out=sys.stdout, color=True): command = ["todo.sh", "list"] if not color: command.insert(1, "-p") p = subprocess.Popen(command, stdout=subprocess.PIPE) lines = p.communicate()[0].decode("utf-8").splitlines() for line in lines: out.write(line + "\n") if getSub(line) is not None: out.write(showSub(line, indent=2, color=color)) def main(argv): if(argv[1] == "usage"): print(" sub") print(" list subs") print(" sub add [itemNum] [sub]") print(" add a sub [sub] to [itemNum]") print(" sub edit [itemNum]") print(" edit the sub in [itemNum]") elif len(argv) < 3: showAll() elif argv[2] == "add": if len(argv) != 5: sys.exit("Usage: " + argv[1] + " add [itemNum] [sub]") itemNum = int(argv[3]) addSub(itemNum, argv[4]) elif argv[2] == "edit": if len(argv) != 4: sys.exit("Usage: " + argv[1] + " edit [itemNum]") itemNum = int(argv[3]) editSub(itemNum) else: sys.exit("Command not recognized") if __name__ == '__main__': main(sys.argv)