use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use alacritty_terminal::index::{Column, Point};
use alacritty_terminal::term::Term;
use crate::terminal::search::row_chars;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Target {
Url(String),
Path(PathBuf),
Entry {
path: PathBuf,
name: String,
},
Location {
path: PathBuf,
pos: Pos,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Pos {
pub line: u32,
pub col: Option<u32>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Link {
pub line: i32,
pub start: usize,
pub end: usize,
pub target: Target,
}
fn is_delimiter(c: char) -> bool {
c.is_whitespace() || matches!(c, '\0' | '"' | '\'' | '<' | '>' | '|' | '`')
}
fn word_bounds(chars: &[char], idx: usize) -> Option<(usize, usize)> {
if chars.get(idx).is_none_or(|&c| is_delimiter(c)) {
return None;
}
let (mut lo, mut hi) = (idx, idx);
while lo > 0 && !is_delimiter(chars[lo - 1]) {
lo -= 1;
}
while hi + 1 < chars.len() && !is_delimiter(chars[hi + 1]) {
hi += 1;
}
while lo < hi && matches!(chars[lo], '(' | '[' | '{') {
lo += 1;
}
while hi > lo {
let last = chars[hi];
let opener = match last {
')' => '(',
']' => '[',
'}' => '{',
'.' | ',' | ';' | ':' | '!' | '?' => {
hi -= 1;
continue;
}
_ => break,
};
let word = &chars[lo..=hi];
if word.iter().filter(|&&c| c == last).count() > word.iter().filter(|&&c| c == opener).count() {
hi -= 1;
} else {
break;
}
}
(lo..=hi).contains(&idx).then_some((lo, hi))
}
fn is_web_url(s: &str) -> bool {
let lower = s.to_ascii_lowercase();
["http://", "https://"].iter().any(|p| lower.starts_with(p) && lower.len() > p.len())
}
pub fn split_position(text: &str) -> (&str, Option<Pos>) {
if let Some(inner) = text.strip_suffix(')')
&& let Some(open) = text.rfind('(')
&& open > 0
{
let mut nums = inner[open + 1..].split(',').map(|n| n.trim().parse::<u32>());
if let (Some(Ok(line)), col, None) = (nums.next(), nums.next(), nums.next())
&& col.as_ref().is_none_or(|c| c.is_ok())
{
return (&text[..open], Some(Pos { line, col: col.and_then(Result::ok) }));
}
}
let mut rest = text;
let mut nums = Vec::new();
for _ in 0..2 {
match rest.rfind(':') {
Some(i) if i > 1 && rest.len() > i + 1 && rest[i + 1..].bytes().all(|b| b.is_ascii_digit()) => {
let Ok(n) = rest[i + 1..].parse::<u32>() else { break };
nums.push(n);
rest = &rest[..i];
}
_ => break,
}
}
let pos = match nums.as_slice() {
[line] => Some(Pos { line: *line, col: None }),
[col, line] => Some(Pos { line: *line, col: Some(*col) }),
_ => None,
};
(rest, pos)
}
#[cfg(test)]
fn strip_position(text: &str) -> &str {
split_position(text).0
}
#[cfg(test)]
fn existing_path(text: &str, cwd: Option<&Path>) -> Option<PathBuf> {
existing_path_with(text, cwd).map(|(path, ..)| path)
}
fn existing_path_with<'a>(text: &'a str, cwd: Option<&Path>) -> Option<(PathBuf, &'a str, Option<Pos>)> {
let (s, pos) = split_position(text);
let marked = s.trim_end_matches(['*', '@', '=']);
let diff_stripped = marked.strip_prefix("a/").or_else(|| marked.strip_prefix("b/"));
for cand in [s, marked].into_iter().chain(diff_stripped) {
let b = cand.as_bytes();
let drive = b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'\\' || b[2] == b'/');
if (cand.len() < 2 && cand != "~")
|| cand.contains(['*', '?', '"', '<', '>', '|'])
|| (!drive && cand.contains(':'))
{
continue;
}
let path = if cand == "~" {
dirs::home_dir()?
} else if let Some(rest) = cand.strip_prefix("~/").or_else(|| cand.strip_prefix("~\\")) {
dirs::home_dir()?.join(rest.replace('/', "\\"))
} else if b.len() >= 2 && b[0] == b'/' && b[1].is_ascii_alphabetic() && (b.len() == 2 || b[2] == b'/') {
PathBuf::from(format!(
"{}:\\{}",
(b[1] as char).to_ascii_uppercase(),
cand.get(3..).unwrap_or("").replace('/', "\\")
))
} else if drive {
PathBuf::from(cand.replace('/', "\\"))
} else {
let rel = cand.replace('/', "\\");
let base = cwd?;
if cand.contains(['/', '\\']) {
base.ancestors()
.take(8)
.map(|dir| dir.join(&rel))
.find(|p| p.exists())
.unwrap_or_else(|| base.join(&rel))
} else {
base.join(&rel)
}
};
if path.exists() {
return Some((path, cand, pos));
}
}
None
}
fn path_target(text: &str, cwd: Option<&Path>) -> Option<Target> {
let (path, matched, pos) = existing_path_with(text, cwd)?;
if let Some(pos) = pos
&& path.is_file()
{
return Some(Target::Location { path, pos });
}
let name = matched.trim_end_matches('/');
let bare = pos.is_none() && !name.is_empty() && !name.starts_with('~') && !name.contains(['/', '\\', ':']);
Some(if bare { Target::Entry { path, name: name.to_string() } } else { Target::Path(path) })
}
fn quoted_bounds(chars: &[char], idx: usize) -> Option<(usize, usize)> {
let ends_here = |at: usize| chars.get(at + 1).is_none_or(|n| n.is_whitespace() || "/*@=|>".contains(*n));
let mut i = 0;
while i < chars.len() {
let quote = chars[i];
if (quote == '\'' || quote == '"') && (i == 0 || chars[i - 1].is_whitespace()) {
if let Some(close) = (i + 1..chars.len()).find(|&j| chars[j] == quote && ends_here(j)) {
if idx > i && idx < close {
return (close > i + 1).then_some((i + 1, close - 1));
}
i = close + 1;
continue;
}
}
i += 1;
}
None
}
fn spaced_entry(chars: &[char], idx: usize, cwd: Option<&Path>) -> Option<(usize, usize)> {
let names = std::fs::read_dir(cwd?).ok()?;
let boundary_before = |at: usize| at == 0 || matches!(chars[at - 1], ' ' | '\'' | '"');
let boundary_after = |at: usize| chars.get(at + 1).is_none_or(|n| " '\"/*@=|>".contains(*n));
let mut best: Option<(usize, usize)> = None;
for entry in names.flatten() {
let name: Vec<char> = entry.file_name().to_string_lossy().chars().collect();
if !name.contains(&' ') || name.len() > chars.len() {
continue;
}
for start in 0..=chars.len() - name.len() {
let end = start + name.len() - 1;
if (start..=end).contains(&idx)
&& chars[start..=end] == name[..]
&& boundary_before(start)
&& boundary_after(end)
&& best.is_none_or(|(s, e)| end - start > e - s)
{
best = Some((start, end));
}
}
}
best
}
fn percent_decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
if b[i] == b'%'
&& let Some(hex) = s.get(i + 1..i + 3)
&& let Ok(v) = u8::from_str_radix(hex, 16)
{
out.push(v);
i += 3;
} else {
out.push(b[i]);
i += 1;
}
}
String::from_utf8_lossy(&out).into_owned()
}
fn paren_inner(word: &str) -> Option<&str> {
let inner = word.strip_suffix(')')?;
let open = inner.rfind('(')?;
(open > 0).then(|| &inner[open + 1..])
}
fn classify(word: &str, cwd: Option<&Path>) -> Option<Target> {
if is_web_url(word) {
return Some(Target::Url(word.to_string()));
}
if word.len() > 4 && word[..4].eq_ignore_ascii_case("www.") && word[4..].contains('.') {
return Some(Target::Url(format!("https://{word}")));
}
if word.len() > 8 && word[..8].eq_ignore_ascii_case("file:///") {
return path_target(&percent_decode(&word[8..]), cwd);
}
path_target(word, cwd).or_else(|| paren_inner(word).and_then(|inner| path_target(inner, cwd)))
}
fn following_position(chars: &[char], hi: usize) -> Option<Pos> {
fn number(s: &str) -> Option<(u32, &str)> {
let digits = s.bytes().take_while(u8::is_ascii_digit).count();
(digits > 0).then(|| (s[..digits].parse().ok(), &s[digits..])).and_then(|(n, rest)| Some((n?, rest)))
}
let rest: String = chars.get(hi + 1..)?.iter().collect();
let rest = rest.trim_start_matches(['"', '\'', ',']).trim_start();
if let Some(after) = rest.strip_prefix("line ") {
return number(after.trim_start()).map(|(line, _)| Pos { line, col: None });
}
let (line, after) = number(rest)?;
let col = after.strip_prefix(':').and_then(number).map(|(c, _)| c)?;
Some(Pos { line, col: Some(col) })
}
pub fn find<T>(term: &Term<T>, point: Point, cwd: Option<&Path>) -> Option<Link> {
let row = row_chars(term, point.line);
let idx = row.iter().position(|&(col, _, w)| (col..col + w).contains(&point.column.0))?;
let span = |lo: usize, hi: usize| (row[lo].0, row[hi].0 + row[hi].2);
let cell = &term.grid()[point.line][Column(row[idx].0)];
if let Some(link) = cell.hyperlink() {
let uri = link.uri().to_string();
let same = |i: usize| term.grid()[point.line][Column(row[i].0)].hyperlink().is_some_and(|h| h.uri() == uri);
let (mut lo, mut hi) = (idx, idx);
while lo > 0 && same(lo - 1) {
lo -= 1;
}
while hi + 1 < row.len() && same(hi + 1) {
hi += 1;
}
let (start, end) = span(lo, hi);
return is_web_url(&uri).then_some(Link { line: point.line.0, start, end, target: Target::Url(uri) });
}
let chars: Vec<char> = row.iter().map(|&(_, c, _)| c).collect();
if let Some((lo, hi)) = quoted_bounds(&chars, idx) {
let name: String = chars[lo..=hi].iter().collect();
if let Some(target) = path_target(&name, cwd) {
let (start, end) = span(lo, hi);
return Some(Link { line: point.line.0, start, end, target });
}
}
if let Some((lo, hi)) = spaced_entry(&chars, idx, cwd) {
let name: String = chars[lo..=hi].iter().collect();
if let Some(target) = path_target(&name, cwd) {
let (start, end) = span(lo, hi);
return Some(Link { line: point.line.0, start, end, target });
}
}
let (lo, hi) = word_bounds(&chars, idx)?;
let word: String = chars[lo..=hi].iter().collect();
let mut target = classify(&word, cwd)?;
if let Target::Path(path) | Target::Entry { path, .. } = &target
&& path.is_file()
&& let Some(pos) = following_position(&chars, hi)
{
target = Target::Location { path: path.clone(), pos };
}
let (start, end) = span(lo, hi);
Some(Link { line: point.line.0, start, end, target })
}
#[link(name = "shell32")]
unsafe extern "system" {
fn ShellExecuteW(
hwnd: isize,
op: *const u16,
file: *const u16,
params: *const u16,
dir: *const u16,
show: i32,
) -> isize;
}
fn wide(s: &OsStr) -> Vec<u16> {
s.encode_wide().chain(std::iter::once(0)).collect()
}
pub fn shell_open(what: &OsStr) {
unsafe {
ShellExecuteW(0, wide(OsStr::new("open")).as_ptr(), wide(what).as_ptr(), std::ptr::null(), std::ptr::null(), 1);
}
}
fn runs_code(path: &Path) -> bool {
const EXTS: &[&str] = &[
"exe", "com", "bat", "cmd", "ps1", "psm1", "vbs", "vbe", "js", "jse", "wsf", "wsh", "msi", "msp", "scr", "lnk",
"url", "hta", "reg", "cpl", "jar", "dll", "sys", "pif", "appx", "msix",
];
path.extension().and_then(|e| e.to_str()).is_some_and(|e| EXTS.iter().any(|x| x.eq_ignore_ascii_case(e)))
}
fn open_in_editor(path: &Path, pos: Pos, template: &str) {
let (path, template) = (path.to_path_buf(), template.to_string());
std::thread::spawn(move || open_in_editor_blocking(&path, pos, &template));
}
pub fn open_in_editor_blocking(path: &Path, pos: Pos, template: &str) {
let default_app = |path: &Path| if runs_code(path) { reveal(path) } else { shell_open(path.as_os_str()) };
let template = if template.trim() == BUILT_IN_EDITOR { OUTSIDE_EDITOR } else { template };
if template.trim().is_empty() {
default_app(path);
return;
}
let command = template
.replace("{file}", &path.to_string_lossy())
.replace("{line}", &pos.line.to_string())
.replace("{col}", &pos.col.unwrap_or(1).to_string());
let ok = std::process::Command::new("cmd.exe")
.raw_arg(format!("/S /C \"{command}\""))
.creation_flags(0x0800_0000) .status()
.is_ok_and(|s| s.success());
if !ok {
default_app(path);
}
}
pub fn open(target: &Target, editor: &str) {
match target {
Target::Url(url) if is_web_url(url) => shell_open(OsStr::new(url)),
Target::Url(_) => {}
Target::Location { path, pos } => open_in_editor(path, *pos, editor),
Target::Path(path) | Target::Entry { path, .. } if path.is_dir() || !runs_code(path) => {
shell_open(path.as_os_str())
}
Target::Path(path) | Target::Entry { path, .. } => reveal(path),
}
}
pub fn reveal(path: &Path) {
let _ = std::process::Command::new("explorer.exe").raw_arg(format!("/select,\"{}\"", path.display())).spawn();
}
pub fn path_of(target: &Target) -> Option<&Path> {
match target {
Target::Path(path) | Target::Entry { path, .. } | Target::Location { path, .. } => Some(path),
Target::Url(_) => None,
}
}
const TEXT_EXTS: &[&str] = &[
"txt",
"md",
"markdown",
"rst",
"json",
"jsonc",
"json5",
"jsx",
"js",
"mjs",
"cjs",
"ts",
"tsx",
"css",
"scss",
"sass",
"less",
"html",
"htm",
"xml",
"svg",
"yml",
"yaml",
"toml",
"ini",
"cfg",
"conf",
"env",
"log",
"csv",
"tsv",
"rs",
"py",
"go",
"java",
"kt",
"c",
"h",
"cpp",
"hpp",
"cc",
"cs",
"rb",
"php",
"sh",
"bash",
"zsh",
"fish",
"ps1",
"bat",
"cmd",
"lua",
"sql",
"vue",
"svelte",
"gradle",
"lock",
"gitignore",
"gitattributes",
"editorconfig",
"dockerfile",
"mk",
"cmake",
"tex",
"diff",
"patch",
"properties",
];
const MAX_CAT_BYTES: u64 = 1 << 20;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EntryAction {
Enter,
Print,
Open,
}
fn readable_text(path: &Path) -> bool {
use std::io::Read;
let Ok(meta) = std::fs::metadata(path) else { return false };
if !meta.is_file() || meta.len() > MAX_CAT_BYTES {
return false;
}
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
if ext.as_deref().is_some_and(|e| !TEXT_EXTS.contains(&e)) {
return false;
}
let mut buf = [0u8; 4096];
let n = std::fs::File::open(path).and_then(|mut f| f.read(&mut buf)).unwrap_or(0);
!buf[..n].contains(&0)
}
pub const BUILT_IN_EDITOR: &str = "rustimal";
const OUTSIDE_EDITOR: &str = r#"code -g "{file}:{line}:{col}""#;
pub fn opens_in_editor(path: &Path) -> bool {
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
!matches!(ext.as_deref(), Some("html" | "htm" | "svg")) && readable_text(path)
}
pub fn entry_action(path: &Path) -> EntryAction {
if path.is_dir() {
EntryAction::Enter
} else if readable_text(path) {
EntryAction::Print
} else {
EntryAction::Open
}
}
pub fn msys_path(path: &Path) -> String {
let s = path.to_string_lossy();
let b = s.as_bytes();
if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' {
format!("/{}{}", (b[0] as char).to_ascii_lowercase(), s[2..].replace('\\', "/"))
} else {
s.replace('\\', "/")
}
}
pub fn shell_word(text: &str) -> String {
let plain = !text.is_empty() && text.bytes().all(|b| b.is_ascii_alphanumeric() || b"_./:@%+=,~-".contains(&b));
if plain { text.to_string() } else { shell_quote(text) }
}
fn shell_quote(name: &str) -> String {
format!("'{}'", name.replace('\'', "'\\''"))
}
pub fn entry_command(path: &Path, name: &str) -> Option<String> {
let q = shell_quote(name);
match entry_action(path) {
EntryAction::Enter => Some(format!("cd -- {q} && ls")),
EntryAction::Print => Some(format!("cat -- {q}")),
EntryAction::Open => None,
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ClickMode {
Open,
Explorer,
Run,
Embed,
}
fn windows_word(path: &Path) -> String {
shell_quote(&path.display().to_string())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Program {
Exe,
Batch,
PowerShell,
Shell,
}
fn program_kind(path: &Path) -> Option<Program> {
if !path.is_file() || !runs_code(path) {
return None;
}
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default();
Some(match ext.as_str() {
"exe" | "com" => Program::Exe,
"bat" | "cmd" => Program::Batch,
"ps1" => Program::PowerShell,
_ => Program::Shell,
})
}
pub fn run_command(path: &Path, name: &str) -> Option<String> {
let q = windows_word(path);
match program_kind(path) {
Some(Program::Exe) => return Some(q),
Some(Program::Batch) => return Some(format!("cmd.exe //c {q}")),
Some(Program::PowerShell) => return Some(format!("powershell.exe -NoProfile -File {q}")),
Some(Program::Shell) => return Some(format!("cmd.exe //c start \"\" {q}")),
None => {}
}
entry_command(path, name).or_else(|| Some(format!("cmd.exe //c start \"\" {q}")))
}
pub fn embed_command(path: &Path) -> Option<String> {
let q = windows_word(path);
match program_kind(path) {
Some(Program::Exe) => Some(format!("embed {q}")),
Some(Program::Batch) => Some(format!("embed cmd.exe //c {q}")),
Some(Program::PowerShell) => Some(format!("embed powershell.exe -NoProfile -File {q}")),
Some(Program::Shell) => None,
None if path.is_dir() || opens_in_editor(path) => Some(format!("vscode {q}")),
None => None,
}
}
pub fn embed_url_command(url: &str) -> String {
format!("zen {}", shell_quote(url))
}
pub fn show_in_explorer(path: &Path) {
if path.is_dir() {
shell_open(path.as_os_str());
} else {
reveal(path);
}
}
#[cfg(test)]
mod tests {
#[test]
fn each_click_mode_types_its_own_command() {
let dir = std::env::temp_dir().join(format!("rustimal-modes-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("my folder")).unwrap();
for file in ["brave.exe", "tool.bat", "setup.ps1", "link.lnk", "notes.txt", "photo.png"] {
std::fs::write(dir.join(file), if file.ends_with("png") { &[0u8, 1, 2][..] } else { b"x" }).unwrap();
}
let at = |name: &str| dir.join(name);
let q = |name: &str| format!("'{}'", dir.join(name).display());
assert_eq!(run_command(&at("brave.exe"), "brave.exe"), Some(q("brave.exe")));
assert_eq!(run_command(&at("tool.bat"), "tool.bat"), Some(format!("cmd.exe //c {}", q("tool.bat"))));
assert_eq!(
run_command(&at("setup.ps1"), "setup.ps1"),
Some(format!("powershell.exe -NoProfile -File {}", q("setup.ps1")))
);
assert_eq!(run_command(&at("link.lnk"), "link.lnk"), Some(format!("cmd.exe //c start \"\" {}", q("link.lnk"))));
assert_eq!(run_command(&at("my folder"), "my folder"), Some("cd -- 'my folder' && ls".to_string()));
assert_eq!(run_command(&at("notes.txt"), "notes.txt"), Some("cat -- 'notes.txt'".to_string()));
assert_eq!(
run_command(&at("photo.png"), "photo.png"),
Some(format!("cmd.exe //c start \"\" {}", q("photo.png")))
);
assert_eq!(embed_command(&at("brave.exe")), Some(format!("embed {}", q("brave.exe"))));
assert_eq!(embed_command(&at("tool.bat")), Some(format!("embed cmd.exe //c {}", q("tool.bat"))));
assert_eq!(embed_command(&at("my folder")), Some(format!("vscode {}", q("my folder"))));
assert_eq!(embed_command(&at("notes.txt")), Some(format!("vscode {}", q("notes.txt"))));
assert_eq!(embed_command(&at("link.lnk")), None, "a shortcut hands off to another process");
assert_eq!(embed_command(&at("photo.png")), None, "nothing to edit or run");
assert_eq!(embed_url_command("https://a.b/?x=1"), "zen 'https://a.b/?x=1'");
assert_eq!(embed_url_command("it's"), "zen 'it'\\''s'");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn the_editor_command_gets_file_line_and_column() {
let dir = std::env::temp_dir().join(format!("rustimal-editor-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("app.css");
let out = dir.join("out.txt");
std::fs::write(&file, "a{}").unwrap();
let template = format!("echo {{file}}^|{{line}}^|{{col}} > \"{}\"", out.display());
open_in_editor_blocking(&file, Pos { line: 20, col: None }, &template);
let got = std::fs::read_to_string(&out).unwrap();
assert_eq!(got.trim(), format!("{}|20|1", file.display()).as_str());
let _ = std::fs::remove_dir_all(&dir);
}
use super::*;
fn bounds(text: &str, at: usize) -> Option<String> {
let chars: Vec<char> = text.chars().collect();
word_bounds(&chars, at).map(|(lo, hi)| chars[lo..=hi].iter().collect())
}
#[test]
fn trims_punctuation_around_urls() {
assert_eq!(bounds("see (https://a.io/x).", 8).as_deref(), Some("https://a.io/x"));
assert_eq!(bounds("go to https://a.io/x, then", 10).as_deref(), Some("https://a.io/x"));
assert_eq!(
bounds("https://en.wikipedia.org/wiki/Foo_(bar)", 5).as_deref(),
Some("https://en.wikipedia.org/wiki/Foo_(bar)")
);
}
#[test]
fn no_word_on_whitespace_or_quotes() {
assert_eq!(bounds("a b", 1), None);
assert_eq!(bounds("say \"hi\"", 4), None);
assert_eq!(bounds("abc", 9), None);
}
#[test]
fn classifies_urls() {
assert_eq!(classify("https://a.io", None), Some(Target::Url("https://a.io".into())));
assert_eq!(classify("HTTP://A.IO/x", None), Some(Target::Url("HTTP://A.IO/x".into())));
assert_eq!(classify("www.rust-lang.org", None), Some(Target::Url("https://www.rust-lang.org".into())));
assert_eq!(classify("https://", None), None);
assert_eq!(classify("ftp://a.io", None), None);
}
#[test]
fn position_suffix_is_removed_but_not_the_drive() {
assert_eq!(strip_position("src/app.rs:12:5"), "src/app.rs");
assert_eq!(strip_position("src/app.rs:12"), "src/app.rs");
assert_eq!(strip_position("C:\\x\\y.rs:3"), "C:\\x\\y.rs");
assert_eq!(strip_position("C:\\x"), "C:\\x");
assert_eq!(strip_position("note:abc"), "note:abc");
}
#[test]
fn finds_files_that_exist_only() {
let here = std::env::current_dir().unwrap();
assert_eq!(existing_path("Cargo.toml:3:1", Some(&here)), Some(here.join("Cargo.toml")));
assert_eq!(existing_path("a/src/main.rs", Some(&here)), Some(here.join("src\\main.rs")));
assert_eq!(existing_path("src/no_such_file.rs", Some(&here)), None);
assert_eq!(existing_path("hello", Some(&here)), None);
assert_eq!(existing_path("Cargo.toml", None), None);
let abs = here.join("Cargo.toml");
assert_eq!(existing_path(&abs.to_string_lossy().replace('\\', "/"), None), Some(abs));
}
#[test]
fn finds_names_as_ls_prints_them() {
let here = std::env::current_dir().unwrap();
assert_eq!(existing_path("src", Some(&here)), Some(here.join("src")));
assert_eq!(existing_path("src/", Some(&here)), Some(here.join("src")));
assert_eq!(existing_path("Cargo.toml*", Some(&here)), Some(here.join("Cargo.toml")));
assert_eq!(existing_path("Cargo.toml@", Some(&here)), Some(here.join("Cargo.toml")));
assert_eq!(existing_path("no_such_thing", Some(&here)), None);
assert_eq!(existing_path("~", None), dirs::home_dir());
assert_eq!(existing_path("a:b", Some(&here)), None);
}
#[test]
fn quoted_names_with_spaces() {
let chars: Vec<char> = "ls 'My Folder' 'x y' it's".chars().collect();
let inner = |at: usize| quoted_bounds(&chars, at).map(|(lo, hi)| chars[lo..=hi].iter().collect::<String>());
assert_eq!(inner(7).as_deref(), Some("My Folder")); assert_eq!(inner(18).as_deref(), Some("x y"));
assert_eq!(inner(14), None); assert_eq!(inner(15), None); assert_eq!(inner(0), None);
}
#[test]
fn an_apostrophe_in_a_name_does_not_shift_the_quotes_after_it() {
let chars: Vec<char> = "'a b.txt' c.txt \"it's here\"/ 'my folder'/ plain/".chars().collect();
let inner = |at: usize| quoted_bounds(&chars, at).map(|(lo, hi)| chars[lo..=hi].iter().collect::<String>());
assert_eq!(inner(2).as_deref(), Some("a b.txt"));
assert_eq!(inner(21).as_deref(), Some("it's here"));
assert_eq!(inner(23).as_deref(), Some("it's here"), "on the apostrophe itself");
let at = chars.iter().position(|&c| c == 'f').unwrap();
assert_eq!(inner(at).as_deref(), Some("my folder"), "after the apostrophe's name");
assert_eq!(inner(chars.len() - 3), None, "plain/ has no quotes");
}
#[test]
fn unquoted_names_with_spaces_are_found_from_the_folder() {
let dir = std::env::temp_dir().join(format!("rustimal-spaced-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("my folder")).unwrap();
std::fs::create_dir_all(dir.join("my folder two")).unwrap();
std::fs::write(dir.join("a b.txt"), "x").unwrap();
let chars: Vec<char> = "a b.txt my folder/ my folder two other".chars().collect();
let found =
|at: usize| spaced_entry(&chars, at, Some(&dir)).map(|(lo, hi)| chars[lo..=hi].iter().collect::<String>());
assert_eq!(found(2).as_deref(), Some("a b.txt"));
assert_eq!(found(14).as_deref(), Some("my folder"), "a marker after the name is not part of it");
assert_eq!(found(26).as_deref(), Some("my folder two"), "the longest name that covers the cell");
assert_eq!(found(chars.len() - 2), None);
assert_eq!(spaced_entry(&chars, 2, None), None);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn bare_names_are_entries() {
let here = std::env::current_dir().unwrap();
let entry = |name: &str| Some(Target::Entry { path: here.join(name), name: name.to_string() });
assert_eq!(path_target("src", Some(&here)), entry("src"));
assert_eq!(path_target("src/", Some(&here)), entry("src"));
assert_eq!(path_target("Cargo.toml*", Some(&here)), entry("Cargo.toml"));
assert_eq!(path_target("src/main.rs", Some(&here)), Some(Target::Path(here.join("src\\main.rs"))));
assert_eq!(
path_target("Cargo.toml:3", Some(&here)),
Some(Target::Location { path: here.join("Cargo.toml"), pos: Pos { line: 3, col: None } })
);
assert_eq!(path_target("~", None), dirs::home_dir().map(Target::Path));
}
#[test]
fn click_actions_by_file_kind() {
let dir = std::env::temp_dir().join(format!("rustimal-links-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let write = |name: &str, bytes: &[u8]| {
let p = dir.join(name);
std::fs::write(&p, bytes).unwrap();
p
};
assert_eq!(entry_action(&dir), EntryAction::Enter);
assert_eq!(entry_action(&write("a.json", b"{}")), EntryAction::Print);
assert_eq!(entry_action(&write("App.JSX", b"<a/>")), EntryAction::Print);
assert_eq!(entry_action(&write("LICENSE", b"MIT")), EntryAction::Print);
assert_eq!(entry_action(&write(".gitignore", b"target")), EntryAction::Print);
assert_eq!(entry_action(&write("pic.png", b"png")), EntryAction::Open);
assert_eq!(entry_action(&write("tool.exe", b"MZ")), EntryAction::Open);
assert_eq!(entry_action(&write("nul.json", b"a\0b")), EntryAction::Open);
assert_eq!(entry_action(&write("no_ext_binary", &[1, 0, 2])), EntryAction::Open);
assert_eq!(entry_action(&write("big.txt", &vec![b'x'; (MAX_CAT_BYTES + 1) as usize])), EntryAction::Open);
assert_eq!(entry_command(&dir, "my dir").as_deref(), Some("cd -- 'my dir' && ls"));
assert_eq!(entry_command(&dir.join("a.json"), "a.json").as_deref(), Some("cat -- 'a.json'"));
assert_eq!(entry_command(&dir.join("pic.png"), "pic.png"), None);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn dropped_paths_are_written_for_git_bash() {
let word = |p: &str| shell_word(&msys_path(Path::new(p)));
assert_eq!(word("C:\\Users\\me\\a.txt"), "/c/Users/me/a.txt");
assert_eq!(word("C:\\Users\\me\\a b.txt"), "'/c/Users/me/a b.txt'");
assert_eq!(word("D:\\"), "/d/");
assert_eq!(word("\\\\server\\share\\f.txt"), "//server/share/f.txt");
assert_eq!(word("C:\\it's.txt"), "'/c/it'\\''s.txt'");
assert_eq!(word("C:\\a&b.txt"), "'/c/a&b.txt'");
}
#[test]
fn names_are_quoted_for_bash() {
assert_eq!(shell_quote("plain"), "'plain'");
assert_eq!(shell_quote("it's"), "'it'\\''s'");
assert_eq!(shell_quote("a b; rm -rf *"), "'a b; rm -rf *'");
}
#[test]
fn splits_positions_in_every_style() {
let pos = |line, col| Some(Pos { line, col });
assert_eq!(split_position("src/app.rs:12:5"), ("src/app.rs", pos(12, Some(5))));
assert_eq!(split_position("src/app.rs:12"), ("src/app.rs", pos(12, None)));
assert_eq!(split_position("src/app.ts(12,5)"), ("src/app.ts", pos(12, Some(5))));
assert_eq!(split_position("src/app.ts(12)"), ("src/app.ts", pos(12, None)));
assert_eq!(split_position("C:\\proj\\a.js:3:9"), ("C:\\proj\\a.js", pos(3, Some(9))));
assert_eq!(split_position("C:\\proj\\a.js"), ("C:\\proj\\a.js", None));
assert_eq!(split_position("Foo.bar(Foo.java:12)"), ("Foo.bar(Foo.java:12)", None));
assert_eq!(split_position("f(1,2,3)"), ("f(1,2,3)", None));
}
#[test]
fn positions_after_a_path() {
let after = |text: &str| {
let chars: Vec<char> = text.chars().collect();
let hi = chars.iter().position(|&c| c == ']').unwrap();
following_position(&chars, hi)
};
assert_eq!(after("x.py]\", line 12, in f"), Some(Pos { line: 12, col: None }));
assert_eq!(after("a.js] 12:5-20"), Some(Pos { line: 12, col: Some(5) }));
assert_eq!(after("main.rs] 12 files changed"), None);
assert_eq!(after("main.rs]"), None);
}
#[test]
fn error_traces_become_locations() {
let here = std::env::current_dir().unwrap();
let main = here.join("src").join("main.rs");
let loc = |line, col| Some(Target::Location { path: main.clone(), pos: Pos { line, col } });
assert_eq!(classify("src/main.rs:12:5", Some(&here)), loc(12, Some(5)));
assert_eq!(classify("src/main.rs(12,5)", Some(&here)), loc(12, Some(5)));
assert_eq!(classify("Foo.bar(src/main.rs:30)", Some(&here)), loc(30, None));
let url = format!("file:///{}:7:3", main.to_string_lossy().replace('\\', "/").replace(' ', "%20"));
assert_eq!(classify(&url, None), loc(7, Some(3)));
let sub = here.join("src");
assert_eq!(classify("src/main.rs:12:5", Some(&sub)), loc(12, Some(5)));
assert_eq!(classify("src:3", Some(&here)), Some(Target::Path(here.join("src"))));
assert_eq!(classify("src/nope.rs:3:1", Some(&here)), None);
}
#[test]
fn executables_are_revealed_not_run() {
assert!(runs_code(Path::new("C:\\x\\tool.EXE")));
assert!(runs_code(Path::new("setup.ps1")));
assert!(!runs_code(Path::new("notes.md")));
assert!(!runs_code(Path::new("Makefile")));
}
}