Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(desktop-gpui): install the CLI from Settings with the shared cli-install crate

Richie McIlroy88e159d0bd36
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock
index b7e12867d..b9df7cbb9 100644
--- a/apps/desktop-gpui/Cargo.lock
+++ b/apps/desktop-gpui/Cargo.lock
@@ -1494,6 +1494,15 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "cap-cli-install"
+version = "0.1.0"
+dependencies = [
+ "dirs 6.0.0",
+ "serde",
+ "workspace-hack",
+]
+
[[package]]
name = "cap-cursor-capture"
version = "0.1.0"
@@ -1537,6 +1546,7 @@ dependencies = [
"cap-audio",
"cap-camera",
"cap-camera-effects",
+ "cap-cli-install",
"cap-cursor-info",
"cap-editor",
"cap-enc-ffmpeg",
diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml
index be42a9465..f496ed30e 100644
--- a/apps/desktop-gpui/Cargo.toml
+++ b/apps/desktop-gpui/Cargo.toml
@@ -25,6 +25,7 @@ path = "../../crates/recording/examples/studio-finalization-benchmark.rs"
[dependencies]
cap-audio = { path = "../../crates/audio" }
+cap-cli-install = { path = "../../crates/cli-install" }
cap-gpui-kernels = { path = "kernels" }
# gpui — the wingleeio/zed fork Comet ships. The pinned rev carries f596cde
# ("destination alpha on transparent windows: Porter-Duff OVER, not additive"),
diff --git a/apps/desktop-gpui/src/settings_pages.rs b/apps/desktop-gpui/src/settings_pages.rs
index 62b3f926b..c0d5d6bb4 100644
--- a/apps/desktop-gpui/src/settings_pages.rs
+++ b/apps/desktop-gpui/src/settings_pages.rs
@@ -25,6 +25,7 @@ use gpui::{
MouseButton, ParentElement, SharedString, StatefulInteractiveElement, Styled, Window, div,
prelude::FluentBuilder, px, rgb, svg,
};
+use cap_cli_install as cli_install;
use serde::Deserialize;
use serde_json::{Map, Value, json};
@@ -8110,647 +8111,6 @@ async fn http_json(
/// depend on the crate, and the whole point is that `status`/`install`/
/// `uninstall` behave byte-for-byte like the Tauri commands
/// (`src-tauri/src/cli.rs`) so the two apps manage the same shim.
-mod cli_install {
- #[cfg(unix)]
- use std::ffi::OsStr;
- use std::{
- env, fs,
- path::{Path, PathBuf},
- };
-
- const CAP_DIR_NAME: &str = ".cap";
- const BIN_DIR_NAME: &str = "bin";
- const CLI_BINARY_STEM: &str = "cap-cli";
-
- #[cfg(windows)]
- const SHIM_NAME: &str = "cap.cmd";
- #[cfg(not(windows))]
- const SHIM_NAME: &str = "cap";
-
- #[cfg(windows)]
- const CLI_BINARY_NAME: &str = "cap-cli.exe";
- #[cfg(not(windows))]
- const CLI_BINARY_NAME: &str = "cap-cli";
-
- /// `CliInstallStatus`, minus the serde/specta derives the commands need
- /// and minus `install_dir`, which neither cli.tsx nor this page displays
- /// (`path_entry` carries the same string).
- #[derive(Clone, Debug)]
- pub(crate) struct CliInstallStatus {
- pub shim_path: String,
- pub target_path: String,
- pub installed: bool,
- pub on_path: bool,
- pub conflict: Option<String>,
- pub path_entry: String,
- pub shell_command: String,
- pub path_configured: bool,
- }
-
- fn home_dir() -> Result<PathBuf, String> {
- dirs::home_dir().ok_or_else(|| "Could not determine home directory".to_string())
- }
-
- fn install_dir() -> Result<PathBuf, String> {
- let home = home_dir()?;
- let cap_bin = home.join(CAP_DIR_NAME).join(BIN_DIR_NAME);
- let local_bin = home.join(".local/bin");
-
- // Prefer whichever candidate already holds a Cap-managed shim, so
- // status and install agree regardless of the launching PATH.
- if let Ok(target) = target_path() {
- for candidate in [&cap_bin, &local_bin] {
- let shim = candidate.join(SHIM_NAME);
- if shim_points_to(&shim, &target).unwrap_or(false) || shim_is_cap_managed(&shim) {
- return Ok(candidate.clone());
- }
- }
- }
-
- if path_is_present(&cap_bin.join(SHIM_NAME)) || cfg!(windows) {
- return Ok(cap_bin);
- }
-
- if path_contains_install_dir(&local_bin) {
- return Ok(local_bin);
- }
-
- Ok(cap_bin)
- }
-
- fn shim_path() -> Result<PathBuf, String> {
- Ok(install_dir()?.join(SHIM_NAME))
- }
-
- fn target_path() -> Result<PathBuf, String> {
- let exe =
- env::current_exe().map_err(|e| format!("Could not locate Cap executable: {e}"))?;
- let exe = resolve_path_for_target_lookup(exe);
- let dir = exe
- .parent()
- .ok_or_else(|| "Could not locate Cap executable directory".to_string())?;
-
- for candidate in cli_binary_candidates(dir) {
- if candidate.exists() {
- return Ok(resolve_path_for_target_lookup(candidate));
- }
- }
-
- Ok(dir.join(CLI_BINARY_NAME))
- }
-
- #[cfg(windows)]
- fn resolve_path_for_target_lookup(path: PathBuf) -> PathBuf {
- path
- }
-
- #[cfg(not(windows))]
- fn resolve_path_for_target_lookup(path: PathBuf) -> PathBuf {
- fs::canonicalize(&path).unwrap_or(path)
- }
-
- fn cli_binary_candidates(dir: &Path) -> Vec<PathBuf> {
- let mut names = vec![CLI_BINARY_NAME.to_string()];
- if let Some(target_triple) = current_target_triple() {
- names.push(target_specific_cli_binary_name(target_triple));
- }
-
- let dirs = [
- dir.to_path_buf(),
- dir.join("../MacOS"),
- dir.join("../Resources"),
- ];
- let mut candidates = Vec::new();
- for dir in dirs {
- for name in &names {
- candidates.push(dir.join(name));
- }
- }
- candidates
- }
-
- fn target_specific_cli_binary_name(target_triple: &str) -> String {
- format!(
- "{CLI_BINARY_STEM}-{target_triple}{}",
- exe_suffix_for_target(target_triple)
- )
- }
-
- fn exe_suffix_for_target(target_triple: &str) -> &'static str {
- if target_triple.contains("windows") {
- ".exe"
- } else {
- ""
- }
- }
-
- fn current_target_triple() -> Option<&'static str> {
- if cfg!(all(
- target_os = "windows",
- target_arch = "x86_64",
- target_env = "msvc"
- )) {
- Some("x86_64-pc-windows-msvc")
- } else if cfg!(all(
- target_os = "windows",
- target_arch = "aarch64",
- target_env = "msvc"
- )) {
- Some("aarch64-pc-windows-msvc")
- } else if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
- Some("aarch64-apple-darwin")
- } else if cfg!(all(target_os = "macos", target_arch = "x86_64")) {
- Some("x86_64-apple-darwin")
- } else if cfg!(all(target_os = "linux", target_arch = "x86_64")) {
- Some("x86_64-unknown-linux-gnu")
- } else if cfg!(all(target_os = "linux", target_arch = "aarch64")) {
- Some("aarch64-unknown-linux-gnu")
- } else {
- None
- }
- }
-
- #[cfg(unix)]
- fn cli_binary_file_name_is_cap_managed(name: &OsStr) -> bool {
- if name == CLI_BINARY_NAME {
- return true;
- }
-
- let Some(name) = name.to_str() else {
- return false;
- };
-
- current_target_triple().is_some_and(|target_triple| {
- name.eq_ignore_ascii_case(&target_specific_cli_binary_name(target_triple))
- })
- }
-
- fn display_path(path: &Path) -> String {
- path.to_string_lossy().into_owned()
- }
-
- fn path_is_present(path: &Path) -> bool {
- fs::symlink_metadata(path).is_ok()
- }
-
- fn path_contains_install_dir(install_dir: &Path) -> bool {
- let Some(path) = env::var_os("PATH") else {
- return false;
- };
-
- env::split_paths(&path).any(|entry| entry == install_dir)
- }
-
- #[cfg(unix)]
- fn shim_points_to(shim_path: &Path, target_path: &Path) -> Result<bool, String> {
- match fs::read_link(shim_path) {
- Ok(link) => Ok(link == target_path || same_file(&link, target_path)),
- Err(err)
- if matches!(
- err.kind(),
- std::io::ErrorKind::NotFound | std::io::ErrorKind::InvalidInput
- ) =>
- {
- Ok(false)
- }
- Err(err) => Err(format!("Could not read CLI shim: {err}")),
- }
- }
-
- #[cfg(unix)]
- fn same_file(a: &Path, b: &Path) -> bool {
- match (fs::canonicalize(a), fs::canonicalize(b)) {
- (Ok(a), Ok(b)) => a == b,
- _ => false,
- }
- }
-
- #[cfg(windows)]
- fn shim_points_to(shim_path: &Path, target_path: &Path) -> Result<bool, String> {
- let contents = match fs::read(shim_path) {
- Ok(contents) => contents,
- Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(false),
- Err(err) => return Err(format!("Could not read CLI shim: {err}")),
- };
-
- let target = windows_command_path(target_path);
- Ok(windows_shim_target(&contents).is_some_and(|shim_target| {
- windows_shim_target_matches(shim_target, &target, |name| env::var(name).ok())
- }))
- }
-
- #[cfg(unix)]
- fn shim_is_cap_managed(shim_path: &Path) -> bool {
- match fs::read_link(shim_path) {
- Ok(link) => link
- .file_name()
- .is_some_and(cli_binary_file_name_is_cap_managed),
- Err(_) => false,
- }
- }
-
- #[cfg(windows)]
- fn shim_is_cap_managed(shim_path: &Path) -> bool {
- fs::read(shim_path).is_ok_and(|contents| windows_shim_target(&contents).is_some())
- }
-
- #[cfg(windows)]
- fn windows_shim_target(contents: &[u8]) -> Option<&[u8]> {
- let contents = contents.strip_prefix(b"\xef\xbb\xbf").unwrap_or(contents);
- let mut lines = contents.split(|byte| *byte == b'\n');
- if !trim_ascii_whitespace(lines.next()?).eq_ignore_ascii_case(b"@echo off") {
- return None;
- }
-
- let command = trim_ascii_whitespace(lines.next()?);
- if lines.any(|line| !trim_ascii_whitespace(line).is_empty()) {
- return None;
- }
-
- let target = command.strip_prefix(b"\"")?.strip_suffix(b"\" %*")?;
- if windows_cli_binary_file_name_is_cap_managed(windows_path_file_name(target)) {
- Some(target)
- } else {
- None
- }
- }
-
- #[cfg(windows)]
- fn windows_path_file_name(path: &[u8]) -> &[u8] {
- path.rsplit(|byte| *byte == b'\\' || *byte == b'/')
- .next()
- .unwrap_or(path)
- }
-
- #[cfg(windows)]
- fn windows_cli_binary_file_name_is_cap_managed(name: &[u8]) -> bool {
- name.eq_ignore_ascii_case(b"cap-cli.exe")
- || name.eq_ignore_ascii_case(b"cap-cli-x86_64-pc-windows-msvc.exe")
- || name.eq_ignore_ascii_case(b"cap-cli-aarch64-pc-windows-msvc.exe")
- }
-
- #[cfg(windows)]
- fn windows_command_path(path: &Path) -> String {
- let path = display_path(path);
-
- if let Some(rest) = path.strip_prefix("\\\\?\\UNC\\") {
- return format!("\\\\{rest}");
- }
-
- if let Some(rest) = path.strip_prefix("\\\\?\\") {
- return rest.to_string();
- }
-
- path
- }
-
- #[cfg(windows)]
- fn windows_shim_target_matches<F>(shim_target: &[u8], target: &str, env_value: F) -> bool
- where
- F: FnMut(&str) -> Option<String>,
- {
- if shim_target.eq_ignore_ascii_case(target.as_bytes()) {
- return true;
- }
-
- let Ok(shim_target) = std::str::from_utf8(shim_target) else {
- return false;
- };
-
- windows_expand_env_prefix(shim_target, env_value)
- .is_some_and(|expanded| expanded.eq_ignore_ascii_case(target))
- }
-
- #[cfg(windows)]
- fn windows_expand_env_prefix<F>(target: &str, mut env_value: F) -> Option<String>
- where
- F: FnMut(&str) -> Option<String>,
- {
- let rest = target.strip_prefix('%')?;
- let (name, suffix) = rest.split_once('%')?;
- if name.is_empty() {
- return None;
- }
-
- env_value(name).map(|value| format!("{value}{suffix}"))
- }
-
- #[cfg(windows)]
- fn windows_env_prefixed_path<F>(target: &str, mut env_value: F) -> Option<String>
- where
- F: FnMut(&str) -> Option<String>,
- {
- for name in ["LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)"] {
- let Some(value) = env_value(name) else {
- continue;
- };
- let Some(suffix) = strip_ascii_prefix(target, &value) else {
- continue;
- };
- if suffix.is_empty() || suffix.starts_with('\\') || suffix.starts_with('/') {
- return Some(format!("%{name}%{suffix}"));
- }
- }
-
- None
- }
-
- #[cfg(windows)]
- fn strip_ascii_prefix<'a>(value: &'a str, prefix: &str) -> Option<&'a str> {
- let head = value.get(..prefix.len())?;
- let tail = value.get(prefix.len()..)?;
- head.eq_ignore_ascii_case(prefix).then_some(tail)
- }
-
- #[cfg(windows)]
- fn trim_ascii_whitespace(mut value: &[u8]) -> &[u8] {
- while value.first().is_some_and(|byte| byte.is_ascii_whitespace()) {
- value = &value[1..];
- }
-
- while value.last().is_some_and(|byte| byte.is_ascii_whitespace()) {
- value = &value[..value.len() - 1];
- }
-
- value
- }
-
- fn shell_command(install_dir: &Path) -> String {
- let install_dir = display_path(install_dir);
-
- if cfg!(windows) {
- let install_dir = install_dir.replace('\'', "''");
- format!(
- r#"powershell -NoProfile -Command "[Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path', 'User') + ';{install_dir}', 'User')""#
- )
- } else {
- format!(r#"export PATH="{install_dir}:$PATH""#)
- }
- }
-
- pub(crate) fn status() -> Result<CliInstallStatus, String> {
- let install_dir = install_dir()?;
- let shim_path = shim_path()?;
- let target_path = target_path()?;
- let target_exists = target_path.exists();
- let shim_exists = path_is_present(&shim_path);
- let installed = target_exists && shim_points_to(&shim_path, &target_path)?;
- let conflict = if shim_exists && !installed && !shim_is_cap_managed(&shim_path) {
- Some(format!(
- "{} already exists and is not managed by Cap",
- display_path(&shim_path)
- ))
- } else if !target_exists {
- Some(format!(
- "Bundled CLI binary not found at {}",
- display_path(&target_path)
- ))
- } else {
- None
- };
-
- let on_path = path_contains_install_dir(&install_dir);
-
- Ok(CliInstallStatus {
- shim_path: display_path(&shim_path),
- target_path: display_path(&target_path),
- installed,
- on_path,
- conflict,
- path_entry: display_path(&install_dir),
- shell_command: shell_command(&install_dir),
- path_configured: path_persisted(&install_dir, on_path),
- })
- }
-
- #[cfg(unix)]
- fn write_shim(shim_path: &Path, target_path: &Path) -> Result<(), String> {
- std::os::unix::fs::symlink(target_path, shim_path)
- .map_err(|e| format!("Could not create CLI symlink: {e}"))
- }
-
- #[cfg(windows)]
- fn write_shim(shim_path: &Path, target_path: &Path) -> Result<(), String> {
- let target = windows_command_path(target_path);
- let target =
- windows_env_prefixed_path(&target, |name| env::var(name).ok()).unwrap_or(target);
- let contents = format!(
- r#"@echo off
-"{target}" %*
-"#
- );
- fs::write(shim_path, contents).map_err(|e| format!("Could not write CLI shim: {e}"))
- }
-
- pub(crate) fn install() -> Result<CliInstallStatus, String> {
- let install_dir = install_dir()?;
- let shim_path = shim_path()?;
- let target_path = target_path()?;
-
- if !target_path.exists() {
- return Err(format!(
- "Bundled CLI binary not found at {}",
- display_path(&target_path)
- ));
- }
-
- fs::create_dir_all(&install_dir)
- .map_err(|e| format!("Could not create CLI directory: {e}"))?;
-
- if path_is_present(&shim_path) {
- // Repoint our own shim and any other Cap-managed one; only refuse
- // to clobber a genuinely foreign file.
- if !shim_points_to(&shim_path, &target_path)? && !shim_is_cap_managed(&shim_path) {
- return Err(format!(
- "{} already exists and is not managed by Cap",
- display_path(&shim_path)
- ));
- }
-
- match fs::remove_file(&shim_path) {
- Ok(()) => {}
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
- Err(e) => return Err(format!("Could not replace CLI shim: {e}")),
- }
- }
-
- write_shim(&shim_path, &target_path)?;
-
- let mut status = status()?;
- if !status.on_path && ensure_path_persisted(&install_dir) {
- status.path_configured = true;
- }
- Ok(status)
- }
-
- #[cfg(unix)]
- fn ensure_path_persisted(install_dir: &Path) -> bool {
- if env::var_os("CAP_NO_MODIFY_PATH").is_some() {
- return false;
- }
- let Some(home) = dirs::home_dir() else {
- return false;
- };
- let needle = display_path(install_dir);
- if profile_mentions_dir(&home, &needle) {
- return true;
- }
- let shell = env::var("SHELL").unwrap_or_default();
- let shell_name = Path::new(&shell)
- .file_name()
- .and_then(|name| name.to_str())
- .unwrap_or("");
- append_path_export(&shell_profile(&home, shell_name), &needle)
- }
-
- #[cfg(windows)]
- fn ensure_path_persisted(install_dir: &Path) -> bool {
- if env::var_os("CAP_NO_MODIFY_PATH").is_some() {
- return false;
- }
- let dir = display_path(install_dir).replace('\'', "''");
- let script = format!(
- "$d = '{dir}'; \
- $u = [Environment]::GetEnvironmentVariable('Path', 'User'); \
- $e = if ($u) {{ $u -split ';' }} else {{ @() }}; \
- if ($e -notcontains $d) {{ \
- $n = if ($u) {{ \"$d;$u\" }} else {{ $d }}; \
- [Environment]::SetEnvironmentVariable('Path', $n, 'User') }}"
- );
- let mut command = powershell_command();
- command
- .args(["-NoProfile", "-NonInteractive", "-Command", &script])
- .status()
- .map(|status| status.success())
- .unwrap_or(false)
- }
-
- #[cfg(unix)]
- fn path_persisted(install_dir: &Path, on_path: bool) -> bool {
- on_path
- || dirs::home_dir()
- .is_some_and(|home| profile_mentions_dir(&home, &display_path(install_dir)))
- }
-
- #[cfg(windows)]
- fn path_persisted(install_dir: &Path, on_path: bool) -> bool {
- on_path || windows_user_path_contains(install_dir)
- }
-
- #[cfg(windows)]
- fn windows_user_path_contains(install_dir: &Path) -> bool {
- let mut command = powershell_command();
- let Ok(output) = command
- .args([
- "-NoProfile",
- "-NonInteractive",
- "-Command",
- "[Environment]::GetEnvironmentVariable('Path', 'User')",
- ])
- .output()
- else {
- return false;
- };
- if !output.status.success() {
- return false;
- }
- let needle = display_path(install_dir);
- let needle = needle.trim();
- String::from_utf8_lossy(&output.stdout)
- .split(';')
- .any(|entry| entry.trim().eq_ignore_ascii_case(needle))
- }
-
- #[cfg(windows)]
- fn powershell_command() -> std::process::Command {
- use std::os::windows::process::CommandExt;
-
- const CREATE_NO_WINDOW: u32 = 0x0800_0000;
-
- let mut command = std::process::Command::new("powershell");
- command.creation_flags(CREATE_NO_WINDOW);
- command
- }
-
- #[cfg(unix)]
- fn shell_profile(home: &Path, shell_name: &str) -> PathBuf {
- match shell_name {
- "zsh" => home.join(".zshrc"),
- "bash" => home.join(".bashrc"),
- "" if home.join(".zshrc").exists() => home.join(".zshrc"),
- _ => home.join(".profile"),
- }
- }
-
- #[cfg(unix)]
- fn profile_mentions_dir(home: &Path, needle: &str) -> bool {
- [".zshrc", ".bashrc", ".bash_profile", ".profile"]
- .iter()
- .any(|file| fs::read_to_string(home.join(file)).is_ok_and(|c| c.contains(needle)))
- }
-
- #[cfg(unix)]
- fn append_path_export(profile: &Path, install_dir: &str) -> bool {
- use std::io::Write;
- let line = format!("export PATH=\"{install_dir}:$PATH\"");
- fs::OpenOptions::new()
- .create(true)
- .append(true)
- .open(profile)
- .and_then(|mut file| writeln!(file, "\n# Added by Cap\n{line}"))
- .is_ok()
- }
-
- pub(crate) fn uninstall() -> Result<CliInstallStatus, String> {
- let shim_path = shim_path()?;
- let target_path = target_path()?;
-
- if shim_points_to(&shim_path, &target_path)? {
- fs::remove_file(&shim_path).map_err(|e| format!("Could not remove CLI shim: {e}"))?;
- }
-
- status()
- }
-
- #[cfg(all(test, unix))]
- mod tests {
- use super::*;
-
- #[test]
- fn shell_profile_selection() {
- let home = Path::new("/home/u");
- assert_eq!(shell_profile(home, "zsh"), home.join(".zshrc"));
- assert_eq!(shell_profile(home, "bash"), home.join(".bashrc"));
- assert_eq!(shell_profile(home, "fish"), home.join(".profile"));
- }
-
- #[test]
- fn cap_managed_shim_detection() {
- let dir =
- std::env::temp_dir().join(format!("cap-gpui-cli-test-{}", std::process::id()));
- let _ = fs::remove_dir_all(&dir);
- fs::create_dir_all(&dir).unwrap();
- let shim = dir.join(SHIM_NAME);
-
- // A symlink to a cap-cli binary is Cap-managed even when it points
- // at a different install (the target need not exist).
- std::os::unix::fs::symlink("/elsewhere/Cap.app/Contents/MacOS/cap-cli", &shim).unwrap();
- assert!(shim_is_cap_managed(&shim));
-
- // A symlink to anything else is not.
- fs::remove_file(&shim).unwrap();
- std::os::unix::fs::symlink("/bin/ls", &shim).unwrap();
- assert!(!shim_is_cap_managed(&shim));
-
- // Nor is a regular file, so install refuses to clobber it.
- fs::remove_file(&shim).unwrap();
- fs::write(&shim, b"#!/bin/sh\n").unwrap();
- assert!(!shim_is_cap_managed(&shim));
-
- let _ = fs::remove_dir_all(&dir);
- }
- }
-}
// ---------------------------------------------------------------------------
// Tests