main.py 24 KB

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