main.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. #!/usr/bin/python3
  2. import asyncio, json, os, sys, tempfile
  3. from datetime import datetime
  4. import time
  5. from tabulate import tabulate
  6. from colorama import Fore, Back, Style
  7. import api, lib.util
  8. # USERNAME = lib.config.get("username", "Anonymous")
  9. USERNAME = "Anonymous"
  10. async def add_task(task_args):
  11. task = {
  12. "title": None,
  13. "tags": [],
  14. "desc": None,
  15. "assign": [],
  16. "project": [],
  17. "due": None,
  18. "rank": None,
  19. "created_at": lib.util.now(),
  20. "state": "open"
  21. }
  22. # Everything that isn't an attribute is part of the title
  23. # Open text editor if desc isn't set to write desc text
  24. title_words = []
  25. for arg in task_args:
  26. if arg[0] == "+":
  27. tag = arg[1:]
  28. if tag in task["tags"]:
  29. print(f"error: duplicate tag +{tag} in task", file=sys.stderr)
  30. sys.exit(-1)
  31. task["tags"].append(tag)
  32. elif arg[0] == "@":
  33. assign = arg[1:]
  34. if assign in task["assign"]:
  35. print(f"error: duplicate assign @{assign} in task", file=sys.stderr)
  36. sys.exit(-1)
  37. task["assign"].append(assign)
  38. elif ":" in arg:
  39. attr, val = arg.split(":", 1)
  40. set_task_attr(task, attr, val)
  41. else:
  42. title_words.append(arg)
  43. title = " ".join(title_words)
  44. if len(title) == 0:
  45. print("Error: Title is required")
  46. exit(-1)
  47. task["title"] = title
  48. if task["desc"] is None:
  49. task["desc"] = prompt_description_text(task)
  50. if task["desc"].strip() == '':
  51. print("Abort adding the task due to empty description.")
  52. exit(-1)
  53. if await api.add_task(task):
  54. print(f"Created task '{title}'.")
  55. def prompt_text(comment_lines):
  56. temp = tempfile.NamedTemporaryFile()
  57. temp.write(b"\n")
  58. for line in comment_lines:
  59. temp.write(line.encode() + b"\n")
  60. temp.flush()
  61. editor = os.environ.get('EDITOR') if os.environ.get('EDITOR') else 'nano'
  62. os.system(f"{editor} {temp.name}")
  63. desc = open(temp.name, "r").read()
  64. # Remove comments and empty lines from desc
  65. cleaned = []
  66. for line in desc.split("\n"):
  67. if line == "# ------------------------ >8 ------------------------":
  68. break
  69. if line.startswith("#"):
  70. continue
  71. cleaned.append(line)
  72. return "\n".join(cleaned)
  73. def prompt_description_text(task):
  74. return prompt_text([
  75. "# Write task description above this line.",
  76. "# These lines will be removed.",
  77. "# An empty description aborts adding the task",
  78. "\n# ------------------------ >8 ------------------------",
  79. "# Do not modify or remove the line above.",
  80. "# Everything below it will be ignored.",
  81. f"\n{tabulate_task(task)}"
  82. ])
  83. def prompt_comment_text():
  84. return prompt_text([
  85. "# Write comments above this line",
  86. "# These lines will be removed"
  87. ])
  88. def set_task_attr(task, attr, val):
  89. # templ = lib.util.task_template
  90. assert attr in ["desc", "rank", "due", "project"]
  91. # assert templ[attr] != list
  92. if val.lower() == "none":
  93. task[attr] = None
  94. else:
  95. val = convert_attr_val(attr, val)
  96. task[attr] = val
  97. lib.util._enforce_task_format(task)
  98. def convert_attr_val(attr, val):
  99. templ = lib.util.task_template
  100. if attr in ["desc", "title"]:
  101. assert templ[attr] == str
  102. return val
  103. elif attr == "rank":
  104. try:
  105. return float(val)
  106. except ValueError:
  107. print(f"error: rank value {val} isn't convertable to float",
  108. file=sys.stderr)
  109. sys.exit(-1)
  110. elif attr == "due":
  111. # Other date formats not yet supported... ez to add
  112. assert len(val) == 4
  113. date = datetime.now().date()
  114. year = int(date.strftime("%Y"))%100
  115. try:
  116. dt = datetime.strptime(f"18:00 {val}{year}", "%H:%M %d%m%y")
  117. except ValueError:
  118. print(f"error: unknown date format {val}")
  119. sys.exit(-1)
  120. due = lib.util.datetime_to_unix(dt)
  121. return due
  122. elif attr == "project":
  123. try:
  124. return [val]
  125. except ValueError:
  126. print(f"error: project value {val} isn't convertable to list",
  127. file=sys.stderr)
  128. sys.exit(-1)
  129. else:
  130. print(f"error: unhandled attr '{attr}' = {val}")
  131. sys.exit(-1)
  132. async def show_active_tasks():
  133. refids = await api.get_ref_ids()
  134. tasks = []
  135. for refid in refids:
  136. tasks.append(await api.fetch_task(refid))
  137. list_tasks(tasks, [])
  138. async def show_deactive_tasks(month):
  139. tasks = await api.fetch_deactive_tasks(month)
  140. list_tasks(tasks, [])
  141. def list_tasks(tasks, filters):
  142. headers = ["ID", "Title", "Status", "Project",
  143. "Tags", "assign", "Rank", "Due"]
  144. table_rows = []
  145. for id, task in enumerate(tasks, 1):
  146. if task is None:
  147. continue
  148. if is_filtered(task, filters):
  149. continue
  150. title = task["title"]
  151. status = task["state"]
  152. # project = task["project"] if task["project"] is not None else ""
  153. tags = " ".join(f"+{tag}" for tag in task["tags"])
  154. assign = " ".join(f"@{assign}" for assign in task["assign"])
  155. project = " ".join(f"{project}" for project in task["project"])
  156. if task["due"] is None:
  157. due = ""
  158. else:
  159. dt = lib.util.unix_to_datetime(task["due"])
  160. due = dt.strftime("%H:%M %d/%m/%y")
  161. rank = round(task["rank"], 4) if task["rank"] is not None else ""
  162. if status == "start":
  163. id = Fore.GREEN + str(id) + Style.RESET_ALL
  164. title = Fore.GREEN + str(title) + Style.RESET_ALL
  165. status = Fore.GREEN + str(status) + Style.RESET_ALL
  166. project = Fore.GREEN + str(project) + Style.RESET_ALL
  167. tags = Fore.GREEN + str(tags) + Style.RESET_ALL
  168. assign = Fore.GREEN + str(assign) + Style.RESET_ALL
  169. rank = Fore.GREEN + str(rank) + Style.RESET_ALL
  170. due = Fore.GREEN + str(due) + Style.RESET_ALL
  171. elif status == "pause":
  172. id = Fore.YELLOW + str(id) + Style.RESET_ALL
  173. title = Fore.YELLOW + str(title) + Style.RESET_ALL
  174. status = Fore.YELLOW + str(status) + Style.RESET_ALL
  175. project = Fore.YELLOW + str(project) + Style.RESET_ALL
  176. tags = Fore.YELLOW + str(tags) + Style.RESET_ALL
  177. assign = Fore.YELLOW + str(assign) + Style.RESET_ALL
  178. rank = Fore.YELLOW + str(rank) + Style.RESET_ALL
  179. due = Fore.YELLOW + str(due) + Style.RESET_ALL
  180. else:
  181. #id = Style.DIM + str(id) + Style.RESET_ALL
  182. #title = Style.DIM + str(title) + Style.RESET_ALL
  183. #status = Style.DIM + str(status) + Style.RESET_ALL
  184. project = Style.DIM + str(project) + Style.RESET_ALL
  185. tags = Style.DIM + str(tags) + Style.RESET_ALL
  186. #assign = Style.DIM + str(assign) + Style.RESET_ALL
  187. rank = Style.DIM + str(rank) + Style.RESET_ALL
  188. due = Style.DIM + str(due) + Style.RESET_ALL
  189. rank_value = task["rank"] if task["rank"] is not None else 0
  190. row = [
  191. id,
  192. title,
  193. status,
  194. project,
  195. tags,
  196. assign,
  197. rank,
  198. due,
  199. ]
  200. table_rows.append((rank_value, row))
  201. table = [row for (_, row) in
  202. sorted(table_rows, key=lambda item: item[0], reverse=True)]
  203. print(tabulate(table, headers=headers))
  204. async def show_task(refid):
  205. task = await api.fetch_task(refid)
  206. task_table(task)
  207. return 0
  208. async def show_archive_task(id, month):
  209. task = await api.fetch_archive_task(id, month)
  210. task_table(task)
  211. return 0
  212. def tabulate_task(task):
  213. tags = " ".join(f"+{tag}" for tag in task["tags"])
  214. assign = " ".join(f"@{assign}" for assign in task["assign"])
  215. project = " ".join(f"{project}" for project in task["project"])
  216. rank = round(task["rank"], 4) if task["rank"] is not None else ""
  217. if task["due"] is None:
  218. due = ""
  219. else:
  220. dt = lib.util.unix_to_datetime(task["due"])
  221. due = dt.strftime("%H:%M %d/%m/%y")
  222. assert task["created_at"] is not None
  223. dt = lib.util.unix_to_datetime(task["created_at"])
  224. created_at = dt.strftime("%H:%M %d/%m/%y")
  225. table = [
  226. ["Title:", task["title"]],
  227. ["Description:", task["desc"]],
  228. ["Status:", task["state"]],
  229. ["Project:", project],
  230. ["Tags:", tags],
  231. ["assign:", assign],
  232. ["Rank:", rank],
  233. ["Due:", due],
  234. ["Created:", created_at],
  235. ]
  236. return tabulate(table, headers=["Attribute", "Value"])
  237. def task_table(task):
  238. print(tabulate_task(task))
  239. table = []
  240. for event in task["events"]:
  241. act, who, when, args = event["action"], event["author"], event["timestamp"], event["content"]
  242. when = lib.util.unix_to_datetime(when)
  243. when = when.strftime("%H:%M %d/%m/%y")
  244. if act == "due" and when is not None:
  245. table.append([
  246. Style.DIM + f"{who} changed {act} to {when}" + Style.RESET_ALL,
  247. "",
  248. Style.DIM + when + Style.RESET_ALL
  249. ])
  250. elif act == "tags":
  251. val = f"+{args}"
  252. table.append([
  253. Style.DIM + f"{who} added {act} to {val}" + Style.RESET_ALL,
  254. "",
  255. Style.DIM + when + Style.RESET_ALL
  256. ])
  257. elif act == "assign":
  258. val = f"@{args}"
  259. table.append([
  260. Style.DIM + f"{who} added {act} to {val}" + Style.RESET_ALL,
  261. "",
  262. Style.DIM + when + Style.RESET_ALL
  263. ])
  264. elif act == "state":
  265. status = args
  266. if status == "pause":
  267. status_verb = "paused"
  268. elif status in ["start", "cancel"]:
  269. status_verb = f"{status}ed"
  270. elif status == "stop":
  271. status_verb = f"stopped"
  272. else:
  273. print(f"internal error: unhandled task state {status}",
  274. file=sys.stderr)
  275. sys.exit(-2)
  276. table.append([
  277. f"{who} {status_verb} task",
  278. "",
  279. Style.DIM + when + Style.RESET_ALL
  280. ])
  281. else:
  282. table.append([
  283. Style.DIM + f"{who} changed {act} to {args}" + Style.RESET_ALL,
  284. "",
  285. Style.DIM + when + Style.RESET_ALL
  286. ])
  287. print(tabulate(table))
  288. table = []
  289. for event in task['events']:
  290. act, who, when, args = event["action"], event["author"], event["timestamp"], event["content"]
  291. when = lib.util.unix_to_datetime(when)
  292. when = when.strftime("%H:%M %d/%m/%y")
  293. if act == "comment":
  294. comment = args
  295. table.append([
  296. f"{who}>",
  297. wrap_comment(comment, 58),
  298. Style.DIM + when + Style.RESET_ALL
  299. ])
  300. if len(table) > 0:
  301. print("Comments:")
  302. print(tabulate(table))
  303. def wrap_comment(comment, width):
  304. lines = []
  305. line_start = 0
  306. for i, char in enumerate(comment):
  307. if char == ' ' and (i - line_start >= width):
  308. lines.append(comment[line_start:i + 1])
  309. line_start = i + 1
  310. if line_start < len(comment):
  311. lines.append(comment[line_start:])
  312. return '\n'.join(lines)
  313. async def modify_task(refid, args):
  314. changes = {}
  315. for arg in args:
  316. if arg[0] == "+":
  317. tag = arg
  318. changes["tags"] = tag
  319. # This must go before the next elif block
  320. elif arg.startswith("-@"):
  321. assign = arg
  322. changes["assign"] = assign
  323. elif arg[0] == "-":
  324. tag = arg
  325. changes["tags"] = tag
  326. elif arg[0] == "@":
  327. assign = arg
  328. changes["assign"] = assign
  329. elif ":" in arg:
  330. attr, val = arg.split(":", 1)
  331. if val.lower() == "none":
  332. if attr not in ["project", "rank", "due"]:
  333. print(f"error: invalid you cannot set {attr} to none",
  334. file=sys.stderr)
  335. return -1
  336. val = None
  337. else:
  338. val = convert_attr_val(attr, val)
  339. changes[str(attr)] = val
  340. else:
  341. print(f"warning: unknown arg '{arg}'. Skipping...", file=sys.stderr)
  342. await api.modify_task(refid, changes)
  343. return 0
  344. async def change_task_status(refid, status):
  345. task = await api.fetch_task(refid)
  346. assert task is not None
  347. title = task["title"]
  348. if not await api.change_task_status(refid, status):
  349. return -1
  350. if status == "start":
  351. print(f"Started task '{title}'")
  352. elif status == "pause":
  353. print(f"Paused task '{title}'")
  354. elif status == "stop":
  355. print(f"Completed task '{title}'")
  356. elif status == "cancel":
  357. print(f"Cancelled task '{title}'")
  358. return 0
  359. async def comment(refid, args):
  360. if not args:
  361. comment = prompt_comment_text()
  362. else:
  363. comment = " ".join(args)
  364. if not await api.add_task_comment(refid, comment):
  365. return -1
  366. task = await api.fetch_task(refid)
  367. assert task is not None
  368. title = task["title"]
  369. print(f"Commented on task'{title}'")
  370. return 0
  371. def is_filtered(task, filters):
  372. for fltr in filters:
  373. if fltr.startswith("+"):
  374. tag = fltr[1:]
  375. if tag not in task["tags"]:
  376. return True
  377. elif fltr.startswith("@"):
  378. assign = fltr[1:]
  379. if assign not in task["assign"]:
  380. return True
  381. elif ":" in fltr:
  382. attr, val = fltr.split(":", 1)
  383. if val.lower() == "none":
  384. if attr not in ["project", "rank", "due"]:
  385. print(f"error: invalid you cannot set {attr} to none",
  386. file=sys.stderr)
  387. sys.exit(-1)
  388. if task[attr] is not None:
  389. return True
  390. elif attr == "state" :
  391. if val not in ["open", "start", "pause"]:
  392. print(f"error: invalid, filter by {attr} can only be [\"open\", \"start\", \"pause\"]",
  393. file=sys.stderr)
  394. sys.exit(-1)
  395. if task["state"] != val:
  396. return True
  397. elif attr == "project":
  398. if task["project"] is None:
  399. return True
  400. if not task["project"].startswith(val):
  401. return True
  402. else:
  403. val = convert_attr_val(attr, val)
  404. if task[attr] != val:
  405. return True
  406. else:
  407. print(f"error: unknown arg '{fltr}'", file=sys.stderr)
  408. sys.exit(-1)
  409. return False
  410. def find_free_id(task_ids):
  411. for i in range(1, 1000):
  412. if i not in task_ids:
  413. return i
  414. 1
  415. def map_ids(task_ids, ref_ids):
  416. return dict(zip(task_ids, ref_ids))
  417. async def main():
  418. refids = await api.get_ref_ids()
  419. free_ids = []
  420. tasks = []
  421. for refid in refids:
  422. tasks.append(await api.fetch_task(refid))
  423. free_ids.append(find_free_id(free_ids))
  424. data = map_ids(free_ids, refids)
  425. if len(sys.argv) == 1:
  426. await show_active_tasks()
  427. return 0
  428. if sys.argv[1] in ["-h", "--help", "help"]:
  429. print('''USAGE:
  430. tau [OPTIONS] [SUBCOMMAND]
  431. OPTIONS:
  432. -h, --help Print help information
  433. SUBCOMMANDS:
  434. add Add a new task.
  435. archive Show completed tasks.
  436. comment Write comment for task by id.
  437. modify Modify an existing task by id.
  438. pause Pause task(s).
  439. start Start task(s).
  440. stop Stop task(s).
  441. help Show this help text.
  442. Example:
  443. tau add task one due:0312 rank:1.022 project:zk +lol @sk desc:desc +abc +def
  444. tau add task two rank:1.044 project:cr +mol @up desc:desc2
  445. tau add task three due:0512 project:zy +trol @kk desc:desc3 +who
  446. tau 1 modify @upgr due:1112 rank:none
  447. tau 1 modify -mol -xx
  448. tau 2 start
  449. tau 1 comment "this is an awesome comment"
  450. tau 2 pause
  451. tau archive # current month's completed tasks
  452. tau archive 1122 # completed tasks in Nov. 2022
  453. tau 0 archive 1122 # show info of task completed in Nov. 2022
  454. ''')
  455. return 0
  456. elif sys.argv[1] == "add":
  457. task_args = sys.argv[2:]
  458. await add_task(task_args)
  459. return 0
  460. elif sys.argv[1] == "archive":
  461. if len(sys.argv) > 2:
  462. if len(sys.argv[2]) == 4:
  463. month = sys.argv[2]
  464. else:
  465. print("error: month must be of format MMYY")
  466. return -1
  467. else:
  468. month = lib.util.current_month()
  469. await show_deactive_tasks(month)
  470. return 0
  471. elif sys.argv[1] == "show":
  472. if len(sys.argv) > 2:
  473. filters = sys.argv[2:]
  474. list_tasks(tasks, filters)
  475. else:
  476. await show_active_tasks()
  477. return 0
  478. try:
  479. id = int(sys.argv[1])
  480. refid = data[id]
  481. except (ValueError, KeyError):
  482. print("error: invalid ID", file=sys.stderr)
  483. return -1
  484. args = sys.argv[2:]
  485. if not args:
  486. return await show_task(refid)
  487. subcmd, args = args[0], args[1:]
  488. if subcmd == "modify":
  489. if (errc := await modify_task(refid, args)) < 0:
  490. return errc
  491. time.sleep(0.1)
  492. return await show_task(refid)
  493. elif subcmd in ["start", "pause", "stop", "cancel"]:
  494. status = subcmd
  495. if (errc := await change_task_status(refid, status)) < 0:
  496. return errc
  497. elif subcmd == "comment":
  498. if (errc := await comment(refid, args)) < 0:
  499. return errc
  500. elif subcmd == "archive":
  501. if len(args) == 1:
  502. if len(args[0]) == 4:
  503. month = args[0]
  504. else:
  505. print("Error: month must be of format MMYY")
  506. return -1
  507. else:
  508. month = lib.util.current_month()
  509. if (errc := await show_archive_task(refid, month)) < 0:
  510. return errc
  511. else:
  512. print(f"error: unknown subcommand '{subcmd}'")
  513. return -1
  514. return 0
  515. asyncio.run(main())