Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve logging and exiting #309

Merged
merged 3 commits into from
Jun 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 49 additions & 13 deletions Cargo.lock

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

6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ path = "src/bcachefs.rs"

[dependencies]
log = { version = "0.4", features = ["std"] }
colored = "2"
clap = { version = "4.0.32", features = ["derive", "wrap_help"] }
clap_complete = "4.3.2"
anyhow = "1.0"
Expand All @@ -26,3 +25,8 @@ byteorder = "1.3"
strum = { version = "0.26", features = ["derive"] }
strum_macros = "0.26"
zeroize = { version = "1", features = ["std", "zeroize_derive"] }

[dependencies.env_logger]
version = "0.10"
default-features = false
features = ["auto-color"]
33 changes: 16 additions & 17 deletions src/bcachefs.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
mod commands;
mod key;
mod logging;
mod wrappers;

use std::ffi::{c_char, CString};
use std::{
ffi::{c_char, CString},
process::{ExitCode, Termination},
};

use bch_bindgen::c;
use commands::logger::SimpleLogger;

#[derive(Debug)]
pub struct ErrnoError(pub errno::Errno);
Expand Down Expand Up @@ -71,7 +74,7 @@ fn handle_c_command(mut argv: Vec<String>, symlink_cmd: Option<&str>) -> i32 {
}
}

