Debian Codegraph @

cli/testing/fake-formatter.rs

raw
1 // Copyright 2024 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::fs::OpenOptions;
16 use std::io::Read as _;
17 use std::io::Write as _;
18 use std::path::PathBuf;
19 use std::process::ExitCode;
20
21 use bstr::ByteSlice as _;
22 use clap::Parser;
23 use itertools::Itertools as _;
24 #[cfg(unix)]
25 use nix::sys::signal;
26
27 /// A fake code formatter, useful for testing
28 ///
29 /// `fake-formatter` is similar to `cat`.
30 /// `fake-formatter --reverse` is similar to `rev` (not `tac`).
31 /// `fake-formatter --stdout foo` is similar to `echo foo`.
32 /// `fake-formatter --stdout foo --stderr bar --fail` is similar to
33 /// `echo foo; echo bar >&2; false`.
34 /// `fake-formatter --tee foo` is similar to `tee foo`).
35 ///
36 /// This program acts as a portable alternative to that class of shell commands.
37 #[derive(Parser, Debug)]
38 struct Args {
39 /// Exit with non-successful status.
40 #[arg(long, default_value_t = false)]
41 fail: bool,
42
43 /// Abort instead of exiting
44 #[arg(long, default_value_t = false, conflicts_with = "fail")]
45 abort: bool,
46
47 /// Reverse the characters in each line when reading stdin.
48 #[arg(long, default_value_t = false)]
49 reverse: bool,
50
51 /// Convert all characters to uppercase when reading stdin.
52 #[arg(long, default_value_t = false)]
53 uppercase: bool,
54
55 /// Convert all characters to lowercase when reading stdin.
56 #[arg(long, default_value_t = false)]
57 lowercase: bool,
58
59 /// Adds a line to the end of the file
60 #[arg(long)]
61 append: Option<String>,
62
63 /// Write this string to stdout, and ignore stdin.
64 #[arg(long)]
65 stdout: Option<String>,
66
67 /// Write this string to stderr.
68 #[arg(long)]
69 stderr: Option<String>,
70
71 /// Duplicate stdout into this file.
72 #[arg(long)]
73 tee: Vec<PathBuf>,
74
75 /// Read one byte at a time, and send one byte to the stdout before reading
76 /// the next byte.
77 #[arg(long, default_value_t = false)]
78 byte_mode: bool,
79
80 /// Format lines from first to last inclusive [f, l] (1-indexed)
81 /// For example `--line-ranges 1-2,4-5` or `--line-ranges 1-2 --line-ranges
82 /// 4-5` formats lines 1 and 2, and lines 4 and 5.
83 #[arg(long, value_delimiter = ',')]
84 line_ranges: Vec<String>,
85
86 /// Split lines with an even number of characters into two lines.
87 /// Used only with `--line-ranges`.
88 /// Replicating formatters that expand beyond the line ranges.
89 /// For example, "abcd" becomes "ab\ncd".
90 #[arg(long, default_value_t = false, requires = "line_ranges")]
91 split_even_length_lines: bool,
92 }
93
94 /// Represents an inclusive range of lines.
95 #[derive(Debug)]
96 struct LineRange {
97 first: usize,
98 last: usize,
99 }
100
101 impl LineRange {
102 /// Creates a new line range from a string slice.
103 fn from_str(s: &str) -> Self {
104 let (first, last) = s.split_once('-').unwrap();
105 Self {
106 first: first.parse().unwrap(),
107 last: last.parse().unwrap(),
108 }
109 }
110
111 /// Checks if the line range contains the given line number (1-indexed and
112 /// inclusive).
113 fn contains(&self, line_num: usize) -> bool {
114 line_num >= self.first && line_num <= self.last
115 }
116 }
117
118 /// If a line has an even number of characters (excluding the trailing newline
119 /// if there is one), split it in half into two lines. This simulates a
120 /// formatter that writes to a larger piece of the file than the line range
121 /// it was given.
122 fn split_even_length_line(line: &str) -> String {
123 let line_len = line.strip_suffix('\n').unwrap_or(line).len();
124 if line_len.is_multiple_of(2) {
125 let (first, second) = line.split_at(line_len / 2);
126 format!("{first}\n{second}")
127 } else {
128 line.to_owned()
129 }
130 }
131
132 fn main() -> ExitCode {
133 let args: Args = Args::parse();
134 // Code formatters tend to print errors before printing the result.
135 if let Some(data) = args.stderr {
136 eprint!("{data}");
137 }
138 let stdout = if let Some(data) = args.stdout {
139 // Other content-altering flags don't apply to --stdout.
140 assert!(!args.reverse);
141 assert!(!args.uppercase);
142 assert!(!args.lowercase);
143 assert!(args.append.is_none());
144 print!("{data}");
145 data
146 } else if args.byte_mode {
147 assert!(!args.reverse);
148 assert!(args.append.is_none());
149
150 let mut stdout = vec![];
151 #[expect(clippy::unbuffered_bytes)]
152 for byte in std::io::stdin().bytes() {
153 let byte = byte.expect("Failed to read from stdin");
154 let output = if args.uppercase {
155 byte.to_ascii_uppercase()
156 } else if args.lowercase {
157 assert!(!args.uppercase);
158 byte.to_ascii_lowercase()
159 } else {
160 byte
161 };
162 stdout.push(output);
163 std::io::stdout()
164 .write_all(&[output])
165 .expect("Failed to write to stdout");
166 }
167 stdout
168 .to_str()
169 .expect("Output is not a valid UTF-8 string")
170 .to_owned()
171 } else {
172 let line_ranges = if !args.line_ranges.is_empty() {
173 args.line_ranges
174 .iter()
175 .map(|range| LineRange::from_str(range))
176 .collect_vec()
177 } else {
178 vec![LineRange {
179 first: 1,
180 last: usize::MAX,
181 }]
182 };
183
184 let mut input = vec![];
185 std::io::stdin()
186 .read_to_end(&mut input)
187 .expect("Failed to read from stdin");
188 let mut stdout = input
189 .lines_with_terminator()
190 .enumerate()
191 .map(|(i, line)| {
192 let line = line
193 .to_str()
194 .expect("The input is not valid UTF-8 string")
195 .to_owned();
196
197 let line_num = i + 1;
198 let in_range = line_ranges
199 .iter()
200 .any(|line_range| line_range.contains(line_num));
201 if !in_range {
202 return line;
203 }
204
205 let line = if args.reverse {
206 line.chars().rev().collect()
207 } else {
208 line
209 };
210 let line = if args.split_even_length_lines {
211 split_even_length_line(&line)
212 } else {
213 line
214 };
215 if args.uppercase {
216 assert!(!args.lowercase);
217 line.to_uppercase()
218 } else if args.lowercase {
219 assert!(!args.uppercase);
220 line.to_lowercase()
221 } else {
222 line
223 }
224 })
225 .join("");
226 if let Some(line) = args.append {
227 stdout.push_str(&line);
228 }
229 print!("{stdout}");
230 stdout
231 };
232 for path in args.tee {
233 let mut file = OpenOptions::new()
234 .create(true)
235 .append(true)
236 .open(path)
237 .unwrap();
238 write!(file, "{stdout}").unwrap();
239 }
240 if args.abort {
241 // Coredump generation varies by UNIX and is irrelevant to tests
242 // Prefer raising SIGTERM to crash without dumping core
243 #[cfg(unix)]
244 let _ = signal::raise(signal::Signal::SIGTERM);
245 std::process::abort()
246 } else if args.fail {
247 ExitCode::FAILURE
248 } else {
249 ExitCode::SUCCESS
250 }
251 }