Skip to content

Commit 4290aa1

Browse files
author
z3r0yu
committed
fix issue #2
1 parent cdee5bd commit 4290aa1

File tree

2 files changed

+25
-11
lines changed

2 files changed

+25
-11
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,4 @@ Cargo.lock
1212

1313
# MSVC Windows builds of rustc generate these, which store debugging information
1414
*.pdb
15+
*.txt

src/main.rs

+24-11
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
use std::fs::{File, OpenOptions};
1+
use std::fs::{self, File, OpenOptions};
22
use std::io::{self, BufRead, BufReader, BufWriter, Write};
3+
use std::path::Path;
34
use std::str;
45

56
use clap::Parser;
@@ -39,11 +40,18 @@ struct Options {
3940

4041
fn main() -> io::Result<()> {
4142
let args = Options::parse();
43+
44+
// Ensure the directories in the filepath exist before attempting to open the file
45+
if let Some(parent) = Path::new(&args.filepath).parent() {
46+
fs::create_dir_all(parent)?;
47+
}
48+
4249
let mut lines = load_file(&args)?;
4350

4451
if args.rewrite && !args.dry_run {
4552
let file = OpenOptions::new()
4653
.write(true)
54+
.create(true)
4755
.truncate(true)
4856
.open(&args.filepath)?;
4957
let mut writer = BufWriter::new(file);
@@ -83,6 +91,7 @@ fn main() -> io::Result<()> {
8391

8492
let soet_file = OpenOptions::new()
8593
.write(true)
94+
.create(true)
8695
.truncate(true)
8796
.open(&args.filepath)?;
8897
let mut soet_writer = BufWriter::new(soet_file);
@@ -96,18 +105,22 @@ fn main() -> io::Result<()> {
96105
}
97106

98107
fn load_file(args: &Options) -> Result<IndexSet<String>, io::Error> {
99-
let file = File::open(&args.filepath)?;
100-
let reader = BufReader::new(file);
101-
let mut lines = IndexSet::new();
102-
103-
for line in reader.lines() {
104-
let line = line?;
105-
if should_add_line(args, &lines, &line) {
106-
lines.insert(line);
108+
match File::open(&args.filepath) {
109+
Ok(file) => {
110+
let reader = BufReader::new(file);
111+
let mut lines = IndexSet::new();
112+
113+
for line in reader.lines() {
114+
let line = line?;
115+
if should_add_line(args, &lines, &line) {
116+
lines.insert(line);
117+
}
118+
}
119+
120+
Ok(lines)
107121
}
122+
Err(_) => Ok(IndexSet::new()), // If the file does not exist, return an empty set of lines
108123
}
109-
110-
Ok(lines)
111124
}
112125

113126
fn should_add_line(args: &Options, lines: &IndexSet<String>, line: &str) -> bool {

0 commit comments

Comments
 (0)