Skip to content

Commit

Permalink
Add auto-color feature and other improvements (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
mondeja authored Oct 18, 2024
1 parent d9ad41f commit 0f1e366
Show file tree
Hide file tree
Showing 8 changed files with 173 additions and 104 deletions.
16 changes: 14 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
# CHANGELOG

## 2024-10-18 - [0.1.5]
## 2024-10-18 - [0.2.0]

### Breaking changes

- `--no-color` CLI flag has been removed. Use `NO_COLOR` environment variable
instead.
- `-f` short CLI flag has been removed. Use `--fix` instead.

### New features

- Add `auto-color` compilation feature enabled by default to automatically
detect if your terminal supports colors.

### Enhancements

- Reduce distributed binary sizes ~80%.
- Drop `clap-derive` dependency.
- Drop `colored` dependency.
- Generate man page at compile time.

## 2024-09-29 - [0.1.4]

Expand Down Expand Up @@ -42,7 +54,7 @@

First beta release

[0.1.5]: https://github.com/mondeja/hledger-fmt/compare/v0.1.4...master
[0.2.0]: https://github.com/mondeja/hledger-fmt/compare/v0.1.4...v0.2.0
[0.1.4]: https://github.com/mondeja/hledger-fmt/compare/v0.1.3...v0.1.4
[0.1.3]: https://github.com/mondeja/hledger-fmt/compare/v0.1.2...v0.1.3
[0.1.2]: https://github.com/mondeja/hledger-fmt/compare/v0.1.1...v0.1.2
Expand Down
19 changes: 18 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 13 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "hledger-fmt"
version = "0.1.5"
version = "0.2.0"
edition = "2021"
description = "An opinionated hledger's journal files formatter."
repository = "https://github.com/mondeja/hledger-fmt"
Expand All @@ -19,22 +19,20 @@ exclude = [
".vscode",
]

[lib]
path = "src/lib.rs"

[[bin]]
name = "hledger-fmt"

[dependencies]
clap = { version = "4", default-features = false, features = ["std", "help"] }
clap.workspace = true
walkdir = "2"
similar = "2"
anstream = { version = "0.6", optional = true }
anstyle = { version = "1", optional = true }
anstream = { version = "0.6", optional = true, default-features = false }
anstyle = { version = "1", optional = true, default-features = false }

[features]
default = ["color"]
default = ["color", "auto-color"]
color = ["dep:anstream", "dep:anstyle", "clap/color"]
auto-color = ["anstream?/auto", "anstream?/wincon"]

[profile.release]
strip = true
Expand All @@ -45,3 +43,10 @@ panic = "abort"

[workspace]
members = ["."]

[workspace.dependencies]
clap = { version = "4", default-features = false, features = ["std", "help"] }

[build-dependencies]
clap.workspace = true
clap_mangen = "0.2"
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ See `hledger-fmt --help` for more information.
## Features

- **`color`** (enabled by default): Build with terminal color support.
- **`auto-color`** (enabled by default): Automatically detects if your terminal
supports colors.

[cargo-binstall]: https://github.com/cargo-bins/cargo-binstall
[hledger]: https://hledger.org
Expand Down
40 changes: 40 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use clap_mangen::Man;
use std::{
env,
fs::File,
io::Error,
path::{Path, PathBuf},
};

include!("src/cli.rs");

fn build_manpages(outdir: &Path) -> Result<(), Error> {
let app = cli();

let file = Path::new(&outdir).join("example.1");
let mut file = File::create(&file)?;

Man::new(app).render(&mut file)?;

Ok(())
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("cargo:rerun-if-changed=src/cli.rs");
println!("cargo:rerun-if-changed=man");

let outdir = match env::var_os("OUT_DIR") {
None => return Ok(()),
Some(outdir) => outdir,
};

// Create `target/assets/` folder.
let out_path = PathBuf::from(outdir);
let mut path = out_path.ancestors().nth(4).unwrap().to_owned();
path.push("assets");
std::fs::create_dir_all(&path).unwrap();

build_manpages(&path)?;

Ok(())
}
61 changes: 61 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use clap::{value_parser, Arg, ArgAction, Command};

pub fn cli() -> Command {
Command::new("hledger-fmt")
.long_about("An opinionated hledger's journal files formatter.")
.override_usage(concat!("hledger-fmt [OPTIONS] [FILES]...\n"))
.arg(
Arg::new("files")
.help(concat!(
"Paths of files to format. To read from STDIN pass '-'.\n",
"\n",
"If not defined, hledger-fmt will search for hledger files in the",
" current directory and its subdirectories (those that have the",
" extensions '.journal', '.hledger' or '.j').",
" If the paths passed are directories, hledger-fmt will search for",
" hledger files in those directories and their subdirectories.",
))
.action(ArgAction::Append)
.value_parser(value_parser!(String))
.value_name("FILES")
.num_args(1..),
)
.arg(
Arg::new("fix")
.long("fix")
.help(concat!(
"Fix the files in place. WARNING: this is a potentially destructive",
" operation, make sure to make a backup of your files or print the diff",
" first. If not passed, hledger-fmt will print the diff between the",
" original and the formatted file."
))
.action(ArgAction::SetTrue),
)
.arg(
Arg::new("no-diff")
.long("no-diff")
.help(concat!(
"Don't print diff between original and formatted files,",
" but formatted content instead."
))
.action(ArgAction::SetTrue),
)
.disable_help_flag(true)
.arg(
Arg::new("help")
.short('h')
.long("help")
.help("Print help.")
.action(ArgAction::Help),
)
.disable_version_flag(true)
.version(env!("CARGO_PKG_VERSION"))
.arg(
Arg::new("version")
.short('V')
.long("version")
.help("Print version.")
.action(ArgAction::Version),
)
.after_help("To disable colors in the output, use the environment variable NO_COLOR.")
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
mod cli;
pub(crate) mod common;
pub mod formatter;
pub mod parser;

pub use cli::cli;
115 changes: 22 additions & 93 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,70 +1,9 @@
use clap::{value_parser, Arg, ArgAction, ArgMatches, Command};
use similar::{ChangeTag, TextDiff};
use std::ffi::OsStr;
use walkdir::WalkDir;

fn cli() -> ArgMatches {
let cmd = Command::new("hledger-fmt")
.version(env!("CARGO_PKG_VERSION"))
.about("An opinionated hledger's journal files formatter.")
.override_usage(concat!("hledger-fmt [OPTIONS] [files...]\n",))
.arg(
Arg::new("files")
.help(concat!(
"Paths of files to format. To read from STDIN pass '-'.\n",
"\n",
"If not defined, hledger-fmt will search for hledger files in the",
" current directory and its subdirectories (those that have the",
" extensions '.journal', '.hledger' or '.j').",
" If the paths passed are directories, hledger-fmt will search for",
" hledger files in those directories and their subdirectories.",
))
.action(ArgAction::Append)
.value_parser(value_parser!(String))
.value_name("files")
.num_args(1..),
)
.arg(
Arg::new("fix")
.short('f')
.long("fix")
.help(concat!(
"Fix the files in place.\n",
"\n",
"If not passed, hledger-fmt will print the diff between the original",
" and the formatted file. WARNING: this is a potentially destructive",
" operation, make sure to make a backup of your files or print the diff",
" first."
))
.action(ArgAction::SetTrue),
)
.arg(
Arg::new("no-diff")
.long("no-diff")
.help(concat!(
"Do not print the diff between original and formatted files,",
" but the new formatted content."
))
.action(ArgAction::SetTrue),
);

#[cfg(feature = "color")]
let cmd = cmd.arg(
Arg::new("no-color")
.long("no-color")
.help(concat!(
"Do not use colors in the output.\n",
"\n",
"You can also use the environment variable NO_COLOR to disable colors."
))
.action(ArgAction::SetTrue),
);

cmd.get_matches()
}

fn main() {
let args = cli();
let args = hledger_fmt::cli().get_matches();
let files_arg: Vec<String> = if let Some(files) = args.get_many("files") {
files.cloned().collect()
} else {
Expand Down Expand Up @@ -140,8 +79,6 @@ fn main() {
std::process::exit(exitcode);
}

#[cfg(feature = "color")]
let no_color = args.get_flag("no-color") || std::env::var("NO_COLOR").is_ok();
let mut something_printed = false;
let n_files = files.len();

Expand Down Expand Up @@ -206,35 +143,6 @@ fn main() {

let diff = TextDiff::from_lines(&content, &formatted);
for change in diff.iter_all_changes() {
#[cfg(feature = "color")]
{
let line = if no_color {
match change.tag() {
ChangeTag::Delete => format!("- {change}"),
ChangeTag::Insert => format!("+ {change}"),
ChangeTag::Equal => format!(" {change}"),
}
} else {
match change.tag() {
ChangeTag::Delete => {
let bright_red = anstyle::Style::new()
.fg_color(Some(anstyle::AnsiColor::BrightRed.into()));
format!("{bright_red}- {change}{bright_red:#}")
}
ChangeTag::Insert => {
let bright_green = anstyle::Style::new()
.fg_color(Some(anstyle::AnsiColor::BrightGreen.into()));
format!("{bright_green}+ {change}{bright_green:#}")
}
ChangeTag::Equal => {
let dimmed = anstyle::Style::new().dimmed();
format!("{dimmed} {change}{dimmed:#}")
}
}
};
anstream::eprint!("{line}");
}

#[cfg(not(feature = "color"))]
{
let line = match change.tag() {
Expand All @@ -244,6 +152,27 @@ fn main() {
};
eprint!("{line}");
}

#[cfg(feature = "color")]
{
let line = match change.tag() {
ChangeTag::Delete => {
let bright_red = anstyle::Style::new()
.fg_color(Some(anstyle::AnsiColor::BrightRed.into()));
format!("{bright_red}- {change}{bright_red:#}")
}
ChangeTag::Insert => {
let bright_green = anstyle::Style::new()
.fg_color(Some(anstyle::AnsiColor::BrightGreen.into()));
format!("{bright_green}+ {change}{bright_green:#}")
}
ChangeTag::Equal => {
let dimmed = anstyle::Style::new().dimmed();
format!("{dimmed} {change}{dimmed:#}")
}
};
anstream::eprint!("{line}");
}
}
}
}
Expand Down

0 comments on commit 0f1e366

Please sign in to comment.