diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..e2995b8 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,119 @@ +name: Rust + +on: + push: + tags: + - '*' + +jobs: + rustfmt: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - run: rustup component add rustfmt + - run: cargo fmt -- --check + + build-linux: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v1 + # cache the build assets so they dont recompile every time. + - name: Cache Rust dependencies + uses: actions/cache@v1.0.1 + with: + path: target + key: ${{ runner.OS }}-build-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.OS }}-build- + - name: Install latest rust toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: beta + default: true + override: true + - name: Install system dependencies + run: | + sudo apt-get update \ + && sudo apt-get install -y \ + libdbus-1-dev + - name: Build + run: cargo build --all --release && strip target/release/dijo + + - name: Upload binaries to release + uses: svenstaro/upload-release-action@v1-release + with: + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: target/release/dijo + asset_name: dijo-x86_64-linux + tag: ${{ github.ref }} + overwrite: true + + build-apple: + runs-on: macos-latest + + steps: + - name: Checkout + uses: actions/checkout@v1 + - name: Cache Rust dependencies + uses: actions/cache@v1.0.1 + with: + path: target + key: ${{ runner.OS }}-build-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.OS }}-build- + - name: Install latest rust toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: beta + target: x86_64-apple-darwin + default: true + override: true + + - name: Build for mac + run: cargo build --all --release && strip target/release/dijo + + - name: Upload binaries to release + uses: svenstaro/upload-release-action@v1-release + with: + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: target/release/dijo + asset_name: dijo-x86_64-apple + tag: ${{ github.ref }} + overwrite: true + + build-windows: + runs-on: windows-latest + + steps: + - name: Checkout + uses: actions/checkout@v1 + - name: Cache Rust dependencies + uses: actions/cache@v1.0.1 + with: + path: target + key: ${{ runner.OS }}-build-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.OS }}-build- + - name: Install latest rust toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: beta + target: x86_64-pc-windows-msvc + default: true + override: true + + - name: Build for windows + run: | + cargo build --all --release + strip target/release/dijo + + - name: Upload binaries to release + uses: svenstaro/upload-release-action@v1-release + with: + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: target/release/dijo + asset_name: dijo-x86_64-windows + tag: ${{ github.ref }} + overwrite: true diff --git a/Cargo.lock b/Cargo.lock index 6ff6a8a..c4f9734 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -91,12 +91,6 @@ dependencies = [ "constant_time_eq", ] -[[package]] -name = "cc" -version = "1.0.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9a06fb2e53271d7c279ec1efea6ab691c35a2ae67ec0d91d7acec0caf13b518" - [[package]] name = "cfg-if" version = "0.1.10" @@ -167,12 +161,12 @@ checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" [[package]] name = "crossbeam-channel" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cced8691919c02aac3cb0a1bc2e9b73d89e832bf9a06fc579d4e71b68a2da061" +checksum = "09ee0cc8804d5393478d743b035099520087a5186f3b93fa58cec08fa62407b6" dependencies = [ + "cfg-if", "crossbeam-utils", - "maybe-uninit", ] [[package]] @@ -236,10 +230,8 @@ dependencies = [ "lazy_static", "libc", "log", - "maplit", - "ncurses", "signal-hook", - "term_size", + "termion", "unicode-segmentation", "unicode-width", ] @@ -303,7 +295,7 @@ dependencies = [ [[package]] name = "dijo" -version = "0.1.3" +version = "0.2.0" dependencies = [ "chrono", "clap", @@ -582,18 +574,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "maplit" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" - -[[package]] -name = "maybe-uninit" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" - [[package]] name = "mio" version = "0.6.22" @@ -661,17 +641,6 @@ dependencies = [ "winapi 0.3.9", ] -[[package]] -name = "ncurses" -version = "5.99.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15699bee2f37e9f8828c7b35b2bc70d13846db453f2d507713b758fabe536b82" -dependencies = [ - "cc", - "libc", - "pkg-config", -] - [[package]] name = "net2" version = "0.2.34" @@ -773,6 +742,12 @@ dependencies = [ "autocfg", ] +[[package]] +name = "numtoa" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8f8bdf33df195859076e54ab11ee78a1b208382d3a26ec40d142ffc1ecc49ef" + [[package]] name = "owning_ref" version = "0.4.1" @@ -806,12 +781,6 @@ dependencies = [ "winapi 0.3.9", ] -[[package]] -name = "pkg-config" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d36492546b6af1463394d46f0c834346f31548646f6ba10849802c9c9a27ac33" - [[package]] name = "proc-macro-hack" version = "0.5.16" @@ -820,9 +789,9 @@ checksum = "7e0456befd48169b9f13ef0f0ad46d492cf9d2dbb918bcf38e01eed4ce3ec5e4" [[package]] name = "proc-macro2" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "beae6331a816b1f65d04c45b078fd8e6c93e8071771f41b8163255bbd8d7c8fa" +checksum = "04f5f085b5d71e2188cb8271e5da0161ad52c3f227a661a3c135fdf28e258b12" dependencies = [ "unicode-xid", ] @@ -842,6 +811,15 @@ version = "0.1.57" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce" +[[package]] +name = "redox_termios" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76" +dependencies = [ + "redox_syscall", +] + [[package]] name = "redox_users" version = "0.3.4" @@ -982,9 +960,9 @@ checksum = "6446ced80d6c486436db5c078dde11a9f73d42b57fb273121e160b84f63d894c" [[package]] name = "syn" -version = "1.0.34" +version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "936cae2873c940d92e697597c5eee105fb570cd5689c695806f672883653349b" +checksum = "fb7f4c519df8c117855e19dd8cc851e89eb746fe7a73f0157e0d95fdec5369b0" dependencies = [ "proc-macro2", "quote", @@ -992,13 +970,15 @@ dependencies = [ ] [[package]] -name = "term_size" -version = "0.3.2" +name = "termion" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e4129646ca0ed8f45d09b929036bafad5377103edd06e50bf574b353d2b08d9" +checksum = "c22cec9d8978d906be5ac94bceb5a010d885c626c4c8855721a4dbd20e3ac905" dependencies = [ "libc", - "winapi 0.3.9", + "numtoa", + "redox_syscall", + "redox_termios", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 4b35c96..a0872ce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dijo" -version = "0.1.3" +version = "0.2.0" authors = ["Akshay "] edition = "2018" description = "Scriptable, curses-based, digital habit tracker" @@ -23,7 +23,7 @@ notify = "4.0" [dependencies.cursive] version = "0.15" default-features = false -features = ["crossterm-backend"] +features = ["termion-backend", "crossterm-backend"] [dependencies.chrono] version = "0.4" diff --git a/readme.md b/readme.md index c407fae..714234e 100644 --- a/readme.md +++ b/readme.md @@ -19,13 +19,16 @@ much like a certain text editor. - **vim like command mode**: add with `:add`, delete with `:delete` and above all, quit with `:q`!. - **fully scriptable**: [configure `dijo` to - track your `git` commits](./Auto-Habits)! + track your `git` commits](https://github.com/NerdyPepper/dijo/wiki/Auto-Habits)! ### Install Get `dijo` by running the following at the nearest prompt: -``` +```shell +# dijo requires rustc >= v1.42 +$ rustup update + $ cargo install dijo ``` diff --git a/src/app/impl_self.rs b/src/app/impl_self.rs index 744f906..a806dc5 100644 --- a/src/app/impl_self.rs +++ b/src/app/impl_self.rs @@ -37,6 +37,10 @@ impl App { self.habits.push(h); } + pub fn list_habits(&self) -> Vec { + self.habits.iter().map(|x| x.name()).collect::>() + } + pub fn delete_by_name(&mut self, name: &str) { let old_len = self.habits.len(); self.habits.retain(|h| h.name() != name); @@ -118,13 +122,13 @@ impl App { } pub fn status(&self) -> StatusLine { - let today = chrono::Local::now().naive_utc().date(); + let today = chrono::Local::now().naive_local().date(); let remaining = self.habits.iter().map(|h| h.remaining(today)).sum::(); let total = self.habits.iter().map(|h| h.goal()).sum::(); let completed = total - remaining; let timestamp = if self.view_month_offset == 0 { - format!("{}", Local::now().date().format("%d/%b/%y"),) + format!("{}", Local::now().naive_local().date().format("%d/%b/%y"),) } else { let months = self.view_month_offset; format!("{}", format!("{} months ago", months),) @@ -207,12 +211,18 @@ impl App { .iter_mut() .find(|x| x.name() == name && x.is_auto()); if let Some(h) = target_habit { - h.modify(Local::now().naive_utc().date(), event); + h.modify(Local::now().naive_local().date(), event); } }; match result { Ok(c) => match c { Command::Add(name, goal, auto) => { + if let Some(_) = self.habits.iter().find(|x| x.name() == name) { + self.message.set_kind(MessageKind::Error); + self.message + .set_message(format!("Habit `{}` already exist", &name)); + return; + } let kind = if goal == Some(1) { "bit" } else { "count" }; if kind == "count" { self.add_habit(Box::new(Count::new(name, goal.unwrap_or(0), auto))); @@ -230,7 +240,30 @@ impl App { Command::TrackDown(name) => { _track(&name, TrackEvent::Decrement); } - Command::Quit => self.save_state(), + Command::Help(input) => { + if let Some(topic) = input.as_ref().map(String::as_ref) { + self.message.set_message( + match topic { + "a" | "add" => "add [goal] (alias: a)", + "aa" | "add-auto" => "add-auto [goal] (alias: aa)", + "d" | "delete" => "delete (alias: d)", + "mprev" | "month-prev" => "month-prev (alias: mprev)", + "mnext" | "month-next" => "month-next (alias: mnext)", + "tup" | "track-up" => "track-up (alias: tup)", + "tdown" | "track-down" => "track-down (alias: tdown)", + "q" | "quit" => "quit", + "h"|"?" | "help" => "help [|commands|keys] (aliases: h, ?)", + "cmds" | "commands" => "add, add-auto, delete, month-{prev,next}, track-{up,down}, help, quit", + "keys" => "TODO", // TODO (view?) + _ => "unknown command or help topic.", + } + ) + } else { + // TODO (view?) + self.message.set_message("help |commands|keys") + } + } + Command::Quit | Command::Write => self.save_state(), Command::MonthNext => self.sift_forward(), Command::MonthPrev => self.sift_backward(), Command::Blank => {} diff --git a/src/app/impl_view.rs b/src/app/impl_view.rs index 892b00c..0dfd20b 100644 --- a/src/app/impl_view.rs +++ b/src/app/impl_view.rs @@ -102,25 +102,6 @@ impl View for App { self.set_focus(Absolute::Down); return EventResult::Consumed(None); } - Event::Char('d') => { - if self.habits.is_empty() { - return EventResult::Consumed(None); - } - self.habits.remove(self.focus); - self.focus = self.focus.checked_sub(1).unwrap_or(0); - return EventResult::Consumed(None); - } - Event::Char('w') => { - // helper bind to test write to file - let j = serde_json::to_string_pretty(&self.habits).unwrap(); - let mut file = File::create("foo.txt").unwrap(); - file.write_all(j.as_bytes()).unwrap(); - return EventResult::Consumed(None); - } - Event::Char('q') => { - self.save_state(); - return EventResult::with_cb(|s| s.quit()); - } Event::Char('v') => { if self.habits.is_empty() { return EventResult::Consumed(None); diff --git a/src/command.rs b/src/command.rs index f856b00..38d48e9 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1,21 +1,75 @@ use std::fmt; +use cursive::event::{Event, EventResult, Key}; use cursive::theme::{BaseColor, Color, ColorStyle}; use cursive::view::Resizable; -use cursive::views::{EditView, LinearLayout, TextView}; +use cursive::views::{EditView, LinearLayout, OnEventView, TextView}; use cursive::Cursive; use crate::{app::App, CONFIGURATION}; +static COMMANDS: &'static [&'static str] = &[ + "add", + "add-auto", + "delete", + "track-up", + "track-down", + "month-prev", + "month-next", + "quit", + "write", + "help", +]; + +fn get_command_completion(prefix: &str) -> Option { + let first_match = COMMANDS.iter().filter(|&x| x.starts_with(prefix)).next(); + return first_match.map(|&x| x.into()); +} + +fn get_habit_completion(prefix: &str, habit_names: &[String]) -> Option { + let first_match = habit_names.iter().filter(|&x| x.starts_with(prefix)).next(); + eprintln!("{:?}| {:?}", prefix, first_match); + return first_match.map(|x| x.into()); +} + pub fn open_command_window(s: &mut Cursive) { - let command_window = EditView::new() - .filler(" ") - .on_submit(call_on_app) - .style(ColorStyle::new( - Color::Dark(BaseColor::Black), - Color::Dark(BaseColor::White), - )) - .fixed_width(CONFIGURATION.view_width * CONFIGURATION.grid_width); + let habit_list: Vec = s + .call_on_name("Main", |view: &mut App| { + return view.list_habits(); + }) + .unwrap(); + let style = ColorStyle::new(Color::Dark(BaseColor::Black), Color::Dark(BaseColor::White)); + let command_window = OnEventView::new( + EditView::new() + .filler(" ") + .on_submit(call_on_app) + .style(style), + ) + .on_event_inner( + Event::Key(Key::Tab), + move |view: &mut EditView, _: &Event| { + let contents = view.get_content(); + if !contents.contains(" ") { + let completion = get_command_completion(&*contents); + if let Some(c) = completion { + let cb = view.set_content(c); + return Some(EventResult::Consumed(Some(cb))); + }; + return None; + } else { + let word = contents.split(' ').last().unwrap(); + let completion = get_habit_completion(word, &habit_list); + eprintln!("{:?} | {:?}", completion, contents); + if let Some(c) = completion { + let cb = + view.set_content(format!("{}", contents) + c.strip_prefix(word).unwrap()); + return Some(EventResult::Consumed(Some(cb))); + }; + return None; + } + }, + ) + .fixed_width(CONFIGURATION.view_width * CONFIGURATION.grid_width); s.call_on_name("Frame", |view: &mut LinearLayout| { let mut commandline = LinearLayout::horizontal() .child(TextView::new(":")) @@ -59,15 +113,17 @@ pub enum Command { Delete(String), TrackUp(String), TrackDown(String), + Help(Option), + Write, Quit, Blank, } #[derive(Debug)] pub enum CommandLineError { - InvalidCommand(String), - InvalidArg(u32), // position - NotEnoughArgs(String, u32), + InvalidCommand(String), // command name + InvalidArg(u32), // position + NotEnoughArgs(String, u32), // command name, required no. of args } impl std::error::Error for CommandLineError {} @@ -134,9 +190,16 @@ impl Command { } return Ok(Command::TrackDown(args[0].to_string())); } + "h" | "?" | "help" => { + if args.is_empty() { + return Ok(Command::Help(None)); + } + return Ok(Command::Help(Some(args[0].to_string()))); + } "mprev" | "month-prev" => return Ok(Command::MonthPrev), "mnext" | "month-next" => return Ok(Command::MonthNext), "q" | "quit" => return Ok(Command::Quit), + "w" | "write" => return Ok(Command::Write), "" => return Ok(Command::Blank), s => return Err(CommandLineError::InvalidCommand(s.into())), } diff --git a/src/habit/bit.rs b/src/habit/bit.rs index 3386182..8fa14c2 100644 --- a/src/habit/bit.rs +++ b/src/habit/bit.rs @@ -100,11 +100,22 @@ impl Habit for Bit { fn goal(&self) -> u32 { return 1; } - fn modify(&mut self, date: NaiveDate, _: TrackEvent) { + fn modify(&mut self, date: NaiveDate, event: TrackEvent) { if let Some(val) = self.stats.get_mut(&date) { - *val = (val.0 ^ true).into(); + match event { + TrackEvent::Increment => *val = (val.0 ^ true).into(), + TrackEvent::Decrement => { + if val.0 { + *val = false.into(); + } else { + self.stats.remove(&date); + } + } + } } else { - self.insert_entry(date, CustomBool(true)); + if event == TrackEvent::Increment { + self.insert_entry(date, CustomBool(true)); + } } } fn set_view_month_offset(&mut self, offset: u32) { diff --git a/src/habit/count.rs b/src/habit/count.rs index 1bdf920..d351758 100644 --- a/src/habit/count.rs +++ b/src/habit/count.rs @@ -84,12 +84,15 @@ impl Habit for Count { if *val > 0 { *val -= 1 } else { - *val = 0 + self.stats.remove(&date); }; } } } else { - self.insert_entry(date, 1); + match event { + TrackEvent::Increment => self.insert_entry(date, 1), + _ => {} + }; } } fn set_view_month_offset(&mut self, offset: u32) { diff --git a/src/habit/prelude.rs b/src/habit/prelude.rs index 19b00a7..8335d6c 100644 --- a/src/habit/prelude.rs +++ b/src/habit/prelude.rs @@ -2,6 +2,7 @@ use serde::{Deserialize, Serialize}; use std::default; use std::fmt; +#[derive(Debug, PartialEq)] pub enum TrackEvent { Increment, Decrement, diff --git a/src/main.rs b/src/main.rs index fb16aaa..dec3156 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,7 +12,13 @@ use crate::command::{open_command_window, Command}; use crate::utils::{load_configuration_file, AppConfig}; use clap::{App as ClapApp, Arg}; + +#[cfg(target_os = "linux")] +use cursive::termion; + +#[cfg(target_os = "windows")] use cursive::crossterm; + use cursive::views::{LinearLayout, NamedView}; use lazy_static::lazy_static; @@ -33,6 +39,14 @@ fn main() { .value_name("CMD") .help("run a dijo command"), ) + .arg( + Arg::with_name("list") + .short("l") + .long("list") + .takes_value(false) + .help("list dijo habits") + .conflicts_with("command"), + ) .get_matches(); if let Some(c) = matches.value_of("command") { let command = Command::from_string(c); @@ -49,8 +63,17 @@ fn main() { "Commands other than `track-up` and `track-down` are currently not supported!" ), } + } else if matches.is_present("list") { + for h in App::load_state().list_habits() { + println!("{}", h); + } } else { + #[cfg(target_os = "windows")] let mut s = crossterm().unwrap(); + + #[cfg(target_os = "linux")] + let mut s = termion().unwrap(); + let app = App::load_state(); let layout = NamedView::new( "Frame", diff --git a/src/views.rs b/src/views.rs index 24c8a4d..da077ac 100644 --- a/src/views.rs +++ b/src/views.rs @@ -43,7 +43,7 @@ where let strikethrough = Style::from(Effect::Strikethrough); let goal_status = - self.view_month_offset() == 0 && self.reached_goal(Local::now().naive_utc().date()); + self.view_month_offset() == 0 && self.reached_goal(Local::now().naive_local().date()); printer.with_style( Style::merge(&[ @@ -77,12 +77,20 @@ where .collect::>(); for (week, line_nr) in days.chunks(7).zip(2..) { let weekly_goal = self.goal() * week.len() as u32; - let is_this_week = week.contains(&Local::now().naive_utc().date()); + let is_this_week = week.contains(&Local::now().naive_local().date()); let remaining = week.iter().map(|&i| self.remaining(i)).sum::(); let completions = weekly_goal - remaining; let full = CONFIGURATION.view_width - 8; - let bars_to_fill = if weekly_goal > 0 {(completions * full as u32) / weekly_goal} else {0}; - let percentage = if weekly_goal > 0 {(completions as f64 * 100.) / weekly_goal as f64} else {0.0}; + let bars_to_fill = if weekly_goal > 0 { + (completions * full as u32) / weekly_goal + } else { + 0 + }; + let percentage = if weekly_goal > 0 { + (completions as f64 * 100.) / weekly_goal as f64 + } else { + 0.0 + }; printer.with_style(future_style, |p| { p.print((4, line_nr), &"─".repeat(full)); }); @@ -141,7 +149,7 @@ where } fn on_event(&mut self, e: Event) -> EventResult { - let now = Local::now().naive_utc().date(); + let now = Local::now().naive_local().date(); if self.is_auto() { return EventResult::Ignored; }