printer: deduplicate hyperlink alias names
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This exports a new `HyperlinkAlias` type in the `grep-printer` crate. This includes a "display priority" with each alias and a function for getting all supported aliases from the crate. This should hopefully make it possible for downstream users of this crate to include a list of supported aliases in the documentation. Closes #3103
authored by Lucas Trzesniewski · committed by Andrew Gallant · parent fdfda9a · Browse files · 6 files·+1232 added−1134 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+1232 added−1134 removed
- other:+1232 added−1134 removed
Provenance
- Commit
66aa4a6- Tree
8972b0e- Author
Lucas Trzesniewski <lucas.trzesniewski@gmail.com>- Committer
Andrew Gallant <jamslam@gmail.com>- Parent
fdfda9a
6 files changed+1232 added−1134 removed
modified:crates/core/flags/defs.rs+27 added-7 removed
15 unmodified lines16 ripgrep. For example, `-E`, `--encoding` and `--no-encoding` all manipulate the17 same encoding state in ripgrep.18 */19 20-use std::path::PathBuf;20+use std::{path::PathBuf, sync::LazyLock};21 22 use {anyhow::Context as AnyhowContext, bstr::ByteVec};23 24 use crate::flags::{2871 unmodified lines2896 fn doc_short(&self) -> &'static str {2897 r"Set the format of hyperlinks."2898 }2899 fn doc_long(&self) -> &'static str {2900+ static DOC: LazyLock<String> = LazyLock::new(|| {2901+ let mut doc = String::new();2902+ doc.push_str(2900- r#"2903+ r#"2904 Set the format of hyperlinks to use when printing results. Hyperlinks make2905 certain elements of ripgrep's output, such as file paths, clickable. This2906 generally only works in terminal emulators that support OSC-8 hyperlinks. For2907 example, the format \fBfile://{host}{path}\fP will emit an RFC 8089 hyperlink.2908 To see the format that ripgrep is using, pass the \flag{debug} flag.2909 .sp2910 Alternatively, a format string may correspond to one of the following aliases:2908-\fBdefault\fP, \fBnone\fP, \fBfile\fP, \fBgrep+\fP, \fBkitty\fP, \fBmacvim\fP,2909-\fBtextmate\fP, \fBvscode\fP, \fBvscode-insiders\fP, \fBvscodium\fP. The2910-alias will be replaced with a format string that is intended to work for the2911-corresponding application.2911+"#,2912+ );2913+2914+ let mut aliases = grep::printer::hyperlink_aliases();2915+ aliases.sort_by_key(|alias| {2916+ alias.display_priority().unwrap_or(i16::MAX)2917+ });2918+ for (i, alias) in aliases.iter().enumerate() {2919+ doc.push_str(r"\fB");2920+ doc.push_str(alias.name());2921+ doc.push_str(r"\fP");2922+ doc.push_str(if i < aliases.len() - 1 { ", " } else { "." });2923+ }2924+ doc.push_str(2925+ r#"2926+The alias will be replaced with a format string that is intended to work for2927+the corresponding application.2928 .sp2929 The following variables are available in the format string:2930 .sp2931 .TP 1268 unmodified lines3000 \flag{with-filename} flag.3001 .sp3002 For more information on hyperlinks in terminal emulators, see:3003 https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda2988-"#3004+"#,3005+ );3006+ doc3007+ });3008+ &DOC3009 }3010 3011 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3012 let v = v.unwrap_value();4722 unmodified linesadded:crates/printer/src/hyperlink/aliases.rs+44 added
1+use crate::hyperlink::HyperlinkAlias;2+3+/// Aliases to well-known hyperlink schemes.4+///5+/// These need to be sorted by name.6+pub(super) const HYPERLINK_PATTERN_ALIASES: &[HyperlinkAlias] = &[7+ #[cfg(not(windows))]8+ prioritized_alias(0, "default", "file://{host}{path}"),9+ #[cfg(windows)]10+ prioritized_alias(0, "default", "file://{path}"),11+ alias("file", "file://{host}{path}"),12+ // https://github.com/misaki-web/grepp13+ alias("grep+", "grep+://{path}:{line}"),14+ alias("kitty", "file://{host}{path}#{line}"),15+ // https://macvim.org/docs/gui_mac.txt.html#mvim%3A%2F%2F16+ alias(17+ "macvim",18+ "mvim://open?url=file://{path}&line={line}&column={column}",19+ ),20+ prioritized_alias(1, "none", ""),21+ // https://macromates.com/blog/2007/the-textmate-url-scheme/22+ alias(23+ "textmate",24+ "txmt://open?url=file://{path}&line={line}&column={column}",25+ ),26+ // https://code.visualstudio.com/docs/editor/command-line#_opening-vs-code-with-urls27+ alias("vscode", "vscode://file{path}:{line}:{column}"),28+ alias("vscode-insiders", "vscode-insiders://file{path}:{line}:{column}"),29+ alias("vscodium", "vscodium://file{path}:{line}:{column}"),30+];31+32+/// Creates a [`HyperlinkAlias`].33+const fn alias(name: &'static str, format: &'static str) -> HyperlinkAlias {34+ HyperlinkAlias { name, format, display_priority: None }35+}36+37+/// Creates a [`HyperlinkAlias`] with a display priority.38+const fn prioritized_alias(39+ priority: i16,40+ name: &'static str,41+ format: &'static str,42+) -> HyperlinkAlias {43+ HyperlinkAlias { name, format, display_priority: Some(priority) }44+}added:crates/printer/src/hyperlink/mod.rs+1159 added
1+use std::{cell::RefCell, io, path::Path, sync::Arc};2+3+use {4+ bstr::ByteSlice,5+ termcolor::{HyperlinkSpec, WriteColor},6+};7+8+use crate::util::DecimalFormatter;9+10+use self::aliases::HYPERLINK_PATTERN_ALIASES;11+12+mod aliases;13+14+/// Hyperlink configuration.15+///16+/// This configuration specifies both the [hyperlink format](HyperlinkFormat)17+/// and an [environment](HyperlinkConfig) for interpolating a subset of18+/// variables. The specific subset includes variables that are intended to19+/// be invariant throughout the lifetime of a process, such as a machine's20+/// hostname.21+///22+/// A hyperlink configuration can be provided to printer builders such as23+/// [`StandardBuilder::hyperlink`](crate::StandardBuilder::hyperlink).24+#[derive(Clone, Debug, Default, Eq, PartialEq)]25+pub struct HyperlinkConfig(Arc<HyperlinkConfigInner>);26+27+#[derive(Clone, Debug, Default, Eq, PartialEq)]28+struct HyperlinkConfigInner {29+ env: HyperlinkEnvironment,30+ format: HyperlinkFormat,31+}32+33+impl HyperlinkConfig {34+ /// Create a new configuration from an environment and a format.35+ pub fn new(36+ env: HyperlinkEnvironment,37+ format: HyperlinkFormat,38+ ) -> HyperlinkConfig {39+ HyperlinkConfig(Arc::new(HyperlinkConfigInner { env, format }))40+ }41+42+ /// Returns the hyperlink environment in this configuration.43+ pub(crate) fn environment(&self) -> &HyperlinkEnvironment {44+ &self.0.env45+ }46+47+ /// Returns the hyperlink format in this configuration.48+ pub(crate) fn format(&self) -> &HyperlinkFormat {49+ &self.0.format50+ }51+}52+53+/// A hyperlink format with variables.54+///55+/// This can be created by parsing a string using `HyperlinkFormat::from_str`.56+///57+/// The default format is empty. An empty format is valid and effectively58+/// disables hyperlinks.59+///60+/// # Example61+///62+/// ```63+/// use grep_printer::HyperlinkFormat;64+///65+/// let fmt = "vscode".parse::<HyperlinkFormat>()?;66+/// assert_eq!(fmt.to_string(), "vscode://file{path}:{line}:{column}");67+///68+/// # Ok::<(), Box<dyn std::error::Error>>(())69+/// ```70+#[derive(Clone, Debug, Default, Eq, PartialEq)]71+pub struct HyperlinkFormat {72+ parts: Vec<Part>,73+ is_line_dependent: bool,74+}75+76+impl HyperlinkFormat {77+ /// Creates an empty hyperlink format.78+ pub fn empty() -> HyperlinkFormat {79+ HyperlinkFormat::default()80+ }81+82+ /// Returns true if this format is empty.83+ pub fn is_empty(&self) -> bool {84+ self.parts.is_empty()85+ }86+87+ /// Creates a [`HyperlinkConfig`] from this format and the environment88+ /// given.89+ pub fn into_config(self, env: HyperlinkEnvironment) -> HyperlinkConfig {90+ HyperlinkConfig::new(env, self)91+ }92+93+ /// Returns true if the format can produce line-dependent hyperlinks.94+ pub(crate) fn is_line_dependent(&self) -> bool {95+ self.is_line_dependent96+ }97+}98+99+impl std::str::FromStr for HyperlinkFormat {100+ type Err = HyperlinkFormatError;101+102+ fn from_str(s: &str) -> Result<HyperlinkFormat, HyperlinkFormatError> {103+ use self::HyperlinkFormatErrorKind::*;104+105+ #[derive(Debug)]106+ enum State {107+ Verbatim,108+ VerbatimCloseVariable,109+ OpenVariable,110+ InVariable,111+ }112+113+ let mut builder = FormatBuilder::new();114+ let input = match HyperlinkAlias::find(s) {115+ Some(alias) => alias.format(),116+ None => s,117+ };118+ let mut name = String::new();119+ let mut state = State::Verbatim;120+ let err = |kind| HyperlinkFormatError { kind };121+ for ch in input.chars() {122+ state = match state {123+ State::Verbatim => {124+ if ch == '{' {125+ State::OpenVariable126+ } else if ch == '}' {127+ State::VerbatimCloseVariable128+ } else {129+ builder.append_char(ch);130+ State::Verbatim131+ }132+ }133+ State::VerbatimCloseVariable => {134+ if ch == '}' {135+ builder.append_char('}');136+ State::Verbatim137+ } else {138+ return Err(err(InvalidCloseVariable));139+ }140+ }141+ State::OpenVariable => {142+ if ch == '{' {143+ builder.append_char('{');144+ State::Verbatim145+ } else {146+ name.clear();147+ if ch == '}' {148+ builder.append_var(&name)?;149+ State::Verbatim150+ } else {151+ name.push(ch);152+ State::InVariable153+ }154+ }155+ }156+ State::InVariable => {157+ if ch == '}' {158+ builder.append_var(&name)?;159+ State::Verbatim160+ } else {161+ name.push(ch);162+ State::InVariable163+ }164+ }165+ };166+ }167+ match state {168+ State::Verbatim => builder.build(),169+ State::VerbatimCloseVariable => Err(err(InvalidCloseVariable)),170+ State::OpenVariable | State::InVariable => {171+ Err(err(UnclosedVariable))172+ }173+ }174+ }175+}176+177+impl std::fmt::Display for HyperlinkFormat {178+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {179+ for part in self.parts.iter() {180+ part.fmt(f)?;181+ }182+ Ok(())183+ }184+}185+186+/// An alias for a hyperlink format.187+///188+/// Hyperlink aliases are built-in formats, therefore they hold static values.189+/// Some of their features are usable in const blocks.190+#[derive(Clone, Debug)]191+pub struct HyperlinkAlias {192+ name: &'static str,193+ format: &'static str,194+ display_priority: Option<i16>,195+}196+197+impl HyperlinkAlias {198+ /// Returns the name of the alias.199+ pub const fn name(&self) -> &str {200+ self.name201+ }202+203+ /// Returns the display priority of this alias.204+ ///205+ /// If no priority is set, then `None` is returned.206+ ///207+ /// The display priority is meant to reflect some special status associated208+ /// with an alias. For example, the `default` and `none` aliases have a209+ /// display priority. This is meant to encourage listing them first in210+ /// documentation.211+ ///212+ /// A lower display priority implies the alias should be shown before213+ /// aliases with a higher (or absent) display priority.214+ ///215+ /// Callers cannot rely on any specific display priority value to remain216+ /// stable across semver compatible releases of this crate.217+ pub const fn display_priority(&self) -> Option<i16> {218+ self.display_priority219+ }220+221+ /// Returns the format string of the alias.222+ const fn format(&self) -> &'static str {223+ self.format224+ }225+226+ /// Looks for the hyperlink alias defined by the given name.227+ ///228+ /// If one does not exist, `None` is returned.229+ fn find(name: &str) -> Option<&HyperlinkAlias> {230+ HYPERLINK_PATTERN_ALIASES231+ .binary_search_by_key(&name, |alias| alias.name())232+ .map(|i| &HYPERLINK_PATTERN_ALIASES[i])233+ .ok()234+ }235+}236+237+/// A static environment for hyperlink interpolation.238+///239+/// This environment permits setting the values of variables used in hyperlink240+/// interpolation that are not expected to change for the lifetime of a program.241+/// That is, these values are invariant.242+///243+/// Currently, this includes the hostname and a WSL distro prefix.244+#[derive(Clone, Debug, Default, Eq, PartialEq)]245+pub struct HyperlinkEnvironment {246+ host: Option<String>,247+ wsl_prefix: Option<String>,248+}249+250+impl HyperlinkEnvironment {251+ /// Create a new empty hyperlink environment.252+ pub fn new() -> HyperlinkEnvironment {253+ HyperlinkEnvironment::default()254+ }255+256+ /// Set the `{host}` variable, which fills in any hostname components of257+ /// a hyperlink.258+ ///259+ /// One can get the hostname in the current environment via the `hostname`260+ /// function in the `grep-cli` crate.261+ pub fn host(&mut self, host: Option<String>) -> &mut HyperlinkEnvironment {262+ self.host = host;263+ self264+ }265+266+ /// Set the `{wslprefix}` variable, which contains the WSL distro prefix.267+ /// An example value is `wsl$/Ubuntu`. The distro name can typically be268+ /// discovered from the `WSL_DISTRO_NAME` environment variable.269+ pub fn wsl_prefix(270+ &mut self,271+ wsl_prefix: Option<String>,272+ ) -> &mut HyperlinkEnvironment {273+ self.wsl_prefix = wsl_prefix;274+ self275+ }276+}277+278+/// An error that can occur when parsing a hyperlink format.279+#[derive(Clone, Debug, Eq, PartialEq)]280+pub struct HyperlinkFormatError {281+ kind: HyperlinkFormatErrorKind,282+}283+284+#[derive(Clone, Debug, Eq, PartialEq)]285+enum HyperlinkFormatErrorKind {286+ /// This occurs when there are zero variables in the format.287+ NoVariables,288+ /// This occurs when the {path} variable is missing.289+ NoPathVariable,290+ /// This occurs when the {line} variable is missing, while the {column}291+ /// variable is present.292+ NoLineVariable,293+ /// This occurs when an unknown variable is used.294+ InvalidVariable(String),295+ /// The format doesn't start with a valid scheme.296+ InvalidScheme,297+ /// This occurs when an unescaped `}` is found without a corresponding298+ /// `{` preceding it.299+ InvalidCloseVariable,300+ /// This occurs when a `{` is found without a corresponding `}` following301+ /// it.302+ UnclosedVariable,303+}304+305+impl std::error::Error for HyperlinkFormatError {}306+307+impl std::fmt::Display for HyperlinkFormatError {308+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {309+ use self::HyperlinkFormatErrorKind::*;310+311+ match self.kind {312+ NoVariables => {313+ let mut aliases = hyperlink_aliases();314+ aliases.sort_by_key(|alias| {315+ alias.display_priority().unwrap_or(i16::MAX)316+ });317+ let names: Vec<&str> =318+ aliases.iter().map(|alias| alias.name()).collect();319+ write!(320+ f,321+ "at least a {{path}} variable is required in a \322+ hyperlink format, or otherwise use a valid alias: \323+ {aliases}",324+ aliases = names.join(", "),325+ )326+ }327+ NoPathVariable => {328+ write!(329+ f,330+ "the {{path}} variable is required in a hyperlink format",331+ )332+ }333+ NoLineVariable => {334+ write!(335+ f,336+ "the hyperlink format contains a {{column}} variable, \337+ but no {{line}} variable is present",338+ )339+ }340+ InvalidVariable(ref name) => {341+ write!(342+ f,343+ "invalid hyperlink format variable: '{name}', choose \344+ from: path, line, column, host, wslprefix",345+ )346+ }347+ InvalidScheme => {348+ write!(349+ f,350+ "the hyperlink format must start with a valid URL scheme, \351+ i.e., [0-9A-Za-z+-.]+:",352+ )353+ }354+ InvalidCloseVariable => {355+ write!(356+ f,357+ "unopened variable: found '}}' without a \358+ corresponding '{{' preceding it",359+ )360+ }361+ UnclosedVariable => {362+ write!(363+ f,364+ "unclosed variable: found '{{' without a \365+ corresponding '}}' following it",366+ )367+ }368+ }369+ }370+}371+372+/// A builder for `HyperlinkFormat`.373+///374+/// Once a `HyperlinkFormat` is built, it is immutable.375+#[derive(Debug)]376+struct FormatBuilder {377+ parts: Vec<Part>,378+}379+380+impl FormatBuilder {381+ /// Creates a new hyperlink format builder.382+ fn new() -> FormatBuilder {383+ FormatBuilder { parts: vec![] }384+ }385+386+ /// Appends static text.387+ fn append_slice(&mut self, text: &[u8]) -> &mut FormatBuilder {388+ if let Some(Part::Text(contents)) = self.parts.last_mut() {389+ contents.extend_from_slice(text);390+ } else if !text.is_empty() {391+ self.parts.push(Part::Text(text.to_vec()));392+ }393+ self394+ }395+396+ /// Appends a single character.397+ fn append_char(&mut self, ch: char) -> &mut FormatBuilder {398+ self.append_slice(ch.encode_utf8(&mut [0; 4]).as_bytes())399+ }400+401+ /// Appends a variable with the given name. If the name isn't recognized,402+ /// then this returns an error.403+ fn append_var(404+ &mut self,405+ name: &str,406+ ) -> Result<&mut FormatBuilder, HyperlinkFormatError> {407+ let part = match name {408+ "host" => Part::Host,409+ "wslprefix" => Part::WSLPrefix,410+ "path" => Part::Path,411+ "line" => Part::Line,412+ "column" => Part::Column,413+ unknown => {414+ let err = HyperlinkFormatError {415+ kind: HyperlinkFormatErrorKind::InvalidVariable(416+ unknown.to_string(),417+ ),418+ };419+ return Err(err);420+ }421+ };422+ self.parts.push(part);423+ Ok(self)424+ }425+426+ /// Builds the format.427+ fn build(&self) -> Result<HyperlinkFormat, HyperlinkFormatError> {428+ self.validate()?;429+ Ok(HyperlinkFormat {430+ parts: self.parts.clone(),431+ is_line_dependent: self.parts.contains(&Part::Line),432+ })433+ }434+435+ /// Validate that the format is well-formed.436+ fn validate(&self) -> Result<(), HyperlinkFormatError> {437+ use self::HyperlinkFormatErrorKind::*;438+439+ let err = |kind| HyperlinkFormatError { kind };440+ // An empty format is fine. It just means hyperlink support is441+ // disabled.442+ if self.parts.is_empty() {443+ return Ok(());444+ }445+ // If all parts are just text, then there are no variables. It's446+ // likely a reference to an invalid alias.447+ if self.parts.iter().all(|p| matches!(*p, Part::Text(_))) {448+ return Err(err(NoVariables));449+ }450+ // Even if we have other variables, no path variable means the451+ // hyperlink can't possibly work the way it is intended.452+ if !self.parts.contains(&Part::Path) {453+ return Err(err(NoPathVariable));454+ }455+ // If the {column} variable is used, then we also need a {line}456+ // variable or else {column} can't possibly work.457+ if self.parts.contains(&Part::Column)458+ && !self.parts.contains(&Part::Line)459+ {460+ return Err(err(NoLineVariable));461+ }462+ self.validate_scheme()463+ }464+465+ /// Validate that the format starts with a valid scheme. Validation is done466+ /// according to how a scheme is defined in RFC 1738 sections 2.1[1] and467+ /// 5[2]. In short, a scheme is this:468+ ///469+ /// scheme = 1*[ lowalpha | digit | "+" | "-" | "." ]470+ ///471+ /// but is case insensitive.472+ ///473+ /// [1]: https://datatracker.ietf.org/doc/html/rfc1738#section-2.1474+ /// [2]: https://datatracker.ietf.org/doc/html/rfc1738#section-5475+ fn validate_scheme(&self) -> Result<(), HyperlinkFormatError> {476+ let err_invalid_scheme = HyperlinkFormatError {477+ kind: HyperlinkFormatErrorKind::InvalidScheme,478+ };479+ let Some(Part::Text(ref part)) = self.parts.first() else {480+ return Err(err_invalid_scheme);481+ };482+ let Some(colon) = part.find_byte(b':') else {483+ return Err(err_invalid_scheme);484+ };485+ let scheme = &part[..colon];486+ if scheme.is_empty() {487+ return Err(err_invalid_scheme);488+ }489+ let is_valid_scheme_char = |byte| match byte {490+ b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b'+' | b'-' | b'.' => {491+ true492+ }493+ _ => false,494+ };495+ if !scheme.iter().all(|&b| is_valid_scheme_char(b)) {496+ return Err(err_invalid_scheme);497+ }498+ Ok(())499+ }500+}501+502+/// A hyperlink format part.503+///504+/// A sequence of these corresponds to a complete format. (Not all sequences505+/// are valid.)506+#[derive(Clone, Debug, Eq, PartialEq)]507+enum Part {508+ /// Static text.509+ ///510+ /// We use `Vec<u8>` here (and more generally treat a format string as a511+ /// sequence of bytes) because file paths may be arbitrary bytes. A rare512+ /// case, but one for which there is no good reason to choke on.513+ Text(Vec<u8>),514+ /// Variable for the hostname.515+ Host,516+ /// Variable for a WSL path prefix.517+ WSLPrefix,518+ /// Variable for the file path.519+ Path,520+ /// Variable for the line number.521+ Line,522+ /// Variable for the column number.523+ Column,524+}525+526+impl Part {527+ /// Interpolate this part using the given `env` and `values`, and write528+ /// the result of interpolation to the buffer provided.529+ fn interpolate_to(530+ &self,531+ env: &HyperlinkEnvironment,532+ values: &Values,533+ dest: &mut Vec<u8>,534+ ) {535+ match self {536+ Part::Text(ref text) => dest.extend_from_slice(text),537+ Part::Host => dest.extend_from_slice(538+ env.host.as_ref().map(|s| s.as_bytes()).unwrap_or(b""),539+ ),540+ Part::WSLPrefix => dest.extend_from_slice(541+ env.wsl_prefix.as_ref().map(|s| s.as_bytes()).unwrap_or(b""),542+ ),543+ Part::Path => dest.extend_from_slice(&values.path.0),544+ Part::Line => {545+ let line = DecimalFormatter::new(values.line.unwrap_or(1));546+ dest.extend_from_slice(line.as_bytes());547+ }548+ Part::Column => {549+ let column = DecimalFormatter::new(values.column.unwrap_or(1));550+ dest.extend_from_slice(column.as_bytes());551+ }552+ }553+ }554+}555+556+impl std::fmt::Display for Part {557+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {558+ match self {559+ Part::Text(text) => write!(f, "{}", String::from_utf8_lossy(text)),560+ Part::Host => write!(f, "{{host}}"),561+ Part::WSLPrefix => write!(f, "{{wslprefix}}"),562+ Part::Path => write!(f, "{{path}}"),563+ Part::Line => write!(f, "{{line}}"),564+ Part::Column => write!(f, "{{column}}"),565+ }566+ }567+}568+569+/// The values to replace the format variables with.570+///571+/// This only consists of values that depend on each path or match printed.572+/// Values that are invariant throughout the lifetime of the process are set573+/// via a [`HyperlinkEnvironment`].574+#[derive(Clone, Debug)]575+pub(crate) struct Values<'a> {576+ path: &'a HyperlinkPath,577+ line: Option<u64>,578+ column: Option<u64>,579+}580+581+impl<'a> Values<'a> {582+ /// Creates a new set of values, starting with the path given.583+ ///584+ /// Callers may also set the line and column number using the mutator585+ /// methods.586+ pub(crate) fn new(path: &'a HyperlinkPath) -> Values<'a> {587+ Values { path, line: None, column: None }588+ }589+590+ /// Sets the line number for these values.591+ ///592+ /// If a line number is not set and a hyperlink format contains a `{line}`593+ /// variable, then it is interpolated with the value of `1` automatically.594+ pub(crate) fn line(mut self, line: Option<u64>) -> Values<'a> {595+ self.line = line;596+ self597+ }598+599+ /// Sets the column number for these values.600+ ///601+ /// If a column number is not set and a hyperlink format contains a602+ /// `{column}` variable, then it is interpolated with the value of `1`603+ /// automatically.604+ pub(crate) fn column(mut self, column: Option<u64>) -> Values<'a> {605+ self.column = column;606+ self607+ }608+}609+610+/// An abstraction for interpolating a hyperlink format with values for every611+/// variable.612+///613+/// Interpolation of variables occurs through two different sources. The614+/// first is via a `HyperlinkEnvironment` for values that are expected to615+/// be invariant. This comes from the `HyperlinkConfig` used to build this616+/// interpolator. The second source is via `Values`, which is provided to617+/// `Interpolator::begin`. The `Values` contains things like the file path,618+/// line number and column number.619+#[derive(Clone, Debug)]620+pub(crate) struct Interpolator {621+ config: HyperlinkConfig,622+ buf: RefCell<Vec<u8>>,623+}624+625+impl Interpolator {626+ /// Create a new interpolator for the given hyperlink format configuration.627+ pub(crate) fn new(config: &HyperlinkConfig) -> Interpolator {628+ Interpolator { config: config.clone(), buf: RefCell::new(vec![]) }629+ }630+631+ /// Start interpolation with the given values by writing a hyperlink632+ /// to `wtr`. Subsequent writes to `wtr`, until `Interpolator::end` is633+ /// called, are the label for the hyperlink.634+ ///635+ /// This returns an interpolator status which indicates whether the636+ /// hyperlink was written. It might not be written, for example, if the637+ /// underlying writer doesn't support hyperlinks or if the hyperlink638+ /// format is empty. The status should be provided to `Interpolator::end`639+ /// as an instruction for whether to close the hyperlink or not.640+ pub(crate) fn begin<W: WriteColor>(641+ &self,642+ values: &Values,643+ mut wtr: W,644+ ) -> io::Result<InterpolatorStatus> {645+ if self.config.format().is_empty()646+ || !wtr.supports_hyperlinks()647+ || !wtr.supports_color()648+ {649+ return Ok(InterpolatorStatus::inactive());650+ }651+ let mut buf = self.buf.borrow_mut();652+ buf.clear();653+ for part in self.config.format().parts.iter() {654+ part.interpolate_to(self.config.environment(), values, &mut buf);655+ }656+ let spec = HyperlinkSpec::open(&buf);657+ wtr.set_hyperlink(&spec)?;658+ Ok(InterpolatorStatus { active: true })659+ }660+661+ /// Writes the correct escape sequences to `wtr` to close any extant662+ /// hyperlink, marking the end of a hyperlink's label.663+ ///664+ /// The status given should be returned from a corresponding665+ /// `Interpolator::begin` call. Since `begin` may not write a hyperlink666+ /// (e.g., if the underlying writer doesn't support hyperlinks), it follows667+ /// that `finish` must not close a hyperlink that was never opened. The668+ /// status indicates whether the hyperlink was opened or not.669+ pub(crate) fn finish<W: WriteColor>(670+ &self,671+ status: InterpolatorStatus,672+ mut wtr: W,673+ ) -> io::Result<()> {674+ if !status.active {675+ return Ok(());676+ }677+ wtr.set_hyperlink(&HyperlinkSpec::close())678+ }679+}680+681+/// A status indicating whether a hyperlink was written or not.682+///683+/// This is created by `Interpolator::begin` and used by `Interpolator::finish`684+/// to determine whether a hyperlink was actually opened or not. If it wasn't685+/// opened, then finishing interpolation is a no-op.686+#[derive(Debug)]687+pub(crate) struct InterpolatorStatus {688+ active: bool,689+}690+691+impl InterpolatorStatus {692+ /// Create an inactive interpolator status.693+ #[inline]694+ pub(crate) fn inactive() -> InterpolatorStatus {695+ InterpolatorStatus { active: false }696+ }697+}698+699+/// Represents the `{path}` part of a hyperlink.700+///701+/// This is the value to use as-is in the hyperlink, converted from an OS file702+/// path.703+#[derive(Clone, Debug)]704+pub(crate) struct HyperlinkPath(Vec<u8>);705+706+impl HyperlinkPath {707+ /// Returns a hyperlink path from an OS path.708+ #[cfg(unix)]709+ pub(crate) fn from_path(original_path: &Path) -> Option<HyperlinkPath> {710+ use std::os::unix::ffi::OsStrExt;711+712+ // We canonicalize the path in order to get an absolute version of it713+ // without any `.` or `..` or superfluous separators. Unfortunately,714+ // this does also remove symlinks, and in theory, it would be nice to715+ // retain them. Perhaps even simpler, we could just join the current716+ // working directory with the path and be done with it. There was717+ // some discussion about this on PR#2483, and there generally appears718+ // to be some uncertainty about the extent to which hyperlinks with719+ // things like `..` in them actually work. So for now, we do the safest720+ // thing possible even though I think it can result in worse user721+ // experience. (Because it means the path you click on and the actual722+ // path that gets followed are different, even though they ostensibly723+ // refer to the same file.)724+ //725+ // There's also the potential issue that path canonicalization is726+ // expensive since it can touch the file system. That is probably727+ // less of an issue since hyperlinks are only created when they're728+ // supported, i.e., when writing to a tty.729+ //730+ // [1]: https://github.com/BurntSushi/ripgrep/pull/2483731+ let path = match original_path.canonicalize() {732+ Ok(path) => path,733+ Err(err) => {734+ log::debug!(735+ "hyperlink creation for {:?} failed, error occurred \736+ during path canonicalization: {}",737+ original_path,738+ err,739+ );740+ return None;741+ }742+ };743+ let bytes = path.as_os_str().as_bytes();744+ // This should not be possible since one imagines that canonicalization745+ // should always return an absolute path. But it doesn't actually746+ // appear guaranteed by POSIX, so we check whether it's true or not and747+ // refuse to create a hyperlink from a relative path if it isn't.748+ if !bytes.starts_with(b"/") {749+ log::debug!(750+ "hyperlink creation for {:?} failed, canonicalization \751+ returned {:?}, which does not start with a slash",752+ original_path,753+ path,754+ );755+ return None;756+ }757+ Some(HyperlinkPath::encode(bytes))758+ }759+760+ /// Returns a hyperlink path from an OS path.761+ #[cfg(windows)]762+ pub(crate) fn from_path(original_path: &Path) -> Option<HyperlinkPath> {763+ // On Windows, we use `std::path::absolute` instead of `Path::canonicalize`764+ // as it can be much faster since it does not touch the file system.765+ // It wraps the [`GetFullPathNameW`][1] API, except for verbatim paths766+ // (those which start with `\\?\`, see [the documentation][2] for details).767+ //768+ // Here, we strip any verbatim path prefixes since we cannot use them769+ // in hyperlinks anyway. This can only happen if the user explicitly770+ // supplies a verbatim path as input, which already needs to be absolute:771+ //772+ // \\?\C:\dir\file.txt (local path)773+ // \\?\UNC\server\dir\file.txt (network share)774+ //775+ // The `\\?\` prefix is constant for verbatim paths, and can be followed776+ // by `UNC\` (universal naming convention), which denotes a network share.777+ //778+ // Given that the default URL format on Windows is file://{path}779+ // we need to return the following from this function:780+ //781+ // /C:/dir/file.txt (local path)782+ // //server/dir/file.txt (network share)783+ //784+ // Which produces the following links:785+ //786+ // file:///C:/dir/file.txt (local path)787+ // file:////server/dir/file.txt (network share)788+ //789+ // This substitutes the {path} variable with the expected value for790+ // the most common DOS paths, but on the other hand, network paths791+ // start with a single slash, which may be unexpected. It seems to work792+ // though?793+ //794+ // Note that the following URL syntax also seems to be valid?795+ //796+ // file://server/dir/file.txt797+ //798+ // But the initial implementation of this routine went for the format799+ // above.800+ //801+ // Also note that the file://C:/dir/file.txt syntax is not correct,802+ // even though it often works in practice.803+ //804+ // In the end, this choice was confirmed by VSCode, whose format is805+ //806+ // vscode://file{path}:{line}:{column}807+ //808+ // and which correctly understands the following URL format for network809+ // drives:810+ //811+ // vscode://file//server/dir/file.txt:1:1812+ //813+ // It doesn't parse any other number of slashes in "file//server" as a814+ // network path.815+ //816+ // [1]: https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew817+ // [2]: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file818+819+ const WIN32_NAMESPACE_PREFIX: &str = r"\\?\";820+ const UNC_PREFIX: &str = r"UNC\";821+822+ let path = match std::path::absolute(original_path) {823+ Ok(path) => path,824+ Err(err) => {825+ log::debug!(826+ "hyperlink creation for {:?} failed, error occurred \827+ during conversion to absolute path: {}",828+ original_path,829+ err,830+ );831+ return None;832+ }833+ };834+ // We convert the path to a string for easier manipulation. If it835+ // wasn't valid UTF-16 (and thus could not be non-lossily transcoded836+ // to UTF-8), then we just give up. It's not clear we could make837+ // a meaningful hyperlink from it anyway. And this should be an838+ // exceptionally rare case.839+ let mut string = match path.to_str() {840+ Some(string) => string,841+ None => {842+ log::debug!(843+ "hyperlink creation for {:?} failed, path is not \844+ valid UTF-8",845+ original_path,846+ );847+ return None;848+ }849+ };850+851+ // Strip verbatim path prefixes (see the comment above for details).852+ if string.starts_with(WIN32_NAMESPACE_PREFIX) {853+ string = &string[WIN32_NAMESPACE_PREFIX.len()..];854+855+ // Drop the UNC prefix if there is one, but keep the leading slash.856+ if string.starts_with(UNC_PREFIX) {857+ string = &string[(UNC_PREFIX.len() - 1)..];858+ }859+ } else if string.starts_with(r"\\") || string.starts_with(r"//") {860+ // Drop one of the two leading slashes of network paths, it will be added back.861+ string = &string[1..];862+ }863+864+ // Finally, add a leading slash. In the local file case, this turns865+ // C:\foo\bar into /C:\foo\bar (and then percent encoding turns it into866+ // /C:/foo/bar). In the network share case, this turns \share\foo\bar867+ // into /\share/foo/bar (and then percent encoding turns it into868+ // //share/foo/bar).869+ let with_slash = format!("/{string}");870+ Some(HyperlinkPath::encode(with_slash.as_bytes()))871+ }872+873+ /// For other platforms (not windows, not unix), return None and log a debug message.874+ #[cfg(not(any(windows, unix)))]875+ pub(crate) fn from_path(original_path: &Path) -> Option<HyperlinkPath> {876+ log::debug!("hyperlinks are not supported on this platform");877+ None878+ }879+880+ /// Percent-encodes a path.881+ ///882+ /// The alphanumeric ASCII characters and "-", ".", "_", "~" are unreserved883+ /// as per section 2.3 of RFC 3986 (Uniform Resource Identifier (URI):884+ /// Generic Syntax), and are not encoded. The other ASCII characters except885+ /// "/" and ":" are percent-encoded, and "\" is replaced by "/" on Windows.886+ ///887+ /// Section 4 of RFC 8089 (The "file" URI Scheme) does not mandate precise888+ /// encoding requirements for non-ASCII characters, and this implementation889+ /// leaves them unencoded. On Windows, the UrlCreateFromPathW function does890+ /// not encode non-ASCII characters. Doing so with UTF-8 encoded paths891+ /// creates invalid file:// URLs on that platform.892+ fn encode(input: &[u8]) -> HyperlinkPath {893+ let mut result = Vec::with_capacity(input.len());894+ for &byte in input.iter() {895+ match byte {896+ b'0'..=b'9'897+ | b'A'..=b'Z'898+ | b'a'..=b'z'899+ | b'/'900+ | b':'901+ | b'-'902+ | b'.'903+ | b'_'904+ | b'~'905+ | 128.. => {906+ result.push(byte);907+ }908+ #[cfg(windows)]909+ b'\\' => {910+ result.push(b'/');911+ }912+ _ => {913+ const HEX: &[u8] = b"0123456789ABCDEF";914+ result.push(b'%');915+ result.push(HEX[(byte >> 4) as usize]);916+ result.push(HEX[(byte & 0xF) as usize]);917+ }918+ }919+ }920+ HyperlinkPath(result)921+ }922+}923+924+/// Returns the set of hyperlink aliases supported by this crate.925+///926+/// Aliases are supported by the `FromStr` trait implementation of a927+/// [`HyperlinkFormat`]. That is, if an alias is seen, then it is automatically928+/// replaced with the corresponding format. For example, the `vscode` alias929+/// maps to `vscode://file{path}:{line}:{column}`.930+///931+/// This is exposed to allow callers to include hyperlink aliases in932+/// documentation in a way that is guaranteed to match what is actually933+/// supported.934+///935+/// The list returned is guaranteed to be sorted lexicographically936+/// by the alias name. Callers may want to re-sort the list using937+/// [`HyperlinkAlias::display_priority`] via a stable sort when showing the938+/// list to users. This will cause special aliases like `none` and `default` to939+/// appear first.940+pub fn hyperlink_aliases() -> Vec<HyperlinkAlias> {941+ HYPERLINK_PATTERN_ALIASES.iter().cloned().collect()942+}943+944+#[cfg(test)]945+mod tests {946+ use std::str::FromStr;947+948+ use super::*;949+950+ #[test]951+ fn build_format() {952+ let format = FormatBuilder::new()953+ .append_slice(b"foo://")954+ .append_slice(b"bar-")955+ .append_slice(b"baz")956+ .append_var("path")957+ .unwrap()958+ .build()959+ .unwrap();960+961+ assert_eq!(format.to_string(), "foo://bar-baz{path}");962+ assert_eq!(format.parts[0], Part::Text(b"foo://bar-baz".to_vec()));963+ assert!(!format.is_empty());964+ }965+966+ #[test]967+ fn build_empty_format() {968+ let format = FormatBuilder::new().build().unwrap();969+970+ assert!(format.is_empty());971+ assert_eq!(format, HyperlinkFormat::empty());972+ assert_eq!(format, HyperlinkFormat::default());973+ }974+975+ #[test]976+ fn handle_alias() {977+ assert!(HyperlinkFormat::from_str("file").is_ok());978+ assert!(HyperlinkFormat::from_str("none").is_ok());979+ assert!(HyperlinkFormat::from_str("none").unwrap().is_empty());980+ }981+982+ #[test]983+ fn parse_format() {984+ let format = HyperlinkFormat::from_str(985+ "foo://{host}/bar/{path}:{line}:{column}",986+ )987+ .unwrap();988+989+ assert_eq!(990+ format.to_string(),991+ "foo://{host}/bar/{path}:{line}:{column}"992+ );993+ assert_eq!(format.parts.len(), 8);994+ assert!(format.parts.contains(&Part::Path));995+ assert!(format.parts.contains(&Part::Line));996+ assert!(format.parts.contains(&Part::Column));997+ }998+999+ #[test]1000+ fn parse_valid() {1001+ assert!(HyperlinkFormat::from_str("").unwrap().is_empty());1002+ assert_eq!(1003+ HyperlinkFormat::from_str("foo://{path}").unwrap().to_string(),1004+ "foo://{path}"1005+ );1006+ assert_eq!(1007+ HyperlinkFormat::from_str("foo://{path}/bar").unwrap().to_string(),1008+ "foo://{path}/bar"1009+ );1010+1011+ HyperlinkFormat::from_str("f://{path}").unwrap();1012+ HyperlinkFormat::from_str("f:{path}").unwrap();1013+ HyperlinkFormat::from_str("f-+.:{path}").unwrap();1014+ HyperlinkFormat::from_str("f42:{path}").unwrap();1015+ HyperlinkFormat::from_str("42:{path}").unwrap();1016+ HyperlinkFormat::from_str("+:{path}").unwrap();1017+ HyperlinkFormat::from_str("F42:{path}").unwrap();1018+ HyperlinkFormat::from_str("F42://foo{{bar}}{path}").unwrap();1019+ }1020+1021+ #[test]1022+ fn parse_invalid() {1023+ use super::HyperlinkFormatErrorKind::*;1024+1025+ let err = |kind| HyperlinkFormatError { kind };1026+ assert_eq!(1027+ HyperlinkFormat::from_str("foo://bar").unwrap_err(),1028+ err(NoVariables),1029+ );1030+ assert_eq!(1031+ HyperlinkFormat::from_str("foo://{line}").unwrap_err(),1032+ err(NoPathVariable),1033+ );1034+ assert_eq!(1035+ HyperlinkFormat::from_str("foo://{path").unwrap_err(),1036+ err(UnclosedVariable),1037+ );1038+ assert_eq!(1039+ HyperlinkFormat::from_str("foo://{path}:{column}").unwrap_err(),1040+ err(NoLineVariable),1041+ );1042+ assert_eq!(1043+ HyperlinkFormat::from_str("{path}").unwrap_err(),1044+ err(InvalidScheme),1045+ );1046+ assert_eq!(1047+ HyperlinkFormat::from_str(":{path}").unwrap_err(),1048+ err(InvalidScheme),1049+ );1050+ assert_eq!(1051+ HyperlinkFormat::from_str("f*:{path}").unwrap_err(),1052+ err(InvalidScheme),1053+ );1054+1055+ assert_eq!(1056+ HyperlinkFormat::from_str("foo://{bar}").unwrap_err(),1057+ err(InvalidVariable("bar".to_string())),1058+ );1059+ assert_eq!(1060+ HyperlinkFormat::from_str("foo://{}}bar}").unwrap_err(),1061+ err(InvalidVariable("".to_string())),1062+ );1063+ assert_eq!(1064+ HyperlinkFormat::from_str("foo://{b}}ar}").unwrap_err(),1065+ err(InvalidVariable("b".to_string())),1066+ );1067+ assert_eq!(1068+ HyperlinkFormat::from_str("foo://{bar}}}").unwrap_err(),1069+ err(InvalidVariable("bar".to_string())),1070+ );1071+ assert_eq!(1072+ HyperlinkFormat::from_str("foo://{{bar}").unwrap_err(),1073+ err(InvalidCloseVariable),1074+ );1075+ assert_eq!(1076+ HyperlinkFormat::from_str("foo://{{{bar}").unwrap_err(),1077+ err(InvalidVariable("bar".to_string())),1078+ );1079+ assert_eq!(1080+ HyperlinkFormat::from_str("foo://{b{{ar}").unwrap_err(),1081+ err(InvalidVariable("b{{ar".to_string())),1082+ );1083+ assert_eq!(1084+ HyperlinkFormat::from_str("foo://{bar{{}").unwrap_err(),1085+ err(InvalidVariable("bar{{".to_string())),1086+ );1087+ }1088+1089+ #[test]1090+ #[cfg(windows)]1091+ fn convert_to_hyperlink_path() {1092+ let convert = |path| {1093+ String::from_utf8(1094+ HyperlinkPath::from_path(Path::new(path)).unwrap().0,1095+ )1096+ .unwrap()1097+ };1098+1099+ assert_eq!(convert(r"C:\dir\file.txt"), "/C:/dir/file.txt");1100+ assert_eq!(1101+ convert(r"C:\foo\bar\..\other\baz.txt"),1102+ "/C:/foo/other/baz.txt"1103+ );1104+1105+ assert_eq!(convert(r"\\server\dir\file.txt"), "//server/dir/file.txt");1106+ assert_eq!(1107+ convert(r"\\server\dir\foo\..\other\file.txt"),1108+ "//server/dir/other/file.txt"1109+ );1110+1111+ assert_eq!(convert(r"\\?\C:\dir\file.txt"), "/C:/dir/file.txt");1112+ assert_eq!(1113+ convert(r"\\?\UNC\server\dir\file.txt"),1114+ "//server/dir/file.txt"1115+ );1116+ }1117+1118+ #[test]1119+ fn aliases_are_sorted() {1120+ let aliases = hyperlink_aliases();1121+ let mut prev =1122+ aliases.first().expect("aliases should be non-empty").name();1123+ for alias in aliases.iter().skip(1) {1124+ let name = alias.name();1125+ assert!(1126+ name > prev,1127+ "'{prev}' should come before '{name}' in \1128+ HYPERLINK_PATTERN_ALIASES",1129+ );1130+ prev = name;1131+ }1132+ }1133+1134+ #[test]1135+ fn alias_names_are_reasonable() {1136+ for alias in hyperlink_aliases() {1137+ // There's no hard rule here, but if we want to define an alias1138+ // with a name that doesn't pass this assert, then we should1139+ // probably flag it as worthy of consideration. For example, we1140+ // really do not want to define an alias that contains `{` or `}`,1141+ // which might confuse it for a variable.1142+ assert!(alias.name().chars().all(|c| c.is_alphanumeric()1143+ || c == '+'1144+ || c == '-'1145+ || c == '.'));1146+ }1147+ }1148+1149+ #[test]1150+ fn aliases_are_valid_formats() {1151+ for alias in hyperlink_aliases() {1152+ let (name, format) = (alias.name(), alias.format());1153+ assert!(1154+ format.parse::<HyperlinkFormat>().is_ok(),1155+ "invalid hyperlink alias '{name}': {format}",1156+ );1157+ }1158+ }1159+}deleted:crates/printer/src/hyperlink_aliases.rs-85 removed
1-/// Aliases to well-known hyperlink schemes.2-///3-/// These need to be sorted by name.4-const HYPERLINK_PATTERN_ALIASES: &[(&str, &str)] = &[5- #[cfg(not(windows))]6- ("default", "file://{host}{path}"),7- #[cfg(windows)]8- ("default", "file://{path}"),9- ("file", "file://{host}{path}"),10- // https://github.com/misaki-web/grepp11- ("grep+", "grep+://{path}:{line}"),12- ("kitty", "file://{host}{path}#{line}"),13- // https://macvim.org/docs/gui_mac.txt.html#mvim%3A%2F%2F14- ("macvim", "mvim://open?url=file://{path}&line={line}&column={column}"),15- ("none", ""),16- // https://macromates.com/blog/2007/the-textmate-url-scheme/17- ("textmate", "txmt://open?url=file://{path}&line={line}&column={column}"),18- // https://code.visualstudio.com/docs/editor/command-line#_opening-vs-code-with-urls19- ("vscode", "vscode://file{path}:{line}:{column}"),20- ("vscode-insiders", "vscode-insiders://file{path}:{line}:{column}"),21- ("vscodium", "vscodium://file{path}:{line}:{column}"),22-];23-24-/// Look for the hyperlink format defined by the given alias name.25-///26-/// If one does not exist, `None` is returned.27-pub(crate) fn find(name: &str) -> Option<&str> {28- HYPERLINK_PATTERN_ALIASES29- .binary_search_by_key(&name, |&(name, _)| name)30- .map(|i| HYPERLINK_PATTERN_ALIASES[i].1)31- .ok()32-}33-34-/// Return an iterator over all available alias names and their definitions.35-pub(crate) fn iter() -> impl Iterator<Item = (&'static str, &'static str)> {36- HYPERLINK_PATTERN_ALIASES.iter().copied()37-}38-39-#[cfg(test)]40-mod tests {41- use crate::HyperlinkFormat;42-43- use super::*;44-45- #[test]46- fn is_sorted() {47- let mut prev = HYPERLINK_PATTERN_ALIASES48- .get(0)49- .expect("aliases should be non-empty")50- .0;51- for &(name, _) in HYPERLINK_PATTERN_ALIASES.iter().skip(1) {52- assert!(53- name > prev,54- "'{prev}' should come before '{name}' in \55- HYPERLINK_PATTERN_ALIASES",56- );57- prev = name;58- }59- }60-61- #[test]62- fn alias_names_are_reasonable() {63- for &(name, _) in HYPERLINK_PATTERN_ALIASES.iter() {64- // There's no hard rule here, but if we want to define an alias65- // with a name that doesn't pass this assert, then we should66- // probably flag it as worthy of consideration. For example, we67- // really do not want to define an alias that contains `{` or `}`,68- // which might confuse it for a variable.69- assert!(name.chars().all(|c| c.is_alphanumeric()70- || c == '+'71- || c == '-'72- || c == '.'));73- }74- }75-76- #[test]77- fn aliases_are_valid_formats() {78- for (name, definition) in HYPERLINK_PATTERN_ALIASES {79- assert!(80- definition.parse::<HyperlinkFormat>().is_ok(),81- "invalid hyperlink alias '{name}': {definition}",82- );83- }84- }85-}deleted:crates/printer/src/hyperlink.rs-1039 removed
1-use std::{cell::RefCell, io, path::Path, sync::Arc};2-3-use {4- bstr::ByteSlice,5- termcolor::{HyperlinkSpec, WriteColor},6-};7-8-use crate::{hyperlink_aliases, util::DecimalFormatter};9-10-/// Hyperlink configuration.11-///12-/// This configuration specifies both the [hyperlink format](HyperlinkFormat)13-/// and an [environment](HyperlinkConfig) for interpolating a subset of14-/// variables. The specific subset includes variables that are intended to15-/// be invariant throughout the lifetime of a process, such as a machine's16-/// hostname.17-///18-/// A hyperlink configuration can be provided to printer builders such as19-/// [`StandardBuilder::hyperlink`](crate::StandardBuilder::hyperlink).20-#[derive(Clone, Debug, Default, Eq, PartialEq)]21-pub struct HyperlinkConfig(Arc<HyperlinkConfigInner>);22-23-#[derive(Clone, Debug, Default, Eq, PartialEq)]24-struct HyperlinkConfigInner {25- env: HyperlinkEnvironment,26- format: HyperlinkFormat,27-}28-29-impl HyperlinkConfig {30- /// Create a new configuration from an environment and a format.31- pub fn new(32- env: HyperlinkEnvironment,33- format: HyperlinkFormat,34- ) -> HyperlinkConfig {35- HyperlinkConfig(Arc::new(HyperlinkConfigInner { env, format }))36- }37-38- /// Returns the hyperlink environment in this configuration.39- pub(crate) fn environment(&self) -> &HyperlinkEnvironment {40- &self.0.env41- }42-43- /// Returns the hyperlink format in this configuration.44- pub(crate) fn format(&self) -> &HyperlinkFormat {45- &self.0.format46- }47-}48-49-/// A hyperlink format with variables.50-///51-/// This can be created by parsing a string using `HyperlinkFormat::from_str`.52-///53-/// The default format is empty. An empty format is valid and effectively54-/// disables hyperlinks.55-///56-/// # Example57-///58-/// ```59-/// use grep_printer::HyperlinkFormat;60-///61-/// let fmt = "vscode".parse::<HyperlinkFormat>()?;62-/// assert_eq!(fmt.to_string(), "vscode://file{path}:{line}:{column}");63-///64-/// # Ok::<(), Box<dyn std::error::Error>>(())65-/// ```66-#[derive(Clone, Debug, Default, Eq, PartialEq)]67-pub struct HyperlinkFormat {68- parts: Vec<Part>,69- is_line_dependent: bool,70-}71-72-impl HyperlinkFormat {73- /// Creates an empty hyperlink format.74- pub fn empty() -> HyperlinkFormat {75- HyperlinkFormat::default()76- }77-78- /// Returns true if this format is empty.79- pub fn is_empty(&self) -> bool {80- self.parts.is_empty()81- }82-83- /// Creates a [`HyperlinkConfig`] from this format and the environment84- /// given.85- pub fn into_config(self, env: HyperlinkEnvironment) -> HyperlinkConfig {86- HyperlinkConfig::new(env, self)87- }88-89- /// Returns true if the format can produce line-dependent hyperlinks.90- pub(crate) fn is_line_dependent(&self) -> bool {91- self.is_line_dependent92- }93-}94-95-impl std::str::FromStr for HyperlinkFormat {96- type Err = HyperlinkFormatError;97-98- fn from_str(s: &str) -> Result<HyperlinkFormat, HyperlinkFormatError> {99- use self::HyperlinkFormatErrorKind::*;100-101- #[derive(Debug)]102- enum State {103- Verbatim,104- VerbatimCloseVariable,105- OpenVariable,106- InVariable,107- }108-109- let mut builder = FormatBuilder::new();110- let input = match hyperlink_aliases::find(s) {111- Some(format) => format,112- None => s,113- };114- let mut name = String::new();115- let mut state = State::Verbatim;116- let err = |kind| HyperlinkFormatError { kind };117- for ch in input.chars() {118- state = match state {119- State::Verbatim => {120- if ch == '{' {121- State::OpenVariable122- } else if ch == '}' {123- State::VerbatimCloseVariable124- } else {125- builder.append_char(ch);126- State::Verbatim127- }128- }129- State::VerbatimCloseVariable => {130- if ch == '}' {131- builder.append_char('}');132- State::Verbatim133- } else {134- return Err(err(InvalidCloseVariable));135- }136- }137- State::OpenVariable => {138- if ch == '{' {139- builder.append_char('{');140- State::Verbatim141- } else {142- name.clear();143- if ch == '}' {144- builder.append_var(&name)?;145- State::Verbatim146- } else {147- name.push(ch);148- State::InVariable149- }150- }151- }152- State::InVariable => {153- if ch == '}' {154- builder.append_var(&name)?;155- State::Verbatim156- } else {157- name.push(ch);158- State::InVariable159- }160- }161- };162- }163- match state {164- State::Verbatim => builder.build(),165- State::VerbatimCloseVariable => Err(err(InvalidCloseVariable)),166- State::OpenVariable | State::InVariable => {167- Err(err(UnclosedVariable))168- }169- }170- }171-}172-173-impl std::fmt::Display for HyperlinkFormat {174- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {175- for part in self.parts.iter() {176- part.fmt(f)?;177- }178- Ok(())179- }180-}181-182-/// A static environment for hyperlink interpolation.183-///184-/// This environment permits setting the values of variables used in hyperlink185-/// interpolation that are not expected to change for the lifetime of a program.186-/// That is, these values are invariant.187-///188-/// Currently, this includes the hostname and a WSL distro prefix.189-#[derive(Clone, Debug, Default, Eq, PartialEq)]190-pub struct HyperlinkEnvironment {191- host: Option<String>,192- wsl_prefix: Option<String>,193-}194-195-impl HyperlinkEnvironment {196- /// Create a new empty hyperlink environment.197- pub fn new() -> HyperlinkEnvironment {198- HyperlinkEnvironment::default()199- }200-201- /// Set the `{host}` variable, which fills in any hostname components of202- /// a hyperlink.203- ///204- /// One can get the hostname in the current environment via the `hostname`205- /// function in the `grep-cli` crate.206- pub fn host(&mut self, host: Option<String>) -> &mut HyperlinkEnvironment {207- self.host = host;208- self209- }210-211- /// Set the `{wslprefix}` variable, which contains the WSL distro prefix.212- /// An example value is `wsl$/Ubuntu`. The distro name can typically be213- /// discovered from the `WSL_DISTRO_NAME` environment variable.214- pub fn wsl_prefix(215- &mut self,216- wsl_prefix: Option<String>,217- ) -> &mut HyperlinkEnvironment {218- self.wsl_prefix = wsl_prefix;219- self220- }221-}222-223-/// An error that can occur when parsing a hyperlink format.224-#[derive(Clone, Debug, Eq, PartialEq)]225-pub struct HyperlinkFormatError {226- kind: HyperlinkFormatErrorKind,227-}228-229-#[derive(Clone, Debug, Eq, PartialEq)]230-enum HyperlinkFormatErrorKind {231- /// This occurs when there are zero variables in the format.232- NoVariables,233- /// This occurs when the {path} variable is missing.234- NoPathVariable,235- /// This occurs when the {line} variable is missing, while the {column}236- /// variable is present.237- NoLineVariable,238- /// This occurs when an unknown variable is used.239- InvalidVariable(String),240- /// The format doesn't start with a valid scheme.241- InvalidScheme,242- /// This occurs when an unescaped `}` is found without a corresponding243- /// `{` preceding it.244- InvalidCloseVariable,245- /// This occurs when a `{` is found without a corresponding `}` following246- /// it.247- UnclosedVariable,248-}249-250-impl std::error::Error for HyperlinkFormatError {}251-252-impl std::fmt::Display for HyperlinkFormatError {253- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {254- use self::HyperlinkFormatErrorKind::*;255-256- match self.kind {257- NoVariables => {258- let aliases = hyperlink_aliases::iter()259- .map(|(name, _)| name)260- .collect::<Vec<&str>>()261- .join(", ");262- write!(263- f,264- "at least a {{path}} variable is required in a \265- hyperlink format, or otherwise use a valid alias: {}",266- aliases,267- )268- }269- NoPathVariable => {270- write!(271- f,272- "the {{path}} variable is required in a hyperlink format",273- )274- }275- NoLineVariable => {276- write!(277- f,278- "the hyperlink format contains a {{column}} variable, \279- but no {{line}} variable is present",280- )281- }282- InvalidVariable(ref name) => {283- write!(284- f,285- "invalid hyperlink format variable: '{name}', choose \286- from: path, line, column, host, wslprefix",287- )288- }289- InvalidScheme => {290- write!(291- f,292- "the hyperlink format must start with a valid URL scheme, \293- i.e., [0-9A-Za-z+-.]+:",294- )295- }296- InvalidCloseVariable => {297- write!(298- f,299- "unopened variable: found '}}' without a \300- corresponding '{{' preceding it",301- )302- }303- UnclosedVariable => {304- write!(305- f,306- "unclosed variable: found '{{' without a \307- corresponding '}}' following it",308- )309- }310- }311- }312-}313-314-/// A builder for `HyperlinkFormat`.315-///316-/// Once a `HyperlinkFormat` is built, it is immutable.317-#[derive(Debug)]318-struct FormatBuilder {319- parts: Vec<Part>,320-}321-322-impl FormatBuilder {323- /// Creates a new hyperlink format builder.324- fn new() -> FormatBuilder {325- FormatBuilder { parts: vec![] }326- }327-328- /// Appends static text.329- fn append_slice(&mut self, text: &[u8]) -> &mut FormatBuilder {330- if let Some(Part::Text(contents)) = self.parts.last_mut() {331- contents.extend_from_slice(text);332- } else if !text.is_empty() {333- self.parts.push(Part::Text(text.to_vec()));334- }335- self336- }337-338- /// Appends a single character.339- fn append_char(&mut self, ch: char) -> &mut FormatBuilder {340- self.append_slice(ch.encode_utf8(&mut [0; 4]).as_bytes())341- }342-343- /// Appends a variable with the given name. If the name isn't recognized,344- /// then this returns an error.345- fn append_var(346- &mut self,347- name: &str,348- ) -> Result<&mut FormatBuilder, HyperlinkFormatError> {349- let part = match name {350- "host" => Part::Host,351- "wslprefix" => Part::WSLPrefix,352- "path" => Part::Path,353- "line" => Part::Line,354- "column" => Part::Column,355- unknown => {356- let err = HyperlinkFormatError {357- kind: HyperlinkFormatErrorKind::InvalidVariable(358- unknown.to_string(),359- ),360- };361- return Err(err);362- }363- };364- self.parts.push(part);365- Ok(self)366- }367-368- /// Builds the format.369- fn build(&self) -> Result<HyperlinkFormat, HyperlinkFormatError> {370- self.validate()?;371- Ok(HyperlinkFormat {372- parts: self.parts.clone(),373- is_line_dependent: self.parts.contains(&Part::Line),374- })375- }376-377- /// Validate that the format is well-formed.378- fn validate(&self) -> Result<(), HyperlinkFormatError> {379- use self::HyperlinkFormatErrorKind::*;380-381- let err = |kind| HyperlinkFormatError { kind };382- // An empty format is fine. It just means hyperlink support is383- // disabled.384- if self.parts.is_empty() {385- return Ok(());386- }387- // If all parts are just text, then there are no variables. It's388- // likely a reference to an invalid alias.389- if self.parts.iter().all(|p| matches!(*p, Part::Text(_))) {390- return Err(err(NoVariables));391- }392- // Even if we have other variables, no path variable means the393- // hyperlink can't possibly work the way it is intended.394- if !self.parts.contains(&Part::Path) {395- return Err(err(NoPathVariable));396- }397- // If the {column} variable is used, then we also need a {line}398- // variable or else {column} can't possibly work.399- if self.parts.contains(&Part::Column)400- && !self.parts.contains(&Part::Line)401- {402- return Err(err(NoLineVariable));403- }404- self.validate_scheme()405- }406-407- /// Validate that the format starts with a valid scheme. Validation is done408- /// according to how a scheme is defined in RFC 1738 sections 2.1[1] and409- /// 5[2]. In short, a scheme is this:410- ///411- /// scheme = 1*[ lowalpha | digit | "+" | "-" | "." ]412- ///413- /// but is case insensitive.414- ///415- /// [1]: https://datatracker.ietf.org/doc/html/rfc1738#section-2.1416- /// [2]: https://datatracker.ietf.org/doc/html/rfc1738#section-5417- fn validate_scheme(&self) -> Result<(), HyperlinkFormatError> {418- let err_invalid_scheme = HyperlinkFormatError {419- kind: HyperlinkFormatErrorKind::InvalidScheme,420- };421- let Some(Part::Text(ref part)) = self.parts.first() else {422- return Err(err_invalid_scheme);423- };424- let Some(colon) = part.find_byte(b':') else {425- return Err(err_invalid_scheme);426- };427- let scheme = &part[..colon];428- if scheme.is_empty() {429- return Err(err_invalid_scheme);430- }431- let is_valid_scheme_char = |byte| match byte {432- b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b'+' | b'-' | b'.' => {433- true434- }435- _ => false,436- };437- if !scheme.iter().all(|&b| is_valid_scheme_char(b)) {438- return Err(err_invalid_scheme);439- }440- Ok(())441- }442-}443-444-/// A hyperlink format part.445-///446-/// A sequence of these corresponds to a complete format. (Not all sequences447-/// are valid.)448-#[derive(Clone, Debug, Eq, PartialEq)]449-enum Part {450- /// Static text.451- ///452- /// We use `Vec<u8>` here (and more generally treat a format string as a453- /// sequence of bytes) because file paths may be arbitrary bytes. A rare454- /// case, but one for which there is no good reason to choke on.455- Text(Vec<u8>),456- /// Variable for the hostname.457- Host,458- /// Variable for a WSL path prefix.459- WSLPrefix,460- /// Variable for the file path.461- Path,462- /// Variable for the line number.463- Line,464- /// Variable for the column number.465- Column,466-}467-468-impl Part {469- /// Interpolate this part using the given `env` and `values`, and write470- /// the result of interpolation to the buffer provided.471- fn interpolate_to(472- &self,473- env: &HyperlinkEnvironment,474- values: &Values,475- dest: &mut Vec<u8>,476- ) {477- match self {478- Part::Text(ref text) => dest.extend_from_slice(text),479- Part::Host => dest.extend_from_slice(480- env.host.as_ref().map(|s| s.as_bytes()).unwrap_or(b""),481- ),482- Part::WSLPrefix => dest.extend_from_slice(483- env.wsl_prefix.as_ref().map(|s| s.as_bytes()).unwrap_or(b""),484- ),485- Part::Path => dest.extend_from_slice(&values.path.0),486- Part::Line => {487- let line = DecimalFormatter::new(values.line.unwrap_or(1));488- dest.extend_from_slice(line.as_bytes());489- }490- Part::Column => {491- let column = DecimalFormatter::new(values.column.unwrap_or(1));492- dest.extend_from_slice(column.as_bytes());493- }494- }495- }496-}497-498-impl std::fmt::Display for Part {499- fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {500- match self {501- Part::Text(text) => write!(f, "{}", String::from_utf8_lossy(text)),502- Part::Host => write!(f, "{{host}}"),503- Part::WSLPrefix => write!(f, "{{wslprefix}}"),504- Part::Path => write!(f, "{{path}}"),505- Part::Line => write!(f, "{{line}}"),506- Part::Column => write!(f, "{{column}}"),507- }508- }509-}510-511-/// The values to replace the format variables with.512-///513-/// This only consists of values that depend on each path or match printed.514-/// Values that are invariant throughout the lifetime of the process are set515-/// via a [`HyperlinkEnvironment`].516-#[derive(Clone, Debug)]517-pub(crate) struct Values<'a> {518- path: &'a HyperlinkPath,519- line: Option<u64>,520- column: Option<u64>,521-}522-523-impl<'a> Values<'a> {524- /// Creates a new set of values, starting with the path given.525- ///526- /// Callers may also set the line and column number using the mutator527- /// methods.528- pub(crate) fn new(path: &'a HyperlinkPath) -> Values<'a> {529- Values { path, line: None, column: None }530- }531-532- /// Sets the line number for these values.533- ///534- /// If a line number is not set and a hyperlink format contains a `{line}`535- /// variable, then it is interpolated with the value of `1` automatically.536- pub(crate) fn line(mut self, line: Option<u64>) -> Values<'a> {537- self.line = line;538- self539- }540-541- /// Sets the column number for these values.542- ///543- /// If a column number is not set and a hyperlink format contains a544- /// `{column}` variable, then it is interpolated with the value of `1`545- /// automatically.546- pub(crate) fn column(mut self, column: Option<u64>) -> Values<'a> {547- self.column = column;548- self549- }550-}551-552-/// An abstraction for interpolating a hyperlink format with values for every553-/// variable.554-///555-/// Interpolation of variables occurs through two different sources. The556-/// first is via a `HyperlinkEnvironment` for values that are expected to557-/// be invariant. This comes from the `HyperlinkConfig` used to build this558-/// interpolator. The second source is via `Values`, which is provided to559-/// `Interpolator::begin`. The `Values` contains things like the file path,560-/// line number and column number.561-#[derive(Clone, Debug)]562-pub(crate) struct Interpolator {563- config: HyperlinkConfig,564- buf: RefCell<Vec<u8>>,565-}566-567-impl Interpolator {568- /// Create a new interpolator for the given hyperlink format configuration.569- pub(crate) fn new(config: &HyperlinkConfig) -> Interpolator {570- Interpolator { config: config.clone(), buf: RefCell::new(vec![]) }571- }572-573- /// Start interpolation with the given values by writing a hyperlink574- /// to `wtr`. Subsequent writes to `wtr`, until `Interpolator::end` is575- /// called, are the label for the hyperlink.576- ///577- /// This returns an interpolator status which indicates whether the578- /// hyperlink was written. It might not be written, for example, if the579- /// underlying writer doesn't support hyperlinks or if the hyperlink580- /// format is empty. The status should be provided to `Interpolator::end`581- /// as an instruction for whether to close the hyperlink or not.582- pub(crate) fn begin<W: WriteColor>(583- &self,584- values: &Values,585- mut wtr: W,586- ) -> io::Result<InterpolatorStatus> {587- if self.config.format().is_empty()588- || !wtr.supports_hyperlinks()589- || !wtr.supports_color()590- {591- return Ok(InterpolatorStatus::inactive());592- }593- let mut buf = self.buf.borrow_mut();594- buf.clear();595- for part in self.config.format().parts.iter() {596- part.interpolate_to(self.config.environment(), values, &mut buf);597- }598- let spec = HyperlinkSpec::open(&buf);599- wtr.set_hyperlink(&spec)?;600- Ok(InterpolatorStatus { active: true })601- }602-603- /// Writes the correct escape sequences to `wtr` to close any extant604- /// hyperlink, marking the end of a hyperlink's label.605- ///606- /// The status given should be returned from a corresponding607- /// `Interpolator::begin` call. Since `begin` may not write a hyperlink608- /// (e.g., if the underlying writer doesn't support hyperlinks), it follows609- /// that `finish` must not close a hyperlink that was never opened. The610- /// status indicates whether the hyperlink was opened or not.611- pub(crate) fn finish<W: WriteColor>(612- &self,613- status: InterpolatorStatus,614- mut wtr: W,615- ) -> io::Result<()> {616- if !status.active {617- return Ok(());618- }619- wtr.set_hyperlink(&HyperlinkSpec::close())620- }621-}622-623-/// A status indicating whether a hyperlink was written or not.624-///625-/// This is created by `Interpolator::begin` and used by `Interpolator::finish`626-/// to determine whether a hyperlink was actually opened or not. If it wasn't627-/// opened, then finishing interpolation is a no-op.628-#[derive(Debug)]629-pub(crate) struct InterpolatorStatus {630- active: bool,631-}632-633-impl InterpolatorStatus {634- /// Create an inactive interpolator status.635- #[inline]636- pub(crate) fn inactive() -> InterpolatorStatus {637- InterpolatorStatus { active: false }638- }639-}640-641-/// Represents the `{path}` part of a hyperlink.642-///643-/// This is the value to use as-is in the hyperlink, converted from an OS file644-/// path.645-#[derive(Clone, Debug)]646-pub(crate) struct HyperlinkPath(Vec<u8>);647-648-impl HyperlinkPath {649- /// Returns a hyperlink path from an OS path.650- #[cfg(unix)]651- pub(crate) fn from_path(original_path: &Path) -> Option<HyperlinkPath> {652- use std::os::unix::ffi::OsStrExt;653-654- // We canonicalize the path in order to get an absolute version of it655- // without any `.` or `..` or superfluous separators. Unfortunately,656- // this does also remove symlinks, and in theory, it would be nice to657- // retain them. Perhaps even simpler, we could just join the current658- // working directory with the path and be done with it. There was659- // some discussion about this on PR#2483, and there generally appears660- // to be some uncertainty about the extent to which hyperlinks with661- // things like `..` in them actually work. So for now, we do the safest662- // thing possible even though I think it can result in worse user663- // experience. (Because it means the path you click on and the actual664- // path that gets followed are different, even though they ostensibly665- // refer to the same file.)666- //667- // There's also the potential issue that path canonicalization is668- // expensive since it can touch the file system. That is probably669- // less of an issue since hyperlinks are only created when they're670- // supported, i.e., when writing to a tty.671- //672- // [1]: https://github.com/BurntSushi/ripgrep/pull/2483673- let path = match original_path.canonicalize() {674- Ok(path) => path,675- Err(err) => {676- log::debug!(677- "hyperlink creation for {:?} failed, error occurred \678- during path canonicalization: {}",679- original_path,680- err,681- );682- return None;683- }684- };685- let bytes = path.as_os_str().as_bytes();686- // This should not be possible since one imagines that canonicalization687- // should always return an absolute path. But it doesn't actually688- // appear guaranteed by POSIX, so we check whether it's true or not and689- // refuse to create a hyperlink from a relative path if it isn't.690- if !bytes.starts_with(b"/") {691- log::debug!(692- "hyperlink creation for {:?} failed, canonicalization \693- returned {:?}, which does not start with a slash",694- original_path,695- path,696- );697- return None;698- }699- Some(HyperlinkPath::encode(bytes))700- }701-702- /// Returns a hyperlink path from an OS path.703- #[cfg(windows)]704- pub(crate) fn from_path(original_path: &Path) -> Option<HyperlinkPath> {705- // On Windows, we use `std::path::absolute` instead of `Path::canonicalize`706- // as it can be much faster since it does not touch the file system.707- // It wraps the [`GetFullPathNameW`][1] API, except for verbatim paths708- // (those which start with `\\?\`, see [the documentation][2] for details).709- //710- // Here, we strip any verbatim path prefixes since we cannot use them711- // in hyperlinks anyway. This can only happen if the user explicitly712- // supplies a verbatim path as input, which already needs to be absolute:713- //714- // \\?\C:\dir\file.txt (local path)715- // \\?\UNC\server\dir\file.txt (network share)716- //717- // The `\\?\` prefix is constant for verbatim paths, and can be followed718- // by `UNC\` (universal naming convention), which denotes a network share.719- //720- // Given that the default URL format on Windows is file://{path}721- // we need to return the following from this function:722- //723- // /C:/dir/file.txt (local path)724- // //server/dir/file.txt (network share)725- //726- // Which produces the following links:727- //728- // file:///C:/dir/file.txt (local path)729- // file:////server/dir/file.txt (network share)730- //731- // This substitutes the {path} variable with the expected value for732- // the most common DOS paths, but on the other hand, network paths733- // start with a single slash, which may be unexpected. It seems to work734- // though?735- //736- // Note that the following URL syntax also seems to be valid?737- //738- // file://server/dir/file.txt739- //740- // But the initial implementation of this routine went for the format741- // above.742- //743- // Also note that the file://C:/dir/file.txt syntax is not correct,744- // even though it often works in practice.745- //746- // In the end, this choice was confirmed by VSCode, whose format is747- //748- // vscode://file{path}:{line}:{column}749- //750- // and which correctly understands the following URL format for network751- // drives:752- //753- // vscode://file//server/dir/file.txt:1:1754- //755- // It doesn't parse any other number of slashes in "file//server" as a756- // network path.757- //758- // [1]: https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew759- // [2]: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file760-761- const WIN32_NAMESPACE_PREFIX: &str = r"\\?\";762- const UNC_PREFIX: &str = r"UNC\";763-764- let path = match std::path::absolute(original_path) {765- Ok(path) => path,766- Err(err) => {767- log::debug!(768- "hyperlink creation for {:?} failed, error occurred \769- during conversion to absolute path: {}",770- original_path,771- err,772- );773- return None;774- }775- };776- // We convert the path to a string for easier manipulation. If it777- // wasn't valid UTF-16 (and thus could not be non-lossily transcoded778- // to UTF-8), then we just give up. It's not clear we could make779- // a meaningful hyperlink from it anyway. And this should be an780- // exceptionally rare case.781- let mut string = match path.to_str() {782- Some(string) => string,783- None => {784- log::debug!(785- "hyperlink creation for {:?} failed, path is not \786- valid UTF-8",787- original_path,788- );789- return None;790- }791- };792-793- // Strip verbatim path prefixes (see the comment above for details).794- if string.starts_with(WIN32_NAMESPACE_PREFIX) {795- string = &string[WIN32_NAMESPACE_PREFIX.len()..];796-797- // Drop the UNC prefix if there is one, but keep the leading slash.798- if string.starts_with(UNC_PREFIX) {799- string = &string[(UNC_PREFIX.len() - 1)..];800- }801- } else if string.starts_with(r"\\") || string.starts_with(r"//") {802- // Drop one of the two leading slashes of network paths, it will be added back.803- string = &string[1..];804- }805-806- // Finally, add a leading slash. In the local file case, this turns807- // C:\foo\bar into /C:\foo\bar (and then percent encoding turns it into808- // /C:/foo/bar). In the network share case, this turns \share\foo\bar809- // into /\share/foo/bar (and then percent encoding turns it into810- // //share/foo/bar).811- let with_slash = format!("/{string}");812- Some(HyperlinkPath::encode(with_slash.as_bytes()))813- }814-815- /// For other platforms (not windows, not unix), return None and log a debug message.816- #[cfg(not(any(windows, unix)))]817- pub(crate) fn from_path(original_path: &Path) -> Option<HyperlinkPath> {818- log::debug!("hyperlinks are not supported on this platform");819- None820- }821-822- /// Percent-encodes a path.823- ///824- /// The alphanumeric ASCII characters and "-", ".", "_", "~" are unreserved825- /// as per section 2.3 of RFC 3986 (Uniform Resource Identifier (URI):826- /// Generic Syntax), and are not encoded. The other ASCII characters except827- /// "/" and ":" are percent-encoded, and "\" is replaced by "/" on Windows.828- ///829- /// Section 4 of RFC 8089 (The "file" URI Scheme) does not mandate precise830- /// encoding requirements for non-ASCII characters, and this implementation831- /// leaves them unencoded. On Windows, the UrlCreateFromPathW function does832- /// not encode non-ASCII characters. Doing so with UTF-8 encoded paths833- /// creates invalid file:// URLs on that platform.834- fn encode(input: &[u8]) -> HyperlinkPath {835- let mut result = Vec::with_capacity(input.len());836- for &byte in input.iter() {837- match byte {838- b'0'..=b'9'839- | b'A'..=b'Z'840- | b'a'..=b'z'841- | b'/'842- | b':'843- | b'-'844- | b'.'845- | b'_'846- | b'~'847- | 128.. => {848- result.push(byte);849- }850- #[cfg(windows)]851- b'\\' => {852- result.push(b'/');853- }854- _ => {855- const HEX: &[u8] = b"0123456789ABCDEF";856- result.push(b'%');857- result.push(HEX[(byte >> 4) as usize]);858- result.push(HEX[(byte & 0xF) as usize]);859- }860- }861- }862- HyperlinkPath(result)863- }864-}865-866-#[cfg(test)]867-mod tests {868- use std::str::FromStr;869-870- use super::*;871-872- #[test]873- fn build_format() {874- let format = FormatBuilder::new()875- .append_slice(b"foo://")876- .append_slice(b"bar-")877- .append_slice(b"baz")878- .append_var("path")879- .unwrap()880- .build()881- .unwrap();882-883- assert_eq!(format.to_string(), "foo://bar-baz{path}");884- assert_eq!(format.parts[0], Part::Text(b"foo://bar-baz".to_vec()));885- assert!(!format.is_empty());886- }887-888- #[test]889- fn build_empty_format() {890- let format = FormatBuilder::new().build().unwrap();891-892- assert!(format.is_empty());893- assert_eq!(format, HyperlinkFormat::empty());894- assert_eq!(format, HyperlinkFormat::default());895- }896-897- #[test]898- fn handle_alias() {899- assert!(HyperlinkFormat::from_str("file").is_ok());900- assert!(HyperlinkFormat::from_str("none").is_ok());901- assert!(HyperlinkFormat::from_str("none").unwrap().is_empty());902- }903-904- #[test]905- fn parse_format() {906- let format = HyperlinkFormat::from_str(907- "foo://{host}/bar/{path}:{line}:{column}",908- )909- .unwrap();910-911- assert_eq!(912- format.to_string(),913- "foo://{host}/bar/{path}:{line}:{column}"914- );915- assert_eq!(format.parts.len(), 8);916- assert!(format.parts.contains(&Part::Path));917- assert!(format.parts.contains(&Part::Line));918- assert!(format.parts.contains(&Part::Column));919- }920-921- #[test]922- fn parse_valid() {923- assert!(HyperlinkFormat::from_str("").unwrap().is_empty());924- assert_eq!(925- HyperlinkFormat::from_str("foo://{path}").unwrap().to_string(),926- "foo://{path}"927- );928- assert_eq!(929- HyperlinkFormat::from_str("foo://{path}/bar").unwrap().to_string(),930- "foo://{path}/bar"931- );932-933- HyperlinkFormat::from_str("f://{path}").unwrap();934- HyperlinkFormat::from_str("f:{path}").unwrap();935- HyperlinkFormat::from_str("f-+.:{path}").unwrap();936- HyperlinkFormat::from_str("f42:{path}").unwrap();937- HyperlinkFormat::from_str("42:{path}").unwrap();938- HyperlinkFormat::from_str("+:{path}").unwrap();939- HyperlinkFormat::from_str("F42:{path}").unwrap();940- HyperlinkFormat::from_str("F42://foo{{bar}}{path}").unwrap();941- }942-943- #[test]944- fn parse_invalid() {945- use super::HyperlinkFormatErrorKind::*;946-947- let err = |kind| HyperlinkFormatError { kind };948- assert_eq!(949- HyperlinkFormat::from_str("foo://bar").unwrap_err(),950- err(NoVariables),951- );952- assert_eq!(953- HyperlinkFormat::from_str("foo://{line}").unwrap_err(),954- err(NoPathVariable),955- );956- assert_eq!(957- HyperlinkFormat::from_str("foo://{path").unwrap_err(),958- err(UnclosedVariable),959- );960- assert_eq!(961- HyperlinkFormat::from_str("foo://{path}:{column}").unwrap_err(),962- err(NoLineVariable),963- );964- assert_eq!(965- HyperlinkFormat::from_str("{path}").unwrap_err(),966- err(InvalidScheme),967- );968- assert_eq!(969- HyperlinkFormat::from_str(":{path}").unwrap_err(),970- err(InvalidScheme),971- );972- assert_eq!(973- HyperlinkFormat::from_str("f*:{path}").unwrap_err(),974- err(InvalidScheme),975- );976-977- assert_eq!(978- HyperlinkFormat::from_str("foo://{bar}").unwrap_err(),979- err(InvalidVariable("bar".to_string())),980- );981- assert_eq!(982- HyperlinkFormat::from_str("foo://{}}bar}").unwrap_err(),983- err(InvalidVariable("".to_string())),984- );985- assert_eq!(986- HyperlinkFormat::from_str("foo://{b}}ar}").unwrap_err(),987- err(InvalidVariable("b".to_string())),988- );989- assert_eq!(990- HyperlinkFormat::from_str("foo://{bar}}}").unwrap_err(),991- err(InvalidVariable("bar".to_string())),992- );993- assert_eq!(994- HyperlinkFormat::from_str("foo://{{bar}").unwrap_err(),995- err(InvalidCloseVariable),996- );997- assert_eq!(998- HyperlinkFormat::from_str("foo://{{{bar}").unwrap_err(),999- err(InvalidVariable("bar".to_string())),1000- );1001- assert_eq!(1002- HyperlinkFormat::from_str("foo://{b{{ar}").unwrap_err(),1003- err(InvalidVariable("b{{ar".to_string())),1004- );1005- assert_eq!(1006- HyperlinkFormat::from_str("foo://{bar{{}").unwrap_err(),1007- err(InvalidVariable("bar{{".to_string())),1008- );1009- }1010-1011- #[test]1012- #[cfg(windows)]1013- fn convert_to_hyperlink_path() {1014- let convert = |path| {1015- String::from_utf8(1016- HyperlinkPath::from_path(Path::new(path)).unwrap().0,1017- )1018- .unwrap()1019- };1020-1021- assert_eq!(convert(r"C:\dir\file.txt"), "/C:/dir/file.txt");1022- assert_eq!(1023- convert(r"C:\foo\bar\..\other\baz.txt"),1024- "/C:/foo/other/baz.txt"1025- );1026-1027- assert_eq!(convert(r"\\server\dir\file.txt"), "//server/dir/file.txt");1028- assert_eq!(1029- convert(r"\\server\dir\foo\..\other\file.txt"),1030- "//server/dir/other/file.txt"1031- );1032-1033- assert_eq!(convert(r"\\?\C:\dir\file.txt"), "/C:/dir/file.txt");1034- assert_eq!(1035- convert(r"\\?\UNC\server\dir\file.txt"),1036- "//server/dir/file.txt"1037- );1038- }1039-}modified:crates/printer/src/lib.rs+2 added-3 removed
61 unmodified lines62 63 pub use crate::{64 color::{default_color_specs, ColorError, ColorSpecs, UserColorSpec},65 hyperlink::{66- HyperlinkConfig, HyperlinkEnvironment, HyperlinkFormat,67- HyperlinkFormatError,66+ hyperlink_aliases, HyperlinkAlias, HyperlinkConfig,67+ HyperlinkEnvironment, HyperlinkFormat, HyperlinkFormatError,68 },69 path::{PathPrinter, PathPrinterBuilder},70 standard::{Standard, StandardBuilder, StandardSink},71 stats::Stats,19 unmodified lines91 92 mod color;93 mod counter;94 mod hyperlink;95-mod hyperlink_aliases;95 #[cfg(feature = "serde")]96 mod json;97 #[cfg(feature = "serde")]98 mod jsont;5 unmodified lines