Skip to content

Commit

Permalink
feat: Use color_eyre instead of anyhow ✨
Browse files Browse the repository at this point in the history
  • Loading branch information
kdheepak committed Sep 3, 2023
1 parent fe171ea commit f238239
Show file tree
Hide file tree
Showing 18 changed files with 1,178 additions and 409 deletions.
970 changes: 736 additions & 234 deletions Cargo.lock

Large diffs are not rendered by default.

38 changes: 22 additions & 16 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,38 +7,45 @@ repository = "https://github.com/kdheepak/taskwarrior-tui/"
homepage = "https://kdheepak.com/taskwarrior-tui"
readme = "README.md"
authors = ["Dheepak Krishnamurthy <[email protected]>"]
edition = "2018"
edition = "2021"
keywords = ["taskwarrior", "tui"]
categories = ["command-line-utilities"]


[dependencies]
anyhow = "1.0.75"
better-panic = "0.3.0"
cassowary = "0.3.0"
chrono = "0.4.26"
clap = { version = "4.4.1", features = ["derive"] }
crossterm = { version = "0.27.0", features = [
"event-stream",
] }
dirs = "5.0.1"
chrono = "0.4.28"
clap = { version = "4.4.2", features = ["std", "color", "help", "usage", "error-context", "suggestions", "derive", "cargo", "wrap_help", "unicode", "string", "unstable-styles"] }
color-eyre = "0.6.2"
config = "0.13.3"
crossterm = { version = "0.27.0", features = ["event-stream", "serde"] }
directories = "5.0.1"
futures = "0.3.28"
human-panic = "1.2.0"
itertools = "0.11.0"
lazy_static = "1.4.0"
libc = "0.2.147"
log = "0.4.20"
log4rs = "1.2.0"
path-clean = "1.0.1"
pretty_assertions = "1.4.0"
rand = "0.8.5"
regex = "1.9.4"
ratatui = "0.23.0"
regex = "1.9.5"
rustyline = { version = "12.0.0", features = ["with-file-history", "derive"] }
serde = { version = "1.0.188", features = ["derive"] }
serde_derive = "1.0.188"
serde_json = "1.0.105"
shellexpand = "3.1.0"
shlex = "1.1.0"
signal-hook = "0.3.17"
strip-ansi-escapes = "0.2.0"
task-hookrs = "0.9.0"
tokio = { version = "1.32.0", features = ["full"] }
tokio-stream = "0.1.14"
ratatui = "0.23.0"
tokio-util = "0.7.8"
tracing = "0.1.37"
tracing-error = "0.2.0"
tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }
tui-logger = { version = "0.9.5", features = ["ratatui-support", "tracing-support"] }
unicode-segmentation = "1.10.1"
unicode-truncate = "0.2.0"
unicode-width = "0.1.10"
Expand All @@ -55,11 +62,10 @@ buildflags = ["--release"]
taskwarrior-tui = { path = "/usr/bin/taskwarrior-tui" }

[profile.release]
debug = 1
incremental = true
lto = "off"
lto = true

[build-dependencies]
clap = { version = "4.4.1", features = ["derive"] }
clap = { version = "4.4.2", features = ["derive"] }
clap_complete = "4.4.0"
shlex = "1.1.0"
54 changes: 54 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,61 @@ fn run_pandoc() -> Result<Output, std::io::Error> {
cmd.output()
}

fn get_commit_hash() {
let git_output = std::process::Command::new("git").args(["rev-parse", "--git-dir"]).output().ok();
let git_dir = git_output.as_ref().and_then(|output| {
std::str::from_utf8(&output.stdout)
.ok()
.and_then(|s| s.strip_suffix('\n').or_else(|| s.strip_suffix("\r\n")))
});

// Tell cargo to rebuild if the head or any relevant refs change.
if let Some(git_dir) = git_dir {
let git_path = std::path::Path::new(git_dir);
let refs_path = git_path.join("refs");
if git_path.join("HEAD").exists() {
println!("cargo:rerun-if-changed={}/HEAD", git_dir);
}
if git_path.join("packed-refs").exists() {
println!("cargo:rerun-if-changed={}/packed-refs", git_dir);
}
if refs_path.join("heads").exists() {
println!("cargo:rerun-if-changed={}/refs/heads", git_dir);
}
if refs_path.join("tags").exists() {
println!("cargo:rerun-if-changed={}/refs/tags", git_dir);
}
}

let git_output = std::process::Command::new("git")
.args(["describe", "--always", "--tags", "--long", "--dirty"])
.output()
.ok();
let git_info = git_output
.as_ref()
.and_then(|output| std::str::from_utf8(&output.stdout).ok().map(str::trim));
let cargo_pkg_version = env!("CARGO_PKG_VERSION");

// Default git_describe to cargo_pkg_version
let mut git_describe = String::from(cargo_pkg_version);

if let Some(git_info) = git_info {
// If the `git_info` contains `CARGO_PKG_VERSION`, we simply use `git_info` as it is.
// Otherwise, prepend `CARGO_PKG_VERSION` to `git_info`.
if git_info.contains(cargo_pkg_version) {
// Remove the 'g' before the commit sha
let git_info = &git_info.replace('g', "");
git_describe = git_info.to_string();
} else {
git_describe = format!("v{}-{}", cargo_pkg_version, git_info);
}
}

println!("cargo:rustc-env=TASKWARRIOR_TUI_GIT_INFO={}", git_describe);
}

