|
| 1 | +use std::env; |
| 2 | +use std::fs; |
| 3 | +use std::io::ErrorKind; |
| 4 | +use std::io::Write; |
| 5 | +use std::path::Path; |
| 6 | +use std::path::PathBuf; |
| 7 | + |
| 8 | +use anyhow::Context; |
| 9 | +use anyhow::Result; |
| 10 | +use anyhow::bail; |
| 11 | +use clap_complete::Shell; |
| 12 | + |
| 13 | +const BEGIN: &str = "# >>> filetrail completions >>>"; |
| 14 | +const END: &str = "# <<< filetrail completions <<<"; |
| 15 | + |
| 16 | +/// Install startup hooks without requiring an initialized repository or data directory. |
| 17 | +/// Hooks ask the installed binary for current definitions, so upgrades need no regeneration. |
| 18 | +pub fn install(shell: Shell, binary: &Path) -> Result<Vec<PathBuf>> { |
| 19 | + let hook = hook(shell, binary)?; |
| 20 | + let home = dirs::home_dir().context("cannot determine home directory")?; |
| 21 | + let paths = match shell { |
| 22 | + Shell::Bash => { |
| 23 | + // Bash reads .bashrc for interactive shells and the first available |
| 24 | + // login profile for login shells (including macOS Terminal). |
| 25 | + let mut login = home.join(".bash_profile"); |
| 26 | + for name in [".bash_profile", ".bash_login", ".profile"] { |
| 27 | + let candidate = home.join(name); |
| 28 | + match fs::symlink_metadata(&candidate) { |
| 29 | + Ok(_) => { |
| 30 | + login = candidate; |
| 31 | + break; |
| 32 | + } |
| 33 | + Err(error) if error.kind() == ErrorKind::NotFound => {} |
| 34 | + Err(error) => return Err(error.into()), |
| 35 | + } |
| 36 | + } |
| 37 | + vec![home.join(".bashrc"), login] |
| 38 | + } |
| 39 | + Shell::Zsh => vec![environment_directory("ZDOTDIR", &home).join(".zshrc")], |
| 40 | + Shell::Fish => vec![ |
| 41 | + environment_directory("XDG_CONFIG_HOME", &home.join(".config")) |
| 42 | + .join("fish/completions/filetrail.fish"), |
| 43 | + ], |
| 44 | + _ => bail!("automatic installation supports bash, zsh, and fish only"), |
| 45 | + }; |
| 46 | + |
| 47 | + // Validate every file before writing any of them. Resolve existing symlinks |
| 48 | + // so common dotfile setups retain both their symlinks and file permissions. |
| 49 | + let updates = paths |
| 50 | + .iter() |
| 51 | + .map(|path| prepare_update(path, &hook)) |
| 52 | + .collect::<Result<Vec<_>>>()?; |
| 53 | + for (path, content, permissions) in updates { |
| 54 | + let parent = path |
| 55 | + .parent() |
| 56 | + .context("missing shell configuration parent")?; |
| 57 | + fs::create_dir_all(parent)?; |
| 58 | + let mut file = tempfile::NamedTempFile::new_in(parent)?; |
| 59 | + file.write_all(content.as_bytes())?; |
| 60 | + if let Some(permissions) = permissions { |
| 61 | + file.as_file().set_permissions(permissions)?; |
| 62 | + } |
| 63 | + file.as_file().sync_all()?; |
| 64 | + file.persist(&path) |
| 65 | + .with_context(|| format!("cannot update {}", path.display()))?; |
| 66 | + } |
| 67 | + Ok(paths) |
| 68 | +} |
| 69 | + |
| 70 | +fn environment_directory(name: &str, fallback: &Path) -> PathBuf { |
| 71 | + env::var_os(name) |
| 72 | + .filter(|value| !value.is_empty()) |
| 73 | + .map(PathBuf::from) |
| 74 | + .unwrap_or_else(|| fallback.to_owned()) |
| 75 | +} |
| 76 | + |
| 77 | +fn hook(shell: Shell, binary: &Path) -> Result<String> { |
| 78 | + let binary = binary |
| 79 | + .to_str() |
| 80 | + .context("executable path must be valid UTF-8")?; |
| 81 | + let quoted = match shell { |
| 82 | + Shell::Fish => format!("'{}'", binary.replace('\\', "\\\\").replace('\'', "\\'")), |
| 83 | + _ => format!("'{}'", binary.replace('\'', "'\\''")), |
| 84 | + }; |
| 85 | + let body = match shell { |
| 86 | + Shell::Bash => format!( |
| 87 | + "if [ -n \"${{BASH_VERSION-}}\" ] && [ -x {quoted} ]; then\n\ |
| 88 | + case $- in\n\ |
| 89 | + *i*) eval \"$({quoted} completions bash)\" ;;\n\ |
| 90 | + esac\n\ |
| 91 | + fi\n" |
| 92 | + ), |
| 93 | + Shell::Zsh => format!( |
| 94 | + "if [[ -o interactive && -x {quoted} ]]; then\n\ |
| 95 | + if (( ! $+functions[compdef] )); then\n\ |
| 96 | + autoload -Uz compinit\n\ |
| 97 | + compinit\n\ |
| 98 | + fi\n\ |
| 99 | + eval \"$({quoted} completions zsh)\"\n\ |
| 100 | + fi\n" |
| 101 | + ), |
| 102 | + Shell::Fish => format!( |
| 103 | + "if test -x {quoted}\n\ |
| 104 | + {quoted} completions fish | source\n\ |
| 105 | + end\n" |
| 106 | + ), |
| 107 | + _ => bail!("automatic installation supports bash, zsh, and fish only"), |
| 108 | + }; |
| 109 | + Ok(format!("{BEGIN}\n{body}{END}\n")) |
| 110 | +} |
| 111 | + |
| 112 | +fn prepare_update(path: &Path, hook: &str) -> Result<(PathBuf, String, Option<fs::Permissions>)> { |
| 113 | + let (path, original, permissions) = match fs::symlink_metadata(path) { |
| 114 | + Ok(_) => { |
| 115 | + let resolved = fs::canonicalize(path) |
| 116 | + .with_context(|| format!("cannot resolve {}", path.display()))?; |
| 117 | + let metadata = fs::metadata(&resolved)?; |
| 118 | + if !metadata.is_file() { |
| 119 | + bail!("{} is not a regular file", path.display()); |
| 120 | + } |
| 121 | + let content = fs::read_to_string(&resolved) |
| 122 | + .with_context(|| format!("cannot read {}", path.display()))?; |
| 123 | + (resolved, content, Some(metadata.permissions())) |
| 124 | + } |
| 125 | + Err(error) if error.kind() == ErrorKind::NotFound => (path.to_owned(), String::new(), None), |
| 126 | + Err(error) => return Err(error.into()), |
| 127 | + }; |
| 128 | + let updated = replace_hook(&original, hook) |
| 129 | + .with_context(|| format!("invalid FileTrail completion block in {}", path.display()))?; |
| 130 | + Ok((path, updated, permissions)) |
| 131 | +} |
| 132 | + |
| 133 | +fn replace_hook(original: &str, hook: &str) -> Result<String> { |
| 134 | + let mut begin = None; |
| 135 | + let mut end = None; |
| 136 | + let mut offset = 0; |
| 137 | + for line in original.split_inclusive('\n') { |
| 138 | + match line.trim_end_matches(['\r', '\n']) { |
| 139 | + BEGIN if begin.is_none() && end.is_none() => begin = Some(offset), |
| 140 | + END if begin.is_some() && end.is_none() => end = Some(offset + line.len()), |
| 141 | + BEGIN | END => { |
| 142 | + bail!("duplicate or out-of-order markers; repair the marked block first") |
| 143 | + } |
| 144 | + _ => {} |
| 145 | + } |
| 146 | + offset += line.len(); |
| 147 | + } |
| 148 | + match (begin, end) { |
| 149 | + (Some(begin), Some(end)) => Ok(format!("{}{hook}{}", &original[..begin], &original[end..])), |
| 150 | + (None, None) => { |
| 151 | + let separator = if original.is_empty() || original.ends_with('\n') { |
| 152 | + "" |
| 153 | + } else { |
| 154 | + "\n" |
| 155 | + }; |
| 156 | + Ok(format!("{original}{separator}{hook}")) |
| 157 | + } |
| 158 | + _ => bail!("incomplete markers; repair the marked block first"), |
| 159 | + } |
| 160 | +} |
| 161 | + |
| 162 | +#[cfg(test)] |
| 163 | +mod tests { |
| 164 | + use super::BEGIN; |
| 165 | + use super::END; |
| 166 | + use super::replace_hook; |
| 167 | + |
| 168 | + #[test] |
| 169 | + fn replaces_only_its_own_block_and_preserves_surrounding_content() { |
| 170 | + let hook = format!("{BEGIN}\nnew\n{END}\n"); |
| 171 | + let original = format!("before\n{BEGIN}\nold\n{END}\nafter\n"); |
| 172 | + let updated = replace_hook(&original, &hook).unwrap(); |
| 173 | + assert_eq!(updated, format!("before\n{hook}after\n")); |
| 174 | + assert_eq!(replace_hook(&updated, &hook).unwrap(), updated); |
| 175 | + assert_eq!( |
| 176 | + replace_hook("no newline", &hook).unwrap(), |
| 177 | + format!("no newline\n{hook}") |
| 178 | + ); |
| 179 | + for broken in [ |
| 180 | + format!("{BEGIN}\n"), |
| 181 | + format!("{END}\n"), |
| 182 | + format!("{hook}{hook}"), |
| 183 | + ] { |
| 184 | + assert!(replace_hook(&broken, &hook).is_err()); |
| 185 | + } |
| 186 | + } |
| 187 | +} |
0 commit comments