tau 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. #!/usr/bin/env python3
  2. import asyncio, os, sys, tempfile
  3. from datetime import datetime
  4. import time
  5. from tabulate import tabulate
  6. from colorama import Fore, Style
  7. import api, lib.util
  8. known_attrs = ["desc", "rank", "due", "project"]
  9. async def add_task(task_args, server_name, port):
  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
  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
  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 and arg.split(":")[0] in known_attrs:
  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 task["rank"] is not None:
  53. task["rank"] = round(task["rank"], 4)
  54. try:
  55. if task["ref_id"].strip() == '':
  56. task.pop('ref_id')
  57. if task["workspace"].strip() == '':
  58. task.pop('workspace')
  59. except KeyError:
  60. pass
  61. ref = await api.add_task(task, server_name, port)
  62. if ref:
  63. return ref, title
  64. else:
  65. print("You don't have write access")
  66. exit(-1)
  67. def prompt_text(comment_lines):
  68. temp = tempfile.NamedTemporaryFile()
  69. temp.write(b"\n")
  70. for line in comment_lines:
  71. temp.write(line.encode() + b"\n")
  72. temp.flush()
  73. editor = os.environ.get('EDITOR') if os.environ.get('EDITOR') else 'nano'
  74. os.system(f"{editor} {temp.name}")
  75. desc = open(temp.name, "r").read()
  76. # Remove comments and empty lines from desc
  77. cleaned = []
  78. for line in desc.split("\n"):
  79. if line == "# ------------------------ >8 ------------------------":
  80. break
  81. if line.startswith("#"):
  82. continue
  83. cleaned.append(line)
  84. return "\n".join(cleaned)
  85. def prompt_description_text(task):
  86. return prompt_text([
  87. "# Write task description above this line.",
  88. "# These lines will be removed.",
  89. "# An empty description aborts adding the task",
  90. "\n# ------------------------ >8 ------------------------",
  91. "# Do not modify or remove the line above.",
  92. "# Everything below it will be ignored.",
  93. f"\n{tabulate_task(task, True)}"
  94. ])
  95. def prompt_comment_text():
  96. return prompt_text([
  97. "# Write comments above this line",
  98. "# These lines will be removed"
  99. ])
  100. def prompt_description_edit(text):
  101. return prompt_text([
  102. f"{text}"
  103. "# Edit the task description above this line",
  104. "# These lines will be removed"
  105. ])
  106. def set_task_attr(task, attr, val):
  107. if attr not in known_attrs:
  108. print(f"Error: invalid attribute: {attr} {val}")
  109. print("Task is not added")
  110. exit(-1)
  111. if val.lower() == "none":
  112. task[attr] = None
  113. else:
  114. val = convert_attr_val(attr, val)
  115. task[attr] = val
  116. lib.util._enforce_task_format(task)
  117. def convert_attr_val(attr, val):
  118. templ = lib.util.task_template
  119. if attr in ["desc", "title"]:
  120. assert templ[attr] == str
  121. return val
  122. elif attr == "rank":
  123. try:
  124. return float(val)
  125. except ValueError:
  126. print(f"error: rank value {val} isn't convertable to float",
  127. file=sys.stderr)
  128. sys.exit(-1)
  129. elif attr == "due":
  130. # Other date formats not yet supported... ez to add
  131. if len(val) != 4:
  132. print(f"Error: due date must be of length 4 in mmyy format")
  133. sys.exit(-1)
  134. date = datetime.now().date()
  135. year = int(date.strftime("%Y"))%100
  136. try:
  137. dt = datetime.strptime(f"18:00 {val}{year}", "%H:%M %d%m%y")
  138. if dt.date() < date:
  139. dt = datetime.strptime(f"18:00 {val}{year+1}", "%H:%M %d%m%y")
  140. except ValueError:
  141. print(f"error: unknown date format {val}")
  142. sys.exit(-1)
  143. due = lib.util.datetime_to_unix(dt)
  144. return due
  145. elif attr == "project":
  146. try:
  147. return [val]
  148. except ValueError:
  149. print(f"error: project value {val} isn't convertable to list",
  150. file=sys.stderr)
  151. sys.exit(-1)
  152. else:
  153. print(f"error: unhandled attr '{attr}' = {val}")
  154. sys.exit(-1)
  155. async def show_active_tasks(workspace, server_name, port):
  156. refids = await api.get_ref_ids(server_name, port)
  157. tasks = []
  158. for refid in refids:
  159. tasks.append(await api.fetch_task(refid, server_name, port))
  160. list_tasks(tasks, workspace, [])
  161. async def show_deactive_tasks(month_ts, workspace, server_name, port):
  162. tasks = await api.fetch_deactive_tasks(month_ts, server_name, port)
  163. list_tasks(tasks, workspace, [])
  164. async def show_log(server_name, port, timeframe):
  165. # fetch all tasks
  166. refids = await api.get_ref_ids(server_name, port)
  167. tasks = await api.fetch_deactive_tasks(None, server_name, port)
  168. for refid in refids:
  169. tasks.append(await api.fetch_task(refid, server_name, port))
  170. # list tasks events within a timeframe
  171. if timeframe == "day":
  172. timestamp = 86400
  173. elif timeframe == "week" or timeframe == None:
  174. timestamp = 604800
  175. elif timeframe == "month":
  176. timestamp = 2628002
  177. else:
  178. print(f"Error: invalid timeframe {timeframe}")
  179. print("valid timeframes are: 'day', 'week' and 'month'")
  180. print("try: tau log week")
  181. exit(-1)
  182. res_events = []
  183. now = lib.util.now()
  184. for task in tasks:
  185. events = task["events"]
  186. for event in events:
  187. # if timestamp is in ms convert it to s
  188. event_ts = int(event["timestamp"])
  189. if event_ts > 10e10:
  190. event_ts //= 1000
  191. date = lib.util.unix_to_datetime(event_ts)
  192. if (now - event_ts) < timestamp:
  193. if event["action"] == "state":
  194. action = "stopped" if event["content"] == "stop" else f"{event["content"]}ed"
  195. res = f"{date}: {event["author"]} {action} task: ({task["ref_id"][:6]}) '{task["title"]}'"
  196. res_events.append(res)
  197. if event["action"] == "comment":
  198. res = f"{date}: {event["author"]} commented on task: ({task["ref_id"][:6]}) '{task["title"]}'"
  199. res_events.append(res)
  200. if event["action"] in ["assign", "tags"] :
  201. res = f"{date}: {event["author"]} added {event["content"][1:]} to {event["action"]} in task: ({task["ref_id"][:6]}) '{task["title"]}'"
  202. res_events.append(res)
  203. for i in res_events:
  204. print(i)
  205. def list_tasks(tasks, workspace, filters):
  206. print(f"Workspace: {workspace}")
  207. headers = ["ID", "Title", "Status", "Project",
  208. "Tags", "assign", "Rank", "Due", "RefID"]
  209. table_rows = []
  210. for id, task in enumerate(tasks, 1):
  211. if task is None:
  212. continue
  213. if is_filtered(task, filters):
  214. continue
  215. ref_id = task["ref_id"][:6]
  216. title = task["title"]
  217. status = task["state"]
  218. # project = task["project"] if task["project"] is not None else ""
  219. tags = " ".join(f"+{tag}" for tag in task["tags"])
  220. assign = " ".join(f"@{assign}" for assign in task["assign"])
  221. project = " ".join(f"{project}" for project in task["project"])
  222. if task["due"] is None:
  223. due = ""
  224. else:
  225. dt = lib.util.unix_to_datetime(task["due"])
  226. due = dt.strftime("%H:%M %d/%m/%y")
  227. rank = round(task["rank"], 4) if task["rank"] is not None else ""
  228. if status == "start":
  229. id = Fore.GREEN + str(id) + Style.RESET_ALL
  230. title = Fore.GREEN + str(title) + Style.RESET_ALL
  231. status = Fore.GREEN + str(status) + Style.RESET_ALL
  232. project = Fore.GREEN + str(project) + Style.RESET_ALL
  233. tags = Fore.GREEN + str(tags) + Style.RESET_ALL
  234. assign = Fore.GREEN + str(assign) + Style.RESET_ALL
  235. rank = Fore.GREEN + str(rank) + Style.RESET_ALL
  236. due = Fore.GREEN + str(due) + Style.RESET_ALL
  237. ref_id = Fore.GREEN + str(ref_id) + Style.RESET_ALL
  238. elif status == "pause":
  239. id = Fore.YELLOW + str(id) + Style.RESET_ALL
  240. title = Fore.YELLOW + str(title) + Style.RESET_ALL
  241. status = Fore.YELLOW + str(status) + Style.RESET_ALL
  242. project = Fore.YELLOW + str(project) + Style.RESET_ALL
  243. tags = Fore.YELLOW + str(tags) + Style.RESET_ALL
  244. assign = Fore.YELLOW + str(assign) + Style.RESET_ALL
  245. rank = Fore.YELLOW + str(rank) + Style.RESET_ALL
  246. due = Fore.YELLOW + str(due) + Style.RESET_ALL
  247. ref_id = Fore.YELLOW + str(ref_id) + Style.RESET_ALL
  248. elif status == "stop":
  249. id = Fore.RED + str(id) + Style.RESET_ALL
  250. title = Fore.RED + str(title) + Style.RESET_ALL
  251. status = Fore.RED + str(status) + Style.RESET_ALL
  252. project = Fore.RED + str(project) + Style.RESET_ALL
  253. tags = Fore.RED + str(tags) + Style.RESET_ALL
  254. assign = Fore.RED + str(assign) + Style.RESET_ALL
  255. rank = Fore.RED + str(rank) + Style.RESET_ALL
  256. due = Fore.RED + str(due) + Style.RESET_ALL
  257. ref_id = Fore.RED + str(ref_id) + Style.RESET_ALL
  258. else:
  259. #id = Style.DIM + str(id) + Style.RESET_ALL
  260. #title = Style.DIM + str(title) + Style.RESET_ALL
  261. #status = Style.DIM + str(status) + Style.RESET_ALL
  262. project = Style.DIM + str(project) + Style.RESET_ALL
  263. tags = Style.DIM + str(tags) + Style.RESET_ALL
  264. #assign = Style.DIM + str(assign) + Style.RESET_ALL
  265. rank = Style.DIM + str(rank) + Style.RESET_ALL
  266. due = Style.DIM + str(due) + Style.RESET_ALL
  267. #ref_id = Style.DIM + str(ref_id) + Style.RESET_ALL
  268. rank_value = task["rank"] if task["rank"] is not None else 0
  269. row = [
  270. id,
  271. title,
  272. status,
  273. project,
  274. tags,
  275. assign,
  276. rank,
  277. due,
  278. ref_id
  279. ]
  280. table_rows.append((rank_value, row))
  281. table = [row for (_, row) in
  282. sorted(table_rows, key=lambda item: item[0], reverse=True)]
  283. print(tabulate(table, headers=headers))
  284. async def show_task(refid, server_name, port):
  285. task = await api.fetch_task(refid, server_name, port)
  286. task_table(task)
  287. return 0
  288. async def show_archive_task(ref_id, month_ts, server_name, port):
  289. task = await api.fetch_archive_task(ref_id, month_ts, server_name, port)
  290. task_table(task)
  291. return 0
  292. def tabulate_task(task, prompt):
  293. tags = " ".join(f"+{tag}" for tag in task["tags"])
  294. assign = " ".join(f"{assign}" for assign in task["assign"])
  295. project = " ".join(f"{project}" for project in task["project"])
  296. rank = round(task["rank"], 4) if task["rank"] is not None else ""
  297. if task["due"] is None:
  298. due = ""
  299. else:
  300. dt = lib.util.unix_to_datetime(task["due"])
  301. due = dt.strftime("%H:%M %d/%m/%y")
  302. assert task["created_at"] is not None
  303. dt = lib.util.unix_to_datetime(task["created_at"])
  304. created_at = dt.strftime("%H:%M %d/%m/%y")
  305. if prompt:
  306. task["ref_id"] = ''
  307. task["workspace"] = ''
  308. table = [
  309. ["RefID:", task["ref_id"]],
  310. ["Title:", task["title"]],
  311. ["Workspace:", task["workspace"]],
  312. ["Description:", task["desc"]],
  313. ["Status:", task["state"]],
  314. ["Project:", project],
  315. ["Tags:", tags],
  316. ["Assign:", assign],
  317. ["Rank:", rank],
  318. ["Due:", due],
  319. ["Created:", created_at],
  320. ]
  321. return tabulate(table, headers=["Attribute", "Value"])
  322. def task_table(task):
  323. print(tabulate_task(task, False))
  324. table = []
  325. for event in task["events"]:
  326. act, who, when, args = event["action"], event["author"], event["timestamp"], event["content"]
  327. when = lib.util.unix_to_datetime(when)
  328. when = when.strftime("%H:%M %d/%m/%y")
  329. if act == "due" and when is not None:
  330. due_date = lib.util.unix_to_datetime(args)
  331. due_date = due_date.strftime("%H:%M %d/%m/%y")
  332. table.append([
  333. Style.DIM + f"{who} changed {act} to {due_date}" + Style.RESET_ALL,
  334. "",
  335. Style.DIM + when + Style.RESET_ALL
  336. ])
  337. elif act == "tags" or act == "assign":
  338. val = f"{args}"
  339. event = f"{who} added {val} to {act}"
  340. if val[0] == "-":
  341. event = f"{who} removed {val[1:]} from {act}"
  342. table.append([
  343. Style.DIM + event + Style.RESET_ALL,
  344. "",
  345. Style.DIM + when + Style.RESET_ALL
  346. ])
  347. elif act == "state":
  348. status = args
  349. if status == "pause":
  350. status_verb = "paused"
  351. elif status in ["start", "open"]:
  352. status_verb = f"{status}ed"
  353. elif status == "stop":
  354. status_verb = f"stopped"
  355. else:
  356. print(f"internal error: unhandled task state {status}",
  357. file=sys.stderr)
  358. sys.exit(-2)
  359. table.append([
  360. f"{who} {status_verb} task",
  361. "",
  362. Style.DIM + when + Style.RESET_ALL
  363. ])
  364. elif act == "comment":
  365. continue
  366. else:
  367. table.append([
  368. Style.DIM + f"{who} changed {act} to {args}" + Style.RESET_ALL,
  369. "",
  370. Style.DIM + when + Style.RESET_ALL
  371. ])
  372. print(tabulate(table))
  373. table = []
  374. for event in task['events']:
  375. act, who, when, args = event["action"], event["author"], event["timestamp"], event["content"]
  376. when = lib.util.unix_to_datetime(when)
  377. when = when.strftime("%H:%M %d/%m/%y")
  378. if act == "comment":
  379. comment = args
  380. table.append([
  381. f"{who}>",
  382. wrap_comment(comment, 58),
  383. Style.DIM + when + Style.RESET_ALL
  384. ])
  385. if len(table) > 0:
  386. print("Comments:")
  387. print(tabulate(table))
  388. def wrap_comment(comment, width):
  389. lines = []
  390. line_start = 0
  391. for i, char in enumerate(comment):
  392. if char == ' ' and (i - line_start >= width):
  393. lines.append(comment[line_start:i + 1])
  394. line_start = i + 1
  395. if line_start < len(comment):
  396. lines.append(comment[line_start:])
  397. return '\n'.join(lines)
  398. async def modify_task(refid, args, server_name, port):
  399. changes = {}
  400. changes["assign"] = []
  401. changes["tags"] = []
  402. for arg in args:
  403. # This must go before the next elif block
  404. if arg.startswith("@") or arg.startswith("-@"):
  405. changes["assign"].append(arg)
  406. elif arg.startswith("+") or arg.startswith("-"):
  407. changes["tags"].append(arg)
  408. elif arg.lower() in ["desc", "description"]:
  409. task = await api.fetch_task(refid, server_name, port)
  410. desc = task["desc"]
  411. new_desc = prompt_description_edit(desc).lstrip()
  412. if desc == new_desc:
  413. print("Abort due to unchanged description")
  414. exit(-1)
  415. changes["desc"] = new_desc
  416. elif ":" in arg:
  417. attr, val = arg.split(":", 1)
  418. if val.lower() == "none":
  419. if attr not in ["project", "rank", "due"]:
  420. print(f"error: invalid you cannot set {attr} to none",
  421. file=sys.stderr)
  422. return -1
  423. val = None
  424. else:
  425. val = convert_attr_val(attr, val)
  426. changes[str(attr)] = val
  427. else:
  428. print(f"warning: unknown arg '{arg}'. Skipping...", file=sys.stderr)
  429. if not await api.modify_task(refid, changes, server_name, port):
  430. print("You don't have write access")
  431. exit(-1)
  432. return 0
  433. async def change_task_status(refid, status, server_name, port):
  434. task = await api.fetch_task(refid, server_name, port)
  435. assert task is not None
  436. title = task["title"]
  437. if not await api.change_task_status(refid, status, server_name, port):
  438. return -1
  439. if status == "start":
  440. print(f"Started task '{title}'")
  441. elif status == "pause":
  442. print(f"Paused task '{title}'")
  443. elif status == "stop":
  444. print(f"Completed task '{title}'")
  445. elif status == "open":
  446. print(f"Opened task '{title}'")
  447. return 0
  448. async def comment(refid, args, server_name, port):
  449. if not args:
  450. comment = prompt_comment_text()
  451. else:
  452. comment = " ".join(args)
  453. if comment.strip() == '':
  454. print("Abort adding comment due to empty content.")
  455. exit(-1)
  456. if not await api.add_task_comment(refid, comment, server_name, port):
  457. print("You don't have write access")
  458. exit(-1)
  459. # Two json rpcs back to back cause Unexpected EOF error
  460. time.sleep(0.1)
  461. task = await api.fetch_task(refid, server_name, port)
  462. assert task is not None
  463. title = task["title"]
  464. print(f"Commented on task '{title}'")
  465. return 0
  466. def is_filtered(task, filters):
  467. for fltr in filters:
  468. if fltr.startswith("+"):
  469. tag = fltr[1:]
  470. if tag not in task["tags"]:
  471. return True
  472. elif fltr.startswith("@"):
  473. assign = fltr[1:]
  474. if assign not in task["assign"]:
  475. return True
  476. elif ":" in fltr:
  477. attr, val = fltr.split(":", 1)
  478. if val.lower() == "none":
  479. if attr not in ["project", "rank", "due"]:
  480. print(f"error: invalid you cannot set {attr} to none",
  481. file=sys.stderr)
  482. sys.exit(-1)
  483. if task[attr] is not None:
  484. return True
  485. elif attr == "state" :
  486. if val not in ["open", "start", "pause"]:
  487. print(f"error: invalid, filter by {attr} can only be [\"open\", \"start\", \"pause\"]",
  488. file=sys.stderr)
  489. sys.exit(-1)
  490. if task["state"] != val:
  491. return True
  492. else:
  493. val = convert_attr_val(attr, val)
  494. if task[attr] != val:
  495. return True
  496. else:
  497. print(f"error: unknown arg '{fltr}'", file=sys.stderr)
  498. sys.exit(-1)
  499. return False
  500. def find_free_id(task_ids):
  501. for i in range(1, 1000):
  502. if i not in task_ids:
  503. return i
  504. 1
  505. def map_ids(task_ids, ref_ids):
  506. return dict(zip(task_ids, ref_ids))
  507. async def main():
  508. val = str('127.0.0.1:23330')
  509. allowed_states = ["start", "pause", "stop", "open"]
  510. for i in range(1, len(sys.argv)):
  511. if sys.argv[i] == "-e":
  512. val = sys.argv[i+1]
  513. del sys.argv[i]
  514. del sys.argv[i]
  515. break
  516. server_name, port = val.split(':')
  517. refids = await api.get_ref_ids(server_name, port)
  518. free_ids = []
  519. tasks = []
  520. for refid in refids:
  521. tasks.append(await api.fetch_task(refid, server_name, port))
  522. free_ids.append(find_free_id(free_ids))
  523. data = map_ids(free_ids, refids)
  524. workspace = await api.get_workspace(server_name, port)
  525. if len(sys.argv) == 1:
  526. await show_active_tasks(workspace, server_name, port)
  527. return 0
  528. if any(x in ["-h", "--help", "help"] for x in sys.argv):
  529. print('''USAGE:
  530. tau [OPTIONS] [SUBCOMMAND]
  531. OPTIONS:
  532. -h, --help Print help information
  533. -e RPC endpoint [default: 127.0.0.1:23330]
  534. SUBCOMMANDS:
  535. add Add a new task.
  536. archive Show completed tasks.
  537. comment Write comment for task by id.
  538. modify Modify an existing task by id.
  539. pause Pause task(s).
  540. start Start task(s).
  541. stop Stop task(s).
  542. switch Switch between configured workspaces.
  543. show List filtered tasks.
  544. export Save current workspace tasks to a path.
  545. import Load current workspace tasks from a path.
  546. help Show this help text.
  547. Examples:
  548. tau add task one due:0312 rank:1.022 project:zk +lol @sk desc:desc +abc +def
  549. tau add task two rank:1.044 project:cr +mol @up desc:desc2
  550. tau add task three due:0512 project:zy +trol @kk desc:desc3 +who
  551. tau 1 modify @upgr due:1112 rank:none
  552. tau 1 modify -@up
  553. tau 1 modify -mol -xx
  554. tau 1,2 modify +dev @erto
  555. tau 1-3 start
  556. tau 1 comment "this is an awesome comment"
  557. tau 2 pause
  558. tau show @erto state:start # list started tasks that are assigned to 'erto'
  559. tau show +dev project:zk # list tasks with 'dev' tag project 'zk'
  560. tau switch darkfi # switch to configured 'darkfi' workspace
  561. tau archive # current month's completed tasks
  562. tau archive 1122 # completed tasks of Nov. 2022
  563. tau archive 1122 1 # show info of task completed in Nov. 2022
  564. ''')
  565. return 0
  566. elif sys.argv[1] == "log":
  567. if len(sys.argv) == 3:
  568. timeframe = sys.argv[2]
  569. else:
  570. timeframe = None
  571. await show_log(server_name, port, timeframe)
  572. return 0
  573. elif sys.argv[1] == "add":
  574. task_args = sys.argv[2:]
  575. ref, title = await add_task(task_args, server_name, port)
  576. if title:
  577. print(f"Created task ({find_free_id(free_ids)}) ({ref[:7]}) '{title}'.")
  578. return 0
  579. elif sys.argv[1] == "archive":
  580. if len(sys.argv) == 4:
  581. if len(sys.argv[2]) == 4:
  582. month = sys.argv[2]
  583. month_ts = lib.util.month_to_unix(month)
  584. else:
  585. print("error: usage format is: tau archive [MONTH] [ID]")
  586. return -1
  587. archive_refids = await api.get_archive_ref_ids(month_ts, server_name, port)
  588. afree_ids = []
  589. atasks = []
  590. for arefid in archive_refids:
  591. atasks.append(await api.fetch_archive_task(arefid, month_ts, server_name, port))
  592. afree_ids.append(find_free_id(afree_ids))
  593. adata = map_ids(afree_ids, archive_refids)
  594. if len(sys.argv[3]) < 4:
  595. try:
  596. tid = int(sys.argv[3])
  597. arefid = adata[tid]
  598. except (ValueError, KeyError):
  599. print("error: invalid ID", file=sys.stderr)
  600. return -1
  601. else:
  602. print("error: invalid ID", file=sys.stderr)
  603. return -1
  604. if (errc := await show_archive_task(arefid, month_ts, server_name, port)) < 0:
  605. return errc
  606. elif len(sys.argv) == 3:
  607. if sys.argv[2] == "all":
  608. await show_deactive_tasks(None, workspace, server_name, port)
  609. elif len(sys.argv[2]) == 4:
  610. month = sys.argv[2]
  611. month_ts = lib.util.month_to_unix(month)
  612. await show_deactive_tasks(month_ts, workspace, server_name, port)
  613. elif len(sys.argv[2]) < 4:
  614. month_ts = lib.util.month_to_unix()
  615. archive_refids = await api.get_archive_ref_ids(month_ts, server_name, port)
  616. afree_ids = []
  617. atasks = []
  618. for arefid in archive_refids:
  619. atasks.append(await api.fetch_archive_task(arefid, month_ts, server_name, port))
  620. afree_ids.append(find_free_id(afree_ids))
  621. adata = map_ids(afree_ids, archive_refids)
  622. try:
  623. tid = int(sys.argv[2])
  624. arefid = adata[tid]
  625. except (ValueError, KeyError):
  626. print("error: invalid ID", file=sys.stderr)
  627. return -1
  628. if (errc := await show_archive_task(arefid, month_ts, server_name, port)) < 0:
  629. return errc
  630. else:
  631. print("error: month must be of format MMYY")
  632. return -1
  633. else:
  634. month_ts = lib.util.month_to_unix()
  635. await show_deactive_tasks(month_ts, workspace, server_name, port)
  636. return 0
  637. elif sys.argv[1] == "show":
  638. if len(sys.argv) > 2:
  639. filters = sys.argv[2:]
  640. list_tasks(tasks, workspace, filters)
  641. else:
  642. await show_active_tasks(workspace, server_name, port)
  643. return 0
  644. elif sys.argv[1] == "switch":
  645. if not len(sys.argv) == 3:
  646. print("Error: you must provide workspace name")
  647. return 0
  648. if not await api.switch_workspace(sys.argv[2], server_name, port):
  649. print(f"Error: Workspace \"{sys.argv[2]}\" is not configured.")
  650. else:
  651. print(f"You are now on \"{sys.argv[2]}\" workspace.")
  652. return 0
  653. elif sys.argv[1] == "export":
  654. if len(sys.argv) == 2:
  655. path = "~/.local/share/darkfi"
  656. else:
  657. path = sys.argv[2]
  658. if await api.export_to(path, server_name, port):
  659. print(f"Exported tasks successfuly to {path}")
  660. return 0
  661. elif sys.argv[1] == "import":
  662. if len(sys.argv) == 2:
  663. path = "~/.local/share/darkfi"
  664. else:
  665. path = sys.argv[2]
  666. if await api.import_from(path, server_name, port):
  667. print(f"Imported tasks successfuly from {path}")
  668. return 0
  669. try:
  670. id = sys.argv[1]
  671. subcommands = ["modify", "comment"]
  672. if any(id in ls for ls in [allowed_states, subcommands]):
  673. user_input = input("This command has no filter, and will modify all tasks. Are you sure? [y/N] ")
  674. if user_input.lower() in ['y', 'yes']:
  675. refid = list(refids)
  676. args = sys.argv[1:]
  677. else:
  678. print("Command prevented from running.")
  679. exit(-1)
  680. elif any(id == rfid[:len(id)] for rfid in refids if len(id) > 2):
  681. refid = []
  682. for rid in refids:
  683. if id == rid[:len(id)]:
  684. refid.append(rid)
  685. args = sys.argv[2:]
  686. else:
  687. lines = id.split(',')
  688. numbers = []
  689. for line in lines:
  690. if line == '':
  691. continue
  692. elif '-' in line:
  693. t = line.split('-')
  694. numbers += range(int(t[0]), int(t[1]) + 1)
  695. else:
  696. numbers.append(int(line))
  697. refid = []
  698. for i in numbers:
  699. refid.append(data[i])
  700. args = sys.argv[2:]
  701. except (ValueError, KeyError):
  702. print("error: invalid ID", file=sys.stderr)
  703. return -1
  704. except EOFError:
  705. print('\nOperation is cancelled')
  706. return -1
  707. if not args:
  708. for rid in refid:
  709. await show_task(rid, server_name, port)
  710. return 0
  711. subcmd, args = args[0], args[1:]
  712. if subcmd == "modify":
  713. if not args:
  714. print("Error: modify subcommand must have at least one argument.")
  715. exit(-1)
  716. for rid in refid:
  717. if (errc := await modify_task(rid, args, server_name, port)) < 0:
  718. return errc
  719. time.sleep(0.1)
  720. await show_task(rid, server_name, port)
  721. elif subcmd in allowed_states:
  722. status = subcmd
  723. for rid in refid:
  724. if (errc := await change_task_status(rid, status, server_name, port)) < 0:
  725. return errc
  726. time.sleep(0.1)
  727. elif subcmd == "comment":
  728. for rid in refid:
  729. if (errc := await comment(rid, args, server_name, port)) < 0:
  730. return errc
  731. else:
  732. print(f"error: unknown subcommand '{subcmd}'")
  733. return -1
  734. return 0
  735. asyncio.run(main())