summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/bcachefs.rs33
-rw-r--r--src/commands/completions.rs3
-rw-r--r--src/commands/list.rs29
-rw-r--r--src/commands/logger.rs28
-rw-r--r--src/commands/mod.rs1
-rw-r--r--src/commands/mount.rs31
-rw-r--r--src/commands/subvolume.rs15
-rw-r--r--src/logging.rs26
8 files changed, 82 insertions, 84 deletions
diff --git a/src/bcachefs.rs b/src/bcachefs.rs
index e5776ec0..26422abd 100644
--- a/src/bcachefs.rs
+++ b/src/bcachefs.rs
@@ -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);
@@ -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") {
@@ -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()),
}
}
diff --git a/src/commands/completions.rs b/src/commands/completions.rs
index d4e98569..e05934ca 100644
--- a/src/commands/completions.rs
+++ b/src/commands/completions.rs
@@ -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
}
diff --git a/src/commands/list.rs b/src/commands/list.rs
index 77f53b4f..b1bf144a 100644
--- a/src/commands/list.rs
+++ b/src/commands/list.rs
@@ -1,3 +1,4 @@
+use anyhow::Result;
use bch_bindgen::bcachefs;
use bch_bindgen::bkey::BkeySC;
use bch_bindgen::btree::BtreeIter;
@@ -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(
@@ -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>,
@@ -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);
}
@@ -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)
}
diff --git a/src/commands/logger.rs b/src/commands/logger.rs
deleted file mode 100644
index a24bcbda..00000000
--- a/src/commands/logger.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-use colored::Colorize;
-use log::{Level, Metadata, Record};
-
-pub struct SimpleLogger;
-
-impl log::Log for SimpleLogger {
- fn enabled(&self, _: &Metadata) -> bool {
- true
- }
-
- fn log(&self, record: &Record) {
- let debug_prefix = match record.level() {
- Level::Error => "ERROR".bright_red(),
- Level::Warn => "WARN".bright_yellow(),
- Level::Info => "INFO".green(),
- Level::Debug => "DEBUG".bright_blue(),
- Level::Trace => "TRACE".into(),
- };
- eprintln!(
- "{} - {}: {}",
- debug_prefix,
- record.module_path().unwrap_or_default().bright_black(),
- record.args()
- );
- }
-
- fn flush(&self) {}
-}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index e873a46d..7f466f92 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -2,7 +2,6 @@ use clap::Subcommand;
pub mod completions;
pub mod list;
-pub mod logger;
pub mod mount;
pub mod subvolume;
diff --git a/src/commands/mount.rs b/src/commands/mount.rs
index 18b4aae5..235a1825 100644
--- a/src/commands/mount.rs
+++ b/src/commands/mount.rs
@@ -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,
@@ -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,
@@ -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.
@@ -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!(),
- });
+ // TODO: centralize this on the top level CLI
+ logging::setup(cli.quiet, cli.verbose, cli.colorize);
- colored::control::set_override(cli.colorize);
- if let Err(e) = cmd_mount_inner(&cli) {
- error!("Fatal error: {}", e);
- 1
- } else {
- info!("Successfully mounted");
- 0
- }
+ cmd_mount_inner(&cli)
}
diff --git a/src/commands/subvolume.rs b/src/commands/subvolume.rs
index b059ff4a..bb0141c4 100644
--- a/src/commands/subvolume.rs
+++ b/src/commands/subvolume.rs
@@ -1,5 +1,6 @@
use std::{env, path::PathBuf};
+use anyhow::{Context, Result};
use bch_bindgen::c::BCH_SUBVOL_SNAPSHOT_RO;
use clap::{Parser, Subcommand};
@@ -36,7 +37,7 @@ enum Subcommands {
},
}
-pub fn subvolume(argv: Vec<String>) -> i32 {
+pub fn subvolume(argv: Vec<String>) -> Result<()> {
let cli = Cli::parse_from(argv);
match cli.subcommands {
@@ -47,25 +48,25 @@ pub fn subvolume(argv: Vec<String>) -> i32 {
} else {
env::current_dir()
.map(|p| p.join(target))
- .expect("unable to get current directory")
+ .context("unable to get current directory")?
};
if let Some(dirname) = target.parent() {
let fs = unsafe { BcachefsHandle::open(dirname) };
fs.create_subvolume(target)
- .expect("Failed to create the subvolume");
+ .context("Failed to create the subvolume")?;
}
}
}
Subcommands::Delete { target } => {
let target = target
.canonicalize()
- .expect("subvolume path does not exist or can not be canonicalized");
+ .context("subvolume path does not exist or can not be canonicalized")?;
if let Some(dirname) = target.parent() {
let fs = unsafe { BcachefsHandle::open(dirname) };
fs.delete_subvolume(target)
- .expect("Failed to delete the subvolume");
+ .context("Failed to delete the subvolume")?;
}
}
Subcommands::Snapshot {
@@ -91,10 +92,10 @@ pub fn subvolume(argv: Vec<String>) -> i32 {
source,
dest,
)
- .expect("Failed to snapshot the subvolume");
+ .context("Failed to snapshot the subvolume")?;
}
}
}
- 0
+ Ok(())
}
diff --git a/src/logging.rs b/src/logging.rs
new file mode 100644
index 00000000..dee99881
--- /dev/null
+++ b/src/logging.rs
@@ -0,0 +1,26 @@
+use env_logger::WriteStyle;
+use log::LevelFilter;
+
+pub fn setup(quiet: bool, verbose: u8, color: bool) {
+ let level_filter = if quiet {
+ LevelFilter::Off
+ } else {
+ match verbose {
+ 0 => LevelFilter::Info,
+ 1 => LevelFilter::Debug,
+ _ => LevelFilter::Trace,
+ }
+ };
+
+ let style = if color {
+ WriteStyle::Always
+ } else {
+ WriteStyle::Never
+ };
+
+ env_logger::Builder::new()
+ .filter_level(level_filter)
+ .write_style(style)
+ .parse_env("BCACHEFS_LOG")
+ .init();
+}