дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-30 22:32:35 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
b9a64de050 | ||
|
|
cc02c2fe40 | ||
|
|
74a3f6470a | ||
|
|
4c8c078666 | ||
|
|
e672b14d52 | ||
|
|
c0300f8959 | ||
|
|
11cf9864a1 |
No files matched your search
@@ -63,13 +63,30 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_burst_of_calls_runs_once_after_the_delay() {
|
||||
// Timing-based: a loaded CI machine can oversleep, so each check allows for that.
|
||||
let delay = Duration::from_millis(500);
|
||||
let (mut last, mut widest_gap) = (None::<Instant>, Duration::ZERO);
|
||||
for _ in 0..5 {
|
||||
debounce(&DUE, Duration::from_millis(100), count);
|
||||
debounce(&DUE, delay, count);
|
||||
let now = Instant::now();
|
||||
widest_gap = widest_gap.max(last.map_or(Duration::ZERO, |l| now - l));
|
||||
last = Some(now);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert_eq!(RUNS.load(SeqCst), 0);
|
||||
std::thread::sleep(Duration::from_millis(400));
|
||||
assert_eq!(RUNS.load(SeqCst), 1);
|
||||
if last.unwrap().elapsed() < delay {
|
||||
assert_eq!(RUNS.load(SeqCst), 0, "ran before the delay passed");
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while RUNS.load(SeqCst) == 0 && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
// A second run would come within another delay.
|
||||
std::thread::sleep(delay);
|
||||
if widest_gap < delay {
|
||||
assert_eq!(RUNS.load(SeqCst), 1);
|
||||
} else {
|
||||
assert!(RUNS.load(SeqCst) >= 1);
|
||||
}
|
||||
release_free_pages_soon();
|
||||
}
|
||||
}
|
||||
@@ -760,6 +760,11 @@ impl PluginHost {
|
||||
.filter(|(_, p)| p.dev_root.as_deref() == Some(root))
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect();
|
||||
// Nothing to unload, nothing to announce: `CommandsChanged` makes every window list the
|
||||
// plugins again, and listing restricts an untrusted project again, which looped while idle.
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
for id in ids {
|
||||
self.unload(&id);
|
||||
}
|
||||
|
||||
@@ -565,6 +565,21 @@ impl Host {
|
||||
.collect();
|
||||
matches!(rest.as_slice(), [first, ..] if first == "worktrees" && rest.len() <= 2)
|
||||
});
|
||||
// `git worktree add` writes the worktree's gitfile before its gitdir's
|
||||
// `HEAD`: a rescan in between finds no repository there yet, so that `HEAD`
|
||||
// rescans too while its worktree is unknown and one a rescan would find.
|
||||
git_dirs |= batch.vcs.iter().any(|p| {
|
||||
let Some(gitdir) = p.parent().filter(|_| p.ends_with("HEAD")) else { return false };
|
||||
if !gitdir.parent().is_some_and(|d| d.ends_with(".git/worktrees")) {
|
||||
return false;
|
||||
}
|
||||
// `gitdir` may be relative to itself (`git worktree add --relative-paths`).
|
||||
let worktree = std::fs::read_to_string(gitdir.join("gitdir"))
|
||||
.and_then(|gitfile| dunce::canonicalize(gitdir.join(gitfile.trim())));
|
||||
worktree.ok().as_deref().and_then(Path::parent).is_some_and(|dir| {
|
||||
!known.iter().any(|r| r == dir) && repository_searched(&root, dir, &settings.effective())
|
||||
})
|
||||
});
|
||||
// A repository folder moved or restored into the project: no `.git` event is
|
||||
// written inside it before the watcher sees the new directory, its creation is
|
||||
// the signal. A `git clone` / `git init` inside the project already arrives
|
||||
@@ -1186,18 +1201,34 @@ fn detect_repositories(
|
||||
build_cache: &Path,
|
||||
trusted: bool,
|
||||
) -> IdeResult<Repos> {
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(content_roots(settings, root, build_cache, trusted));
|
||||
Repos::discover_roots(&roots, &repository_scan_skips(settings))
|
||||
}
|
||||
|
||||
/// Folders the search for nested repositories leaves out, besides hidden and dependency ones.
|
||||
fn repository_scan_skips(settings: &ide_core::settings::Settings) -> impl Fn(&Path) -> bool {
|
||||
let ignored = settings.ignored_names();
|
||||
let skip = |p: &Path| {
|
||||
move |p: &Path| {
|
||||
p.file_name().is_some_and(|n| {
|
||||
let name = n.to_string_lossy();
|
||||
ignored.is_ignored_name(&name)
|
||||
|| (ide_workspace::unity::GENERATED_DIRS.contains(&name.as_ref())
|
||||
&& p.parent().is_some_and(ide_workspace::unity::is_project))
|
||||
})
|
||||
};
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(content_roots(settings, root, build_cache, trusted));
|
||||
Repos::discover_roots(&roots, &skip)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a scan of the project at `root` would look for a repository at `dir` and keep it.
|
||||
fn repository_searched(root: &Path, dir: &Path, settings: &ide_core::settings::Settings) -> bool {
|
||||
settings.vcs.git.enabled
|
||||
&& !settings
|
||||
.vcs
|
||||
.mappings
|
||||
.excluded
|
||||
.iter()
|
||||
.any(|p| dunce::canonicalize(VcsMappings::resolve(root, p)).is_ok_and(|e| e == dir))
|
||||
&& Repos::searched(root, dir, &repository_scan_skips(settings))
|
||||
}
|
||||
|
||||
impl Project {
|
||||
|
||||
@@ -8170,3 +8170,20 @@ fn contributes_skills_needs_api_1_15_and_warns_without_failing_plugin_on_bad_ent
|
||||
assert_eq!(dirs.len(), 1);
|
||||
assert!(dirs[0].ends_with("skills/good-skill"), "{dirs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restricting_a_project_without_its_plugins_announces_nothing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let events: Events = Arc::default();
|
||||
let sink = {
|
||||
let events = events.clone();
|
||||
move |client: Option<&str>, e: PluginEvent| events.lock().push((client.map(str::to_owned), e))
|
||||
};
|
||||
let host = PluginHost::new(tmp.path().join("plugins"), Arc::new(sink), Limits::default()).unwrap();
|
||||
host.load_all();
|
||||
events.lock().clear();
|
||||
// A restricted window lists the plugins, which restricts its project again each time.
|
||||
host.restrict_project(tmp.path());
|
||||
host.restrict_project(tmp.path());
|
||||
assert!(!events.lock().iter().any(|(_, e)| matches!(e, PluginEvent::CommandsChanged)));
|
||||
}
|
||||
@@ -28,6 +28,10 @@ struct Fixture {
|
||||
|
||||
impl Fixture {
|
||||
async fn new() -> Self {
|
||||
Self::with_sink(Arc::new(ide_core::NullSink)).await
|
||||
}
|
||||
|
||||
async fn with_sink(sink: ide_core::SharedSink) -> Self {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
@@ -40,7 +44,8 @@ impl Fixture {
|
||||
std::fs::write(root.join("file.txt"), "original\n").unwrap();
|
||||
git(&root, &["add", "."]);
|
||||
git(&root, &["commit", "-m", "original"]);
|
||||
let host = Host::new(common::host_config(&base));
|
||||
let host =
|
||||
Host::new(ide_host::HostConfig { sink_for: Box::new(move |_| sink.clone()), ..common::host_config(&base) });
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
wait_for_repos(&project, 1).await;
|
||||
@@ -278,6 +283,50 @@ async fn watcher_picks_up_a_worktree_added_below_the_project() {
|
||||
assert!(roots.contains(&linked), "watcher did not discover the worktree added below the project: {roots:?}");
|
||||
}
|
||||
|
||||
/// `git worktree add` writes the worktree's gitfile before its gitdir's `commondir` and `HEAD`; a
|
||||
/// slow git lets the watcher rescan in between and find no repository there yet.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn watcher_picks_up_a_worktree_whose_head_is_written_after_a_rescan() {
|
||||
let changes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let counter = changes.clone();
|
||||
let sink: ide_core::SharedSink = Arc::new(move |event: ide_core::IdeEvent| {
|
||||
if matches!(event, ide_core::IdeEvent::VcsChanged { .. }) {
|
||||
counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
});
|
||||
let f = Fixture::with_sink(sink).await;
|
||||
// The watcher reports a batch that rescans only once the rescan is done.
|
||||
let next_change = || {
|
||||
let (changes, seen) = (changes.clone(), changes.load(std::sync::atomic::Ordering::SeqCst));
|
||||
async move {
|
||||
for _ in 0..200 {
|
||||
if changes.load(std::sync::atomic::Ordering::SeqCst) > seen {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
panic!("the watcher reported no change");
|
||||
}
|
||||
};
|
||||
let linked = f.root.join("watched");
|
||||
let gitdir = f.root.join(".git/worktrees/watched");
|
||||
let registered = next_change();
|
||||
std::fs::create_dir_all(&gitdir).unwrap();
|
||||
std::fs::write(gitdir.join("gitdir"), format!("{}\n", linked.join(".git").display())).unwrap();
|
||||
registered.await;
|
||||
let rescanned = next_change();
|
||||
std::fs::create_dir_all(&linked).unwrap();
|
||||
std::fs::write(linked.join(".git"), format!("gitdir: {}\n", gitdir.display())).unwrap();
|
||||
rescanned.await;
|
||||
assert_eq!(f.project.repos().all().len(), 1, "a gitfile without its gitdir's HEAD is no repository yet");
|
||||
std::fs::write(gitdir.join("commondir"), "../..\n").unwrap();
|
||||
// As git does: through a lock file.
|
||||
std::fs::write(gitdir.join("HEAD.lock"), "ref: refs/heads/main\n").unwrap();
|
||||
std::fs::rename(gitdir.join("HEAD.lock"), gitdir.join("HEAD")).unwrap();
|
||||
wait_for_repos(&f.project, 2).await;
|
||||
assert!(f.project.repos().roots().contains(&linked));
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
async fn open(&self, root: &std::path::Path) {
|
||||
self.host.trust.decide(root, true, false).unwrap();
|
||||
|
||||
@@ -227,6 +227,10 @@ pub struct LanguageServerConfig {
|
||||
/// it parses a document.
|
||||
#[serde(default)]
|
||||
pub resync_on_configuration: bool,
|
||||
/// Server-created work-done tokens to ignore, including slash-delimited suffixes.
|
||||
/// Client-created request tokens are handled independently.
|
||||
#[serde(default)]
|
||||
pub ignored_progress_token_prefixes: Vec<String>,
|
||||
/// Set by the settings hook: what the user sees as the server when another program serves
|
||||
/// in its place (TypeScript 7's own `tsc --lsp` for vtsls).
|
||||
#[serde(skip)]
|
||||
|
||||
@@ -909,7 +909,10 @@ mod tests {
|
||||
let cfg = reg.get(&LanguageId::new("php")).unwrap();
|
||||
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
|
||||
// After the fallback: hover, rename and symbols stay with Intelephense.
|
||||
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
|
||||
assert_eq!(names, ["intelephense", "phpantom", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
|
||||
let phpantom = &cfg.language_servers[1];
|
||||
assert!(phpantom.fallback && phpantom.args.is_empty());
|
||||
assert_eq!(phpantom.command, "phpantom_lsp");
|
||||
// Phoxite answers the Laravel strings itself.
|
||||
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
|
||||
assert!(phoxite.fallback && phoxite.replaces == ["laravel-lsp"]);
|
||||
|
||||
@@ -73,6 +73,7 @@ fn server_config() -> LanguageServerConfig {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
|
||||
@@ -151,6 +151,23 @@ impl ClientHandler {
|
||||
}
|
||||
|
||||
fn progress(&self, mgr: &LspManager, params: Value) {
|
||||
if let Some(token) = params["token"].as_str() {
|
||||
if let Some(id) = token.strip_prefix(crate::server::REQUEST_PROGRESS_PREFIX) {
|
||||
if let (Ok(id), Ok(update)) = (id.parse::<u32>(), serde_json::from_value(params["value"].clone())) {
|
||||
self.server.request_progress(mgr.sink(), TaskId(id), update);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self
|
||||
.server
|
||||
.config
|
||||
.ignored_progress_token_prefixes
|
||||
.iter()
|
||||
.any(|prefix| token.strip_prefix(prefix).is_some_and(|rest| rest.is_empty() || rest.starts_with('/')))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
let token = progress_key(¶ms["token"]);
|
||||
let value = ¶ms["value"];
|
||||
let kind = value.get("kind").and_then(Value::as_str);
|
||||
|
||||
@@ -1598,10 +1598,20 @@ impl LspManager {
|
||||
cancel: Option<&CancellationToken>,
|
||||
timeout: Duration,
|
||||
) -> IdeResult<R> {
|
||||
let params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let mut params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
// ImplementationParams accepts an optional client work-done token. Servers
|
||||
// may report on it even when implementationProvider is advertised as `true`.
|
||||
let progress = (method == "textDocument/implementation")
|
||||
.then(|| t.server.track_request_progress(t.run.generation, self.sink(), cancel));
|
||||
let cancel = if let Some(progress) = &progress {
|
||||
params["workDoneToken"] = json!(progress.wire_token());
|
||||
Some(progress.cancel.clone())
|
||||
} else {
|
||||
cancel.cloned()
|
||||
};
|
||||
let stamp = self.injected_request_stamp(¶ms);
|
||||
let fut = async {
|
||||
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel.cloned()).await?;
|
||||
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel).await?;
|
||||
virtual_doc::normalize_uris(&mut value);
|
||||
serde_json::from_value(value).map_err(|e| RpcError::Protocol(format!("{method}: {e}")))
|
||||
};
|
||||
|
||||
@@ -53,10 +53,58 @@ struct State {
|
||||
generation: u64,
|
||||
conn: Conn,
|
||||
restarting: bool,
|
||||
request_progress: HashMap<TaskId, RequestProgressState>,
|
||||
events: VecDeque<IdeEvent>,
|
||||
publishing: bool,
|
||||
}
|
||||
|
||||
pub(crate) const REQUEST_PROGRESS_PREFIX: &str = "openidea/request/";
|
||||
|
||||
struct RequestProgressState {
|
||||
title: Option<String>,
|
||||
message: Option<String>,
|
||||
fraction: Option<f32>,
|
||||
_cancel: ide_core::task::CancelHandle,
|
||||
}
|
||||
|
||||
impl RequestProgressState {
|
||||
fn event(&self, id: TaskId, done: bool) -> Option<IdeEvent> {
|
||||
Some(IdeEvent::Task {
|
||||
id,
|
||||
title: self.title.clone()?,
|
||||
message: self.message.clone(),
|
||||
fraction: self.fraction,
|
||||
done,
|
||||
cancellable: !done,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Progress provided to an LSP request. Dropping the request always retires its token.
|
||||
pub(crate) struct RequestProgress<'a> {
|
||||
id: TaskId,
|
||||
server: &'a Server,
|
||||
sink: &'a SharedSink,
|
||||
pub(crate) cancel: CancellationToken,
|
||||
}
|
||||
|
||||
impl RequestProgress<'_> {
|
||||
pub(crate) fn wire_token(&self) -> String {
|
||||
format!("{REQUEST_PROGRESS_PREFIX}{}", self.id.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RequestProgress<'_> {
|
||||
fn drop(&mut self) {
|
||||
let mut st = self.server.state.lock();
|
||||
if let Some(progress) = st.request_progress.remove(&self.id) {
|
||||
st.events.extend(progress.event(self.id, true));
|
||||
}
|
||||
drop(st);
|
||||
self.server.publish(self.sink);
|
||||
}
|
||||
}
|
||||
|
||||
/// A file opened on the server by the client itself (not by the user) for the
|
||||
/// duration of a request, e.g. to widen a references search.
|
||||
struct Transient {
|
||||
@@ -172,6 +220,7 @@ impl Server {
|
||||
generation: 0,
|
||||
conn: Conn::Idle,
|
||||
restarting: false,
|
||||
request_progress: HashMap::new(),
|
||||
events: VecDeque::new(),
|
||||
publishing: false,
|
||||
}),
|
||||
@@ -552,6 +601,9 @@ impl Server {
|
||||
|
||||
fn queue_cleanup(&self, st: &mut State) {
|
||||
*self.initializing.lock() = None;
|
||||
for (id, progress) in st.request_progress.drain() {
|
||||
st.events.extend(progress.event(id, true));
|
||||
}
|
||||
for (id, title) in self.take_progress() {
|
||||
st.events.push_back(IdeEvent::Task {
|
||||
id,
|
||||
@@ -572,6 +624,61 @@ impl Server {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn track_request_progress<'a>(
|
||||
&'a self,
|
||||
generation: u64,
|
||||
sink: &'a SharedSink,
|
||||
parent_cancel: Option<&CancellationToken>,
|
||||
) -> RequestProgress<'a> {
|
||||
let id = TaskId::next();
|
||||
let cancel = parent_cancel.map(CancellationToken::child_token).unwrap_or_default();
|
||||
let mut st = self.state.lock();
|
||||
if st.generation == generation && matches!(st.conn, Conn::Ready(_)) {
|
||||
let token = cancel.clone();
|
||||
st.request_progress.insert(
|
||||
id,
|
||||
RequestProgressState {
|
||||
title: None,
|
||||
message: None,
|
||||
fraction: None,
|
||||
_cancel: ide_core::task::on_cancel(id, move || token.cancel()),
|
||||
},
|
||||
);
|
||||
}
|
||||
RequestProgress { id, server: self, sink, cancel }
|
||||
}
|
||||
|
||||
pub(crate) fn request_progress(&self, sink: &SharedSink, id: TaskId, update: lsp::WorkDoneProgress) {
|
||||
let mut st = self.state.lock();
|
||||
let Some(progress) = st.request_progress.get_mut(&id) else { return };
|
||||
let fraction = |p: u32| p.min(100) as f32 / 100.0;
|
||||
let event = match update {
|
||||
lsp::WorkDoneProgress::Begin(begin) => {
|
||||
progress.title = Some(begin.title);
|
||||
progress.message = begin.message;
|
||||
progress.fraction = begin.percentage.map(fraction);
|
||||
progress.event(id, false)
|
||||
}
|
||||
lsp::WorkDoneProgress::Report(report) => {
|
||||
progress.message = report.message.or_else(|| progress.message.take());
|
||||
progress.fraction = report.percentage.map(fraction).or(progress.fraction);
|
||||
progress.event(id, false)
|
||||
}
|
||||
lsp::WorkDoneProgress::End(end) => {
|
||||
progress.message = end.message.or_else(|| progress.message.take());
|
||||
progress.fraction = Some(1.0);
|
||||
let event = progress.event(id, true);
|
||||
st.request_progress.remove(&id);
|
||||
event
|
||||
}
|
||||
};
|
||||
// Queue under the state lock so a reply or cancellation can't publish `done`
|
||||
// before a concurrent progress update and leave a stale row.
|
||||
st.events.extend(event);
|
||||
drop(st);
|
||||
self.publish(sink);
|
||||
}
|
||||
|
||||
pub fn emit(&self, sink: &SharedSink, event: IdeEvent) {
|
||||
self.state.lock().events.push_back(event);
|
||||
self.publish(sink);
|
||||
|
||||
@@ -277,6 +277,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
@@ -2225,6 +2226,54 @@ async fn a_progress_token_begun_again_ends_the_task_it_replaces() {
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn toml_progress_quirk_ignores_server_tokens_left_open_after_cancel() {
|
||||
let registry = LanguageRegistry::load(None).unwrap();
|
||||
let php = registry.get(&LanguageId::new("php")).unwrap();
|
||||
let quirk = &php.language_servers.iter().find(|s| s.name == "phpantom").unwrap().ignored_progress_token_prefixes;
|
||||
let h = harness_configured("php", "php", &[("mock", incremental_caps())], |cfg| {
|
||||
cfg.ignored_progress_token_prefixes = quirk.clone();
|
||||
});
|
||||
let (doc, path) = h.open("a.php", "<?php target();");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let server = h.launcher.state("mock");
|
||||
let peer = server.peer();
|
||||
let progress = |token, kind, title| {
|
||||
peer.notify("$/progress", json!({ "token": token, "value": { "kind": kind, "title": title } })).unwrap();
|
||||
};
|
||||
let method = "textDocument/references";
|
||||
let search = || h.mgr.references_streaming(doc, Pos::new(0, 7), true, false, true, Default::default(), None);
|
||||
|
||||
progress("find_references/1", "begin", "Find References");
|
||||
progress("find_references", "begin", "Find References");
|
||||
progress("goto_implementation/1", "begin", "Go to Implementation");
|
||||
progress("find_references_index/1", "begin", "Indexing");
|
||||
h.wait_status("mock", ServerStatus::Busy).await;
|
||||
server.errors.lock().insert(method.into(), (-32800, "Canceled".into()));
|
||||
assert_eq!(search().await.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
|
||||
|
||||
server.errors.lock().remove(method);
|
||||
server.respond(
|
||||
method,
|
||||
json!([{
|
||||
"uri": uri_of(&path),
|
||||
"range": { "start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 12 } }
|
||||
}]),
|
||||
);
|
||||
progress("find_references/2", "begin", "Find References");
|
||||
assert_eq!(search().await.unwrap().locations.len(), 1);
|
||||
progress("find_references/2", "end", "Find References");
|
||||
progress("find_references_index/1", "end", "Indexing");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
|
||||
let events = h.events.lock();
|
||||
assert!(!events.iter().any(
|
||||
|e| matches!(e, IdeEvent::Task { title, .. } if title == "Find References" || title == "Go to Implementation")
|
||||
));
|
||||
assert!(events.iter().any(|e| matches!(e, IdeEvent::Task { title, done: false, .. } if title == "Indexing")));
|
||||
assert!(events.iter().any(|e| matches!(e, IdeEvent::Task { title, done: true, .. } if title == "Indexing")));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replacing_progress_keeps_cancellation_reports_and_indexing_on_the_new_task() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
@@ -4239,6 +4288,118 @@ async fn implementations_per_position() {
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn implementation_progress_ends_on_cancel_without_server_end() {
|
||||
implementation_progress_ends_with_request(false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn implementation_progress_ends_on_timeout_without_server_end() {
|
||||
implementation_progress_ends_with_request(true).await;
|
||||
}
|
||||
|
||||
async fn implementation_progress_ends_with_request(timeout: bool) {
|
||||
let caps = json!({ "textDocumentSync": 1, "implementationProvider": true });
|
||||
let h = harness_for("php", "php", &[("mock", caps)], &[]);
|
||||
let (doc, path) = h.open("a.php", "<?php\ninterface A {}\nclass B implements A {}\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let server = h.launcher.state("mock");
|
||||
let method = "textDocument/implementation";
|
||||
let gate = Arc::new(Gate::default());
|
||||
let uri = uri_of(&path);
|
||||
*server.responder.lock() =
|
||||
Some(Arc::new({
|
||||
let gate = gate.clone();
|
||||
move |server, requested, params| {
|
||||
if requested != method {
|
||||
return None;
|
||||
}
|
||||
let token = ¶ms["workDoneToken"];
|
||||
let peer = server.peer();
|
||||
peer.notify("$/progress", json!({
|
||||
"token": token, "value": { "kind": "begin", "title": "Go to Implementation", "cancellable": false }
|
||||
})).unwrap();
|
||||
if params["position"]["character"] == 10 {
|
||||
peer.notify(
|
||||
"$/progress",
|
||||
json!({
|
||||
"token": token, "value": { "kind": "report", "percentage": 88 }
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
gate.hold();
|
||||
}
|
||||
// The mock answers without sending `end`.
|
||||
Some(json!([{
|
||||
"uri": uri,
|
||||
"range": { "start": { "line": 2, "character": 6 }, "end": { "line": 2, "character": 7 } }
|
||||
}]))
|
||||
}
|
||||
}));
|
||||
|
||||
let mgr = h.mgr.clone();
|
||||
let batch = tokio::spawn(async move {
|
||||
mgr.implementations(doc, &[Pos::new(1, 10), Pos::new(2, 6)], Default::default()).await.unwrap()
|
||||
});
|
||||
let task_events = || {
|
||||
h.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::Task { id, title, done, fraction, cancellable, .. } if title == "Go to Implementation" => {
|
||||
Some((*id, *done, *fraction, *cancellable))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
eventually(|| {
|
||||
let events = task_events();
|
||||
gate.entered() && events.iter().any(|e| e.2 == Some(0.88)) && events.iter().any(|(_, done, _, _)| *done)
|
||||
})
|
||||
.await;
|
||||
let scanning = task_events().into_iter().find(|e| e.2 == Some(0.88)).expect("scan reported 88%");
|
||||
let (task, _, _, cancellable) = scanning;
|
||||
assert!(cancellable);
|
||||
assert!(!task_events().iter().any(|(id, done, _, _)| *id == task && *done));
|
||||
let requests = server.requested(method);
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert_ne!(requests[0]["workDoneToken"], requests[1]["workDoneToken"]);
|
||||
|
||||
if timeout {
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(31)).await;
|
||||
tokio::time::resume();
|
||||
} else {
|
||||
assert!(ide_core::task::cancel(task));
|
||||
}
|
||||
let found = batch.await.unwrap();
|
||||
gate.open();
|
||||
eventually(|| !server.notified("$/cancelRequest").is_empty()).await;
|
||||
assert!(found[0].is_empty());
|
||||
assert_eq!(found[1][0].range.start.line, 2);
|
||||
assert!(!ide_core::task::cancel(task));
|
||||
assert_eq!(task_events().iter().filter(|(id, done, _, _)| *id == task && *done).count(), 1);
|
||||
|
||||
// Late progress for either retired token must not bring back its task.
|
||||
let before = task_events();
|
||||
let peer = server.peer();
|
||||
for request in requests {
|
||||
peer.notify(
|
||||
"$/progress",
|
||||
json!({
|
||||
"token": request["workDoneToken"], "value": { "kind": "begin", "title": "Go to Implementation" }
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
peer.notify("$/progress", json!({ "token": "index", "value": { "kind": "begin", "title": "Indexing" } })).unwrap();
|
||||
h.wait_status("mock", ServerStatus::Busy).await;
|
||||
assert_eq!(task_events(), before);
|
||||
peer.notify("$/progress", json!({ "token": "index", "value": { "kind": "end" } })).unwrap();
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn java_implementations_come_from_sources_first() {
|
||||
let caps = json!({
|
||||
|
||||
@@ -428,6 +428,7 @@ async fn missing_binary_is_reported_with_install_hint() {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
};
|
||||
@@ -721,6 +722,7 @@ async fn typescript_language_server_end_to_end() {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
};
|
||||
@@ -775,6 +777,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
|
||||
@@ -1811,6 +1811,7 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ pub(crate) fn server(name: &str) -> LanguageServerConfig {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
|
||||
@@ -681,6 +681,28 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://github.com/laravel/lsp",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "phpantom",
|
||||
display: "PHPantom",
|
||||
kind: LanguageServer,
|
||||
commands: &["phpantom_lsp"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "PHPantom-dev/phpantom_lsp" },
|
||||
assets: &[
|
||||
rule(Mac, Arm64, "phpantom_lsp-aarch64-apple-darwin.tar.gz"),
|
||||
rule(Mac, X64, "phpantom_lsp-x86_64-apple-darwin.tar.gz"),
|
||||
rule(Linux, Arm64, "phpantom_lsp-aarch64-unknown-linux-gnu.tar.gz"),
|
||||
rule(Linux, X64, "phpantom_lsp-x86_64-unknown-linux-gnu.tar.gz"),
|
||||
rule(Windows, Arm64, "phpantom_lsp-aarch64-pc-windows-msvc.zip"),
|
||||
rule(Windows, X64, "phpantom_lsp-x86_64-pc-windows-msvc.zip"),
|
||||
],
|
||||
locate: &["phpantom_lsp"],
|
||||
},
|
||||
fallback: None,
|
||||
version: ver("phpantom_lsp"),
|
||||
homepage: "https://github.com/PHPantom-dev/phpantom_lsp",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "phoxite",
|
||||
display: "Phoxite",
|
||||
|
||||
@@ -190,6 +190,7 @@ fn everything_missing_on_an_empty_system() {
|
||||
#[test]
|
||||
fn interchangeable_servers_list_their_alternatives() {
|
||||
let env = Env::new();
|
||||
env.script(&env.sys, "curl", "exit 1");
|
||||
let list = env.tools().list(&langs());
|
||||
let python = ["basedpyright", "pyright", "ty", "pyrefly"];
|
||||
for name in python {
|
||||
@@ -203,6 +204,13 @@ fn interchangeable_servers_list_their_alternatives() {
|
||||
for name in ["kotlin-lsp", "kotlin-language-server"] {
|
||||
assert_eq!(find(&list, name).alternatives, ["kotlin-lsp", "kotlin-language-server", "kmp-lsp"]);
|
||||
}
|
||||
let php = ["intelephense", "phpantom", "phpactor", "phoxite", "devsense-php-ls"];
|
||||
for name in php {
|
||||
assert_eq!(find(&list, name).alternatives, php);
|
||||
}
|
||||
let phpantom = find(&list, "phpantom");
|
||||
assert!(phpantom.can_install, "{:?}", phpantom.unavailable_reason);
|
||||
assert!(find(&list, "laravel-lsp").alternatives.is_empty());
|
||||
// A regular server after a fallback starts no group with it.
|
||||
assert!(find(&list, "angular-language-server").alternatives.is_empty());
|
||||
assert!(find(&list, "ruff").alternatives.is_empty());
|
||||
|
||||
@@ -15,6 +15,12 @@ const MAX_DEPTH: usize = 4;
|
||||
/// Folders never searched for nested repositories (dependencies, build output).
|
||||
const SKIPPED: &[&str] = &["node_modules", "target", "build", "dist", "out", "vendor", "venv", "__pycache__"];
|
||||
|
||||
/// A folder the nested-repository search neither looks at nor descends into.
|
||||
fn not_searched(path: &Path, skip: &dyn Fn(&Path) -> bool) -> bool {
|
||||
let name = path.file_name().map(|n| n.to_string_lossy()).unwrap_or_default();
|
||||
name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(path)
|
||||
}
|
||||
|
||||
/// The repositories of a project, sorted by root; lookups pick the innermost one.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Repos {
|
||||
@@ -46,6 +52,18 @@ impl Repos {
|
||||
Ok(Self { repos, primary })
|
||||
}
|
||||
|
||||
/// Whether [`Self::discover`] from `project_root` looks for a repository at `dir`, below it.
|
||||
pub fn searched(project_root: &Path, dir: &Path, skip: &dyn Fn(&Path) -> bool) -> bool {
|
||||
let Ok(rel) = dir.strip_prefix(project_root) else { return false };
|
||||
let depth = rel.components().count();
|
||||
let mut path = project_root.to_path_buf();
|
||||
(1..=MAX_DEPTH).contains(&depth)
|
||||
&& rel.components().all(|c| {
|
||||
path.push(c);
|
||||
!not_searched(&path, skip)
|
||||
})
|
||||
}
|
||||
|
||||
/// The repository containing `project_root` and every repository whose worktree
|
||||
/// root lies below it (up to [`MAX_DEPTH`] levels; hidden and dependency folders and
|
||||
/// folders `skip` rejects are not searched).
|
||||
@@ -61,10 +79,8 @@ impl Repos {
|
||||
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
let path = entry.path();
|
||||
if name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(&path) {
|
||||
if not_searched(&path, skip) {
|
||||
continue;
|
||||
}
|
||||
if path.join(".git").exists()
|
||||
@@ -350,6 +366,24 @@ mod tests {
|
||||
assert!(ok, "git {args:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn searched_matches_what_discover_finds() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
git_init(&root);
|
||||
let dirs = ["a", "a/b/c/d", "a/b/c/d/e", ".hidden/x", "vendor/x", "skipped/x", "a/skipped/x"];
|
||||
for dir in dirs {
|
||||
git_init(&root.join(dir));
|
||||
}
|
||||
let skip = |p: &Path| p.file_name().is_some_and(|n| n == "skipped");
|
||||
let found = Repos::discover(&root, &skip).unwrap().roots();
|
||||
for dir in dirs {
|
||||
let dir = root.join(dir);
|
||||
assert_eq!(Repos::searched(&root, &dir, &skip), found.contains(&dir), "{}", dir.display());
|
||||
}
|
||||
assert!(!Repos::searched(&root, &root, &skip), "the project root itself is no nested repository");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignored_files_use_git_rules_without_listing_other_repositories_twice() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -51,6 +51,60 @@ test("suggests and configures a project-scoped GitHub account in Settings › Ve
|
||||
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]);
|
||||
});
|
||||
|
||||
test("Update failure offers project-scoped GitHub account selection", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
let configuredAccount = "";
|
||||
const status = (): GhProjectAccountStatus => ({
|
||||
ghInstalled: true,
|
||||
accounts: [
|
||||
{ login: "alice", active: true },
|
||||
{ login: "alice-work", active: false },
|
||||
],
|
||||
configuredAccount,
|
||||
effectiveAccount: configuredAccount || "alice",
|
||||
suggestedAccount: configuredAccount ? null : "alice-work",
|
||||
});
|
||||
Object.assign(window.__ipc.handlers, {
|
||||
vcs_branch_info: () => ({ head: "main", upstream: "origin/main", headCommit: "c1", operation: null }),
|
||||
vcs_remote: () => {
|
||||
throw {
|
||||
kind: "invalid",
|
||||
message: "remote: Repository not found.\nfatal: repository 'https://github.com/acme/private.git/' not found",
|
||||
};
|
||||
},
|
||||
gh_project_account_status: () => status(),
|
||||
gh_set_project_account: ({ account }: { account: string }) => {
|
||||
configuredAccount = account;
|
||||
return status();
|
||||
},
|
||||
settings_get_global: () => ({}),
|
||||
window_open_settings: () => {
|
||||
throw { kind: "unavailable", message: "separate settings window disabled in browser test" };
|
||||
},
|
||||
});
|
||||
const opsModule = "/src/features/vcs/ops.ts";
|
||||
const { runRemote } = await import(/* @vite-ignore */ opsModule);
|
||||
await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/dev/acme-api"]);
|
||||
});
|
||||
|
||||
await expect(page.getByText("Update failed", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText(/Repository not found/)).toBeVisible();
|
||||
await expect(page.getByText(/alice may not have access/)).toBeVisible();
|
||||
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([]);
|
||||
const settingsLink = page.getByRole("button", { name: "GitHub Settings", exact: true });
|
||||
await expect(settingsLink).toBeVisible();
|
||||
if (process.env.CAPTURE_GH_AUTH_FAILURE) {
|
||||
await page.screenshot({ path: process.env.CAPTURE_GH_AUTH_FAILURE, animations: "disabled" });
|
||||
}
|
||||
await settingsLink.click();
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("Automatic (alice)");
|
||||
await dialog.getByRole("button", { name: "Use alice-work for this project" }).click();
|
||||
await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("alice-work");
|
||||
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]);
|
||||
});
|
||||
|
||||
test("adds a GitHub account in Settings › Version Control › GitHub with OAuth device-code banner", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
|
||||
@@ -63,14 +63,13 @@ test("Shelf keeps patch and file selection available in a narrow dock", async ({
|
||||
const location = panel.getByText(directory, { exact: true });
|
||||
await expect.poll(() => location.evaluate((el) => el.clientWidth)).toBeGreaterThan(100);
|
||||
|
||||
const divider = panel.getByRole("separator", { name: "Resize shelf panes" });
|
||||
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
|
||||
const files = panel.getByRole("tree", { name: "Shelved files" });
|
||||
await expect(files.getByRole("treeitem")).toHaveCount(2);
|
||||
const pathBox = (await location.boundingBox())!;
|
||||
const filesBox = (await files.boundingBox())!;
|
||||
expect(pathBox.x).toBeLessThan(filesBox.x + filesBox.width - 50);
|
||||
const files = patches;
|
||||
await expect(patches.getByRole("treeitem").filter({ hasText: filename })).toHaveCount(1);
|
||||
const row = files.getByRole("treeitem").filter({ hasText: filename });
|
||||
const nameBox = (await row.getByText(filename, { exact: true }).boundingBox())!;
|
||||
const pathBox = (await location.boundingBox())!;
|
||||
expect(pathBox.x).toBeGreaterThan(nameBox.x + nameBox.width);
|
||||
expect(Math.abs(pathBox.y + pathBox.height - nameBox.y - nameBox.height)).toBeLessThan(3);
|
||||
await row.click({ position: { x: 90, y: 12 } });
|
||||
await expect(row).toHaveAttribute("aria-selected", "true");
|
||||
await panel.getByRole("button", { name: "Unshelve…", exact: true }).click();
|
||||
@@ -81,13 +80,9 @@ test("Shelf keeps patch and file selection available in a narrow dock", async ({
|
||||
await expect(dialog.getByText("README.md", { exact: true })).toHaveCount(0);
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const dock = "/src/workbench/toolwindows/store.ts";
|
||||
(await import(/* @vite-ignore */ dock)).setToolWindowSize("left", 640);
|
||||
});
|
||||
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
|
||||
await expect(row).toHaveAttribute("aria-selected", "true");
|
||||
await patches.getByRole("treeitem").filter({ hasText: "Update release notes" }).click();
|
||||
await expect(files.getByRole("treeitem")).toHaveCount(1);
|
||||
const other = patches.getByRole("treeitem").filter({ hasText: "Update release notes" });
|
||||
await other.click();
|
||||
if ((await other.getAttribute("aria-expanded")) === "false") await page.keyboard.press("ArrowRight");
|
||||
await expect(files.getByText("CHANGELOG.md", { exact: true })).toBeVisible();
|
||||
});
|
||||
@@ -17,6 +17,16 @@ install-hint = "npm i -g intelephense"
|
||||
# Intelephense applies the PHP version only to documents it parses after reading it.
|
||||
resync-on-configuration = true
|
||||
|
||||
[[language-servers]]
|
||||
name = "phpantom"
|
||||
# PHPantom 1.1.0 can cancel these operations without ending server-created progress.
|
||||
ignored-progress-token-prefixes = ["find_references", "goto_implementation"]
|
||||
fallback = true
|
||||
command = "phpantom_lsp"
|
||||
args = []
|
||||
root-markers = ["composer.json", "index.php"]
|
||||
install-hint = "Install PHPantom in Settings › Languages & Frameworks › Language Servers"
|
||||
|
||||
[[language-servers]]
|
||||
name = "phpactor"
|
||||
# Alternative: used only when the server above is not installed.
|
||||
|
||||
@@ -2,7 +2,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Diagnostic, FileProblems } from "@/bindings";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
trusted: true as boolean | undefined,
|
||||
projectChanged: () => {},
|
||||
trustChanged: () => {},
|
||||
remoteChanged: () => {},
|
||||
report: vi.fn(),
|
||||
}));
|
||||
@@ -20,9 +22,11 @@ vi.mock("@/platform/ipc", async (importOriginal) => ({
|
||||
|
||||
vi.mock("@/platform/project", () => ({
|
||||
useProject: {
|
||||
getState: () => ({ project: { root: "/p" } }),
|
||||
getState: () => ({ project: { root: "/p", trusted: state.trusted } }),
|
||||
subscribe: (fn: (s: unknown, prev: unknown) => void) => {
|
||||
state.projectChanged = () => fn({ project: { root: "/p" } }, { project: null });
|
||||
state.trustChanged = () =>
|
||||
fn({ project: { root: "/p", trusted: true } }, { project: { root: "/p", trusted: false } });
|
||||
return () => {};
|
||||
},
|
||||
},
|
||||
@@ -58,6 +62,7 @@ describe("reportProblems", () => {
|
||||
clearProblems();
|
||||
reports.length = 0;
|
||||
state.report.mockReset();
|
||||
state.trusted = true;
|
||||
applyDiagnosticsEvent("/p/a.rs", "ra", [d(1), d(2)]);
|
||||
stop = reportProblems();
|
||||
});
|
||||
@@ -76,6 +81,20 @@ describe("reportProblems", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports nothing without a retry timer in a restricted project, then once when trusted", async () => {
|
||||
stop();
|
||||
state.trusted = false;
|
||||
reports.length = 0;
|
||||
stop = reportProblems();
|
||||
await vi.advanceTimersByTimeAsync(5000);
|
||||
expect(reports).toHaveLength(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
state.trusted = true;
|
||||
state.trustChanged();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(summary()).toEqual([[true, [["/p/a.rs", 2]]]]);
|
||||
});
|
||||
|
||||
it("retries a failed delta with the full snapshot", async () => {
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
state.report.mockRejectedValueOnce(new Error("disconnected"));
|
||||
|
||||
@@ -13,7 +13,9 @@ export function reportProblems(): () => void {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
const flush = () => {
|
||||
timer = null;
|
||||
if (!useProject.getState().project) return;
|
||||
const project = useProject.getState().project;
|
||||
// Restricted Mode refuses this command; the trust change below resets and reschedules.
|
||||
if (!project || project.trusted === false) return;
|
||||
const map = useProblems.getState().map;
|
||||
const files: FileProblems[] = [];
|
||||
for (const [path, sources] of map)
|
||||
@@ -37,7 +39,7 @@ export function reportProblems(): () => void {
|
||||
if (s.map !== prev.map) schedule();
|
||||
});
|
||||
const offProject = useProject.subscribe((s, prev) => {
|
||||
if (s.project?.root !== prev.project?.root) {
|
||||
if (s.project?.root !== prev.project?.root || s.project?.trusted !== prev.project?.trusted) {
|
||||
reset = true;
|
||||
reported = new Map();
|
||||
schedule();
|
||||
|
||||
@@ -42,7 +42,9 @@ export function activate(): () => void {
|
||||
const report = () => {
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = null;
|
||||
if (!useProject.getState().project) return;
|
||||
const project = useProject.getState().project;
|
||||
// Restricted Mode refuses these commands; the trust change below reschedules the report.
|
||||
if (!project || project.trusted === false) return;
|
||||
const paths = openEditorPaths();
|
||||
const editor = activeEditor();
|
||||
const focused = document.hasFocus();
|
||||
|
||||
@@ -181,6 +181,27 @@ describe("MCP editor reports", () => {
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
expect(state.uiReady).toHaveBeenCalledWith(true);
|
||||
});
|
||||
it("sends no editor reports and runs no retry timer in a restricted project", async () => {
|
||||
stop();
|
||||
state.trusted = false;
|
||||
state.reportOpen.mockClear();
|
||||
state.reportFocused.mockClear();
|
||||
stop = activate();
|
||||
await vi.advanceTimersByTimeAsync(5000);
|
||||
expect(state.reportOpen).not.toHaveBeenCalled();
|
||||
expect(state.reportFocused).not.toHaveBeenCalled();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
state.trusted = true;
|
||||
state.trustChanged();
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
expect(state.reportOpen).toHaveBeenCalledTimes(1);
|
||||
expect(state.reportFocused).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("retries a failed editor report in a trusted project", async () => {
|
||||
state.reportOpen.mockRejectedValueOnce(new Error("disconnected"));
|
||||
await vi.advanceTimersByTimeAsync(600);
|
||||
expect(state.reportOpen).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("forwards remote editor reports and stops after disposal", async () => {
|
||||
state.remote = true;
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
|
||||
@@ -12,18 +12,9 @@
|
||||
|
||||
.fileText {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.filesHeader {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: var(--h-compact-header);
|
||||
padding-inline: var(--space-2);
|
||||
border-bottom: 1px solid var(--border);
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
align-items: baseline;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.detail {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { BranchInfo, FetchReport, PushReport, RemoteOp } from "@/bindings";
|
||||
import type { BranchInfo, FetchReport, GhProjectAccountStatus, PushReport, RemoteOp } from "@/bindings";
|
||||
|
||||
let branch: Partial<BranchInfo> = {};
|
||||
/** What a pull brings in: the head moves to `c2`, with these changed files and commits. */
|
||||
@@ -10,6 +10,7 @@ let reports: Record<string, PushReport | FetchReport> = {};
|
||||
let partialReport: PushReport | null = null;
|
||||
let remoteGate: Promise<void> | null = null;
|
||||
let remoteRepos: Array<string | null> = [];
|
||||
const ghAccountStatus = vi.fn();
|
||||
|
||||
vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@tauri-apps/api/core")>()),
|
||||
@@ -51,6 +52,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
vcsDiffRevisions: async () => ({ status: "ok", data: Array.from({ length: pulled.files }, (_, i) => ({ i })) }),
|
||||
vcsLog: async () => ({ status: "ok", data: Array.from({ length: pulled.commits }, (_, i) => ({ i })) }),
|
||||
vcsFinishShelfBatch: async () => ({ status: "ok", data: null }),
|
||||
ghProjectAccountStatus: () => ghAccountStatus(),
|
||||
cancelRequest: async () => ({ status: "ok", data: null }),
|
||||
},
|
||||
};
|
||||
@@ -73,11 +75,13 @@ import {
|
||||
import { pushTargets } from "../remoteUi";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
type Note = { title: string; level: string; body?: string };
|
||||
type Note = { title: string; level: string; body?: string; actions?: Array<{ label: string; run: () => void }> };
|
||||
let notes: Note[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
notes = [];
|
||||
ghAccountStatus.mockReset();
|
||||
ghAccountStatus.mockResolvedValue({ status: "ok", data: null });
|
||||
provideNotificationService({ notify: (n) => void notes.push(n as Note), expire: () => {} });
|
||||
});
|
||||
|
||||
@@ -101,6 +105,108 @@ const pushTitle = async () => {
|
||||
return notes.at(-1)!.title;
|
||||
};
|
||||
|
||||
describe("GitHub HTTPS authentication failure", () => {
|
||||
const message =
|
||||
"remote: Repository not found.\nfatal: repository 'https://github.com/example/private.git/' not found";
|
||||
const multiAccount: GhProjectAccountStatus = {
|
||||
ghInstalled: true,
|
||||
accounts: [
|
||||
{ login: "personal", active: true },
|
||||
{ login: "work", active: false },
|
||||
],
|
||||
configuredAccount: "",
|
||||
effectiveAccount: "personal",
|
||||
suggestedAccount: "work",
|
||||
};
|
||||
|
||||
it("preserves the Git error and opens project GitHub settings without changing accounts", async () => {
|
||||
failure = { kind: "invalid", message };
|
||||
ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount });
|
||||
const settings = vi.fn();
|
||||
const unregister = registerActions([{ id: "file.settings", title: "Settings", run: settings }]);
|
||||
try {
|
||||
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
|
||||
const note = notes.at(-1)!;
|
||||
expect(note.title).toBe("Update failed");
|
||||
expect(note.body).toContain(message);
|
||||
expect(note.body).toContain("personal may not have access");
|
||||
expect(ghAccountStatus).toHaveBeenCalledTimes(1);
|
||||
expect(settings).not.toHaveBeenCalled();
|
||||
expect(remoteRepos).toEqual(["/p"]);
|
||||
note.actions?.find((action) => action.label === "GitHub Settings")?.run();
|
||||
await vi.waitFor(() => expect(settings).toHaveBeenCalledWith(expect.objectContaining({ arg: "vcs.github" })));
|
||||
} finally {
|
||||
unregister();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
"fatal: repository 'https://gitlab.com/example/private.git/' not found",
|
||||
"fatal: repository 'https://github.com.evil.example/private.git/' not found",
|
||||
"fatal: repository '[email protected]:example/private.git' not found",
|
||||
"remote: Repository not found.",
|
||||
"fatal: unable to access 'https://github.com/example/private.git/': Could not resolve host: github.com",
|
||||
])("does not check gh for unrelated errors: %s", async (message) => {
|
||||
failure = { kind: "invalid", message };
|
||||
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
|
||||
expect(ghAccountStatus).not.toHaveBeenCalled();
|
||||
expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message });
|
||||
});
|
||||
|
||||
it("keeps the original failure when only one account is signed in", async () => {
|
||||
failure = { kind: "invalid", message };
|
||||
ghAccountStatus.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: { ...multiAccount, accounts: multiAccount.accounts.slice(0, 1) },
|
||||
});
|
||||
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
|
||||
expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message, actions: undefined });
|
||||
});
|
||||
|
||||
it("keeps the original failure when account detection is unavailable", async () => {
|
||||
failure = { kind: "invalid", message };
|
||||
ghAccountStatus.mockRejectedValue(new Error("gh unavailable"));
|
||||
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
|
||||
expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message, actions: undefined });
|
||||
});
|
||||
|
||||
it("offers the same guidance for push failures without retrying", async () => {
|
||||
failure = { kind: "invalid", message };
|
||||
ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount });
|
||||
expect(
|
||||
await pushTargets([
|
||||
{
|
||||
repo: "/p",
|
||||
op: {
|
||||
op: "pushSelected",
|
||||
selection: { branch: "main", revision: null, remote: "origin", target: "main" },
|
||||
force_with_lease: false,
|
||||
set_upstream: false,
|
||||
tags: null,
|
||||
no_verify: false,
|
||||
},
|
||||
},
|
||||
]),
|
||||
).toBe(false);
|
||||
expect(notes.at(-1)).toMatchObject({
|
||||
title: "Push failed",
|
||||
body: expect.stringContaining("personal may not have access"),
|
||||
actions: [expect.objectContaining({ label: "GitHub Settings" })],
|
||||
});
|
||||
expect(remoteRepos).toEqual(["/p"]);
|
||||
});
|
||||
|
||||
it("offers the same guidance for fetch authentication failures", async () => {
|
||||
failure = {
|
||||
kind: "invalid",
|
||||
message: "fatal: Authentication failed for 'https://github.com/example/private.git/'",
|
||||
};
|
||||
ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount });
|
||||
expect(await runRemote({ op: "fetch" }, undefined, ["/p"])).toBe(false);
|
||||
expect(notes.at(-1)?.actions?.map(({ label }) => label)).toEqual(["Show Git Console", "GitHub Settings"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetch result notification", () => {
|
||||
it("keeps successful remotes and pruned refs visible when other remotes fail", async () => {
|
||||
const showConsole = vi.fn();
|
||||
|
||||
@@ -80,6 +80,8 @@ beforeEach(() => {
|
||||
mocks.patch.mockResolvedValue(null);
|
||||
useVcs.setState({ root: "/repo", roots: [], repo: null, available: false, status: [] });
|
||||
useCommit.setState({ selectedShelf: "work\u0000a.txt" });
|
||||
localStorage.removeItem("openidea.vcs.shelf.groupByDir");
|
||||
localStorage.removeItem("openidea.vcs.shelf.diffPreview");
|
||||
useShelf.setState({ shelves: [entry], loaded: true, diffs: { work: diffs } });
|
||||
mocks.ipc.mockResolvedValueOnce([entry]).mockResolvedValue(diffs);
|
||||
});
|
||||
@@ -287,6 +289,62 @@ describe("shelf scope and diffs", () => {
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: "Copy as Patch to Clipboard" }));
|
||||
expect(mocks.execute).toHaveBeenCalledWith("vcs.shelf.copyPatch", { id: "work", path: "a.txt" });
|
||||
});
|
||||
it("deletes the selected shelf with the Delete key", async () => {
|
||||
useShelf.setState({ shelves: [entry] });
|
||||
useCommit.setState({ selectedShelf: "work" });
|
||||
render(<ShelfPanel />);
|
||||
await waitFor(() => expect(screen.getByText("Work")).toBeTruthy());
|
||||
fireEvent.keyDown(screen.getByRole("tree"), { key: "Delete" });
|
||||
expect(mocks.execute).toHaveBeenCalledWith("vcs.shelf.delete", { id: "work", path: undefined });
|
||||
});
|
||||
|
||||
it("groups shelved files by directory and exposes preview and tree controls", async () => {
|
||||
const grouped: ShelvedChangeList = {
|
||||
...entry,
|
||||
files: [
|
||||
{ path: "src/a.txt", kind: "modified", oldPath: null },
|
||||
{ path: "src/nested/b.txt", kind: "added", oldPath: null },
|
||||
],
|
||||
};
|
||||
const groupedDiff = [{ path: "src/a.txt", before: "base", after: "shelved", patch: "patch" }];
|
||||
mocks.ipc.mockReset().mockResolvedValueOnce([grouped]).mockResolvedValue(groupedDiff);
|
||||
localStorage.setItem("openidea.vcs.shelf.diffPreview", "false");
|
||||
act(() => useProject.setState({ settings: { vcs: { commit: { nonModal: false } } } as never }));
|
||||
useShelf.setState({
|
||||
shelves: [grouped],
|
||||
diffs: { work: groupedDiff },
|
||||
});
|
||||
useCommit.setState({ selectedShelf: "work\u0000src/a.txt" });
|
||||
render(
|
||||
<>
|
||||
<ShelfPanel />
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByText("Work")).toBeTruthy());
|
||||
expect(useCommit.getState().selectedShelf).toBe("work\u0000src/a.txt");
|
||||
fireEvent.click(screen.getByRole("button", { name: "View Options" }));
|
||||
fireEvent.click(screen.getByText("Directory"));
|
||||
expect(localStorage.getItem("openidea.vcs.shelf.groupByDir")).toBe("true");
|
||||
expect(useCommit.getState().selectedShelf).toBe("work\u0000src/a.txt");
|
||||
expect(screen.getAllByText("src")).toHaveLength(1);
|
||||
fireEvent.mouseDown(screen.getByText("src"));
|
||||
expect(screen.getByRole("button", { name: "Unshelve…" }).hasAttribute("disabled")).toBe(true);
|
||||
fireEvent.keyDown(screen.getByRole("tree"), { key: "Delete" });
|
||||
expect(mocks.execute).not.toHaveBeenCalledWith("vcs.shelf.delete", expect.anything());
|
||||
fireEvent.click(screen.getByRole("button", { name: "Collapse All" }));
|
||||
expect(screen.queryByText("a.txt")).toBeNull();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Expand All" }));
|
||||
expect(screen.getByText("a.txt")).toBeTruthy();
|
||||
fireEvent.click(screen.getByRole("button", { name: "View Options" }));
|
||||
fireEvent.click(screen.getByText("Show Diff Preview"));
|
||||
expect(localStorage.getItem("openidea.vcs.shelf.diffPreview")).toBe("true");
|
||||
expect(screen.getByLabelText("Resize shelf preview")).toBeTruthy();
|
||||
act(() => useProject.setState({ settings: { vcs: { commit: { nonModal: true } } } as never }));
|
||||
expect(screen.queryByLabelText("Resize shelf preview")).toBeNull();
|
||||
fireEvent.click(screen.getByRole("button", { name: "View Options" }));
|
||||
expect(screen.queryByText("Show Diff Preview")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Shelve Silently / Unshelve Silently", () => {
|
||||
|
||||
@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({
|
||||
checkout: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
openWorktree: vi.fn(),
|
||||
ghAccountStatus: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/platform/actions", async (original) => ({
|
||||
...(await original<typeof import("@/platform/actions")>()),
|
||||
@@ -23,7 +24,15 @@ vi.mock("../ops", async (original) => ({
|
||||
vi.mock("../openWorktree", () => ({ openWorktree: mocks.openWorktree }));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
return { ...real, commands: { ...real.commands, vcsBranchInfo: mocks.head, vcsCheckout: mocks.checkout } };
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsBranchInfo: mocks.head,
|
||||
vcsCheckout: mocks.checkout,
|
||||
ghProjectAccountStatus: mocks.ghAccountStatus,
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/contributions")>()),
|
||||
@@ -123,6 +132,28 @@ describe("Update Selected", () => {
|
||||
expect(mocks.openWorktree).toHaveBeenCalledWith("/worktrees/topic", true);
|
||||
});
|
||||
|
||||
it("offers GitHub account settings for an unchecked branch's HTTPS failure", async () => {
|
||||
mocks.update.mockResolvedValue([
|
||||
result("topic", "failed", "/p", "fatal: repository 'https://github.com/acme/private.git/' not found"),
|
||||
]);
|
||||
mocks.ghAccountStatus.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: {
|
||||
ghInstalled: true,
|
||||
accounts: [
|
||||
{ login: "personal", active: true },
|
||||
{ login: "work", active: false },
|
||||
],
|
||||
effectiveAccount: "personal",
|
||||
},
|
||||
});
|
||||
await updateBranches([target("topic", "/p")]);
|
||||
const [action] = mocks.notify.mock.lastCall![0].actions;
|
||||
expect(action.label).toBe("GitHub Settings");
|
||||
action.run();
|
||||
expect(mocks.execute).toHaveBeenCalledWith("file.settings", "vcs.github");
|
||||
});
|
||||
|
||||
it("offers Update Selected in the context menu of a multi-selection", () => {
|
||||
const selected = [target("a", "/p"), target("b", "/p")];
|
||||
const items = branchMenu(selected[0]!.branch, "main", () => {}, { selected });
|
||||
|
||||
@@ -17,6 +17,7 @@ import { executeAction } from "@/platform/actions";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { openWorktree } from "./openWorktree";
|
||||
import { githubHttpsFailureHelp } from "./githubHttpsFailure";
|
||||
import { activeRepository } from "./activeRepository";
|
||||
import { ask, confirmChecked } from "@/workbench/messages";
|
||||
import { branchNamePrefixes, isFavoriteBranch, isProtectedBranch, pushRecent, shortRemoteName } from "./branches";
|
||||
@@ -1446,6 +1447,11 @@ export async function updateBranches(targets: readonly BranchUpdateTarget[]) {
|
||||
const results = await runBranchUpdates(new Map([...byRepo].map(([repo, names]) => [repo, [...names]])));
|
||||
if (!results || useProject.getState().project !== project) return;
|
||||
const { lines, ...summary } = branchUpdateSummary(results, heads.length > 1);
|
||||
const help = await githubHttpsFailureHelp(
|
||||
results.flatMap((r) => (r.status === "failed" && r.message ? [r.message] : [])),
|
||||
);
|
||||
if (useProject.getState().project !== project) return;
|
||||
if (help) lines.push(help.message);
|
||||
const body = createElement(Fragment, null, ...lines.map((line) => createElement("div", { key: line }, line)));
|
||||
const worktrees = [...new Set(results.flatMap((r) => (r.status === "failed" && r.worktree ? [r.worktree] : [])))];
|
||||
notifications().notify({
|
||||
@@ -1454,10 +1460,13 @@ export async function updateBranches(targets: readonly BranchUpdateTarget[]) {
|
||||
userInitiated: true,
|
||||
...summary,
|
||||
body,
|
||||
actions: worktrees.map((path) => {
|
||||
const name = repoName(path);
|
||||
return { label: tx`Open Worktree ${name}`, run: () => void openWorktree(path, true) };
|
||||
}),
|
||||
actions: [
|
||||
...worktrees.map((path) => {
|
||||
const name = repoName(path);
|
||||
return { label: tx`Open Worktree ${name}`, run: () => void openWorktree(path, true) };
|
||||
}),
|
||||
...(help ? [help.action] : []),
|
||||
],
|
||||
});
|
||||
}
|
||||
if (current.length && useProject.getState().project === project) await runRemoteRound(current);
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
/** GitHub deliberately uses "Repository not found" for inaccessible private repositories.
|
||||
* Require Git's actual failing HTTPS URL: the same error from another host or SSH is unrelated
|
||||
* to gh's HTTPS credential helper. Never infer a credential mismatch from the error alone.
|
||||
*/
|
||||
function isGithubHttpsFailure(message: string): boolean {
|
||||
return /^fatal: (?:repository 'https:\/\/github\.com\/[^'\r\n]+' not found|Authentication failed for 'https:\/\/github\.com\/[^'\r\n]+')\.?(?:\r?$)/im.test(
|
||||
message,
|
||||
);
|
||||
}
|
||||
|
||||
/** Diagnose only explicit failed remote operations. The existing project account settings
|
||||
* handle selection; do not switch gh's global account, edit remotes, or retry a Git write.
|
||||
*/
|
||||
export async function githubHttpsFailureHelp(messages: readonly string[]) {
|
||||
if (!messages.some(isGithubHttpsFailure)) return null;
|
||||
const project = useProject.getState().project;
|
||||
const status = await call(commands.ghProjectAccountStatus()).catch(() => null);
|
||||
if (!status?.ghInstalled || status.accounts.length < 2 || useProject.getState().project !== project) return null;
|
||||
return {
|
||||
message: status.effectiveAccount
|
||||
? tx`GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, ${status.effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.`
|
||||
: tx(
|
||||
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.",
|
||||
),
|
||||
action: {
|
||||
label: "GitHub Settings",
|
||||
run: () => {
|
||||
if (useProject.getState().project === project) void executeAction("file.settings", "vcs.github");
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import { flushChangelists } from "./changelists";
|
||||
import { pushHistoryRepo, rememberPushTarget } from "./pushHistory";
|
||||
import { describePush, formatPushOutcomes, partialPushReport, pushedCommits, type RepoPushOutcome } from "./pushReport";
|
||||
import { cancelIncomingCheck } from "./incomingRequest";
|
||||
import { githubHttpsFailureHelp } from "./githubHttpsFailure";
|
||||
import { beginGitWork, conflictedFiles, currentRepo, refreshNow, repoName, repoOf, useVcs } from "./store";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -551,6 +552,13 @@ export async function runRemoteRound<Op extends RemoteOp>(
|
||||
: first.op === "unshallow"
|
||||
? tx("Could not fetch full Git history")
|
||||
: `${doneTitle} failed`;
|
||||
const help = await githubHttpsFailureHelp(remaining.map(({ error }) => errorMessage(error)));
|
||||
if (cancelRequested || useProject.getState().project !== project)
|
||||
throw new IpcError({ kind: "cancelled", message: "cancelled" });
|
||||
const actions = [
|
||||
...(partial || isFetch ? [gitConsoleNotificationAction()] : []),
|
||||
...(help ? [help.action] : []),
|
||||
];
|
||||
notify({
|
||||
level: "error",
|
||||
key: "vcs.remote",
|
||||
@@ -561,9 +569,9 @@ export async function runRemoteRound<Op extends RemoteOp>(
|
||||
? tx(message)
|
||||
: message,
|
||||
)
|
||||
.concat(pruned)
|
||||
.concat(pruned, help ? [help.message] : [])
|
||||
.join("\n"),
|
||||
actions: partial || isFetch ? [gitConsoleNotificationAction()] : undefined,
|
||||
actions: actions.length ? actions : undefined,
|
||||
});
|
||||
}
|
||||
if (!reported && isUpdate(first) && updated.length) await notifyUpdated(updated, "vcs.remote.updated");
|
||||
|
||||
@@ -26,6 +26,7 @@ import { openDialog } from "./dialogs";
|
||||
import { useBranches } from "./gitMenuDialogs";
|
||||
import { saveVcsSetting } from "./settingsUi";
|
||||
import { formatTime } from "./model";
|
||||
import { githubHttpsFailureHelp } from "./githubHttpsFailure";
|
||||
import {
|
||||
allRepos,
|
||||
errorMessage,
|
||||
@@ -1493,12 +1494,13 @@ function pushReviewActions(review: readonly PushReviewTarget[]) {
|
||||
];
|
||||
}
|
||||
|
||||
function pushFailed(
|
||||
async function pushFailed(
|
||||
failures: RemoteFailure<PushOp>[],
|
||||
total: number,
|
||||
rejected: boolean,
|
||||
pushed: readonly RepoPushOutcome[],
|
||||
): false {
|
||||
): Promise<false> {
|
||||
const project = useProject.getState().project;
|
||||
const isPartial = ({ error }: RemoteFailure<PushOp>) => !!partialPushReport(error);
|
||||
const names = (items: RemoteFailure<PushOp>[]) =>
|
||||
items.flatMap(({ target }) => (target.repo ? [repoName(target.repo)] : [])).join(", ");
|
||||
@@ -1521,7 +1523,11 @@ function pushFailed(
|
||||
: tx(errorMessage(failures[0]!.error)),
|
||||
);
|
||||
}
|
||||
const actions = pushReviewActions(review);
|
||||
const help = await githubHttpsFailureHelp(failures.map(({ error }) => errorMessage(error)));
|
||||
if (useProject.getState().project !== project) return false;
|
||||
if (help) lines.push(help.message);
|
||||
const actions = [...(pushReviewActions(review) ?? []), ...(help ? [help.action] : [])];
|
||||
if (partiallyApplied.length) actions.push(gitConsoleNotificationAction());
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "error",
|
||||
@@ -1534,7 +1540,7 @@ function pushFailed(
|
||||
? "Push rejected"
|
||||
: "Push failed",
|
||||
body: lines.join("\n"),
|
||||
actions: partiallyApplied.length ? [...(actions ?? []), gitConsoleNotificationAction()] : actions,
|
||||
actions: actions.length ? actions : undefined,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -18,18 +18,20 @@ import type {
|
||||
} from "@/bindings";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { openDiff, openVcsDiff, withChain, workingDiffData, type DiffData } from "./diffInput";
|
||||
import { diffInput, openDiff, openVcsDiff, withChain, workingDiffData, type DiffData } from "./diffInput";
|
||||
import { useDiffSource } from "./diffSource";
|
||||
import { showCreatePatchForShelf } from "./patches";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { useWorkflowSettings, workflowSettings } from "@/platform/workflowSettings";
|
||||
import {
|
||||
Checkbox,
|
||||
Dialog,
|
||||
EmptyState,
|
||||
Icon,
|
||||
IconButton,
|
||||
Input,
|
||||
lazyComponent,
|
||||
Select,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
@@ -40,7 +42,8 @@ import {
|
||||
T,
|
||||
} from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { groupOf } from "./changes";
|
||||
import { groupOf, moduleOf } from "./changes";
|
||||
import { useChangeModules } from "./changeModules";
|
||||
import { buildFileTree, dirKeys, type FileTreeNode } from "./fileTree";
|
||||
import { activeList, listOf, moveFiles, relOf, updateChangelists, useChangelists } from "./changelists";
|
||||
import { useCommit } from "./commitStore";
|
||||
@@ -65,6 +68,27 @@ import viewStyles from "./CommitView.module.css";
|
||||
import shelfStyles from "./Shelf.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
const DiffEditor = lazyComponent(() => import("./DiffEditor").then((m) => m.DiffEditor));
|
||||
|
||||
type ShelfViewOption = "groupByDir" | "groupByModule" | "diffPreview";
|
||||
|
||||
function readShelfViewOption(option: ShelfViewOption, fallback: boolean): boolean {
|
||||
try {
|
||||
const saved = localStorage.getItem(`openidea.vcs.shelf.${option}`);
|
||||
return saved === null ? fallback : saved === "true";
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function saveShelfViewOption(option: ShelfViewOption, value: boolean) {
|
||||
try {
|
||||
localStorage.setItem(`openidea.vcs.shelf.${option}`, String(value));
|
||||
} catch {
|
||||
// The view remains usable if browser storage is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
interface ShelfState {
|
||||
shelves: ShelvedChangeList[];
|
||||
loaded: boolean;
|
||||
@@ -571,6 +595,19 @@ interface ShelfNode {
|
||||
key: string;
|
||||
entry: ShelvedChangeList;
|
||||
file?: ShelvedChangeList["files"][number];
|
||||
directory?: boolean;
|
||||
module?: boolean;
|
||||
label?: string;
|
||||
children?: ShelfNode[];
|
||||
}
|
||||
|
||||
function shelfDirKeys(nodes: readonly ShelfNode[], out: string[] = []): string[] {
|
||||
for (const node of nodes)
|
||||
if (node.children?.length) {
|
||||
out.push(node.key);
|
||||
shelfDirKeys(node.children, out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface ShelfTarget {
|
||||
@@ -702,30 +739,35 @@ export function createShelfPatch(arg?: unknown) {
|
||||
|
||||
function ShelfTree({
|
||||
nodes,
|
||||
kind,
|
||||
selectedKey,
|
||||
empty,
|
||||
expanded,
|
||||
onExpandedChange,
|
||||
grouped,
|
||||
}: {
|
||||
nodes: ShelfNode[];
|
||||
kind: "changes" | "files";
|
||||
selectedKey: string | null;
|
||||
empty: string;
|
||||
expanded: ReadonlySet<string>;
|
||||
onExpandedChange: (expanded: Set<string>) => void;
|
||||
grouped: boolean;
|
||||
}) {
|
||||
const selected = useMemo(() => new Set(selectedKey ? [selectedKey] : []), [selectedKey]);
|
||||
const filePane = kind === "files";
|
||||
return (
|
||||
<Tree<ShelfNode>
|
||||
roots={nodes}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) => (n.file ? baseName(n.file.path) : n.entry.name)}
|
||||
getChildren={() => undefined}
|
||||
isExpandable={() => false}
|
||||
getLabel={(n) => (n.file ? baseName(n.file.path) : n.directory ? (n.label ?? "") : n.entry.name)}
|
||||
getChildren={(n) => n.children}
|
||||
isExpandable={(n) => !!n.children?.length}
|
||||
expanded={expanded}
|
||||
onExpandedChange={(next) => onExpandedChange(next)}
|
||||
selected={selected}
|
||||
onSelectionChange={(sel) => useCommit.setState({ selectedShelf: [...sel][0] ?? null })}
|
||||
horizontalScroll={filePane}
|
||||
rowHeight={filePane ? 40 : undefined}
|
||||
horizontalScroll
|
||||
multiSelect={false}
|
||||
onActivate={(n) => {
|
||||
if (n.directory) return;
|
||||
void executeAction(n.file ? "vcs.shelf.showDiff" : "vcs.unshelve", { id: n.entry.id, path: n.file?.path });
|
||||
}}
|
||||
onContextMenu={(node, _sel, e: MouseEvent) => {
|
||||
@@ -744,10 +786,18 @@ function ShelfTree({
|
||||
}),
|
||||
).then((supported) => showContextMenu(point, shelfMenu(node, supported.some(Boolean))));
|
||||
}}
|
||||
aria-label={filePane ? "Shelved files" : "Shelved changes"}
|
||||
aria-label="Shelved changes"
|
||||
empty={<span className={viewStyles.empty}>{tx(empty)}</span>}
|
||||
renderNode={(n) => {
|
||||
const file = n.file;
|
||||
if (n.directory) {
|
||||
return (
|
||||
<>
|
||||
<Icon name={n.module ? "module" : "folder"} size={16} className={viewStyles.icon} />
|
||||
<span className={shelfStyles.patchName}>{n.label}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (file) {
|
||||
const directory = dirName(file.path);
|
||||
return (
|
||||
@@ -757,7 +807,7 @@ function ShelfTree({
|
||||
<span style={{ color: KIND_COLOR[file.kind === "untracked" ? "added" : file.kind] }}>
|
||||
{baseName(file.path)}
|
||||
</span>
|
||||
{directory && <span className={shelfStyles.detail}>{directory}</span>}
|
||||
{directory && !grouped && <span className={shelfStyles.detail}>{directory}</span>}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
@@ -765,11 +815,13 @@ function ShelfTree({
|
||||
const time = n.entry.timeMs ? formatTime(n.entry.timeMs) : null;
|
||||
return (
|
||||
<>
|
||||
<Icon name="shelve" size={16} className={viewStyles.icon} />
|
||||
<span className={shelfStyles.patchName} title={n.entry.name}>
|
||||
{n.entry.name}
|
||||
</span>
|
||||
<span className={shelfStyles.detail}>{fileCount(n.entry.files.length)}</span>
|
||||
<span className={shelfStyles.detail}>
|
||||
{fileCount(n.entry.files.length)}
|
||||
{time ? "," : ""}
|
||||
</span>
|
||||
{time && (
|
||||
<span className={shelfStyles.date} title={time}>
|
||||
{time}
|
||||
@@ -788,8 +840,17 @@ export function ShelfPanel() {
|
||||
const loaded = useShelf((s) => s.loaded);
|
||||
const root = useVcs((s) => s.root);
|
||||
const selectedShelf = useCommit((s) => s.selectedShelf);
|
||||
const shelfDiffFiles = useShelf((s) => s.diffs);
|
||||
const panelRef = useRef<HTMLDivElement>(null);
|
||||
const [stacked, setStacked] = useState(true);
|
||||
const viewRef = useRef<HTMLButtonElement>(null);
|
||||
const [stacked, setStacked] = useState(false);
|
||||
const [groupByDir, setGroupByDir] = useState(() => readShelfViewOption("groupByDir", false));
|
||||
const [groupByModule, setGroupByModule] = useState(() => readShelfViewOption("groupByModule", false));
|
||||
const changeModules = useChangeModules();
|
||||
const nonModal = useWorkflowSettings((s) => s.vcs.commit.nonModal);
|
||||
const [diffPreviewOption, setDiffPreview] = useState(() => readShelfViewOption("diffPreview", true));
|
||||
const diffPreview = diffPreviewOption && !nonModal;
|
||||
const [expanded, setExpanded] = useState<{ scope: string; keys: ReadonlySet<string> } | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
const panel = panelRef.current;
|
||||
if (!panel) return;
|
||||
@@ -805,20 +866,68 @@ export function ShelfPanel() {
|
||||
return () => setContext("shelfFocus", false);
|
||||
}, [root]);
|
||||
useDiffSource(panelRef, { diff: () => shelfDiffData(), show: () => showShelfDiff() });
|
||||
const selectedId = selectedShelf?.split("\u0000", 1)[0];
|
||||
const entry = shelves.find((s) => s.id === selectedId);
|
||||
const patches = useMemo<ShelfNode[]>(() => shelves.map((s) => ({ key: s.id, entry: s })), [shelves]);
|
||||
const files = useMemo<ShelfNode[]>(
|
||||
() => entry?.files.map((file) => ({ key: `${entry.id}\u0000${file.path}`, entry, file })) ?? [],
|
||||
[entry],
|
||||
const nodes = useMemo<ShelfNode[]>(
|
||||
() =>
|
||||
shelves.map((entry) => {
|
||||
type F = (typeof entry.files)[number];
|
||||
const build = (files: F[]) =>
|
||||
groupByDir
|
||||
? buildFileTree(files, (file) => file.path.replaceAll("\\", "/"))
|
||||
: files.map((file) => ({
|
||||
key: `f:${file.path}`,
|
||||
name: baseName(file.path),
|
||||
file,
|
||||
children: [],
|
||||
count: 1,
|
||||
}));
|
||||
const convert = (node: FileTreeNode<F>): ShelfNode => ({
|
||||
key: `${entry.id}\u0000${node.file ? node.file.path : node.key}`,
|
||||
entry,
|
||||
file: node.file ?? undefined,
|
||||
directory: !node.file,
|
||||
label: node.name,
|
||||
children: node.file ? undefined : node.children.map(convert),
|
||||
});
|
||||
if (!groupByModule || !changeModules.length)
|
||||
return { key: entry.id, entry, children: build(entry.files).map(convert) };
|
||||
const byModule = new Map<string, { name: string; files: F[] }>();
|
||||
const loose: F[] = [];
|
||||
for (const file of entry.files) {
|
||||
const rel = file.path.replaceAll("\\", "/");
|
||||
const mod = moduleOf(rel.startsWith("/") || !root ? rel : `${stripSlash(root)}/${rel}`, changeModules);
|
||||
if (!mod) loose.push(file);
|
||||
else
|
||||
(byModule.get(mod.path) ?? byModule.set(mod.path, { name: mod.name, files: [] }).get(mod.path)!).files.push(
|
||||
file,
|
||||
);
|
||||
}
|
||||
const children: ShelfNode[] = [...byModule].map(([path, m]) => ({
|
||||
key: `${entry.id}\u0000m:${path}`,
|
||||
entry,
|
||||
directory: true,
|
||||
module: true,
|
||||
label: m.name,
|
||||
children: build(m.files).map(convert),
|
||||
}));
|
||||
return { key: entry.id, entry, children: [...children, ...build(loose).map(convert)] };
|
||||
}),
|
||||
[shelves, groupByDir, groupByModule, changeModules, root],
|
||||
);
|
||||
const allKeys = useMemo(() => shelfDirKeys(nodes), [nodes]);
|
||||
const expansionScope = `${groupByDir}:${groupByModule}`;
|
||||
const expandedKeys = expanded?.scope === expansionScope ? expanded.keys : new Set(allKeys);
|
||||
const updateExpanded = (keys: Set<string>) => setExpanded({ scope: expansionScope, keys });
|
||||
const current = selectedShelf ? shelfTarget(selectedShelf) : null;
|
||||
const patchTree = (
|
||||
const previewDiff = diffPreview && current?.path ? shelfDiffs({ id: current.entry.id, path: current.path })[0] : null;
|
||||
const previewInput = previewDiff ? diffInput(previewDiff) : null;
|
||||
const tree = (
|
||||
<ShelfTree
|
||||
nodes={patches}
|
||||
kind="changes"
|
||||
selectedKey={entry?.id ?? null}
|
||||
nodes={nodes}
|
||||
selectedKey={selectedShelf}
|
||||
empty={loaded ? "No shelved changes" : "Loading…"}
|
||||
expanded={expandedKeys}
|
||||
onExpandedChange={updateExpanded}
|
||||
grouped={groupByDir}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
@@ -826,6 +935,12 @@ export function ShelfPanel() {
|
||||
className={viewStyles.changes}
|
||||
ref={panelRef}
|
||||
data-shelf-panel
|
||||
onKeyDown={(e) => {
|
||||
if (e.defaultPrevented || e.altKey || e.ctrlKey || !current) return;
|
||||
if (e.key !== "Delete" && !(e.key === "Backspace" && e.metaKey)) return;
|
||||
e.preventDefault();
|
||||
void executeAction("vcs.shelf.delete", { id: current.entry.id, path: current.path });
|
||||
}}
|
||||
onFocusCapture={() => setContext("shelfFocus", true)}
|
||||
onBlurCapture={(e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setContext("shelfFocus", false);
|
||||
@@ -833,7 +948,6 @@ export function ShelfPanel() {
|
||||
>
|
||||
<div className={viewStyles.toolbar} role="toolbar" aria-label={tx("Shelf")}>
|
||||
<IconButton icon="refresh" action="vcs.shelf.refresh" size="small" />
|
||||
<IconButton icon="shelve" action="vcs.shelve" size="small" />
|
||||
<span className={viewStyles.sep} />
|
||||
<IconButton
|
||||
icon="unshelve"
|
||||
@@ -842,6 +956,71 @@ export function ShelfPanel() {
|
||||
disabled={!current}
|
||||
onClick={() => current && void executeAction("vcs.unshelve", { id: current.entry.id, path: current.path })}
|
||||
/>
|
||||
<IconButton
|
||||
ref={viewRef}
|
||||
icon="eye"
|
||||
title="View Options"
|
||||
size="small"
|
||||
aria-haspopup="menu"
|
||||
onClick={() => {
|
||||
const rect = viewRef.current?.getBoundingClientRect();
|
||||
if (!rect) return;
|
||||
showContextMenu({ x: rect.left, y: rect.bottom + 2 }, [
|
||||
{ kind: "header", label: "Group By" },
|
||||
{
|
||||
label: "Directory",
|
||||
checked: groupByDir,
|
||||
run: () => {
|
||||
const value = !groupByDir;
|
||||
setGroupByDir(value);
|
||||
saveShelfViewOption("groupByDir", value);
|
||||
},
|
||||
},
|
||||
...(changeModules.length > 0
|
||||
? [
|
||||
{
|
||||
label: "Module",
|
||||
checked: groupByModule,
|
||||
run: () => {
|
||||
const value = !groupByModule;
|
||||
setGroupByModule(value);
|
||||
saveShelfViewOption("groupByModule", value);
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(nonModal
|
||||
? []
|
||||
: [
|
||||
{ kind: "separator" as const },
|
||||
{
|
||||
label: "Show Diff Preview",
|
||||
checked: diffPreview,
|
||||
run: () => {
|
||||
const value = !diffPreview;
|
||||
setDiffPreview(value);
|
||||
saveShelfViewOption("diffPreview", value);
|
||||
},
|
||||
},
|
||||
]),
|
||||
]);
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
icon="expand-all"
|
||||
title="Expand All"
|
||||
size="small"
|
||||
disabled={!allKeys.length}
|
||||
onClick={() => updateExpanded(new Set(allKeys))}
|
||||
/>
|
||||
<IconButton
|
||||
icon="collapse-all"
|
||||
title="Collapse All"
|
||||
size="small"
|
||||
disabled={!allKeys.length}
|
||||
onClick={() => updateExpanded(new Set())}
|
||||
/>
|
||||
<span className={viewStyles.sep} />
|
||||
<IconButton
|
||||
icon="trash"
|
||||
title="Delete"
|
||||
@@ -852,31 +1031,35 @@ export function ShelfPanel() {
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{patches.length ? (
|
||||
{nodes.length && diffPreview ? (
|
||||
<SplitGroup
|
||||
id="shelf-panes"
|
||||
className={shelfStyles.split}
|
||||
orientation={stacked ? "vertical" : "horizontal"}
|
||||
storageKey={`openidea.vcs.shelf.layout.${stacked ? "stacked" : "sideBySide"}`}
|
||||
>
|
||||
<SplitPanel id="shelf-changes" defaultSize="50%" minSize="25%">
|
||||
{patchTree}
|
||||
<SplitPanel id="shelf-tree" defaultSize="50%" minSize="25%">
|
||||
{tree}
|
||||
</SplitPanel>
|
||||
<SplitHandle aria-label={tx("Resize shelf panes")} />
|
||||
<SplitPanel id="shelf-files" defaultSize="50%" minSize="25%">
|
||||
<div className={shelfStyles.filesHeader}>
|
||||
<T>Shelved files</T>
|
||||
</div>
|
||||
<ShelfTree
|
||||
nodes={files}
|
||||
kind="files"
|
||||
selectedKey={current?.path ? selectedShelf : null}
|
||||
empty={entry ? "No files" : "Select a shelf to view its files"}
|
||||
/>
|
||||
<SplitHandle aria-label={tx("Resize shelf preview")} />
|
||||
<SplitPanel id="shelf-preview" defaultSize="50%" minSize="25%">
|
||||
{previewInput ? (
|
||||
<DiffEditor input={previewInput} />
|
||||
) : (
|
||||
<EmptyState>
|
||||
<T>
|
||||
{!current?.path
|
||||
? "Select a file to preview its changes"
|
||||
: shelfDiffFiles[current.entry.id]
|
||||
? "No diff available for this file"
|
||||
: "Loading…"}
|
||||
</T>
|
||||
</EmptyState>
|
||||
)}
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
) : (
|
||||
<div className={viewStyles.treeWrap}>{patchTree}</div>
|
||||
<div className={viewStyles.treeWrap}>{tree}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -3830,9 +3830,8 @@
|
||||
"Resize rebase panes": "Resize rebase panes",
|
||||
"New message for {id}": "New message for {id}",
|
||||
"Resize right merge pane": "Resize right merge pane",
|
||||
"Resize shelf panes": "Resize shelf panes",
|
||||
"Shelved files": "Shelved files",
|
||||
"Select a shelf to view its files": "Select a shelf to view its files",
|
||||
"Resize shelf preview": "Resize shelf preview",
|
||||
"No diff available for this file": "No diff available for this file",
|
||||
"No files": "No files",
|
||||
"Database and schema": "Database and schema",
|
||||
"Loading…": "Loading…",
|
||||
@@ -4830,5 +4829,8 @@
|
||||
"Create Library": "Create Library",
|
||||
"Library name": "Library name",
|
||||
"Library name cannot be empty.": "Library name cannot be empty.",
|
||||
"A library with this name already exists.": "A library with this name already exists."
|
||||
"A library with this name already exists.": "A library with this name already exists.",
|
||||
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.",
|
||||
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.",
|
||||
"GitHub Settings": "GitHub Settings"
|
||||
}
|
||||
@@ -3320,8 +3320,8 @@
|
||||
"Shelve Changes": "Отложить изменения",
|
||||
"Shelve Changes…": "Отложить изменения…",
|
||||
"Shelved changes": "Отложенные изменения",
|
||||
"Shelved files": "Отложенные файлы",
|
||||
"Select a shelf to view its files": "Выберите полку для просмотра её файлов",
|
||||
"Resize shelf preview": "Изменить размер предпросмотра отложенных изменений",
|
||||
"No diff available for this file": "Для этого файла нет diff",
|
||||
"No files": "Нет файлов",
|
||||
"Show": "Показать",
|
||||
"Show \"Today\", \"Yesterday\" and \"N min ago\" for recent dates": "Показывать «Сегодня», «Вчера» и «N мин назад» для недавних дат",
|
||||
@@ -9845,7 +9845,6 @@
|
||||
"Resize left merge pane": "Изменить размер левой панели слияния",
|
||||
"Resize rebase panes": "Изменить размер панелей перебазирования",
|
||||
"Resize right merge pane": "Изменить размер правой панели слияния",
|
||||
"Resize shelf panes": "Изменить размер панелей отложенных изменений",
|
||||
"Database and schema": "База данных и схема",
|
||||
"Shelve Silently": "Отложить без подтверждения",
|
||||
"Unshelve Silently": "Восстановить без подтверждения",
|
||||
|
||||
@@ -2748,9 +2748,8 @@
|
||||
"Resize rebase panes": "Rebase bölmelerini yeniden boyutlandır",
|
||||
"New message for {id}": "{id} için yeni mesaj",
|
||||
"Resize right merge pane": "Sağ birleştirme bölmesini yeniden boyutlandır",
|
||||
"Resize shelf panes": "Raf bölmelerini yeniden boyutlandır",
|
||||
"Shelved files": "Rafa alınmış dosyalar",
|
||||
"Select a shelf to view its files": "Dosyalarını görüntülemek için bir raf seçin",
|
||||
"Resize shelf preview": "Raf önizlemesini yeniden boyutlandır",
|
||||
"No diff available for this file": "Bu dosya için fark yok",
|
||||
"No files": "Yok dosyaları",
|
||||
"Database and schema": "Veritabanı ve şema",
|
||||
"Loading…": "Yükleniyor…",
|
||||
|
||||
@@ -2923,8 +2923,8 @@
|
||||
"Shelve Changes": "擱置更改",
|
||||
"Shelve Changes…": "擱置更改…",
|
||||
"Shelved changes": "已擱置的更改",
|
||||
"Shelved files": "已擱置的檔案",
|
||||
"Select a shelf to view its files": "選擇一條擱置記錄以檢視檔案",
|
||||
"Resize shelf preview": "調整擱置記錄預覽大小",
|
||||
"No diff available for this file": "此檔案沒有可用的差異",
|
||||
"No files": "沒有檔案",
|
||||
"Show": "顯示",
|
||||
"Show \"Today\", \"Yesterday\" and \"N min ago\" for recent dates": "對最近的日期顯示「今天」、「昨天」和「N 分鐘前」",
|
||||
@@ -9281,7 +9281,6 @@
|
||||
"Resize left merge pane": "調整左側合併窗格寬度",
|
||||
"Resize rebase panes": "調整重定基底計劃和詳細資訊窗格大小",
|
||||
"Resize right merge pane": "調整右側合併窗格寬度",
|
||||
"Resize shelf panes": "調整擱置記錄和檔案窗格大小",
|
||||
"Database and schema": "資料庫和 schema",
|
||||
"Shelve Silently": "靜默擱置",
|
||||
"Unshelve Silently": "靜默取消擱置",
|
||||
@@ -9539,5 +9538,8 @@
|
||||
"Create Library": "建立庫",
|
||||
"Library name": "庫名稱",
|
||||
"Library name cannot be empty.": "庫名稱不可為空。",
|
||||
"A library with this name already exists.": "已存在同名的庫。"
|
||||
"A library with this name already exists.": "已存在同名的庫。",
|
||||
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登入了多個帳號。如果 Git 透過 gh 取得 HTTPS 憑證,{effectiveAccount} 可能沒有存取權限。請檢查遠端 URL,或在 GitHub 設定中選擇有權限的帳號後重試。",
|
||||
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登入了多個帳號。如果 Git 透過 gh 取得 HTTPS 憑證,請檢查遠端 URL,或在 GitHub 設定中選擇有權限的帳號後重試。",
|
||||
"GitHub Settings": "GitHub 設定"
|
||||
}
|
||||
@@ -3587,8 +3587,8 @@
|
||||
"Shelve Changes": "搁置更改",
|
||||
"Shelve Changes…": "搁置更改…",
|
||||
"Shelved changes": "已搁置的更改",
|
||||
"Shelved files": "已搁置的文件",
|
||||
"Select a shelf to view its files": "选择一条搁置记录以查看文件",
|
||||
"Resize shelf preview": "调整搁置记录预览大小",
|
||||
"No diff available for this file": "此文件没有可用的差异",
|
||||
"No files": "没有文件",
|
||||
"Show": "显示",
|
||||
"Show \"Today\", \"Yesterday\" and \"N min ago\" for recent dates": "对最近的日期显示“今天”、“昨天”和“N 分钟前”",
|
||||
@@ -10422,7 +10422,6 @@
|
||||
"Resize left merge pane": "调整左侧合并窗格宽度",
|
||||
"Resize rebase panes": "调整变基计划和详细信息窗格大小",
|
||||
"Resize right merge pane": "调整右侧合并窗格宽度",
|
||||
"Resize shelf panes": "调整搁置记录和文件窗格大小",
|
||||
"Database and schema": "数据库和 schema",
|
||||
"Shelve Silently": "静默搁置",
|
||||
"Unshelve Silently": "静默取消搁置",
|
||||
@@ -11527,5 +11526,8 @@
|
||||
"Create Library": "创建库",
|
||||
"Library name": "库名称",
|
||||
"Library name cannot be empty.": "库名称不能为空。",
|
||||
"A library with this name already exists.": "已存在同名的库。"
|
||||
"A library with this name already exists.": "已存在同名的库。",
|
||||
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登录了多个账号。如果 Git 通过 gh 获取 HTTPS 凭据,{effectiveAccount} 可能没有访问权限。请检查远程 URL,或在 GitHub 设置中选择有权限的账号后重试。",
|
||||
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登录了多个账号。如果 Git 通过 gh 获取 HTTPS 凭据,请检查远程 URL,或在 GitHub 设置中选择有权限的账号后重试。",
|
||||
"GitHub Settings": "GitHub 设置"
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
gitRevisionOf,
|
||||
isVirtualUri,
|
||||
@@ -6,8 +6,10 @@ import {
|
||||
libraryEntryPaths,
|
||||
virtualContainer,
|
||||
virtualName,
|
||||
virtualDocument,
|
||||
virtualParent,
|
||||
} from "./virtualDocs";
|
||||
import { commands } from "./ipc";
|
||||
import { basename, dirname, relativeDir, relativePath } from "./project";
|
||||
|
||||
const JDT =
|
||||
@@ -151,3 +153,23 @@ describe("Git revision URIs", () => {
|
||||
expect(gitRevisionOf("jdt://contents/x.jar/a/B.class")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("virtualDocument cache", () => {
|
||||
it("keeps the most recently used documents and fetches an evicted one again", async () => {
|
||||
const fetch = vi
|
||||
.spyOn(commands, "lspVirtualDocument")
|
||||
.mockImplementation(async (uri) => ({ status: "ok", data: { uri, text: uri } }) as never);
|
||||
const uris = Array.from({ length: 33 }, (_, i) => `jdt://contents/a${i}.class`);
|
||||
await virtualDocument(uris[0]!);
|
||||
// oxlint-disable-next-line no-await-in-loop -- the order of use is what the test checks
|
||||
for (const uri of uris.slice(1, 32)) await virtualDocument(uri);
|
||||
await virtualDocument(uris[0]!);
|
||||
expect(fetch).toHaveBeenCalledTimes(32);
|
||||
await virtualDocument(uris[32]!);
|
||||
await virtualDocument(uris[0]!);
|
||||
expect(fetch).toHaveBeenCalledTimes(33);
|
||||
await virtualDocument(uris[1]!);
|
||||
expect(fetch).toHaveBeenCalledTimes(34);
|
||||
fetch.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -97,6 +97,8 @@ export function virtualContainer(uri: string): string {
|
||||
return segs.join(" › ");
|
||||
}
|
||||
|
||||
/** Cached documents beyond this many are dropped, least recently used first. */
|
||||
const MAX_CACHED = 32;
|
||||
const cache = new Map<string, Promise<VirtualDocument>>();
|
||||
|
||||
export function invalidateVirtualDocument(uri: string): void {
|
||||
@@ -111,11 +113,14 @@ export function invalidateVirtualDocuments(): void {
|
||||
/** Contents of a virtual document (cached; failures are retried on the next call). */
|
||||
export function virtualDocument(uri: string): Promise<VirtualDocument> {
|
||||
let p = cache.get(uri);
|
||||
if (!p) {
|
||||
p = call(commands.lspVirtualDocument(uri));
|
||||
p.catch(() => cache.delete(uri));
|
||||
cache.set(uri, p);
|
||||
if (p) {
|
||||
cache.delete(uri);
|
||||
} else {
|
||||
const fetched = (p = call(commands.lspVirtualDocument(uri)));
|
||||
p.catch(() => cache.get(uri) === fetched && cache.delete(uri));
|
||||
}
|
||||
cache.set(uri, p);
|
||||
if (cache.size > MAX_CACHED) cache.delete(cache.keys().next().value!);
|
||||
return p;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Заблокувати користувача