main.py 18 KB

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