1
- use std:: fs:: { File , OpenOptions } ;
1
+ use std:: fs:: { self , File , OpenOptions } ;
2
2
use std:: io:: { self , BufRead , BufReader , BufWriter , Write } ;
3
+ use std:: path:: Path ;
3
4
use std:: str;
4
5
5
6
use clap:: Parser ;
@@ -39,11 +40,18 @@ struct Options {
39
40
40
41
fn main ( ) -> io:: Result < ( ) > {
41
42
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
+
42
49
let mut lines = load_file ( & args) ?;
43
50
44
51
if args. rewrite && !args. dry_run {
45
52
let file = OpenOptions :: new ( )
46
53
. write ( true )
54
+ . create ( true )
47
55
. truncate ( true )
48
56
. open ( & args. filepath ) ?;
49
57
let mut writer = BufWriter :: new ( file) ;
@@ -83,6 +91,7 @@ fn main() -> io::Result<()> {
83
91
84
92
let soet_file = OpenOptions :: new ( )
85
93
. write ( true )
94
+ . create ( true )
86
95
. truncate ( true )
87
96
. open ( & args. filepath ) ?;
88
97
let mut soet_writer = BufWriter :: new ( soet_file) ;
@@ -96,18 +105,22 @@ fn main() -> io::Result<()> {
96
105
}
97
106
98
107
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)
107
121
}
122
+ Err ( _) => Ok ( IndexSet :: new ( ) ) , // If the file does not exist, return an empty set of lines
108
123
}
109
-
110
- Ok ( lines)
111
124
}
112
125
113
126
fn should_add_line ( args : & Options , lines : & IndexSet < String > , line : & str ) -> bool {
0 commit comments