File: catl.rs 1 /* 2 The MIT License (MIT) 3 4 Copyright © 2020-2025 pacman64 5 6 Permission is hereby granted, free of charge, to any person obtaining a copy of 7 this software and associated documentation files (the “Software”), to deal 8 in the Software without restriction, including without limitation the rights to 9 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 10 of the Software, and to permit persons to whom the Software is furnished to do 11 so, subject to the following conditions: 12 13 The above copyright notice and this permission notice shall be included in all 14 copies or substantial portions of the Software. 15 16 THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 SOFTWARE. 23 */ 24 25 /* 26 Single-file source-code for catl. 27 28 To compile a smaller-sized command-line app, you can use the `rustc` command 29 as follows: 30 31 rustc -C opt-level=3 -C strip=symbols -C lto=true catl.rs 32 */ 33 34 use std::env; 35 use std::fs::File; 36 use std::io::{BufRead, BufReader, Error, Read, StdoutLock, Write, stdin, stdout}; 37 use std::process::exit; 38 39 fn main() { 40 // let dashes = env::args_os().skip(1).count_if(|e| e == "-"); 41 let mut dashes = 0; 42 for arg in env::args_os().skip(1) { 43 if arg == "-" { 44 dashes += 1; 45 } 46 } 47 let dashes = dashes; 48 49 if dashes > 1 { 50 let msg = "can't use standard input (dash) more than once"; 51 eprintln!("\x1b[31m{}\x1b[0m", msg); 52 exit(1); 53 } 54 55 let w = stdout(); 56 let mut errors = 0; 57 58 for arg in env::args_os().skip(1) { 59 if arg == "-" { 60 match catl(&mut w.lock(), stdin().lock()) { 61 Ok(()) => continue, 62 Err(_) => return, 63 } 64 } 65 66 let file = File::open(arg); 67 match file { 68 Ok(r) => { 69 match catl(&mut w.lock(), r) { 70 Ok(()) => (), 71 Err(_) => return, 72 } 73 } 74 75 Err(e) => { 76 errors += 1; 77 eprintln!("\x1b[31m{}\x1b[0m", e); 78 }, 79 } 80 } 81 82 if env::args_os().len() < 2 { 83 _ = catl(&mut w.lock(), stdin().lock()); 84 } 85 86 exit(if errors > 0 { 1 } else { 0 }); 87 } 88 89 fn catl(w: &mut StdoutLock, r: impl Read) -> Result<(), Error> { 90 let br = BufReader::new(r); 91 92 for (i, line) in br.lines().enumerate() { 93 match line { 94 Ok(l) => { 95 let l = l.as_bytes(); 96 let skip = i == 0 && l.starts_with(b"\xef\xbb\xbf"); 97 if skip { 98 _ = w.write(&l[3..]) 99 } else { 100 _ = w.write(l) 101 } 102 103 _ = w.write(b"\n"); 104 match w.flush() { 105 Ok(()) => (), 106 Err(e) => return Err(e), 107 }; 108 }, 109 110 Err(e) => return Err(e) 111 } 112 } 113 114 Ok(()) 115 }