Skip to content

Commit

Permalink
🐛 zx: open file only once
Browse files Browse the repository at this point in the history
  • Loading branch information
FineFindus committed Jan 20, 2024
1 parent 3468d59 commit b89f7db
Showing 1 changed file with 29 additions and 23 deletions.
52 changes: 29 additions & 23 deletions zbus_xmlgen/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ use zvariant::ObjectPath;

mod cli;

enum OutputTarget {
SingleFile(File),
Stdout,
MultipleFiles,
}

fn main() -> Result<(), Box<dyn Error>> {
let args = cli::Args::parse();

Expand Down Expand Up @@ -54,6 +60,15 @@ fn main() -> Result<(), Box<dyn Error>> {
.iter()
.partition(|&i| i.name().starts_with(fdo_iface_prefix));

let mut output_target = match args.output.as_deref() {
Some("-") => OutputTarget::Stdout,
Some(path) => {
let file = OpenOptions::new().create(true).write(true).open(path)?;
OutputTarget::SingleFile(file)
}
_ => OutputTarget::MultipleFiles,
};

for interface in needed_ifaces {
let output = write_interfaces(
&[&interface],
Expand All @@ -62,29 +77,20 @@ fn main() -> Result<(), Box<dyn Error>> {
path.clone(),
&input_src,
)?;
match args.output.as_deref() {
Some("-") => println!("{}", output),
Some(path) => {
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(path)
.expect("Failed to open file");
file.write_all(output.as_bytes())?;
}
_ => {
std::fs::write(
format!(
"{}.rs",
interface
.name()
.split('.')
.last()
.expect("Failed to split name")
),
output,
)?;
}
match output_target {
OutputTarget::Stdout => println!("{}", output),
OutputTarget::SingleFile(ref mut file) => file.write_all(output.as_bytes())?,
OutputTarget::MultipleFiles => std::fs::write(
format!(
"{}.rs",
interface
.name()
.split('.')
.last()
.expect("Failed to split name")
),
output,
)?,
};
}

Expand Down

0 comments on commit b89f7db

Please sign in to comment.