Skip to content
Myr

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

12 files+215 added−34 removed

modified:contrib/completion/_fd+3 added-1 removed
137 unmodified lines
138 never\:"do not use colorized output"139 always\:"always use colorized output"140 ))'141142 '--hyperlink=-[add hyperlinks to output paths]::when:(auto never always)'143144 + '(threads)'145 {-j+,--threads=}'[set the number of threads for searching and executing]:number of threads'146147 + '(exec-cmds)' # execute command
15 unmodified lines
163 $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 -/'165166 + 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)'168169 + and170 '--and=[additional required search path]:pattern'171
114 unmodified lines
modified:doc/fd.1+18 added
274 unmodified lines
275.IP always276Always colorize output.277.RE278.TP279.B "\-\-hyperlink280Specify whether the output should use terminal escape codes to indicate a hyperlink to a281file url pointing to the path.282283The value can be auto, always, or never.284285Currently, the default is "never", and if the option is used without an argument "auto" is286used. In the future this may be changed to "auto" and "always".287.RS288.IP auto289Only output hyperlinks if color is also enabled, as a proxy for whether terminal escape290codes are acceptable.291.IP never292Never output hyperlink escapes.293.IP always294Always output hyperlink escapes, regardless of color settings.295.RE296.TP297.BI "\-j, \-\-threads " num298Set number of threads to use for searching & executing (default: number of available CPU cores).299.TP300.BI "\-S, \-\-size " size
257 unmodified lines
modified:src/cli.rs+28 added
507 unmodified lines
508 long_help,509 )]510 pub color: ColorWhen,511512 /// 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,529530 /// 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 lines
812 /// Never strip the ./813 Never,814}815816#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]817pub 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}825826// there isn't a derive api for getting grouped values yet,827// so we have to use hand-rolled parsing for exec and exec-batch828pub struct Exec {829 pub command: Option<CommandSet>,
110 unmodified lines
modified:src/config.rs+3 added
124 unmodified lines
125 pub max_results: Option<usize>,126127 /// Whether or not to strip the './' prefix for search results128 pub strip_cwd_prefix: bool,129130 /// Whether or not to use hyperlinks on paths131 pub hyperlink: bool,132}133134impl Config {135 /// Check whether results are being printed.
4 unmodified lines
added:src/hyperlink.rs+87 added
1use crate::filesystem::absolute_path;2use std::fmt::{self, Formatter, Write};3use std::path::{Path, PathBuf};4use std::sync::OnceLock;56pub(crate) struct PathUrl(PathBuf);78#[cfg(unix)]9static HOSTNAME: OnceLock<String> = OnceLock::new();1011impl PathUrl {12 pub(crate) fn new(path: &Path) -> Option<PathUrl> {13 Some(PathUrl(absolute_path(path).ok()?))14 }15}1617impl 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}2728fn 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}4647#[cfg(unix)]48fn 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}5859#[cfg(not(unix))]60const fn host() -> &'static str {61 ""62}6364#[cfg(test)]65mod test {66 use super::*;6768 // This allows us to test the encoding without having to worry about the host, or absolute path69 struct Encoded(&'static str);7071 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 }7980 #[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 lines
7mod filesystem;8mod filetypes;9mod filter;10mod fmt;11mod hyperlink;12mod output;13mod regex_helper;14mod walk;15
8 unmodified lines
24use globset::GlobBuilder;25use lscolors::LsColors;26use regex::bytes::{Regex, RegexBuilder, RegexSetBuilder};2727use crate::cli::{ColorWhen, Opts};28use crate::cli::{ColorWhen, HyperlinkWhen, Opts};29use crate::config::Config;30use crate::exec::CommandSet;31use crate::exit_codes::ExitCode;32use crate::filetypes::FileTypes;
201 unmodified lines
234 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();245246 Ok(Config {
16 unmodified lines
263 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 lines
modified:src/output.rs+25 added-30 removed
3 unmodified lines
4use lscolors::{Indicator, LsColors, Style};56use crate::config::Config;7use crate::dir_entry::DirEntry;8use crate::error::print_error;9use crate::exit_codes::ExitCode;8use crate::fmt::FormatTemplate;9use crate::hyperlink::PathUrl;1011fn replace_path_separator(path: &str, new_path_separator: &str) -> String {12 path.replace(std::path::MAIN_SEPARATOR, new_path_separator)13}1415// TODO: this function is performance critical and can probably be optimized17pub 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)16pub 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 }2425 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 };3227 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 }3637 if config.null_separator {38 write!(stdout, "\0")39 } else {40 writeln!(stdout)41 }42}4344// 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 lines
70 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}8182// TODO: this function is performance critical and can probably be optimized83fn print_entry_colorized<W: Write>(
43 unmodified lines
127 config,128 ls_colors.style_for_indicator(Indicator::Directory),129 )?;130126 if config.null_separator {127 write!(stdout, "\0")?;128 } else {129 writeln!(stdout)?;130 }131131 Ok(())132}133134// TODO: this function is performance critical and can probably be optimized
1 unmodified line
136 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);141142 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}149150#[cfg(not(unix))]151fn print_entry_uncolorized<W: Write>(
16 unmodified lines
168 // 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 lines
249 }250251 /// 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 }259260 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 lines
modified:tests/testenv/mod.rs+3 added
314 unmodified lines
315 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);323324 // Run *fd*.325 cmd.output().expect("fd output")
29 unmodified lines
modified:tests/tests.rs+18 added
2670 unmodified lines
26712672 te.assert_output_subdirectory("sub", &["--hidden"], "");2673 te.assert_output_subdirectory("sub", &["--hidden", "--search-path", "."], "");2674}26752676#[test]2677fn test_hyperlink() {2678 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);26792680 #[cfg(unix)]2681 let hostname = nix::unistd::gethostname().unwrap().into_string().unwrap();2682 #[cfg(not(unix))]2683 let hostname = "";26842685 let expected = format!(2686 "\x1b]8;;file://{}{}/a.foo\x1b\\a.foo\x1b]8;;\x1b\\",2687 hostname,2688 get_absolute_root_path(&te),2689 );26902691 te.assert_output(&["--hyperlink=always", "a.foo"], &expected);2692}
modified:Cargo.toml+1 added-1 removed
63 unmodified lines
64default-features = false65features = ["nu-ansi-term"]6667[target.'cfg(unix)'.dependencies]68nix = { version = "0.29.0", default-features = false, features = ["signal", "user"] }68nix = { version = "0.29.0", default-features = false, features = ["signal", "user", "hostname"] }6970[target.'cfg(all(unix, not(target_os = "redox")))'.dependencies]71libc = "0.2"72
22 unmodified lines
modified:CHANGELOG.md+15 added
1# Upcoming release23## Features45- Add --hyperlink option to add OSC 8 hyperlinks to output678## Bugfixes91011## Changes121314## Other1516# 10.1.01718## Features19
766 unmodified lines