feat: add si command line interface #37

Merged
reya merged 7 commits from feat/cli into master 2026-11-30 00:34:45 +00:00
7 changed files with 242 additions and 20 deletions
Showing only changes of commit df1f232aae - Show all commits
+2
View File
@@ -5,6 +5,7 @@
### Added
- Add a `si` command line interface that opens the desktop app and clones, publishes, syncs and deletes repositories with the app's identity, data and keychain, without the app running
- Install the `si` command from Settings, which links the binary built next to the app into a folder on your PATH
- Add a confirmation dialog before deleting a repository
- Browse the files of a commit as of that commit from the Commits list, the short id on a row shows the commit's files in place of the worktree and the branch selector shows the commit until a branch or tag is picked again
@@ -28,6 +29,7 @@
### Fixed
- Fix a long description in Settings pushing its control past the dialog's edge, the description now wraps inside the row
- Fix the status badge on issue and pull request rows sitting below the title instead of centered with it
- Fix opening a local repository or switching its branch discarding uncommitted changes, a checkout now refuses to overwrite uncommitted edits or untracked files and leaves the branch untouched when it fails
- Fix viewing a commit diff crashing when the repository configures an external diff driver
Generated
+1
View File
@@ -7230,6 +7230,7 @@ dependencies = [
"signed_git",
"signed_nostr",
"signed_state",
"tempfile",
"ui",
"utils",
]
+4 -11
View File
@@ -132,17 +132,8 @@ async fn run(command: Command, cx: &mut AsyncApp) -> anyhow::Result<()> {
/// Launches the desktop app: the `signed` binary built next to this one, else the installed app.
fn open_desktop() -> anyhow::Result<()> {
let exe = std::env::current_exe().context("failed to locate this executable")?;
let extension = std::env::consts::EXE_EXTENSION;
let sibling = if extension.is_empty() {
exe.with_file_name("signed")
} else {
exe.with_file_name(format!("signed.{extension}"))
};
if sibling.is_file() {
std::process::Command::new(&sibling)
if let Some(desktop) = paths::sibling_binary("signed") {
std::process::Command::new(desktop)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
@@ -165,6 +156,8 @@ fn open_desktop() -> anyhow::Result<()> {
return Ok(());
}
let exe = std::env::current_exe().context("failed to locate this executable")?;
bail!(
"the desktop app was not found next to {}; run `cargo run -p signed` instead",
exe.display()
+16
View File
@@ -73,6 +73,22 @@ pub fn documents_dir() -> PathBuf {
dirs::document_dir().unwrap_or_else(|| dirs::home_dir().unwrap_or_default())
}
/// The binary named `name` built next to the running executable, when it is there.
pub fn sibling_binary(name: &str) -> Option<PathBuf> {
let name = if std::env::consts::EXE_EXTENSION.is_empty() {
name.to_owned()
} else {
format!("{name}.{}", std::env::consts::EXE_EXTENSION)
};
let binary = std::env::current_exe().ok()?.with_file_name(name);
binary.is_file().then_some(binary)
}
/// Returns the user's binary folder, `~/.local/bin`, which most shells put on the PATH.
pub fn user_bin_dir() -> PathBuf {
home_dir().join(".local").join("bin")
}
fn config_dir() -> &'static Path {
CONFIG_DIR.as_path()
}
+1
View File
@@ -23,6 +23,7 @@ log.workspace = true
[dev-dependencies]
gpui = { workspace = true, features = ["test-support"] }
tempfile = "3"
[lints]
workspace = true
+187 -2
View File
@@ -1,5 +1,7 @@
use std::path::PathBuf;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use anyhow::Context as _;
use gpui::{
AnyElement, App, AppContext as _, Div, ElementId, Entity, IntoElement, ParentElement as _,
PathPromptOptions, SharedString, Styled as _, WeakEntity, Window, div, px,
@@ -9,12 +11,18 @@ use ui::button::{Button, ButtonVariant};
use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::layout::root::RootContext as _;
use ui::select::{Select, SelectOption};
use ui::theme::ActiveTheme as _;
use ui::toast::Toast;
use ui::tooltip::Tooltip;
use crate::settings::{PathRow, ServerRow, SettingsDialog};
use crate::shared::labels::ServerInputExt as _;
use crate::shared::log_dropped;
/// The name of the command line tool's binary.
const CLI_NAME: &str = "si";
/// The title and description a settings row or block opens with.
fn setting_header(
@@ -44,7 +52,7 @@ pub fn setting_row(
.w_full()
.justify_between()
.gap_4()
.child(setting_header(cx, title, description))
.child(setting_header(cx, title, description).flex_1().min_w_0())
.child(div().w(px(200.)).flex_shrink_0().child(control))
.into_any_element()
}
@@ -373,3 +381,180 @@ fn choose_default_folder(
})
.ok();
}
/// Where the `si` command is installed.
#[derive(Clone, PartialEq, Debug)]
pub(crate) enum CliInstall {
/// The app was built without the `si` binary next to it.
Missing,
NotInstalled,
Installed(PathBuf),
}
/// The folders `si` is installed into in order of preference, the first one that accepts it.
fn cli_install_dirs() -> Vec<PathBuf> {
if let Some(local) = std::env::var_os("LOCALAPPDATA") {
// Windows puts this per-user folder on the PATH.
return vec![PathBuf::from(local).join("Microsoft").join("WindowsApps")];
}
vec![PathBuf::from("/usr/local/bin"), paths::user_bin_dir()]
}
/// Where the `si` command built with this app is installed.
pub(crate) fn current_cli_install() -> CliInstall {
cli_install(
paths::sibling_binary(CLI_NAME).as_deref(),
&cli_install_dirs(),
)
}
/// Whether `binary` is installed, given the folders it may live in.
pub(crate) fn cli_install(binary: Option<&Path>, dirs: &[PathBuf]) -> CliInstall {
let Some(binary) = binary else {
return CliInstall::Missing;
};
let Some(name) = binary.file_name() else {
return CliInstall::NotInstalled;
};
for dir in dirs {
let link = dir.join(name);
if is_cli_link(&link, binary) {
return CliInstall::Installed(link);
}
}
CliInstall::NotInstalled
}
/// Whether `link` is this app's installed `binary`.
fn is_cli_link(link: &Path, binary: &Path) -> bool {
#[cfg(windows)]
{
link.is_file()
}
#[cfg(not(windows))]
{
std::fs::read_link(link).is_ok_and(|target| target == binary)
}
}
/// Installs `binary` into the first folder of `dirs` that accepts it, returning the installed path.
pub(crate) fn install_cli_binary(binary: &Path, dirs: &[PathBuf]) -> anyhow::Result<PathBuf> {
let mut failure = None;
for dir in dirs {
match install_into(binary, dir) {
Ok(link) => return Ok(link),
Err(error) if error.kind() == ErrorKind::AlreadyExists => return Err(error.into()),
Err(error) => failure = Some(error),
}
}
let failure =
failure.unwrap_or_else(|| std::io::Error::other("there is no folder to install into"));
Err(failure.into())
}
/// Links `binary` into `dir`, creating the folder when it does not exist yet.
fn install_into(binary: &Path, dir: &Path) -> std::io::Result<PathBuf> {
let name = binary
.file_name()
.ok_or_else(|| std::io::Error::new(ErrorKind::InvalidInput, "the binary has no name"))?;
let link = dir.join(name);
if let Err(error) = replace_link(binary, &link) {
if error.kind() != ErrorKind::NotFound {
return Err(error);
}
std::fs::create_dir_all(dir)?;
replace_link(binary, &link)?;
}
Ok(link)
}
/// Points `link` at `binary`, replacing a previous install and leaving any other file untouched.
fn replace_link(binary: &Path, link: &Path) -> std::io::Result<()> {
if let Ok(metadata) = link.symlink_metadata() {
// A previous install is a symlink, or a copy on Windows.
if metadata.file_type().is_symlink() || cfg!(windows) {
std::fs::remove_file(link)?;
} else {
return Err(std::io::Error::new(
ErrorKind::AlreadyExists,
format!("{} already exists and was left untouched", link.display()),
));
}
}
#[cfg(windows)]
{
std::fs::copy(binary, link)?;
}
#[cfg(not(windows))]
{
std::os::unix::fs::symlink(binary, link)?;
}
Ok(())
}
/// The description of the command line tool row for the current install state.
pub(crate) fn cli_description(cli: &CliInstall) -> SharedString {
match cli {
CliInstall::Missing => {
"The `si` binary was not found next to the app, so there is nothing to install.".into()
}
CliInstall::NotInstalled => {
"Install the `si` command to manage repositories from a terminal.".into()
}
CliInstall::Installed(link) => format!(
"`si` is installed at {}. Its folder must be on your PATH.",
link.display()
)
.into(),
}
}
/// The button of the command line tool row.
pub(crate) fn install_cli_button(this: &WeakEntity<SettingsDialog>, cli: &CliInstall) -> Button {
let label = match cli {
CliInstall::Installed(_) => "Reinstall",
_ => "Install",
};
Button::new("settings-install-cli")
.label(label)
.w_full()
.disabled(matches!(cli, CliInstall::Missing))
.on_click({
let this = this.clone();
move |_, _, cx| install_cli(&this, cx)
})
}
fn install_cli(this: &WeakEntity<SettingsDialog>, cx: &mut App) {
let installed = paths::sibling_binary(CLI_NAME)
.with_context(|| "the `si` binary was not found next to the app")
.and_then(|binary| install_cli_binary(&binary, &cli_install_dirs()));
log_dropped(this.update(cx, |dialog, cx| {
dialog.refresh_cli();
if let Err(error) = &installed {
cx.toast(
Toast::new(format!("Failed to install `si`: {error:#}")).icon(IconRole::Warning),
);
}
cx.notify();
}));
}
+31 -7
View File
@@ -8,8 +8,9 @@ use gpui::{
SharedString, Styled as _, Subscription, Task, Window, px,
};
use helpers::{
appearance_select, default_folder_selector, event_fetching_select, grasp_servers_editor,
scan_paths_editor, setting_block, setting_row,
CliInstall, appearance_select, cli_description, current_cli_install, default_folder_selector,
event_fetching_select, grasp_servers_editor, install_cli_button, scan_paths_editor,
setting_block, setting_row,
};
use settings::SettingsStore;
use ui::alert::{Alert, AlertSeverity};
@@ -19,6 +20,7 @@ use ui::input::InputState;
use ui::separator::Separator;
use crate::shared::labels::{RelayHostExt as _, ServerInputExt as _};
use crate::shared::log_dropped;
/// One grasp server row, with its display strings built when settings change.
#[derive(Clone)]
@@ -46,6 +48,8 @@ pub struct SettingsDialog {
servers: Vec<ServerRow>,
/// Scan path rows, rebuilt when the settings change.
scan_paths: Vec<PathRow>,
/// Where the `si` command is installed.
cli: CliInstall,
/// Prompts this dialog started, cancelled when it drops.
tasks: Vec<Task<()>>,
/// Rebuilds the rows when the settings change.
@@ -69,18 +73,25 @@ impl SettingsDialog {
.read_only()
.build(cx);
let dialog = cx.new(|cx| {
let mut dialog = Self {
let dialog = cx.new(|cx: &mut Context<Self>| {
let weak = cx.weak_entity();
cx.defer(move |cx| {
log_dropped(weak.update(cx, |dialog, cx| {
dialog.rebuild_rows(cx);
dialog.refresh_cli();
}));
});
Self {
handle: DialogHandle::new(true),
grasp_input,
default_folder,
servers: Vec::new(),
scan_paths: Vec::new(),
cli: CliInstall::Missing,
tasks: Vec::new(),
_subscription: None,
};
dialog.rebuild_rows(cx);
dialog
}
});
dialog.update(cx, |dialog, cx| {
@@ -129,6 +140,11 @@ impl SettingsDialog {
})
.collect();
}
/// Looks up where the `si` command is installed.
fn refresh_cli(&mut self) {
self.cli = current_cli_install();
}
}
impl Render for SettingsDialog {
@@ -145,6 +161,7 @@ impl Render for SettingsDialog {
let default_folder = self.default_folder.clone();
let servers = self.servers.clone();
let scan_paths = self.scan_paths.clone();
let cli = self.cli.clone();
let this = cx.weak_entity();
Dialog::new("settings-dialog")
@@ -200,6 +217,13 @@ impl Render for SettingsDialog {
FOLDER_DESC,
default_folder_selector(&default_folder, &this),
))
.child(Separator::horizontal())
.child(setting_row(
cx,
"Command Line Tool",
cli_description(&cli),
install_cli_button(&this, &cli),
))
.into_any_element()
})
}