mirror of
https://github.com/martinvonz/jj.git
synced 2025-01-28 15:26:25 +00:00
cli: introduce wrapper to writeln!() a message with label
It's common to write a formatted error/warning message, but we can't use writeln!() with the current ui.write_*() API, and sometimes we forget to add "\n" to the message. With this wrapper, ui.write_error("message\n") will be writeln!(ui.error(), "message"), and trivial formatter.with_label() call can be replaced with write!(formatter.labeled(...), ...).
This commit is contained in:
parent
dfe861a5e7
commit
99b84778ed
1 changed files with 27 additions and 1 deletions
|
@ -12,10 +12,11 @@
|
|||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::borrow::BorrowMut;
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::io::{Error, Write};
|
||||
use std::sync::Arc;
|
||||
use std::{fmt, io};
|
||||
|
||||
// Lets the caller label strings and translates the labels to colors
|
||||
pub trait Formatter: Write {
|
||||
|
@ -45,6 +46,31 @@ impl dyn Formatter + '_ {
|
|||
}
|
||||
}
|
||||
|
||||
/// `Formatter` wrapper to write a labeled message with `write!()` or
|
||||
/// `writeln!()`.
|
||||
pub struct LabeledWriter<T, S> {
|
||||
formatter: T,
|
||||
label: S,
|
||||
}
|
||||
|
||||
impl<T, S> LabeledWriter<T, S> {
|
||||
pub fn new(formatter: T, label: S) -> Self {
|
||||
LabeledWriter { formatter, label }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, S> LabeledWriter<T, S>
|
||||
where
|
||||
T: BorrowMut<dyn Formatter + 'a>,
|
||||
S: AsRef<str>,
|
||||
{
|
||||
pub fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
|
||||
self.formatter
|
||||
.borrow_mut()
|
||||
.with_label(self.label.as_ref(), |formatter| formatter.write_fmt(args))
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates `Formatter` instances with preconfigured parameters.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FormatterFactory {
|
||||
|
|
Loading…
Reference in a new issue