main.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{collections::HashMap, process::exit, sync::Arc};
  19. use clap::{Parser, Subcommand};
  20. use log::{error, info};
  21. use simplelog::{ColorChoice, TermLogger, TerminalMode};
  22. use smol::Executor;
  23. use url::Url;
  24. use darkfi::{
  25. rpc::client::RpcClient,
  26. util::cli::{get_log_config, get_log_level},
  27. Result,
  28. };
  29. mod drawdown;
  30. mod filter;
  31. mod primitives;
  32. mod rpc;
  33. mod util;
  34. mod view;
  35. use drawdown::{drawdown, to_naivedate};
  36. use filter::{apply_filter, get_ids, no_filter_warn};
  37. use primitives::{task_from_cli, State, TaskEvent};
  38. use util::{due_as_timestamp, prompt_text};
  39. use view::{find_free_id, print_task_info, print_task_list};
  40. use taud::task_info::TaskInfo;
  41. const DEFAULT_PATH: &str = "~/tau_exported_tasks";
  42. #[derive(Parser)]
  43. #[clap(name = "tau", version)]
  44. #[clap(subcommand_precedence_over_arg = true)]
  45. struct Args {
  46. #[arg(short, action = clap::ArgAction::Count)]
  47. /// Increase verbosity (-vvv supported)
  48. verbose: u8,
  49. #[clap(short, long, default_value = "tcp://127.0.0.1:23330")]
  50. /// taud JSON-RPC endpoint
  51. endpoint: Url,
  52. /// Search filters (zero or more)
  53. filters: Vec<String>,
  54. #[clap(subcommand)]
  55. command: Option<TauSubcommand>,
  56. }
  57. #[derive(Subcommand)]
  58. enum TauSubcommand {
  59. /// Add a new task.
  60. ///
  61. /// Quick start:
  62. /// Adding a new task named "New task":
  63. /// tau add New task
  64. /// New task with description:
  65. /// tau add Add more info to tau desc:"some awesome description"
  66. /// New task with project and assignee:
  67. /// tau add Third task project:p2p Arusty
  68. /// Add a task with due date September 12th and rank of 4.6:
  69. /// tau add Task no. Four due:1209 rank:4.6
  70. ///
  71. /// Notice that if the command does not have "desc" key it will open
  72. /// an Editor so you can write the description there.
  73. ///
  74. /// Also note that "project" key can have multiple
  75. /// comma-separated values.
  76. /// "assign" on the other hand uses '@' character but also could be
  77. /// multiple values, but like so:
  78. /// @person1 @person2
  79. ///
  80. /// All keys example:
  81. /// tau add Improve CLI desc:"Description here" project:tau,darkirc @dave @rusty due:0210 rank:2.2
  82. ///
  83. #[clap(verbatim_doc_comment)]
  84. Add {
  85. /// Pairs of key:value (e.g. desc:description @dark).
  86. values: Vec<String>,
  87. },
  88. /// Modify/Edit an existing task.
  89. Modify {
  90. #[clap(allow_hyphen_values = true)]
  91. /// Values (e.g. project:blockchain).
  92. values: Vec<String>,
  93. },
  94. /// List tasks.
  95. List,
  96. /// Start task(s).
  97. Start,
  98. /// Open task(s).
  99. Open,
  100. /// Pause task(s).
  101. Pause,
  102. /// Stop task(s).
  103. Stop,
  104. /// Set or Get comment for task(s).
  105. Comment {
  106. /// Set comment content if provided (Get comments otherwise).
  107. content: Vec<String>,
  108. },
  109. /// Get all data about selected task(s).
  110. Info,
  111. /// Switch workspace.
  112. Switch {
  113. /// Tau workspace.
  114. workspace: String,
  115. },
  116. /// Import tasks from a specified directory.
  117. Import {
  118. /// The parent directory from where you want to import tasks.
  119. path: Option<String>,
  120. },
  121. /// Export tasks to a specified directory.
  122. Export {
  123. /// The parent directory to where you want to export tasks.
  124. path: Option<String>,
  125. },
  126. /// Log drawdown.
  127. Log {
  128. /// The month in which we want to draw a heatmap (e.g. 0822 for August 2022).
  129. month: Option<String>,
  130. /// The person of which we want to draw a heatmap
  131. /// (if not provided we list all assignees).
  132. assignee: Option<String>,
  133. },
  134. }
  135. pub struct Tau {
  136. pub rpc_client: RpcClient,
  137. }
  138. fn main() -> Result<()> {
  139. let args = Args::parse();
  140. let log_level = get_log_level(args.verbose);
  141. let log_config = get_log_config(args.verbose);
  142. TermLogger::init(log_level, log_config, TerminalMode::Mixed, ColorChoice::Auto)?;
  143. let executor = Arc::new(Executor::new());
  144. smol::block_on(executor.run(async {
  145. let rpc_client = RpcClient::new(args.endpoint, executor.clone()).await?;
  146. let tau = Tau { rpc_client };
  147. let mut filters = args.filters.clone();
  148. // If IDs are provided in filter we use them to get the tasks from the daemon
  149. // then remove IDs from filter so we can do apply_filter() normally.
  150. // If not provided we use get_ids() to get them from the daemon.
  151. let ids = get_ids(&mut filters)?;
  152. let ids_clone = ids.clone();
  153. let mut tasks_local_id = HashMap::new();
  154. let task_ref_ids = tau.get_ref_ids().await?;
  155. let tasks = if filters.contains(&"state:stop".to_string()) ||
  156. filters.contains(&"all".to_string())
  157. {
  158. tau.get_stop_tasks(None).await?
  159. } else {
  160. vec![]
  161. };
  162. let mut store_ids = vec![];
  163. for task in tasks.clone() {
  164. let task_id = find_free_id(&store_ids);
  165. tasks_local_id.insert(task_id as usize, task);
  166. store_ids.push(task_id);
  167. }
  168. for refid in task_ref_ids {
  169. let task_id = find_free_id(&store_ids);
  170. let element = tau.get_task_by_ref_id(&refid).await?;
  171. tasks_local_id.insert(task_id as usize, element);
  172. store_ids.push(task_id);
  173. }
  174. if ids_clone.len() == 1 && args.command.is_none() {
  175. let id_itself = ids_clone[0] as usize;
  176. let tsk = tasks_local_id.get(&id_itself).unwrap();
  177. print_task_info(id_itself, tsk.clone())?;
  178. return Ok(())
  179. }
  180. for filter in filters {
  181. apply_filter(&mut tasks_local_id.clone().into_values().collect(), &filter);
  182. }
  183. // Parse subcommands
  184. match args.command {
  185. Some(sc) => match sc {
  186. TauSubcommand::Add { values } => {
  187. let mut task = task_from_cli(values)?;
  188. if task.title.is_empty() {
  189. error!("Please provide a title for the task.");
  190. exit(1);
  191. };
  192. if task.desc.is_none() {
  193. task.desc = prompt_text(TaskInfo::from(task.clone()), "description")?;
  194. };
  195. if task.clone().desc.unwrap().trim().is_empty() {
  196. error!("Abort adding the task due to empty description.");
  197. exit(1)
  198. }
  199. let title = task.clone().title;
  200. if tau.add(task).await? {
  201. println!("Created task \"{}\"", title);
  202. }
  203. Ok(())
  204. }
  205. TauSubcommand::Modify { values } => {
  206. if args.filters.is_empty() {
  207. no_filter_warn()
  208. }
  209. let base_task = task_from_cli(values)?;
  210. for id in ids_clone {
  211. let task = tasks_local_id.get(&(id as usize)).unwrap();
  212. let res = tau.modify(&task.ref_id, base_task.clone()).await?;
  213. if res {
  214. let tsk = tau.get_task_by_ref_id(&task.ref_id).await?;
  215. print_task_info(id as usize, tsk)?;
  216. }
  217. }
  218. Ok(())
  219. }
  220. TauSubcommand::Start => {
  221. if args.filters.is_empty() {
  222. no_filter_warn()
  223. }
  224. let state = State::Start;
  225. for id in ids_clone {
  226. let task = tasks_local_id.get(&(id as usize)).unwrap();
  227. if tau.set_state(&task.ref_id, &state).await? {
  228. println!("Started task: {} with refid: {}", id, task.ref_id);
  229. }
  230. }
  231. Ok(())
  232. }
  233. TauSubcommand::Open => {
  234. if args.filters.is_empty() {
  235. no_filter_warn()
  236. }
  237. let state = State::Open;
  238. for id in ids_clone {
  239. let task = tasks_local_id.get(&(id as usize)).unwrap();
  240. if tau.set_state(&task.ref_id, &state).await? {
  241. println!("Opened task: {} with refid: {}", id, task.ref_id);
  242. }
  243. }
  244. Ok(())
  245. }
  246. TauSubcommand::Pause => {
  247. if args.filters.is_empty() {
  248. no_filter_warn()
  249. }
  250. let state = State::Pause;
  251. for id in ids_clone {
  252. let task = tasks_local_id.get(&(id as usize)).unwrap();
  253. if tau.set_state(&task.ref_id, &state).await? {
  254. println!("Paused task: {} with refid: {}", id, task.ref_id);
  255. }
  256. }
  257. Ok(())
  258. }
  259. TauSubcommand::Stop => {
  260. if args.filters.is_empty() {
  261. no_filter_warn()
  262. }
  263. let state = State::Stop;
  264. for id in ids_clone {
  265. let task = tasks_local_id.get(&(id as usize)).unwrap();
  266. if tau.set_state(&task.ref_id, &state).await? {
  267. println!("Stopped task: {} with refid: {}", id, task.ref_id);
  268. }
  269. }
  270. Ok(())
  271. }
  272. TauSubcommand::Comment { content } => {
  273. if args.filters.is_empty() {
  274. no_filter_warn()
  275. }
  276. for id in ids_clone {
  277. let task = tasks_local_id.get(&(id as usize)).unwrap();
  278. let comment = if content.is_empty() {
  279. prompt_text(task.clone(), "comment")?
  280. } else {
  281. Some(content.join(" "))
  282. };
  283. if comment.clone().unwrap().trim().is_empty() || comment.is_none() {
  284. error!("Abort due to empty comment.");
  285. exit(1)
  286. }
  287. let res = tau.set_comment(&task.ref_id, comment.unwrap().trim()).await?;
  288. if res {
  289. let tsk = tau.get_task_by_ref_id(&task.ref_id).await?;
  290. print_task_info(id as usize, tsk)?;
  291. }
  292. }
  293. Ok(())
  294. }
  295. TauSubcommand::Info => {
  296. for id in ids_clone {
  297. let task = tasks_local_id.get(&(id as usize)).unwrap();
  298. let task = tau.get_task_by_ref_id(&task.ref_id).await?;
  299. print_task_info(id as usize, task)?;
  300. }
  301. Ok(())
  302. }
  303. TauSubcommand::Switch { workspace } => {
  304. if tau.switch_ws(workspace.clone()).await? {
  305. println!("You are now on \"{}\" workspace", workspace);
  306. } else {
  307. println!("Workspace \"{}\" is not configured", workspace);
  308. }
  309. Ok(())
  310. }
  311. TauSubcommand::Export { path } => {
  312. let path = path.unwrap_or_else(|| DEFAULT_PATH.into());
  313. let res = tau.export_to(path.clone()).await?;
  314. if res {
  315. info!("Exported to {}", path);
  316. } else {
  317. error!("Error exporting to {}", path);
  318. }
  319. Ok(())
  320. }
  321. TauSubcommand::Import { path } => {
  322. let path = path.unwrap_or_else(|| DEFAULT_PATH.into());
  323. let res = tau.import_from(path.clone()).await?;
  324. if res {
  325. info!("Imported from {}", path);
  326. } else {
  327. error!("Error importing from {}", path);
  328. }
  329. Ok(())
  330. }
  331. TauSubcommand::Log { month, assignee } => {
  332. match month {
  333. Some(date) => {
  334. let ts = to_naivedate(date.clone())?
  335. .and_hms_opt(12, 0, 0)
  336. .unwrap()
  337. .timestamp();
  338. let tasks = tau.get_stop_tasks(Some(ts.try_into().unwrap())).await?;
  339. drawdown(date, tasks, assignee)?;
  340. }
  341. None => {
  342. let _ws = tau.get_ws().await?;
  343. let _tasks = tau.get_stop_tasks(None).await?;
  344. // print_task_list(tasks, ws)?;
  345. }
  346. }
  347. Ok(())
  348. }
  349. TauSubcommand::List => {
  350. let ws = tau.get_ws().await?;
  351. print_task_list(tasks_local_id, ws)
  352. }
  353. },
  354. None => {
  355. let ws = tau.get_ws().await?;
  356. print_task_list(tasks_local_id, ws)
  357. }
  358. }?;
  359. tau.close_connection().await;
  360. Ok(())
  361. }))
  362. }