main.ha (1165B)
1 use fmt; 2 use fs; 3 use getopt; 4 use io; 5 use os; 6 use os::exec; 7 8 export type error = !(io::error | fs::error | exec::error); 9 10 @symbol("utilmain") fn utilmain() (error | void); 11 12 // Shared main function for all utilities, to simplify error handling. 13 export @symbol("main") fn main() void = { 14 match (utilmain()) { 15 case let err: io::error => 16 fmt::fatal("I/O error:", io::strerror(err)); 17 case let err: fs::error => 18 fmt::fatal("Filesystem error:", fs::strerror(err)); 19 case let err: exec::error => 20 fmt::fatal("Exec error:", exec::strerror(err)); 21 case void => void; 22 }; 23 }; 24 25 // Prints to stderr a flag error message if specified, then the program usage. 26 // Exists the program with error code 1. 27 export fn usage(help: []getopt::help, flags: rune...) never = { 28 const progname = os::args[0]; 29 30 if (len(flags) == 1) { 31 fmt::errorfln("{}: invalid argument for option -{}", 32 progname, flags[0])!; 33 } else if (len(flags) > 1) { 34 fmt::errorf("{}: invalid combination of options", 35 progname)!; 36 for (let i = 0z; i < len(flags); i += 1) { 37 fmt::errorf(" -{}", flags[i])!; 38 }; 39 fmt::errorln()!; 40 }; 41 42 getopt::printusage(os::stderr, progname, help)!; 43 os::exit(1); 44 };