Merge pull request #1571 from tmccombs/hyperlink
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add hyperlink support to fd
authored by Thayne McCombs · committed by GitHub · parents 9cefd79, 45d6fbb · Browse files · 12 files·+215 added−34 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+215 added−34 removed
- tests:+21 added−0 removed
- other:+194 added−34 removed
Provenance
- Commit
cfced97- Tree
49d4ab1- Author
Thayne McCombs <astrothayne@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
9cefd79- Parent 2
45d6fbb
12 files changed+215 added−34 removed
modified:contrib/completion/_fd+3 added-1 removed
137 unmodified lines138 never\:"do not use colorized output"139 always\:"always use colorized output"140 ))'141 142+ '--hyperlink=-[add hyperlinks to output paths]::when:(auto never always)'143+144 + '(threads)'145 {-j+,--threads=}'[set the number of threads for searching and executing]:number of threads'146 147 + '(exec-cmds)' # execute command15 unmodified lines163 $no'(--base-directory)--base-directory=[change the current working directory to the given path]:directory:_files -/'164 $no'(*)*--search-path=[set search path (instead of positional <path> arguments)]:directory:_files -/'165 166 + strip-cwd-prefix165- $no'(strip-cwd-prefix exec-cmds)--strip-cwd-prefix=[When to strip ./]:when:(always never auto)'167+ $no'(strip-cwd-prefix exec-cmds)--strip-cwd-prefix=-[When to strip ./]::when:(always never auto)'168 169 + and170 '--and=[additional required search path]:pattern'171 114 unmodified linesmodified:doc/fd.1+18 added
274 unmodified lines275 .IP always276 Always colorize output.277 .RE278 .TP279+.B "\-\-hyperlink280+Specify whether the output should use terminal escape codes to indicate a hyperlink to a281+file url pointing to the path.282+283+The value can be auto, always, or never.284+285+Currently, the default is "never", and if the option is used without an argument "auto" is286+used. In the future this may be changed to "auto" and "always".287+.RS288+.IP auto289+Only output hyperlinks if color is also enabled, as a proxy for whether terminal escape290+codes are acceptable.291+.IP never292+Never output hyperlink escapes.293+.IP always294+Always output hyperlink escapes, regardless of color settings.295+.RE296+.TP297 .BI "\-j, \-\-threads " num298 Set number of threads to use for searching & executing (default: number of available CPU cores).299 .TP300 .BI "\-S, \-\-size " size257 unmodified linesmodified:src/cli.rs+28 added
507 unmodified lines508 long_help,509 )]510 pub color: ColorWhen,511 512+ /// Add a terminal hyperlink to a file:// url for each path in the output.513+ ///514+ /// Auto mode is used if no argument is given to this option.515+ ///516+ /// This doesn't do anything for --exec and --exec-batch.517+ #[arg(518+ long,519+ alias = "hyper",520+ value_name = "when",521+ require_equals = true,522+ value_enum,523+ default_value_t = HyperlinkWhen::Never,524+ default_missing_value = "auto",525+ num_args = 0..=1,526+ help = "Add hyperlinks to output paths"527+ )]528+ pub hyperlink: HyperlinkWhen,529+530 /// Set number of threads to use for searching & executing (default: number531 /// of available CPU cores)532 #[arg(long, short = 'j', value_name = "num", hide_short_help = true, value_parser = str::parse::<NonZeroUsize>)]533 pub threads: Option<NonZeroUsize>,278 unmodified lines812 /// Never strip the ./813 Never,814 }815 816+#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]817+pub enum HyperlinkWhen {818+ /// Use hyperlinks only if color is enabled819+ Auto,820+ /// Always use hyperlinks when printing file paths821+ Always,822+ /// Never use hyperlinks823+ Never,824+}825+826 // there isn't a derive api for getting grouped values yet,827 // so we have to use hand-rolled parsing for exec and exec-batch828 pub struct Exec {829 pub command: Option<CommandSet>,110 unmodified linesmodified:src/config.rs+3 added
124 unmodified lines125 pub max_results: Option<usize>,126 127 /// Whether or not to strip the './' prefix for search results128 pub strip_cwd_prefix: bool,129+130+ /// Whether or not to use hyperlinks on paths131+ pub hyperlink: bool,132 }133 134 impl Config {135 /// Check whether results are being printed.4 unmodified linesadded:src/hyperlink.rs+87 added
1+use crate::filesystem::absolute_path;2+use std::fmt::{self, Formatter, Write};3+use std::path::{Path, PathBuf};4+use std::sync::OnceLock;5+6+pub(crate) struct PathUrl(PathBuf);7+8+#[cfg(unix)]9+static HOSTNAME: OnceLock<String> = OnceLock::new();10+11+impl PathUrl {12+ pub(crate) fn new(path: &Path) -> Option<PathUrl> {13+ Some(PathUrl(absolute_path(path).ok()?))14+ }15+}16+17+impl fmt::Display for PathUrl {18+ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {19+ write!(f, "file://{}", host())?;20+ let bytes = self.0.as_os_str().as_encoded_bytes();21+ for &byte in bytes.iter() {22+ encode(f, byte)?;23+ }24+ Ok(())25+ }26+}27+28+fn encode(f: &mut Formatter, byte: u8) -> fmt::Result {29+ // NOTE:30+ // Most terminals can handle non-ascii unicode characters in a file url fine. But on some OSes (notably31+ // windows), the encoded bytes of the path may not be valid UTF-8. Since we don't know if a32+ // byte >= 128 is part of a valid UTF-8 encoding or not, we just percent encode any non-ascii33+ // byte.34+ // Percent encoding these bytes is probably safer anyway.35+ match byte {36+ b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b'/' | b':' | b'-' | b'.' | b'_' | b'~' => {37+ f.write_char(byte.into())38+ }39+ #[cfg(windows)]40+ b'\\' => f.write_char('/'),41+ _ => {42+ write!(f, "%{:02X}", byte)43+ }44+ }45+}46+47+#[cfg(unix)]48+fn host() -> &'static str {49+ HOSTNAME50+ .get_or_init(|| {51+ nix::unistd::gethostname()52+ .ok()53+ .and_then(|h| h.into_string().ok())54+ .unwrap_or_default()55+ })56+ .as_ref()57+}58+59+#[cfg(not(unix))]60+const fn host() -> &'static str {61+ ""62+}63+64+#[cfg(test)]65+mod test {66+ use super::*;67+68+ // This allows us to test the encoding without having to worry about the host, or absolute path69+ struct Encoded(&'static str);70+71+ impl fmt::Display for Encoded {72+ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {73+ for byte in self.0.bytes() {74+ encode(f, byte)?;75+ }76+ Ok(())77+ }78+ }79+80+ #[test]81+ fn test_unicode_encoding() {82+ assert_eq!(83+ Encoded("$*\x1bßé/∫😃\x07").to_string(),84+ "%24%2A%1B%C3%9F%C3%A9/%E2%88%AB%F0%9F%98%83%07",85+ );86+ }87+}modified:src/main.rs+8 added-1 removed
6 unmodified lines7 mod filesystem;8 mod filetypes;9 mod filter;10 mod fmt;11+mod hyperlink;12 mod output;13 mod regex_helper;14 mod walk;15 8 unmodified lines24 use globset::GlobBuilder;25 use lscolors::LsColors;26 use regex::bytes::{Regex, RegexBuilder, RegexSetBuilder};27 27-use crate::cli::{ColorWhen, Opts};28+use crate::cli::{ColorWhen, HyperlinkWhen, Opts};29 use crate::config::Config;30 use crate::exec::CommandSet;31 use crate::exit_codes::ExitCode;32 use crate::filetypes::FileTypes;201 unmodified lines234 Some(LsColors::from_env().unwrap_or_else(|| LsColors::from_string(DEFAULT_LS_COLORS)))235 } else {236 None237 };238+ let hyperlink = match opts.hyperlink {239+ HyperlinkWhen::Always => true,240+ HyperlinkWhen::Never => false,241+ HyperlinkWhen::Auto => colored_output,242+ };243 let command = extract_command(&mut opts, colored_output)?;244 let has_command = command.is_some();245 246 Ok(Config {16 unmodified lines263 prune: opts.prune,264 threads: opts.threads().get(),265 max_buffer_time: opts.max_buffer_time,266 ls_colors,267+ hyperlink,268 interactive_terminal,269 file_types: opts.filetype.as_ref().map(|values| {270 use crate::cli::FileType::*;271 let mut file_types = FileTypes::default();219 unmodified linesmodified:src/output.rs+25 added-30 removed
3 unmodified lines4 use lscolors::{Indicator, LsColors, Style};5 6 use crate::config::Config;7 use crate::dir_entry::DirEntry;8-use crate::error::print_error;9-use crate::exit_codes::ExitCode;8 use crate::fmt::FormatTemplate;9+use crate::hyperlink::PathUrl;10 11 fn replace_path_separator(path: &str, new_path_separator: &str) -> String {12 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)13 }14 15 // TODO: this function is performance critical and can probably be optimized17-pub fn print_entry<W: Write>(stdout: &mut W, entry: &DirEntry, config: &Config) {18- // TODO: use format if supplied19- let r = if let Some(ref format) = config.format {20- print_entry_format(stdout, entry, config, format)16+pub fn print_entry<W: Write>(stdout: &mut W, entry: &DirEntry, config: &Config) -> io::Result<()> {17+ let mut has_hyperlink = false;18+ if config.hyperlink {19+ if let Some(url) = PathUrl::new(entry.path()) {20+ write!(stdout, "\x1B]8;;{}\x1B\\", url)?;21+ has_hyperlink = true;22+ }23+ }24+25+ if let Some(ref format) = config.format {26+ print_entry_format(stdout, entry, config, format)?;27 } else if let Some(ref ls_colors) = config.ls_colors {22- print_entry_colorized(stdout, entry, config, ls_colors)28+ print_entry_colorized(stdout, entry, config, ls_colors)?;29 } else {24- print_entry_uncolorized(stdout, entry, config)30+ print_entry_uncolorized(stdout, entry, config)?;31 };32 27- if let Err(e) = r {28- if e.kind() == ::std::io::ErrorKind::BrokenPipe {29- // Exit gracefully in case of a broken pipe (e.g. 'fd ... | head -n 3').30- ExitCode::Success.exit();31- } else {32- print_error(format!("Could not write to output: {}", e));33- ExitCode::GeneralError.exit();34- }33+ if has_hyperlink {34+ write!(stdout, "\x1B]8;;\x1B\\")?;35 }36+37+ if config.null_separator {38+ write!(stdout, "\0")39+ } else {40+ writeln!(stdout)41+ }42 }43 44 // Display a trailing slash if the path is a directory and the config option is enabled.45 // If the path_separator option is set, display that instead.24 unmodified lines70 entry: &DirEntry,71 config: &Config,72 format: &FormatTemplate,73 ) -> io::Result<()> {68- let separator = if config.null_separator { "\0" } else { "\n" };74 let output = format.generate(75 entry.stripped_path(config),76 config.path_separator.as_deref(),77 );78 // TODO: support writing raw bytes on unix?74- write!(stdout, "{}{}", output.to_string_lossy(), separator)79+ write!(stdout, "{}", output.to_string_lossy())80 }81 82 // TODO: this function is performance critical and can probably be optimized83 fn print_entry_colorized<W: Write>(43 unmodified lines127 config,128 ls_colors.style_for_indicator(Indicator::Directory),129 )?;130 126- if config.null_separator {127- write!(stdout, "\0")?;128- } else {129- writeln!(stdout)?;130- }131-131 Ok(())132 }133 134 // TODO: this function is performance critical and can probably be optimized1 unmodified line136 stdout: &mut W,137 entry: &DirEntry,138 config: &Config,139 ) -> io::Result<()> {141- let separator = if config.null_separator { "\0" } else { "\n" };140 let path = entry.stripped_path(config);141 142 let mut path_string = path.to_string_lossy();143 if let Some(ref separator) = config.path_separator {144 *path_string.to_mut() = replace_path_separator(&path_string, separator);145 }146 write!(stdout, "{}", path_string)?;149- print_trailing_slash(stdout, entry, config, None)?;150- write!(stdout, "{}", separator)147+ print_trailing_slash(stdout, entry, config, None)148 }149 150 #[cfg(not(unix))]151 fn print_entry_uncolorized<W: Write>(16 unmodified lines168 // Fall back to the base implementation169 print_entry_uncolorized_base(stdout, entry, config)170 } else {171 // Print path as raw bytes, allowing invalid UTF-8 filenames to be passed to other processes175- let separator = if config.null_separator { b"\0" } else { b"\n" };172 stdout.write_all(entry.stripped_path(config).as_os_str().as_bytes())?;177- print_trailing_slash(stdout, entry, config, None)?;178- stdout.write_all(separator)173+ print_trailing_slash(stdout, entry, config, None)174 }175 }modified:src/walk.rs+6 added-1 removed
248 unmodified lines249 }250 251 /// Output a path.252 fn print(&mut self, entry: &DirEntry) -> Result<(), ExitCode> {253- output::print_entry(&mut self.stdout, entry, self.config);253+ if let Err(e) = output::print_entry(&mut self.stdout, entry, self.config) {254+ if e.kind() != ::std::io::ErrorKind::BrokenPipe {255+ print_error(format!("Could not write to output: {}", e));256+ return Err(ExitCode::GeneralError);257+ }258+ }259 260 if self.interrupt_flag.load(Ordering::Relaxed) {261 // Ignore any errors on flush, because we're about to exit anyway262 let _ = self.flush();411 unmodified linesmodified:tests/testenv/mod.rs+3 added
314 unmodified lines315 cmd.env("XDG_CONFIG_HOME", config_dir.path());316 } else {317 cmd.arg("--no-global-ignore-file");318 }319+ // Make sure LS_COLORS is unset to ensure consistent320+ // color output321+ cmd.env("LS_COLORS", "");322 cmd.args(args);323 324 // Run *fd*.325 cmd.output().expect("fd output")29 unmodified linesmodified:tests/tests.rs+18 added
2670 unmodified lines2671 2672 te.assert_output_subdirectory("sub", &["--hidden"], "");2673 te.assert_output_subdirectory("sub", &["--hidden", "--search-path", "."], "");2674 }2675+2676+#[test]2677+fn test_hyperlink() {2678+ let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);2679+2680+ #[cfg(unix)]2681+ let hostname = nix::unistd::gethostname().unwrap().into_string().unwrap();2682+ #[cfg(not(unix))]2683+ let hostname = "";2684+2685+ let expected = format!(2686+ "\x1b]8;;file://{}{}/a.foo\x1b\\a.foo\x1b]8;;\x1b\\",2687+ hostname,2688+ get_absolute_root_path(&te),2689+ );2690+2691+ te.assert_output(&["--hyperlink=always", "a.foo"], &expected);2692+}modified:Cargo.toml+1 added-1 removed
63 unmodified lines64 default-features = false65 features = ["nu-ansi-term"]66 67 [target.'cfg(unix)'.dependencies]68-nix = { version = "0.29.0", default-features = false, features = ["signal", "user"] }68+nix = { version = "0.29.0", default-features = false, features = ["signal", "user", "hostname"] }69 70 [target.'cfg(all(unix, not(target_os = "redox")))'.dependencies]71 libc = "0.2"72 22 unmodified linesmodified:CHANGELOG.md+15 added
1+# Upcoming release2+3+## Features4+5+- Add --hyperlink option to add OSC 8 hyperlinks to output6+7+8+## Bugfixes9+10+11+## Changes12+13+14+## Other15+16 # 10.1.017 18 ## Features19 766 unmodified lines