feat(args): add --write flag for only enabling the write mode

This commit is contained in:
Orhun Parmaksız 2021-12-15 13:15:44 +03:00
parent 7d3ac997d2
commit 5a4933fcbd
No known key found for this signature in database
GPG key ID: F83424824B3E4B90
3 changed files with 18 additions and 3 deletions

View file

@ -118,7 +118,12 @@ impl<'a> App<'a> {
}
/// Updates the parameter if it has the format `name=value`, displays it otherwise.
pub fn process_parameter(&mut self, mut parameter: String, display_value: bool) -> Result<()> {
pub fn process_parameter(
&mut self,
mut parameter: String,
display_value: bool,
write_mode: bool,
) -> Result<()> {
let new_value = if parameter.contains('=') {
let fields = parameter
.split('=')
@ -142,6 +147,12 @@ impl<'a> App<'a> {
param.update_value(&new_value, &config, &mut self.stdout)?;
}
}
} else if write_mode {
eprintln!(
"{}: {:?} must be in the format: name=value",
env!("CARGO_PKG_NAME"),
parameter
);
} else if display_value {
self.sysctl
.get_parameters(&parameter)
@ -166,7 +177,7 @@ impl<'a> App<'a> {
}
let contents = reader::read_to_string(path)?;
for parameter in contents.lines() {
self.process_parameter(parameter.to_string(), false)?;
self.process_parameter(parameter.to_string(), false, false)?;
}
Ok(())
}

View file

@ -22,6 +22,8 @@ pub struct Args {
pub verbose: bool,
/// Whether if the quiet mode is enabled.
pub quiet: bool,
/// Whether if only the write mode is enabled.
pub write: bool,
/// Path of the Linux kernel documentation.
pub kernel_docs: Option<PathBuf>,
/// Display type of the variables.
@ -67,6 +69,7 @@ impl Args {
"<expr>",
);
opts.optflag("q", "quiet", "do not print variable after the value is set");
opts.optflag("w", "write", "only enable writing a value to variable");
opts.optflag("d", "", "alias of -h");
opts.optflag(
"E",
@ -141,6 +144,7 @@ impl Args {
Some(Args {
verbose: matches.opt_present("v"),
quiet: matches.opt_present("q"),
write: matches.opt_present("w"),
kernel_docs: matches.opt_str("d").map(PathBuf::from),
display_type,
display_deprecated: matches.opt_present("D"),

View file

@ -41,7 +41,7 @@ pub fn run(args: Args) -> Result<()> {
}
} else {
for param in args.values {
app.process_parameter(param, true)?;
app.process_parameter(param, true, args.write)?;
}
}