Debian Codegraph @

rust/rhg/src/ui.rs

raw
1 use std::io;
2 use std::io::BufWriter;
3 use std::io::ErrorKind;
4 use std::io::IsTerminal;
5 use std::io::StderrLock;
6 use std::io::StdoutLock;
7 use std::io::Write;
8 use std::path::Path;
9
10 use format_bytes::format_bytes;
11 use format_bytes::write_bytes;
12 use hg::config::Config;
13 use hg::config::PlainInfo;
14 use hg::encoding::Encoder;
15 use hg::errors::HgError;
16 use hg::warnings::format::write_warning;
17 use hg::warnings::HgWarningContext;
18
19 use crate::color::ColorConfig;
20 use crate::color::Effect;
21
22 pub struct Ui {
23 stdout: std::io::Stdout,
24 stderr: std::io::Stderr,
25 colors: Option<ColorConfig>,
26 encoder: Encoder,
27 }
28
29 /// The kind of user interface error
30 pub enum UiError {
31 /// The standard output stream cannot be written to
32 StdoutError(io::Error),
33 /// The standard error stream cannot be written to
34 StderrError(io::Error),
35 }
36
37 /// The commandline user interface
38 impl Ui {
39 pub fn new(config: &Config) -> Result<Self, HgError> {
40 Ok(Ui {
41 // If using something else, also adapt `isatty()` below.
42 stdout: std::io::stdout(),
43
44 stderr: std::io::stderr(),
45 colors: ColorConfig::new(config)?,
46 encoder: Encoder::from_env()?,
47 })
48 }
49
50 /// Default to no color if color configuration errors.
51 ///
52 /// Useful when we’re already handling another error.
53 pub fn new_infallible(config: &Config) -> Self {
54 Ui {
55 // If using something else, also adapt `isatty()` below.
56 stdout: std::io::stdout(),
57
58 stderr: std::io::stderr(),
59 colors: ColorConfig::new(config).unwrap_or(None),
60 encoder: Encoder::default(),
61 }
62 }
63
64 /// Returns a buffered handle on stdout for faster batch printing
65 /// operations.
66 pub fn stdout_buffer(&self) -> StdoutBuffer<'_, BufWriter<StdoutLock>> {
67 StdoutBuffer {
68 stdout: BufWriter::new(self.stdout.lock()),
69 colors: &self.colors,
70 }
71 }
72
73 /// Write bytes to stdout
74 pub fn write_stdout(&self, bytes: &[u8]) -> Result<(), UiError> {
75 let mut stdout = self.stdout.lock();
76
77 stdout.write_all(bytes).or_else(handle_stdout_error)?;
78
79 stdout.flush().or_else(handle_stdout_error)
80 }
81
82 /// Write bytes to stderr
83 pub fn write_stderr(&self, bytes: &[u8]) -> Result<(), UiError> {
84 let mut stderr = self.stderr.lock();
85
86 stderr.write_all(bytes).or_else(handle_stderr_error)?;
87
88 stderr.flush().or_else(handle_stderr_error)
89 }
90
91 /// Return a lock to stderr
92 pub fn stderr_locked(&self) -> StderrLock {
93 self.stderr.lock()
94 }
95
96 pub fn encoder(&self) -> &Encoder {
97 &self.encoder
98 }
99 }
100
101 /// A buffered stdout writer for faster batch printing operations.
102 pub struct StdoutBuffer<'a, W> {
103 colors: &'a Option<ColorConfig>,
104 stdout: W,
105 }
106
107 impl<W: Write> StdoutBuffer<'_, W> {
108 /// Write bytes to stdout with the given label
109 ///
110 /// Like the optional `label` parameter in `mercurial/ui.py`,
111 /// this label influences the color used for this output.
112 pub fn write_stdout_labelled(
113 &mut self,
114 bytes: &[u8],
115 label: &str,
116 ) -> Result<(), UiError> {
117 if let Some(colors) = &self.colors {
118 if let Some(effects) = colors.styles.get(label.as_bytes()) {
119 if !effects.is_empty() {
120 return self
121 .write_stdout_with_effects(bytes, effects)
122 .or_else(handle_stdout_error);
123 }
124 }
125 }
126 self.write_all(bytes)
127 }
128
129 fn write_stdout_with_effects(
130 &mut self,
131 bytes: &[u8],
132 effects: &[Effect],
133 ) -> io::Result<()> {
134 let stdout = &mut self.stdout;
135 let mut write_line = |line: &[u8], first: bool| {
136 // `line` does not include the newline delimiter
137 if !first {
138 stdout.write_all(b"\n")?;
139 }
140 if line.is_empty() {
141 return Ok(());
142 }
143 /// 0x1B == 27 == 0o33
144 const ASCII_ESCAPE: &[u8] = b"\x1b";
145 write_bytes!(stdout, b"{}[0", ASCII_ESCAPE)?;
146 for effect in effects {
147 write_bytes!(stdout, b";{}", effect)?;
148 }
149 write_bytes!(stdout, b"m")?;
150 stdout.write_all(line)?;
151 write_bytes!(stdout, b"{}[0m", ASCII_ESCAPE)
152 };
153 let mut lines = bytes.split(|&byte| byte == b'\n');
154 if let Some(first) = lines.next() {
155 write_line(first, true)?;
156 for line in lines {
157 write_line(line, false)?
158 }
159 }
160 Ok(())
161 }
162
163 /// Write bytes to stdout buffer
164 pub fn write_all(&mut self, bytes: &[u8]) -> Result<(), UiError> {
165 self.stdout.write_all(bytes).or_else(handle_stdout_error)
166 }
167
168 /// Flush bytes to stdout
169 pub fn flush(&mut self) -> Result<(), UiError> {
170 self.stdout.flush().or_else(handle_stdout_error)
171 }
172 }
173
174 // TODO: pass the PlainInfo to call sites directly and
175 // delete this function
176 pub fn plain(opt_feature: Option<&str>) -> bool {
177 let plain_info = PlainInfo::from_env();
178 match opt_feature {
179 None => plain_info.is_plain(),
180 Some(feature) => plain_info.is_feature_plain(feature),
181 }
182 }
183
184 /// Sometimes writing to stdout is not possible, try writing to stderr to
185 /// signal that failure, otherwise just bail.
186 fn handle_stdout_error(error: io::Error) -> Result<(), UiError> {
187 if let ErrorKind::BrokenPipe = error.kind() {
188 // This makes `| head` work for example
189 return Ok(());
190 }
191 let mut stderr = io::stderr();
192
193 stderr
194 .write_all(&format_bytes!(b"abort: {}\n", error.to_string().as_bytes()))
195 .map_err(UiError::StderrError)?;
196
197 stderr.flush().map_err(UiError::StderrError)?;
198
199 Err(UiError::StdoutError(error))
200 }
201
202 /// Sometimes writing to stderr is not possible.
203 fn handle_stderr_error(error: io::Error) -> Result<(), UiError> {
204 // A broken pipe should not result in a error
205 // like with `| head` for example
206 if let ErrorKind::BrokenPipe = error.kind() {
207 return Ok(());
208 }
209 Err(UiError::StdoutError(error))
210 }
211
212 /// Should formatted output be used?
213 ///
214 /// Note: rhg does not have the formatter mechanism yet,
215 /// but this is also used when deciding whether to use color.
216 pub fn formatted(config: &Config) -> Result<bool, HgError> {
217 if let Some(formatted) = config.get_option(b"ui", b"formatted")? {
218 Ok(formatted)
219 } else {
220 isatty(config)
221 }
222 }
223
224 pub enum RelativePaths {
225 Legacy,
226 Bool(bool),
227 }
228
229 pub fn relative_paths(config: &Config) -> Result<RelativePaths, HgError> {
230 Ok(match config.get(b"ui", b"relative-paths") {
231 None | Some(b"legacy") => RelativePaths::Legacy,
232 _ => RelativePaths::Bool(config.get_bool(b"ui", b"relative-paths")?),
233 })
234 }
235
236 fn isatty(config: &Config) -> Result<bool, HgError> {
237 Ok(if config.get_bool(b"ui", b"nontty")? {
238 false
239 } else {
240 std::io::stdout().is_terminal()
241 })
242 }
243
244 pub fn print_warnings(ui: &Ui, warnings: HgWarningContext, working_dir: &Path) {
245 let mut stderr = ui.stderr_locked();
246 // Can't really do anything if writing to stderr failed
247 let _ = warnings.finish(|w| write_warning(&w, &mut stderr, working_dir));
248 }