Debian Codegraph @

cli/tests/common/command_output.rs

raw
1 // Copyright 2020 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::fmt;
16 use std::fmt::Debug;
17 use std::fmt::Display;
18 use std::process::ExitStatus;
19
20 /// Command output and exit status to be displayed in normalized form.
21 #[derive(Clone, Debug, Eq, PartialEq)]
22 pub struct CommandOutput {
23 pub stdout: CommandOutputString,
24 pub stderr: CommandOutputString,
25 pub status: ExitStatus,
26 }
27
28 impl CommandOutput {
29 /// Normalizes Windows directory separator to slash.
30 #[must_use]
31 pub fn normalize_backslash(self) -> Self {
32 Self {
33 stdout: self.stdout.normalize_backslash(),
34 stderr: self.stderr.normalize_backslash(),
35 status: self.status,
36 }
37 }
38
39 /// Normalizes [`ExitStatus`] message in stderr text.
40 #[must_use]
41 pub fn normalize_stderr_exit_status(self) -> Self {
42 Self {
43 stdout: self.stdout,
44 stderr: self.stderr.normalize_exit_status(),
45 status: self.status,
46 }
47 }
48
49 /// Removes the last line (such as platform-specific error message) from the
50 /// normalized stderr text.
51 #[must_use]
52 pub fn strip_stderr_last_line(self) -> Self {
53 Self {
54 stdout: self.stdout,
55 stderr: self.stderr.strip_last_line(),
56 status: self.status,
57 }
58 }
59
60 /// Removes all but the first `n` lines from normalized stdout text.
61 #[must_use]
62 pub fn take_stdout_n_lines(self, n: usize) -> Self {
63 Self {
64 stdout: self.stdout.take_n_lines(n),
65 stderr: self.stderr,
66 status: self.status,
67 }
68 }
69
70 #[must_use]
71 pub fn normalize_stdout_with(self, f: impl FnOnce(String) -> String) -> Self {
72 Self {
73 stdout: self.stdout.normalize_with(f),
74 stderr: self.stderr,
75 status: self.status,
76 }
77 }
78
79 #[must_use]
80 pub fn normalize_stderr_with(self, f: impl FnOnce(String) -> String) -> Self {
81 Self {
82 stdout: self.stdout,
83 stderr: self.stderr.normalize_with(f),
84 status: self.status,
85 }
86 }
87
88 /// Ensures that the command exits with success status.
89 #[track_caller]
90 pub fn success(self) -> Self {
91 assert!(self.status.success(), "{self}");
92 self
93 }
94 }
95
96 impl Display for CommandOutput {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 let Self {
99 stdout,
100 stderr,
101 status,
102 } = self;
103 write!(f, "{stdout}")?;
104 if !stderr.is_empty() {
105 writeln!(f, "------- stderr -------")?;
106 write!(f, "{stderr}")?;
107 }
108 if !status.success() {
109 // If there is an exit code, `{status}` would get rendered as "exit
110 // code: N" on Windows, so we render it ourselves for compatibility.
111 if let Some(code) = status.code() {
112 writeln!(f, "[exit status: {code}]")?;
113 } else {
114 writeln!(f, "[{status}]")?;
115 }
116 }
117 Ok(())
118 }
119 }
120
121 /// Command output data to be displayed in normalized form.
122 #[derive(Clone)]
123 pub struct CommandOutputString {
124 // TODO: use BString?
125 pub(super) raw: String,
126 pub(super) normalized: String,
127 }
128
129 impl CommandOutputString {
130 /// Normalizes Windows directory separator to slash.
131 #[must_use]
132 pub fn normalize_backslash(self) -> Self {
133 self.normalize_with(|s| s.replace('\\', "/"))
134 }
135
136 /// Normalizes [`ExitStatus`] message.
137 ///
138 /// On Windows, it prints "exit code" instead of "exit status".
139 #[must_use]
140 pub fn normalize_exit_status(self) -> Self {
141 self.normalize_with(|s| s.replace("exit code:", "exit status:"))
142 }
143
144 /// Removes the last line (such as platform-specific error message) from the
145 /// normalized text.
146 #[must_use]
147 pub fn strip_last_line(self) -> Self {
148 self.normalize_with(|mut s| {
149 s.truncate(strip_last_line(&s).len());
150 s
151 })
152 }
153
154 /// Removes all but the first `n` lines from the normalized text.
155 #[must_use]
156 pub fn take_n_lines(self, n: usize) -> Self {
157 self.normalize_with(|s| s.split_inclusive('\n').take(n).collect())
158 }
159
160 #[must_use]
161 pub fn normalize_with(mut self, f: impl FnOnce(String) -> String) -> Self {
162 self.normalized = f(self.normalized);
163 self
164 }
165
166 #[must_use]
167 pub fn is_empty(&self) -> bool {
168 self.raw.is_empty()
169 }
170
171 /// Raw output data.
172 #[must_use]
173 pub fn raw(&self) -> &str {
174 &self.raw
175 }
176
177 /// Normalized text for snapshot testing.
178 #[must_use]
179 pub fn normalized(&self) -> &str {
180 &self.normalized
181 }
182
183 /// Extracts raw output data.
184 #[must_use]
185 pub fn into_raw(self) -> String {
186 self.raw
187 }
188 }
189
190 impl Debug for CommandOutputString {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 // Print only raw data. Normalized string should be nearly identical.
193 Debug::fmt(&self.raw, f)
194 }
195 }
196
197 impl Display for CommandOutputString {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 if self.is_empty() {
200 return Ok(());
201 }
202 // Append "[EOF]" marker to test line ending
203 // https://github.com/mitsuhiko/insta/issues/384
204 writeln!(f, "{}[EOF]", self.normalized)
205 }
206 }
207
208 impl Eq for CommandOutputString {}
209
210 impl PartialEq for CommandOutputString {
211 fn eq(&self, other: &Self) -> bool {
212 // Compare only raw data. Normalized string is for displaying purpose.
213 self.raw == other.raw
214 }
215 }
216
217 /// Returns a string with the last line removed.
218 ///
219 /// Use this to remove the root error message containing platform-specific
220 /// content for example.
221 pub fn strip_last_line(s: &str) -> &str {
222 s.trim_end_matches('\n')
223 .rsplit_once('\n')
224 .map_or(s, |(h, _)| &s[..h.len() + 1])
225 }