@@ -8,32 +8,43 @@ use std::env;
88
99use std:: fs;
1010use std:: io:: { self , Write } ;
11+ use std:: process:: { exit, ExitCode } ;
1112
1213mod context_diff;
1314mod ed_diff;
1415mod normal_diff;
1516mod params;
1617mod unified_diff;
1718
18- fn main ( ) -> Result < ( ) , String > {
19+ // Exit codes are documented at
20+ // https://www.gnu.org/software/diffutils/manual/html_node/Invoking-diff.html.
21+ // An exit status of 0 means no differences were found,
22+ // 1 means some differences were found,
23+ // and 2 means trouble.
24+ fn main ( ) -> ExitCode {
1925 let opts = env:: args_os ( ) ;
2026 let Params {
2127 from,
2228 to,
2329 context_count,
2430 format,
25- } = parse_params ( opts) ?;
31+ } = parse_params ( opts) . unwrap_or_else ( |error| {
32+ eprintln ! ( "{error}" ) ;
33+ exit ( 2 ) ;
34+ } ) ;
2635 // read files
2736 let from_content = match fs:: read ( & from) {
2837 Ok ( from_content) => from_content,
2938 Err ( e) => {
30- return Err ( format ! ( "Failed to read from-file: {e}" ) ) ;
39+ eprintln ! ( "Failed to read from-file: {e}" ) ;
40+ return ExitCode :: from ( 2 ) ;
3141 }
3242 } ;
3343 let to_content = match fs:: read ( & to) {
3444 Ok ( to_content) => to_content,
3545 Err ( e) => {
36- return Err ( format ! ( "Failed to read to-file: {e}" ) ) ;
46+ eprintln ! ( "Failed to read to-file: {e}" ) ;
47+ return ExitCode :: from ( 2 ) ;
3748 }
3849 } ;
3950 // run diff
@@ -53,8 +64,15 @@ fn main() -> Result<(), String> {
5364 & to. to_string_lossy ( ) ,
5465 context_count,
5566 ) ,
56- Format :: Ed => ed_diff:: diff ( & from_content, & to_content) ?,
67+ Format :: Ed => ed_diff:: diff ( & from_content, & to_content) . unwrap_or_else ( |error| {
68+ eprintln ! ( "{error}" ) ;
69+ exit ( 2 ) ;
70+ } ) ,
5771 } ;
5872 io:: stdout ( ) . write_all ( & result) . unwrap ( ) ;
59- Ok ( ( ) )
73+ if result. is_empty ( ) {
74+ ExitCode :: SUCCESS
75+ } else {
76+ ExitCode :: from ( 1 )
77+ }
6078}
0 commit comments