fn main() {
get_commit_hash();
let mut app = generate_cli_app();
let name = app.get_name().to_string();
let outdir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("completions/");
Expand Down
4 changes: 2 additions & 2 deletions completions/_taskwarrior-tui
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ _taskwarrior-tui() {
_arguments "${_arguments_options[@]}" \
'-d+[Sets the data folder for taskwarrior-tui]:FOLDER: ' \
'--data=[Sets the data folder for taskwarrior-tui]:FOLDER: ' \
'-c+[Sets the config folder for taskwarrior-tui (currently not used)]:FOLDER: ' \
'--config=[Sets the config folder for taskwarrior-tui (currently not used)]:FOLDER: ' \
'-c+[Sets the config folder for taskwarrior-tui]:FOLDER: ' \
'--config=[Sets the config folder for taskwarrior-tui]:FOLDER: ' \
'--taskdata=[Sets the .task folder using the TASKDATA environment variable for taskwarrior]:FOLDER: ' \
'--taskrc=[Sets the .taskrc file using the TASKRC environment variable for taskwarrior]:FILE: ' \
'-r+[Sets default report]:STRING: ' \
Expand Down
4 changes: 2 additions & 2 deletions completions/_taskwarrior-tui.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ Register-ArgumentCompleter -Native -CommandName 'taskwarrior-tui' -ScriptBlock {
'taskwarrior-tui' {
[CompletionResult]::new('-d', 'd', [CompletionResultType]::ParameterName, 'Sets the data folder for taskwarrior-tui')
[CompletionResult]::new('--data', 'data', [CompletionResultType]::ParameterName, 'Sets the data folder for taskwarrior-tui')
[CompletionResult]::new('-c', 'c', [CompletionResultType]::ParameterName, 'Sets the config folder for taskwarrior-tui (currently not used)')
[CompletionResult]::new('--config', 'config', [CompletionResultType]::ParameterName, 'Sets the config folder for taskwarrior-tui (currently not used)')
[CompletionResult]::new('-c', 'c', [CompletionResultType]::ParameterName, 'Sets the config folder for taskwarrior-tui')
[CompletionResult]::new('--config', 'config', [CompletionResultType]::ParameterName, 'Sets the config folder for taskwarrior-tui')
[CompletionResult]::new('--taskdata', 'taskdata', [CompletionResultType]::ParameterName, 'Sets the .task folder using the TASKDATA environment variable for taskwarrior')
[CompletionResult]::new('--taskrc', 'taskrc', [CompletionResultType]::ParameterName, 'Sets the .taskrc file using the TASKRC environment variable for taskwarrior')
[CompletionResult]::new('-r', 'r', [CompletionResultType]::ParameterName, 'Sets default report')
Expand Down
2 changes: 1 addition & 1 deletion completions/taskwarrior-tui.fish
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
complete -c taskwarrior-tui -s d -l data -d 'Sets the data folder for taskwarrior-tui' -r
complete -c taskwarrior-tui -s c -l config -d 'Sets the config folder for taskwarrior-tui (currently not used)' -r
complete -c taskwarrior-tui -s c -l config -d 'Sets the config folder for taskwarrior-tui' -r
complete -c taskwarrior-tui -l taskdata -d 'Sets the .task folder using the TASKDATA environment variable for taskwarrior' -r
complete -c taskwarrior-tui -l taskrc -d 'Sets the .taskrc file using the TASKRC environment variable for taskwarrior' -r
complete -c taskwarrior-tui -s r -l report -d 'Sets default report' -r
Expand Down
15 changes: 9 additions & 6 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ use std::{
convert::TryInto,
fs, io,
io::{Read, Write},
path::Path,
path::{Path, PathBuf},
sync::{mpsc, Arc, Mutex},
time::{Duration, Instant, SystemTime},
};

use anyhow::{anyhow, Context as AnyhowContext, Result};
use chrono::{DateTime, Datelike, FixedOffset, Local, NaiveDate, NaiveDateTime, TimeZone, Timelike};
use color_eyre::eyre::{anyhow, Context as AnyhowContext, Result};
use crossterm::{
event::{DisableMouseCapture, EnableMouseCapture},
execute,
Expand Down Expand Up @@ -57,7 +57,8 @@ use crate::{
scrollbar::Scrollbar,
table::{Row, Table, TableMode, TableState},
task_report::TaskReportTable,
ui, utils,
ui,
utils::{self, get_data_dir},
};

const MAX_LINE: usize = 4096;
Expand Down Expand Up @@ -240,7 +241,7 @@ impl TaskwarriorTui {
.output()
.context("Unable to run `task --version`")?;

let task_version = Versioning::new(String::from_utf8_lossy(&output.stdout).trim()).context("Unable to get version string")?;
let task_version = Versioning::new(String::from_utf8_lossy(&output.stdout).trim()).ok_or(anyhow!("Unable to get version string"))?;

let (w, h) = crossterm::terminal::size().unwrap_or((50, 15));

Expand All @@ -251,6 +252,8 @@ impl TaskwarriorTui {
};
let event_loop = crate::event::EventLoop::new(tick_rate, init_event_loop);

let data_dir = get_data_dir();

let mut app = Self {
should_quit: false,
dirty: true,
Expand Down Expand Up @@ -280,8 +283,8 @@ impl TaskwarriorTui {
keyconfig: kc,
terminal_width: w,
terminal_height: h,
filter_history: HistoryContext::new("filter.history"),
command_history: HistoryContext::new("command.history"),
filter_history: HistoryContext::new("filter.history", data_dir.clone()),
command_history: HistoryContext::new("command.history", data_dir.clone()),
history_status: None,
completion_list: CompletionList::with_items(vec![]),
show_completion_pane: false,
Expand Down
2 changes: 1 addition & 1 deletion src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub fn generate_cli_app() -> clap::Command {
.short('c')
.long("config")
.value_name("FOLDER")
.help("Sets the config folder for taskwarrior-tui (currently not used)")
.help("Sets the config folder for taskwarrior-tui")
.action(clap::ArgAction::Set),
)
.arg(
Expand Down
8 changes: 4 additions & 4 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{collections::HashMap, error::Error, str};

use anyhow::{Context, Result};
use color_eyre::eyre::{eyre, Context, Result};
use ratatui::{
style::{Color, Modifier, Style},
symbols::{bar::FULL, line::DOUBLE_VERTICAL},
Expand Down Expand Up @@ -465,14 +465,14 @@ impl Config {

fn get_rule_precedence_color(data: &str) -> Vec<String> {
let data = Self::get_config("rule.precedence.color", data)
.context("Unable to parse `task show rule.precedence.color`.")
.ok_or_else(|| eyre!("Unable to parse `task show rule.precedence.color`."))
.unwrap();
data.split(',').map(ToString::to_string).collect::<Vec<_>>()
}

fn get_uda_priority_values(data: &str) -> Vec<String> {
let data = Self::get_config("uda.priority.values", data)
.context("Unable to parse `task show uda.priority.values`.")
.ok_or_else(|| eyre!("Unable to parse `task show uda.priority.values`."))
.unwrap();
data.split(',').map(ToString::to_string).collect::<Vec<_>>()
}
Expand All @@ -489,7 +489,7 @@ impl Config {

fn get_data_location(data: &str) -> String {
Self::get_config("data.location", data)
.context("Unable to parse `task show data.location`.")
.ok_or_else(|| eyre!("Unable to parse `task show data.location`."))
.unwrap()
}

Expand Down
12 changes: 2 additions & 10 deletions src/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{
path::{Path, PathBuf},
};

use anyhow::{anyhow, Result};
use color_eyre::eyre::{anyhow, Result};
use rustyline::{
error::ReadlineError,
history::{DefaultHistory, History, SearchDirection},
Expand All @@ -16,17 +16,9 @@ pub struct HistoryContext {
}

impl HistoryContext {
pub fn new(filename: &str) -> Self {
pub fn new(filename: &str, data_path: PathBuf) -> Self {
let history = DefaultHistory::new();

let data_path = if let Ok(s) = std::env::var("TASKWARRIOR_TUI_DATA") {
PathBuf::from(s)
} else {
dirs::data_local_dir()
.map(|d| d.join("taskwarrior-tui"))
.expect("Unable to create configuration directory for taskwarrior-tui")
};

std::fs::create_dir_all(&data_path).unwrap_or_else(|_| panic!("Unable to create configuration directory in {:?}", &data_path));

let data_path = data_path.join(filename);
Expand Down
2 changes: 1 addition & 1 deletion src/keyconfig.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{collections::HashSet, error::Error, hash::Hash};

use anyhow::{anyhow, Result};
use color_eyre::eyre::{anyhow, Result};
use log::{error, info, warn};
use serde::{Deserialize, Serialize};

Expand Down
Loading

0 comments on commit f238239

Please sign in to comment.