fn main() {
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().collect();

let symlink_cmd: Option<&str> = if args[0].contains("mkfs") {
Expand All @@ -89,28 +92,24 @@ fn main() {
if symlink_cmd.is_none() && args.len() < 2 {
println!("missing command");
unsafe { c::bcachefs_usage() };
std::process::exit(1);
return ExitCode::from(1);
}

unsafe { c::raid_init() };

log::set_boxed_logger(Box::new(SimpleLogger)).unwrap();
log::set_max_level(log::LevelFilter::Warn);

let cmd = match symlink_cmd {
Some(s) => s,
None => args[1].as_str(),
};

let ret = match cmd {
"completions" => commands::completions(args[1..].to_vec()),
"list" => commands::list(args[1..].to_vec()),
"mount" => commands::mount(args, symlink_cmd),
"subvolume" => commands::subvolume(args[1..].to_vec()),
_ => handle_c_command(args, symlink_cmd),
};

if ret != 0 {
std::process::exit(1);
match cmd {
"completions" => {
commands::completions(args[1..].to_vec());
ExitCode::SUCCESS
}
"list" => commands::list(args[1..].to_vec()).report(),
"mount" => commands::mount(args, symlink_cmd).report(),
"subvolume" => commands::subvolume(args[1..].to_vec()).report(),
_ => ExitCode::from(u8::try_from(handle_c_command(args, symlink_cmd)).unwrap()),
}
}
3 changes: 1 addition & 2 deletions src/commands/completions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout());
}

pub fn completions(argv: Vec<String>) -> i32 {
pub fn completions(argv: Vec<String>) {
let cli = Cli::parse_from(argv);
print_completions(cli.shell, &mut super::Cli::command());
0
}
29 changes: 17 additions & 12 deletions src/commands/list.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use anyhow::Result;
use bch_bindgen::bcachefs;
use bch_bindgen::bkey::BkeySC;
use bch_bindgen::btree::BtreeIter;
Expand All @@ -7,9 +8,10 @@ use bch_bindgen::btree::BtreeTrans;
use bch_bindgen::fs::Fs;
use bch_bindgen::opt_set;
use clap::Parser;
use log::error;
use std::io::{stdout, IsTerminal};

use crate::logging;

fn list_keys(fs: &Fs, opt: &Cli) -> anyhow::Result<()> {
let trans = BtreeTrans::new(fs);
let mut iter = BtreeIter::new(
Expand Down Expand Up @@ -145,13 +147,18 @@ pub struct Cli {
#[arg(short, long)]
fsck: bool,

// FIXME: would be nicer to have `--color[=WHEN]` like diff or ls?
/// Force color on/off. Default: autodetect tty
#[arg(short, long, action = clap::ArgAction::Set, default_value_t=stdout().is_terminal())]
colorize: bool,

/// Verbose mode
/// Quiet mode
#[arg(short, long)]
verbose: bool,
quiet: bool,

/// Verbose mode
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,

#[arg(required(true))]
devices: Vec<std::path::PathBuf>,
Expand Down Expand Up @@ -180,7 +187,7 @@ fn cmd_list_inner(opt: &Cli) -> anyhow::Result<()> {
opt_set!(fs_opts, norecovery, 0);
}

if opt.verbose {
if opt.verbose > 0 {
opt_set!(fs_opts, verbose, 1);
}

Expand All @@ -194,13 +201,11 @@ fn cmd_list_inner(opt: &Cli) -> anyhow::Result<()> {
}
}

pub fn list(argv: Vec<String>) -> i32 {
pub fn list(argv: Vec<String>) -> Result<()> {
let opt = Cli::parse_from(argv);
colored::control::set_override(opt.colorize);
if let Err(e) = cmd_list_inner(&opt) {
error!("Fatal error: {}", e);
1
} else {
0
}

// TODO: centralize this on the top level CLI
logging::setup(opt.quiet, opt.verbose, opt.colorize);

cmd_list_inner(&opt)
}
28 changes: 0 additions & 28 deletions src/commands/logger.rs

This file was deleted.

1 change: 0 additions & 1 deletion src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use clap::Subcommand;

pub mod completions;
pub mod list;
pub mod logger;
pub mod mount;
pub mod subvolume;

Expand Down
33 changes: 15 additions & 18 deletions src/commands/mount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ use std::{
use anyhow::{ensure, Result};
use bch_bindgen::{bcachefs, bcachefs::bch_sb_handle, opt_set, path_to_cstr};
use clap::Parser;
use log::{debug, error, info, LevelFilter};
use log::{debug, info};
use uuid::Uuid;

use crate::key::{KeyHandle, Passphrase, UnlockPolicy};
use crate::{
key::{KeyHandle, Passphrase, UnlockPolicy},
logging,
};

fn mount_inner(
src: String,
Expand Down Expand Up @@ -242,10 +245,15 @@ pub struct Cli {
#[arg(short, default_value = "")]
options: String,

// FIXME: would be nicer to have `--color[=WHEN]` like diff or ls?
/// Force color on/off. Autodetect tty is used to define default:
#[arg(short, long, action = clap::ArgAction::Set, default_value_t=stdout().is_terminal())]
colorize: bool,

/// Quiet mode
#[arg(short, long)]
quiet: bool,

/// Verbose mode
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
Expand Down Expand Up @@ -364,7 +372,7 @@ fn cmd_mount_inner(cli: &Cli) -> Result<()> {
}
}

pub fn mount(mut argv: Vec<String>, symlink_cmd: Option<&str>) -> i32 {
pub fn mount(mut argv: Vec<String>, symlink_cmd: Option<&str>) -> Result<()> {
// If the bcachefs tool is being called as "bcachefs mount dev ..." (as opposed to via a
// symlink like "/usr/sbin/mount.bcachefs dev ...", then we need to pop the 0th argument
// ("bcachefs") since the CLI parser here expects the device at position 1.
Expand All @@ -374,19 +382,8 @@ pub fn mount(mut argv: Vec<String>, symlink_cmd: Option<&str>) -> i32 {

let cli = Cli::parse_from(argv);

// @TODO : more granular log levels via mount option
log::set_max_level(match cli.verbose {
0 => LevelFilter::Warn,
1 => LevelFilter::Trace,
2_u8..=u8::MAX => todo!(),
});

colored::control::set_override(cli.colorize);
if let Err(e) = cmd_mount_inner(&cli) {
error!("Fatal error: {}", e);
1
} else {
info!("Successfully mounted");
0
}
// TODO: centralize this on the top level CLI
logging::setup(cli.quiet, cli.verbose, cli.colorize);

cmd_mount_inner(&cli)
}
Loading