mirror of
https://github.com/BurntSushi/ripgrep.git
synced 2025-08-06 07:02:04 -07:00
hyperlink: rejigger how hyperlinks work
This essentially takes the work done in #2483 and does a bit of a facelift. A brief summary: * We reduce the hyperlink API we expose to just the format, a configuration and an environment. * We move buffer management into a hyperlink-specific interpolator. * We expand the documentation on --hyperlink-format. * We rewrite the hyperlink format parser to be a simple state machine with support for escaping '{{' and '}}'. * We remove the 'gethostname' dependency and instead insist on the caller to provide the hostname. (So grep-printer doesn't get it itself, but the application will.) Similarly for the WSL prefix. * Probably some other things. Overall, the general structure of #2483 was kept. The biggest change is probably requiring the caller to pass in things like a hostname instead of having the crate do it. I did this for a couple reasons: 1. I feel uncomfortable with code deep inside the printing logic reaching out into the environment to assume responsibility for retrieving the hostname. This feels more like an application-level responsibility. Arguably, path canonicalization falls into this same bucket, but it is more difficult to rip that out. (And we can do it in the future in a backwards compatible fashion I think.) 2. I wanted to permit end users to tell ripgrep about their system's hostname in their own way, e.g., by running a custom executable. I want this because I know at least for my own use cases, I sometimes log into systems using an SSH hostname that is distinct from the system's actual hostname (usually because the system is shared in some way or changing its hostname is not allowed/practical). I think that's about it. Closes #665, Closes #2483
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -1,23 +1,87 @@
|
||||
/// Aliases to well-known hyperlink schemes.
|
||||
///
|
||||
/// These need to be sorted by name.
|
||||
pub(crate) const HYPERLINK_PATTERN_ALIASES: &[(&str, &str)] = &[
|
||||
#[cfg(unix)]
|
||||
("file", "file://{host}/{file}"),
|
||||
const HYPERLINK_PATTERN_ALIASES: &[(&str, &str)] = &[
|
||||
#[cfg(not(windows))]
|
||||
("default", "file://{host}{path}"),
|
||||
#[cfg(windows)]
|
||||
("file", "file:///{file}"),
|
||||
("default", "file://{path}"),
|
||||
("file", "file://{host}{path}"),
|
||||
// https://github.com/misaki-web/grepp
|
||||
("grep+", "grep+:///{file}:{line}"),
|
||||
("kitty", "file://{host}/{file}#{line}"),
|
||||
("grep+", "grep+://{path}:{line}"),
|
||||
("kitty", "file://{host}{path}#{line}"),
|
||||
// https://macvim.org/docs/gui_mac.txt.html#mvim%3A%2F%2F
|
||||
("macvim", "mvim://open?url=file:///{file}&line={line}&column={column}"),
|
||||
("macvim", "mvim://open?url=file://{path}&line={line}&column={column}"),
|
||||
("none", ""),
|
||||
// https://github.com/inopinatus/sublime_url
|
||||
("subl", "subl://open?url=file:///{file}&line={line}&column={column}"),
|
||||
("subl", "subl://open?url=file://{path}&line={line}&column={column}"),
|
||||
// https://macromates.com/blog/2007/the-textmate-url-scheme/
|
||||
("textmate", "txmt://open?url=file:///{file}&line={line}&column={column}"),
|
||||
("textmate", "txmt://open?url=file://{path}&line={line}&column={column}"),
|
||||
// https://code.visualstudio.com/docs/editor/command-line#_opening-vs-code-with-urls
|
||||
("vscode", "vscode://file/{file}:{line}:{column}"),
|
||||
("vscode-insiders", "vscode-insiders://file/{file}:{line}:{column}"),
|
||||
("vscodium", "vscodium://file/{file}:{line}:{column}"),
|
||||
("vscode", "vscode://file{path}:{line}:{column}"),
|
||||
("vscode-insiders", "vscode-insiders://file{path}:{line}:{column}"),
|
||||
("vscodium", "vscodium://file{path}:{line}:{column}"),
|
||||
];
|
||||
|
||||
/// Look for the hyperlink format defined by the given alias name.
|
||||
///
|
||||
/// If one does not exist, `None` is returned.
|
||||
pub(crate) fn find(name: &str) -> Option<&str> {
|
||||
HYPERLINK_PATTERN_ALIASES
|
||||
.binary_search_by_key(&name, |&(name, _)| name)
|
||||
.map(|i| HYPERLINK_PATTERN_ALIASES[i].1)
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Return an iterator over all available alias names and their definitions.
|
||||
pub(crate) fn iter() -> impl Iterator<Item = (&'static str, &'static str)> {
|
||||
HYPERLINK_PATTERN_ALIASES.iter().copied()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::HyperlinkFormat;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn is_sorted() {
|
||||
let mut prev = HYPERLINK_PATTERN_ALIASES
|
||||
.get(0)
|
||||
.expect("aliases should be non-empty")
|
||||
.0;
|
||||
for &(name, _) in HYPERLINK_PATTERN_ALIASES.iter().skip(1) {
|
||||
assert!(
|
||||
name > prev,
|
||||
"'{prev}' should come before '{name}' in \
|
||||
HYPERLINK_PATTERN_ALIASES",
|
||||
);
|
||||
prev = name;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alias_names_are_reasonable() {
|
||||
for &(name, _) in HYPERLINK_PATTERN_ALIASES.iter() {
|
||||
// There's no hard rule here, but if we want to define an alias
|
||||
// with a name that doesn't pass this assert, then we should
|
||||
// probably flag it as worthy of consideration. For example, we
|
||||
// really do not want to define an alias that contains `{` or `}`,
|
||||
// which might confuse it for a variable.
|
||||
assert!(name.chars().all(|c| c.is_alphanumeric()
|
||||
|| c == '+'
|
||||
|| c == '-'
|
||||
|| c == '.'));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aliases_are_valid_formats() {
|
||||
for (name, definition) in HYPERLINK_PATTERN_ALIASES {
|
||||
assert!(
|
||||
definition.parse::<HyperlinkFormat>().is_ok(),
|
||||
"invalid hyperlink alias '{name}': {definition}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -60,12 +60,13 @@ assert_eq!(output, expected);
|
||||
*/
|
||||
|
||||
#![deny(missing_docs)]
|
||||
#![cfg_attr(feature = "pattern", feature(pattern))]
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
|
||||
pub use crate::{
|
||||
color::{default_color_specs, ColorError, ColorSpecs, UserColorSpec},
|
||||
hyperlink::{
|
||||
HyperlinkPattern, HyperlinkPatternBuilder, HyperlinkPatternError,
|
||||
HyperlinkConfig, HyperlinkEnvironment, HyperlinkFormat,
|
||||
HyperlinkFormatError,
|
||||
},
|
||||
path::{PathPrinter, PathPrinterBuilder},
|
||||
standard::{Standard, StandardBuilder, StandardSink},
|
||||
|
@@ -4,7 +4,7 @@ use termcolor::WriteColor;
|
||||
|
||||
use crate::{
|
||||
color::ColorSpecs,
|
||||
hyperlink::{HyperlinkPattern, HyperlinkSpan},
|
||||
hyperlink::{self, HyperlinkConfig},
|
||||
util::PrinterPath,
|
||||
};
|
||||
|
||||
@@ -12,7 +12,7 @@ use crate::{
|
||||
#[derive(Clone, Debug)]
|
||||
struct Config {
|
||||
colors: ColorSpecs,
|
||||
hyperlink_pattern: HyperlinkPattern,
|
||||
hyperlink: HyperlinkConfig,
|
||||
separator: Option<u8>,
|
||||
terminator: u8,
|
||||
}
|
||||
@@ -21,7 +21,7 @@ impl Default for Config {
|
||||
fn default() -> Config {
|
||||
Config {
|
||||
colors: ColorSpecs::default(),
|
||||
hyperlink_pattern: HyperlinkPattern::default(),
|
||||
hyperlink: HyperlinkConfig::default(),
|
||||
separator: None,
|
||||
terminator: b'\n',
|
||||
}
|
||||
@@ -43,7 +43,9 @@ impl PathPrinterBuilder {
|
||||
/// Create a new path printer with the current configuration that writes
|
||||
/// paths to the given writer.
|
||||
pub fn build<W: WriteColor>(&self, wtr: W) -> PathPrinter<W> {
|
||||
PathPrinter { config: self.config.clone(), wtr, buf: vec![] }
|
||||
let interpolator =
|
||||
hyperlink::Interpolator::new(&self.config.hyperlink);
|
||||
PathPrinter { config: self.config.clone(), wtr, interpolator }
|
||||
}
|
||||
|
||||
/// Set the user color specifications to use for coloring in this printer.
|
||||
@@ -73,7 +75,7 @@ impl PathPrinterBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the hyperlink pattern to use for hyperlinks output by this printer.
|
||||
/// Set the configuration to use for hyperlinks output by this printer.
|
||||
///
|
||||
/// Regardless of the hyperlink format provided here, whether hyperlinks
|
||||
/// are actually used or not is determined by the implementation of
|
||||
@@ -83,12 +85,12 @@ impl PathPrinterBuilder {
|
||||
///
|
||||
/// This completely overrides any previous hyperlink format.
|
||||
///
|
||||
/// The default pattern format results in not emitting any hyperlinks.
|
||||
pub fn hyperlink_pattern(
|
||||
/// The default configuration results in not emitting any hyperlinks.
|
||||
pub fn hyperlink(
|
||||
&mut self,
|
||||
pattern: HyperlinkPattern,
|
||||
config: HyperlinkConfig,
|
||||
) -> &mut PathPrinterBuilder {
|
||||
self.config.hyperlink_pattern = pattern;
|
||||
self.config.hyperlink = config;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -140,40 +142,35 @@ impl PathPrinterBuilder {
|
||||
pub struct PathPrinter<W> {
|
||||
config: Config,
|
||||
wtr: W,
|
||||
buf: Vec<u8>,
|
||||
interpolator: hyperlink::Interpolator,
|
||||
}
|
||||
|
||||
impl<W: WriteColor> PathPrinter<W> {
|
||||
/// Write the given path to the underlying writer.
|
||||
pub fn write(&mut self, path: &Path) -> io::Result<()> {
|
||||
let ppath = PrinterPath::with_separator(path, self.config.separator);
|
||||
let ppath = PrinterPath::new(path.as_ref())
|
||||
.with_separator(self.config.separator);
|
||||
if !self.wtr.supports_color() {
|
||||
self.wtr.write_all(ppath.as_bytes())?;
|
||||
} else {
|
||||
let mut hyperlink = self.start_hyperlink_span(&ppath)?;
|
||||
let status = self.start_hyperlink(&ppath)?;
|
||||
self.wtr.set_color(self.config.colors.path())?;
|
||||
self.wtr.write_all(ppath.as_bytes())?;
|
||||
self.wtr.reset()?;
|
||||
hyperlink.end(&mut self.wtr)?;
|
||||
self.interpolator.finish(status, &mut self.wtr)?;
|
||||
}
|
||||
self.wtr.write_all(&[self.config.terminator])
|
||||
}
|
||||
|
||||
/// Starts a hyperlink span when applicable.
|
||||
fn start_hyperlink_span(
|
||||
fn start_hyperlink(
|
||||
&mut self,
|
||||
path: &PrinterPath,
|
||||
) -> io::Result<HyperlinkSpan> {
|
||||
if self.wtr.supports_hyperlinks() {
|
||||
if let Some(spec) = path.create_hyperlink_spec(
|
||||
&self.config.hyperlink_pattern,
|
||||
None,
|
||||
None,
|
||||
&mut self.buf,
|
||||
) {
|
||||
return Ok(HyperlinkSpan::start(&mut self.wtr, &spec)?);
|
||||
}
|
||||
}
|
||||
Ok(HyperlinkSpan::default())
|
||||
) -> io::Result<hyperlink::InterpolatorStatus> {
|
||||
let Some(hyperpath) = path.as_hyperlink() else {
|
||||
return Ok(hyperlink::InterpolatorStatus::inactive());
|
||||
};
|
||||
let values = hyperlink::Values::new(hyperpath);
|
||||
self.interpolator.begin(&values, &mut self.wtr)
|
||||
}
|
||||
}
|
||||
|
@@ -20,7 +20,7 @@ use {
|
||||
use crate::{
|
||||
color::ColorSpecs,
|
||||
counter::CounterWriter,
|
||||
hyperlink::{HyperlinkPattern, HyperlinkSpan},
|
||||
hyperlink::{self, HyperlinkConfig},
|
||||
stats::Stats,
|
||||
util::{
|
||||
find_iter_at_in_context, trim_ascii_prefix, trim_line_terminator,
|
||||
@@ -36,7 +36,7 @@ use crate::{
|
||||
#[derive(Debug, Clone)]
|
||||
struct Config {
|
||||
colors: ColorSpecs,
|
||||
hyperlink_pattern: HyperlinkPattern,
|
||||
hyperlink: HyperlinkConfig,
|
||||
stats: bool,
|
||||
heading: bool,
|
||||
path: bool,
|
||||
@@ -62,7 +62,7 @@ impl Default for Config {
|
||||
fn default() -> Config {
|
||||
Config {
|
||||
colors: ColorSpecs::default(),
|
||||
hyperlink_pattern: HyperlinkPattern::default(),
|
||||
hyperlink: HyperlinkConfig::default(),
|
||||
stats: false,
|
||||
heading: false,
|
||||
path: true,
|
||||
@@ -131,7 +131,6 @@ impl StandardBuilder {
|
||||
Standard {
|
||||
config: self.config.clone(),
|
||||
wtr: RefCell::new(CounterWriter::new(wtr)),
|
||||
buf: RefCell::new(vec![]),
|
||||
matches: vec![],
|
||||
}
|
||||
}
|
||||
@@ -170,7 +169,7 @@ impl StandardBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the hyperlink pattern to use for hyperlinks output by this printer.
|
||||
/// Set the configuration to use for hyperlinks output by this printer.
|
||||
///
|
||||
/// Regardless of the hyperlink format provided here, whether hyperlinks
|
||||
/// are actually used or not is determined by the implementation of
|
||||
@@ -180,12 +179,12 @@ impl StandardBuilder {
|
||||
///
|
||||
/// This completely overrides any previous hyperlink format.
|
||||
///
|
||||
/// The default pattern format results in not emitting any hyperlinks.
|
||||
pub fn hyperlink_pattern(
|
||||
/// The default configuration results in not emitting any hyperlinks.
|
||||
pub fn hyperlink(
|
||||
&mut self,
|
||||
pattern: HyperlinkPattern,
|
||||
config: HyperlinkConfig,
|
||||
) -> &mut StandardBuilder {
|
||||
self.config.hyperlink_pattern = pattern;
|
||||
self.config.hyperlink = config;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -496,7 +495,6 @@ impl StandardBuilder {
|
||||
pub struct Standard<W> {
|
||||
config: Config,
|
||||
wtr: RefCell<CounterWriter<W>>,
|
||||
buf: RefCell<Vec<u8>>,
|
||||
matches: Vec<Match>,
|
||||
}
|
||||
|
||||
@@ -533,12 +531,15 @@ impl<W: WriteColor> Standard<W> {
|
||||
&'s mut self,
|
||||
matcher: M,
|
||||
) -> StandardSink<'static, 's, M, W> {
|
||||
let interpolator =
|
||||
hyperlink::Interpolator::new(&self.config.hyperlink);
|
||||
let stats = if self.config.stats { Some(Stats::new()) } else { None };
|
||||
let needs_match_granularity = self.needs_match_granularity();
|
||||
StandardSink {
|
||||
matcher,
|
||||
standard: self,
|
||||
replacer: Replacer::new(),
|
||||
interpolator,
|
||||
path: None,
|
||||
start_time: Instant::now(),
|
||||
match_count: 0,
|
||||
@@ -565,16 +566,17 @@ impl<W: WriteColor> Standard<W> {
|
||||
if !self.config.path {
|
||||
return self.sink(matcher);
|
||||
}
|
||||
let interpolator =
|
||||
hyperlink::Interpolator::new(&self.config.hyperlink);
|
||||
let stats = if self.config.stats { Some(Stats::new()) } else { None };
|
||||
let ppath = PrinterPath::with_separator(
|
||||
path.as_ref(),
|
||||
self.config.separator_path,
|
||||
);
|
||||
let ppath = PrinterPath::new(path.as_ref())
|
||||
.with_separator(self.config.separator_path);
|
||||
let needs_match_granularity = self.needs_match_granularity();
|
||||
StandardSink {
|
||||
matcher,
|
||||
standard: self,
|
||||
replacer: Replacer::new(),
|
||||
interpolator,
|
||||
path: Some(ppath),
|
||||
start_time: Instant::now(),
|
||||
match_count: 0,
|
||||
@@ -659,6 +661,7 @@ pub struct StandardSink<'p, 's, M: Matcher, W> {
|
||||
matcher: M,
|
||||
standard: &'s mut Standard<W>,
|
||||
replacer: Replacer<M>,
|
||||
interpolator: hyperlink::Interpolator,
|
||||
path: Option<PrinterPath<'p>>,
|
||||
start_time: Instant,
|
||||
match_count: u64,
|
||||
@@ -1241,22 +1244,10 @@ impl<'a, M: Matcher, W: WriteColor> StandardImpl<'a, M, W> {
|
||||
) -> io::Result<()> {
|
||||
let mut prelude = PreludeWriter::new(self);
|
||||
prelude.start(line_number, column)?;
|
||||
|
||||
if !self.config().heading {
|
||||
prelude.write_path()?;
|
||||
}
|
||||
if let Some(n) = line_number {
|
||||
prelude.write_line_number(n)?;
|
||||
}
|
||||
if let Some(n) = column {
|
||||
if self.config().column {
|
||||
prelude.write_column_number(n)?;
|
||||
}
|
||||
}
|
||||
if self.config().byte_offset {
|
||||
prelude.write_byte_offset(absolute_byte_offset)?;
|
||||
}
|
||||
|
||||
prelude.write_path()?;
|
||||
prelude.write_line_number(line_number)?;
|
||||
prelude.write_column_number(column)?;
|
||||
prelude.write_byte_offset(absolute_byte_offset)?;
|
||||
prelude.end()
|
||||
}
|
||||
|
||||
@@ -1507,30 +1498,30 @@ impl<'a, M: Matcher, W: WriteColor> StandardImpl<'a, M, W> {
|
||||
}
|
||||
|
||||
fn write_path_hyperlink(&self, path: &PrinterPath) -> io::Result<()> {
|
||||
let mut hyperlink = self.start_hyperlink_span(path, None, None)?;
|
||||
let status = self.start_hyperlink(path, None, None)?;
|
||||
self.write_path(path)?;
|
||||
hyperlink.end(&mut *self.wtr().borrow_mut())
|
||||
self.end_hyperlink(status)
|
||||
}
|
||||
|
||||
fn start_hyperlink_span(
|
||||
fn start_hyperlink(
|
||||
&self,
|
||||
path: &PrinterPath,
|
||||
line_number: Option<u64>,
|
||||
column: Option<u64>,
|
||||
) -> io::Result<HyperlinkSpan> {
|
||||
let mut wtr = self.wtr().borrow_mut();
|
||||
if wtr.supports_hyperlinks() {
|
||||
let mut buf = self.buf().borrow_mut();
|
||||
if let Some(spec) = path.create_hyperlink_spec(
|
||||
&self.config().hyperlink_pattern,
|
||||
line_number,
|
||||
column,
|
||||
&mut buf,
|
||||
) {
|
||||
return HyperlinkSpan::start(&mut *wtr, &spec);
|
||||
}
|
||||
}
|
||||
Ok(HyperlinkSpan::default())
|
||||
) -> io::Result<hyperlink::InterpolatorStatus> {
|
||||
let Some(hyperpath) = path.as_hyperlink() else {
|
||||
return Ok(hyperlink::InterpolatorStatus::inactive());
|
||||
};
|
||||
let values =
|
||||
hyperlink::Values::new(hyperpath).line(line_number).column(column);
|
||||
self.sink.interpolator.begin(&values, &mut *self.wtr().borrow_mut())
|
||||
}
|
||||
|
||||
fn end_hyperlink(
|
||||
&self,
|
||||
status: hyperlink::InterpolatorStatus,
|
||||
) -> io::Result<()> {
|
||||
self.sink.interpolator.finish(status, &mut *self.wtr().borrow_mut())
|
||||
}
|
||||
|
||||
fn start_color_match(&self) -> io::Result<()> {
|
||||
@@ -1586,12 +1577,6 @@ impl<'a, M: Matcher, W: WriteColor> StandardImpl<'a, M, W> {
|
||||
&self.sink.standard.wtr
|
||||
}
|
||||
|
||||
/// Return a temporary buffer, which may be used for anything.
|
||||
/// It is not necessarily empty when returned.
|
||||
fn buf(&self) -> &'a RefCell<Vec<u8>> {
|
||||
&self.sink.standard.buf
|
||||
}
|
||||
|
||||
/// Return the path associated with this printer, if one exists.
|
||||
fn path(&self) -> Option<&'a PrinterPath<'a>> {
|
||||
self.sink.path.as_ref()
|
||||
@@ -1645,7 +1630,7 @@ struct PreludeWriter<'a, M: Matcher, W> {
|
||||
std: &'a StandardImpl<'a, M, W>,
|
||||
next_separator: PreludeSeparator,
|
||||
field_separator: &'a [u8],
|
||||
hyperlink: HyperlinkSpan,
|
||||
interp_status: hyperlink::InterpolatorStatus,
|
||||
}
|
||||
|
||||
/// A type of separator used in the prelude
|
||||
@@ -1660,45 +1645,45 @@ enum PreludeSeparator {
|
||||
|
||||
impl<'a, M: Matcher, W: WriteColor> PreludeWriter<'a, M, W> {
|
||||
/// Creates a new prelude printer.
|
||||
#[inline(always)]
|
||||
fn new(std: &'a StandardImpl<'a, M, W>) -> PreludeWriter<'a, M, W> {
|
||||
Self {
|
||||
PreludeWriter {
|
||||
std,
|
||||
next_separator: PreludeSeparator::None,
|
||||
field_separator: std.separator_field(),
|
||||
hyperlink: HyperlinkSpan::default(),
|
||||
interp_status: hyperlink::InterpolatorStatus::inactive(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the prelude with a hyperlink when applicable.
|
||||
///
|
||||
/// If a heading was written, and the hyperlink pattern is invariant on
|
||||
/// If a heading was written, and the hyperlink format is invariant on
|
||||
/// the line number, then this doesn't hyperlink each line prelude, as it
|
||||
/// wouldn't point to the line anyway. The hyperlink on the heading should
|
||||
/// be sufficient and less confusing.
|
||||
#[inline(always)]
|
||||
fn start(
|
||||
&mut self,
|
||||
line_number: Option<u64>,
|
||||
column: Option<u64>,
|
||||
) -> io::Result<()> {
|
||||
if let Some(path) = self.std.path() {
|
||||
if self.config().hyperlink_pattern.is_line_dependent()
|
||||
|| !self.config().heading
|
||||
{
|
||||
self.hyperlink = self.std.start_hyperlink_span(
|
||||
path,
|
||||
line_number,
|
||||
column,
|
||||
)?;
|
||||
}
|
||||
let Some(path) = self.std.path() else { return Ok(()) };
|
||||
if self.config().hyperlink.format().is_line_dependent()
|
||||
|| !self.config().heading
|
||||
{
|
||||
self.interp_status =
|
||||
self.std.start_hyperlink(path, line_number, column)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ends the prelude and writes the remaining output.
|
||||
#[inline(always)]
|
||||
fn end(&mut self) -> io::Result<()> {
|
||||
if self.hyperlink.is_active() {
|
||||
self.hyperlink.end(&mut *self.std.wtr().borrow_mut())?;
|
||||
}
|
||||
self.std.end_hyperlink(std::mem::replace(
|
||||
&mut self.interp_status,
|
||||
hyperlink::InterpolatorStatus::inactive(),
|
||||
))?;
|
||||
self.write_separator()
|
||||
}
|
||||
|
||||
@@ -1706,22 +1691,30 @@ impl<'a, M: Matcher, W: WriteColor> PreludeWriter<'a, M, W> {
|
||||
/// write that path to the underlying writer followed by the given field
|
||||
/// separator. (If a path terminator is set, then that is used instead of
|
||||
/// the field separator.)
|
||||
#[inline(always)]
|
||||
fn write_path(&mut self) -> io::Result<()> {
|
||||
if let Some(path) = self.std.path() {
|
||||
self.write_separator()?;
|
||||
self.std.write_path(path)?;
|
||||
|
||||
self.next_separator = if self.config().path_terminator.is_some() {
|
||||
PreludeSeparator::PathTerminator
|
||||
} else {
|
||||
PreludeSeparator::FieldSeparator
|
||||
};
|
||||
// The prelude doesn't handle headings, only what comes before a match
|
||||
// on the same line. So if we are emitting paths in headings, we should
|
||||
// not do it here on each line.
|
||||
if self.config().heading {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(path) = self.std.path() else { return Ok(()) };
|
||||
self.write_separator()?;
|
||||
self.std.write_path(path)?;
|
||||
|
||||
self.next_separator = if self.config().path_terminator.is_some() {
|
||||
PreludeSeparator::PathTerminator
|
||||
} else {
|
||||
PreludeSeparator::FieldSeparator
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes the line number field.
|
||||
fn write_line_number(&mut self, line_number: u64) -> io::Result<()> {
|
||||
/// Writes the line number field if present.
|
||||
#[inline(always)]
|
||||
fn write_line_number(&mut self, line: Option<u64>) -> io::Result<()> {
|
||||
let Some(line_number) = line else { return Ok(()) };
|
||||
self.write_separator()?;
|
||||
let n = line_number.to_string();
|
||||
self.std.write_spec(self.config().colors.line(), n.as_bytes())?;
|
||||
@@ -1729,8 +1722,13 @@ impl<'a, M: Matcher, W: WriteColor> PreludeWriter<'a, M, W> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes the column number field.
|
||||
fn write_column_number(&mut self, column_number: u64) -> io::Result<()> {
|
||||
/// Writes the column number field if present and configured to do so.
|
||||
#[inline(always)]
|
||||
fn write_column_number(&mut self, column: Option<u64>) -> io::Result<()> {
|
||||
if !self.config().column {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(column_number) = column else { return Ok(()) };
|
||||
self.write_separator()?;
|
||||
let n = column_number.to_string();
|
||||
self.std.write_spec(self.config().colors.column(), n.as_bytes())?;
|
||||
@@ -1738,8 +1736,12 @@ impl<'a, M: Matcher, W: WriteColor> PreludeWriter<'a, M, W> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes the byte offset field.
|
||||
/// Writes the byte offset field if configured to do so.
|
||||
#[inline(always)]
|
||||
fn write_byte_offset(&mut self, offset: u64) -> io::Result<()> {
|
||||
if !self.config().byte_offset {
|
||||
return Ok(());
|
||||
}
|
||||
self.write_separator()?;
|
||||
let n = offset.to_string();
|
||||
self.std.write_spec(self.config().colors.column(), n.as_bytes())?;
|
||||
@@ -1751,6 +1753,7 @@ impl<'a, M: Matcher, W: WriteColor> PreludeWriter<'a, M, W> {
|
||||
///
|
||||
/// This is called before writing the contents of a field, and at
|
||||
/// the end of the prelude.
|
||||
#[inline(always)]
|
||||
fn write_separator(&mut self) -> io::Result<()> {
|
||||
match self.next_separator {
|
||||
PreludeSeparator::None => {}
|
||||
@@ -1767,6 +1770,7 @@ impl<'a, M: Matcher, W: WriteColor> PreludeWriter<'a, M, W> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn config(&self) -> &Config {
|
||||
self.std.config()
|
||||
}
|
||||
|
@@ -15,7 +15,7 @@ use {
|
||||
use crate::{
|
||||
color::ColorSpecs,
|
||||
counter::CounterWriter,
|
||||
hyperlink::{HyperlinkPattern, HyperlinkSpan},
|
||||
hyperlink::{self, HyperlinkConfig},
|
||||
stats::Stats,
|
||||
util::{find_iter_at_in_context, PrinterPath},
|
||||
};
|
||||
@@ -29,7 +29,7 @@ use crate::{
|
||||
struct Config {
|
||||
kind: SummaryKind,
|
||||
colors: ColorSpecs,
|
||||
hyperlink_pattern: HyperlinkPattern,
|
||||
hyperlink: HyperlinkConfig,
|
||||
stats: bool,
|
||||
path: bool,
|
||||
max_matches: Option<u64>,
|
||||
@@ -44,7 +44,7 @@ impl Default for Config {
|
||||
Config {
|
||||
kind: SummaryKind::Count,
|
||||
colors: ColorSpecs::default(),
|
||||
hyperlink_pattern: HyperlinkPattern::default(),
|
||||
hyperlink: HyperlinkConfig::default(),
|
||||
stats: false,
|
||||
path: true,
|
||||
max_matches: None,
|
||||
@@ -169,7 +169,6 @@ impl SummaryBuilder {
|
||||
Summary {
|
||||
config: self.config.clone(),
|
||||
wtr: RefCell::new(CounterWriter::new(wtr)),
|
||||
buf: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,7 +215,7 @@ impl SummaryBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the hyperlink pattern to use for hyperlinks output by this printer.
|
||||
/// Set the configuration to use for hyperlinks output by this printer.
|
||||
///
|
||||
/// Regardless of the hyperlink format provided here, whether hyperlinks
|
||||
/// are actually used or not is determined by the implementation of
|
||||
@@ -226,12 +225,12 @@ impl SummaryBuilder {
|
||||
///
|
||||
/// This completely overrides any previous hyperlink format.
|
||||
///
|
||||
/// The default pattern format results in not emitting any hyperlinks.
|
||||
pub fn hyperlink_pattern(
|
||||
/// The default configuration results in not emitting any hyperlinks.
|
||||
pub fn hyperlink(
|
||||
&mut self,
|
||||
pattern: HyperlinkPattern,
|
||||
config: HyperlinkConfig,
|
||||
) -> &mut SummaryBuilder {
|
||||
self.config.hyperlink_pattern = pattern;
|
||||
self.config.hyperlink = config;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -357,7 +356,6 @@ impl SummaryBuilder {
|
||||
pub struct Summary<W> {
|
||||
config: Config,
|
||||
wtr: RefCell<CounterWriter<W>>,
|
||||
buf: Vec<u8>,
|
||||
}
|
||||
|
||||
impl<W: WriteColor> Summary<W> {
|
||||
@@ -400,6 +398,8 @@ impl<W: WriteColor> Summary<W> {
|
||||
&'s mut self,
|
||||
matcher: M,
|
||||
) -> SummarySink<'static, 's, M, W> {
|
||||
let interpolator =
|
||||
hyperlink::Interpolator::new(&self.config.hyperlink);
|
||||
let stats = if self.config.stats || self.config.kind.requires_stats() {
|
||||
Some(Stats::new())
|
||||
} else {
|
||||
@@ -408,6 +408,7 @@ impl<W: WriteColor> Summary<W> {
|
||||
SummarySink {
|
||||
matcher,
|
||||
summary: self,
|
||||
interpolator,
|
||||
path: None,
|
||||
start_time: Instant::now(),
|
||||
match_count: 0,
|
||||
@@ -432,18 +433,19 @@ impl<W: WriteColor> Summary<W> {
|
||||
if !self.config.path && !self.config.kind.requires_path() {
|
||||
return self.sink(matcher);
|
||||
}
|
||||
let interpolator =
|
||||
hyperlink::Interpolator::new(&self.config.hyperlink);
|
||||
let stats = if self.config.stats || self.config.kind.requires_stats() {
|
||||
Some(Stats::new())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let ppath = PrinterPath::with_separator(
|
||||
path.as_ref(),
|
||||
self.config.separator_path,
|
||||
);
|
||||
let ppath = PrinterPath::new(path.as_ref())
|
||||
.with_separator(self.config.separator_path);
|
||||
SummarySink {
|
||||
matcher,
|
||||
summary: self,
|
||||
interpolator,
|
||||
path: Some(ppath),
|
||||
start_time: Instant::now(),
|
||||
match_count: 0,
|
||||
@@ -490,6 +492,7 @@ impl<W> Summary<W> {
|
||||
pub struct SummarySink<'p, 's, M: Matcher, W> {
|
||||
matcher: M,
|
||||
summary: &'s mut Summary<W>,
|
||||
interpolator: hyperlink::Interpolator,
|
||||
path: Option<PrinterPath<'p>>,
|
||||
start_time: Instant,
|
||||
match_count: u64,
|
||||
@@ -595,36 +598,34 @@ impl<'p, 's, M: Matcher, W: WriteColor> SummarySink<'p, 's, M, W> {
|
||||
/// (color and hyperlink).
|
||||
fn write_path(&mut self) -> io::Result<()> {
|
||||
if self.path.is_some() {
|
||||
let mut hyperlink = self.start_hyperlink_span()?;
|
||||
|
||||
let status = self.start_hyperlink()?;
|
||||
self.write_spec(
|
||||
self.summary.config.colors.path(),
|
||||
self.path.as_ref().unwrap().as_bytes(),
|
||||
)?;
|
||||
|
||||
if hyperlink.is_active() {
|
||||
hyperlink.end(&mut *self.summary.wtr.borrow_mut())?;
|
||||
}
|
||||
self.end_hyperlink(status)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Starts a hyperlink span when applicable.
|
||||
fn start_hyperlink_span(&mut self) -> io::Result<HyperlinkSpan> {
|
||||
if let Some(ref path) = self.path {
|
||||
let mut wtr = self.summary.wtr.borrow_mut();
|
||||
if wtr.supports_hyperlinks() {
|
||||
if let Some(spec) = path.create_hyperlink_spec(
|
||||
&self.summary.config.hyperlink_pattern,
|
||||
None,
|
||||
None,
|
||||
&mut self.summary.buf,
|
||||
) {
|
||||
return Ok(HyperlinkSpan::start(&mut *wtr, &spec)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(HyperlinkSpan::default())
|
||||
fn start_hyperlink(
|
||||
&mut self,
|
||||
) -> io::Result<hyperlink::InterpolatorStatus> {
|
||||
let Some(hyperpath) =
|
||||
self.path.as_ref().and_then(|p| p.as_hyperlink())
|
||||
else {
|
||||
return Ok(hyperlink::InterpolatorStatus::inactive());
|
||||
};
|
||||
let values = hyperlink::Values::new(hyperpath);
|
||||
self.interpolator.begin(&values, &mut *self.summary.wtr.borrow_mut())
|
||||
}
|
||||
|
||||
fn end_hyperlink(
|
||||
&self,
|
||||
status: hyperlink::InterpolatorStatus,
|
||||
) -> io::Result<()> {
|
||||
self.interpolator.finish(status, &mut *self.summary.wtr.borrow_mut())
|
||||
}
|
||||
|
||||
/// Write the line terminator configured on the given searcher.
|
||||
|
@@ -1,21 +1,17 @@
|
||||
use std::{borrow::Cow, fmt, io, path::Path, time};
|
||||
use std::{borrow::Cow, cell::OnceCell, fmt, io, path::Path, time};
|
||||
|
||||
use {
|
||||
bstr::{ByteSlice, ByteVec},
|
||||
bstr::ByteVec,
|
||||
grep_matcher::{Captures, LineTerminator, Match, Matcher},
|
||||
grep_searcher::{
|
||||
LineIter, Searcher, SinkContext, SinkContextKind, SinkError, SinkMatch,
|
||||
},
|
||||
termcolor::HyperlinkSpec,
|
||||
};
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Serialize, Serializer};
|
||||
|
||||
use crate::{
|
||||
hyperlink::{HyperlinkPath, HyperlinkPattern, HyperlinkValues},
|
||||
MAX_LOOK_AHEAD,
|
||||
};
|
||||
use crate::{hyperlink::HyperlinkPath, MAX_LOOK_AHEAD};
|
||||
|
||||
/// A type for handling replacements while amortizing allocation.
|
||||
pub(crate) struct Replacer<M: Matcher> {
|
||||
@@ -268,11 +264,12 @@ impl<'a> Sunk<'a> {
|
||||
/// something else. This allows us to amortize work if we are printing the
|
||||
/// file path for every match.
|
||||
///
|
||||
/// In the common case, no transformation is needed, which lets us avoid the
|
||||
/// allocation. Typically, only Windows requires a transform, since we can't
|
||||
/// access the raw bytes of a path directly and first need to lossily convert
|
||||
/// to UTF-8. Windows is also typically where the path separator replacement
|
||||
/// is used, e.g., in cygwin environments to use `/` instead of `\`.
|
||||
/// In the common case, no transformation is needed, which lets us avoid
|
||||
/// the allocation. Typically, only Windows requires a transform, since
|
||||
/// it's fraught to access the raw bytes of a path directly and first need
|
||||
/// to lossily convert to UTF-8. Windows is also typically where the path
|
||||
/// separator replacement is used, e.g., in cygwin environments to use `/`
|
||||
/// instead of `\`.
|
||||
///
|
||||
/// Users of this type are expected to construct it from a normal `Path`
|
||||
/// found in the standard library. It can then be written to any `io::Write`
|
||||
@@ -281,54 +278,55 @@ impl<'a> Sunk<'a> {
|
||||
/// will not roundtrip correctly.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct PrinterPath<'a> {
|
||||
// On Unix, we can re-materialize a `Path` from our `Cow<'a, [u8]>` with
|
||||
// zero cost, so there's no point in storing it. At time of writing,
|
||||
// OsStr::as_os_str_bytes (and its corresponding constructor) are not
|
||||
// stable yet. Those would let us achieve the same end portably. (As long
|
||||
// as we keep our UTF-8 requirement on Windows.)
|
||||
#[cfg(not(unix))]
|
||||
path: &'a Path,
|
||||
bytes: Cow<'a, [u8]>,
|
||||
hyperlink_path: std::cell::OnceCell<Option<HyperlinkPath>>,
|
||||
hyperlink: OnceCell<Option<HyperlinkPath>>,
|
||||
}
|
||||
|
||||
impl<'a> PrinterPath<'a> {
|
||||
/// Create a new path suitable for printing.
|
||||
pub(crate) fn new(path: &'a Path) -> PrinterPath<'a> {
|
||||
PrinterPath {
|
||||
#[cfg(not(unix))]
|
||||
path,
|
||||
// N.B. This is zero-cost on Unix and requires at least a UTF-8
|
||||
// check on Windows. This doesn't allocate on Windows unless the
|
||||
// path is invalid UTF-8 (which is exceptionally rare).
|
||||
bytes: Vec::from_path_lossy(path),
|
||||
hyperlink_path: std::cell::OnceCell::new(),
|
||||
hyperlink: OnceCell::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new printer path from the given path which can be efficiently
|
||||
/// written to a writer without allocation.
|
||||
/// Set the separator on this path.
|
||||
///
|
||||
/// If the given separator is present, then any separators in `path` are
|
||||
/// replaced with it.
|
||||
/// When set, `PrinterPath::as_bytes` will return the path provided but
|
||||
/// with its separator replaced with the one given.
|
||||
pub(crate) fn with_separator(
|
||||
path: &'a Path,
|
||||
mut self,
|
||||
sep: Option<u8>,
|
||||
) -> PrinterPath<'a> {
|
||||
let mut ppath = PrinterPath::new(path);
|
||||
if let Some(sep) = sep {
|
||||
ppath.replace_separator(sep);
|
||||
}
|
||||
ppath
|
||||
}
|
||||
|
||||
/// Replace the path separator in this path with the given separator
|
||||
/// and do it in place. On Windows, both `/` and `\` are treated as
|
||||
/// path separators that are both replaced by `new_sep`. In all other
|
||||
/// environments, only `/` is treated as a path separator.
|
||||
fn replace_separator(&mut self, new_sep: u8) {
|
||||
let transformed_path: Vec<u8> = self
|
||||
.as_bytes()
|
||||
.bytes()
|
||||
.map(|b| {
|
||||
if b == b'/' || (cfg!(windows) && b == b'\\') {
|
||||
new_sep
|
||||
} else {
|
||||
b
|
||||
/// Replace the path separator in this path with the given separator
|
||||
/// and do it in place. On Windows, both `/` and `\` are treated as
|
||||
/// path separators that are both replaced by `new_sep`. In all other
|
||||
/// environments, only `/` is treated as a path separator.
|
||||
fn replace_separator(bytes: &[u8], sep: u8) -> Vec<u8> {
|
||||
let mut bytes = bytes.to_vec();
|
||||
for b in bytes.iter_mut() {
|
||||
if *b == b'/' || (cfg!(windows) && *b == b'\\') {
|
||||
*b = sep;
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
self.bytes = Cow::Owned(transformed_path);
|
||||
}
|
||||
bytes
|
||||
}
|
||||
let Some(sep) = sep else { return self };
|
||||
self.bytes = Cow::Owned(replace_separator(self.as_bytes(), sep));
|
||||
self
|
||||
}
|
||||
|
||||
/// Return the raw bytes for this path.
|
||||
@@ -336,32 +334,30 @@ impl<'a> PrinterPath<'a> {
|
||||
&self.bytes
|
||||
}
|
||||
|
||||
/// Creates a hyperlink for this path and the given line and column, using
|
||||
/// the specified pattern. Uses the given buffer to store the hyperlink.
|
||||
pub(crate) fn create_hyperlink_spec<'b>(
|
||||
&self,
|
||||
pattern: &HyperlinkPattern,
|
||||
line_number: Option<u64>,
|
||||
column: Option<u64>,
|
||||
buffer: &'b mut Vec<u8>,
|
||||
) -> Option<HyperlinkSpec<'b>> {
|
||||
if pattern.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let file_path = self.hyperlink_path()?;
|
||||
let values = HyperlinkValues::new(file_path, line_number, column);
|
||||
buffer.clear();
|
||||
pattern.render(&values, buffer).ok()?;
|
||||
Some(HyperlinkSpec::open(buffer))
|
||||
/// Return this path as a hyperlink.
|
||||
///
|
||||
/// Note that a hyperlink may not be able to be created from a path.
|
||||
/// Namely, computing the hyperlink may require touching the file system
|
||||
/// (e.g., for path canonicalization) and that can fail. This failure is
|
||||
/// silent but is logged.
|
||||
pub(crate) fn as_hyperlink(&self) -> Option<&HyperlinkPath> {
|
||||
self.hyperlink
|
||||
.get_or_init(|| HyperlinkPath::from_path(self.as_path()))
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// Returns the file path to use in hyperlinks, if any.
|
||||
///
|
||||
/// This is what the {file} placeholder will be substituted with.
|
||||
fn hyperlink_path(&self) -> Option<&HyperlinkPath> {
|
||||
self.hyperlink_path
|
||||
.get_or_init(|| HyperlinkPath::from_path(self.path))
|
||||
.as_ref()
|
||||
/// Return this path as an actual `Path` type.
|
||||
fn as_path(&self) -> &Path {
|
||||
#[cfg(unix)]
|
||||
fn imp<'p>(p: &'p PrinterPath<'_>) -> &'p Path {
|
||||
use std::{ffi::OsStr, os::unix::ffi::OsStrExt};
|
||||
Path::new(OsStr::from_bytes(p.as_bytes()))
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
fn imp<'p>(p: &'p PrinterPath<'_>) -> &'p Path {
|
||||
p.path
|
||||
}
|
||||
imp(self)
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user