Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/but/src/args/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub enum CommandName {
Rub,
Diff,
Edit,
Open,
Show,
Commit,
CommitEmpty,
Expand Down
18 changes: 18 additions & 0 deletions crates/but/src/args/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,24 @@ pub enum Subcommands {
file: String,
},

/// Open a file with uncommitted changes in the workspace using your configured editor.
///
/// This is a shorthand command to be able to open a file in the workspace using a CLI ID. The
/// primary use case is to run `but status` followed by `but open <id>` using one of the IDs
/// emitted by `status`.
///
/// ## Examples
///
/// ```text
/// but open nt
/// ```
///
#[clap(verbatim_doc_comment)]
Open {
/// The CLI ID of the entity to open in your editor
target: String,
},

/// Shows detailed information about a commit or branch.
///
/// When given a commit ID, displays the full commit message, author information,
Expand Down
1 change: 1 addition & 0 deletions crates/but/src/command/legacy/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub mod mark;
pub mod mcp;
pub mod mcp_internal;
pub mod merge;
pub mod open;
pub mod oplog;
pub mod pick;
pub mod pull;
Expand Down
33 changes: 33 additions & 0 deletions crates/but/src/command/legacy/open.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use anyhow::{Result, bail};
use but_ctx::Context;

use crate::{CliId, IdMap, tui::get_text};

pub(crate) fn open_target(ctx: &mut Context, target: &str) -> Result<()> {
let id_map = IdMap::new_from_context(ctx, None)?;
let cli_ids = id_map.parse_using_context(target, ctx)?;
if cli_ids.is_empty() {
bail!("ID '{target}' not found")
}

if cli_ids.len() > 1 {
bail!(
"ID '{target}' is ambiguous. Found {} matches",
cli_ids.len()
)
}

let cli_id = &cli_ids[0];

match cli_id {
CliId::Uncommitted(uncommitted_id) => {
if !uncommitted_id.is_entire_file {
bail!("Cannot open part of file")
}

let path = &uncommitted_id.hunk_assignments.head.path;
get_text::launch_editor(path.as_ref())
}
_ => bail!("Can only open uncommitted files"),
}
}
11 changes: 11 additions & 0 deletions crates/but/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,17 @@ async fn match_subcommand(
Ok(())
}
Subcommands::Gui => command::gui::open(&args.current_dir).emit_metrics(metrics_ctx),
Subcommands::Open { target } => {
let mut ctx = setup::init_ctx(
&args,
InitCtxOptions {
background_sync: BackgroundSync::Enabled,
..Default::default()
},
out,
)?;
command::legacy::open::open_target(&mut ctx, target.as_ref()).emit_metrics(metrics_ctx)
}
Subcommands::Completions { shell } => {
command::completions::generate_completions(shell).emit_metrics(metrics_ctx)
}
Expand Down
37 changes: 31 additions & 6 deletions crates/but/src/tui/get_text.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,26 @@
//! Various functions that involve launching the Git editor (i.e. `GIT_EDITOR`).
//!
//! When no external editor is configured, falls back to the built-in TUI editor.
use std::ffi::OsStr;
use std::{ffi::OsStr, path::Path};

use anyhow::{Result, bail};
use bstr::{BStr, BString, ByteSlice};

/// Opens the provided filepath in the user's preferred editor.
///
/// # Note
///
/// The user-configured editor command is allowed to be a shell expression (e.g. `"code --wait"`),
/// and is therefore executed within a shell. As such, the path passed into this function **must be
/// safe to use in a shell context**. Never pass in user-supplied strings that have not been
/// verified to point to a file that `but` is supposed to be allowed to open.
pub fn launch_editor(path: &Path) -> Result<()> {
match get_editor_command() {
Some(editor_cmd) => launch_external_editor(&editor_cmd, path),
None => bail!("Built-in editor not yet supported"),
}
}

/// Launches the user's preferred text editor to edit some `initial_text`,
/// identified by a `filename_safe_intent` to help the user understand what's wanted of them.
/// Note that this string must be valid in filenames.
Expand Down Expand Up @@ -68,20 +83,30 @@ fn from_external_editor(
.tempfile()?;
std::fs::write(&tempfile, initial_text)?;

// The editor command is allowed to be a shell expression, e.g. "code --wait" is somewhat common.
// We need to execute within a shell to make sure we don't get "No such file or directory" errors.
launch_external_editor(editor_cmd, tempfile.path())?;
Ok(std::fs::read(&tempfile)?.into())
}

/// Launch an external editor.
///
/// # Note
///
/// The editor command is allowed to be a shell expression (e.g. `"code --wait"`),
/// so it is executed within a shell to avoid "No such file or directory" errors.
fn launch_external_editor(editor_cmd: &str, path_safe_intent: &Path) -> Result<(), anyhow::Error> {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since path_safe_intent is so special, could it be explained in the doc string? Also, I am trying to establish a pattern where every parameter is named in the doc-string, so The editor command would probably be ``editor_cmd is….

Copy link
Contributor Author

@slarse slarse Mar 10, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't thoroughly gone through the code yet so docs are not entirely accurate.

But this highlights something important that I've been thinking about: the path passed in here is not safe. It's an arbitrary path from the repository. It could be a file called $(rm dad-jokes.md) for example. Very much not a safe path, the intent is entirely unknown, and I've been trying to inject badness here but without success.

From what I can tell in gix, any single added .arg() is passed separately to to exec, so it seems fine?

I'll address the docs before trying to get this merged, just want a sanity check on using a potentially unsafe path as input here.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe this tells us that we'd want to have a path which proves that a path is inside the worktree (and probably not inside .git).

Git actually has the notion of a prefix, which is the subdirectory the user's CWD is in compared to the worktree. It is used to normalise input paths to be worktree-relative, and to denormalise (?) output paths to once again be relative to the prefix, i.e. the user's CWD.

Also, to be clear about the "let's have the best-possible docs" directive: this is based on thinking that the non-command parts of the but CLI are like its own little SDK, so it should be very re-usable and thus well documented. Much like the but-api or the plumbing crates, which should all excel in helping to use it correctly with docs (and types). Or said differently: docs capture the expert knowledge that isn't obvious when looking at the code, and that will soon be gone once the human moved on.

Copy link
Contributor Author

@slarse slarse Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe this tells us that we'd want to have a path which proves that a path is inside the worktree (and probably not inside .git).

Perhaps, or perhaps we want a path that is provably accessible to GitButler given the context of the current repository. Excluding the changes I've made here, none of the paths we open in this module are actually relative to the worktree, they're all temporary files (that would usually end up in /tmp, but it's fundamentally up to the OS). So that doesn't work if we don't change that mechanism. I believe Git always opens its temporary files in the .git/ directory (e.g. .git/COMMIT_EDITMSG), and doesn't make use of temporary files the way we do. But maybe we should do the same there and create temporary files in .git/gitbutler. At least macOS and Linux allow us to specify the directory

I'm really aching for the kind of functionality that but open would provide, and it can be further expanded with all kinds of interesting stuff, but we need to think through the security implications carefully. I think I'll finish up the basic implementation and then we'll take it from there, I'm sure we can make it secure and useful all in one big lovely package.

Also, to be clear about the "let's have the best-possible docs" directive: this is based on thinking that the non-command parts of the but CLI are like its own little SDK, so it should be very re-usable and thus well documented. Much like the but-api or the plumbing crates, which should all excel in helping to use it correctly with docs (and types). Or said differently: docs capture the expert knowledge that isn't obvious when looking at the code, and that will soon be gone once the human moved on.

I'm not opposed to any of that. I would probably delimit that effort to public functions, however. High-quality docs are harder to maintain than code as they cannot be automatically checked (although LLMs do help a bit, but it's far from bullet proof).

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

While type-safety around this is nothing I'd even suggest to tackle here, it's something I always eyed but never accomplished. Maybe one day.

Regarding docs, while this one isn't public, it still triggered this conversation about that path parameter, which is clear sign that expanding the docs to contain this expert knowledge should be worthwhile.

let status = gix::command::prepare(editor_cmd)
.arg(tempfile.path())
.arg(path_safe_intent)
.stdin(std::process::Stdio::inherit())
.stdout(std::process::Stdio::inherit())
.stderr(std::process::Stdio::inherit())
.with_shell()
.spawn()?
.wait()?;

if !status.success() {
bail!("Editor exited with non-zero status");
}
Ok(std::fs::read(&tempfile)?.into())

Ok(())
}

/// Launch the built-in TUI editor.
Expand Down
1 change: 1 addition & 0 deletions crates/but/src/utils/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ impl Subcommands {
skill::Subcommands::Check { .. } => SkillCheck,
},
Subcommands::Edit { .. } => Edit,
Subcommands::Open { .. } => Open,
Subcommands::Link(link::Platform { .. }) => Unknown,
Subcommands::Onboarding | Subcommands::EvalHook => Unknown,
}
Expand Down
Loading