A3: add untracked files to .gitignore from the Changes context menu
git.ignore appends one anchored, escaped literal pattern per path to the work tree root's .gitignore, skipping patterns already there. The Changes window gets a row context menu (right click, Shift+F10, context-menu key) with Open and Add to .gitignore. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
ce681871ad
commit
68599fa2ac
14 changed files with 633 additions and 5 deletions
80
crates/engine/src/cmd/git_ignore.rs
Normal file
80
crates/engine/src/cmd/git_ignore.rs
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
//! `git.ignore` (C7 A3): adds literal patterns for chosen files to the
|
||||
//! work tree's `.gitignore`, on top of `lutra_vcs::Repo::ignore`.
|
||||
//!
|
||||
//! It runs through [`super::git::start_with`] like the other `git.*`
|
||||
//! commands and sends `gitChanged` afterwards, since the status changes.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::git::{rel_path, start_with};
|
||||
use super::params::parse;
|
||||
use crate::{Command, CommandSpec, EngineError, Outcome, Registry, State};
|
||||
|
||||
/// Most paths one call takes.
|
||||
const MAX_PATHS: usize = 10_000;
|
||||
|
||||
/// Registers `git.ignore`.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`EngineError::Internal`] if the id is taken.
|
||||
pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
|
||||
registry.register(Box::new(Ignore))
|
||||
}
|
||||
|
||||
/// Params of `git.ignore`.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct IgnoreParams {
|
||||
/// Project-relative or absolute paths inside the project.
|
||||
paths: Vec<String>,
|
||||
}
|
||||
|
||||
/// `git.ignore`.
|
||||
struct Ignore;
|
||||
|
||||
impl Command for Ignore {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "git.ignore",
|
||||
label: "Git: Add to .gitignore",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "{ paths: [path inside the project] } (1 to 10000); appends one literal pattern per path to the .gitignore at the work tree's root (created when missing): anchored with /, with \\ * ? [ and trailing spaces escaped, so it matches exactly that file or folder; returns { patterns: [added pattern] }, leaving out patterns already in the file",
|
||||
}
|
||||
}
|
||||
|
||||
fn enabled(&self, state: &State) -> bool {
|
||||
state.has_project()
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let p: IgnoreParams = parse(command, params)?;
|
||||
if p.paths.is_empty() || p.paths.len() > MAX_PATHS {
|
||||
return Err(EngineError::invalid_params(
|
||||
command,
|
||||
format!("paths takes 1 to {MAX_PATHS} entries"),
|
||||
));
|
||||
}
|
||||
let paths = p
|
||||
.paths
|
||||
.iter()
|
||||
.map(|path| rel_path(state, command, path))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
start_with(
|
||||
state,
|
||||
command,
|
||||
true,
|
||||
Box::new(move |repo| {
|
||||
let patterns = repo.ignore(&paths)?;
|
||||
Ok(json!({ "patterns": patterns }))
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of the commands this module registers, checked against the
|
||||
/// registry by the engine's listing test. Add a new command's id here.
|
||||
#[cfg(test)]
|
||||
pub(crate) const COMMAND_IDS: &[&str] = &["git.ignore"];
|
||||
|
|
@ -5,6 +5,7 @@ mod buffer;
|
|||
mod file;
|
||||
pub mod git;
|
||||
pub mod git_blame;
|
||||
pub mod git_ignore;
|
||||
pub mod git_lines;
|
||||
pub mod git_log;
|
||||
pub mod git_merge;
|
||||
|
|
@ -78,6 +79,7 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
|
|||
git_remote::register(registry)?;
|
||||
git_merge::register(registry)?;
|
||||
git_stash::register(registry)?;
|
||||
git_ignore::register(registry)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -91,6 +93,7 @@ pub(crate) const BUILTIN_COMMAND_IDS: &[&[&str]] = &[
|
|||
file::COMMAND_IDS,
|
||||
git::COMMAND_IDS,
|
||||
git_blame::COMMAND_IDS,
|
||||
git_ignore::COMMAND_IDS,
|
||||
git_lines::COMMAND_IDS,
|
||||
git_log::COMMAND_IDS,
|
||||
git_merge::COMMAND_IDS,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
//! The merge commands through the engine with pending outcomes:
|
||||
//! `git.merge` up to date, with conflicts and refused; `git.conflictVersions`;
|
||||
//! `git.markResolved` and `git.mergeAbort`, each followed by `gitChanged`;
|
||||
//! bad params. Skips with a message when git is not installed.
|
||||
//! `git.mergeMessage`; `git.ignore` (C7 A3); bad params. Skips with a message when git is not installed.
|
||||
|
||||
#![allow(
|
||||
clippy::unwrap_used,
|
||||
|
|
@ -198,6 +198,8 @@ fn bad_params_and_no_project() {
|
|||
("git.merge", json!({"branch": "-x"})),
|
||||
("git.markResolved", json!({"paths": []})),
|
||||
("git.conflictVersions", json!({"path": 3})),
|
||||
("git.ignore", json!({"paths": []})),
|
||||
("git.ignore", json!({"paths": ["../x"]})),
|
||||
] {
|
||||
assert!(
|
||||
matches!(
|
||||
|
|
@ -216,3 +218,32 @@ fn bad_params_and_no_project() {
|
|||
Err(EngineError::Disabled(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignore_appends_a_literal_pattern_and_refreshes() {
|
||||
if !have_git() {
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
conflicting(root);
|
||||
std::fs::write(root.join("debug[1].log"), "x").unwrap();
|
||||
std::fs::write(root.join("debug1.log"), "x").unwrap();
|
||||
let host = Host::open(root);
|
||||
host.git_changes();
|
||||
let out = host
|
||||
.run("git.ignore", json!({"paths": ["debug[1].log"]}))
|
||||
.unwrap();
|
||||
assert_eq!(out["patterns"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(host.git_changes(), 1);
|
||||
let status = host.run("git.status", Value::Null).unwrap();
|
||||
let paths: Vec<&str> = status["files"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|f| f["path"].as_str().unwrap())
|
||||
.collect();
|
||||
assert!(paths.contains(&"debug1.log"), "{paths:?}");
|
||||
assert!(paths.contains(&".gitignore"), "{paths:?}");
|
||||
assert!(!paths.contains(&"debug[1].log"), "{paths:?}");
|
||||
}
|
||||
|
|
|
|||
115
crates/vcs/src/ignore.rs
Normal file
115
crates/vcs/src/ignore.rs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
//! Ignoring files (C7 A3): appending literal patterns for chosen paths to
|
||||
//! the `.gitignore` at the work tree's root.
|
||||
//!
|
||||
//! Each path becomes one pattern that matches exactly that path: anchored
|
||||
//! with a leading `/`, and with the characters gitignore treats specially
|
||||
//! (`\`, `*`, `?`, `[`, and trailing spaces) escaped with a backslash, so a
|
||||
//! file named `a*.php` ignores only itself. Patterns already in the file
|
||||
//! are not added again.
|
||||
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{ErrorKind, Write};
|
||||
|
||||
use crate::Repo;
|
||||
use crate::VcsError;
|
||||
use crate::repo::SMALL_CAP;
|
||||
|
||||
/// The literal, root-anchored gitignore pattern of a root-relative path.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `path`: a root-relative path with `/` separators, as
|
||||
/// [`Repo::to_repo_path`] returns it.
|
||||
pub fn ignore_pattern(path: &str) -> String {
|
||||
let kept = path.trim_end_matches(' ');
|
||||
let trailing = path.len() - kept.len();
|
||||
let mut out = String::with_capacity(path.len() + 8);
|
||||
out.push('/');
|
||||
for c in kept.chars() {
|
||||
if matches!(c, '\\' | '*' | '?' | '[') {
|
||||
out.push('\\');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
for _ in 0..trailing {
|
||||
out.push_str("\\ ");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Repo {
|
||||
/// Appends a literal pattern for each path to the root's `.gitignore`
|
||||
/// (created when missing), on a line of its own.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `paths`: project-relative paths of files or folders.
|
||||
///
|
||||
/// # Returns
|
||||
/// The patterns added, in the order given; patterns already in the
|
||||
/// file are left out.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`VcsError::InvalidPath`] for a bad path (nothing is written);
|
||||
/// [`VcsError::Git`] when `.gitignore` cannot be read or written, or is
|
||||
/// larger than 16 MiB.
|
||||
pub fn ignore(&self, paths: &[String]) -> Result<Vec<String>, VcsError> {
|
||||
let mut patterns = Vec::with_capacity(paths.len());
|
||||
for path in paths {
|
||||
let pattern = ignore_pattern(&self.to_repo_path(path)?);
|
||||
if pattern != "/" && !patterns.contains(&pattern) {
|
||||
patterns.push(pattern);
|
||||
}
|
||||
}
|
||||
if patterns.is_empty() {
|
||||
return Ok(patterns);
|
||||
}
|
||||
let _guard = self.lock();
|
||||
let file = self.root().join(".gitignore");
|
||||
let failed = |e: std::io::Error| VcsError::Git(format!("cannot update .gitignore: {e}"));
|
||||
let existing = match std::fs::read(&file) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => Vec::new(),
|
||||
Err(e) => return Err(failed(e)),
|
||||
};
|
||||
if existing.len() > SMALL_CAP {
|
||||
return Err(VcsError::Git(
|
||||
"cannot update .gitignore: the file is too large".into(),
|
||||
));
|
||||
}
|
||||
let text = String::from_utf8_lossy(&existing);
|
||||
let present: Vec<&str> = text.lines().collect();
|
||||
patterns.retain(|p| !present.contains(&p.as_str()));
|
||||
if patterns.is_empty() {
|
||||
return Ok(patterns);
|
||||
}
|
||||
let mut out = String::new();
|
||||
if !existing.is_empty() && !existing.ends_with(b"\n") {
|
||||
out.push('\n');
|
||||
}
|
||||
for pattern in &patterns {
|
||||
out.push_str(pattern);
|
||||
out.push('\n');
|
||||
}
|
||||
OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&file)
|
||||
.and_then(|mut f| f.write_all(out.as_bytes()))
|
||||
.map_err(failed)?;
|
||||
Ok(patterns)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn patterns_are_anchored_and_literal() {
|
||||
assert_eq!(ignore_pattern("tmp.txt"), "/tmp.txt");
|
||||
assert_eq!(ignore_pattern("a/b c.php"), "/a/b c.php");
|
||||
assert_eq!(ignore_pattern("x*?[y].php"), "/x\\*\\?\\[y].php");
|
||||
assert_eq!(ignore_pattern("#note!"), "/#note!");
|
||||
assert_eq!(ignore_pattern("back\\slash"), "/back\\\\slash");
|
||||
assert_eq!(ignore_pattern("end "), "/end\\ \\ ");
|
||||
}
|
||||
}
|
||||
|
|
@ -12,6 +12,8 @@
|
|||
//! git's credential helper and the ssh agent (see `remote.rs`).
|
||||
//! - Blame (M4.7): who last changed each line, of the working copy or an
|
||||
//! editor buffer (`blame.rs`).
|
||||
//! - Ignoring files (C7 A3): literal patterns appended to `.gitignore`
|
||||
//! (`ignore.rs`).
|
||||
//! - [`RepoWatch`] notices changes inside `.git` (HEAD, index, refs).
|
||||
//!
|
||||
//! Every call goes through [`runner::run`]: arguments as an array, never a
|
||||
|
|
@ -25,6 +27,7 @@
|
|||
|
||||
pub mod blame;
|
||||
mod error;
|
||||
mod ignore;
|
||||
pub mod log;
|
||||
pub mod porcelain;
|
||||
mod remote;
|
||||
|
|
@ -35,6 +38,7 @@ mod watch;
|
|||
|
||||
pub use blame::{BlameLine, UNCOMMITTED_AUTHOR, is_uncommitted};
|
||||
pub use error::VcsError;
|
||||
pub use ignore::ignore_pattern;
|
||||
pub use log::{CommitDetails, CommitFile, LOG_LIMIT, LogCommit, LogQuery};
|
||||
pub use porcelain::{FileState, FileStatus, Head, Status, Version};
|
||||
pub use remote::{
|
||||
|
|
|
|||
86
crates/vcs/tests/ignore.rs
Normal file
86
crates/vcs/tests/ignore.rs
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
//! Ignoring files against a real temp repository: literal patterns for
|
||||
//! odd names, a project in a subfolder, no duplicates, a missing final line
|
||||
//! break, and refused paths. Skips with a message when git is not
|
||||
//! installed.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use lutra_vcs::{Git, VcsError};
|
||||
|
||||
/// The installed git, or `None` (with a message) when there is none.
|
||||
fn installed() -> Option<Git> {
|
||||
match Git::detect("") {
|
||||
Ok(git) => Some(git),
|
||||
Err(e) => {
|
||||
eprintln!("skipped: no usable git installed ({e})");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs git in `dir` and returns its stdout and whether it succeeded.
|
||||
fn git(dir: &Path, args: &[&str]) -> (String, bool) {
|
||||
let out = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.env_remove("GIT_DIR")
|
||||
.env_remove("GIT_WORK_TREE")
|
||||
.env_remove("GIT_INDEX_FILE")
|
||||
.output()
|
||||
.unwrap();
|
||||
(
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_string(),
|
||||
out.status.success(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether git ignores `path` (root-relative).
|
||||
fn ignored(dir: &Path, path: &str) -> bool {
|
||||
git(dir, &["check-ignore", "-q", "--no-index", "--", path]).1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_exactly_the_given_paths() {
|
||||
let Some(cli) = installed() else { return };
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
assert!(git(root, &["init", "-q", "-b", "main"]).1);
|
||||
std::fs::create_dir_all(root.join("app/var")).unwrap();
|
||||
std::fs::write(root.join(".gitignore"), "vendor/").unwrap();
|
||||
for name in [
|
||||
"app/a[1].php",
|
||||
"app/a1.php",
|
||||
"app/var/cache.log",
|
||||
"app/b.php",
|
||||
] {
|
||||
std::fs::write(root.join(name), "x").unwrap();
|
||||
}
|
||||
let repo = cli.open(&root.join("app")).unwrap().expect("a repository");
|
||||
|
||||
let added = repo
|
||||
.ignore(&[
|
||||
"a[1].php".to_string(),
|
||||
"var".to_string(),
|
||||
"var/".to_string(),
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(added, vec![r"/app/a\[1].php", "/app/var"]);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(root.join(".gitignore")).unwrap(),
|
||||
"vendor/\n/app/a\\[1].php\n/app/var\n"
|
||||
);
|
||||
assert!(ignored(root, "app/a[1].php"));
|
||||
assert!(!ignored(root, "app/a1.php"));
|
||||
assert!(ignored(root, "app/var/cache.log"));
|
||||
assert!(!ignored(root, "app/b.php"));
|
||||
|
||||
assert!(repo.ignore(&["a[1].php".to_string()]).unwrap().is_empty());
|
||||
assert!(matches!(
|
||||
repo.ignore(&["../outside".to_string(), "b.php".to_string()]),
|
||||
Err(VcsError::InvalidPath(_))
|
||||
));
|
||||
assert!(!ignored(root, "app/b.php"));
|
||||
}
|
||||
|
|
@ -594,6 +594,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
- **Commands** (UI commands, menu group Git): `vcs.openChanges` `Mod+Alt+Shift+G` shows the tab; `vcs.commit` `Mod+Alt+Shift+M` shows it and focuses the message box; `vcs.refresh` re-reads the status (enabled while `git.status` is). The shortcuts are Lutra's own: checked against the public default keymaps (Windows and macOS) so they copy no default there, and against Lutra's registered shortcuts and CodeMirror's `basicSetup` keys (`Mod+Alt+G` is its go to line, which the global listener would swallow).
|
||||
- **Status:** read from the shared status store (`ui/src/stores/vcsStatus.ts`, since C6 F1), which runs `git.status` on start, on `projectOpened`, on `gitChanged` and on `vcs.refresh`; `projectClosed` clears it and with it the rows and the selection. The result is untrusted: unknown states and malformed entries are dropped, at most 50,000 files.
|
||||
- **Amend prefill (C6 F1):** checking Amend with an empty message box fills it from `git.lastMessage`; clearing Amend empties a box that still holds exactly that text. A message already typed is never replaced. The event type `gitChanged` is now part of `EngineEventPayload` in `ui/src/ipc.ts`.
|
||||
- **Context menu and ignoring (C7 A3):** a right click on a row (or Shift+F10 / the context-menu key) opens `ChangesContextMenu.vue`: Open, and Add to .gitignore for untracked rows. That runs `git.ignore {paths}` (`cmd/git_ignore.rs`, `crates/vcs/src/ignore.rs`) → `{patterns}`: one pattern per path appended to the work tree root's `.gitignore`, anchored with `/` and with `\ * ? [` and trailing spaces escaped, so it matches only that path; patterns already present are skipped; `gitChanged` follows.
|
||||
- **Groups:** Staged (the index side changed), Changes (the work tree side changed, or conflicted), Untracked. A partly staged file is in Staged and Changes. Names are coloured with `--lt-vcs-*` (renamed and modified use `modified`, copied uses `added`); a deleted file is struck through. A staged rename shows "from <old path>".
|
||||
- **Staging:** a checkbox per file and per group header: checked in Staged (clearing it unstages), clear elsewhere (checking it stages). `git.stage {paths}` / `git.unstage {paths}`, both through `runWaiting`; unstaging a staged rename passes both paths, as M4.1 requires. Keyboard: Up/Down, Page Up/Down, Home, End move; Space stages or unstages; Enter opens. Failures toast git's message (`notification.command.failed`).
|
||||
- **Opening:** Enter or a double-click runs the UI command `vcs.showDiff {path, staged}` when something provides it (the diff viewer, M4.3, registers and provides it); until then the file opens with `file.open`, and a deleted file does nothing.
|
||||
|
|
@ -756,6 +757,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-31 | minor | C7 A3: `git.mergeMessage` and the merge message prefill, `git.ignore` and the Changes context menu, gutter markers kept on their line, per-module `COMMAND_IDS` for the command listing test |
|
||||
| 2026-10-30 | minor | M4.7: blame (`git.blame` with `--contents` from the buffer, the annotation gutter by age, hover with the commit message, `vcs.toggleBlame`, `vcs.showCommit`) |
|
||||
| 2026-10-28 | minor | M4.6: history backend (`git.log`, `git.showCommit`, `git.showAt`), the shared hook for new git commands, the Log tab, diffs at a commit |
|
||||
| 2026-10-28 | minor | M4.10: remotes (`Call::network` with progress and cancel, URL redaction, `git.fetch/pull/push/clone/cancel/remotes/remoteAdd/remoteSetUrl/remoteRemove`, `gitProgress`, `git.pull.mode`, the clone and remotes dialogs) |
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -41,7 +41,7 @@
|
|||
- [ ] Terminal tool window
|
||||
- M3.6 (2026-10-18): a Terminal tab in the bottom panel (the panel shows Find and Terminal as tabs while both are open; Left/Right switch); xterm.js with the fit addon follows the panel size; several terminals as sub-tabs (Local, Local (2)…) with a close button each and a new-terminal button, Left/Right/Home/End/Delete on a sub-tab, an ended shell dims its tab and prints its exit code; output survives collapsing the panel; copy with `Mod+Shift+C` or `Ctrl+C` on a selection, paste with `Mod+Shift+V` or `Ctrl+V`; while a terminal has the focus plain Ctrl keys go to the shell and only Mod+Shift / Mod+Alt shortcuts reach Lutra; Lutra's own ANSI palette in both themes (text colours ≥ 4.5:1). `terminal.open` `Mod+Shift+T`. Missing: renaming and splitting tabs, a context menu, search, clickable links and paths, drag and drop, a key back to the editor, a confirmation before killing a running process, terminal settings.
|
||||
- [ ] Git tool window
|
||||
- M4.2 (2026-10-25): a Changes tab in the bottom panel (`vcs.openChanges` `Mod+Alt+Shift+G`, menu Git › Changes): Staged, Changes and Untracked groups with counts, file names coloured by status (`--lt-vcs-*`, deleted struck through, a staged rename shows its old path), a checkbox per file and per group to stage or unstage, Up/Down/Page/Home/End and Space in the list, double-click or Enter opens the diff (M4.3) or the file; a commit message box with Amend and Commit (`Mod+Enter`; `vcs.commit` `Mod+Alt+Shift+M` focuses it), saving open files first; a refresh button (`vcs.refresh`); hints when git is missing or the folder is not a repository. Vitest (19 tests). Missing: a tree view and grouping by directory or module, changelists, chunk staging, a context menu (rollback, delete, add to .gitignore), recent commit messages, commit options (sign-off, author, skip hooks), commit and push, a commit preview of the diff. Behaviour notes: `plan/phpstorm/16-vcs-basics.md`.
|
||||
- M4.2 (2026-10-25): a Changes tab in the bottom panel (`vcs.openChanges` `Mod+Alt+Shift+G`, menu Git › Changes): Staged, Changes and Untracked groups with counts, file names coloured by status (`--lt-vcs-*`, deleted struck through, a staged rename shows its old path), a checkbox per file and per group to stage or unstage, Up/Down/Page/Home/End and Space in the list, double-click or Enter opens the diff (M4.3) or the file; a commit message box with Amend and Commit (`Mod+Enter`; `vcs.commit` `Mod+Alt+Shift+M` focuses it), saving open files first; a refresh button (`vcs.refresh`); hints when git is missing or the folder is not a repository. Vitest (19 tests). C7 A3: a row context menu (right click, Shift+F10, the context-menu key) with Open and Add to .gitignore for untracked files, and git's prepared merge message offered in an empty box during a merge. Missing: a tree view and grouping by directory or module, changelists, chunk staging, context menu actions to roll back or delete, recent commit messages, commit options (sign-off, author, skip hooks), commit and push, a commit preview of the diff. Behaviour notes: `plan/phpstorm/16-vcs-basics.md`.
|
||||
- M4.4 (2026-10-25): the editor gutter shows a bar beside lines added or changed since the staged version and a notch where lines were deleted (tooltips from the catalog), updated 150 ms after typing and whenever Git changes; file names in the project tree and the tabs take the Git status colour (added, modified, deleted, untracked, conflicted; ignored entries inside a repository). Vitest. Missing: clicking a marker to see the old text, revert or stage the chunk, next/previous change, markers against HEAD, coloured directories.
|
||||
- M4.3 (2026-10-26): "Diff: <name>" tabs in the editor area after the file tabs (`vcs.showDiff` `Mod+Alt+Shift+D`, menu Git › Show Diff; double-click or Enter in Changes; right click or Shift+F10 on a file in the project tree → Show Diff): the staged version or the last commit on the left, read-only, and the working copy on the right, editable like its own tab; a caption says what is compared; changed lines and words tinted with the VCS tokens, a change bar in each gutter, unchanged stretches collapsed to a clickable row; next/previous change `Alt+Shift+]` / `Alt+Shift+[` (wrapping); notices for binary, too large and deleted files and for git's errors. The project tree got its first context menu (Open, Show Diff; WAI-ARIA menu, keyboard). Vitest. Missing: unified view, revert/stage arrows between the sides, synchronised horizontal scrolling, whitespace and highlighting options, comparing with any revision, a diff window of its own, more tree context menu items.
|
||||
- M4.5 (2026-10-26): the status bar shows the current branch (Lucide `git-branch`), or the short hash when detached, hidden outside a repository. A click or `vcs.branches` (menu Git › Branches…) opens a popup above it: a filter field, "New branch…", Local (current one checked, upstream beside it) and Remote headings; Up/Down/Page keys, Enter or a click checks out, Escape or a click outside closes and returns the focus. "New branch…" switches to a name field with a "Check out" checkbox; git's refusal shows under the field. An exclusive modal. Vitest (16 tests). Missing: merge, rebase, rename, delete, compare with current, favourites, recent branches first, incoming/outgoing markers, a submenu per branch.
|
||||
|
|
@ -51,6 +51,7 @@
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-31 | patch | Changes context menu with Add to .gitignore and the merge message prefill (C7 A3) |
|
||||
| 2026-10-28 | minor | Fetch/pull/push with progress, clone and remotes dialogs (M4.10) |
|
||||
| 2026-10-26 | minor | Branch widget and popup (M4.5) |
|
||||
| 2026-10-26 | minor | Diff viewer and the project tree's context menu (M4.3) |
|
||||
|
|
|
|||
200
ui/src/components/vcs/changes/ChangesContextMenu.vue
Normal file
200
ui/src/components/vcs/changes/ChangesContextMenu.vue
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* The Changes window's context menu for a file row (C7 A3): Open (as a
|
||||
* double-click does) and Add to .gitignore (`git.ignore`, only for
|
||||
* untracked files; dimmed otherwise).
|
||||
*
|
||||
* Follows the WAI-ARIA menu pattern like the project tree's menu: it takes
|
||||
* the focus when it opens, Up/Down move between items (wrapping), Enter or
|
||||
* Space runs one, Escape, Tab or a press outside closes it. The position
|
||||
* is clamped into the window.
|
||||
*/
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { t } from "../../../i18n";
|
||||
import { useChangesStore, type ChangeRow } from "./changes";
|
||||
|
||||
const props = defineProps<{
|
||||
/** The row the menu is for. */
|
||||
row: ChangeRow;
|
||||
/** Window x of the pointer (or the row) in pixels. */
|
||||
x: number;
|
||||
/** Window y of the pointer (or the row) in pixels. */
|
||||
y: number;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** The menu should close (an item ran or the user dismissed it). */
|
||||
close: [];
|
||||
/** Open the row, as a double-click does. */
|
||||
open: [row: ChangeRow];
|
||||
}>();
|
||||
|
||||
const changes = useChangesStore();
|
||||
|
||||
/** The menu element. */
|
||||
const menuEl = ref<HTMLElement | null>(null);
|
||||
/** Index of the focused item. */
|
||||
const focused = ref(0);
|
||||
|
||||
/** One item of the menu. */
|
||||
interface MenuItem {
|
||||
/** Stable id, also used by tests. */
|
||||
id: string;
|
||||
/** Text shown. */
|
||||
label: string;
|
||||
/** Whether it can run now. */
|
||||
enabled: boolean;
|
||||
/** Runs it. */
|
||||
run: () => Promise<void>;
|
||||
}
|
||||
|
||||
/** The items, in order. */
|
||||
const items = computed<MenuItem[]>(() => [
|
||||
{
|
||||
id: "open",
|
||||
label: t("vcs.changes.menu.open"),
|
||||
enabled: true,
|
||||
run: () => {
|
||||
emit("open", props.row);
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "ignore",
|
||||
label: t("vcs.changes.menu.ignore"),
|
||||
enabled: props.row.group === "untracked" && !changes.busy,
|
||||
run: () => changes.ignore([props.row]),
|
||||
},
|
||||
]);
|
||||
|
||||
/** The menu's position, kept inside the window. */
|
||||
const position = computed(() => ({
|
||||
left: `${String(Math.max(0, Math.min(props.x, window.innerWidth - 200)))}px`,
|
||||
top: `${String(Math.max(0, Math.min(props.y, window.innerHeight - 80)))}px`,
|
||||
}));
|
||||
|
||||
/**
|
||||
* Runs an item and closes the menu.
|
||||
*
|
||||
* @param item - the item.
|
||||
*/
|
||||
async function choose(item: MenuItem): Promise<void> {
|
||||
if (!item.enabled) {
|
||||
return;
|
||||
}
|
||||
emit("close");
|
||||
await item.run();
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyboard handling of the menu.
|
||||
*
|
||||
* @param event - the key event.
|
||||
*/
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
const count = items.value.length;
|
||||
switch (event.key) {
|
||||
case "ArrowDown":
|
||||
focused.value = (focused.value + 1) % count;
|
||||
break;
|
||||
case "ArrowUp":
|
||||
focused.value = (focused.value - 1 + count) % count;
|
||||
break;
|
||||
case "Enter":
|
||||
case " ": {
|
||||
const item = items.value[focused.value];
|
||||
if (item) {
|
||||
void choose(item);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "Escape":
|
||||
case "Tab":
|
||||
emit("close");
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the menu on a press outside it.
|
||||
*
|
||||
* @param event - the pointer event on the window.
|
||||
*/
|
||||
function onPointerDown(event: PointerEvent): void {
|
||||
if (menuEl.value && event.target instanceof Node && !menuEl.value.contains(event.target)) {
|
||||
emit("close");
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener("pointerdown", onPointerDown, true);
|
||||
void nextTick(() => menuEl.value?.focus());
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener("pointerdown", onPointerDown, true);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
ref="menuEl"
|
||||
class="changes-menu"
|
||||
role="menu"
|
||||
tabindex="-1"
|
||||
:aria-label="t('vcs.changes.menu.label', { path: row.file.path })"
|
||||
:aria-activedescendant="`lt-changes-menu-${items[focused]?.id ?? ''}`"
|
||||
:style="position"
|
||||
data-test="changes-menu"
|
||||
@keydown="onKeydown"
|
||||
@contextmenu.prevent
|
||||
>
|
||||
<div
|
||||
v-for="(item, index) in items"
|
||||
:id="`lt-changes-menu-${item.id}`"
|
||||
:key="item.id"
|
||||
class="changes-menu__item"
|
||||
:class="{ 'changes-menu__item--focused': index === focused, 'changes-menu__item--disabled': !item.enabled }"
|
||||
role="menuitem"
|
||||
:aria-disabled="!item.enabled"
|
||||
:data-item="item.id"
|
||||
data-test="changes-menu-item"
|
||||
@mouseenter="focused = index"
|
||||
@click="choose(item)"
|
||||
>
|
||||
{{ item.label }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.changes-menu {
|
||||
position: fixed;
|
||||
z-index: 50;
|
||||
min-width: 160px;
|
||||
padding: 4px 0;
|
||||
color: var(--lt-fg);
|
||||
background: var(--lt-bg);
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: 4px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.changes-menu__item {
|
||||
padding: 4px 16px;
|
||||
cursor: default;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.changes-menu__item--focused {
|
||||
background: var(--lt-editor-selection-bg);
|
||||
}
|
||||
|
||||
.changes-menu__item--disabled {
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
</style>
|
||||
|
|
@ -20,6 +20,9 @@
|
|||
* `vcs.showDiff {path, staged}` when something provides it (the diff
|
||||
* viewer, M4.3); until then the file opens in the editor (`file.open`),
|
||||
* unless it was deleted.
|
||||
* - **Context menu (C7 A3):** a right click on a row, or Shift+F10 / the
|
||||
* context-menu key on the selected one, opens `ChangesContextMenu.vue`:
|
||||
* Open, and Add to .gitignore for untracked files.
|
||||
* - **Commit box:** the message, an Amend checkbox and Commit. Commit
|
||||
* saves dirty buffers first (`flushDirty`); `Mod+Enter` in the box
|
||||
* commits too.
|
||||
|
|
@ -35,6 +38,7 @@ import { t } from "../../../i18n";
|
|||
import { run } from "../../../ipc";
|
||||
import { baseName } from "../../../stores/editor";
|
||||
import { useNotificationsStore } from "../../../stores/notifications";
|
||||
import ChangesContextMenu from "./ChangesContextMenu.vue";
|
||||
import { SHORT_HASH, useChangesStore, type ChangeRow, type FileState, type GroupId } from "./changes";
|
||||
|
||||
const changes = useChangesStore();
|
||||
|
|
@ -46,6 +50,27 @@ const list = ref<HTMLElement | null>(null);
|
|||
/** The commit message box. */
|
||||
const messageBox = ref<HTMLTextAreaElement | null>(null);
|
||||
|
||||
/** The open context menu: its row and where it shows; null when closed. */
|
||||
const menu = ref<{ row: ChangeRow; x: number; y: number } | null>(null);
|
||||
|
||||
/**
|
||||
* Opens the context menu of a row.
|
||||
*
|
||||
* @param row - the row; it becomes the selection.
|
||||
* @param x - window x of the menu.
|
||||
* @param y - window y of the menu.
|
||||
*/
|
||||
function openMenu(row: ChangeRow, x: number, y: number): void {
|
||||
changes.select(row.key);
|
||||
menu.value = { row, x, y };
|
||||
}
|
||||
|
||||
/** Closes the context menu and gives the focus back to the list. */
|
||||
function closeMenu(): void {
|
||||
menu.value = null;
|
||||
list.value?.focus();
|
||||
}
|
||||
|
||||
/** Rows moved by Page Up and Page Down. */
|
||||
const PAGE = 10;
|
||||
|
||||
|
|
@ -259,6 +284,10 @@ function onListKey(event: KeyboardEvent): void {
|
|||
} else if (event.key === " " && row) {
|
||||
event.preventDefault();
|
||||
void changes.toggle(row);
|
||||
} else if ((event.key === "ContextMenu" || (event.key === "F10" && event.shiftKey)) && row) {
|
||||
event.preventDefault();
|
||||
const rect = document.getElementById(optionId(changes.selectedIndex))?.getBoundingClientRect();
|
||||
openMenu(row, rect ? rect.left + 24 : 0, rect ? rect.bottom : 0);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -399,6 +428,7 @@ watch(
|
|||
data-test="changes-row"
|
||||
@click="changes.select(row.key)"
|
||||
@dblclick="openRow(row)"
|
||||
@contextmenu.prevent="openMenu(row, $event.clientX, $event.clientY)"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
|
|
@ -420,6 +450,14 @@ watch(
|
|||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ChangesContextMenu
|
||||
v-if="menu"
|
||||
:row="menu.row"
|
||||
:x="menu.x"
|
||||
:y="menu.y"
|
||||
@close="closeMenu"
|
||||
@open="openRow"
|
||||
/>
|
||||
<form
|
||||
class="changes__commit"
|
||||
data-test="changes-commit"
|
||||
|
|
|
|||
|
|
@ -11,6 +11,8 @@
|
|||
* when its work tree side changed or it is conflicted, and Untracked when
|
||||
* git does not track it. A partly staged file is in both Staged and
|
||||
* Changes. Ignored files are not listed by the backend.
|
||||
* - **Ignoring (C7 A3):** `git.ignore {paths}` for untracked rows adds a
|
||||
* literal pattern per file to the root `.gitignore`, then re-reads.
|
||||
* - **Staging:** `git.stage` / `git.unstage` per file or per group.
|
||||
* Unstaging a staged rename passes both paths, as the backend asks.
|
||||
* - **Commit:** `flushDirty()` first, so the files on disk hold what the
|
||||
|
|
@ -240,6 +242,11 @@ export const useChangesStore = defineStore("changes", () => {
|
|||
void onAmend(on);
|
||||
});
|
||||
|
||||
/** Whether the box is empty and Amend is off, so a prepared message may fill it. */
|
||||
function boxFree(): boolean {
|
||||
return !amend.value && message.value.trim() === "";
|
||||
}
|
||||
|
||||
/** Whether the prepared merge message was offered for the merge in progress. */
|
||||
let mergeOffered = false;
|
||||
|
||||
|
|
@ -249,7 +256,7 @@ export const useChangesStore = defineStore("changes", () => {
|
|||
* is; no merge also ends the current offer.
|
||||
*/
|
||||
async function offerMergeMessage(): Promise<void> {
|
||||
if (amend.value || message.value.trim() !== "") {
|
||||
if (!boxFree()) {
|
||||
return;
|
||||
}
|
||||
const result = await runWaiting("git.mergeMessage");
|
||||
|
|
@ -266,7 +273,7 @@ export const useChangesStore = defineStore("changes", () => {
|
|||
return;
|
||||
}
|
||||
mergeOffered = true;
|
||||
if (!amend.value && message.value.trim() === "") {
|
||||
if (boxFree()) {
|
||||
message.value = text;
|
||||
}
|
||||
}
|
||||
|
|
@ -343,6 +350,32 @@ export const useChangesStore = defineStore("changes", () => {
|
|||
return row.group === "staged" ? unstage([row]) : stage([row]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds untracked files to the root `.gitignore`, one literal pattern
|
||||
* each, and toasts the result.
|
||||
*
|
||||
* @param list - rows; those not in Untracked are ignored.
|
||||
*/
|
||||
async function ignore(list: ChangeRow[]): Promise<void> {
|
||||
const paths = [...new Set(list.filter((row) => row.group === "untracked").map((row) => row.file.path))];
|
||||
if (paths.length === 0 || busy.value) {
|
||||
return;
|
||||
}
|
||||
busy.value = true;
|
||||
try {
|
||||
if ((await mutate("git.ignore", { paths })) !== null) {
|
||||
notifications.notify({
|
||||
level: "info",
|
||||
messageKey: "notification.vcs.ignored",
|
||||
params: { path: paths.join(", ") },
|
||||
});
|
||||
await refresh();
|
||||
}
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stages or unstages a whole group.
|
||||
*
|
||||
|
|
@ -482,6 +515,7 @@ export const useChangesStore = defineStore("changes", () => {
|
|||
unstage,
|
||||
toggle,
|
||||
toggleGroup,
|
||||
ignore,
|
||||
commit,
|
||||
start,
|
||||
stop,
|
||||
|
|
|
|||
|
|
@ -183,6 +183,7 @@
|
|||
"notification.vcs.fetchFailed": "Fetch failed: {reason}",
|
||||
"notification.vcs.fetched": "Fetched from every remote",
|
||||
"notification.vcs.historyNoFile": "Open a file or pass a path to show its history",
|
||||
"notification.vcs.ignored": "Added to .gitignore: {path}",
|
||||
"notification.vcs.mergeAborted": "Merge aborted",
|
||||
"notification.vcs.mergeConflicts": "Merging {branch} stopped on conflicts (conflicted files: {count}). Resolve them, then commit.",
|
||||
"notification.vcs.mergeFailed": "Git did not merge {branch}: {reason}",
|
||||
|
|
@ -347,6 +348,9 @@
|
|||
"vcs.changes.group.untracked": "Untracked",
|
||||
"vcs.changes.list.label": "Changed files",
|
||||
"vcs.changes.loading": "Reading the Git status…",
|
||||
"vcs.changes.menu.ignore": "Add to .gitignore",
|
||||
"vcs.changes.menu.label": "Actions for {path}",
|
||||
"vcs.changes.menu.open": "Open",
|
||||
"vcs.changes.noCommits": "no commits yet",
|
||||
"vcs.changes.noProject": "Open a project to see its changes",
|
||||
"vcs.changes.noRepo": "This project is not in a Git repository",
|
||||
|
|
|
|||
|
|
@ -430,6 +430,35 @@ describe("the Changes window", () => {
|
|||
expect(callsOf("file.open").map((c) => c.params)).toEqual([{ path: "src/a.php" }]);
|
||||
});
|
||||
|
||||
it("adds an untracked file to .gitignore from its context menu", async () => {
|
||||
const wrapper = await mountChanges();
|
||||
const rows = wrapper.findAll("[data-test=changes-row]");
|
||||
await rows[0]?.trigger("contextmenu", { clientX: 10, clientY: 10 });
|
||||
const items = (): HTMLElement[] => [...document.querySelectorAll<HTMLElement>("[data-test=changes-menu-item]")];
|
||||
expect(items().map((item) => item.dataset.item)).toEqual(["open", "ignore"]);
|
||||
expect(items()[1]?.getAttribute("aria-disabled")).toBe("true");
|
||||
items()[1]?.click();
|
||||
await flushPromises();
|
||||
expect(callsOf("git.ignore")).toHaveLength(0);
|
||||
document.querySelector<HTMLElement>("[data-test=changes-menu]")?.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: "Escape", bubbles: true }),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(document.querySelector("[data-test=changes-menu]")).toBeNull();
|
||||
|
||||
const list = wrapper.get("[data-test=changes-list]");
|
||||
await list.trigger("keydown", { key: "End" });
|
||||
await list.trigger("keydown", { key: "F10", shiftKey: true });
|
||||
expect(items()[1]?.getAttribute("aria-disabled")).toBe("false");
|
||||
const refreshes = callsOf("git.status").length;
|
||||
items()[1]?.click();
|
||||
await flushPromises();
|
||||
expect(callsOf("git.ignore").map((c) => c.params)).toEqual([{ paths: ["tmp.txt"] }]);
|
||||
expect(callsOf("git.status").length).toBe(refreshes + 1);
|
||||
expect(useNotificationsStore(pinia).toasts.map((toast) => toast.text)).toContain("Added to .gitignore: tmp.txt");
|
||||
expect(document.querySelector("[data-test=changes-menu]")).toBeNull();
|
||||
});
|
||||
|
||||
it("opens through vcs.showDiff when it is provided, and never opens a deleted file", async () => {
|
||||
const wrapper = await mountChanges();
|
||||
const rows = wrapper.findAll("[data-test=changes-row]");
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue