From 48aab9e860f816b9b6504c472ff05b30b3400085 Mon Sep 17 00:00:00 2001 From: Dmitriy Pleshevskiy Date: Fri, 5 Aug 2022 10:42:35 +0300 Subject: [PATCH] add priority subcommand --- src/cli.rs | 11 +++++++++++ src/main.rs | 43 ++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/cli.rs b/src/cli.rs index 245c7fe..c163542 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -34,4 +34,15 @@ pub enum SubCommand { Remove { idx: usize, }, + Priority { + idx: usize, + #[clap(subcommand)] + priority: Priority, + }, +} + +#[derive(Parser)] +pub enum Priority { + Before { idx: usize }, + After { idx: usize }, } diff --git a/src/main.rs b/src/main.rs index 4c1173b..6fcb52b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,9 @@ use clap::Parser; use serde::{Deserialize, Serialize}; -use std::io::{BufRead, Write}; +use std::{ + cmp::Ordering, + io::{BufRead, Write}, +}; use xdg::BaseDirectories; mod cli; @@ -94,6 +97,44 @@ fn main() { println!("{}", task.name); } } + cli::SubCommand::Priority { + idx: target_idx, + priority, + } => { + if target_idx == 0 || target_idx > tasks.len() { + println!("invalid index"); + } + + let idx = match priority { + cli::Priority::Before { idx } | cli::Priority::After { idx } => { + match target_idx.cmp(&idx) { + Ordering::Equal => return, + Ordering::Less => idx - 1, + Ordering::Greater => idx, + } + } + }; + if idx == 0 || idx > tasks.len() { + println!("invalid index"); + } + + let target = tasks.remove(target_idx - 1); + + match priority { + cli::Priority::Before { .. } => { + tasks.insert(idx - 1, target); + println!("{} < {}", target_idx, idx); + } + cli::Priority::After { .. } => { + tasks.insert(idx, target); + println!("{} > {}", target_idx, idx); + } + } + + let mut file = std::fs::File::create(&tasks_file_path).unwrap(); + file.write_all(&serde_json::to_vec(&tasks).unwrap()) + .unwrap(); + } cli::SubCommand::Start => { println!("starting..."); println!("-- on start hook found");