дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 21:12:34 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
1e3de07cbb |
No files matched your search
@@ -1,52 +0,0 @@
|
||||
name: CNB mirror
|
||||
|
||||
# Copies a published release to cnb.cool/l0ng-ai/openidea, the updater's CNB source
|
||||
# (scripts/cnb-mirror.ts). Release runs it after publishing; run it by hand to mirror
|
||||
# an existing tag again. Skipped without the CNB_TOKEN secret.
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag: { type: string, required: true }
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Published release to mirror (e.g. v0.1.38)"
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: cnb-mirror-${{ inputs.tag }}
|
||||
|
||||
jobs:
|
||||
mirror:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
CNB_TOKEN: ${{ secrets.CNB_TOKEN }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- name: Check token
|
||||
id: token
|
||||
run: |
|
||||
if [ -z "$CNB_TOKEN" ]; then
|
||||
echo "::notice::CNB_TOKEN unset: not mirroring $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.token.outputs.skip != 'true'
|
||||
with: { sparse-checkout: scripts }
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.token.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Download release
|
||||
if: steps.token.outputs.skip != 'true'
|
||||
run: |
|
||||
gh release download "$TAG" -R "$GITHUB_REPOSITORY" -D assets
|
||||
gh release view "$TAG" -R "$GITHUB_REPOSITORY" --json body,isPrerelease > assets/release.json
|
||||
du -sh assets
|
||||
- name: Upload to CNB
|
||||
if: steps.token.outputs.skip != 'true'
|
||||
run: node scripts/cnb-mirror.ts "$TAG" assets
|
||||
@@ -355,10 +355,3 @@ jobs:
|
||||
await github.rest.repos.updateRelease({
|
||||
...context.repo, release_id: Number(process.env.RELEASE_ID), draft: false,
|
||||
});
|
||||
|
||||
# The China mirror the updater's CNB source reads; a failure here leaves the GitHub release as is.
|
||||
cnb-mirror:
|
||||
needs: publish
|
||||
uses: ./.github/workflows/cnb-mirror.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
Створено
+2
-1
@@ -4212,7 +4212,6 @@ dependencies = [
|
||||
name = "ide-dap"
|
||||
version = "0.1.37"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
"ide-language",
|
||||
@@ -6013,6 +6012,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.6.2",
|
||||
"dispatch2",
|
||||
"objc2 0.6.5",
|
||||
]
|
||||
@@ -6403,6 +6403,7 @@ dependencies = [
|
||||
"ide-workspace",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2-web-kit 0.3.2",
|
||||
"parking_lot",
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
|
||||
## Project Lombok
|
||||
|
||||
`java/lombok/lombok-1.18.48-openidea.3.jar` contains Project Lombok v1.18.48 with the Equinox
|
||||
classloader fix from [projectlombok/lombok#4059](https://github.com/projectlombok/lombok/pull/4059),
|
||||
the [compact record constructor builder fix](java/lombok/patches/builder-compact-constructor.patch)
|
||||
`java/lombok/lombok-1.18.48-openidea.2.jar` contains Project Lombok v1.18.48 with the Equinox
|
||||
classloader fix from [projectlombok/lombok#4059](https://github.com/projectlombok/lombok/pull/4059)
|
||||
and the ECJ constructor-call fix from [projectlombok/lombok#4089](https://github.com/projectlombok/lombok/pull/4089).
|
||||
Copyright (C) 2009-2021 The Project Lombok Authors. MIT license and bundled component
|
||||
notices are retained in [java/lombok/LICENSE](java/lombok/LICENSE) and inside the jar.
|
||||
|
||||
@@ -268,8 +268,6 @@ pub struct GeneralSettings {
|
||||
pub power_save_mode: bool,
|
||||
/// File › Rename Project… (project layer): the name shown for the project; empty = its folder name.
|
||||
pub project_name: String,
|
||||
/// Where updates come from: `auto` (the CNB mirror for the Chinese UI, else GitHub) | `github` | `cnb`.
|
||||
pub update_source: String,
|
||||
}
|
||||
|
||||
impl Default for GeneralSettings {
|
||||
@@ -284,7 +282,6 @@ impl Default for GeneralSettings {
|
||||
date_format: DateFormatSettings::default(),
|
||||
power_save_mode: false,
|
||||
project_name: String::new(),
|
||||
update_source: "auto".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
futures.workspace = true
|
||||
tempfile.workspace = true
|
||||
ide-core.workspace = true
|
||||
ide-language.workspace = true
|
||||
|
||||
@@ -19,7 +19,6 @@ mod session;
|
||||
|
||||
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
use connection::{Connection, DapError};
|
||||
use futures::future::join_all;
|
||||
use ide_core::{DebugSessionId, IdeError, IdeResult, SharedSink};
|
||||
use ide_language::LanguageRegistry;
|
||||
use parking_lot::Mutex;
|
||||
@@ -511,18 +510,6 @@ pub(crate) fn capabilities_from(caps: &Value) -> DebugCapabilities {
|
||||
}
|
||||
}
|
||||
|
||||
/// States of a file's line breakpoints that no session has been sent.
|
||||
fn unsent(breakpoints: &[Breakpoint]) -> Vec<BreakpointState> {
|
||||
breakpoints
|
||||
.iter()
|
||||
.map(|b| BreakpointState {
|
||||
line: b.line,
|
||||
verified: false,
|
||||
message: (!b.enabled).then(|| "Disabled".to_owned()),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// States for breakpoints no session has verified yet.
|
||||
fn unverified(enabled: impl Iterator<Item = bool>) -> Vec<BreakpointState> {
|
||||
enabled
|
||||
@@ -890,20 +877,12 @@ impl DebugManager {
|
||||
let _ = tokio::time::timeout(INIT_TIMEOUT, initialized.wait_for(|v| *v)).await;
|
||||
}
|
||||
|
||||
// A fresh adapter has no breakpoints, so a file with none enabled needs no request; the
|
||||
// others go out together, as VS Code sends them, instead of one round trip per file.
|
||||
let (files, idle): (Vec<_>, Vec<_>) = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|(p, b)| (p.clone(), b.clone()))
|
||||
.partition(|(_, b)| b.iter().any(|b| b.enabled));
|
||||
let sent = join_all(files.iter().map(|(path, bps)| s.send_breakpoints(path, bps, None))).await;
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> =
|
||||
self.breakpoints.lock().iter().map(|(p, b)| (p.clone(), b.clone())).collect();
|
||||
// Breakpoint states follow the owner's first session.
|
||||
let first = self.live_sessions().into_iter().find(|f| f.owner.key == s.owner.key).map(|f| f.id) == Some(s.id);
|
||||
let idle = idle.into_iter().map(|(path, bps)| (path, Ok(unsent(&bps))));
|
||||
for (path, result) in files.into_iter().map(|(path, _)| path).zip(sent).chain(idle) {
|
||||
match result {
|
||||
for (path, bps) in files {
|
||||
match s.send_breakpoints(&path, &bps, None).await {
|
||||
Ok(states) => {
|
||||
if first {
|
||||
self.states.lock().insert(path.clone(), states);
|
||||
@@ -1011,7 +990,16 @@ impl DebugManager {
|
||||
Err(e) => tracing::debug!("setBreakpoints on session {} failed: {e}", s.id.0),
|
||||
}
|
||||
}
|
||||
let states = result.unwrap_or_else(|| unsent(&breakpoints));
|
||||
let states = result.unwrap_or_else(|| {
|
||||
breakpoints
|
||||
.iter()
|
||||
.map(|b| BreakpointState {
|
||||
line: b.line,
|
||||
verified: false,
|
||||
message: (!b.enabled).then(|| "Disabled".to_owned()),
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
self.states.lock().insert(path, states.clone());
|
||||
Ok(states)
|
||||
}
|
||||
@@ -1339,26 +1327,13 @@ impl DebugManager {
|
||||
/// Sends empty breakpoint lists (line, function, data) to `session` until its next
|
||||
/// stop, when the stored ones are restored. `except` is left to the caller.
|
||||
async fn suspend_breakpoints(&self, session: &Arc<Session>, except: Option<&Path>) -> IdeResult<()> {
|
||||
// While paused the adapter holds the stored lists: only files with something enabled change.
|
||||
let files: Vec<PathBuf> = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
let sent = join_all(files.iter().map(|path| session.send_breakpoints(path, &[], None))).await;
|
||||
let mut failed = None;
|
||||
for (path, result) in files.into_iter().zip(sent) {
|
||||
match result {
|
||||
Ok(_) => {
|
||||
session.pending_restore.lock().files.insert(path);
|
||||
}
|
||||
Err(e) => failed = failed.or(Some(e)),
|
||||
let files: Vec<PathBuf> = self.breakpoints.lock().keys().cloned().collect();
|
||||
for path in files {
|
||||
if Some(path.as_path()) == except {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Some(e) = failed {
|
||||
return Err(e.into());
|
||||
session.send_breakpoints(&path, &[], None).await?;
|
||||
session.pending_restore.lock().files.insert(path);
|
||||
}
|
||||
if !self.function_breakpoints.lock().is_empty() && session.supports("supportsFunctionBreakpoints") {
|
||||
session.send_function_breakpoints(&[]).await?;
|
||||
@@ -1374,11 +1349,9 @@ impl DebugManager {
|
||||
/// Re-sends what [`suspend_breakpoints`](Self::suspend_breakpoints) / run to cursor replaced.
|
||||
pub(crate) async fn restore_breakpoints(&self, session: &Arc<Session>) {
|
||||
let pending = std::mem::take(&mut *session.pending_restore.lock());
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> =
|
||||
pending.files.into_iter().map(|path| (path.clone(), self.stored_breakpoints(&path))).collect();
|
||||
let sent = join_all(files.iter().map(|(path, bps)| session.send_breakpoints(path, bps, None))).await;
|
||||
for ((path, _), result) in files.iter().zip(sent) {
|
||||
if let Err(e) = result {
|
||||
for path in pending.files {
|
||||
let bps = self.stored_breakpoints(&path);
|
||||
if let Err(e) = session.send_breakpoints(&path, &bps, None).await {
|
||||
tracing::debug!("restoring breakpoints of {} failed: {e}", path.display());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,8 +17,6 @@ struct Script {
|
||||
start_debugging: bool,
|
||||
ignore_configuration_done: bool,
|
||||
source_path: Option<String>,
|
||||
/// Answer `setBreakpoints` only once this many are waiting (a client that waits for each never gets one).
|
||||
hold_set_breakpoints: usize,
|
||||
}
|
||||
|
||||
struct FakeLauncher {
|
||||
@@ -51,7 +49,6 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
let mut r = BufReader::new(r);
|
||||
let mut seq = 1000;
|
||||
let mut pending_launch: Option<i64> = None;
|
||||
let mut held: Vec<Value> = Vec::new();
|
||||
macro_rules! send {
|
||||
($v:expr) => {{
|
||||
let mut v: Value = $v;
|
||||
@@ -104,20 +101,14 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
send!(json!({"type": "event", "event": "initialized"}));
|
||||
}
|
||||
"setBreakpoints" => {
|
||||
held.push(msg);
|
||||
if held.len() < script.hold_set_breakpoints {
|
||||
continue;
|
||||
}
|
||||
for msg in std::mem::take(&mut held) {
|
||||
let bps: Vec<Value> = msg["arguments"]["breakpoints"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, b)| json!({"id": i + 1, "verified": true, "line": b["line"]}))
|
||||
.collect();
|
||||
ok!(msg, json!({"breakpoints": bps}));
|
||||
}
|
||||
let bps: Vec<Value> = msg["arguments"]["breakpoints"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, b)| json!({"id": i + 1, "verified": true, "line": b["line"]}))
|
||||
.collect();
|
||||
ok!(msg, json!({"breakpoints": bps}));
|
||||
}
|
||||
"setExceptionBreakpoints" => ok!(msg, json!({})),
|
||||
"setFunctionBreakpoints" | "setDataBreakpoints" => {
|
||||
@@ -930,7 +921,6 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
let b = PathBuf::from("/p/b.py");
|
||||
h.manager.set_breakpoints(a.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(b.clone(), vec![bp(3)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
h.manager.set_function_breakpoints(vec![function_bp("run", true)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
@@ -959,24 +949,6 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
h.manager.run_to(id, 1, a.clone(), 9, true).await.unwrap();
|
||||
assert_eq!(sent_for("/p/a.py").last().unwrap(), &json!([{"line": 10}]));
|
||||
assert_eq!(sent_for("/p/b.py").last().unwrap(), &json!([]));
|
||||
assert!(sent_for("/p/off.py").is_empty(), "nothing enabled there, nothing to suspend or restore");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled() {
|
||||
let h = harness(Script { hold_set_breakpoints: 2, ..Script::default() });
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
|
||||
let off = PathBuf::from("/p/off.py");
|
||||
h.manager.set_breakpoints(off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
// Waiting for each answer before the next request would stall until the request timeout.
|
||||
tokio::time::timeout(Duration::from_secs(5), h.start(config())).await.expect("requests pipelined").unwrap();
|
||||
let paths: Vec<Value> = requests(&h, "setBreakpoints").into_iter().map(|r| r["source"]["path"].clone()).collect();
|
||||
assert_eq!(paths, [json!("/p/a.py"), json!("/p/b.py")]);
|
||||
assert_eq!(
|
||||
h.manager.breakpoint_states(&off),
|
||||
[BreakpointState { line: 5, verified: false, message: Some("Disabled".into()) }]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -103,20 +103,12 @@ pub enum RemoteOp {
|
||||
Pull {
|
||||
rebase: bool,
|
||||
},
|
||||
/// Update Project › Reset to the Remote Branch.
|
||||
ResetToUpstream,
|
||||
Push {
|
||||
force_with_lease: bool,
|
||||
set_upstream: bool,
|
||||
/// Push dialog › Push tags.
|
||||
#[serde(default)]
|
||||
tags: Option<PushTags>,
|
||||
/// Plain `--force` (Force push anyway).
|
||||
#[serde(default)]
|
||||
force: bool,
|
||||
/// Push dialog › Run Git hooks unchecked (`--no-verify`).
|
||||
#[serde(default)]
|
||||
no_verify: bool,
|
||||
},
|
||||
/// Deletes a remote branch; `branch` is the remote-tracking name (`origin/feature`).
|
||||
DeleteBranch {
|
||||
@@ -133,23 +125,6 @@ pub enum RemoteOp {
|
||||
target: Option<String>,
|
||||
#[serde(default)]
|
||||
remote: Option<String>,
|
||||
#[serde(default)]
|
||||
force: bool,
|
||||
/// Record the target as upstream (Push dialog › Set upstream).
|
||||
#[serde(default)]
|
||||
set_upstream: bool,
|
||||
#[serde(default)]
|
||||
no_verify: bool,
|
||||
},
|
||||
/// Push Tag › Push to `remote`.
|
||||
PushTag {
|
||||
tag: String,
|
||||
remote: String,
|
||||
},
|
||||
/// Deletes tag `tag` on `remote` (Delete on Remote).
|
||||
DeleteRemoteTag {
|
||||
tag: String,
|
||||
remote: String,
|
||||
},
|
||||
/// Fast-forwards local `branch` (not checked out) to its upstream.
|
||||
UpdateBranch {
|
||||
@@ -180,15 +155,11 @@ pub struct GitExecutableInfo {
|
||||
pub enum GitOperation {
|
||||
/// Continue the merge / rebase / cherry-pick / revert in progress.
|
||||
Continue,
|
||||
/// Stage and Retry: stage the changes of tracked files, then continue.
|
||||
StageAndContinue,
|
||||
Abort,
|
||||
Skip,
|
||||
/// Commits oldest first; `record_origin` adds "(cherry picked from commit …)".
|
||||
/// Commits oldest first.
|
||||
CherryPick {
|
||||
commits: Vec<String>,
|
||||
#[serde(default, rename = "recordOrigin")]
|
||||
record_origin: bool,
|
||||
},
|
||||
/// Commits newest first.
|
||||
Revert {
|
||||
@@ -601,33 +572,6 @@ pub async fn vcs_undo_commit(host: &Host, window: &str, repo: Option<PathBuf>, c
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.undo_commit(&commit))).await
|
||||
}
|
||||
|
||||
/// Edit Commit Message: rewrites the commit and its descendants without touching the
|
||||
/// working tree.
|
||||
pub async fn vcs_reword(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
commit: String,
|
||||
message: String,
|
||||
) -> IdeResult<ide_vcs::HeadChange> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.reword(&commit, &message))).await
|
||||
}
|
||||
|
||||
/// Undo of a history rewrite (Edit Commit Message, Drop, Squash).
|
||||
pub async fn vcs_restore_head(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
before: String,
|
||||
after: String,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.restore_head(&before, &after))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_delete_branch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -640,19 +584,6 @@ pub async fn vcs_delete_branch(
|
||||
}
|
||||
|
||||
/// "Restore" of the branch-deleted notification.
|
||||
/// Deletes a local tag; the result restores it.
|
||||
pub async fn vcs_delete_tag(host: &Host, window: &str, repo: Option<PathBuf>, name: String) -> IdeResult<DeletedTag> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.delete_tag(&name))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_restore_tag(host: &Host, window: &str, repo: Option<PathBuf>, deleted: DeletedTag) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.restore_tag(&deleted))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_restore_branch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -748,42 +679,26 @@ pub async fn vcs_remote(
|
||||
let out = |line: String| {
|
||||
let _ = on_output.send(line);
|
||||
};
|
||||
let recorded = matches!(op, RemoteOp::Pull { .. } | RemoteOp::PullFrom { .. } | RemoteOp::ResetToUpstream)
|
||||
.then_some("Git pull");
|
||||
let recorded = matches!(op, RemoteOp::Pull { .. } | RemoteOp::PullFrom { .. }).then_some("Git pull");
|
||||
project.with_repo_recorded(repo.as_deref(), recorded, |r| match op {
|
||||
RemoteOp::Fetch => r.fetch(&cancel, &out),
|
||||
RemoteOp::Pull { rebase } => r.pull(rebase, &cancel, &out),
|
||||
RemoteOp::ResetToUpstream => r.reset_to_upstream(&cancel, &out),
|
||||
RemoteOp::Push { force_with_lease, set_upstream, tags, force, no_verify } => {
|
||||
r.push_with(PushOptions { force_with_lease, force, set_upstream, tags, no_verify }, &cancel, &out)
|
||||
RemoteOp::Push { force_with_lease, set_upstream, tags } => {
|
||||
r.push_with_tags(force_with_lease, set_upstream, tags, &cancel, &out)
|
||||
}
|
||||
RemoteOp::DeleteBranch { branch } => r.delete_remote_branch(&branch, &cancel, &out),
|
||||
RemoteOp::PushBranch {
|
||||
branch,
|
||||
revision,
|
||||
force_with_lease,
|
||||
target,
|
||||
remote,
|
||||
force,
|
||||
set_upstream,
|
||||
no_verify,
|
||||
} => r.push_branch_to(
|
||||
RemoteOp::PushBranch { branch, revision, force_with_lease, target, remote } => r.push_branch_to(
|
||||
&branch,
|
||||
PushBranchOptions {
|
||||
revision: revision.as_deref(),
|
||||
target: target.as_deref(),
|
||||
remote: remote.as_deref(),
|
||||
force_with_lease,
|
||||
force,
|
||||
set_upstream,
|
||||
no_verify,
|
||||
},
|
||||
&cancel,
|
||||
&out,
|
||||
),
|
||||
RemoteOp::UpdateBranch { branch } => r.update_branch(&branch, &cancel, &out),
|
||||
RemoteOp::PushTag { tag, remote } => r.push_tag(&tag, &remote, &cancel, &out),
|
||||
RemoteOp::DeleteRemoteTag { tag, remote } => r.delete_remote_tag(&tag, &remote, &cancel, &out),
|
||||
RemoteOp::PullFrom { remote, branches, rebase, options } => {
|
||||
r.pull_from(&remote, &branches, rebase, &options, &cancel, &out)
|
||||
}
|
||||
@@ -919,12 +834,9 @@ pub async fn vcs_operation(
|
||||
};
|
||||
project.with_repo_recorded(repo.as_deref(), recorded, |r| match op {
|
||||
GitOperation::Continue => r.continue_operation(&cancel, &out),
|
||||
GitOperation::StageAndContinue => r.stage_and_continue(&cancel, &out),
|
||||
GitOperation::Abort => r.abort_operation(&cancel, &out),
|
||||
GitOperation::Skip => r.skip_operation(&cancel, &out),
|
||||
GitOperation::CherryPick { commits, record_origin } => {
|
||||
r.cherry_pick_with(&commits, record_origin, &cancel, &out)
|
||||
}
|
||||
GitOperation::CherryPick { commits } => r.cherry_pick(&commits, &cancel, &out),
|
||||
GitOperation::Revert { commits } => r.revert(&commits, &cancel, &out),
|
||||
GitOperation::Reset { commit, mode } => r.reset(&commit, mode, &cancel, &out),
|
||||
GitOperation::InteractiveRebase { base, entries } => {
|
||||
@@ -1108,12 +1020,6 @@ pub async fn vcs_diff_numstat(
|
||||
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.diff_numstat(&from, &to, &paths))).await
|
||||
}
|
||||
|
||||
/// Whether the repository has the executable Git hook `name` (Push dialog › Run Git hooks).
|
||||
pub async fn vcs_has_hook(host: &Host, window: &str, repo: Option<PathBuf>, name: String) -> IdeResult<bool> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.has_hook(&name))).await
|
||||
}
|
||||
|
||||
/// The best common ancestor of `a` and `b` (`git merge-base`), if any: the New Pull
|
||||
/// Request tab's three-dot diff.
|
||||
pub async fn vcs_merge_base(
|
||||
@@ -1341,22 +1247,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
"vcs_undo_commit",
|
||||
|c| async move { vcs_undo_commit(&c.host, &c.window, c.arg("repo")?, c.arg("commit")?).await },
|
||||
);
|
||||
d.add("vcs_reword", |c| async move {
|
||||
vcs_reword(&c.host, &c.window, c.arg("repo")?, c.arg("commit")?, c.arg("message")?).await
|
||||
});
|
||||
d.add("vcs_restore_head", |c| async move {
|
||||
vcs_restore_head(&c.host, &c.window, c.arg("repo")?, c.arg("before")?, c.arg("after")?).await
|
||||
});
|
||||
d.add("vcs_delete_branch", |c| async move {
|
||||
vcs_delete_branch(&c.host, &c.window, c.arg("repo")?, c.arg("branch")?).await
|
||||
});
|
||||
d.add(
|
||||
"vcs_delete_tag",
|
||||
|c| async move { vcs_delete_tag(&c.host, &c.window, c.arg("repo")?, c.arg("name")?).await },
|
||||
);
|
||||
d.add("vcs_restore_tag", |c| async move {
|
||||
vcs_restore_tag(&c.host, &c.window, c.arg("repo")?, c.arg("deleted")?).await
|
||||
});
|
||||
d.add("vcs_restore_branch", |c| async move {
|
||||
vcs_restore_branch(&c.host, &c.window, c.arg("repo")?, c.arg("deleted")?).await
|
||||
});
|
||||
@@ -1480,7 +1373,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("vcs_diff_numstat", |c| async move {
|
||||
vcs_diff_numstat(&c.host, &c.window, c.arg("repo")?, c.arg("from")?, c.arg("to")?, c.arg("paths")?).await
|
||||
});
|
||||
d.add("vcs_has_hook", |c| async move { vcs_has_hook(&c.host, &c.window, c.arg("repo")?, c.arg("name")?).await });
|
||||
d.add("vcs_merge_base", |c| async move {
|
||||
vcs_merge_base(&c.host, &c.window, c.arg("repo")?, c.arg("a")?, c.arg("b")?).await
|
||||
});
|
||||
|
||||
@@ -526,7 +526,6 @@ impl Host {
|
||||
}));
|
||||
}
|
||||
self.insert_project(window, project.clone());
|
||||
project.lsp.prewarm_java_configuration();
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
bridge.start(&self.runtime);
|
||||
}
|
||||
|
||||
@@ -121,7 +121,6 @@ impl crate::Host {
|
||||
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
|
||||
}
|
||||
project.lsp.set_execution_allowed(true);
|
||||
project.lsp.prewarm_java_configuration();
|
||||
} else {
|
||||
self.environment.project_closed();
|
||||
project.agents.shutdown();
|
||||
@@ -341,7 +340,6 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "vcs_diff_revisions"
|
||||
| "vcs_diff_numstat"
|
||||
| "vcs_merge_base"
|
||||
| "vcs_has_hook"
|
||||
| "vcs_shelves"
|
||||
| "vcs_shelf_patch"
|
||||
| "vcs_changelists_load"
|
||||
|
||||
@@ -327,36 +327,6 @@ impl LspManager {
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// Start Java in trusted build-root projects during idle startup, so configuration
|
||||
/// navigation can warm after import even when no Java editor has been opened.
|
||||
pub fn prewarm_java_configuration(self: &Arc<Self>) {
|
||||
let weak = Arc::downgrade(self);
|
||||
self.runtime.spawn(async move {
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
let Some(mgr) = weak.upgrade() else { return };
|
||||
if mgr.shutting_down.load(std::sync::atomic::Ordering::Acquire)
|
||||
|| !mgr.execution_allowed.load(std::sync::atomic::Ordering::Acquire)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let root = mgr.project_root.clone();
|
||||
let java_project = tokio::task::spawn_blocking(move || {
|
||||
["pom.xml", "build.gradle", "build.gradle.kts", ".classpath"]
|
||||
.iter()
|
||||
.any(|name| root.join(name).is_file())
|
||||
})
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
if java_project {
|
||||
for server in mgr.servers_for(&LanguageId::new("java"), &mgr.project_root) {
|
||||
if server.name == SERVER {
|
||||
mgr.ensure_started(&server);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn java_import_ready(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
|
||||
let mgr = self.clone();
|
||||
self.runtime.spawn(async move {
|
||||
@@ -364,32 +334,6 @@ impl LspManager {
|
||||
if let Err(e) = mgr.java_configure_compiler(&server, &run).await {
|
||||
tracing::warn!("jdtls: cannot apply compiler defaults: {e}");
|
||||
}
|
||||
// The extension only queues bounded, low-priority work; this request
|
||||
// never waits for the configuration index itself to be built.
|
||||
const WARMUP: &str = "openidea.java.configuration.warmup";
|
||||
if server.running_gen(generation).is_some()
|
||||
&& run.caps.read().commands().iter().any(|command| command == WARMUP)
|
||||
{
|
||||
let preferred: Vec<_> = mgr
|
||||
.docs
|
||||
.lock()
|
||||
.values()
|
||||
.filter(|doc| matches!(doc.language.as_str(), "yaml" | "properties"))
|
||||
.map(|doc| doc.uri.to_string())
|
||||
.collect();
|
||||
let result = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
run.peer.request::<_, Value>(
|
||||
"workspace/executeCommand",
|
||||
json!({"command": WARMUP, "arguments": ["start", preferred]}),
|
||||
None,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
if !matches!(result, Ok(Ok(_))) {
|
||||
tracing::debug!("jdtls: configuration warmup unavailable; retaining on-demand navigation");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -814,7 +758,7 @@ mod tests {
|
||||
for wrapped in [false, true] {
|
||||
let mut cfg = java_config();
|
||||
let settings = json!({"java": {"project": {"referencedLibraries": ["vendor/*.jar"]}}});
|
||||
cfg.settings = Some(if wrapped { json!({ "settings": settings }) } else { settings });
|
||||
cfg.settings = Some(if wrapped { json!({"settings": settings}) } else { settings });
|
||||
configure_source_paths(&mut cfg, Some(vec!["custom".into()]));
|
||||
let settings = crate::handler::all_settings(&cfg);
|
||||
assert_eq!(settings["java"]["project"]["referencedLibraries"], json!(["vendor/*.jar"]));
|
||||
|
||||
@@ -2377,7 +2377,7 @@ async fn class_file_opening_routes_sources_and_binary_documents() {
|
||||
let source = sources.join("p/Outer.java");
|
||||
std::fs::write(&source, "package p; class Outer {} ").unwrap();
|
||||
s.respond("java/classFileContents", json!("// Source code is decompiled from a .class file using FernFlower decompiler (from Intellij IDEA).\npackage p;\npublic class Outer {}"));
|
||||
s.respond("workspace/executeCommand", json!({ "org.eclipse.jdt.ls.core.sourcePaths": [sources] }));
|
||||
s.respond("workspace/executeCommand", json!({"org.eclipse.jdt.ls.core.sourcePaths":[sources]}));
|
||||
for class in ["Outer", "Outer$Nested", "Outer$1"] {
|
||||
let path = h.root.join(format!("target/classes/p/{class}.class"));
|
||||
let resolved = h.mgr.java_class_file(&path, None).await.unwrap();
|
||||
@@ -3394,7 +3394,7 @@ async fn gopls_interactive_command_validates_before_execution_and_applies_edits(
|
||||
let reply: Value = tokio::task::block_in_place(|| {
|
||||
tokio::runtime::Handle::current().block_on(s.peer().request(
|
||||
"workspace/applyEdit",
|
||||
json!({ "edit": edit }),
|
||||
json!({"edit": edit}),
|
||||
None,
|
||||
))
|
||||
})
|
||||
@@ -3679,54 +3679,6 @@ async fn configuration_extension_failure_preserves_native_java_navigation() {
|
||||
assert_eq!(s.requested("textDocument/definition").len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn configuration_prewarm_starts_java_without_an_open_editor_and_waits_for_import() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({"commands": ["openidea.java.configuration.warmup"]});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
std::fs::write(h.root.join("pom.xml"), "<project/>").unwrap();
|
||||
let s = h.launcher.state("jdtls");
|
||||
h.mgr.prewarm_java_configuration();
|
||||
h.mgr.prewarm_java_configuration();
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
assert_eq!(s.launches.load(Ordering::SeqCst), 1);
|
||||
assert!(s.requested("workspace/executeCommand").is_empty());
|
||||
let config = h.root.join("application.yml");
|
||||
h.mgr.did_open(DocId::next(), &config, &LanguageId::new("yaml"), 1, "app: {}\n");
|
||||
s.peer().notify("language/status", json!({"type": "ServiceReady"})).unwrap();
|
||||
eventually(|| {
|
||||
s.requested("workspace/executeCommand").iter().any(|p| p["command"] == "openidea.java.configuration.warmup")
|
||||
})
|
||||
.await;
|
||||
let requests = s.requested("workspace/executeCommand");
|
||||
let warmup = requests.iter().find(|p| p["command"] == "openidea.java.configuration.warmup").unwrap();
|
||||
assert_eq!(warmup["arguments"], json!(["start", [uri_of(&config)]]));
|
||||
assert!(s.notified("textDocument/didOpen").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn configuration_prewarm_respects_trust_shutdown_and_non_java_roots() {
|
||||
let mut fixtures = Vec::new();
|
||||
for mode in ["untrusted", "closed", "non-java"] {
|
||||
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
if mode != "non-java" {
|
||||
std::fs::write(h.root.join("pom.xml"), "<project/>").unwrap();
|
||||
}
|
||||
if mode == "untrusted" {
|
||||
h.mgr.set_execution_allowed(false);
|
||||
}
|
||||
h.mgr.prewarm_java_configuration();
|
||||
if mode == "closed" {
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
fixtures.push(h);
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(2200)).await;
|
||||
for h in fixtures {
|
||||
assert_eq!(h.launcher.state("jdtls").launches.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The configuration command indexes the whole project, so Go to Definition (and
|
||||
/// every Ctrl+hover probe) consults it only inside a key argument; ordinary Java
|
||||
/// symbols in a Spring file go straight to JDT.
|
||||
|
||||
@@ -880,7 +880,7 @@ mod tests {
|
||||
configure_jdtls(&mut plain, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
|
||||
let data = |c: &LanguageServerConfig| c.args[c.args.iter().position(|a| a == "-data").unwrap() + 1].clone();
|
||||
assert_ne!(data(&cfg), data(&plain), "a separate workspace, so everything is rebuilt with the agent");
|
||||
let patched = Path::new("/managed/lombok-1.18.48-openidea.3.jar");
|
||||
let patched = Path::new("/managed/lombok-1.18.48-openidea.2.jar");
|
||||
let mut fixed = jdtls();
|
||||
configure_jdtls(
|
||||
&mut fixed,
|
||||
@@ -894,23 +894,6 @@ mod tests {
|
||||
Some(patched),
|
||||
);
|
||||
assert_ne!(data(&cfg), data(&fixed), "the patch must rebuild classes compiled with the official agent");
|
||||
let mut previous = jdtls();
|
||||
configure_jdtls(
|
||||
&mut previous,
|
||||
Path::new("/p"),
|
||||
Path::new("/data"),
|
||||
&[],
|
||||
None,
|
||||
None,
|
||||
JDTLS_MIN_JAVA,
|
||||
&[],
|
||||
Some(Path::new("/managed/lombok-1.18.48-openidea.2.jar")),
|
||||
);
|
||||
assert_ne!(
|
||||
data(&previous),
|
||||
data(&fixed),
|
||||
"the new patch must rebuild classes compiled with the previous bundle"
|
||||
);
|
||||
let before = cfg.clone();
|
||||
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], Some(jar));
|
||||
assert_eq!(cfg, before, "idempotent");
|
||||
@@ -1186,7 +1169,7 @@ mod kotlin_bridge_bundle_tests {
|
||||
|
||||
/// Installs the app-owned JDT LS command bundle, falling back to ordinary LSP on IO failure.
|
||||
pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
|
||||
let extension = data_dir.join("java-usages-1.6.0.jar");
|
||||
let extension = data_dir.join("java-usages-1.5.0.jar");
|
||||
let bytes = include_bytes!("../../../java/java-usages/openidea-java-usages.jar");
|
||||
if std::fs::read(&extension).is_ok_and(|old| old == bytes) {
|
||||
clean_usages_bundles(data_dir, &extension);
|
||||
|
||||
@@ -507,7 +507,7 @@ mod tests {
|
||||
let cache = repo.join("org/projectlombok/lombok/1.18.48");
|
||||
fs::create_dir_all(&cache).unwrap();
|
||||
fs::write(cache.join("lombok-1.18.48.jar"), b"official agent").unwrap();
|
||||
let patched = PathBuf::from("/managed/lombok-1.18.48-openidea.3.jar");
|
||||
let patched = PathBuf::from("/managed/lombok-1.18.48-openidea.2.jar");
|
||||
let selected = lombok_agent(tmp.path(), None, Some(patched.clone()), Some(repo.clone()));
|
||||
assert_eq!(selected.jar(), Some(patched.as_path()));
|
||||
assert_eq!(selected.problem(), None);
|
||||
|
||||
@@ -1221,26 +1221,10 @@ impl Tools {
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<sources::Download> {
|
||||
match source {
|
||||
ReleaseSource::GitHub { repo } => match http.get_text(&sources::github_latest_url(repo), cancel) {
|
||||
Ok(json) => sources::github_pick(&json, assets, self.platform),
|
||||
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
|
||||
// Without a token the API allows 60 requests an hour per IP address, often used
|
||||
// up behind a shared one (403/429); the release's web pages have no such limit.
|
||||
Err(api) => self.resolve_github_web(http, repo, assets, cancel).map_err(|web| {
|
||||
if web.kind == ErrorKind::Cancelled {
|
||||
return web;
|
||||
}
|
||||
tracing::warn!("GitHub release lookup for {repo} failed: {api}; web pages: {web}");
|
||||
IdeError::new(
|
||||
api.kind,
|
||||
format!(
|
||||
"{}\nDownload it from {} and set its Path in Settings › Languages & Frameworks › Language Servers.",
|
||||
api.message,
|
||||
sources::github_latest_page(repo)
|
||||
),
|
||||
)
|
||||
}),
|
||||
},
|
||||
ReleaseSource::GitHub { repo } => {
|
||||
let json = http.get_text(&sources::github_latest_url(repo), cancel)?;
|
||||
sources::github_pick(&json, assets, self.platform)
|
||||
}
|
||||
ReleaseSource::HashiCorp { product } => {
|
||||
let json = http.get_text(&sources::hashicorp_latest_url(product), cancel)?;
|
||||
sources::hashicorp_pick(&json, assets, self.platform)
|
||||
@@ -1267,27 +1251,6 @@ impl Tools {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`resolve_release`](Self::resolve_release) for a GitHub release, from its web pages.
|
||||
fn resolve_github_web(
|
||||
&self,
|
||||
http: &Http,
|
||||
repo: &str,
|
||||
assets: &[platform::AssetRule],
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<sources::Download> {
|
||||
let page = http.effective_url(&sources::github_latest_page(repo), cancel)?;
|
||||
let tag = sources::github_tag_from_url(&page)
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{repo} has no published release")))?;
|
||||
let list = http.get_text(&sources::github_assets_page(repo, &tag), cancel)?;
|
||||
match sources::github_pick_web(repo, &tag, &list, None, assets, self.platform) {
|
||||
Err(e) if e.kind == ErrorKind::Unavailable => {
|
||||
let notes = http.get_text(&sources::github_tag_page(repo, &tag), cancel)?;
|
||||
sources::github_pick_web(repo, &tag, &list, Some(¬es), assets, self.platform)
|
||||
}
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
fn install_release(
|
||||
&self,
|
||||
spec: &ToolSpec,
|
||||
|
||||
@@ -263,15 +263,6 @@ fn curl_takes_revoke_best_effort(version: &str) -> bool {
|
||||
(major, minor) >= (7, 70) && first.split_whitespace().any(|w| w.eq_ignore_ascii_case("schannel"))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Request {
|
||||
Get,
|
||||
/// Adoptium uses 404 as well as an empty array for absent platform builds.
|
||||
GetOrEmptyOn404,
|
||||
/// Headers, then the URL redirects ended at.
|
||||
Head,
|
||||
}
|
||||
|
||||
/// HTTP via the system `curl` (shipped with macOS, Windows 10+ and every
|
||||
/// mainstream Linux), so the IDE carries no TLS stack of its own.
|
||||
pub struct Http {
|
||||
@@ -345,39 +336,26 @@ impl Http {
|
||||
self.get_text_limited(url, None, cancel)
|
||||
}
|
||||
|
||||
/// Where `url` ends up after redirects (a HEAD request).
|
||||
pub fn effective_url(&self, url: &str, cancel: &CancellationToken) -> IdeResult<String> {
|
||||
let out = self.get_text_response(url, None, Request::Head, cancel)?;
|
||||
Ok(out.trim_end().rsplit('\n').next().unwrap_or_default().trim().to_owned())
|
||||
}
|
||||
|
||||
/// GETs `url` as text, failing when the response is larger than `max_bytes`.
|
||||
pub fn get_text_limited(&self, url: &str, max_bytes: Option<u64>, cancel: &CancellationToken) -> IdeResult<String> {
|
||||
self.get_text_response(url, max_bytes, Request::Get, cancel)
|
||||
self.get_text_response(url, max_bytes, false, cancel)
|
||||
}
|
||||
|
||||
/// Adoptium uses 404 as well as an empty array for absent platform builds.
|
||||
pub fn get_text_or_empty_on_404(&self, url: &str, cancel: &CancellationToken) -> IdeResult<String> {
|
||||
self.get_text_response(url, None, Request::GetOrEmptyOn404, cancel)
|
||||
self.get_text_response(url, None, true, cancel)
|
||||
}
|
||||
|
||||
fn get_text_response(
|
||||
&self,
|
||||
url: &str,
|
||||
max_bytes: Option<u64>,
|
||||
request: Request,
|
||||
empty_on_404: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
let (mut cmd, token) = self.base(url, cancel)?;
|
||||
let empty_on_404 = request == Request::GetOrEmptyOn404;
|
||||
match request {
|
||||
Request::Get => {}
|
||||
Request::GetOrEmptyOn404 => {
|
||||
cmd.args(["--write-out", "\n%{http_code}"]);
|
||||
}
|
||||
Request::Head => {
|
||||
cmd.args(["--head", "--write-out", "\n%{url_effective}"]);
|
||||
}
|
||||
if empty_on_404 {
|
||||
cmd.args(["--write-out", "\n%{http_code}"]);
|
||||
}
|
||||
if let Some(max) = max_bytes {
|
||||
cmd.arg("--max-filesize").arg(max.to_string());
|
||||
|
||||
@@ -646,13 +646,12 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
// Equinox removed getModuleClassLoader(boolean), breaking lombok.config lookup (lombok#4059);
|
||||
// ECJ 3.46.200 keeps the constructor call in a constructor's statements, which
|
||||
// @SneakyThrows / @NonNull must not wrap or precede (lombok#4089).
|
||||
// Builders on compact record constructors need the patch in java/lombok/patches.
|
||||
// Return to Maven Central once an official release includes all of these fixes.
|
||||
// Return to Maven Central once an official release includes both.
|
||||
// Source commit, build instructions and checksum: java/lombok/README.md.
|
||||
method: Method::Bundled {
|
||||
filename: "lombok-1.18.48-openidea.3.jar",
|
||||
version: "1.18.48-openidea.3",
|
||||
bytes: include_bytes!("../../../java/lombok/lombok-1.18.48-openidea.3.jar"),
|
||||
filename: "lombok-1.18.48-openidea.2.jar",
|
||||
version: "1.18.48-openidea.2",
|
||||
bytes: include_bytes!("../../../java/lombok/lombok-1.18.48-openidea.2.jar"),
|
||||
},
|
||||
fallback: None,
|
||||
version: V,
|
||||
|
||||
@@ -47,146 +47,38 @@ pub fn github_latest_url(repo: &str) -> String {
|
||||
format!("https://api.github.com/repos/{repo}/releases/latest")
|
||||
}
|
||||
|
||||
/// The latest release's web page; it redirects to `…/releases/tag/<tag>`. Web pages don't
|
||||
/// count against the API's rate limit for unauthenticated clients (60 requests an hour).
|
||||
pub fn github_latest_page(repo: &str) -> String {
|
||||
format!("https://github.com/{repo}/releases/latest")
|
||||
}
|
||||
|
||||
/// The tag `github_latest_page` redirected to.
|
||||
pub fn github_tag_from_url(url: &str) -> Option<String> {
|
||||
let (_, tag) = url.split_once("/releases/tag/")?;
|
||||
let tag = tag.split(['?', '#']).next().unwrap_or(tag).trim_end_matches('/');
|
||||
(!tag.is_empty()).then(|| percent_decode(tag))
|
||||
}
|
||||
|
||||
pub fn github_tag_page(repo: &str, tag: &str) -> String {
|
||||
format!("https://github.com/{repo}/releases/tag/{tag}")
|
||||
}
|
||||
|
||||
/// The asset list the release page loads (HTML).
|
||||
pub fn github_assets_page(repo: &str, tag: &str) -> String {
|
||||
format!("https://github.com/{repo}/releases/expanded_assets/{tag}")
|
||||
}
|
||||
|
||||
/// One file of a release, from the API or its web page.
|
||||
struct ReleaseAsset {
|
||||
name: String,
|
||||
url: String,
|
||||
size: Option<u64>,
|
||||
sha256: Option<String>,
|
||||
}
|
||||
|
||||
/// Picks the platform asset from a GitHub `releases/latest` response. Links
|
||||
/// in the release notes count as assets too (some projects host binaries on
|
||||
/// a CDN and only link them).
|
||||
pub fn github_pick(json: &str, rules: &[AssetRule], platform: Platform) -> IdeResult<Download> {
|
||||
let rel: GhRelease = serde_json::from_str(json).map_err(|e| proto(format!("unexpected GitHub response: {e}")))?;
|
||||
let assets: Vec<ReleaseAsset> = rel
|
||||
.assets
|
||||
.into_iter()
|
||||
.map(|a| ReleaseAsset {
|
||||
sha256: a.digest.as_deref().and_then(|d| d.strip_prefix("sha256:")).map(str::to_ascii_lowercase),
|
||||
name: a.name,
|
||||
url: a.browser_download_url,
|
||||
size: a.size,
|
||||
})
|
||||
.collect();
|
||||
pick_release(&rel.tag_name, &assets, rel.body.as_deref().unwrap_or(""), rules, platform)
|
||||
}
|
||||
|
||||
/// [`github_pick`] from the release's web pages: `assets_html` from [`github_assets_page`] and,
|
||||
/// for projects that only link their builds, `notes_html` from [`github_tag_page`].
|
||||
pub fn github_pick_web(
|
||||
repo: &str,
|
||||
tag: &str,
|
||||
assets_html: &str,
|
||||
notes_html: Option<&str>,
|
||||
rules: &[AssetRule],
|
||||
platform: Platform,
|
||||
) -> IdeResult<Download> {
|
||||
let prefix = format!("href=\"/{repo}/releases/download/");
|
||||
let mut assets: Vec<ReleaseAsset> = Vec::new();
|
||||
let mut rest = assets_html;
|
||||
while let Some(i) = rest.find(&prefix) {
|
||||
let tail = &rest[i + "href=\"".len()..];
|
||||
let Some(end) = tail.find('"') else { break };
|
||||
let path = html_unescape(&tail[..end]);
|
||||
rest = &tail[end..];
|
||||
let name = percent_decode(file_name(&path));
|
||||
if name.is_empty() || assets.iter().any(|a| a.name == name) {
|
||||
continue;
|
||||
}
|
||||
// `<clipboard-copy aria-label="Copy to clipboard digest for <name>" … value="sha256:<hex>">`
|
||||
let sha256 = assets_html.find(&format!("digest for {}\"", html_escape(&name))).and_then(|at| {
|
||||
let tag_end = assets_html[at..].find('>').map_or(assets_html.len(), |e| at + e);
|
||||
let value = assets_html[at..tag_end].split_once("value=\"sha256:")?.1;
|
||||
let hex: String = value.chars().take_while(char::is_ascii_hexdigit).collect();
|
||||
(hex.len() == 64).then(|| hex.to_ascii_lowercase())
|
||||
});
|
||||
assets.push(ReleaseAsset { url: format!("https://github.com{path}"), name, size: None, sha256 });
|
||||
}
|
||||
pick_release(tag, &assets, &html_unescape(notes_html.unwrap_or("")), rules, platform)
|
||||
}
|
||||
|
||||
fn pick_release(
|
||||
tag: &str,
|
||||
assets: &[ReleaseAsset],
|
||||
notes: &str,
|
||||
rules: &[AssetRule],
|
||||
platform: Platform,
|
||||
) -> IdeResult<Download> {
|
||||
let version = tag.trim_start_matches('v').to_string();
|
||||
let names: Vec<&str> = assets.iter().map(|a| a.name.as_str()).collect();
|
||||
let version = rel.tag_name.trim_start_matches('v').to_string();
|
||||
let names: Vec<&str> = rel.assets.iter().map(|a| a.name.as_str()).collect();
|
||||
if let Some(name) = select_asset(&names, rules, platform) {
|
||||
let a = assets.iter().find(|a| a.name == name).expect("selected from list");
|
||||
let checksum_url = assets
|
||||
let a = rel.assets.iter().find(|a| a.name == name).expect("selected from list");
|
||||
let sha256 = a.digest.as_deref().and_then(|d| d.strip_prefix("sha256:")).map(str::to_ascii_lowercase);
|
||||
let checksum_url = rel
|
||||
.assets
|
||||
.iter()
|
||||
.find(|c| c.name == format!("{name}.sha256") || c.name == format!("{name}.sha256sum"))
|
||||
.map(|c| c.url.clone());
|
||||
.map(|c| c.browser_download_url.clone());
|
||||
return Ok(Download {
|
||||
version,
|
||||
name: a.name.clone(),
|
||||
url: a.url.clone(),
|
||||
url: a.browser_download_url.clone(),
|
||||
size: a.size,
|
||||
sha256: a.sha256.clone(),
|
||||
sha256,
|
||||
checksum_url,
|
||||
});
|
||||
}
|
||||
let links = extract_links(notes);
|
||||
let links = extract_links(rel.body.as_deref().unwrap_or(""));
|
||||
let link_names: Vec<&str> = links.iter().map(|u| file_name(u)).collect();
|
||||
if let Some(name) = select_asset(&link_names, rules, platform) {
|
||||
let url = links.iter().find(|u| file_name(u) == name).expect("selected from list").clone();
|
||||
let checksum_url = links.iter().find(|u| *u == &format!("{url}.sha256")).cloned();
|
||||
return Ok(Download { version, name: name.to_string(), url, size: None, sha256: None, checksum_url });
|
||||
}
|
||||
Err(IdeError::unavailable(format!("release {tag} has no build for this platform")))
|
||||
}
|
||||
|
||||
fn html_unescape(s: &str) -> String {
|
||||
s.replace(""", "\"").replace("'", "'").replace("<", "<").replace(">", ">").replace("&", "&")
|
||||
}
|
||||
|
||||
fn html_escape(s: &str) -> String {
|
||||
s.replace('&', "&").replace('"', """).replace('<', "<").replace('>', ">")
|
||||
}
|
||||
|
||||
fn percent_decode(s: &str) -> String {
|
||||
let bytes = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%'
|
||||
&& let Some(b) = s.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
|
||||
{
|
||||
out.push(b);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8(out).unwrap_or_else(|_| s.to_owned())
|
||||
Err(IdeError::unavailable(format!("release {} has no build for this platform", rel.tag_name)))
|
||||
}
|
||||
|
||||
fn file_name(url: &str) -> &str {
|
||||
@@ -444,71 +336,6 @@ mod tests {
|
||||
assert_eq!(d.name, "kotlin-lsp-0.253.10629-linux-x64.zip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_tag_from_redirect() {
|
||||
let url = "https://github.com/Kotlin/kotlin-lsp/releases/tag/kotlin-lsp/v263.7084.0";
|
||||
assert_eq!(github_tag_from_url(url).as_deref(), Some("kotlin-lsp/v263.7084.0"));
|
||||
let url = "https://github.com/o/r/releases/tag/v1.0%2Bbuild";
|
||||
assert_eq!(github_tag_from_url(url).as_deref(), Some("v1.0+build"));
|
||||
// A repository without releases stays on the list.
|
||||
assert_eq!(github_tag_from_url("https://github.com/o/r/releases"), None);
|
||||
}
|
||||
|
||||
/// Trimmed from `github.com/<repo>/releases/expanded_assets/<tag>`.
|
||||
const ASSETS_HTML: &str = r#"<li><div><a href="/LuaLS/lua-language-server/releases/download/3.13.5/lua-language-server-3.13.5-darwin-arm64.tar.gz" rel="nofollow" data-turbo="false" class="wb-break-all">
|
||||
<span class="text-bold">lua-language-server-3.13.5-darwin-arm64.tar.gz</span></a></div>
|
||||
<span class="Truncate-text">sha256:ABCDEF0123456789abcdef0123456789abcdef0123456789abcdef0123456789</span>
|
||||
<clipboard-copy id="clipboard-button-sha256:abc" aria-label="Copy to clipboard digest for lua-language-server-3.13.5-darwin-arm64.tar.gz" type="button" value="sha256:ABCDEF0123456789abcdef0123456789abcdef0123456789abcdef0123456789" class="Button"></clipboard-copy></li>
|
||||
<li><a href="/LuaLS/lua-language-server/releases/download/3.13.5/lua-language-server-3.13.5-linux-x64.tar.gz" rel="nofollow">lua-language-server-3.13.5-linux-x64.tar.gz</a></li>
|
||||
<li><a href="/LuaLS/lua-language-server/archive/refs/tags/3.13.5.zip" rel="nofollow">Source code (zip)</a></li>"#;
|
||||
|
||||
#[test]
|
||||
fn github_web_assets_with_digest() {
|
||||
let rules = find("lua-language-server").unwrap().asset_rules();
|
||||
let d = github_pick_web("LuaLS/lua-language-server", "3.13.5", ASSETS_HTML, None, rules, MAC_ARM).unwrap();
|
||||
assert_eq!(d.version, "3.13.5");
|
||||
assert_eq!(d.name, "lua-language-server-3.13.5-darwin-arm64.tar.gz");
|
||||
assert_eq!(
|
||||
d.url,
|
||||
"https://github.com/LuaLS/lua-language-server/releases/download/3.13.5/lua-language-server-3.13.5-darwin-arm64.tar.gz"
|
||||
);
|
||||
assert_eq!(d.sha256.as_deref(), Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"));
|
||||
let d = github_pick_web("LuaLS/lua-language-server", "3.13.5", ASSETS_HTML, None, rules, LINUX).unwrap();
|
||||
assert_eq!(d.sha256, None);
|
||||
let win = Platform { os: Os::Windows, arch: Arch::X64 };
|
||||
let err = github_pick_web("LuaLS/lua-language-server", "3.13.5", ASSETS_HTML, None, rules, win).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_web_sibling_checksum_and_notes_links() {
|
||||
let html = r#"<a href="/artempyanykh/marksman/releases/download/2024-12-18/marksman-macos" rel="nofollow">
|
||||
<a href="/artempyanykh/marksman/releases/download/2024-12-18/marksman-macos.sha256" rel="nofollow">"#;
|
||||
let d = github_pick_web(
|
||||
"artempyanykh/marksman",
|
||||
"2024-12-18",
|
||||
html,
|
||||
None,
|
||||
find("marksman").unwrap().asset_rules(),
|
||||
MAC_ARM,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
d.checksum_url.as_deref(),
|
||||
Some("https://github.com/artempyanykh/marksman/releases/download/2024-12-18/marksman-macos.sha256")
|
||||
);
|
||||
|
||||
let notes = r#"<li><a href="https://download-cdn.jetbrains.com/kotlin-lsp/0.253.10629/kotlin-lsp-0.253.10629-mac-aarch64.zip?a=1&b=2" rel="nofollow">macOS arm</a></li>"#;
|
||||
let rules = find("kotlin-lsp").unwrap().asset_rules();
|
||||
let d =
|
||||
github_pick_web("Kotlin/kotlin-lsp", "kotlin-lsp/v0.253.10629", "", Some(notes), rules, MAC_ARM).unwrap();
|
||||
assert_eq!(d.name, "kotlin-lsp-0.253.10629-mac-aarch64.zip");
|
||||
assert_eq!(
|
||||
d.url,
|
||||
"https://download-cdn.jetbrains.com/kotlin-lsp/0.253.10629/kotlin-lsp-0.253.10629-mac-aarch64.zip?a=1&b=2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hashicorp() {
|
||||
let json = r#"{"version":"0.36.4","url_shasums":"https://r/terraform-ls_0.36.4_SHA256SUMS","builds":[
|
||||
|
||||
@@ -58,20 +58,16 @@ fn bundled_lombok_replaces_legacy_installs_on_every_platform_without_downloads()
|
||||
fs::create_dir_all(legacy.parent().unwrap()).unwrap();
|
||||
fs::write(&legacy, b"old official agent").unwrap();
|
||||
fs::write(env.root.join("lombok").join(MANIFEST), r#"{"version":"1.18.48"}"#).unwrap();
|
||||
let previous = env.root.join("lombok/bin/lombok-1.18.48-openidea.2.jar");
|
||||
fs::write(&previous, b"previous bundled agent").unwrap();
|
||||
let tools = Tools::with_paths(env.root.clone(), OsString::new(), Platform { os, arch });
|
||||
let info = tools.info("lombok", &[]).unwrap();
|
||||
let path = managed_bundle(env.root.parent().unwrap(), "lombok").unwrap();
|
||||
assert_eq!(info.status, ToolStatus::Installed);
|
||||
assert_eq!(info.version.as_deref(), Some("1.18.48-openidea.3"));
|
||||
assert_eq!(info.version.as_deref(), Some("1.18.48-openidea.2"));
|
||||
assert_eq!(info.path, Some(path.clone().into()));
|
||||
assert_eq!(path.file_name().unwrap(), "lombok-1.18.48-openidea.3.jar");
|
||||
assert_eq!(path.file_name().unwrap(), "lombok-1.18.48-openidea.2.jar");
|
||||
assert!(!info.can_install && !info.can_uninstall);
|
||||
assert_eq!(tools.unavailable_reason(registry::find("lombok").unwrap()), None);
|
||||
assert_eq!(fs::read(&legacy).unwrap(), b"old official agent", "other windows may still use it");
|
||||
assert_ne!(path, previous, "new agent path must invalidate the JDT LS workspace");
|
||||
assert_eq!(fs::read(&previous).unwrap(), b"previous bundled agent", "other windows may still use it");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,131 +93,6 @@ fn git_select(
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The commits of a file's history and the path it had in each. The commits that changed
|
||||
/// the path, merges included (`--full-history --simplify-merges`); where it appears, a
|
||||
/// rename from any parent continues the history under the old path from that parent.
|
||||
/// Unlike `--follow`, this sees renames done in merges and history merged in from other
|
||||
/// branches.
|
||||
fn file_history(
|
||||
r: &Repo,
|
||||
scopes: &[String],
|
||||
rel: &str,
|
||||
first_parent: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<(HashSet<ObjectId>, HashMap<ObjectId, String>)> {
|
||||
let mut ids = HashSet::new();
|
||||
let mut paths = HashMap::new();
|
||||
let mut starts: std::collections::VecDeque<(Vec<String>, String)> =
|
||||
scopes.iter().map(|s| (s.split_whitespace().map(str::to_string).collect(), rel.to_string())).collect();
|
||||
let mut started = HashSet::new();
|
||||
while let Some((revs, path)) = starts.pop_front() {
|
||||
if !started.insert((revs.clone(), path.clone())) {
|
||||
continue;
|
||||
}
|
||||
let mut args: Vec<String> =
|
||||
["log", "--format=%x00%H", "--name-status", "-z", "--full-history", "--simplify-merges", "--no-follow"]
|
||||
.map(String::from)
|
||||
.into();
|
||||
if first_parent {
|
||||
args.push("--first-parent".into());
|
||||
}
|
||||
args.push("--end-of-options".into());
|
||||
args.extend(revs);
|
||||
let pathspec = ["--".to_string(), format!(":(literal){path}")];
|
||||
let run = |args: &[String]| -> IdeResult<Vec<(ObjectId, Option<char>)>> {
|
||||
let argv: Vec<&str> = args.iter().chain(&pathspec).map(String::as_str).collect();
|
||||
Ok(parse_name_status_log(&crate::cli::run_cancellable(r.root(), &argv, cancel)?.stdout_str()))
|
||||
};
|
||||
let records = run(&args)?;
|
||||
// Where the file appears its history ends: what is behind that is another file of
|
||||
// the same name (a rename continues the history below). The commits of the history
|
||||
// are those not behind a creation; the statuses come from the full listing (with
|
||||
// its parents excluded a merge shows no changes).
|
||||
let created: Vec<ObjectId> = records.iter().filter(|(_, s)| *s == Some('A')).map(|(id, _)| *id).collect();
|
||||
let kept: Option<HashSet<ObjectId>> = if created.is_empty() {
|
||||
None
|
||||
} else {
|
||||
args.extend(created.iter().map(|id| format!("^{id}^@")));
|
||||
Some(run(&args)?.into_iter().map(|(id, _)| id).collect())
|
||||
};
|
||||
let mut created = Vec::new();
|
||||
for (id, first_status) in records {
|
||||
if kept.as_ref().is_some_and(|k| !k.contains(&id)) || !ids.insert(id) {
|
||||
continue;
|
||||
}
|
||||
paths.insert(id, path.clone());
|
||||
if first_status == Some('A') {
|
||||
created.push(id);
|
||||
}
|
||||
}
|
||||
for commit in created {
|
||||
let line = crate::cli::run_cancellable(
|
||||
r.root(),
|
||||
&["rev-list", "--parents", "-n", "1", "--end-of-options", &commit.to_string()],
|
||||
cancel,
|
||||
)?
|
||||
.stdout_str();
|
||||
let parents: Vec<&str> =
|
||||
line.split_whitespace().skip(1).take(if first_parent { 1 } else { usize::MAX }).collect();
|
||||
for parent in parents {
|
||||
if let Some(old) = renamed_from(r, parent, &commit.to_string(), &path, cancel)? {
|
||||
starts.push_back((vec![parent.to_string()], old));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((ids, paths))
|
||||
}
|
||||
|
||||
/// `git log --format=%x00%H --name-status -z`: each commit with the status letter of its
|
||||
/// first change (none for a merge listed without changes).
|
||||
fn parse_name_status_log(text: &str) -> Vec<(ObjectId, Option<char>)> {
|
||||
let mut out: Vec<(ObjectId, Option<char>)> = Vec::new();
|
||||
let mut tokens = text.split('\0');
|
||||
while let Some(token) = tokens.next() {
|
||||
let token = token.trim_start_matches('\n');
|
||||
if let Ok(id) = ObjectId::from_hex(token.as_bytes()) {
|
||||
out.push((id, None));
|
||||
continue;
|
||||
}
|
||||
let Some(status) = token.chars().next().filter(|c| c.is_ascii_uppercase()) else { continue };
|
||||
if !token[1..].bytes().all(|b| b.is_ascii_digit()) {
|
||||
continue;
|
||||
}
|
||||
let paths = if matches!(status, 'R' | 'C') { 2 } else { 1 };
|
||||
for _ in 0..paths {
|
||||
tokens.next();
|
||||
}
|
||||
if let Some(last) = out.last_mut() {
|
||||
last.1.get_or_insert(status);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The path `path` had in `parent` when `commit` renamed it.
|
||||
fn renamed_from(
|
||||
r: &Repo,
|
||||
parent: &str,
|
||||
commit: &str,
|
||||
path: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<String>> {
|
||||
let args = ["diff", "-M", "--name-status", "-z", "--diff-filter=R", "--no-ext-diff", parent, commit, "--"];
|
||||
let text = crate::cli::run_cancellable(r.root(), &args, cancel)?.stdout_str();
|
||||
let mut tokens = text.split('\0');
|
||||
while let Some(status) = tokens.next() {
|
||||
if !status.starts_with('R') {
|
||||
continue;
|
||||
}
|
||||
let (Some(old), Some(new)) = (tokens.next(), tokens.next()) else { break };
|
||||
if new == path {
|
||||
return Ok(Some(old.to_string()));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResult<Vec<Commit>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -355,8 +230,45 @@ fn log_indexed(
|
||||
let path_ids = if paths.is_empty() {
|
||||
None
|
||||
} else if q.follow && paths.len() == 1 {
|
||||
let (ids, at) = file_history(r, &scopes, &paths[0], q.first_parent, cancel)?;
|
||||
history_paths = at;
|
||||
let mut ids = HashSet::new();
|
||||
let rel = &paths[0];
|
||||
let mut args = vec![
|
||||
"log".to_string(),
|
||||
"--format=%x00%H".into(),
|
||||
"--name-status".into(),
|
||||
"-z".into(),
|
||||
"--follow".into(),
|
||||
"--topo-order".into(),
|
||||
];
|
||||
if q.first_parent {
|
||||
args.push("--first-parent".into());
|
||||
}
|
||||
args.push("--end-of-options".into());
|
||||
for scope in &scopes {
|
||||
let mut args = args.clone();
|
||||
args.extend(scope.split_whitespace().map(str::to_string));
|
||||
args.extend(["--".into(), rel.clone()]);
|
||||
let output =
|
||||
crate::cli::run_cancellable(r.root(), &args.iter().map(String::as_str).collect::<Vec<_>>(), cancel)?;
|
||||
let text = output.stdout_str();
|
||||
let mut tokens = text.split('\0').peekable();
|
||||
let mut current_path = rel.clone();
|
||||
while let Some(token) = tokens.next() {
|
||||
let token = token.trim_start_matches('\n');
|
||||
if let Ok(id) = ObjectId::from_hex(token.as_bytes()) {
|
||||
ids.insert(id);
|
||||
history_paths.insert(id, current_path.clone());
|
||||
} else if token.starts_with('R') && token[1..].bytes().all(|b| b.is_ascii_digit()) {
|
||||
if let (Some(old), Some(new)) = (tokens.next(), tokens.next())
|
||||
&& new == current_path
|
||||
{
|
||||
current_path = old.to_string();
|
||||
}
|
||||
} else if ["A", "D", "M", "T", "U"].contains(&token) {
|
||||
tokens.next();
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(ids)
|
||||
} else {
|
||||
Some(git_select(r, &scopes, &[], &paths, q.first_parent, cancel)?)
|
||||
|
||||
@@ -273,12 +273,6 @@ pub struct CommitOptions {
|
||||
/// entries of the index change; afterwards their index entries match the new commit.
|
||||
#[serde(default)]
|
||||
pub partial: Vec<PartialCommitFile>,
|
||||
/// Files committed with their working-tree content, staged or not.
|
||||
#[serde(default)]
|
||||
pub stage: Vec<ide_core::IpcPath>,
|
||||
/// Staged files left out of the commit; they stay staged afterwards.
|
||||
#[serde(default)]
|
||||
pub exclude: Vec<ide_core::IpcPath>,
|
||||
}
|
||||
|
||||
/// A file of a partial commit: which of its changes against HEAD to commit.
|
||||
@@ -362,27 +356,6 @@ pub struct PushBranchOptions<'a> {
|
||||
pub remote: Option<&'a str>,
|
||||
/// `git push --force-with-lease`.
|
||||
pub force_with_lease: bool,
|
||||
/// `git push --force` (Force push anyway after a rejected force-with-lease push).
|
||||
pub force: bool,
|
||||
/// Record the target as the branch's upstream even when it already has one.
|
||||
pub set_upstream: bool,
|
||||
/// Skip the pre-push hook (`--no-verify`).
|
||||
pub no_verify: bool,
|
||||
}
|
||||
|
||||
/// Options of [`Repo::push_with`]: the Push dialog's choices for the current branch.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct PushOptions {
|
||||
/// `git push --force-with-lease`.
|
||||
pub force_with_lease: bool,
|
||||
/// `git push --force` (Force push anyway after a rejected force-with-lease push).
|
||||
pub force: bool,
|
||||
/// Push to the branch's remote under the same name and record it as upstream.
|
||||
pub set_upstream: bool,
|
||||
/// Push tags too.
|
||||
pub tags: Option<PushTags>,
|
||||
/// Skip the pre-push hook (`--no-verify`).
|
||||
pub no_verify: bool,
|
||||
}
|
||||
|
||||
/// What an interactive rebase does with one commit.
|
||||
@@ -507,10 +480,6 @@ pub enum CheckoutOutcome {
|
||||
LocalChanges {
|
||||
files: Vec<String>,
|
||||
},
|
||||
/// These untracked files (repository-relative paths) would be overwritten.
|
||||
UntrackedFiles {
|
||||
files: Vec<String>,
|
||||
},
|
||||
/// Local branch `local` has commits that remote branch `remote` does not.
|
||||
LocalBranchAhead {
|
||||
local: String,
|
||||
@@ -523,14 +492,6 @@ pub enum CheckoutOutcome {
|
||||
},
|
||||
}
|
||||
|
||||
/// HEAD before and after a history rewrite, for its Undo.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HeadChange {
|
||||
pub before: String,
|
||||
pub after: String,
|
||||
}
|
||||
|
||||
/// A deleted local branch, enough to restore it (IDEA's "Restore" notification action).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -544,15 +505,6 @@ pub struct DeletedBranch {
|
||||
pub unmerged: bool,
|
||||
}
|
||||
|
||||
/// A deleted tag, enough to restore it (Restore in the tag-deleted notification).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeletedTag {
|
||||
pub name: String,
|
||||
/// What the tag pointed at: its tag object (annotated tags) or commit.
|
||||
pub target: String,
|
||||
}
|
||||
|
||||
/// Who stands on each side of the conflicts of the operation in progress (merge editor
|
||||
/// titles, as IDEA labels them).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -623,8 +575,6 @@ mod log_index;
|
||||
mod manage;
|
||||
mod ops;
|
||||
mod patch;
|
||||
mod preserve;
|
||||
pub use ops::UNSTAGED_CHANGES_PREVENT_REBASE;
|
||||
mod refs;
|
||||
mod remotes;
|
||||
mod repo;
|
||||
@@ -1056,7 +1006,7 @@ impl Repo {
|
||||
/// `amend` keeps the previous message.
|
||||
pub fn commit(&self, message: &str, amend: bool, sign_off: bool) -> IdeResult<String> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let options = CommitOptions { amend, sign_off, author: None, run_hooks: true, ..Default::default() };
|
||||
let options = CommitOptions { amend, sign_off, author: None, run_hooks: true, partial: Vec::new() };
|
||||
write::commit(self, message, &options, &|_| Ok(encoding_rs::UTF_8.into()))
|
||||
}
|
||||
/// Commits with the Commit Options popup's choices.
|
||||
@@ -1098,17 +1048,6 @@ impl Repo {
|
||||
write::undo_commit(self, commit)
|
||||
}
|
||||
/// Deletes a local branch (`git branch -d`, `-D` when `force`).
|
||||
/// Edit Commit Message without touching the index or the working tree; returns HEAD
|
||||
/// before and after.
|
||||
pub fn reword(&self, commit: &str, message: &str) -> IdeResult<HeadChange> {
|
||||
write::reword(self, commit, message).map(|(before, after)| HeadChange { before, after })
|
||||
}
|
||||
|
||||
/// Undoes a history rewrite: HEAD goes from `after` back to `before`, local changes kept.
|
||||
pub fn restore_head(&self, before: &str, after: &str) -> IdeResult<()> {
|
||||
write::restore_head(self, before, after)
|
||||
}
|
||||
|
||||
pub fn delete_branch(&self, branch: &str, force: bool) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::delete_branch(self, branch, force)
|
||||
@@ -1185,11 +1124,9 @@ impl Repo {
|
||||
pub fn pull(&self, rebase: bool, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let mode: &[&str] = if rebase { &["--rebase"] } else { &["--no-rebase", "--ff"] };
|
||||
let mut args = vec!["pull", "--progress"];
|
||||
let mut args = vec!["pull", "--progress", "--autostash"];
|
||||
args.extend_from_slice(mode);
|
||||
preserve::around(self, "Local changes saved before update", || {
|
||||
cli::run_streaming(&self.root, &args, cancel, on_output)
|
||||
})
|
||||
cli::run_streaming(&self.root, &args, cancel, on_output)
|
||||
}
|
||||
/// Pushes the current branch. `set_upstream` pushes to the branch's remote (or
|
||||
/// `origin`) under the same name and records it as upstream.
|
||||
@@ -1200,7 +1137,8 @@ impl Repo {
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
self.push_with(PushOptions { force_with_lease, set_upstream, ..Default::default() }, cancel, on_output)
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::push(self, force_with_lease, set_upstream, None, cancel, on_output)
|
||||
}
|
||||
/// [`Repo::push`] that also pushes tags (Push dialog › Push tags).
|
||||
pub fn push_with_tags(
|
||||
@@ -1210,23 +1148,9 @@ impl Repo {
|
||||
tags: Option<PushTags>,
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
self.push_with(PushOptions { force_with_lease, set_upstream, tags, ..Default::default() }, cancel, on_output)
|
||||
}
|
||||
/// Pushes the current branch with the Push dialog's options.
|
||||
pub fn push_with(
|
||||
&self,
|
||||
options: PushOptions,
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::push(self, options, cancel, on_output)
|
||||
}
|
||||
/// Whether the repository has an executable hook `name` (e.g. `pre-push`), wherever
|
||||
/// `core.hooksPath` puts it: the Push dialog then offers to skip it.
|
||||
pub fn has_hook(&self, name: &str) -> IdeResult<bool> {
|
||||
write::has_hook(self, name)
|
||||
write::push(self, force_with_lease, set_upstream, tags, cancel, on_output)
|
||||
}
|
||||
/// Pushes a local branch, or its history up to `revision`, to its upstream (Git Log
|
||||
/// › Push…, Push All up to Here).
|
||||
@@ -1260,12 +1184,6 @@ impl Repo {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::push_branch(self, branch, options, cancel, on_output)
|
||||
}
|
||||
/// Update Project › Reset to the Remote Branch: the current branch is moved to its
|
||||
/// freshly fetched tracked branch; local commits are dropped, local changes kept.
|
||||
pub fn reset_to_upstream(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
write::reset_to_upstream(self, cancel, on_output)
|
||||
}
|
||||
/// Fast-forwards a local branch that is not checked out to its upstream (Branches ›
|
||||
/// Update). Fails when the branch has diverged.
|
||||
pub fn update_branch(&self, branch: &str, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
@@ -1278,12 +1196,7 @@ impl Repo {
|
||||
/// conflicts are unresolved.
|
||||
pub fn continue_operation(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::continue_op(self, false, cancel, on_output)
|
||||
}
|
||||
/// Stage and Retry: stages the changes of tracked files, then continues.
|
||||
pub fn stage_and_continue(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::continue_op(self, true, cancel, on_output)
|
||||
ops::continue_op(self, cancel, on_output)
|
||||
}
|
||||
pub fn abort_operation(&self, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
@@ -1300,19 +1213,9 @@ impl Repo {
|
||||
commits: &[String],
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
self.cherry_pick_with(commits, false, cancel, on_output)
|
||||
}
|
||||
/// [`Repo::cherry_pick`]; `record_origin` adds "(cherry picked from commit …)" (`-x`).
|
||||
pub fn cherry_pick_with(
|
||||
&self,
|
||||
commits: &[String],
|
||||
record_origin: bool,
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::cherry_pick(self, commits, record_origin, cancel, on_output)
|
||||
ops::cherry_pick(self, commits, cancel, on_output)
|
||||
}
|
||||
/// Reverts `commits` in order (newest first) with git's default messages.
|
||||
pub fn revert(&self, commits: &[String], cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
@@ -1348,38 +1251,6 @@ impl Repo {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::create_tag(self, name, commit, message, force)
|
||||
}
|
||||
/// Deletes a local tag, returning what [`Repo::restore_tag`] needs to undo it.
|
||||
pub fn delete_tag(&self, name: &str) -> IdeResult<DeletedTag> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::delete_tag(self, name)
|
||||
}
|
||||
/// Recreates a deleted tag (annotated ones with their message).
|
||||
pub fn restore_tag(&self, deleted: &DeletedTag) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::restore_tag(self, deleted)
|
||||
}
|
||||
/// Pushes one tag to `remote` (Push Tag › Push to …).
|
||||
pub fn push_tag(
|
||||
&self,
|
||||
tag: &str,
|
||||
remote: &str,
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::push_tag(self, tag, remote, false, cancel, on_output)
|
||||
}
|
||||
/// Deletes a tag on `remote` (Delete on Remote, after deleting it locally).
|
||||
pub fn delete_remote_tag(
|
||||
&self,
|
||||
tag: &str,
|
||||
remote: &str,
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::push_tag(self, tag, remote, true, cancel, on_output)
|
||||
}
|
||||
pub fn tags(&self) -> IdeResult<Vec<String>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
ops::tags(self)
|
||||
|
||||
@@ -106,7 +106,7 @@ pub(crate) fn merge_args(branches: &[String], o: &MergeOptions) -> IdeResult<Vec
|
||||
if branches.is_empty() {
|
||||
return Err(IdeError::invalid("no branch to merge"));
|
||||
}
|
||||
let mut args: Vec<String> = vec!["merge".into()];
|
||||
let mut args: Vec<String> = vec!["merge".into(), "--autostash".into()];
|
||||
args.extend(merge_flags(o)?.into_iter().map(String::from));
|
||||
match o.message.as_deref().map(str::trim).filter(|m| !m.is_empty()) {
|
||||
Some(m) => args.extend(["-m".into(), m.to_string()]),
|
||||
@@ -120,7 +120,7 @@ pub(crate) fn merge_args(branches: &[String], o: &MergeOptions) -> IdeResult<Vec
|
||||
|
||||
/// `git rebase` arguments for the Rebase dialog.
|
||||
pub(crate) fn rebase_args(upstream: &str, o: &RebaseOptions) -> IdeResult<Vec<String>> {
|
||||
let mut args: Vec<String> = vec!["rebase".into()];
|
||||
let mut args: Vec<String> = vec!["rebase".into(), "--autostash".into()];
|
||||
if o.rebase_merges {
|
||||
args.push("--rebase-merges".into());
|
||||
}
|
||||
@@ -137,7 +137,7 @@ pub(crate) fn rebase_args(upstream: &str, o: &RebaseOptions) -> IdeResult<Vec<St
|
||||
/// `git pull` arguments for the Pull dialog: `remote` and its `branches` (none = the
|
||||
/// upstream's configured merge branch).
|
||||
pub(crate) fn pull_args(remote: &str, branches: &[String], rebase: bool, o: &MergeOptions) -> IdeResult<Vec<String>> {
|
||||
let mut args: Vec<String> = vec!["pull".into(), "--progress".into()];
|
||||
let mut args: Vec<String> = vec!["pull".into(), "--progress".into(), "--autostash".into()];
|
||||
if rebase {
|
||||
if o.no_ff || o.ff_only || o.squash || o.no_commit {
|
||||
return Err(IdeError::invalid("--rebase cannot be combined with merge options"));
|
||||
@@ -213,7 +213,7 @@ impl Repo {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let args = merge_args(branches, options)?;
|
||||
let args: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
crate::preserve::around(self, "Local changes saved before merge", || run(self.root(), &args, None).map(|_| ()))
|
||||
run(self.root(), &args, None).map(|_| ())
|
||||
}
|
||||
|
||||
/// Rebases the current branch onto `upstream` (or `upstream..HEAD` onto `options.onto`).
|
||||
@@ -221,7 +221,7 @@ impl Repo {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let args = rebase_args(upstream, options)?;
|
||||
let args: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
crate::preserve::around(self, "Local changes saved before rebase", || run(self.root(), &args, None).map(|_| ()))
|
||||
run(self.root(), &args, None).map(|_| ())
|
||||
}
|
||||
|
||||
/// Git › Pull…: pulls `branches` of `remote` into the current branch.
|
||||
@@ -237,9 +237,7 @@ impl Repo {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
let args = pull_args(remote, branches, rebase, options)?;
|
||||
let args: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
crate::preserve::around(self, "Local changes saved before update", || {
|
||||
cli::run_streaming(self.root(), &args, cancel, on_output)
|
||||
})
|
||||
cli::run_streaming(self.root(), &args, cancel, on_output)
|
||||
}
|
||||
|
||||
/// Manage Remotes: adds, removes or edits a remote.
|
||||
@@ -307,10 +305,13 @@ mod tests {
|
||||
#[test]
|
||||
fn merge_args_follow_the_options() {
|
||||
let o = MergeOptions { no_ff: true, message: Some("Merge it".into()), ..Default::default() };
|
||||
assert_eq!(merge_args(&["dev".into()], &o).unwrap(), ["merge", "--no-ff", "-m", "Merge it", "dev"]);
|
||||
assert_eq!(
|
||||
merge_args(&["dev".into()], &o).unwrap(),
|
||||
["merge", "--autostash", "--no-ff", "-m", "Merge it", "dev"]
|
||||
);
|
||||
assert_eq!(
|
||||
merge_args(&["a".into(), "b".into()], &MergeOptions::default()).unwrap(),
|
||||
["merge", "--no-edit", "a", "b"]
|
||||
["merge", "--autostash", "--no-edit", "a", "b"]
|
||||
);
|
||||
let bad = MergeOptions { ff_only: true, squash: true, ..Default::default() };
|
||||
assert!(merge_args(&["dev".into()], &bad).is_err());
|
||||
@@ -321,15 +322,18 @@ mod tests {
|
||||
#[test]
|
||||
fn rebase_and_pull_args() {
|
||||
let o = RebaseOptions { onto: Some("main".into()), rebase_merges: true, keep_empty: false };
|
||||
assert_eq!(rebase_args("feature~3", &o).unwrap(), ["rebase", "--rebase-merges", "--onto", "main", "feature~3"]);
|
||||
assert_eq!(
|
||||
rebase_args("feature~3", &o).unwrap(),
|
||||
["rebase", "--autostash", "--rebase-merges", "--onto", "main", "feature~3"]
|
||||
);
|
||||
assert_eq!(
|
||||
pull_args("origin", &["main".into()], false, &MergeOptions { ff_only: true, ..Default::default() })
|
||||
.unwrap(),
|
||||
["pull", "--progress", "--no-rebase", "--ff-only", "origin", "main"]
|
||||
["pull", "--progress", "--autostash", "--no-rebase", "--ff-only", "origin", "main"]
|
||||
);
|
||||
assert_eq!(
|
||||
pull_args("origin", &[], true, &MergeOptions::default()).unwrap(),
|
||||
["pull", "--progress", "--rebase", "origin"]
|
||||
["pull", "--progress", "--autostash", "--rebase", "origin"]
|
||||
);
|
||||
assert!(pull_args("origin", &[], true, &MergeOptions { squash: true, ..Default::default() }).is_err());
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ use crate::cli::{self, run};
|
||||
use crate::repo::{gx, resolve};
|
||||
use crate::{ChangeKind, ChangedFile, FileLineStats, MergeSides, RebaseAction, RebaseEntry, Repo, ResetMode};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// The in-progress operation git can continue / abort / skip.
|
||||
fn sequencer(r: &Repo) -> IdeResult<&'static str> {
|
||||
@@ -58,8 +57,7 @@ pub(crate) fn merge_sides(r: &Repo) -> IdeResult<MergeSides> {
|
||||
Some("cherry-pick") => sides.commit = read("CHERRY_PICK_HEAD").map(short),
|
||||
Some("revert") => sides.commit = read("REVERT_HEAD").map(short),
|
||||
// Conflicts outside an operation come from restoring stashed changes (Smart
|
||||
// Checkout, local changes put aside for a merge or update): stage 2 is the new HEAD,
|
||||
// stage 3 the user's.
|
||||
// Checkout, update with autostash): stage 2 is the new HEAD, stage 3 the user's.
|
||||
None if !crate::write::unmerged_paths(r)?.is_empty() => {
|
||||
sides.operation = Some("unstash".into());
|
||||
sides.reversed = true;
|
||||
@@ -115,38 +113,13 @@ fn check_commits(commits: &[String]) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Why a rebase can't continue: tracked files changed while it was stopped, not staged.
|
||||
pub const UNSTAGED_CHANGES_PREVENT_REBASE: &str =
|
||||
"There are unstaged changes in tracked files preventing rebase from continuing";
|
||||
|
||||
fn changed_paths(r: &Repo, args: &[&str]) -> IdeResult<Vec<String>> {
|
||||
let text = run(r.root(), args, None)?.stdout_str();
|
||||
Ok(text.split('\0').filter(|p| !p.is_empty()).map(str::to_string).collect())
|
||||
}
|
||||
|
||||
/// Concludes the operation in progress once every conflict is resolved (staged).
|
||||
/// `stage` first stages the changes of tracked files (Stage and Retry). Without it a
|
||||
/// rebase stages only edits of files already staged (made while resolving them) and
|
||||
/// otherwise fails with [`UNSTAGED_CHANGES_PREVENT_REBASE`].
|
||||
pub(crate) fn continue_op(r: &Repo, stage: bool, cancel: &CancellationToken, out: &dyn Fn(String)) -> IdeResult<()> {
|
||||
pub(crate) fn continue_op(r: &Repo, cancel: &CancellationToken, out: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let op = sequencer(r)?;
|
||||
let unresolved = unmerged_paths(r)?;
|
||||
if !unresolved.is_empty() {
|
||||
return Err(IdeError::invalid(format!("resolve all conflicts before continuing: {}", unresolved.join(", "))));
|
||||
}
|
||||
if stage {
|
||||
run(r.root(), &["add", "-u"], None)?;
|
||||
} else if op == "rebase" {
|
||||
let unstaged = changed_paths(r, &["diff", "--name-only", "-z", "--no-ext-diff"])?;
|
||||
if !unstaged.is_empty() {
|
||||
let staged: HashSet<String> =
|
||||
changed_paths(r, &["diff", "--cached", "--name-only", "-z", "--no-ext-diff"])?.into_iter().collect();
|
||||
if !unstaged.iter().all(|p| staged.contains(p)) {
|
||||
return Err(IdeError::invalid(UNSTAGED_CHANGES_PREVENT_REBASE));
|
||||
}
|
||||
cli::run_paths(r.root(), &["add", "-u"], &unstaged)?;
|
||||
}
|
||||
}
|
||||
let args: &[&str] = match op {
|
||||
// `git merge --continue` commits with the prepared MERGE_MSG.
|
||||
"merge" => &["merge", "--continue"],
|
||||
@@ -155,16 +128,12 @@ pub(crate) fn continue_op(r: &Repo, stage: bool, cancel: &CancellationToken, out
|
||||
"revert" => &["revert", "--continue"],
|
||||
_ => &["am", "--continue"],
|
||||
};
|
||||
let result = cli::run_streaming(r.root(), args, cancel, out);
|
||||
let finished = finish_operation(r);
|
||||
result.and(finished)
|
||||
cli::run_streaming(r.root(), args, cancel, out)
|
||||
}
|
||||
|
||||
pub(crate) fn abort_op(r: &Repo, cancel: &CancellationToken, out: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let op = sequencer(r)?;
|
||||
let result = cli::run_streaming(r.root(), &[op, "--abort"], cancel, out);
|
||||
let finished = finish_operation(r);
|
||||
result.and(finished)
|
||||
cli::run_streaming(r.root(), &[op, "--abort"], cancel, out)
|
||||
}
|
||||
|
||||
pub(crate) fn skip_op(r: &Repo, cancel: &CancellationToken, out: &dyn Fn(String)) -> IdeResult<()> {
|
||||
@@ -172,9 +141,7 @@ pub(crate) fn skip_op(r: &Repo, cancel: &CancellationToken, out: &dyn Fn(String)
|
||||
if op == "merge" {
|
||||
return Err(IdeError::invalid("a merge cannot be skipped; abort it instead"));
|
||||
}
|
||||
let result = cli::run_streaming(r.root(), &[op, "--skip"], cancel, out);
|
||||
let finished = finish_operation(r);
|
||||
result.and(finished)
|
||||
cli::run_streaming(r.root(), &[op, "--skip"], cancel, out)
|
||||
}
|
||||
|
||||
/// Merge commits need a mainline (`-m`), which IDEA doesn't offer for cherry-pick / revert.
|
||||
@@ -190,23 +157,18 @@ fn reject_merges(r: &Repo, commits: &[String], verb: &str) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Applies `commits` on top of HEAD, in the given order (pass oldest first);
|
||||
/// `record_origin` adds "(cherry picked from commit …)" to their messages.
|
||||
/// Applies `commits` on top of HEAD, in the given order (pass oldest first).
|
||||
pub(crate) fn cherry_pick(
|
||||
r: &Repo,
|
||||
commits: &[String],
|
||||
record_origin: bool,
|
||||
cancel: &CancellationToken,
|
||||
out: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
check_commits(commits)?;
|
||||
reject_merges(r, commits, "cherry-pick")?;
|
||||
let mut args = vec!["cherry-pick"];
|
||||
if record_origin {
|
||||
args.push("-x");
|
||||
}
|
||||
args.extend(commits.iter().map(String::as_str));
|
||||
apply_skipping_empty(r, "cherry-pick", &args, cancel, out)
|
||||
cli::run_streaming(r.root(), &args, cancel, out)
|
||||
}
|
||||
|
||||
/// Creates commits undoing `commits`, in the given order (pass newest first).
|
||||
@@ -215,42 +177,7 @@ pub(crate) fn revert(r: &Repo, commits: &[String], cancel: &CancellationToken, o
|
||||
reject_merges(r, commits, "revert")?;
|
||||
let mut args = vec!["revert", "--no-edit"];
|
||||
args.extend(commits.iter().map(String::as_str));
|
||||
apply_skipping_empty(r, "revert", &args, cancel, out)
|
||||
}
|
||||
|
||||
/// Runs a cherry-pick / revert sequence. A commit whose changes are already there leaves
|
||||
/// nothing to commit: it is skipped and the rest of the sequence goes on.
|
||||
fn apply_skipping_empty(
|
||||
r: &Repo,
|
||||
verb: &str,
|
||||
args: &[&str],
|
||||
cancel: &CancellationToken,
|
||||
out: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let head_file = if verb == "revert" { "REVERT_HEAD" } else { "CHERRY_PICK_HEAD" };
|
||||
let said_nothing = std::cell::Cell::new(false);
|
||||
let watch = |line: String| {
|
||||
// git runs with LC_ALL=C; a single commit with nothing left to apply stops here.
|
||||
said_nothing.set(said_nothing.get() || line.contains("nothing to commit"));
|
||||
out(line)
|
||||
};
|
||||
let mut result = cli::run_streaming(r.root(), args, cancel, &watch);
|
||||
if result.is_err() && said_nothing.get() && r.branch_info()?.operation.is_none() {
|
||||
out("Skipped: its changes are already applied".into());
|
||||
return Ok(());
|
||||
}
|
||||
while result.is_err() && !cancel.is_cancelled() {
|
||||
let Ok(stopped) = std::fs::read_to_string(r.git_dir.join(head_file)) else { break };
|
||||
let empty = unmerged_paths(r)?.is_empty()
|
||||
&& cli::run_raw(r.root(), &["diff", "--cached", "--quiet", "HEAD", "--"], None)?.code == Some(0);
|
||||
if !empty {
|
||||
break;
|
||||
}
|
||||
let id = stopped.trim();
|
||||
out(format!("{} skipped: its changes are already applied", &id[..id.len().min(8)]));
|
||||
result = cli::run_streaming(r.root(), &[verb, "--skip"], cancel, out);
|
||||
}
|
||||
result
|
||||
cli::run_streaming(r.root(), &args, cancel, out)
|
||||
}
|
||||
|
||||
pub(crate) fn reset(
|
||||
@@ -354,7 +281,7 @@ pub(crate) fn interactive_rebase(
|
||||
let file = work.join(format!("msg-{i}"));
|
||||
std::fs::write(&file, m)?;
|
||||
todo.push_str(&format!(
|
||||
"exec git commit --amend --allow-empty --no-verify --quiet --cleanup=whitespace -F {}\n",
|
||||
"exec git commit --amend --allow-empty --no-verify --quiet --cleanup=strip -F {}\n",
|
||||
quote(&file)
|
||||
));
|
||||
}
|
||||
@@ -362,26 +289,15 @@ pub(crate) fn interactive_rebase(
|
||||
let todo_file = work.join("todo");
|
||||
std::fs::write(&todo_file, todo)?;
|
||||
let editor = format!("cp {}", quote(&todo_file));
|
||||
// Local changes are put aside and restored when the rebase is over, staged ones as
|
||||
// staged (git's --autostash would bring them all back unstaged).
|
||||
crate::preserve::save(r, "Local changes saved before rebase")?;
|
||||
let mut args = vec!["rebase", "--interactive", "--no-autosquash"];
|
||||
let mut args = vec!["rebase", "--interactive", "--autostash", "--no-autosquash"];
|
||||
args.push(base.unwrap_or("--root"));
|
||||
let env = [("GIT_SEQUENCE_EDITOR", std::ffi::OsStr::new(&editor))];
|
||||
let result = cli::run_streaming_env(r.root(), &args, &env, cancel, out);
|
||||
cli::run_streaming_env(r.root(), &args, &env, cancel, out)?;
|
||||
// A stopped rebase still needs the message files for its remaining `exec` lines.
|
||||
let finished = finish_operation(r);
|
||||
result.and(finished)
|
||||
}
|
||||
|
||||
/// Once a rebase / merge / cherry-pick / revert is over, brings back the local changes
|
||||
/// put aside for it; the plan files of [`interactive_rebase`] go once it is done.
|
||||
pub(crate) fn finish_operation(r: &Repo) -> IdeResult<()> {
|
||||
if r.branch_info()?.operation.is_some() {
|
||||
return Ok(());
|
||||
if r.branch_info()?.operation.is_none() {
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(r.git_dir.join("openidea-rebase"));
|
||||
crate::preserve::restore(r)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates a tag on `commit`: annotated when `message` is non-empty, else lightweight.
|
||||
@@ -409,51 +325,6 @@ pub(crate) fn create_tag(r: &Repo, name: &str, commit: &str, message: Option<&st
|
||||
run(r.root(), &args, message.map(str::as_bytes)).map(|_| ())
|
||||
}
|
||||
|
||||
fn tag_ref(name: &str) -> IdeResult<String> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() || name.starts_with('-') || name.contains("..") || name.contains(':') {
|
||||
return Err(IdeError::invalid(format!("'{name}' is not a valid tag name")));
|
||||
}
|
||||
Ok(format!("refs/tags/{name}"))
|
||||
}
|
||||
|
||||
pub(crate) fn delete_tag(r: &Repo, name: &str) -> IdeResult<crate::DeletedTag> {
|
||||
let tag = tag_ref(name)?;
|
||||
let target = run(r.root(), &["rev-parse", "-q", "--verify", &tag], None)
|
||||
.map_err(|_| IdeError::invalid(format!("Could not find tag {name}")))?
|
||||
.stdout_str();
|
||||
let target = target.trim().to_string();
|
||||
run(r.root(), &["update-ref", "-d", &tag, &target], None)?;
|
||||
Ok(crate::DeletedTag { name: name.trim().to_string(), target })
|
||||
}
|
||||
|
||||
pub(crate) fn restore_tag(r: &Repo, deleted: &crate::DeletedTag) -> IdeResult<()> {
|
||||
let tag = tag_ref(&deleted.name)?;
|
||||
let target = deleted.target.trim();
|
||||
if target.is_empty() || target.starts_with('-') {
|
||||
return Err(IdeError::invalid("invalid tag target"));
|
||||
}
|
||||
// Only recreates it: a tag made with that name meanwhile stays.
|
||||
run(r.root(), &["update-ref", &tag, target, ""], None).map(|_| ())
|
||||
}
|
||||
|
||||
pub(crate) fn push_tag(
|
||||
r: &Repo,
|
||||
name: &str,
|
||||
remote: &str,
|
||||
delete: bool,
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let tag = tag_ref(name)?;
|
||||
let remote = remote.trim();
|
||||
if remote.is_empty() || remote.starts_with('-') {
|
||||
return Err(IdeError::invalid(format!("invalid remote '{remote}'")));
|
||||
}
|
||||
let spec = if delete { format!(":{tag}") } else { format!("{tag}:{tag}") };
|
||||
cli::run_streaming(r.root(), &["push", "--progress", remote, &spec], cancel, on_output)
|
||||
}
|
||||
|
||||
/// Tag names, sorted.
|
||||
pub(crate) fn tags(r: &Repo) -> IdeResult<Vec<String>> {
|
||||
let repo = r.gix()?;
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
//! Local changes put aside around merge, rebase and pull, and brought back once the
|
||||
//! operation is over: staged changes as staged (git's `--autostash` brings everything
|
||||
//! back unstaged). An operation that stops on conflicts keeps them aside until it is
|
||||
//! continued, skipped, aborted or concluded by a commit.
|
||||
|
||||
use crate::Repo;
|
||||
use crate::cli::{self, run};
|
||||
use crate::write::unmerged_paths;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
|
||||
/// `.git/<MARKER>` holds the id of the stash the changes went to.
|
||||
const MARKER: &str = "openidea-saved-changes";
|
||||
|
||||
/// Stashes the local changes of tracked files, if any.
|
||||
pub(crate) fn save(r: &Repo, message: &str) -> IdeResult<()> {
|
||||
let marker = r.git_dir.join(MARKER);
|
||||
if marker.exists() {
|
||||
// Changes saved by an operation still in progress stay where they are; those of
|
||||
// one concluded outside the IDE come back first.
|
||||
if r.branch_info()?.operation.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
restore(r)?;
|
||||
}
|
||||
if run(r.root(), &["status", "--porcelain", "--untracked-files=no"], None)?.stdout_str().trim().is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let before = run(r.root(), &["rev-parse", "-q", "--verify", "refs/stash"], None).map(|o| o.stdout_str()).ok();
|
||||
run(r.root(), &["stash", "push", "-q", "-m", message], None)?;
|
||||
let id = run(r.root(), &["rev-parse", "refs/stash"], None)?.stdout_str();
|
||||
if before.as_deref().map(str::trim) == Some(id.trim()) {
|
||||
return Err(IdeError::invalid("could not save the local changes"));
|
||||
}
|
||||
std::fs::write(marker, id.trim())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Brings the saved changes back once no operation is in progress. Fails when they come
|
||||
/// back with conflicts (they then also stay in the stash).
|
||||
pub(crate) fn restore(r: &Repo) -> IdeResult<()> {
|
||||
let marker = r.git_dir.join(MARKER);
|
||||
let Ok(saved) = std::fs::read_to_string(&marker) else { return Ok(()) };
|
||||
if r.branch_info()?.operation.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let _ = std::fs::remove_file(&marker);
|
||||
let saved = saved.trim();
|
||||
let stashes = run(r.root(), &["stash", "list", "--format=%H"], None)?.stdout_str();
|
||||
let Some(index) = stashes.lines().position(|id| id.trim() == saved) else { return Ok(()) };
|
||||
let entry = format!("stash@{{{index}}}");
|
||||
if cli::run_raw(r.root(), &["stash", "pop", "-q", "--index", &entry], None)?.code == Some(0) {
|
||||
return Ok(());
|
||||
}
|
||||
// The staged part no longer applies as it was: bring everything back unstaged.
|
||||
if unmerged_paths(r)?.is_empty() && cli::run_raw(r.root(), &["stash", "pop", "-q", &entry], None)?.code == Some(0) {
|
||||
return Ok(());
|
||||
}
|
||||
Err(IdeError::invalid("local changes were restored with conflicts; resolve them (a copy stays in the stash)"))
|
||||
}
|
||||
|
||||
/// Runs `op` with the local changes put aside, and brings them back if it finished.
|
||||
pub(crate) fn around<T>(r: &Repo, message: &str, op: impl FnOnce() -> IdeResult<T>) -> IdeResult<T> {
|
||||
save(r, message)?;
|
||||
let result = op();
|
||||
let restored = restore(r);
|
||||
let value = result?;
|
||||
restored.map(|_| value)
|
||||
}
|
||||
@@ -372,13 +372,11 @@ pub(crate) fn commit(
|
||||
args.extend(["-F", "-"]);
|
||||
Some(message.as_bytes())
|
||||
};
|
||||
if options.partial.is_empty() && options.stage.is_empty() && options.exclude.is_empty() {
|
||||
if options.partial.is_empty() {
|
||||
run(r.root(), &args, stdin)?;
|
||||
} else {
|
||||
commit_selected(r, &args, stdin, options, encoding)?;
|
||||
commit_partial(r, &args, stdin, &options.partial, encoding)?;
|
||||
}
|
||||
// A commit concluding a merge brings back the local changes put aside for it.
|
||||
let _ = crate::preserve::restore(r);
|
||||
let repo = r.gix()?;
|
||||
Ok(repo.head_id().map_err(gx)?.detach().to_string())
|
||||
}
|
||||
@@ -393,16 +391,15 @@ impl Drop for TempIndex {
|
||||
}
|
||||
}
|
||||
|
||||
/// Commits a selection of the changes through a copy of the index (`GIT_INDEX_FILE`):
|
||||
/// `exclude` goes back to HEAD in the copy, `stage` takes its working-tree content and
|
||||
/// `partial` only the chosen hunks. The working tree and the user's index are left alone
|
||||
/// except that the committed files' entries end up matching the new commit, so changes
|
||||
/// left out keep their staged state.
|
||||
fn commit_selected(
|
||||
/// Commits the index with only the chosen hunks of `partial` files, through a copy of the
|
||||
/// index (`GIT_INDEX_FILE`), as IDEA's partial commit does: the working tree and the
|
||||
/// user's index are left alone except that the partial files' entries end up matching
|
||||
/// the new commit.
|
||||
fn commit_partial(
|
||||
r: &Repo,
|
||||
commit_args: &[&str],
|
||||
stdin: Option<&[u8]>,
|
||||
options: &CommitOptions,
|
||||
partial: &[crate::PartialCommitFile],
|
||||
encoding: &dyn Fn(&Path) -> IdeResult<TextEncoding>,
|
||||
) -> IdeResult<()> {
|
||||
let tmp = TempIndex(r.git_dir.join("openidea-partial-index"));
|
||||
@@ -411,22 +408,8 @@ fn commit_selected(
|
||||
std::fs::copy(&index, &tmp.0)?;
|
||||
}
|
||||
let env = [("GIT_INDEX_FILE", tmp.0.as_os_str())];
|
||||
let rel_paths = |paths: &[ide_core::IpcPath]| -> IdeResult<Vec<String>> {
|
||||
let paths: Vec<PathBuf> = paths.iter().map(|p| p.0.clone()).collect();
|
||||
r.rel_paths(&paths)
|
||||
};
|
||||
let exclude = rel_paths(&options.exclude)?;
|
||||
if !exclude.is_empty() {
|
||||
let args: &[&str] = if r.has_head()? {
|
||||
&["--literal-pathspecs", "reset", "-q", "HEAD", "--"]
|
||||
} else {
|
||||
&["--literal-pathspecs", "rm", "--cached", "-r", "-q", "--ignore-unmatch", "--"]
|
||||
};
|
||||
cli::run_paths_env(r.root(), args, &exclude, None, &env)?;
|
||||
}
|
||||
let mut rels = rel_paths(&options.stage)?;
|
||||
cli::run_paths_env(r.root(), &["--literal-pathspecs", "add", "-A", "--"], &rels, None, &env)?;
|
||||
for file in &options.partial {
|
||||
let mut rels = Vec::new();
|
||||
for file in partial {
|
||||
let rel = r.rel_path(&file.path.0)?;
|
||||
let head = {
|
||||
let repo = r.gix()?;
|
||||
@@ -542,16 +525,8 @@ fn switch_plan(r: &Repo, branch: &str, create: bool, diverged: Option<DivergedLo
|
||||
|
||||
/// Files git refuses to overwrite with local changes, from its error message.
|
||||
fn overwritten_files(stderr: &str) -> Option<Vec<String>> {
|
||||
listed_files(stderr, "local changes to the following files would be overwritten")
|
||||
}
|
||||
|
||||
/// Untracked files git refuses to overwrite, from its error message.
|
||||
fn overwritten_untracked(stderr: &str) -> Option<Vec<String>> {
|
||||
listed_files(stderr, "untracked working tree files would be")
|
||||
}
|
||||
|
||||
fn listed_files(stderr: &str, header: &str) -> Option<Vec<String>> {
|
||||
let mut lines = stderr.lines().skip_while(|l| !l.contains(header));
|
||||
let mut lines =
|
||||
stderr.lines().skip_while(|l| !l.contains("local changes to the following files would be overwritten"));
|
||||
lines.next()?;
|
||||
Some(lines.take_while(|l| l.starts_with('\t')).map(|l| l.trim().to_string()).collect())
|
||||
}
|
||||
@@ -572,13 +547,10 @@ pub(crate) fn checkout_with(
|
||||
let mut args = match switch_plan(r, branch, create, options.diverged)? {
|
||||
SwitchPlan::Ahead { local, remote } => return Ok(CheckoutOutcome::LocalBranchAhead { local, remote }),
|
||||
SwitchPlan::Rebase { local, remote } => {
|
||||
crate::preserve::save(r, "Local changes saved before checkout")?;
|
||||
let out = cli::run_raw(r.root(), &["rebase", &remote, &local], None)?;
|
||||
let out = cli::run_raw(r.root(), &["rebase", "--autostash", &remote, &local], None)?;
|
||||
if out.code == Some(0) {
|
||||
crate::preserve::restore(r)?;
|
||||
return Ok(CheckoutOutcome::Done);
|
||||
}
|
||||
crate::preserve::restore(r)?;
|
||||
let files = unmerged_paths(r)?;
|
||||
if files.is_empty() {
|
||||
return Err(cli::failure(&["rebase"], &out.stderr, &out.stdout, out.code));
|
||||
@@ -595,11 +567,7 @@ pub(crate) fn checkout_with(
|
||||
if out.code == Some(0) {
|
||||
return Ok(CheckoutOutcome::Done);
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
if let Some(files) = overwritten_untracked(&stderr) {
|
||||
return Ok(CheckoutOutcome::UntrackedFiles { files });
|
||||
}
|
||||
let Some(files) = overwritten_files(&stderr) else {
|
||||
let Some(files) = overwritten_files(&String::from_utf8_lossy(&out.stderr)) else {
|
||||
return Err(cli::failure(&argv, &out.stderr, &out.stdout, out.code));
|
||||
};
|
||||
if options.mode != CheckoutMode::Smart {
|
||||
@@ -615,17 +583,7 @@ pub(crate) fn checkout_with(
|
||||
run(r.root(), &["stash", "pop", "-q", "--index"], None)?;
|
||||
return Err(e);
|
||||
}
|
||||
// Staged changes come back staged; when the index can't be restored as it was (it
|
||||
// conflicts with the new branch), the changes come back unstaged.
|
||||
let pop = cli::run_raw(r.root(), &["stash", "pop", "-q", "--index"], None)?;
|
||||
if pop.code == Some(0) {
|
||||
return Ok(CheckoutOutcome::Done);
|
||||
}
|
||||
let pop = if unmerged_paths(r)?.is_empty() && stash_count(r)? > before {
|
||||
cli::run_raw(r.root(), &["stash", "pop", "-q"], None)?
|
||||
} else {
|
||||
pop
|
||||
};
|
||||
let pop = cli::run_raw(r.root(), &["stash", "pop", "-q"], None)?;
|
||||
if pop.code == Some(0) {
|
||||
return Ok(CheckoutOutcome::Done);
|
||||
}
|
||||
@@ -665,104 +623,6 @@ pub(crate) fn create_branch(r: &Repo, name: &str, start: Option<&str>, checkout:
|
||||
|
||||
/// Undo Commit: moves the current branch back to the parent of `commit` (which must be
|
||||
/// HEAD), keeping its changes staged. Returns the undone commit's message.
|
||||
/// Edit Commit Message: writes `commit` again with `message`, and its descendants on top
|
||||
/// of it with their own trees, then moves HEAD to the new tip. Trees don't change, so the
|
||||
/// index and the working tree stay as they are (local changes included). Returns HEAD
|
||||
/// before and after, for [`restore_head`].
|
||||
pub(crate) fn reword(r: &Repo, commit: &str, message: &str) -> IdeResult<(String, String)> {
|
||||
if r.branch_info()?.operation.is_some() {
|
||||
return Err(IdeError::invalid(
|
||||
"cannot edit a commit message while a merge, rebase or cherry-pick is in progress",
|
||||
));
|
||||
}
|
||||
let message = message.trim();
|
||||
if message.is_empty() {
|
||||
return Err(IdeError::invalid("commit message is empty"));
|
||||
}
|
||||
let (target, head) = {
|
||||
let repo = r.gix()?;
|
||||
let head = repo.head_id().map_err(|_| IdeError::invalid("there is no commit to edit"))?.detach();
|
||||
let target = repo.find_object(resolve(&repo, commit)?).map_err(gx)?.peel_to_commit().map_err(gx)?.id;
|
||||
(target.to_string(), head.to_string())
|
||||
};
|
||||
if cli::run_raw(r.root(), &["merge-base", "--is-ancestor", &target, &head], None)?.code != Some(0) {
|
||||
return Err(IdeError::invalid("the commit is not in the current branch"));
|
||||
}
|
||||
// target..HEAD must be a straight line on top of the target.
|
||||
let range = format!("{target}..{head}");
|
||||
let listed = run(r.root(), &["rev-list", "--reverse", "--topo-order", "--parents", &range], None)?.stdout_str();
|
||||
let mut chain = vec![target.clone()];
|
||||
for line in listed.lines() {
|
||||
let ids: Vec<&str> = line.split_whitespace().collect();
|
||||
if ids.len() != 2 || ids[1] != chain.last().unwrap() {
|
||||
return Err(IdeError::invalid("the commits after this one are not a linear history"));
|
||||
}
|
||||
chain.push(ids[0].to_string());
|
||||
}
|
||||
let mut parent: Option<String> = None;
|
||||
for (i, id) in chain.iter().enumerate() {
|
||||
let raw = run(r.root(), &["cat-file", "commit", id], None)?.stdout;
|
||||
let text = String::from_utf8_lossy(&raw);
|
||||
let (headers, body) = text.split_once("\n\n").unwrap_or((&text, ""));
|
||||
let mut tree = "";
|
||||
let mut parents = Vec::new();
|
||||
let mut author = "";
|
||||
for line in headers.lines() {
|
||||
if let Some(v) = line.strip_prefix("tree ") {
|
||||
tree = v;
|
||||
} else if let Some(v) = line.strip_prefix("parent ") {
|
||||
parents.push(v.to_string());
|
||||
} else if let Some(v) = line.strip_prefix("author ") {
|
||||
author = v;
|
||||
}
|
||||
}
|
||||
if parents.len() > 1 {
|
||||
return Err(IdeError::invalid("merge commits cannot be reworded"));
|
||||
}
|
||||
if let Some(p) = &parent {
|
||||
parents = vec![p.clone()];
|
||||
}
|
||||
let (name, rest) = author.split_once(" <").unwrap_or((author, ""));
|
||||
let (email, date) = rest.split_once("> ").unwrap_or((rest, ""));
|
||||
let env = [
|
||||
("GIT_AUTHOR_NAME", std::ffi::OsStr::new(name)),
|
||||
("GIT_AUTHOR_EMAIL", std::ffi::OsStr::new(email)),
|
||||
("GIT_AUTHOR_DATE", std::ffi::OsStr::new(date)),
|
||||
];
|
||||
let mut args = vec!["commit-tree", tree];
|
||||
for p in &parents {
|
||||
args.extend(["-p", p.as_str()]);
|
||||
}
|
||||
let new_message = if i == 0 { format!("{message}\n") } else { body.to_string() };
|
||||
let created = cli::run_env(r.root(), &args, Some(new_message.as_bytes()), &env)?.stdout_str();
|
||||
parent = Some(created.trim().to_string());
|
||||
}
|
||||
let new_head = parent.expect("the chain holds the target");
|
||||
let reason = format!("reword: {}", message.lines().next().unwrap_or_default());
|
||||
run(r.root(), &["update-ref", "-m", &reason, "HEAD", &new_head, &head], None)?;
|
||||
Ok((head, new_head))
|
||||
}
|
||||
|
||||
/// Undo of a history rewrite: moves HEAD from `after` back to `before`, keeping local
|
||||
/// changes (`git reset --keep`). Refused when HEAD has moved since.
|
||||
pub(crate) fn restore_head(r: &Repo, before: &str, after: &str) -> IdeResult<()> {
|
||||
if r.branch_info()?.operation.is_some() {
|
||||
return Err(IdeError::invalid("cannot undo while a merge, rebase or cherry-pick is in progress"));
|
||||
}
|
||||
let head = run(r.root(), &["rev-parse", "--verify", "HEAD"], None)?.stdout_str();
|
||||
if head.trim() != after {
|
||||
return Err(IdeError::invalid("the branch has changed since; undo is no longer possible"));
|
||||
}
|
||||
let before = check_rev(before)?;
|
||||
let tree = |rev: &str| run(r.root(), &["rev-parse", &format!("{rev}^{{tree}}")], None).map(|o| o.stdout_str());
|
||||
if tree(before)? == tree(after)? {
|
||||
run(r.root(), &["update-ref", "-m", "undo", "HEAD", before, after], None)?;
|
||||
} else {
|
||||
run(r.root(), &["reset", "-q", "--keep", before, "--"], None)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn undo_commit(r: &Repo, commit: &str) -> IdeResult<String> {
|
||||
if r.branch_info()?.operation.is_some() {
|
||||
return Err(IdeError::invalid("cannot undo a commit while a merge, rebase or cherry-pick is in progress"));
|
||||
@@ -851,17 +711,11 @@ fn check_rev(rev: &str) -> IdeResult<&str> {
|
||||
|
||||
/// Local changes are stashed and restored around the merge (IDEA's "save local changes").
|
||||
pub(crate) fn merge(r: &Repo, branch: &str) -> IdeResult<()> {
|
||||
let branch = check_rev(branch)?;
|
||||
crate::preserve::around(r, "Local changes saved before merge", || {
|
||||
run(r.root(), &["merge", "--no-edit", branch], None).map(|_| ())
|
||||
})
|
||||
run(r.root(), &["merge", "--no-edit", "--autostash", check_rev(branch)?], None).map(|_| ())
|
||||
}
|
||||
|
||||
pub(crate) fn rebase(r: &Repo, onto: &str) -> IdeResult<()> {
|
||||
let onto = check_rev(onto)?;
|
||||
crate::preserve::around(r, "Local changes saved before rebase", || {
|
||||
run(r.root(), &["rebase", onto], None).map(|_| ())
|
||||
})
|
||||
run(r.root(), &["rebase", "--autostash", check_rev(onto)?], None).map(|_| ())
|
||||
}
|
||||
|
||||
pub(crate) fn stash_push(r: &Repo, message: Option<&str>, include_untracked: bool, keep_index: bool) -> IdeResult<()> {
|
||||
@@ -927,16 +781,20 @@ pub(crate) fn delete_remote_branch(
|
||||
|
||||
pub(crate) fn push(
|
||||
r: &Repo,
|
||||
o: crate::PushOptions,
|
||||
force_with_lease: bool,
|
||||
set_upstream: bool,
|
||||
tags: Option<crate::PushTags>,
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let mut args: Vec<String> = vec!["push".into(), "--progress".into()];
|
||||
args.extend(force_args(o.force, o.force_with_lease, o.no_verify));
|
||||
if o.tags == Some(crate::PushTags::CurrentBranch) {
|
||||
if force_with_lease {
|
||||
args.push("--force-with-lease".into());
|
||||
}
|
||||
if tags == Some(crate::PushTags::CurrentBranch) {
|
||||
args.push("--follow-tags".into());
|
||||
}
|
||||
if o.set_upstream {
|
||||
if set_upstream {
|
||||
let repo = r.gix()?;
|
||||
let head =
|
||||
repo.head_name().map_err(gx)?.ok_or_else(|| IdeError::invalid("cannot set upstream: HEAD is detached"))?;
|
||||
@@ -959,49 +817,14 @@ pub(crate) fn push(
|
||||
}
|
||||
let argv: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
cli::run_streaming(r.root(), &argv, cancel, on_output)?;
|
||||
if o.tags == Some(crate::PushTags::All) {
|
||||
if tags == Some(crate::PushTags::All) {
|
||||
// `git push --tags` alone pushes only tags, so it runs after the branch push.
|
||||
let remote = push_remote(r)?;
|
||||
let mut args = vec!["push", "--progress"];
|
||||
if o.no_verify {
|
||||
args.push("--no-verify");
|
||||
}
|
||||
args.extend([remote.as_str(), "--tags"]);
|
||||
cli::run_streaming(r.root(), &args, cancel, on_output)?;
|
||||
cli::run_streaming(r.root(), &["push", "--progress", &remote, "--tags"], cancel, on_output)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `--force` / `--force-with-lease` and `--no-verify` of a push.
|
||||
fn force_args(force: bool, force_with_lease: bool, no_verify: bool) -> Vec<String> {
|
||||
let mut args = Vec::new();
|
||||
if force {
|
||||
args.push("--force".into());
|
||||
} else if force_with_lease {
|
||||
args.push("--force-with-lease".into());
|
||||
}
|
||||
if no_verify {
|
||||
args.push("--no-verify".into());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
pub(crate) fn has_hook(r: &Repo, name: &str) -> IdeResult<bool> {
|
||||
if name.is_empty() || name.contains(['/', '\\']) {
|
||||
return Err(IdeError::invalid(format!("invalid hook name '{name}'")));
|
||||
}
|
||||
let path = run(r.root(), &["rev-parse", "--git-path", &format!("hooks/{name}")], None)?.stdout_str();
|
||||
let path = r.root().join(path.trim());
|
||||
let Ok(meta) = std::fs::metadata(&path) else { return Ok(false) };
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
Ok(meta.is_file() && meta.permissions().mode() & 0o111 != 0)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
Ok(meta.is_file())
|
||||
}
|
||||
|
||||
/// Remote and branch name a local branch pulls from (`branch.<b>.remote` / `.merge`).
|
||||
fn branch_upstream(r: &Repo, branch: &str) -> Option<(String, String)> {
|
||||
let get = |key: &str| {
|
||||
@@ -1032,18 +855,10 @@ pub(crate) fn push_branch(
|
||||
cancel: &CancellationToken,
|
||||
on_output: &dyn Fn(String),
|
||||
) -> IdeResult<()> {
|
||||
let PushBranchOptions {
|
||||
revision,
|
||||
target,
|
||||
remote: remote_override,
|
||||
force_with_lease,
|
||||
force,
|
||||
set_upstream,
|
||||
no_verify,
|
||||
} = opts;
|
||||
let PushBranchOptions { revision, target, remote: remote_override, force_with_lease } = opts;
|
||||
check_local_branch(r, branch)?;
|
||||
let remote_override = remote_override.map(str::trim).filter(|s| !s.is_empty());
|
||||
let (remote, mut name, untracked) = match (remote_override, branch_upstream(r, branch)) {
|
||||
let (remote, mut name, set_upstream) = match (remote_override, branch_upstream(r, branch)) {
|
||||
// An explicit remote keeps the upstream's branch name but pushes elsewhere.
|
||||
(Some(remote), Some((_, name))) => (check_rev(remote)?.to_string(), name, false),
|
||||
(Some(remote), None) => (check_rev(remote)?.to_string(), branch.to_string(), revision.is_none()),
|
||||
@@ -1064,8 +879,10 @@ pub(crate) fn push_branch(
|
||||
None => format!("refs/heads/{branch}"),
|
||||
};
|
||||
let mut args: Vec<String> = vec!["push".into(), "--progress".into()];
|
||||
args.extend(force_args(force, force_with_lease, no_verify));
|
||||
if untracked || (set_upstream && revision.is_none()) {
|
||||
if force_with_lease {
|
||||
args.push("--force-with-lease".into());
|
||||
}
|
||||
if set_upstream {
|
||||
args.push("--set-upstream".into());
|
||||
}
|
||||
args.extend([remote, format!("{source}:refs/heads/{target}")]);
|
||||
@@ -1087,27 +904,6 @@ pub(crate) fn update_branch(
|
||||
cli::run_streaming(r.root(), &["fetch", "--progress", &remote, &refspec], cancel, on_output)
|
||||
}
|
||||
|
||||
/// Update Project › Reset to the Remote Branch: fetches the current branch's tracked
|
||||
/// branch and moves the branch to it, dropping local commits. Local changes are put
|
||||
/// aside and brought back (an error with the conflicts left in place when they clash).
|
||||
pub(crate) fn reset_to_upstream(r: &Repo, cancel: &CancellationToken, on_output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
let head = run(r.root(), &["symbolic-ref", "-q", "--short", "HEAD"], None)
|
||||
.map_err(|_| IdeError::invalid("cannot reset: HEAD is detached"))?
|
||||
.stdout_str();
|
||||
let head = head.trim();
|
||||
let no_tracked =
|
||||
|| IdeError::invalid(format!("no tracked branch configured for branch {head} or the branch doesn't exist"));
|
||||
let (remote, name) = branch_upstream(r, head).ok_or_else(no_tracked)?;
|
||||
cli::run_streaming(r.root(), &["fetch", "--progress", &remote], cancel, on_output)?;
|
||||
let tracked = format!("refs/remotes/{remote}/{name}");
|
||||
if run(r.root(), &["rev-parse", "-q", "--verify", &format!("{tracked}^{{commit}}")], None).is_err() {
|
||||
return Err(no_tracked());
|
||||
}
|
||||
crate::preserve::around(r, "Local changes saved before reset", || {
|
||||
run(r.root(), &["reset", "-q", "--keep", &tracked], None).map(|_| ())
|
||||
})
|
||||
}
|
||||
|
||||
/// The remote the current branch pushes to (`origin`, or the only remote, by default).
|
||||
/// The remote and ref HEAD's branch tracks when the ref has another name: a plain
|
||||
/// `git push` refuses that under the default `push.default=simple`.
|
||||
|
||||
@@ -306,17 +306,6 @@ fn interactive_rebase_reorder_squash_fixup_reword_drop() {
|
||||
assert_eq!(fx.git(&["show", "--format=", "--name-only", "HEAD"]), "f1.txt\nf2.txt\nf3.txt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interactive_rebase_reword_keeps_lines_starting_with_a_hash() {
|
||||
let (fx, ids) = linear();
|
||||
let (cancel, out) = quiet();
|
||||
let message = "Subject\n\n#body starting with a hash";
|
||||
fx.repo()
|
||||
.interactive_rebase(Some(&ids[2]), &[entry(&ids[3], RebaseAction::Reword, Some(message))], &cancel, &out)
|
||||
.unwrap();
|
||||
assert_eq!(fx.git(&["log", "-1", "--format=%B"]), message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interactive_rebase_squash_without_message_combines_messages() {
|
||||
let (fx, ids) = linear();
|
||||
@@ -418,89 +407,6 @@ fn interactive_rebase_conflict_stops_then_continues_with_reword() {
|
||||
assert_eq!(fx.subjects(), vec!["one", "two first", "base"]);
|
||||
}
|
||||
|
||||
/// `main` and `feature` both change `c.txt`: rebasing feature onto main stops on it.
|
||||
fn rebase_stopped_on_a_conflict() -> (Fixture, Repo) {
|
||||
let fx = Fixture::new();
|
||||
fx.write("c.txt", "base\n");
|
||||
fx.write("other.txt", "other\n");
|
||||
fx.commit_all("base");
|
||||
fx.git(&["switch", "-q", "-c", "feature"]);
|
||||
fx.write("c.txt", "feature\n");
|
||||
fx.commit_all("feature change");
|
||||
fx.git(&["switch", "-q", "main"]);
|
||||
fx.write("c.txt", "main\n");
|
||||
fx.commit_all("main change");
|
||||
fx.git(&["switch", "-q", "feature"]);
|
||||
let repo = fx.repo();
|
||||
assert!(repo.rebase("main").is_err());
|
||||
assert_eq!(repo.branch_info().unwrap().operation.as_deref(), Some("rebase"));
|
||||
(fx, repo)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_of_a_resolved_file_go_with_it_when_the_rebase_continues() {
|
||||
let (fx, repo) = rebase_stopped_on_a_conflict();
|
||||
fx.write("c.txt", "resolved\n");
|
||||
repo.stage(&[fx.path("c.txt")]).unwrap();
|
||||
fx.write("c.txt", "resolved\nmore\n");
|
||||
let (cancel, out) = quiet();
|
||||
repo.continue_operation(&cancel, &out).unwrap();
|
||||
assert_eq!(repo.branch_info().unwrap().operation, None);
|
||||
assert_eq!(fx.git(&["show", "HEAD:c.txt"]), "resolved\nmore");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unstaged_changes_of_other_files_stop_the_rebase_until_staged() {
|
||||
let (fx, repo) = rebase_stopped_on_a_conflict();
|
||||
fx.write("c.txt", "resolved\n");
|
||||
repo.stage(&[fx.path("c.txt")]).unwrap();
|
||||
fx.write("other.txt", "changed while stopped\n");
|
||||
let (cancel, out) = quiet();
|
||||
let err = repo.continue_operation(&cancel, &out).unwrap_err();
|
||||
assert_eq!(err.message, UNSTAGED_CHANGES_PREVENT_REBASE);
|
||||
assert_eq!(repo.branch_info().unwrap().operation.as_deref(), Some("rebase"));
|
||||
repo.stage_and_continue(&cancel, &out).unwrap();
|
||||
assert_eq!(repo.branch_info().unwrap().operation, None);
|
||||
assert_eq!(fx.git(&["show", "HEAD:other.txt"]), "changed while stopped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_and_retry_after_editing_a_commit() {
|
||||
let (fx, ids) = linear();
|
||||
let repo = fx.repo();
|
||||
let (cancel, out) = quiet();
|
||||
let plan = [entry(&ids[2], RebaseAction::Edit, None), entry(&ids[3], RebaseAction::Pick, None)];
|
||||
repo.interactive_rebase(Some(&ids[1]), &plan, &cancel, &out).unwrap();
|
||||
assert_eq!(repo.branch_info().unwrap().operation.as_deref(), Some("rebase"));
|
||||
fx.write("f1.txt", "edited\n");
|
||||
std::fs::remove_file(fx.path("f2.txt")).unwrap();
|
||||
assert!(repo.continue_operation(&cancel, &out).is_err());
|
||||
repo.stage_and_continue(&cancel, &out).unwrap();
|
||||
assert_eq!(repo.branch_info().unwrap().operation, None);
|
||||
assert_eq!(fx.git(&["status", "--porcelain"]), "");
|
||||
assert!(!fx.exists("f2.txt"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rebase_and_merge_onto_a_branch_named_like_a_tag_use_the_branch() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("a.txt", "a\n");
|
||||
fx.commit_all("base");
|
||||
fx.git(&["tag", "main"]);
|
||||
fx.write("m.txt", "m\n");
|
||||
let tip = fx.commit_all("main moved on");
|
||||
fx.git(&["switch", "-q", "-c", "feature", "HEAD~1"]);
|
||||
fx.write("f.txt", "f\n");
|
||||
fx.commit_all("feature");
|
||||
let repo = fx.repo();
|
||||
repo.rebase("refs/heads/main").unwrap();
|
||||
assert_eq!(fx.git(&["rev-parse", "HEAD~1"]), tip);
|
||||
fx.git(&["reset", "-q", "--hard", "HEAD~1"]);
|
||||
fx.git(&["switch", "-q", "-c", "other", "refs/heads/main~1"]);
|
||||
repo.merge("refs/heads/main").unwrap();
|
||||
assert_eq!(fx.head(), tip, "fast-forwarded to the branch, not the tag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interactive_rebase_edit_stops_for_amend() {
|
||||
let (fx, ids) = linear();
|
||||
@@ -618,157 +524,6 @@ fn update_merge_with_local_changes_to_the_same_file() {
|
||||
assert_eq!(fx.git(&["rev-list", "--count", "--merges", "HEAD"]), "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_with_rebase_keeps_a_file_added_then_deleted_added_to_the_index() {
|
||||
let (fx, bare) = Fixture::with_origin();
|
||||
fx.push_from_other(&bare, "remote.txt", "r\n");
|
||||
fx.write("local.txt", "l\n");
|
||||
fx.commit_all("local");
|
||||
fx.write("ad.txt", "x\n");
|
||||
fx.git(&["add", "ad.txt"]);
|
||||
std::fs::remove_file(fx.path("ad.txt")).unwrap();
|
||||
let (cancel, out) = quiet();
|
||||
fx.repo().pull(true, &cancel, &out).unwrap();
|
||||
assert!(fx.exists("remote.txt"));
|
||||
assert!(fx.git(&["status", "--porcelain", "--", "ad.txt"]).starts_with('A'), "still added");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_to_the_remote_branch_drops_local_commits_and_keeps_local_changes() {
|
||||
let (fx, bare) = Fixture::with_origin();
|
||||
for i in 0..3 {
|
||||
fx.push_from_other(&bare, "bro.txt", &format!("bro {i}\n"));
|
||||
}
|
||||
fx.write("local1.txt", "1\n");
|
||||
fx.commit_all("local commit");
|
||||
fx.write("untracked.txt", "u\n");
|
||||
fx.write("a.txt", "edited\n");
|
||||
fx.git(&["add", "a.txt"]);
|
||||
let (cancel, out) = quiet();
|
||||
fx.repo().reset_to_upstream(&cancel, &out).unwrap();
|
||||
assert_eq!(fx.head(), fx.git(&["rev-parse", "origin/main"]));
|
||||
assert!(!fx.exists("local1.txt"), "files of local commits are gone");
|
||||
assert!(fx.exists("untracked.txt"));
|
||||
assert_eq!(fx.git(&["status", "--porcelain", "--", "a.txt"]), "M a.txt", "staged changes stay staged");
|
||||
assert_eq!(fx.git(&["stash", "list"]), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_to_the_remote_branch_without_new_remote_commits_drops_local_ones() {
|
||||
let (fx, _bare) = Fixture::with_origin();
|
||||
let before = fx.head();
|
||||
fx.write("local1.txt", "1\n");
|
||||
fx.commit_all("local commit");
|
||||
let (cancel, out) = quiet();
|
||||
fx.repo().reset_to_upstream(&cancel, &out).unwrap();
|
||||
assert_eq!(fx.head(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_to_the_remote_branch_leaves_conflicting_local_changes_to_resolve() {
|
||||
let (fx, bare) = Fixture::with_origin();
|
||||
fx.push_from_other(&bare, "bro.txt", "bro\n");
|
||||
fx.write("bro.txt", "local content\n");
|
||||
fx.git(&["add", "bro.txt"]);
|
||||
let (cancel, out) = quiet();
|
||||
assert!(fx.repo().reset_to_upstream(&cancel, &out).is_err());
|
||||
assert_eq!(fx.head(), fx.git(&["rev-parse", "origin/main"]));
|
||||
assert!(fx.read("bro.txt").contains("<<<<<<<"), "the clash is left to resolve");
|
||||
assert_eq!(fx.git(&["stash", "list"]).lines().count(), 1, "a copy stays in the stash");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_to_the_remote_branch_needs_a_tracked_branch_that_exists() {
|
||||
let (fx, bare) = Fixture::with_origin();
|
||||
let (cancel, out) = quiet();
|
||||
fx.git(&["branch", "--unset-upstream"]);
|
||||
let err = fx.repo().reset_to_upstream(&cancel, &out).unwrap_err();
|
||||
assert!(err.message.contains("no tracked branch"), "{}", err.message);
|
||||
|
||||
fx.git(&["push", "-q", "-u", "origin", "main:feature"]);
|
||||
fx.git(&["switch", "-q", "-c", "feature", "--track", "origin/feature"]);
|
||||
git_in(&bare, &["branch", "-D", "feature"]);
|
||||
fx.git(&["fetch", "-q", "--prune"]);
|
||||
let err = fx.repo().reset_to_upstream(&cancel, &out).unwrap_err();
|
||||
assert!(err.message.contains("no tracked branch"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn push_can_skip_a_failing_pre_push_hook() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let (fx, _bare) = Fixture::with_origin();
|
||||
let repo = fx.repo();
|
||||
assert!(!repo.has_hook("pre-push").unwrap());
|
||||
let hook = fx.path(".git/hooks/pre-push");
|
||||
std::fs::create_dir_all(hook.parent().unwrap()).unwrap();
|
||||
std::fs::write(&hook, "#!/bin/sh\necho refused >&2\nexit 1\n").unwrap();
|
||||
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert!(repo.has_hook("pre-push").unwrap());
|
||||
|
||||
fx.write("local.txt", "l\n");
|
||||
fx.commit_all("local");
|
||||
let (cancel, out) = quiet();
|
||||
assert!(repo.push(false, false, &cancel, &out).is_err(), "the hook refuses the push");
|
||||
let options = PushOptions { no_verify: true, ..Default::default() };
|
||||
repo.push_with(options, &cancel, &out).unwrap();
|
||||
assert_eq!(fx.head(), fx.git(&["rev-parse", "origin/main"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn force_push_without_lease_overwrites_a_remote_that_moved() {
|
||||
let (fx, bare) = Fixture::with_origin();
|
||||
fx.write("local.txt", "l\n");
|
||||
fx.commit_all("local");
|
||||
fx.push_from_other(&bare, "remote.txt", "r\n");
|
||||
fx.git(&["fetch", "-q"]);
|
||||
fx.push_from_other(&bare, "remote2.txt", "r\n");
|
||||
let repo = fx.repo();
|
||||
let (cancel, out) = quiet();
|
||||
let lease = PushOptions { force_with_lease: true, ..Default::default() };
|
||||
let err = repo.push_with(lease, &cancel, &out).unwrap_err();
|
||||
assert!(err.message.contains("stale info"), "{}", err.message);
|
||||
repo.push_with(PushOptions { force: true, ..Default::default() }, &cancel, &out).unwrap();
|
||||
assert_eq!(git_in(&bare, &["rev-parse", "main"]), fx.head());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_to_another_branch_can_make_it_the_upstream() {
|
||||
let (fx, _bare) = Fixture::with_origin();
|
||||
fx.write("local.txt", "l\n");
|
||||
fx.commit_all("local");
|
||||
let repo = fx.repo();
|
||||
let (cancel, out) = quiet();
|
||||
let to = |target, set_upstream| PushBranchOptions { target: Some(target), set_upstream, ..Default::default() };
|
||||
repo.push_branch_to("main", to("feature", false), &cancel, &out).unwrap();
|
||||
assert_eq!(fx.git(&["rev-parse", "--abbrev-ref", "main@{u}"]), "origin/main", "upstream kept");
|
||||
repo.push_branch_to("main", to("feature-1", true), &cancel, &out).unwrap();
|
||||
assert_eq!(fx.git(&["rev-parse", "--abbrev-ref", "main@{u}"]), "origin/feature-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tags_are_pushed_one_at_a_time_deleted_restored_and_deleted_on_the_remote() {
|
||||
let (fx, bare) = Fixture::with_origin();
|
||||
fx.git(&["tag", "-a", "v1", "-m", "release one"]);
|
||||
fx.git(&["tag", "v2"]);
|
||||
let repo = fx.repo();
|
||||
let (cancel, out) = quiet();
|
||||
repo.push_tag("v1", "origin", &cancel, &out).unwrap();
|
||||
assert_eq!(git_in(&bare, &["tag"]), "v1", "only the chosen tag goes");
|
||||
repo.push_tag("v1", "origin", &cancel, &out).unwrap();
|
||||
|
||||
let deleted = repo.delete_tag("v1").unwrap();
|
||||
assert_eq!(fx.git(&["tag"]), "v2");
|
||||
repo.restore_tag(&deleted).unwrap();
|
||||
assert_eq!(fx.git(&["cat-file", "-t", "v1"]), "tag", "annotated, as it was");
|
||||
assert!(fx.git(&["tag", "-n1", "v1"]).contains("release one"));
|
||||
|
||||
repo.delete_tag("v1").unwrap();
|
||||
repo.delete_remote_tag("v1", "origin", &cancel, &out).unwrap();
|
||||
assert_eq!(git_in(&bare, &["tag"]), "");
|
||||
assert!(repo.delete_tag("missing").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_prunes_deleted_remote_branches() {
|
||||
let (fx, bare) = Fixture::with_origin();
|
||||
@@ -1108,100 +863,3 @@ fn remote_progress_is_streamed() {
|
||||
fx.repo().push(false, false, &CancellationToken::new(), &move |l| sink.lock().unwrap().push(l)).unwrap();
|
||||
assert!(!lines.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interactive_rebase_restores_local_changes_staged_as_they_were() {
|
||||
let (fx, ids) = linear();
|
||||
let repo = fx.repo();
|
||||
let (cancel, out) = quiet();
|
||||
fx.write("f1.txt", "staged\n");
|
||||
fx.git(&["add", "f1.txt"]);
|
||||
fx.write("f2.txt", "unstaged\n");
|
||||
repo.interactive_rebase(
|
||||
Some(&ids[1]),
|
||||
&[entry(&ids[2], RebaseAction::Drop, None), entry(&ids[3], RebaseAction::Pick, None)],
|
||||
&cancel,
|
||||
&out,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(fx.subjects(), vec!["c4", "c2", "c1"]);
|
||||
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "f1.txt");
|
||||
assert_eq!(fx.git(&["diff", "--name-only"]), "f2.txt");
|
||||
assert!(fx.git(&["stash", "list"]).is_empty());
|
||||
assert!(!fx.path(".git/openidea-rebase").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_changes_come_back_once_a_stopped_rebase_is_continued() {
|
||||
let (fx, ids) = linear();
|
||||
let repo = fx.repo();
|
||||
let (cancel, out) = quiet();
|
||||
// c4 rewrites f3.txt so that dropping c3 conflicts.
|
||||
fx.write("f3.txt", "3\nmore\n");
|
||||
fx.commit_all("c5");
|
||||
let c5 = fx.git(&["rev-parse", "HEAD"]);
|
||||
fx.write("f1.txt", "staged\n");
|
||||
fx.git(&["add", "f1.txt"]);
|
||||
let result = repo.interactive_rebase(
|
||||
Some(&ids[1]),
|
||||
&[
|
||||
entry(&ids[2], RebaseAction::Drop, None),
|
||||
entry(&ids[3], RebaseAction::Pick, None),
|
||||
entry(&c5, RebaseAction::Pick, None),
|
||||
],
|
||||
&cancel,
|
||||
&out,
|
||||
);
|
||||
assert!(result.is_err());
|
||||
assert_eq!(repo.branch_info().unwrap().operation.as_deref(), Some("rebase"));
|
||||
assert_eq!(fx.read("f1.txt"), "1\n", "put aside while the rebase is stopped");
|
||||
fx.write("f3.txt", "3\nmore\n");
|
||||
repo.stage(&[fx.path("f3.txt")]).unwrap();
|
||||
repo.continue_operation(&cancel, &out).unwrap();
|
||||
assert_eq!(repo.branch_info().unwrap().operation, None);
|
||||
assert_eq!(fx.read("f1.txt"), "staged\n");
|
||||
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "f1.txt");
|
||||
assert!(fx.git(&["stash", "list"]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_brings_staged_changes_back_staged() {
|
||||
let (fx, _ids) = linear();
|
||||
let repo = fx.repo();
|
||||
fx.git(&["checkout", "-q", "-b", "side", "HEAD~1"]);
|
||||
fx.write("side.txt", "side\n");
|
||||
fx.git(&["add", "side.txt"]);
|
||||
fx.git(&["commit", "-q", "-m", "side"]);
|
||||
fx.git(&["checkout", "-q", "main"]);
|
||||
fx.write("f1.txt", "staged\n");
|
||||
fx.git(&["add", "f1.txt"]);
|
||||
fx.write("f2.txt", "unstaged\n");
|
||||
repo.merge_with(&["side".to_string()], &MergeOptions::default()).unwrap();
|
||||
assert!(fx.exists("side.txt"));
|
||||
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "f1.txt");
|
||||
assert_eq!(fx.git(&["diff", "--name-only"]), "f2.txt");
|
||||
assert!(fx.git(&["stash", "list"]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_changes_come_back_after_a_conflicting_merge_is_committed() {
|
||||
let (fx, _ids) = linear();
|
||||
let repo = fx.repo();
|
||||
fx.git(&["checkout", "-q", "-b", "side", "HEAD~1"]);
|
||||
fx.write("f4.txt", "side\n");
|
||||
fx.git(&["add", "f4.txt"]);
|
||||
fx.git(&["commit", "-q", "-m", "side f4"]);
|
||||
fx.git(&["checkout", "-q", "main"]);
|
||||
fx.write("f1.txt", "staged\n");
|
||||
fx.git(&["add", "f1.txt"]);
|
||||
assert!(repo.merge_with(&["side".to_string()], &MergeOptions::default()).is_err());
|
||||
assert_eq!(repo.branch_info().unwrap().operation.as_deref(), Some("merge"));
|
||||
assert_eq!(fx.read("f1.txt"), "1\n", "put aside while the merge is in progress");
|
||||
fx.write("f4.txt", "both\n");
|
||||
repo.stage(&[fx.path("f4.txt")]).unwrap();
|
||||
repo.commit("Merge side", false, false).unwrap();
|
||||
assert_eq!(repo.branch_info().unwrap().operation, None);
|
||||
assert_eq!(fx.read("f1.txt"), "staged\n");
|
||||
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "f1.txt");
|
||||
assert!(fx.git(&["stash", "list"]).is_empty());
|
||||
}
|
||||
@@ -662,45 +662,3 @@ fn shelf_new_renames_keep_self_contained_sides_and_plain_imports_keep_scope() {
|
||||
shelf::delete_path(&shelf, "plain", Some("one.txt")).unwrap();
|
||||
assert_eq!(shelf::list(&shelf).unwrap().iter().find(|s| s.id == "plain").unwrap().files[0].path, "two.txt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cherry_pick_skips_commits_already_applied() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("a.txt", "1\n");
|
||||
fx.commit_all("base");
|
||||
fx.git(&["checkout", "-q", "-b", "side"]);
|
||||
fx.write("a.txt", "2\n");
|
||||
let same = fx.commit_all("same change");
|
||||
fx.write("b.txt", "b\n");
|
||||
let other = fx.commit_all("other change");
|
||||
fx.git(&["checkout", "-q", "main"]);
|
||||
// main already has the first change.
|
||||
fx.write("a.txt", "2\n");
|
||||
fx.commit_all("same change, made on main");
|
||||
let repo = fx.repo();
|
||||
let cancel = CancellationToken::new();
|
||||
let lines = std::sync::Mutex::new(Vec::new());
|
||||
let out = |l: String| lines.lock().unwrap().push(l);
|
||||
|
||||
repo.cherry_pick_with(&[same.clone(), other], true, &cancel, &out).unwrap();
|
||||
assert_eq!(repo.branch_info().unwrap().operation, None, "nothing left in progress");
|
||||
assert_eq!(fx.git(&["log", "--format=%s", "-2"]), "other change\nsame change, made on main");
|
||||
assert!(fx.git(&["log", "-1", "--format=%B"]).contains("(cherry picked from commit"));
|
||||
assert!(lines.lock().unwrap().iter().any(|l| l.starts_with(&same[..8]) && l.contains("skipped")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revert_of_a_commit_already_reverted_is_skipped() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("a.txt", "1\n");
|
||||
fx.commit_all("one");
|
||||
fx.write("a.txt", "2\n");
|
||||
let two = fx.commit_all("two");
|
||||
fx.write("a.txt", "1\n");
|
||||
fx.commit_all("undo two by hand");
|
||||
let repo = fx.repo();
|
||||
let (cancel, out) = quiet();
|
||||
repo.revert(&[two], &cancel, &out).unwrap();
|
||||
assert_eq!(repo.branch_info().unwrap().operation, None);
|
||||
assert_eq!(fx.git(&["rev-list", "--count", "HEAD"]), "3", "no empty revert commit");
|
||||
}
|
||||
@@ -462,153 +462,3 @@ fn case_insensitive_text_folds_non_ascii() {
|
||||
assert_eq!(ids(LogQuery { text: Some("ärger привет".into()), ..Default::default() }), vec![hit.clone()]);
|
||||
assert!(ids(LogQuery { text: Some("ärger".into()), text_match_case: true, ..Default::default() }).is_empty());
|
||||
}
|
||||
|
||||
/// File history (Show History of a file) as (subject, path at that revision), newest first.
|
||||
fn file_history(dir: &Path, path: &str) -> Vec<(String, String)> {
|
||||
let repo = Repo::discover(dir).unwrap().unwrap();
|
||||
let log = repo.log(&LogQuery { path: Some(path.into()), follow: true, ..Default::default() }).unwrap();
|
||||
log.into_iter().map(|c| (c.summary, c.history_path.unwrap_or_default())).collect()
|
||||
}
|
||||
|
||||
fn history_repo() -> (tempfile::TempDir, std::path::PathBuf) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().to_path_buf();
|
||||
git(&dir, &["init", "-q"]);
|
||||
(tmp, dir)
|
||||
}
|
||||
|
||||
fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> {
|
||||
list.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_history_goes_through_a_rename_on_a_merged_branch() {
|
||||
let (_tmp, dir) = history_repo();
|
||||
commit(&dir, "file.txt", "Created");
|
||||
git(&dir, &["switch", "-qc", "feature"]);
|
||||
git(&dir, &["mv", "file.txt", "renamed.txt"]);
|
||||
git(&dir, &["commit", "-qm", "Renamed"]);
|
||||
git(&dir, &["switch", "-q", "main"]);
|
||||
commit(&dir, "other.txt", "Unrelated");
|
||||
git(&dir, &["merge", "-q", "--no-ff", "-m", "Merged", "feature"]);
|
||||
commit(&dir, "renamed.txt", "Modified");
|
||||
let history = file_history(&dir, "renamed.txt");
|
||||
assert_eq!(history, pairs(&[("Modified", "renamed.txt"), ("Renamed", "renamed.txt"), ("Created", "file.txt")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_history_goes_through_a_rename_done_in_a_merge_commit() {
|
||||
let (_tmp, dir) = history_repo();
|
||||
commit(&dir, "file.txt", "Created");
|
||||
git(&dir, &["switch", "-qc", "feature"]);
|
||||
commit(&dir, "side.txt", "Side");
|
||||
git(&dir, &["switch", "-q", "main"]);
|
||||
git(&dir, &["merge", "-q", "--no-ff", "--no-commit", "feature"]);
|
||||
git(&dir, &["mv", "file.txt", "renamed.txt"]);
|
||||
git(&dir, &["commit", "-qm", "Merge with rename"]);
|
||||
let history = file_history(&dir, "renamed.txt");
|
||||
assert_eq!(history, pairs(&[("Merge with rename", "renamed.txt"), ("Created", "file.txt")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_history_shows_merges_that_change_the_file_but_not_trivial_ones() {
|
||||
let (_tmp, dir) = history_repo();
|
||||
std::fs::write(dir.join("file.txt"), "one\ntwo\nthree\n").unwrap();
|
||||
git(&dir, &["add", "-A"]);
|
||||
git(&dir, &["commit", "-qm", "Created"]);
|
||||
git(&dir, &["switch", "-qc", "feature"]);
|
||||
std::fs::write(dir.join("file.txt"), "one\ntwo\nthree\nfeature\n").unwrap();
|
||||
git(&dir, &["commit", "-qam", "Feature"]);
|
||||
git(&dir, &["switch", "-q", "main"]);
|
||||
commit(&dir, "other.txt", "Other");
|
||||
git(&dir, &["merge", "-q", "--no-ff", "-m", "Trivial merge", "feature"]);
|
||||
assert_eq!(
|
||||
file_history(&dir, "file.txt").into_iter().map(|(s, _)| s).collect::<Vec<_>>(),
|
||||
vec!["Feature", "Created"]
|
||||
);
|
||||
|
||||
git(&dir, &["switch", "-qc", "second", "HEAD~1"]);
|
||||
std::fs::write(dir.join("file.txt"), "zero\none\ntwo\nthree\n").unwrap();
|
||||
git(&dir, &["commit", "-qam", "Second"]);
|
||||
git(&dir, &["switch", "-q", "main"]);
|
||||
git(&dir, &["merge", "-q", "--no-ff", "--no-commit", "second"]);
|
||||
std::fs::write(dir.join("file.txt"), "zero\none\ntwo\nthree\nfeature\nresolved\n").unwrap();
|
||||
git(&dir, &["commit", "-qam", "Non-trivial merge"]);
|
||||
let subjects: Vec<String> = file_history(&dir, "file.txt").into_iter().map(|(s, _)| s).collect();
|
||||
assert_eq!(subjects[0], "Non-trivial merge");
|
||||
assert!(subjects.contains(&"Second".to_string()) && subjects.contains(&"Feature".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_history_through_a_monorepo_merge_keeps_each_side() {
|
||||
let (_tmp, dir) = history_repo();
|
||||
commit(&dir, "file1.txt", "Created file1");
|
||||
git(&dir, &["switch", "-q", "--orphan", "repo2"]);
|
||||
commit(&dir, "file2.txt", "Created file2");
|
||||
git(&dir, &["switch", "-q", "main"]);
|
||||
git(&dir, &["merge", "-q", "--no-commit", "--allow-unrelated-histories", "repo2"]);
|
||||
std::fs::create_dir_all(dir.join("repo1")).unwrap();
|
||||
std::fs::create_dir_all(dir.join("repo2")).unwrap();
|
||||
git(&dir, &["mv", "file1.txt", "repo1/file1.txt"]);
|
||||
git(&dir, &["mv", "file2.txt", "repo2/file2.txt"]);
|
||||
git(&dir, &["commit", "-qm", "monorepo merge"]);
|
||||
assert_eq!(
|
||||
file_history(&dir, "repo1/file1.txt"),
|
||||
pairs(&[("monorepo merge", "repo1/file1.txt"), ("Created file1", "file1.txt")])
|
||||
);
|
||||
assert_eq!(
|
||||
file_history(&dir, "repo2/file2.txt"),
|
||||
pairs(&[("monorepo merge", "repo2/file2.txt"), ("Created file2", "file2.txt")])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_history_through_parallel_renames_names_the_path_of_each_revision() {
|
||||
let (_tmp, dir) = history_repo();
|
||||
std::fs::write(dir.join("file.txt"), "base\n").unwrap();
|
||||
git(&dir, &["add", "-A"]);
|
||||
git(&dir, &["commit", "-qm", "Created"]);
|
||||
git(&dir, &["switch", "-qc", "other"]);
|
||||
std::fs::write(dir.join("file.txt"), "base\nother\n").unwrap();
|
||||
git(&dir, &["commit", "-qam", "Modified on other"]);
|
||||
git(&dir, &["mv", "file.txt", "renamed.txt"]);
|
||||
git(&dir, &["commit", "-qm", "Renamed on other"]);
|
||||
git(&dir, &["switch", "-q", "main"]);
|
||||
std::fs::write(dir.join("file.txt"), "main\nbase\n").unwrap();
|
||||
git(&dir, &["commit", "-qam", "Modified on main"]);
|
||||
git(&dir, &["mv", "file.txt", "renamed.txt"]);
|
||||
git(&dir, &["commit", "-qm", "Renamed on main"]);
|
||||
// Both sides changed the file: the merge stops for the resolution.
|
||||
let _ = Command::new("git").current_dir(&dir).args(["merge", "-q", "--no-ff", "--no-commit", "other"]).output();
|
||||
std::fs::write(dir.join("renamed.txt"), "main\nbase\nother\nmerged\n").unwrap();
|
||||
git(&dir, &["add", "-A"]);
|
||||
git(&dir, &["commit", "-qm", "Merged other"]);
|
||||
let mut history = file_history(&dir, "renamed.txt");
|
||||
history.sort();
|
||||
assert_eq!(
|
||||
history,
|
||||
pairs(&[
|
||||
("Created", "file.txt"),
|
||||
("Merged other", "renamed.txt"),
|
||||
("Modified on main", "file.txt"),
|
||||
("Modified on other", "file.txt"),
|
||||
("Renamed on main", "renamed.txt"),
|
||||
("Renamed on other", "renamed.txt"),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_history_through_a_cyclic_rename() {
|
||||
let (_tmp, dir) = history_repo();
|
||||
commit(&dir, "a.txt", "Created a");
|
||||
git(&dir, &["mv", "a.txt", "b.txt"]);
|
||||
git(&dir, &["commit", "-qm", "a to b"]);
|
||||
commit(&dir, "b.txt", "Modified b");
|
||||
git(&dir, &["mv", "b.txt", "a.txt"]);
|
||||
git(&dir, &["commit", "-qm", "b to a"]);
|
||||
assert_eq!(
|
||||
file_history(&dir, "a.txt"),
|
||||
pairs(&[("b to a", "a.txt"), ("Modified b", "b.txt"), ("a to b", "b.txt"), ("Created a", "a.txt")])
|
||||
);
|
||||
}
|
||||
@@ -1687,173 +1687,3 @@ fn restricted_conflict_preview_uses_host_owned_temporary_files() {
|
||||
assert!(versions.merged.unwrap().contains("<<<<<<<"));
|
||||
assert_eq!(std::fs::read_to_string(marker).unwrap(), "untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commit_leaves_excluded_staged_changes_staged() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("a.txt", "a\n");
|
||||
fx.write("b.txt", "b\n");
|
||||
fx.write("old.txt", "renamed\n");
|
||||
fx.commit_all("base");
|
||||
let repo = fx.repo();
|
||||
|
||||
// a.txt: staged and edited again; b.txt: staged; new.txt: staged addition; old.txt: staged rename.
|
||||
fx.write("a.txt", "a staged\n");
|
||||
fx.write("b.txt", "b staged\n");
|
||||
fx.write("new.txt", "new\n");
|
||||
fx.git(&["add", "a.txt", "b.txt", "new.txt"]);
|
||||
fx.git(&["mv", "old.txt", "moved.txt"]);
|
||||
fx.write("a.txt", "a on disk\n");
|
||||
|
||||
// Commit a.txt as it is on disk; leave out b.txt, new.txt and the rename.
|
||||
let options = CommitOptions {
|
||||
stage: vec![fx.path("a.txt").into()],
|
||||
exclude: vec![
|
||||
fx.path("b.txt").into(),
|
||||
fx.path("new.txt").into(),
|
||||
fx.path("moved.txt").into(),
|
||||
fx.path("old.txt").into(),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
repo.commit_with("only a", &options, &|_| Ok(encoding_rs::UTF_8)).unwrap();
|
||||
|
||||
assert_eq!(fx.git(&["show", "--name-only", "--format=", "HEAD"]), "a.txt");
|
||||
assert_eq!(fx.git(&["show", "HEAD:a.txt"]), "a on disk");
|
||||
// What was left out is still staged, exactly as before.
|
||||
let mut staged: Vec<String> =
|
||||
fx.git(&["diff", "--cached", "--name-status", "-M"]).lines().map(str::to_string).collect();
|
||||
staged.sort();
|
||||
assert_eq!(staged, ["A\tnew.txt", "M\tb.txt", "R100\told.txt\tmoved.txt"]);
|
||||
assert_eq!(fx.git(&["show", ":b.txt"]), "b staged");
|
||||
assert_eq!(fx.git(&["diff", "--name-only"]), "", "nothing unstaged is left behind");
|
||||
assert!(!fx.dir.join(".git/openidea-partial-index").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commit_of_staged_version_keeps_the_unstaged_rest() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("a.txt", "1\n");
|
||||
fx.write("b.txt", "1\n");
|
||||
fx.commit_all("base");
|
||||
let repo = fx.repo();
|
||||
fx.write("a.txt", "2\n");
|
||||
fx.write("b.txt", "2\n");
|
||||
fx.git(&["add", "a.txt", "b.txt"]);
|
||||
fx.write("a.txt", "3\n");
|
||||
|
||||
// a.txt committed as staged (its unstaged edit stays), b.txt left out.
|
||||
let options = CommitOptions { exclude: vec![fx.path("b.txt").into()], ..Default::default() };
|
||||
repo.commit_with("staged a", &options, &|_| Ok(encoding_rs::UTF_8)).unwrap();
|
||||
|
||||
assert_eq!(fx.git(&["show", "HEAD:a.txt"]), "2");
|
||||
assert_eq!(fx.git(&["show", "HEAD:b.txt"]), "1");
|
||||
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "b.txt");
|
||||
assert_eq!(fx.git(&["diff", "--name-only"]), "a.txt");
|
||||
assert_eq!(fx.read("a.txt"), "3\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commit_with_exclusions_in_a_repository_without_commits() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("a.txt", "a\n");
|
||||
fx.write("b.txt", "b\n");
|
||||
fx.git(&["add", "-A"]);
|
||||
let repo = fx.repo();
|
||||
let options = CommitOptions { exclude: vec![fx.path("b.txt").into()], ..Default::default() };
|
||||
repo.commit_with("first", &options, &|_| Ok(encoding_rs::UTF_8)).unwrap();
|
||||
assert_eq!(fx.git(&["show", "--name-only", "--format=", "HEAD"]), "a.txt");
|
||||
assert_eq!(fx.git(&["diff", "--cached", "--name-status"]), "A\tb.txt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_checkout_keeps_staged_changes_staged() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("f.txt", "1\n2\n3\n4\n5\n");
|
||||
fx.write("s.txt", "s\n");
|
||||
fx.commit_all("base");
|
||||
fx.git(&["checkout", "-q", "-b", "other"]);
|
||||
fx.write("f.txt", "1\nother\n3\n4\n5\n");
|
||||
fx.commit_all("other edit");
|
||||
fx.git(&["checkout", "-q", "main"]);
|
||||
let repo = fx.repo();
|
||||
|
||||
fx.write("f.txt", "1\n2\n3\n4\nlocal\n");
|
||||
fx.write("s.txt", "staged\n");
|
||||
fx.git(&["add", "s.txt"]);
|
||||
let opts = CheckoutOptions { mode: CheckoutMode::Smart, diverged: None };
|
||||
assert_eq!(repo.checkout_with("other", false, &opts).unwrap(), CheckoutOutcome::Done);
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("other"));
|
||||
assert_eq!(fx.read("f.txt"), "1\nother\n3\n4\nlocal\n");
|
||||
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "s.txt", "staged change stays staged");
|
||||
assert_eq!(fx.git(&["diff", "--name-only"]), "f.txt");
|
||||
assert!(repo.stashes().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkout_reports_untracked_files_it_would_overwrite() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("f.txt", "f\n");
|
||||
fx.commit_all("base");
|
||||
fx.git(&["checkout", "-q", "-b", "other"]);
|
||||
fx.write("dir/new.txt", "theirs\n");
|
||||
fx.commit_all("add new");
|
||||
fx.git(&["checkout", "-q", "main"]);
|
||||
fx.write("dir/new.txt", "mine\n");
|
||||
let repo = fx.repo();
|
||||
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
|
||||
let opts = CheckoutOptions { mode, diverged: None };
|
||||
let outcome = repo.checkout_with("other", false, &opts).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()] });
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
|
||||
assert_eq!(fx.read("dir/new.txt"), "mine\n");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reword_keeps_local_changes_and_can_be_undone() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("a.txt", "1\n");
|
||||
let first = fx.commit_all("first");
|
||||
fx.write("a.txt", "2\n");
|
||||
let second = fx.commit_all("second");
|
||||
fx.write("b.txt", "b\n");
|
||||
fx.commit_all("third");
|
||||
// Local changes, staged and not, must survive untouched.
|
||||
fx.write("a.txt", "local\n");
|
||||
fx.write("staged.txt", "s\n");
|
||||
fx.git(&["add", "staged.txt"]);
|
||||
let repo = fx.repo();
|
||||
|
||||
let change = repo.reword(&second, "second, reworded\n\nwith a body").unwrap();
|
||||
assert_eq!(fx.git(&["log", "--format=%s", "-3"]), "third\nsecond, reworded\nfirst");
|
||||
assert_eq!(fx.git(&["log", "-1", "--format=%B", "HEAD~1"]), "second, reworded\n\nwith a body");
|
||||
assert_eq!(fx.git(&["rev-parse", "HEAD~2"]), first, "commits before it keep their ids");
|
||||
assert_eq!(fx.git(&["rev-parse", "HEAD"]), change.after);
|
||||
assert_eq!(fx.git(&["symbolic-ref", "--short", "HEAD"]), "main", "the branch moved, not a detached HEAD");
|
||||
assert_eq!(fx.read("a.txt"), "local\n");
|
||||
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "staged.txt");
|
||||
assert_eq!(fx.git(&["diff", "--name-only"]), "a.txt");
|
||||
|
||||
repo.restore_head(&change.before, &change.after).unwrap();
|
||||
assert_eq!(fx.git(&["log", "--format=%s", "-3"]), "third\nsecond\nfirst");
|
||||
assert_eq!(fx.read("a.txt"), "local\n");
|
||||
assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "staged.txt");
|
||||
|
||||
// Undo is refused once HEAD has moved.
|
||||
let change = repo.reword("HEAD", "third, reworded").unwrap();
|
||||
fx.git(&["commit", "-q", "--allow-empty", "-m", "later"]);
|
||||
assert!(repo.restore_head(&change.before, &change.after).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reword_refuses_commits_outside_the_current_branch() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("a.txt", "1\n");
|
||||
fx.commit_all("first");
|
||||
fx.git(&["checkout", "-q", "-b", "side"]);
|
||||
fx.write("a.txt", "side\n");
|
||||
let side = fx.commit_all("side");
|
||||
fx.git(&["checkout", "-q", "main"]);
|
||||
assert!(fx.repo().reword(&side, "other").is_err());
|
||||
}
|
||||
@@ -47,16 +47,11 @@ const REPLY = [
|
||||
"```",
|
||||
].join("\n");
|
||||
|
||||
async function openReply(page: Page, text: string, imageData?: string) {
|
||||
async function openReply(page: Page, text: string) {
|
||||
await page.goto("/");
|
||||
await page.getByRole("tree", { name: "Project" }).waitFor();
|
||||
await page.evaluate(
|
||||
async ({ task, text, imageData }) => {
|
||||
if (imageData) {
|
||||
const routePath = "/src/platform/tauriCore.ts";
|
||||
const { setInvokeRoute } = await import(routePath);
|
||||
setInvokeRoute((cmd: string) => (cmd === "fs_read_image" ? Promise.resolve(imageData) : null));
|
||||
}
|
||||
async ({ task, text }) => {
|
||||
// Paths go through variables: knip can't resolve these browser-absolute URLs.
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const store = await import(storePath);
|
||||
@@ -71,7 +66,7 @@ async function openReply(page: Page, text: string, imageData?: string) {
|
||||
});
|
||||
store.dockTask(task.id);
|
||||
},
|
||||
{ task: TASK, text, imageData },
|
||||
{ task: TASK, text },
|
||||
);
|
||||
const reply = page.locator("[class*='_markdown_']").first();
|
||||
await reply.locator("h1, p").first().waitFor();
|
||||
@@ -133,19 +128,3 @@ test("styles quotes, rules, images and task lists", async ({ page }) => {
|
||||
// A checkbox stands in for the bullet.
|
||||
expect(await css(reply, "li:has(> input)", "list-style-type")).toBe("none");
|
||||
});
|
||||
|
||||
test("loads local and web reply images", async ({ page }) => {
|
||||
await page.route("https://images.example.com/code.gif", (route) =>
|
||||
route.fulfill({ contentType: "image/gif", body: Buffer.from(PIXEL.split(",")[1]!, "base64") }),
|
||||
);
|
||||
const reply = await openReply(
|
||||
page,
|
||||
"\n\n",
|
||||
PIXEL,
|
||||
);
|
||||
for (const name of ["Local QR", "Web QR"]) {
|
||||
await expect
|
||||
.poll(() => reply.getByRole("img", { name }).evaluate((img: HTMLImageElement) => img.naturalWidth))
|
||||
.toBe(1);
|
||||
}
|
||||
});
|
||||
@@ -1,100 +0,0 @@
|
||||
/** Real CodeMirror mouse/navigation path with a deliberately slow IPC boundary.
|
||||
* Semantic correctness and JVM timings live in the real-JDT configuration harness.
|
||||
*/
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { commands } from "../src/platform/ipc";
|
||||
import { usePlatform } from "../src/platform/platformInfo";
|
||||
import { provideEditorService } from "../src/workbench/contributions";
|
||||
import { lspDoc } from "../src/editor/lsp/lsp";
|
||||
import { navigationExtension } from "../src/editor/lsp/navigation";
|
||||
import { hoverExtension } from "../src/editor/lsp/hover";
|
||||
import { lspTheme } from "../src/editor/lsp/theme";
|
||||
|
||||
Object.assign(window, { __TAURI_INTERNALS__: {} });
|
||||
usePlatform.setState({ os: "macos" });
|
||||
document.body.innerHTML = `<style>
|
||||
body { --link: #215cc8; font: 16px monospace; margin: 32px; } button { margin: 12px; }
|
||||
.cm-editor { border: 1px solid #888; min-height: 160px; font: 18px monospace; }
|
||||
</style><button id="back">Back to configuration</button><button id="edit">Edit Java target</button>
|
||||
<div id="config"></div><div id="java" hidden></div>
|
||||
<output id="requests">0</output><output id="opened"></output>`;
|
||||
const configHost = document.querySelector<HTMLDivElement>("#config")!;
|
||||
const javaHost = document.querySelector<HTMLDivElement>("#java")!;
|
||||
let requests = 0;
|
||||
let hoverRequests = 0;
|
||||
let targetLine = 0;
|
||||
let clickedAt = 0;
|
||||
const latency: number[] = [];
|
||||
commands.lspGoto = async () => {
|
||||
document.querySelector("#requests")!.textContent = String(++requests);
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
return {
|
||||
status: "ok",
|
||||
data: [
|
||||
{
|
||||
path: "/fixture/Settings.java",
|
||||
uri: null,
|
||||
range: { start: { line: targetLine, col: 24 }, end: { line: targetLine, col: 31 } },
|
||||
},
|
||||
],
|
||||
};
|
||||
};
|
||||
commands.lspHover = async () => {
|
||||
hoverRequests++;
|
||||
return {
|
||||
status: "ok",
|
||||
data: { contents: { kind: "plaintext", value: "dingtalk.driver-class-name String" }, range: null },
|
||||
};
|
||||
};
|
||||
commands.lspDocumentLinks = async () => ({ status: "ok", data: [] });
|
||||
commands.lspDocumentHighlights = async () => ({ status: "ok", data: [] });
|
||||
commands.cancelRequest = async () => ({ status: "ok", data: null });
|
||||
const java = new EditorView({
|
||||
parent: javaHost,
|
||||
state: EditorState.create({
|
||||
doc: "class Settings { String agentId; }",
|
||||
extensions: [
|
||||
lspDoc.of({ doc: 2, path: "/fixture/Settings.java", language: "java", uiMode: "Java", readOnly: false }),
|
||||
navigationExtension(),
|
||||
],
|
||||
}),
|
||||
});
|
||||
const config = new EditorView({
|
||||
parent: configHost,
|
||||
state: EditorState.create({
|
||||
doc: "dingtalk:\n driver-class-name: demo\n",
|
||||
extensions: [
|
||||
EditorState.languageData.of(() => [{ wordChars: "-" }]),
|
||||
lspDoc.of({ doc: 1, path: "/fixture/application.yml", language: "yaml", uiMode: "YAML", readOnly: false }),
|
||||
navigationExtension(),
|
||||
hoverExtension(),
|
||||
lspTheme,
|
||||
],
|
||||
}),
|
||||
});
|
||||
config.contentDOM.addEventListener(
|
||||
"mousedown",
|
||||
() => {
|
||||
clickedAt = performance.now();
|
||||
},
|
||||
true,
|
||||
);
|
||||
provideEditorService({
|
||||
openFile: async (path, options) => {
|
||||
javaHost.hidden = false;
|
||||
configHost.hidden = true;
|
||||
java.dispatch({ selection: { anchor: java.state.doc.line((options?.selection?.line ?? 0) + 1).from + 24 } });
|
||||
document.querySelector("#opened")!.textContent = `${path}:${options?.selection?.line}`;
|
||||
latency.push(performance.now() - clickedAt);
|
||||
},
|
||||
} as Parameters<typeof provideEditorService>[0]);
|
||||
document.querySelector("#back")!.addEventListener("click", () => {
|
||||
javaHost.hidden = true;
|
||||
configHost.hidden = false;
|
||||
});
|
||||
document.querySelector("#edit")!.addEventListener("click", () => {
|
||||
java.dispatch({ changes: { from: 0, insert: "// moved\n" } });
|
||||
targetLine++;
|
||||
});
|
||||
Object.assign(window, { navigationMetrics: () => ({ requests, hoverRequests, latency, injectedServerDelayMs: 500 }) });
|
||||
@@ -1,10 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Configuration navigation fixture</title>
|
||||
</head>
|
||||
<body>
|
||||
<script type="module" src="./configurationNavigation.fixture.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,91 +0,0 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { test, expect, type Page } from "@playwright/test";
|
||||
|
||||
async function keyPosition(page: Page) {
|
||||
const line = page.locator("#config .cm-line").filter({ hasText: "driver-class-name" });
|
||||
const box = (await line.boundingBox())!;
|
||||
// Skip the two-space indentation, land within the actual key.
|
||||
return { x: box.x + 45, y: box.y + box.height / 2 };
|
||||
}
|
||||
async function open(page: Page) {
|
||||
await page.addInitScript(() => Object.defineProperty(Navigator.prototype, "platform", { get: () => "MacIntel" }));
|
||||
await page.goto("/e2e/configurationNavigation.html");
|
||||
await expect(page.locator("#config .cm-content")).toContainText("driver-class-name");
|
||||
}
|
||||
async function metrics(page: Page) {
|
||||
return page.evaluate(() =>
|
||||
(
|
||||
window as unknown as {
|
||||
navigationMetrics: () => {
|
||||
requests: number;
|
||||
hoverRequests: number;
|
||||
latency: number[];
|
||||
injectedServerDelayMs: number;
|
||||
};
|
||||
}
|
||||
).navigationMetrics(),
|
||||
);
|
||||
}
|
||||
|
||||
test("modifier hover and repeated clicks share results; editing Java invalidates them", async ({ page }, info) => {
|
||||
const errors: string[] = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await open(page);
|
||||
const key = await keyPosition(page);
|
||||
await page.keyboard.down("Meta");
|
||||
await page.mouse.move(key.x, key.y);
|
||||
await expect(page.locator(".cm-lsp-link")).toHaveText("driver-class-name");
|
||||
await expect(page.locator(".cm-lsp-link")).toHaveCSS("cursor", "pointer");
|
||||
await expect(page.locator(".cm-lsp-link")).toHaveCSS("color", "rgb(33, 92, 200)");
|
||||
expect((await metrics(page)).hoverRequests).toBe(0);
|
||||
await expect(page.locator(".cm-lsp-nav-info")).toHaveCount(0);
|
||||
await page.screenshot({ path: info.outputPath("configuration-link.png") });
|
||||
await page.mouse.click(key.x, key.y);
|
||||
await expect(page.locator("#opened")).toHaveText("/fixture/Settings.java:0");
|
||||
await page.keyboard.up("Meta");
|
||||
for (let i = 0; i < 10; i++) {
|
||||
await page.getByRole("button", { name: "Back to configuration" }).click();
|
||||
await page.keyboard.down("Meta");
|
||||
await page.mouse.click(key.x, key.y);
|
||||
await expect(page.locator("#java")).toBeVisible();
|
||||
await page.keyboard.up("Meta");
|
||||
}
|
||||
const warm = await metrics(page);
|
||||
expect(warm.requests).toBe(1);
|
||||
expect(warm.latency).toHaveLength(11);
|
||||
const evidence = info.outputPath("warm-navigation.json");
|
||||
await writeFile(evidence, JSON.stringify(warm, null, 2));
|
||||
await info.attach("warm-navigation.json", { path: evidence, contentType: "application/json" });
|
||||
await page.getByRole("button", { name: "Edit Java target" }).click();
|
||||
await page.getByRole("button", { name: "Back to configuration" }).click();
|
||||
await page.keyboard.down("Meta");
|
||||
await page.mouse.click(key.x, key.y);
|
||||
await expect(page.locator("#opened")).toHaveText("/fixture/Settings.java:1");
|
||||
expect((await metrics(page)).requests).toBe(2);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test("clicking before the hover query completes shares the in-flight request", async ({ page }, info) => {
|
||||
await open(page);
|
||||
const key = await keyPosition(page);
|
||||
await page.keyboard.down("Meta");
|
||||
await page.mouse.move(key.x, key.y);
|
||||
await expect(page.locator("#requests")).toHaveText("1");
|
||||
await page.mouse.click(key.x, key.y);
|
||||
await expect(page.locator("#opened")).toHaveText("/fixture/Settings.java:0");
|
||||
const result = await metrics(page);
|
||||
expect(result.requests).toBe(1);
|
||||
await info.attach("inflight-navigation.json", {
|
||||
body: JSON.stringify(result, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
});
|
||||
|
||||
test("ordinary hover still shows configuration documentation", async ({ page }) => {
|
||||
await open(page);
|
||||
const key = await keyPosition(page);
|
||||
await page.mouse.move(key.x, key.y);
|
||||
await expect(page.locator(".cm-lsp-hover")).toContainText("dingtalk.driver-class-name String");
|
||||
expect((await metrics(page)).requests).toBe(0);
|
||||
expect((await metrics(page)).hoverRequests).toBeGreaterThan(0);
|
||||
});
|
||||
@@ -52,27 +52,12 @@ modules, skips nested independent modules and build output, and honors ignore
|
||||
files for disk discovery. It does not guess a global association from matching
|
||||
text in unrelated projects.
|
||||
|
||||
Trusted projects with a Maven/Gradle/Eclipse build file at the root start Java a
|
||||
moment after opening, even without a Java editor open. Once JDT reports
|
||||
ServiceReady and compiler defaults are applied, the app asks the extension to warm
|
||||
the configuration index (`openidea.java.configuration.warmup`). A low-priority
|
||||
system job waits for workspace builds, then builds the same snapshot navigation
|
||||
uses, one Java project at a time: modules with open YAML/properties files first,
|
||||
then modules with open Java editors. At most 64 modules are queued, each attempt
|
||||
has a cooperative 30-second budget, repeated readiness does not repeat finished
|
||||
work, and warming only fills free room within the retention limits below (it never
|
||||
evicts an index a lookup built). A snapshot outdated while it was being built is
|
||||
dropped. Untrusted projects do not start Java; anything warming skips keeps
|
||||
on-demand indexing.
|
||||
|
||||
Otherwise indexing is lazy. The first explicit navigation/search builds a compact snapshot;
|
||||
Indexing is lazy. The first explicit navigation/search builds a compact snapshot;
|
||||
ordinary typing, code-lens probes, bulk scoped reference analysis, and Java Go to Definition / Ctrl+hover outside a `@Value` or property-lookup argument (checked with the bundled tree-sitter grammar) do not start indexing. At most eight project snapshots are
|
||||
retained, with a shared 100,000-association retention cap. Records contain property names, element handles and source locations;
|
||||
ASTs and bindings are discarded after indexing. A lexical prefilter avoids AST
|
||||
construction for ordinary Java units, but every accepted association is resolved
|
||||
semantically. Builds hold a per-project lock that a waiting lookup can cancel, so a
|
||||
background build of one project never delays another, and a lookup in the same
|
||||
project reuses the result. Warm requests reuse the snapshot. Java model changes (sources on
|
||||
semantically. Warm requests reuse the snapshot. Java model changes (sources on
|
||||
disk, classpath, archives) invalidate it conservatively, including dependent-type
|
||||
changes; a fingerprint of working copies with unsaved changes covers edits before
|
||||
they are saved. Opening or closing an editor, reconciling, building, and non-Java
|
||||
@@ -80,14 +65,6 @@ resource changes (configuration files are parsed by the client; metadata files a
|
||||
checked by timestamp) keep it. This is **snapshot invalidation**, not a fully
|
||||
incremental Java semantic index.
|
||||
|
||||
In YAML/properties, ⌘/Ctrl-hover underlines the whole key, hyphens and dots
|
||||
included, and doesn't open the documentation popup. Hover and Go to Definition share
|
||||
one request per key: a click after the hover reuses its answer. The editor keeps up
|
||||
to 128 answers / 4,096 locations, drops them on edits, file and project changes,
|
||||
workspace edits and language-server restarts, and expires them after 30 seconds as a
|
||||
backstop. Empty answers and errors are not kept, since the import may still be in
|
||||
progress.
|
||||
|
||||
Metadata/JAR timestamps are checked before reuse. The client caches parsed disk
|
||||
configuration files by modification time and size (at most 100,000 cached keys), overlays open buffers, and
|
||||
performs bounded discovery/parsing on a blocking worker. It does not continuously
|
||||
@@ -97,7 +74,7 @@ Bounds: 20,000 Java units, 100,000 associations per snapshot, 2 MiB per candidat
|
||||
metadata/configuration file (Java source: 2M UTF-16 units), 1,024-character property names, 2,000 configuration files/results, 50,000 filesystem
|
||||
entries per root, and depth limits on recursive bindings/YAML. Java requests and
|
||||
references are cancellable. File/association scan limits and unreadable files carry the
|
||||
existing incomplete-result indicator; unsupported syntax keys are omitted. Navigation before warming finishes can take seconds on a
|
||||
existing incomplete-result indicator; unsupported syntax keys are omitted. First navigation can take seconds on a
|
||||
cold project; classpath import and source download remain owned by JDT LS.
|
||||
|
||||
## Deliberate limits
|
||||
@@ -128,8 +105,7 @@ cargo test -p ide-language -p ide-lsp
|
||||
The isolated real-server harness covers custom bindings, inheritance, nesting,
|
||||
collections/maps, records, constructor aliases, factory methods, consumers,
|
||||
constant keys, negative identity matches, dependency metadata/source locations,
|
||||
reverse queries, warming (queued once, reused by the first lookup, cancellable), and
|
||||
unsaved-change/close invalidation. Optional stress fixtures
|
||||
reverse queries, and unsaved-change/close invalidation. Optional stress fixtures
|
||||
add 3,000 ordinary units and 100 binding classes; output includes cold/warm/edit
|
||||
latencies for the JDT command only, excluding server import, UI and configuration-file discovery. The optional actual Spring Boot JAR checks `server.port`,
|
||||
`spring.datasource.url` and `spring.jackson.date-format` through dependency
|
||||
|
||||
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
|
||||
Bundle-ManifestVersion: 2
|
||||
Bundle-Name: OpenIDEA Java usages
|
||||
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
|
||||
Bundle-Version: 1.6.0
|
||||
Bundle-Version: 1.5.0
|
||||
Bundle-RequiredExecutionEnvironment: JavaSE-21
|
||||
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
|
||||
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
|
||||
|
||||
@@ -57,7 +57,7 @@ is not a claim of full IntelliJ feature parity.
|
||||
## Rebuild and delivery
|
||||
|
||||
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
|
||||
`java-usages-1.6.0.jar`, and added alongside existing initialization bundles.
|
||||
`java-usages-1.5.0.jar`, and added alongside existing initialization bundles.
|
||||
Users need no compiler, Maven or Python. Manifest/install version must change
|
||||
when replacing the bundle because OSGi caches bundles.
|
||||
|
||||
@@ -83,10 +83,6 @@ Version 1.5.0 answers `{locations, complete}`: `complete` when the type is decla
|
||||
dependencies' implementations after the first ones. The search also covers the project's Kotlin
|
||||
classes attached by the Kotlin bridge; its reproducible SHA-256 is
|
||||
`7588748c2797f9da2beb209714a75c29b4e31b155f095329bfb7e399d807c20a`.
|
||||
Version 1.6.0 adds `openidea.java.configuration.warmup`, which builds configuration indexes in a
|
||||
low-priority background job after import, and builds them under cancellable per-project locks
|
||||
instead of one global lock; its reproducible SHA-256 is
|
||||
`33cfa1bb8489247ffeb6fc8249966c8a2955b7b2858c8169a70486eb70ade696`.
|
||||
|
||||
```sh
|
||||
export PATH=/path/to/jdk25/bin:$PATH
|
||||
|
||||
Бінарний файл не відображається.
@@ -6,7 +6,6 @@
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.configuration.ConfigurationCommand">
|
||||
<command id="openidea.java.configuration"/>
|
||||
<command id="openidea.java.configuration.warmup"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.implementations.ImplementationsCommand">
|
||||
<command id="openidea.java.implementations"/>
|
||||
|
||||
@@ -4,10 +4,7 @@ import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.zip.ZipFile;
|
||||
import com.google.gson.*;
|
||||
import org.eclipse.core.resources.ResourcesPlugin;
|
||||
@@ -32,8 +29,6 @@ public final class ConfigurationCommand implements IDelegateCommandHandler {
|
||||
private static final int MAX_UNITS = 20_000, MAX_ENTRIES = 100_000, MAX_BYTES = 2 * 1024 * 1024;
|
||||
private static final AtomicLong REVISION = new AtomicLong(), GENERATION = new AtomicLong();
|
||||
private static final Map<String, Index> CACHE = new LinkedHashMap<>();
|
||||
/** One build per project at a time; waiting lookups stay cancellable. */
|
||||
private static final Map<String, ReentrantLock> LOCKS = new ConcurrentHashMap<>();
|
||||
/** Unsaved edits are covered by the working-copy digest, so reconciles never
|
||||
* invalidate. Opening/closing a working copy (F_PRIMARY_WORKING_COPY) and
|
||||
* non-Java resources, reported as F_CONTENT on a project, root or package
|
||||
@@ -61,7 +56,6 @@ public final class ConfigurationCommand implements IDelegateCommandHandler {
|
||||
|
||||
@Override
|
||||
public Object executeCommand(String command, List<Object> args, IProgressMonitor monitor) throws Exception {
|
||||
if (command.equals("openidea.java.configuration.warmup")) return ConfigurationWarmup.request(args);
|
||||
String uri = (String) args.get(0);
|
||||
String key = args.get(1) instanceof String s ? s : null;
|
||||
int line = ((Number) args.get(2)).intValue(), column = ((Number) args.get(3)).intValue();
|
||||
@@ -144,7 +138,7 @@ public final class ConfigurationCommand implements IDelegateCommandHandler {
|
||||
(line < r.getEnd().getLine() || line == r.getEnd().getLine() && col < r.getEnd().getCharacter());
|
||||
}
|
||||
private static void check(IProgressMonitor monitor) { if (monitor.isCanceled()) throw new OperationCanceledException(); }
|
||||
static IJavaProject project(String uri) {
|
||||
private static IJavaProject project(String uri) {
|
||||
Path path;
|
||||
try { path = Path.of(URI.create(uri)).toFile().getCanonicalFile().toPath(); } catch (Exception e) { return null; }
|
||||
IJavaProject best = null;
|
||||
@@ -169,33 +163,7 @@ public final class ConfigurationCommand implements IDelegateCommandHandler {
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Builds (or reuses) the project's index in the background; its generation. */
|
||||
static long warm(IJavaProject project, IProgressMonitor monitor) throws Exception {
|
||||
return index(project, monitor, true).generation;
|
||||
}
|
||||
|
||||
/** Warming fills free cache room only; it never evicts an index a lookup built. */
|
||||
static boolean hasWarmupCapacity(IJavaProject project) {
|
||||
synchronized (CACHE) {
|
||||
return CACHE.containsKey(project.getHandleIdentifier()) || (CACHE.size() < 8 &&
|
||||
CACHE.values().stream().mapToInt(value -> value.entries.size()).sum() < MAX_ENTRIES);
|
||||
}
|
||||
}
|
||||
|
||||
private static Index index(IJavaProject project, IProgressMonitor monitor) throws Exception {
|
||||
return index(project, monitor, false);
|
||||
}
|
||||
|
||||
private static Index index(IJavaProject project, IProgressMonitor monitor, boolean background) throws Exception {
|
||||
ReentrantLock lock = LOCKS.computeIfAbsent(project.getHandleIdentifier(), ignored -> new ReentrantLock());
|
||||
while (!lock.tryLock(50, TimeUnit.MILLISECONDS)) check(monitor);
|
||||
try {
|
||||
check(monitor);
|
||||
return build(project, monitor, background);
|
||||
} finally { lock.unlock(); }
|
||||
}
|
||||
|
||||
private static Index build(IJavaProject project, IProgressMonitor monitor, boolean background) throws Exception {
|
||||
private static synchronized Index index(IJavaProject project, IProgressMonitor monitor) throws Exception {
|
||||
long revision = REVISION.get();
|
||||
String id = project.getHandleIdentifier();
|
||||
Map<String, ICompilationUnit> copies = new TreeMap<>();
|
||||
@@ -213,8 +181,7 @@ public final class ConfigurationCommand implements IDelegateCommandHandler {
|
||||
if (source != null) digest.update(source.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
String workingCopies = HexFormat.of().formatHex(digest.digest());
|
||||
Index cached;
|
||||
synchronized (CACHE) { cached = CACHE.get(id); }
|
||||
Index cached = CACHE.get(id);
|
||||
if (cached != null && cached.revision == revision && cached.workingCopies.equals(workingCopies)) {
|
||||
boolean valid = true;
|
||||
for (var entry : cached.files.entrySet()) {
|
||||
@@ -260,19 +227,11 @@ public final class ConfigurationCommand implements IDelegateCommandHandler {
|
||||
roots.add(project.getProject().getLocationURI().toString());
|
||||
builder.metadataDirectory(project.getProject().getLocation().toFile().toPath().resolve("src/main/resources"), project);
|
||||
Index result = new Index(revision, workingCopies, List.copyOf(builder.entries), List.copyOf(roots), Map.copyOf(builder.files), builder.incomplete, builder.parsed, GENERATION.incrementAndGet());
|
||||
check(monitor);
|
||||
// A warmed index that the model has already outdated is dropped, not published.
|
||||
if (background && revision != REVISION.get()) throw new OperationCanceledException();
|
||||
synchronized (CACHE) {
|
||||
if (background && ((!CACHE.containsKey(id) && CACHE.size() >= 8) ||
|
||||
CACHE.entrySet().stream().filter(e -> !e.getKey().equals(id)).mapToInt(e -> e.getValue().entries.size()).sum()
|
||||
+ result.entries.size() > MAX_ENTRIES)) throw new OperationCanceledException();
|
||||
CACHE.remove(id);
|
||||
while (!CACHE.isEmpty() && (CACHE.size() >= 8 ||
|
||||
CACHE.values().stream().mapToInt(value -> value.entries.size()).sum() + result.entries.size() > MAX_ENTRIES))
|
||||
CACHE.remove(CACHE.keySet().iterator().next());
|
||||
CACHE.put(id, result);
|
||||
}
|
||||
CACHE.remove(id);
|
||||
while (!CACHE.isEmpty() && (CACHE.size() >= 8 ||
|
||||
CACHE.values().stream().mapToInt(value -> value.entries.size()).sum() + result.entries.size() > MAX_ENTRIES))
|
||||
CACHE.remove(CACHE.keySet().iterator().next());
|
||||
CACHE.put(id, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
package ai.openidea.configuration;
|
||||
|
||||
import java.util.*;
|
||||
import org.eclipse.core.resources.ResourcesPlugin;
|
||||
import org.eclipse.core.runtime.*;
|
||||
import org.eclipse.core.runtime.jobs.Job;
|
||||
import org.eclipse.jdt.core.*;
|
||||
|
||||
/** One bounded, cooperative queue per language-server process. No polling timer,
|
||||
* retained ASTs, or project builds; an ordinary lookup remains the fallback. */
|
||||
final class ConfigurationWarmup {
|
||||
private static final Map<String, IJavaProject> pending = new LinkedHashMap<>();
|
||||
private static final Set<String> attempted = new HashSet<>();
|
||||
private static final Map<String, Long> completed = new LinkedHashMap<>();
|
||||
private static boolean scheduled, stopped;
|
||||
private static String active;
|
||||
private static final Job job = new Job("Preparing configuration navigation") {
|
||||
@Override protected IStatus run(IProgressMonitor monitor) {
|
||||
// Compiler defaults/import can schedule a build after ServiceReady.
|
||||
// Yield to it instead of blocking a worker on the build job family.
|
||||
if (building()) {
|
||||
synchronized (ConfigurationWarmup.class) {
|
||||
if (!stopped) schedule(2000);
|
||||
else scheduled = false;
|
||||
}
|
||||
return Status.OK_STATUS;
|
||||
}
|
||||
IJavaProject project;
|
||||
synchronized (ConfigurationWarmup.class) {
|
||||
if (stopped || pending.isEmpty()) { scheduled = false; return Status.OK_STATUS; }
|
||||
String id = pending.keySet().iterator().next();
|
||||
project = pending.remove(id);
|
||||
active = id;
|
||||
}
|
||||
long deadline = System.nanoTime() + 30_000_000_000L;
|
||||
IProgressMonitor bounded = new ProgressMonitorWrapper(monitor) {
|
||||
@Override public boolean isCanceled() {
|
||||
return super.isCanceled() || System.nanoTime() >= deadline ||
|
||||
!project.exists() || !project.getProject().isOpen();
|
||||
}
|
||||
};
|
||||
try {
|
||||
if (ConfigurationCommand.hasWarmupCapacity(project)) {
|
||||
long build = ConfigurationCommand.warm(project, bounded);
|
||||
synchronized (ConfigurationWarmup.class) {
|
||||
if (completed.size() < 8) completed.put(project.getHandleIdentifier(), build);
|
||||
}
|
||||
}
|
||||
} catch (OperationCanceledException e) {
|
||||
// No partial index is published. A user lookup can retry later.
|
||||
} catch (Exception e) {
|
||||
org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin.logException("Configuration warmup skipped", e);
|
||||
} finally {
|
||||
synchronized (ConfigurationWarmup.class) {
|
||||
active = null;
|
||||
if (!stopped && !pending.isEmpty()) schedule(200);
|
||||
else scheduled = false;
|
||||
}
|
||||
}
|
||||
return Status.OK_STATUS;
|
||||
}
|
||||
};
|
||||
static { job.setSystem(true); job.setPriority(Job.DECORATE); }
|
||||
|
||||
private static boolean building() {
|
||||
for (Object family : new Object[] { ResourcesPlugin.FAMILY_AUTO_BUILD, ResourcesPlugin.FAMILY_MANUAL_BUILD })
|
||||
for (Job other : Job.getJobManager().find(family))
|
||||
if (other.getState() != Job.NONE) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
static synchronized Object request(List<Object> args) throws JavaModelException {
|
||||
String action = args.isEmpty() ? "start" : String.valueOf(args.get(0));
|
||||
if (action.equals("cancel")) {
|
||||
stopped = true;
|
||||
pending.clear();
|
||||
job.cancel();
|
||||
if (active == null) scheduled = false;
|
||||
} else if (action.equals("start") && !stopped) {
|
||||
// Open Java buffers identify the user's active modules. Keep those
|
||||
// ahead of the rest when the workspace exceeds the cache budget.
|
||||
Set<String> open = new HashSet<>();
|
||||
for (ICompilationUnit unit : JavaCore.getWorkingCopies(null)) open.add(unit.getJavaProject().getHandleIdentifier());
|
||||
for (ICompilationUnit unit : JavaCore.getWorkingCopies(
|
||||
org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin.getInstance().getWorkingCopyOwner()))
|
||||
open.add(unit.getJavaProject().getHandleIdentifier());
|
||||
Set<String> preferred = new HashSet<>();
|
||||
if (args.size() > 1 && args.get(1) instanceof List<?> uris) {
|
||||
for (Object uri : uris) if (uri instanceof String text) {
|
||||
IJavaProject project = ConfigurationCommand.project(text);
|
||||
if (project != null) preferred.add(project.getHandleIdentifier());
|
||||
}
|
||||
}
|
||||
List<IJavaProject> projects = new ArrayList<>(Arrays.asList(
|
||||
JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects()));
|
||||
projects.sort(Comparator.comparing((IJavaProject p) -> !preferred.contains(p.getHandleIdentifier()))
|
||||
.thenComparing(p -> !open.contains(p.getHandleIdentifier()))
|
||||
.thenComparing(IJavaProject::getElementName));
|
||||
for (IJavaProject project : projects) {
|
||||
String id = project.getHandleIdentifier();
|
||||
if (project.getProject().isOpen() && !attempted.contains(id) && pending.size() < 64) {
|
||||
attempted.add(id);
|
||||
pending.put(id, project);
|
||||
}
|
||||
}
|
||||
if (!scheduled && !pending.isEmpty()) { scheduled = true; job.schedule(2000); }
|
||||
}
|
||||
return Map.of("scheduled", scheduled, "pending", pending.size(), "active", active == null ? "" : active,
|
||||
"completed", new LinkedHashMap<>(completed));
|
||||
}
|
||||
}
|
||||
@@ -159,28 +159,11 @@ try:
|
||||
send({'jsonrpc': '2.0', 'method': 'textDocument/didOpen', 'params': {'textDocument': {'uri': file.as_uri(), 'languageId': 'java', 'version': 1, 'text': source}}})
|
||||
request('java/buildWorkspace', True)
|
||||
assert 'openidea.java.configuration' in init['capabilities']['executeCommandProvider']['commands'], init
|
||||
def warmup(action='start'):
|
||||
return request('workspace/executeCommand', {'command': 'openidea.java.configuration.warmup', 'arguments': [action, [(project / 'application.yml').as_uri()]]})
|
||||
# Queuing is cheap and idempotent; the index is built by a background job.
|
||||
queued_at = time.perf_counter()
|
||||
queued = warmup()
|
||||
assert queued['scheduled'] and queued['pending'] > 0 and not queued['completed'], queued
|
||||
assert warmup()['pending'] == queued['pending'], 'a repeated start queued the project twice'
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
warmed = warmup('status')
|
||||
if not warmed['scheduled']: break
|
||||
time.sleep(.1)
|
||||
assert not warmed['scheduled'] and warmed['completed'], warmed
|
||||
assert warmup()['pending'] == 0, 'a repeated start queued a warmed project again'
|
||||
prewarm_seconds = time.perf_counter() - queued_at
|
||||
results = {}
|
||||
for key in ['app', 'vendor', 'app.time-out', 'app.enabled', 'app.nested.url', 'app.clients[0].url', 'app.routes.east.url', 'app.tags[0]', 'app.labels.region', 'app.labels[region.name]', 'constructor.remote-name', 'record.name', 'bean.url', 'app.backup', 'app.required', 'vendor.port', 'extra.url']:
|
||||
start = time.perf_counter()
|
||||
result = query(key)
|
||||
results[key] = {'seconds': time.perf_counter() - start, 'response': result}
|
||||
if key == 'app':
|
||||
assert result['generation'] in warmed['completed'].values(), ('the first lookup rebuilt the warmed index', result, warmed)
|
||||
assert result['locations'], (key, result)
|
||||
attached = request('java/classFileContents', {'uri': results['vendor.port']['response']['locations'][0]['uri']})
|
||||
assert attached and 'LibrarySettings' in attached and 'port' in attached, attached
|
||||
@@ -255,9 +238,7 @@ try:
|
||||
send({'jsonrpc': '2.0', 'method': 'textDocument/didClose', 'params': {'textDocument': {'uri': file.as_uri()}}})
|
||||
restored = query('app.nested.url')
|
||||
assert restored['locations'], restored
|
||||
cancelled = warmup('cancel')
|
||||
assert not cancelled['scheduled'] and cancelled['pending'] == 0, cancelled
|
||||
evidence = {'stress': os.environ.get('OPENIDEA_CONFIGURATION_STRESS') == '1', 'prewarmSeconds': prewarm_seconds, 'editRebuildMs': edit_ms, 'cases': results, 'warmMedianMs': sorted(warm)[len(warm)//2] * 1000, 'warmMaxMs': max(warm) * 1000, 'generations': [generation, after_save, after_close]}
|
||||
evidence = {'stress': os.environ.get('OPENIDEA_CONFIGURATION_STRESS') == '1', 'editRebuildMs': edit_ms, 'cases': results, 'warmMedianMs': sorted(warm)[len(warm)//2] * 1000, 'warmMaxMs': max(warm) * 1000, 'generations': [generation, after_save, after_close]}
|
||||
(work / 'evidence.json').write_text(json.dumps(evidence, indent=2))
|
||||
print(json.dumps(evidence, indent=2))
|
||||
finally:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Lombok agent for JDT LS
|
||||
|
||||
`lombok-1.18.48-openidea.3.jar` is the app-provided Java agent for JDT LS. It includes:
|
||||
`lombok-1.18.48-openidea.2.jar` is the app-provided Java agent for JDT LS. It includes:
|
||||
|
||||
- [projectlombok/lombok#4059](https://github.com/projectlombok/lombok/pull/4059), which restores
|
||||
`lombok.config` lookup after Equinox removed `getModuleClassLoader(boolean)`.
|
||||
@@ -10,11 +10,6 @@
|
||||
that call in the `@SneakyThrows` try block (ECJ then fails with "Internal Error compiling …
|
||||
BlockScope cannot be cast to MethodScope" and the whole workspace build fails) and put `@NonNull`
|
||||
checks before it; constructors Lombok generates lacked the statement.
|
||||
- [`patches/builder-compact-constructor.patch`](patches/builder-compact-constructor.patch), not yet
|
||||
proposed upstream. `@Builder` on a compact record constructor (`record R(...) { @Builder R {} }`)
|
||||
failed under ECJ ("The method builder() is undefined", missing builder setters), because ECJ has
|
||||
not filled in a compact constructor's implicit parameters when Lombok runs. The builder now takes
|
||||
its parameters from the record components in that case; javac was unaffected.
|
||||
|
||||
The jar is embedded by `ide-tools`, so every platform receives the same bytes without a download.
|
||||
Both Java server startup and launch diagnostics obtain it through `managed_bundle`. Tool detection
|
||||
@@ -24,7 +19,7 @@ The filename includes the patch version because JDT LS workspace keys include th
|
||||
changing agents must rebuild classes produced by the old agent. Old jars remain for running windows.
|
||||
|
||||
Replace this temporary bundle with an official Maven Central release once that release includes
|
||||
#4059, #4089 and the compact-constructor builder fix. Restore the registry's Maven Central install method and remove the embedded jar. Keep the
|
||||
#4059 and #4089. Restore the registry's Maven Central install method and remove the embedded jar. Keep the
|
||||
workspace migration test when changing its path.
|
||||
|
||||
## Provenance and build
|
||||
@@ -38,12 +33,10 @@ workspace migration test when changing its path.
|
||||
- PR #4089 (`Rawi01/lombok` `eclipse-constructor-call-statement`):
|
||||
- `7832faa49b35c839088866daf865384c82cd555f`
|
||||
- `3f3a80b857a969839ab1baba12767aec4965ac32`
|
||||
- Then `git apply` [`patches/builder-compact-constructor.patch`](patches/builder-compact-constructor.patch)
|
||||
(changes `src/core/lombok/eclipse/handlers/HandleBuilder.java` only).
|
||||
- Upstream version: `1.18.48`; `openidea.3` identifies this distribution of the patched agent
|
||||
(`openidea.1` had #4059 only; `openidea.2` added #4089).
|
||||
- Upstream version: `1.18.48`; `openidea.2` identifies this distribution of the patched agent
|
||||
(`openidea.1` had #4059 only).
|
||||
Upstream's own `java -jar ... --version` still reports `1.18.48`.
|
||||
- SHA-256: `26069a8138680f5e1100c83cd064d6aa7314385a1afcef74269cdcc41beb0442`
|
||||
- SHA-256: `2978d8b2d55dac1bb4936ba44562bc4549931d4e71a7ebfeaebccd60bcdf7379`
|
||||
- License: [MIT, including bundled component notices](LICENSE), also retained inside the jar.
|
||||
- Build environment: macOS arm64, Temurin 25.0.5, Apache Ant 1.10.15, upstream Ivy setup
|
||||
(`openidea.1` was built with OpenJDK 23.0.1).
|
||||
@@ -58,9 +51,8 @@ git fetch https://github.com/chagong/lombok.git fix-equinox-bundle-wiring
|
||||
git fetch https://github.com/Rawi01/lombok.git eclipse-constructor-call-statement
|
||||
git cherry-pick 2d535482a913de46c27d06c5b0b294918ede3f9c 3098f4dd78b5349c2f382e7310e64db810dd380b
|
||||
git cherry-pick 7832faa49b35c839088866daf865384c82cd555f 3f3a80b857a969839ab1baba12767aec4965ac32
|
||||
git apply /path/to/openidea/java/lombok/patches/builder-compact-constructor.patch
|
||||
ant dist
|
||||
cp dist/lombok.jar /path/to/openidea/java/lombok/lombok-1.18.48-openidea.3.jar
|
||||
cp dist/lombok.jar /path/to/openidea/java/lombok/lombok-1.18.48-openidea.2.jar
|
||||
```
|
||||
|
||||
The changelog context conflicts because the first commit adds a release-note line under the
|
||||
@@ -70,15 +62,13 @@ skipped). The #4089 commits apply cleanly. The final source diff from v1.18.48 c
|
||||
`src/eclipseAgent/lombok/launch/PatchFixesHider.java`, `test/core/src/lombok/TestEclipse.java`,
|
||||
`test/core/src/lombok/launch/PatchFixesHiderTest.java` (#4059) and the Eclipse handlers
|
||||
`EclipseHandlerUtil`, `HandleConstructor`, `HandleFieldNameConstants`, `HandleNonNull`,
|
||||
`HandleSneakyThrows`, `HandleStandardException`, `HandleSuperBuilder`, `HandleUtilityClass` (#4089)
|
||||
and `HandleBuilder` (the compact-constructor patch); no other Java source changes were made.
|
||||
`openidea.3` was built with the unmodified upstream build scripts. (`openidea.2`'s build checkout
|
||||
reordered the two remote resolvers in `buildScripts/ivysettings.xml` to try Maven Central before
|
||||
Eclipse staging and used a local HTTP/HTTPS proxy for downloads.) Compared with `openidea.2`, the
|
||||
only changed class is `HandleBuilder`; other differences are build timestamps in the generated
|
||||
`META-INF/services` files and the nested `mavenEcjBootstrapAgent.jar`. Ant's timestamps mean a
|
||||
rebuild need not be byte-identical; `SHA256SUMS` records the checked-in artifact and is verified by
|
||||
the Rust regression tests.
|
||||
`HandleSneakyThrows`, `HandleStandardException`, `HandleSuperBuilder`, `HandleUtilityClass` (#4089);
|
||||
no other Java source changes were made.
|
||||
In the build checkout, the two remote resolvers in
|
||||
`buildScripts/ivysettings.xml` were reordered to try Maven Central before Eclipse staging; the
|
||||
local resolver and all dependency coordinates were retained. The JVM was configured to use the
|
||||
local HTTP/HTTPS proxy for downloads. Ant's timestamps mean a rebuild need not be byte-identical;
|
||||
`SHA256SUMS` records the checked-in artifact and is verified by the Rust regression tests.
|
||||
|
||||
## Validation
|
||||
|
||||
@@ -108,17 +98,6 @@ On macOS arm64 with JDT LS 1.63.0 / Equinox 3.25.0, server OpenJDK 25 and projec
|
||||
Failed with three internal errors and wrote no classes; `openidea.2` Succeeded with all classes.
|
||||
- `java/java-usages/tests/verify.py` and `read-write.py` passed with `openidea.2`.
|
||||
|
||||
`openidea.3` (compact-constructor builders) on macOS arm64, JDT LS ECJ
|
||||
`compiler.batch_3.46.200.v20261008-1115`, Temurin 25:
|
||||
|
||||
- [`tests/verify.py`](tests/verify.py) compiles and runs
|
||||
[`tests/BuilderCompactConstructor.java`](tests/BuilderCompactConstructor.java) with javac and with
|
||||
ECJ plus the agent: builders on compact constructors (with validation, `toBuilder`, `setterPrefix`,
|
||||
generics, `@Singular`, `@NonNull`, empty records), a long-form canonical constructor, a
|
||||
non-canonical record constructor, type-level record builders, and the #4089 constructor cases.
|
||||
Both passed with `openidea.3`; with `openidea.2`, ECJ failed on every compact-constructor builder.
|
||||
- `java/java-usages/tests/verify.py` and `read-write.py` passed with `openidea.3`.
|
||||
|
||||
Windows and Linux runtime validation has not been performed. Rust tests cover source selection
|
||||
for both supported architectures on all three OS variants, offline provisioning, corruption
|
||||
repair, concurrent windows, explicit user overrides, and JDT LS workspace migration.
|
||||
@@ -1 +1 @@
|
||||
26069a8138680f5e1100c83cd064d6aa7314385a1afcef74269cdcc41beb0442 lombok-1.18.48-openidea.3.jar
|
||||
2978d8b2d55dac1bb4936ba44562bc4549931d4e71a7ebfeaebccd60bcdf7379 lombok-1.18.48-openidea.2.jar
|
||||
BIN
Бінарний файл не відображається.
@@ -1,21 +0,0 @@
|
||||
diff --git a/src/core/lombok/eclipse/handlers/HandleBuilder.java b/src/core/lombok/eclipse/handlers/HandleBuilder.java
|
||||
index 64a3fa9..6ebaaaf 100755
|
||||
--- a/src/core/lombok/eclipse/handlers/HandleBuilder.java
|
||||
+++ b/src/core/lombok/eclipse/handlers/HandleBuilder.java
|
||||
@@ -493,10 +493,13 @@ public class HandleBuilder extends EclipseAnnotationHandler<Builder> {
|
||||
if (!checkBuilderClassNameAnnotationConflict("Builder", "lombok.Builder", job.builderClassName, ast, annotationNode)) return;
|
||||
|
||||
if (fillParametersFrom != null) {
|
||||
- for (EclipseNode param : fillParametersFrom.down()) {
|
||||
- if (param.getKind() != Kind.ARGUMENT) continue;
|
||||
+ // ECJ has not populated the implicit arguments of a compact record constructor yet.
|
||||
+ boolean compactConstructor = parent.get() instanceof ConstructorDeclaration
|
||||
+ && isRecord(job.parentType) && (parent.get().bits & IsCanonicalConstructor) != 0;
|
||||
+ for (EclipseNode param : (compactConstructor ? job.parentType : fillParametersFrom).down()) {
|
||||
+ if (compactConstructor ? !isRecordField(param) : param.getKind() != Kind.ARGUMENT) continue;
|
||||
BuilderFieldData bfd = new BuilderFieldData();
|
||||
- Argument arg = (Argument) param.get();
|
||||
+ AbstractVariableDeclaration arg = (AbstractVariableDeclaration) param.get();
|
||||
|
||||
Annotation[] copyableAnnotations = findCopyableAnnotations(param);
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import lombok.Builder;
|
||||
import lombok.NonNull;
|
||||
import lombok.Singular;
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
public class BuilderCompactConstructor {
|
||||
@Builder(toBuilder = true)
|
||||
record Payment(String number, String phone, BigDecimal amount,
|
||||
BigDecimal serviceCharge, BigDecimal total, Status status) {
|
||||
@Builder
|
||||
Payment {
|
||||
if (serviceCharge == null) serviceCharge = BigDecimal.ZERO;
|
||||
}
|
||||
}
|
||||
|
||||
enum Status { PENDING, SUCCESS, EXPIRED }
|
||||
|
||||
record ConstructorOnly(String name, int count) {
|
||||
@Builder(toBuilder = true, setterPrefix = "with")
|
||||
ConstructorOnly {
|
||||
if (count < 0) throw new IllegalArgumentException("count");
|
||||
}
|
||||
}
|
||||
|
||||
@Builder(toBuilder = true)
|
||||
record TypeOnly(int count) {
|
||||
TypeOnly { count++; }
|
||||
}
|
||||
|
||||
record Generic<T>(@NonNull T value, @Singular List<String> tags) {
|
||||
static final String IGNORED = "not a component";
|
||||
|
||||
@Builder(toBuilder = true)
|
||||
Generic {}
|
||||
}
|
||||
|
||||
record Empty() {
|
||||
@Builder
|
||||
Empty {}
|
||||
}
|
||||
|
||||
record Canonical(String name, int count) {
|
||||
@Builder
|
||||
Canonical(String name, int count) {
|
||||
this.name = name.trim();
|
||||
this.count = count;
|
||||
}
|
||||
}
|
||||
|
||||
record Explicit(String name, int count) {
|
||||
@Builder
|
||||
Explicit(String name) { this(name, 7); }
|
||||
}
|
||||
|
||||
static class Ordinary {
|
||||
final String name;
|
||||
|
||||
@Builder
|
||||
@SneakyThrows
|
||||
Ordinary(String name) { this.name = name; }
|
||||
}
|
||||
|
||||
static class Parent {
|
||||
Parent(String name) {}
|
||||
}
|
||||
|
||||
static class ConstructorCalls extends Parent {
|
||||
final String name;
|
||||
|
||||
@SneakyThrows
|
||||
ConstructorCalls() {
|
||||
this("default");
|
||||
assert name.equals("default");
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
ConstructorCalls(@NonNull String name) {
|
||||
super(name);
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
@RequiredArgsConstructor
|
||||
static class GeneratedConstructor {
|
||||
final int initialized = 7;
|
||||
@NonNull final String name;
|
||||
}
|
||||
|
||||
@Builder(builderMethodName = "methodBuilder", builderClassName = "MethodBuilder")
|
||||
static String named(String name) { return name; }
|
||||
|
||||
public static void main(String[] args) {
|
||||
var payment = Payment.builder().number("inquiry").phone("123")
|
||||
.amount(BigDecimal.TEN).total(BigDecimal.TEN).status(Status.PENDING).build();
|
||||
assert payment.number().equals("inquiry");
|
||||
assert payment.phone().equals("123");
|
||||
assert payment.amount().equals(BigDecimal.TEN);
|
||||
assert payment.serviceCharge().equals(BigDecimal.ZERO);
|
||||
assert payment.total().equals(BigDecimal.TEN);
|
||||
assert payment.status() == Status.PENDING;
|
||||
assert payment.toBuilder().phone("456").build().phone().equals("456");
|
||||
assert Payment.builder().serviceCharge(BigDecimal.ONE).build().serviceCharge().equals(BigDecimal.ONE);
|
||||
|
||||
var constructor = ConstructorOnly.builder().withName("test").withCount(2).build();
|
||||
assert constructor.toBuilder().withCount(3).build().count() == 3;
|
||||
assert constructor.name().equals("test");
|
||||
try {
|
||||
ConstructorOnly.builder().withCount(-1).build();
|
||||
throw new AssertionError("compact constructor validation was bypassed");
|
||||
} catch (IllegalArgumentException expected) {}
|
||||
|
||||
assert TypeOnly.builder().count(2).build().count() == 3;
|
||||
assert Empty.builder().build().equals(new Empty());
|
||||
var generic = Generic.<String>builder().value("value").tag("one").build();
|
||||
assert generic.value().equals("value");
|
||||
assert generic.tags().equals(List.of("one"));
|
||||
assert generic.toBuilder().tag("two").build().tags().equals(List.of("one", "two"));
|
||||
try {
|
||||
Generic.<String>builder().build();
|
||||
throw new AssertionError("non-null check was bypassed");
|
||||
} catch (NullPointerException expected) {}
|
||||
|
||||
assert Canonical.builder().name(" test ").count(2).build().equals(new Canonical("test", 2));
|
||||
assert Explicit.builder().name("test").build().equals(new Explicit("test", 7));
|
||||
assert Ordinary.builder().name("test").build().name.equals("test");
|
||||
assert methodBuilder().name("test").build().equals("test");
|
||||
assert new ConstructorCalls().name.equals("default");
|
||||
assert new ConstructorCalls("explicit").name.equals("explicit");
|
||||
assert new GeneratedConstructor("generated").initialized == 7;
|
||||
assert new GeneratedConstructor("generated").name.equals("generated");
|
||||
try {
|
||||
new ConstructorCalls(null);
|
||||
throw new AssertionError("constructor non-null check was bypassed");
|
||||
} catch (NullPointerException expected) {}
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
"""Compile and run builder regressions with javac and the compiler shipped by JDT LS.
|
||||
|
||||
Usage: python3 java/lombok/tests/verify.py /path/to/jdtls /path/to/lombok.jar
|
||||
Requires a JDK 21+ on PATH. All generated files stay in a temporary directory.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
def main():
|
||||
home, lombok = (pathlib.Path(p).resolve() for p in sys.argv[1:3])
|
||||
ecj, = (home / "plugins").glob("org.eclipse.jdt.core.compiler.batch_*.jar")
|
||||
source = pathlib.Path(__file__).with_name("BuilderCompactConstructor.java")
|
||||
with tempfile.TemporaryDirectory(prefix="openidea-lombok-builders-") as tmp:
|
||||
for compiler in ("javac", "ecj"):
|
||||
output = pathlib.Path(tmp) / compiler
|
||||
output.mkdir()
|
||||
if compiler == "javac":
|
||||
command = ["javac", "--release", "21", "-processorpath", str(lombok)]
|
||||
else:
|
||||
command = ["java", f"-javaagent:{lombok}", "-jar", str(ecj), "-21"]
|
||||
subprocess.run(command + ["-cp", str(lombok), "-d", str(output), str(source)], check=True)
|
||||
subprocess.run(["java", "-ea", "-cp", os.pathsep.join((str(output), str(lombok))),
|
||||
"BuilderCompactConstructor"], check=True)
|
||||
print(f"{compiler}: builder regression assertions passed", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+2
-3
@@ -1,9 +1,8 @@
|
||||
import type { KnipConfig } from "knip";
|
||||
|
||||
const config: KnipConfig = {
|
||||
// Entries come from the Vite (index.html), Vitest, Playwright and package.json script plugins;
|
||||
// standalone browser fixtures are loaded by their own HTML pages.
|
||||
entry: ["e2e/*.fixture.{ts,tsx}"],
|
||||
// Entries come from the Vite (index.html), Vitest, Playwright and package.json script plugins.
|
||||
entry: ["e2e/pythonHighlight.fixture.ts"],
|
||||
project: [
|
||||
"src/**/*.{ts,tsx,css}",
|
||||
"!src/editor/core/cm/angular/parser.terms.ts",
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { KEEP, mirrorManifest, releasesToPrune } from "./cnb-mirror.ts";
|
||||
|
||||
describe("mirrorManifest", () => {
|
||||
const gh = "https://github.com/l0ng-ai/openidea/releases/download/v0.1.38";
|
||||
const manifest = {
|
||||
version: "0.1.38",
|
||||
notes: "",
|
||||
pub_date: "2026-11-06T00:00:00Z",
|
||||
platforms: {
|
||||
"darwin-aarch64": { signature: "sig-mac", url: `${gh}/OpenIDEA_aarch64.app.tar.gz` },
|
||||
"windows-x86_64-nsis": { signature: "sig-win", url: `${gh}/OpenIDEA_0.1.38_x64-setup.exe` },
|
||||
},
|
||||
};
|
||||
|
||||
it("points every bundle at the CNB release and keeps the signatures", () => {
|
||||
const cnb = "https://cnb.cool/l0ng-ai/openidea/-/releases/download/v0.1.38";
|
||||
expect(mirrorManifest(manifest, "v0.1.38")).toEqual({
|
||||
...manifest,
|
||||
platforms: {
|
||||
"darwin-aarch64": { signature: "sig-mac", url: `${cnb}/OpenIDEA_aarch64.app.tar.gz` },
|
||||
"windows-x86_64-nsis": { signature: "sig-win", url: `${cnb}/OpenIDEA_0.1.38_x64-setup.exe` },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses a manifest of another release", () => {
|
||||
expect(() => mirrorManifest(manifest, "v0.1.39")).toThrow(/darwin-aarch64/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("releasesToPrune", () => {
|
||||
const release = (n: number) => ({
|
||||
id: String(n),
|
||||
tag_name: `v0.1.${n}`,
|
||||
created_at: `2026-11-${String(n).padStart(2, "0")}T00:00:00Z`,
|
||||
});
|
||||
|
||||
it("keeps the newest releases and removes the rest", () => {
|
||||
const releases = Array.from({ length: KEEP + 3 }, (_, i) => release(i + 1)).reverse();
|
||||
expect(releasesToPrune(releases, `v0.1.${KEEP + 3}`).map((r) => r.tag_name)).toEqual([
|
||||
"v0.1.3",
|
||||
"v0.1.2",
|
||||
"v0.1.1",
|
||||
]);
|
||||
});
|
||||
|
||||
it("removes nothing within the limit, and never the release being mirrored", () => {
|
||||
expect(releasesToPrune([release(1), release(2)], "v0.1.2")).toEqual([]);
|
||||
// A rerun for an old tag: it is the oldest, but it was just uploaded.
|
||||
expect(releasesToPrune([release(1), release(2), release(3)], "v0.1.1", 2)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,159 +0,0 @@
|
||||
/**
|
||||
* Mirrors a published release to CNB (cnb.cool/l0ng-ai/openidea), where the updater's
|
||||
* CNB source reads `releases/latest/download/latest.json`:
|
||||
* `node scripts/cnb-mirror.ts <tag> <dir>` with `CNB_TOKEN` set (scopes `repo-code:r`,
|
||||
* `repo-release:rw`). `<dir>` holds the release's assets (`gh release download`) and
|
||||
* `release.json` (`gh release view --json body,isPrerelease`). Every asset is uploaded,
|
||||
* `latest.json` last and pointing at CNB, so the mirror's manifest never names a bundle it
|
||||
* lacks. Only the newest `KEEP` releases stay on CNB. Safe to rerun: uploads overwrite.
|
||||
*/
|
||||
import { openAsBlob, readFileSync, readdirSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export const CNB_REPO = "l0ng-ai/openidea";
|
||||
const GITHUB_REPO = "l0ng-ai/openidea";
|
||||
const API = `https://api.cnb.cool/${CNB_REPO}`;
|
||||
export const KEEP = 10;
|
||||
const PARALLEL = 4;
|
||||
const MANIFEST = "latest.json";
|
||||
const RELEASE_INFO = "release.json";
|
||||
|
||||
interface Manifest {
|
||||
version: string;
|
||||
notes?: string;
|
||||
pub_date?: string;
|
||||
platforms: Record<string, { signature: string; url: string }>;
|
||||
}
|
||||
|
||||
interface CnbRelease {
|
||||
id: string;
|
||||
tag_name: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/** `manifest` with each bundle URL moved from the GitHub release to the CNB one. */
|
||||
export function mirrorManifest(manifest: Manifest, tag: string): Manifest {
|
||||
const from = `https://github.com/${GITHUB_REPO}/releases/download/${tag}/`;
|
||||
const to = `https://cnb.cool/${CNB_REPO}/-/releases/download/${tag}/`;
|
||||
const platforms: Manifest["platforms"] = {};
|
||||
for (const [key, entry] of Object.entries(manifest.platforms)) {
|
||||
if (!entry.url.startsWith(from)) throw new Error(`${key}: ${entry.url} is not an asset of ${tag}`);
|
||||
platforms[key] = { ...entry, url: to + entry.url.slice(from.length) };
|
||||
}
|
||||
return { ...manifest, platforms };
|
||||
}
|
||||
|
||||
/** Releases beyond the newest `keep` (by creation time), never `current`. */
|
||||
export function releasesToPrune(releases: CnbRelease[], current: string, keep = KEEP): CnbRelease[] {
|
||||
const newest = [...releases].sort((a, b) => b.created_at.localeCompare(a.created_at));
|
||||
return newest.slice(keep).filter((r) => r.tag_name !== current);
|
||||
}
|
||||
|
||||
function token(): string {
|
||||
const value = process.env.CNB_TOKEN?.trim();
|
||||
if (!value) throw new Error("CNB_TOKEN is not set");
|
||||
return value;
|
||||
}
|
||||
|
||||
async function api<T>(method: string, path: string, body?: unknown): Promise<T | null> {
|
||||
const res = await fetch(path.startsWith("https://") ? path : API + path, {
|
||||
method,
|
||||
headers: {
|
||||
authorization: `Bearer ${token()}`,
|
||||
accept: "application/vnd.cnb.api+json",
|
||||
...(body === undefined ? {} : { "content-type": "application/json" }),
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
if (res.status === 404 && method === "GET") return null;
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw new Error(`${method} ${path}: HTTP ${res.status} ${text}`);
|
||||
return text ? (JSON.parse(text) as T) : null;
|
||||
}
|
||||
|
||||
async function withRetry<T>(what: string, run: () => Promise<T>, attempts = 3): Promise<T> {
|
||||
for (let i = 1; ; i++) {
|
||||
try {
|
||||
return await run();
|
||||
} catch (e) {
|
||||
if (i >= attempts) throw e;
|
||||
console.warn(`${what}: ${e instanceof Error ? e.message : e}; retrying (${i}/${attempts - 1})`);
|
||||
await new Promise((r) => setTimeout(r, 5000 * i));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureRelease(tag: string, body: string, prerelease: boolean): Promise<string> {
|
||||
const existing = await api<CnbRelease>("GET", `/-/releases/tags/${encodeURIComponent(tag)}`);
|
||||
if (existing) return existing.id;
|
||||
const created = await api<CnbRelease>("POST", "/-/releases", {
|
||||
tag_name: tag,
|
||||
target_commitish: "main",
|
||||
name: tag,
|
||||
body,
|
||||
prerelease,
|
||||
make_latest: prerelease ? "false" : "true",
|
||||
});
|
||||
return created!.id;
|
||||
}
|
||||
|
||||
async function upload(releaseId: string, name: string, file: Blob) {
|
||||
const target = await api<{ upload_url: string; verify_url: string }>(
|
||||
"POST",
|
||||
`/-/releases/${releaseId}/asset-upload-url`,
|
||||
{ asset_name: name, size: file.size, overwrite: true },
|
||||
);
|
||||
const put = await fetch(target!.upload_url, { method: "PUT", body: file });
|
||||
if (!put.ok) throw new Error(`PUT ${name}: HTTP ${put.status} ${await put.text()}`);
|
||||
await api("POST", target!.verify_url);
|
||||
}
|
||||
|
||||
async function uploadAll(releaseId: string, dir: string, names: string[]) {
|
||||
const queue = [...names];
|
||||
const worker = async () => {
|
||||
for (let name = queue.shift(); name; name = queue.shift()) {
|
||||
const path = join(dir, name);
|
||||
const mb = (statSync(path).size / 1048576).toFixed(1);
|
||||
const started = Date.now();
|
||||
await withRetry(name, async () => upload(releaseId, name, await openAsBlob(path)));
|
||||
console.log(`uploaded ${name} (${mb} MB, ${Math.round((Date.now() - started) / 1000)} s)`);
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: PARALLEL }, worker));
|
||||
}
|
||||
|
||||
async function prune(current: string) {
|
||||
const releases = (await api<CnbRelease[]>("GET", "/-/releases?page_size=100")) ?? [];
|
||||
for (const old of releasesToPrune(releases, current)) {
|
||||
await api("DELETE", `/-/releases/${old.id}`);
|
||||
await api("DELETE", `/-/git/tags/${encodeURIComponent(old.tag_name)}`).catch((e) => console.warn(String(e)));
|
||||
console.log(`removed ${old.tag_name}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const [tag, dir] = process.argv.slice(2);
|
||||
if (!tag || !dir) throw new Error("usage: node scripts/cnb-mirror.ts <tag> <dir>");
|
||||
const info = JSON.parse(readFileSync(join(dir, RELEASE_INFO), "utf8")) as { body?: string; isPrerelease?: boolean };
|
||||
const manifest = JSON.parse(readFileSync(join(dir, MANIFEST), "utf8")) as Manifest;
|
||||
const mirrored = mirrorManifest(manifest, tag);
|
||||
const assets = readdirSync(dir).filter(
|
||||
(n) => n !== MANIFEST && n !== RELEASE_INFO && statSync(join(dir, n)).isFile(),
|
||||
);
|
||||
|
||||
const releaseId = await ensureRelease(tag, info.body ?? "", !!info.isPrerelease);
|
||||
console.log(`CNB release ${tag} (${releaseId}): uploading ${assets.length} assets`);
|
||||
await uploadAll(releaseId, dir, assets);
|
||||
const blob = new Blob([JSON.stringify(mirrored, null, 2)], { type: "application/json" });
|
||||
await withRetry(MANIFEST, () => upload(releaseId, MANIFEST, blob));
|
||||
console.log(`uploaded ${MANIFEST}: ${Object.keys(mirrored.platforms).length} platforms`);
|
||||
await prune(tag);
|
||||
}
|
||||
|
||||
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
|
||||
main().catch((e) => {
|
||||
console.error(e instanceof Error ? e.message : e);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -82,7 +82,8 @@ block2 = "0.6"
|
||||
# Plugin secrets in the login keychain.
|
||||
security-framework = "3.7"
|
||||
objc2 = "0.6"
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSEvent", "NSResponder", "NSScreen", "NSToolbar", "NSView", "NSWindow"] }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSButton", "NSEvent", "NSResponder", "NSScreen", "NSView", "NSWindow"] }
|
||||
objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "CFRunLoop"] }
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] }
|
||||
# Used only by the debug font-restriction override; Cargo dependency cfg cannot test debug_assertions.
|
||||
objc2-web-kit = { version = "0.3", default-features = false, features = ["std", "WKWebViewConfiguration", "WKPreferences"] }
|
||||
|
||||
@@ -278,12 +278,8 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
vcs::vcs_checkout,
|
||||
vcs::vcs_delete_branch,
|
||||
vcs::vcs_restore_branch,
|
||||
vcs::vcs_delete_tag,
|
||||
vcs::vcs_restore_tag,
|
||||
vcs::vcs_create_branch,
|
||||
vcs::vcs_undo_commit,
|
||||
vcs::vcs_reword,
|
||||
vcs::vcs_restore_head,
|
||||
vcs::vcs_rename_branch,
|
||||
vcs::vcs_merge,
|
||||
vcs::vcs_rebase,
|
||||
@@ -315,7 +311,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
vcs::vcs_compare_paths,
|
||||
vcs::vcs_diff_revisions,
|
||||
vcs::vcs_diff_numstat,
|
||||
vcs::vcs_has_hook,
|
||||
vcs::vcs_merge_base,
|
||||
vcs::vcs_create_patch,
|
||||
vcs::vcs_patch_preview,
|
||||
|
||||
@@ -285,33 +285,6 @@ pub async fn vcs_undo_commit(
|
||||
ide_host::ops::vcs::vcs_undo_commit(&state.host, window.label(), repo, commit).await
|
||||
}
|
||||
|
||||
/// Edit Commit Message: rewrites the commit and its descendants without touching the
|
||||
/// working tree.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_reword(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
commit: String,
|
||||
message: String,
|
||||
) -> IdeResult<ide_vcs::HeadChange> {
|
||||
ide_host::ops::vcs::vcs_reword(&state.host, window.label(), repo, commit, message).await
|
||||
}
|
||||
|
||||
/// Undo of a history rewrite (Edit Commit Message, Drop, Squash).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_restore_head(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
before: String,
|
||||
after: String,
|
||||
) -> IdeResult<()> {
|
||||
ide_host::ops::vcs::vcs_restore_head(&state.host, window.label(), repo, before, after).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_delete_branch(
|
||||
@@ -323,30 +296,6 @@ pub async fn vcs_delete_branch(
|
||||
ide_host::ops::vcs::vcs_delete_branch(&state.host, window.label(), repo, branch).await
|
||||
}
|
||||
|
||||
/// Tag › Delete: the result is what "Restore" needs.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_delete_tag(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
name: String,
|
||||
) -> IdeResult<ide_vcs::DeletedTag> {
|
||||
ide_host::ops::vcs::vcs_delete_tag(&state.host, window.label(), repo, name).await
|
||||
}
|
||||
|
||||
/// "Restore" of the tag-deleted notification.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_restore_tag(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
deleted: ide_vcs::DeletedTag,
|
||||
) -> IdeResult<()> {
|
||||
ide_host::ops::vcs::vcs_restore_tag(&state.host, window.label(), repo, deleted).await
|
||||
}
|
||||
|
||||
/// "Restore" of the branch-deleted notification.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
@@ -697,18 +646,6 @@ pub async fn vcs_diff_numstat(
|
||||
ide_host::ops::vcs::vcs_diff_numstat(&state.host, window.label(), repo, from, to, paths).await
|
||||
}
|
||||
|
||||
/// Whether the repository has the executable Git hook `name` (Push dialog › Run Git hooks).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_has_hook(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
name: String,
|
||||
) -> IdeResult<bool> {
|
||||
ide_host::ops::vcs::vcs_has_hook(&state.host, window.label(), repo, name).await
|
||||
}
|
||||
|
||||
/// The best common ancestor of `a` and `b` (`git merge-base`), if any.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
|
||||
@@ -330,74 +330,36 @@ fn update_endpoint_env() -> Option<String> {
|
||||
/// tauri.conf.json, or the `OPENIDEA_UPDATE_ENDPOINT` environment variable. Empty by
|
||||
/// default, and "Check for Updates…" is hidden then.
|
||||
pub fn updates_configured<R: tauri::Runtime>(app: &AppHandle<R>) -> bool {
|
||||
!config_endpoints(app).is_empty() || update_endpoint_env().is_some()
|
||||
}
|
||||
|
||||
/// Where updates are downloaded from (System Settings › Updates).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum UpdateSource {
|
||||
/// The GitHub releases named in tauri.conf.json.
|
||||
#[default]
|
||||
Github,
|
||||
/// The CNB mirror of the same releases, for networks where GitHub is slow.
|
||||
Cnb,
|
||||
}
|
||||
|
||||
const CNB_ENDPOINT: &str = "https://cnb.cool/l0ng-ai/openidea/-/releases/latest/download/latest.json";
|
||||
|
||||
fn config_endpoints<R: tauri::Runtime>(app: &AppHandle<R>) -> Vec<String> {
|
||||
app.config()
|
||||
let in_config = app
|
||||
.config()
|
||||
.plugins
|
||||
.0
|
||||
.get("updater")
|
||||
.and_then(|u| u.get("endpoints"))
|
||||
.and_then(|e| e.as_array())
|
||||
.map(|e| e.iter().filter_map(|u| u.as_str().map(String::from)).collect())
|
||||
.unwrap_or_default()
|
||||
.is_some_and(|e| !e.is_empty());
|
||||
in_config || update_endpoint_env().is_some()
|
||||
}
|
||||
|
||||
/// The endpoints tried in order: `source` first, the other source when it fails or has
|
||||
/// no manifest. Bundles are signed, so either source's manifest and downloads verify.
|
||||
/// No official endpoint (a build without updates) means no mirror either.
|
||||
fn source_endpoints(official: Vec<String>, source: UpdateSource) -> Vec<String> {
|
||||
if official.is_empty() {
|
||||
return official;
|
||||
}
|
||||
let mirror = vec![CNB_ENDPOINT.to_string()];
|
||||
match source {
|
||||
UpdateSource::Github => [official, mirror].concat(),
|
||||
UpdateSource::Cnb => [mirror, official].concat(),
|
||||
}
|
||||
}
|
||||
|
||||
fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plugin_updater::Updater>> {
|
||||
fn updater(app: &AppHandle) -> IdeResult<Option<tauri_plugin_updater::Updater>> {
|
||||
use tauri_plugin_updater::UpdaterExt;
|
||||
if !updates_configured(app) {
|
||||
return Ok(None);
|
||||
}
|
||||
let endpoints = match update_endpoint_env() {
|
||||
Some(url) => vec![url],
|
||||
None => source_endpoints(config_endpoints(app), source),
|
||||
};
|
||||
let endpoints = endpoints
|
||||
.iter()
|
||||
.map(|u| u.parse().map_err(|e| IdeError::invalid(format!("update endpoint {u}: {e}"))))
|
||||
.collect::<IdeResult<Vec<_>>>()?;
|
||||
let env = update_endpoint_env();
|
||||
let proxy = ide_core::proxy_settings::proxy();
|
||||
app.updater_builder()
|
||||
.configure_client(move |b| ide_http::client::with_proxy(b, &proxy))
|
||||
.endpoints(endpoints)
|
||||
.map_err(|e| IdeError::invalid(e.to_string()))?
|
||||
.build()
|
||||
.map(Some)
|
||||
.map_err(|e| IdeError::unavailable(e.to_string()))
|
||||
let mut builder = app.updater_builder().configure_client(move |b| ide_http::client::with_proxy(b, &proxy));
|
||||
if let Some(url) = env {
|
||||
let url = url.parse().map_err(|e| IdeError::invalid(format!("OPENIDEA_UPDATE_ENDPOINT: {e}")))?;
|
||||
builder = builder.endpoints(vec![url]).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
}
|
||||
builder.build().map(Some).map_err(|e| IdeError::unavailable(e.to_string()))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn app_check_update(app: AppHandle, source: UpdateSource) -> IdeResult<UpdateCheck> {
|
||||
let Some(updater) = updater(&app, source)? else {
|
||||
pub async fn app_check_update(app: AppHandle) -> IdeResult<UpdateCheck> {
|
||||
let Some(updater) = updater(&app)? else {
|
||||
return Ok(UpdateCheck { enabled: false, update: None });
|
||||
};
|
||||
let update = updater.check().await.map_err(|e| IdeError::unavailable(e.to_string()))?;
|
||||
@@ -417,12 +379,12 @@ pub async fn app_check_update(app: AppHandle, source: UpdateSource) -> IdeResult
|
||||
/// not reported: the user didn't ask for this check.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn app_startup_update_check(app: AppHandle, source: UpdateSource) -> Option<UpdateInfo> {
|
||||
pub async fn app_startup_update_check(app: AppHandle) -> Option<UpdateInfo> {
|
||||
static DONE: AtomicBool = AtomicBool::new(false);
|
||||
if cfg!(debug_assertions) || DONE.swap(true, Ordering::SeqCst) {
|
||||
return None;
|
||||
}
|
||||
match app_check_update(app, source).await {
|
||||
match app_check_update(app).await {
|
||||
Ok(check) => check.update,
|
||||
Err(e) => {
|
||||
tracing::warn!("startup update check failed: {e}");
|
||||
@@ -490,7 +452,6 @@ impl Drop for InstallingGuard {
|
||||
pub async fn app_install_update(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
source: UpdateSource,
|
||||
request: RequestId,
|
||||
on_progress: Channel<UpdateProgress>,
|
||||
) -> IdeResult<()> {
|
||||
@@ -498,7 +459,7 @@ pub async fn app_install_update(
|
||||
InstallingGuard::acquire().ok_or_else(|| IdeError::unavailable("an update is already being installed"))?;
|
||||
let token = state.host.begin_request(request);
|
||||
let result = async {
|
||||
let updater = updater(&app, source)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?;
|
||||
let updater = updater(&app)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?;
|
||||
let update = tokio::select! {
|
||||
r = updater.check() => r.map_err(|e| IdeError::unavailable(e.to_string()))?,
|
||||
_ = token.cancelled() => return Err(IdeError::cancelled()),
|
||||
@@ -561,15 +522,6 @@ mod tests {
|
||||
assert!(ProgressThrottle::default().chunk(1, Some(0)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chosen_source_is_tried_first_and_the_other_after_it() {
|
||||
let github = "https://github.com/l0ng-ai/openidea/releases/latest/download/latest.json".to_string();
|
||||
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Github), [github.clone(), CNB_ENDPOINT.into()]);
|
||||
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Cnb), [CNB_ENDPOINT.into(), github]);
|
||||
// A build without an update endpoint stays without one.
|
||||
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_one_install_at_a_time() {
|
||||
let first = InstallingGuard::acquire().expect("first install starts");
|
||||
|
||||
@@ -200,6 +200,7 @@ pub fn run() {
|
||||
tauri::WindowEvent::Destroyed => {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
titlebar::forget(window);
|
||||
macos::forget_fullscreen(window.label());
|
||||
}
|
||||
if windows::auxiliary_parent(window.label()).is_none() {
|
||||
|
||||
@@ -1,30 +1,106 @@
|
||||
//! Size the native title bar around the window buttons to match the web toolbar.
|
||||
//!
|
||||
//! An empty unified toolbar makes AppKit lay out and vertically centre the buttons itself, so
|
||||
//! nothing moves them behind its back and they stay still during live resize.
|
||||
//! Keep the native window buttons aligned with the web toolbar, in AppKit points.
|
||||
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2_app_kit::{NSToolbar, NSWindow, NSWindowToolbarStyle};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// Unified compact (38pt) and unified (52pt) toolbars; pick the one closer to the web bar.
|
||||
const COMPACT_MAX_HEIGHT: f64 = 45.0;
|
||||
use block2::RcBlock;
|
||||
use objc2_app_kit::{NSWindow, NSWindowButton, NSWindowStyleMask};
|
||||
use objc2_core_foundation::{
|
||||
CFIndex, CFOptionFlags, CFRetained, CFRunLoop, CFRunLoopActivity, CFRunLoopObserver, kCFRunLoopCommonModes,
|
||||
};
|
||||
use objc2_foundation::NSPoint;
|
||||
|
||||
/// AppKit lays out the title bar in a run loop observer and puts the buttons back at their
|
||||
/// defaults on resize, title changes and fullscreen exit. Core Animation commits at 2000000, so
|
||||
/// correcting the frames just before it keeps AppKit's positions off screen.
|
||||
const BEFORE_COMMIT: CFIndex = 1_999_999;
|
||||
|
||||
struct Titlebar {
|
||||
height: Rc<Cell<f64>>,
|
||||
spacing: f64,
|
||||
observer: CFRetained<CFRunLoopObserver>,
|
||||
}
|
||||
|
||||
impl Drop for Titlebar {
|
||||
fn drop(&mut self) {
|
||||
self.observer.invalidate();
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static TITLEBARS: RefCell<HashMap<String, Titlebar>> = RefCell::default();
|
||||
}
|
||||
|
||||
pub fn set_height(window: &tauri::WebviewWindow, height: f64) -> tauri::Result<()> {
|
||||
// with_webview runs on the AppKit thread.
|
||||
let label = window.label().to_owned();
|
||||
// with_webview runs on the AppKit thread; the observer is also delivered there.
|
||||
window.with_webview(move |webview| unsafe {
|
||||
let Some(mtm) = MainThreadMarker::new() else { return };
|
||||
let native = &*webview.ns_window().cast::<NSWindow>();
|
||||
if native.toolbar().is_none() {
|
||||
let toolbar = NSToolbar::new(mtm);
|
||||
native.setToolbar(Some(&toolbar));
|
||||
}
|
||||
let style = if height < COMPACT_MAX_HEIGHT {
|
||||
NSWindowToolbarStyle::UnifiedCompact
|
||||
} else {
|
||||
NSWindowToolbarStyle::Unified
|
||||
};
|
||||
if native.toolbarStyle() != style {
|
||||
native.setToolbarStyle(style);
|
||||
}
|
||||
let Some(close) = native.standardWindowButton(NSWindowButton::CloseButton) else { return };
|
||||
let Some(minimize) = native.standardWindowButton(NSWindowButton::MiniaturizeButton) else { return };
|
||||
let Some(run_loop) = CFRunLoop::main() else { return };
|
||||
let spacing = minimize.frame().origin.x - close.frame().origin.x;
|
||||
TITLEBARS.with_borrow_mut(|bars| {
|
||||
if let Some(bar) = bars.get(&label) {
|
||||
bar.height.set(height);
|
||||
center_buttons(native, height, bar.spacing);
|
||||
return;
|
||||
}
|
||||
let shared = Rc::new(Cell::new(height));
|
||||
let current = shared.clone();
|
||||
let pointer = native as *const NSWindow;
|
||||
let block = RcBlock::new(move |_: *mut CFRunLoopObserver, _: CFRunLoopActivity| {
|
||||
center_buttons(&*pointer, current.get(), spacing)
|
||||
});
|
||||
let activities = CFRunLoopActivity::BeforeWaiting.0 as CFOptionFlags;
|
||||
let Some(observer) = CFRunLoopObserver::with_handler(None, activities, true, BEFORE_COMMIT, Some(&block))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
run_loop.add_observer(Some(&observer), kCFRunLoopCommonModes);
|
||||
center_buttons(native, height, spacing);
|
||||
bars.insert(label, Titlebar { height: shared, spacing, observer });
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
pub fn forget(window: &tauri::Window) {
|
||||
let label = window.label().to_owned();
|
||||
let _ = window.run_on_main_thread(move || {
|
||||
TITLEBARS.with_borrow_mut(|bars| bars.remove(&label));
|
||||
});
|
||||
}
|
||||
|
||||
unsafe fn center_buttons(window: &NSWindow, height: f64, spacing: f64) {
|
||||
// Fullscreen uses AppKit's own revealable title bar.
|
||||
if window.styleMask().contains(NSWindowStyleMask::FullScreen) {
|
||||
return;
|
||||
}
|
||||
let Some(close) = window.standardWindowButton(NSWindowButton::CloseButton) else { return };
|
||||
let Some(container) = (unsafe { close.superview().and_then(|view| view.superview()) }) else { return };
|
||||
let Some(content) = window.contentView() else { return };
|
||||
let mut frame = container.frame();
|
||||
let top = frame.origin.y + frame.size.height;
|
||||
if (frame.size.height - height).abs() > 0.01 {
|
||||
frame.size.height = height;
|
||||
frame.origin.y = top - height;
|
||||
container.setFrame(frame);
|
||||
}
|
||||
let bounds = content.bounds();
|
||||
let y = bounds.origin.y + if content.isFlipped() { height / 2.0 } else { bounds.size.height - height / 2.0 };
|
||||
for (index, kind) in [NSWindowButton::CloseButton, NSWindowButton::MiniaturizeButton, NSWindowButton::ZoomButton]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let Some(button) = window.standardWindowButton(kind) else { continue };
|
||||
let Some(parent) = (unsafe { button.superview() }) else { continue };
|
||||
let center = parent.convertPoint_fromView(NSPoint::new(0.0, y), Some(&content));
|
||||
let frame = button.frame();
|
||||
let x = 14.0 + index as f64 * spacing;
|
||||
let target = center.y - frame.size.height / 2.0;
|
||||
if (frame.origin.x - x).abs() > 0.01 || (frame.origin.y - target).abs() > 0.01 {
|
||||
button.setFrameOrigin(NSPoint::new(x, target));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; img-src 'self' asset: data: blob: http: https:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src ipc: http://ipc.localhost; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:; frame-src http://127.0.0.1:* openidea-plugin: http://openidea-plugin.localhost"
|
||||
"csp": "default-src 'self'; img-src 'self' asset: data: blob: https://avatars.githubusercontent.com; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src ipc: http://ipc.localhost; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:; frame-src http://127.0.0.1:* openidea-plugin: http://openidea-plugin.localhost"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
|
||||
+10
-65
@@ -523,10 +523,6 @@ export const commands = {
|
||||
vcsDeleteBranch: (repo: string | null, branch: string) => typedError<DeletedBranch, IdeError>(__TAURI_INVOKE("vcs_delete_branch", { repo, branch })),
|
||||
/** "Restore" of the branch-deleted notification. */
|
||||
vcsRestoreBranch: (repo: string | null, deleted: DeletedBranch) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_restore_branch", { repo, deleted })),
|
||||
/** Tag › Delete: the result is what "Restore" needs. */
|
||||
vcsDeleteTag: (repo: string | null, name: string) => typedError<DeletedTag, IdeError>(__TAURI_INVOKE("vcs_delete_tag", { repo, name })),
|
||||
/** "Restore" of the tag-deleted notification. */
|
||||
vcsRestoreTag: (repo: string | null, deleted: DeletedTag) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_restore_tag", { repo, deleted })),
|
||||
/** New Branch: creates `name` at `start` (HEAD when absent), optionally checking it out. */
|
||||
vcsCreateBranch: (repo: string | null, name: string, start: string | null, checkout: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_create_branch", { repo, name, start, checkout })),
|
||||
/**
|
||||
@@ -534,13 +530,6 @@ export const commands = {
|
||||
* Returns the undone commit's message.
|
||||
*/
|
||||
vcsUndoCommit: (repo: string | null, commit: string) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_undo_commit", { repo, commit })),
|
||||
/**
|
||||
* Edit Commit Message: rewrites the commit and its descendants without touching the
|
||||
* working tree.
|
||||
*/
|
||||
vcsReword: (repo: string | null, commit: string, message: string) => typedError<HeadChange, IdeError>(__TAURI_INVOKE("vcs_reword", { repo, commit, message })),
|
||||
/** Undo of a history rewrite (Edit Commit Message, Drop, Squash). */
|
||||
vcsRestoreHead: (repo: string | null, before: string, after: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_restore_head", { repo, before, after })),
|
||||
vcsRenameBranch: (repo: string | null, from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rename_branch", { repo, from, to })),
|
||||
vcsMerge: (repo: string | null, branch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_merge", { repo, branch })),
|
||||
vcsRebase: (repo: string | null, onto: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_rebase", { repo, onto })),
|
||||
@@ -599,8 +588,6 @@ export const commands = {
|
||||
* `paths` limits the diff to those repository-relative paths; empty diffs every file.
|
||||
*/
|
||||
vcsDiffNumstat: (repo: string | null, from: string, to: string, paths: string[]) => typedError<FileLineStats[], IdeError>(__TAURI_INVOKE("vcs_diff_numstat", { repo, from, to, paths })),
|
||||
/** Whether the repository has the executable Git hook `name` (Push dialog › Run Git hooks). */
|
||||
vcsHasHook: (repo: string | null, name: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("vcs_has_hook", { repo, name })),
|
||||
/** The best common ancestor of `a` and `b` (`git merge-base`), if any. */
|
||||
vcsMergeBase: (repo: string | null, a: string, b: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("vcs_merge_base", { repo, a, b })),
|
||||
vcsCreatePatch: (repo: string | null, source: PatchSource) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_create_patch", { repo, source })),
|
||||
@@ -910,24 +897,24 @@ export const commands = {
|
||||
menuSetDisabled: (ids: string[]) => __TAURI_INVOKE<void>("menu_set_disabled", { ids }),
|
||||
appLogLocation: () => typedError<LogLocation, IdeError>(__TAURI_INVOKE("app_log_location")),
|
||||
appBuildInfo: () => __TAURI_INVOKE<BuildInfo>("app_build_info"),
|
||||
appCheckUpdate: (source: UpdateSource) => typedError<UpdateCheck, IdeError>(__TAURI_INVOKE("app_check_update", { source })),
|
||||
appCheckUpdate: () => typedError<UpdateCheck, IdeError>(__TAURI_INVOKE("app_check_update")),
|
||||
/**
|
||||
* The background check made once per process when the first window starts;
|
||||
* later calls (other windows) and debug builds get `None`. Failures are logged,
|
||||
* not reported: the user didn't ask for this check.
|
||||
*/
|
||||
appStartupUpdateCheck: (source: UpdateSource) => __TAURI_INVOKE<{
|
||||
appStartupUpdateCheck: () => __TAURI_INVOKE<{
|
||||
version: string,
|
||||
currentVersion: string,
|
||||
notes: string | null,
|
||||
date: string | null,
|
||||
} | null>("app_startup_update_check", { source }),
|
||||
} | null>("app_startup_update_check"),
|
||||
/**
|
||||
* Downloads and installs the available update, streaming progress to `on_progress`.
|
||||
* Cancellable through `request` until the download completes; the UI then restarts
|
||||
* with `app_restart`. One install runs at a time.
|
||||
*/
|
||||
appInstallUpdate: (source: UpdateSource, request: RequestId, onProgress: Channel<UpdateProgress>) => typedError<null, IdeError>(__TAURI_INVOKE("app_install_update", { source, request, onProgress })),
|
||||
appInstallUpdate: (request: RequestId, onProgress: Channel<UpdateProgress>) => typedError<null, IdeError>(__TAURI_INVOKE("app_install_update", { request, onProgress })),
|
||||
debugExceptionFilters: () => typedError<SessionExceptionFilters[], IdeError>(__TAURI_INVOKE("debug_exception_filters")),
|
||||
debugSetExceptionBreakpoints: (choices: { [key in string]: boolean }) => typedError<null, IdeError>(__TAURI_INVOKE("debug_set_exception_breakpoints", { choices })),
|
||||
debugSetVariable: (session: DebugSessionId, container: number, name: string, evaluateName: string | null, frameId: number | null, value: string) => typedError<Variable, IdeError>(__TAURI_INVOKE("debug_set_variable", { session, container, name, evaluateName, frameId, value })),
|
||||
@@ -2094,8 +2081,6 @@ export type CheckoutOptions = {
|
||||
export type CheckoutOutcome = { kind: "done" } |
|
||||
/** These local changes (repository-relative paths) would be overwritten. */
|
||||
{ kind: "localChanges"; files: string[] } |
|
||||
/** These untracked files (repository-relative paths) would be overwritten. */
|
||||
{ kind: "untrackedFiles"; files: string[] } |
|
||||
/** Local branch `local` has commits that remote branch `remote` does not. */
|
||||
{ kind: "localBranchAhead"; local: string; remote: string } |
|
||||
/**
|
||||
@@ -2240,10 +2225,6 @@ export type CommitOptions = {
|
||||
* entries of the index change; afterwards their index entries match the new commit.
|
||||
*/
|
||||
partial?: PartialCommitFile[],
|
||||
/** Files committed with their working-tree content, staged or not. */
|
||||
stage?: IpcPath[],
|
||||
/** Staged files left out of the commit; they stay staged afterwards. */
|
||||
exclude?: IpcPath[],
|
||||
};
|
||||
|
||||
/** Version Control › Commit: commit checks and commit-message inspections. */
|
||||
@@ -2940,13 +2921,6 @@ export type DeletedBranch = {
|
||||
unmerged: boolean,
|
||||
};
|
||||
|
||||
/** A deleted tag, enough to restore it (Restore in the tag-deleted notification). */
|
||||
export type DeletedTag = {
|
||||
name: string,
|
||||
/** What the tag pointed at: its tag object (annotated tags) or commit. */
|
||||
target: string,
|
||||
};
|
||||
|
||||
export type DependencyUpdate = {
|
||||
latest: string,
|
||||
replacement: string,
|
||||
@@ -3866,8 +3840,6 @@ export type GeneralSettings = {
|
||||
powerSaveMode?: boolean,
|
||||
/** File › Rename Project… (project layer): the name shown for the project; empty = its folder name. */
|
||||
projectName?: string,
|
||||
/** Where updates come from: `auto` (the CNB mirror for the Chinese UI, else GitHub) | `github` | `cnb`. */
|
||||
updateSource?: string,
|
||||
};
|
||||
|
||||
/** A repository of the signed-in account (owned, collaborator, or organization member). */
|
||||
@@ -3937,11 +3909,9 @@ export type GitExecutableInfo = {
|
||||
|
||||
export type GitOperation =
|
||||
/** Continue the merge / rebase / cherry-pick / revert in progress. */
|
||||
{ op: "continue" } |
|
||||
/** Stage and Retry: stage the changes of tracked files, then continue. */
|
||||
{ op: "stageAndContinue" } | { op: "abort" } | { op: "skip" } |
|
||||
/** Commits oldest first; `record_origin` adds "(cherry picked from commit …)". */
|
||||
{ op: "cherryPick"; commits: string[]; recordOrigin?: boolean } |
|
||||
{ op: "continue" } | { op: "abort" } | { op: "skip" } |
|
||||
/** Commits oldest first. */
|
||||
{ op: "cherryPick"; commits: string[] } |
|
||||
/** Commits newest first. */
|
||||
{ op: "revert"; commits: string[] } | { op: "reset"; commit: string; mode: ResetMode } |
|
||||
/** Rebases `base..HEAD` (`base: None` = from the root) following `entries`, oldest first. */
|
||||
@@ -4092,12 +4062,6 @@ export type GradleTask = {
|
||||
description: string | null,
|
||||
};
|
||||
|
||||
/** HEAD before and after a history rewrite, for its Undo. */
|
||||
export type HeadChange = {
|
||||
before: string,
|
||||
after: string,
|
||||
};
|
||||
|
||||
export type HierarchyChoice = {
|
||||
id: string,
|
||||
makeAbstract: boolean,
|
||||
@@ -6253,15 +6217,9 @@ export type RemoteLaunch = {
|
||||
path: string,
|
||||
};
|
||||
|
||||
export type RemoteOp = { op: "fetch" } | { op: "pull"; rebase: boolean } |
|
||||
/** Update Project › Reset to the Remote Branch. */
|
||||
{ op: "resetToUpstream" } | { op: "push"; force_with_lease: boolean; set_upstream: boolean;
|
||||
export type RemoteOp = { op: "fetch" } | { op: "pull"; rebase: boolean } | { op: "push"; force_with_lease: boolean; set_upstream: boolean;
|
||||
/** Push dialog › Push tags. */
|
||||
tags?: PushTags | null;
|
||||
/** Plain `--force` (Force push anyway). */
|
||||
force?: boolean;
|
||||
/** Push dialog › Run Git hooks unchecked (`--no-verify`). */
|
||||
no_verify?: boolean } |
|
||||
tags?: PushTags | null } |
|
||||
/** Deletes a remote branch; `branch` is the remote-tracking name (`origin/feature`). */
|
||||
{ op: "deleteBranch"; branch: string } |
|
||||
/**
|
||||
@@ -6269,13 +6227,7 @@ no_verify?: boolean } |
|
||||
* remote branch `target`; `remote` overrides the upstream's remote (Push dialog's
|
||||
* remote picker).
|
||||
*/
|
||||
{ op: "pushBranch"; branch: string; revision: string | null; force_with_lease: boolean; target?: string | null; remote?: string | null; force?: boolean;
|
||||
/** Record the target as upstream (Push dialog › Set upstream). */
|
||||
set_upstream?: boolean; no_verify?: boolean } |
|
||||
/** Push Tag › Push to `remote`. */
|
||||
{ op: "pushTag"; tag: string; remote: string } |
|
||||
/** Deletes tag `tag` on `remote` (Delete on Remote). */
|
||||
{ op: "deleteRemoteTag"; tag: string; remote: string } |
|
||||
{ op: "pushBranch"; branch: string; revision: string | null; force_with_lease: boolean; target?: string | null; remote?: string | null } |
|
||||
/** Fast-forwards local `branch` (not checked out) to its upstream. */
|
||||
{ op: "updateBranch"; branch: string } |
|
||||
/** Pull dialog: `branches` of `remote` (none = the configured merge branch). */
|
||||
@@ -7600,13 +7552,6 @@ export type UpdateProgress =
|
||||
/** Download done; the new version is being written over this one. */
|
||||
{ type: "installing" };
|
||||
|
||||
/** Where updates are downloaded from (System Settings › Updates). */
|
||||
export type UpdateSource =
|
||||
/** The GitHub releases named in tauri.conf.json. */
|
||||
"github" |
|
||||
/** The CNB mirror of the same releases, for networks where GitHub is slow. */
|
||||
"cnb";
|
||||
|
||||
export type Variable = {
|
||||
name: string,
|
||||
value: string,
|
||||
|
||||
@@ -1,218 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { commands, Location } from "@/platform/ipc";
|
||||
|
||||
const lspGoto = vi.hoisted(() => vi.fn<typeof commands.lspGoto>());
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const real = await orig<typeof import("@/platform/ipc")>();
|
||||
return { ...real, isTauri: () => true, commands: { ...real.commands, lspGoto } };
|
||||
});
|
||||
const { emitLocalIdeEvent } = await import("@/platform/ipc");
|
||||
const { _emitEditorEvent } = await import("@/editor/api");
|
||||
const { lspDoc } = await import("./lsp");
|
||||
const { navigationExtension } = await import("./navigation");
|
||||
const { requestNavigation, invalidateConfigurationNavigation, installConfigurationNavigationEvents, navigationWord } =
|
||||
await import("./configurationNavigation");
|
||||
|
||||
const target: Location = {
|
||||
path: "/p/Config.java",
|
||||
uri: null,
|
||||
range: { start: { line: 3, col: 4 }, end: { line: 3, col: 9 } },
|
||||
};
|
||||
const views: EditorView[] = [];
|
||||
function editor(doc = 1, language = "yaml", text = "server:\n port: 8080\n") {
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: text,
|
||||
extensions: [
|
||||
lspDoc.of({ doc, path: `/p/${doc}.${language}`, language, uiMode: language, readOnly: false }),
|
||||
navigationExtension(),
|
||||
],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
return view;
|
||||
}
|
||||
let off: () => void;
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
invalidateConfigurationNavigation();
|
||||
lspGoto.mockReset().mockResolvedValue({ status: "ok", data: [target] });
|
||||
off = installConfigurationNavigationEvents();
|
||||
});
|
||||
afterEach(() => {
|
||||
off();
|
||||
views.splice(0).forEach((v) => v.destroy());
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("configuration navigation result reuse", () => {
|
||||
it.each(["yaml", "properties"])("%s names include separators but exclude syntax and adjacent values", (language) => {
|
||||
const view = editor(1, language, ' "spring.datasource.driver-class-name": example.Driver');
|
||||
for (const offset of [3, 9, 20, 26, 32, 35]) {
|
||||
const range = navigationWord(view, offset)!;
|
||||
expect(view.state.sliceDoc(range.from, range.to)).toBe("spring.datasource.driver-class-name");
|
||||
}
|
||||
expect(navigationWord(view, 1)).toBeNull();
|
||||
expect(navigationWord(view, 39)).toBeNull();
|
||||
});
|
||||
|
||||
it("shares an in-flight hover lookup with a click anywhere in the same key", async () => {
|
||||
let resolve!: (r: Awaited<ReturnType<typeof commands.lspGoto>>) => void;
|
||||
lspGoto.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((r) => {
|
||||
resolve = r;
|
||||
}),
|
||||
);
|
||||
const view = editor();
|
||||
const hover = requestNavigation(view, 10, "definition");
|
||||
const click = requestNavigation(view, 12, "definition");
|
||||
expect(click).toBe(hover);
|
||||
await vi.waitFor(() => expect(lspGoto).toHaveBeenCalledOnce());
|
||||
resolve({ status: "ok", data: [target] });
|
||||
expect(await click).toEqual([target]);
|
||||
expect(await requestNavigation(view, 11, "definition")).toEqual([target]);
|
||||
expect(lspGoto).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("reuses results when the same document is shown again", async () => {
|
||||
const view = editor();
|
||||
await requestNavigation(view, 10, "definition");
|
||||
await requestNavigation(editor(), 11, "definition");
|
||||
expect(lspGoto).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("keeps different keys and documents separate", async () => {
|
||||
const view = editor();
|
||||
await requestNavigation(view, 1, "definition");
|
||||
await requestNavigation(view, 10, "definition");
|
||||
await requestNavigation(editor(2), 10, "definition");
|
||||
expect(lspGoto).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it.each(["java", "typescript"])("leaves %s native navigation uncached", async (language) => {
|
||||
const view = editor(1, language, "value");
|
||||
await requestNavigation(view, 1, "definition");
|
||||
await requestNavigation(view, 1, "definition");
|
||||
expect(lspGoto).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not mix definition with other navigation kinds", async () => {
|
||||
const view = editor();
|
||||
await requestNavigation(view, 10, "definition");
|
||||
await requestNavigation(view, 10, "typeDefinition");
|
||||
expect(lspGoto).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("invalidates on edits to another open Java document, before its IPC sync", async () => {
|
||||
const view = editor();
|
||||
const java = editor(2, "java", "class Config {}");
|
||||
await requestNavigation(view, 10, "definition");
|
||||
java.dispatch({ changes: { from: 6, to: 12, insert: "Changed" } });
|
||||
await requestNavigation(view, 10, "definition");
|
||||
expect(lspGoto).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ type: "fsChanged", created: [], modified: ["/p/Config.java"], removed: [] },
|
||||
{ type: "fsChanged", created: [], modified: [], removed: ["/p/Config.java"] },
|
||||
{ type: "docPatched", doc: 2, baseVersion: 1, version: 2, changes: [] },
|
||||
{ type: "languageServer", server: 1, name: "jdtls", status: "starting", message: null },
|
||||
{ type: "lspRefresh", server: 1, kind: "codeLens" },
|
||||
{ type: "excludedDirsChanged", dirs: ["/p/target"] },
|
||||
] as const)("invalidates on $type", async (event) => {
|
||||
const view = editor();
|
||||
await requestNavigation(view, 10, "definition");
|
||||
emitLocalIdeEvent(event as Parameters<typeof emitLocalIdeEvent>[0]);
|
||||
await requestNavigation(view, 10, "definition");
|
||||
expect(lspGoto).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not invalidate just because navigation opened a clean target", async () => {
|
||||
const view = editor();
|
||||
await requestNavigation(view, 10, "definition");
|
||||
_emitEditorEvent({ type: "docOpened", doc: 2, path: target.path, language: "java" });
|
||||
await requestNavigation(view, 10, "definition");
|
||||
expect(lspGoto).toHaveBeenCalledOnce();
|
||||
_emitEditorEvent({ type: "docClosed", doc: 2, path: target.path });
|
||||
await requestNavigation(view, 10, "definition");
|
||||
expect(lspGoto).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("discards in-flight results when dependencies change", async () => {
|
||||
let resolve!: (r: Awaited<ReturnType<typeof commands.lspGoto>>) => void;
|
||||
lspGoto.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((r) => {
|
||||
resolve = r;
|
||||
}),
|
||||
);
|
||||
const view = editor();
|
||||
const pending = requestNavigation(view, 10, "definition");
|
||||
const rejected = expect(pending).rejects.toMatchObject({ kind: "cancelled" });
|
||||
await vi.waitFor(() => expect(lspGoto).toHaveBeenCalledOnce());
|
||||
invalidateConfigurationNavigation();
|
||||
resolve({ status: "ok", data: [target] });
|
||||
await rejected;
|
||||
await requestNavigation(view, 10, "definition");
|
||||
expect(lspGoto).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each(["settled", "refresh"])("does not swallow an in-flight click on its own server %s event", async (event) => {
|
||||
let resolve!: (r: Awaited<ReturnType<typeof commands.lspGoto>>) => void;
|
||||
lspGoto.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((r) => {
|
||||
resolve = r;
|
||||
}),
|
||||
);
|
||||
const view = editor();
|
||||
const pending = requestNavigation(view, 10, "definition");
|
||||
await vi.waitFor(() => expect(lspGoto).toHaveBeenCalledOnce());
|
||||
if (event === "settled") {
|
||||
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "jdtls", status: "busy", message: null });
|
||||
vi.setSystemTime(Date.now() + 1600);
|
||||
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "jdtls", status: "ready", message: null });
|
||||
} else emitLocalIdeEvent({ type: "lspRefresh", server: 1, kind: "codeLens" });
|
||||
resolve({ status: "ok", data: [target] });
|
||||
expect(await pending).toEqual([target]);
|
||||
await requestNavigation(view, 10, "definition");
|
||||
expect(lspGoto).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not retain errors or missing targets during import", async () => {
|
||||
const view = editor();
|
||||
lspGoto.mockResolvedValueOnce({ status: "error", error: { kind: "protocol", message: "timeout" } });
|
||||
await expect(requestNavigation(view, 10, "definition")).rejects.toThrow("timeout");
|
||||
lspGoto.mockResolvedValueOnce({ status: "ok", data: [] });
|
||||
expect(await requestNavigation(view, 10, "definition")).toEqual([]);
|
||||
expect(await requestNavigation(view, 10, "definition")).toEqual([target]);
|
||||
expect(lspGoto).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("expires results when a server did not report a change", async () => {
|
||||
const view = editor();
|
||||
await requestNavigation(view, 10, "definition");
|
||||
vi.setSystemTime(Date.now() + 30_001);
|
||||
await requestNavigation(view, 10, "definition");
|
||||
expect(lspGoto).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("bounds retained entries", async () => {
|
||||
const view = editor(1, "properties", Array.from({ length: 130 }, (_, i) => `key${i}=x\n`).join(""));
|
||||
for (let i = 1; i <= 130; i++) await requestNavigation(view, view.state.doc.line(i).from, "definition");
|
||||
await requestNavigation(view, 0, "definition");
|
||||
expect(lspGoto).toHaveBeenCalledTimes(131);
|
||||
});
|
||||
|
||||
it("bounds retained locations even for large multi-target answers", async () => {
|
||||
const view = editor();
|
||||
lspGoto.mockResolvedValueOnce({ status: "ok", data: Array.from({ length: 4097 }, () => target) });
|
||||
await requestNavigation(view, 10, "definition");
|
||||
await requestNavigation(view, 10, "definition");
|
||||
expect(lspGoto).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -1,160 +0,0 @@
|
||||
/** Shared, bounded navigation results for YAML/properties hover and click. */
|
||||
import type { Text } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { onEditorEvent } from "@/editor/api";
|
||||
import { commands, IpcError, onIdeEvent, type GotoKind, type Location } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { onServerSettled } from "./availability";
|
||||
import { docOf, lspRequest } from "./lsp";
|
||||
import { offsetToPos } from "./positions";
|
||||
|
||||
// Events provide invalidation; the age limit is a backstop for servers/remote
|
||||
// file systems which do not report every semantic change. Empty/error responses
|
||||
// are never retained, since import may still be in progress.
|
||||
export const CONFIGURATION_NAVIGATION_MAX_AGE = 30_000;
|
||||
const MAX_ENTRIES = 128;
|
||||
const MAX_LOCATIONS = 4096;
|
||||
interface Cached {
|
||||
text: Text;
|
||||
path: string;
|
||||
at: number;
|
||||
size: number;
|
||||
retain: boolean;
|
||||
pending: Promise<Location[]>;
|
||||
}
|
||||
const results = new Map<string, Cached>();
|
||||
let revision = 0;
|
||||
|
||||
export function configurationNavigationRevision(): number {
|
||||
return revision;
|
||||
}
|
||||
|
||||
export function invalidateConfigurationNavigation() {
|
||||
revision++;
|
||||
results.clear();
|
||||
}
|
||||
|
||||
export function isConfigurationDocument(view: EditorView): boolean {
|
||||
const language = docOf(view)?.language;
|
||||
return language === "yaml" || language === "properties";
|
||||
}
|
||||
|
||||
/** Configuration names include hyphens and dots even when the editor's
|
||||
* language word rules split them. Share this range between decoration and lookup. */
|
||||
export function navigationWord(view: EditorView, offset: number): { from: number; to: number } | null {
|
||||
if (!isConfigurationDocument(view)) return view.state.wordAt(offset);
|
||||
const line = view.state.doc.lineAt(offset);
|
||||
const nameChar = /[\p{L}\p{N}_.$-]/u;
|
||||
let from = offset - line.from;
|
||||
let to = from;
|
||||
while (from > 0 && nameChar.test(line.text[from - 1]!)) from--;
|
||||
while (to < line.text.length && nameChar.test(line.text[to]!)) to++;
|
||||
return from < to ? { from: line.from + from, to: line.from + to } : null;
|
||||
}
|
||||
|
||||
/** Indexing/refresh can be progress from this very lookup. Do not cancel an
|
||||
* explicit click when its own server task finishes; simply don't retain that
|
||||
* answer. Source edits/restarts still invalidate the request generation. */
|
||||
function refreshConfigurationNavigation() {
|
||||
for (const [key, entry] of results) {
|
||||
entry.retain = false;
|
||||
if (entry.size) results.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
export function hasConfigurationNavigation(view: EditorView, offset: number): boolean {
|
||||
const doc = docOf(view);
|
||||
const word = navigationWord(view, offset);
|
||||
if (!doc || !word) return false;
|
||||
const entry = results.get(`${doc.doc}:${word.from}:${word.to}`);
|
||||
return (
|
||||
!!entry &&
|
||||
entry.size > 0 &&
|
||||
entry.retain &&
|
||||
entry.path === doc.path &&
|
||||
entry.text.eq(view.state.doc) &&
|
||||
Date.now() - entry.at < CONFIGURATION_NAVIGATION_MAX_AGE
|
||||
);
|
||||
}
|
||||
|
||||
export function requestNavigation(view: EditorView, offset: number, kind: GotoKind): Promise<Location[]> {
|
||||
const doc = docOf(view)!;
|
||||
const word = navigationWord(view, offset);
|
||||
if (!isConfigurationDocument(view) || kind !== "definition" || !word)
|
||||
return lspRequest(() => commands.lspGoto(doc.doc, offsetToPos(view.state.doc, offset), kind));
|
||||
const key = `${doc.doc}:${word.from}:${word.to}`;
|
||||
const text = view.state.doc;
|
||||
const hit = results.get(key);
|
||||
if (
|
||||
hit &&
|
||||
hit.path === doc.path &&
|
||||
hit.text.eq(text) &&
|
||||
Date.now() - hit.at < (hit.size ? CONFIGURATION_NAVIGATION_MAX_AGE : 3000)
|
||||
) {
|
||||
results.delete(key);
|
||||
results.set(key, hit);
|
||||
return hit.pending;
|
||||
}
|
||||
const version = revision;
|
||||
const entry: Cached = {
|
||||
text,
|
||||
path: doc.path,
|
||||
at: Date.now(),
|
||||
size: 0,
|
||||
retain: true,
|
||||
pending: lspRequest(
|
||||
() => commands.lspGoto(doc.doc, offsetToPos(text, word.from), kind),
|
||||
() => revision === version,
|
||||
)
|
||||
.then((locations) => {
|
||||
if (revision !== version || !view.state.doc.eq(text))
|
||||
throw new IpcError({ kind: "cancelled", message: "cancelled" });
|
||||
entry.size = locations.length;
|
||||
if ((!locations.length || !entry.retain) && results.get(key) === entry) results.delete(key);
|
||||
let size = 0;
|
||||
for (const value of results.values()) size += value.size;
|
||||
while (size > MAX_LOCATIONS && results.size) {
|
||||
const oldest = results.keys().next().value!;
|
||||
size -= results.get(oldest)!.size;
|
||||
results.delete(oldest);
|
||||
}
|
||||
return locations;
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (results.get(key) === entry) results.delete(key);
|
||||
throw error;
|
||||
}),
|
||||
};
|
||||
results.delete(key);
|
||||
results.set(key, entry);
|
||||
while (results.size > MAX_ENTRIES) results.delete(results.keys().next().value!);
|
||||
return entry.pending;
|
||||
}
|
||||
|
||||
export function installConfigurationNavigationEvents(): () => void {
|
||||
const clear = invalidateConfigurationNavigation;
|
||||
const off = [
|
||||
onIdeEvent("fsChanged", clear),
|
||||
onIdeEvent("excludedDirsChanged", clear),
|
||||
onIdeEvent("docPatched", clear),
|
||||
onIdeEvent("docLanguage", clear),
|
||||
onIdeEvent("workspaceEditApplied", clear),
|
||||
onIdeEvent("lspRefresh", refreshConfigurationNavigation),
|
||||
onIdeEvent("languageServer", (e) => {
|
||||
if (e.status === "starting" || e.status === "stopped" || e.status === "crashed") clear();
|
||||
}),
|
||||
onIdeEvent("languageServerRemoved", clear),
|
||||
onServerSettled(refreshConfigurationNavigation),
|
||||
onEditorEvent((e) => {
|
||||
// Closing an unsaved Java buffer restores its on-disk declarations.
|
||||
if (e.type === "docClosed" || e.type === "docSaved") clear();
|
||||
}),
|
||||
useProject.subscribe((s, previous) => {
|
||||
if (s.project?.root !== previous.project?.root) clear();
|
||||
}),
|
||||
];
|
||||
return () => {
|
||||
off.forEach((dispose) => dispose());
|
||||
clear();
|
||||
};
|
||||
}
|
||||
@@ -27,7 +27,6 @@ import { inlineCompletionExtension, registerInlineCompletionActions } from "./in
|
||||
import { semanticExtension } from "./semantic";
|
||||
import { usagesLensExtension } from "./codeLens";
|
||||
import { autoImportExtension } from "./autoImport";
|
||||
import { installConfigurationNavigationEvents } from "./configurationNavigation";
|
||||
import { installAvailabilityEvents } from "./availability";
|
||||
import { registerActionsOnSave, registerFormatOnSave, registerLspActions } from "./actions";
|
||||
import { lspTheme } from "./theme";
|
||||
@@ -70,7 +69,6 @@ export function activate(): () => void {
|
||||
const disposers = [
|
||||
installDiagnosticsEvents(),
|
||||
installAvailabilityEvents(),
|
||||
installConfigurationNavigationEvents(),
|
||||
registerEditorContribution({ id: "lsp", order: 50, extensions: lspExtensions }),
|
||||
// After the run icons (order 55), as their own gutter column.
|
||||
registerEditorContribution({ id: "lsp.lineMarkers", order: 56, extensions: implementationGutter }),
|
||||
|
||||
@@ -78,15 +78,6 @@ import { dispatchMouseShortcut, shortcutLabel } from "@/platform/keymap";
|
||||
import { isNavigationGesture, onNavigationModifier, navigationModifierHeld } from "@/platform/navigationModifier";
|
||||
import { create } from "zustand";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import {
|
||||
CONFIGURATION_NAVIGATION_MAX_AGE,
|
||||
configurationNavigationRevision,
|
||||
navigationWord,
|
||||
hasConfigurationNavigation,
|
||||
invalidateConfigurationNavigation,
|
||||
isConfigurationDocument,
|
||||
requestNavigation,
|
||||
} from "./configurationNavigation";
|
||||
|
||||
const highlightsBackoff = featureBackoff();
|
||||
|
||||
@@ -166,7 +157,7 @@ function searchingTitle(name: string | null, count: number): string {
|
||||
}
|
||||
|
||||
function nameAt(view: EditorView, offset: number): string | null {
|
||||
const word = navigationWord(view, offset);
|
||||
const word = view.state.wordAt(offset);
|
||||
return word ? view.state.sliceDoc(word.from, word.to) : null;
|
||||
}
|
||||
|
||||
@@ -294,7 +285,9 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number)
|
||||
const done = showPendingHint(view, tx`Finding navigation target…`);
|
||||
const stream = kind === "implementation" ? streamedImplementations(view, offset, done) : null;
|
||||
streamed = stream;
|
||||
const request = stream ? () => stream.request(doc.doc, pos) : () => requestNavigation(view, offset, kind);
|
||||
const request = stream
|
||||
? () => stream.request(doc.doc, pos)
|
||||
: () => lspRequest(() => commands.lspGoto(doc.doc, pos, kind));
|
||||
try {
|
||||
locs = dedupeLocations(await gotoAfterEdits(view, request));
|
||||
} finally {
|
||||
@@ -488,7 +481,7 @@ function linkAt(view: EditorView, x: number, y: number): { from: number; to: num
|
||||
const links = knownLinks(view);
|
||||
const ref = (links && linkReference(view.state.doc, links, pos)) ?? textReference(view.state.doc, pos);
|
||||
if (ref) return { from: ref.from, to: ref.to, link: true };
|
||||
const word = navigationWord(view, pos);
|
||||
const word = view.state.wordAt(pos);
|
||||
return word && word.from < word.to ? { from: word.from, to: word.to, link: false } : null;
|
||||
}
|
||||
|
||||
@@ -507,7 +500,7 @@ async function probeNavigation(
|
||||
if (!navigable && doc) {
|
||||
const pos = offsetToPos(view.state.doc, offset);
|
||||
try {
|
||||
navigable = (await requestNavigation(view, offset, "definition")).length > 0;
|
||||
navigable = (await lspRequest(() => commands.lspGoto(doc.doc, pos, "definition"))).length > 0;
|
||||
} catch (e) {
|
||||
if (!isUnavailable(e)) throw e;
|
||||
navigable = !!(await gotoFallback(view, doc, pos))?.length;
|
||||
@@ -523,11 +516,7 @@ const linkPlugin = ViewPlugin.fromClass(
|
||||
class {
|
||||
last: { x: number; y: number } | null = null;
|
||||
/** Probe results per word (`from:to`) for the current document. */
|
||||
private probed = new Map<
|
||||
string,
|
||||
{ result: { info: NavInfo | null; plugin?: NavigationMatch } | null; at: number }
|
||||
>();
|
||||
private revision = configurationNavigationRevision();
|
||||
private probed = new Map<string, { info: NavInfo | null; plugin?: NavigationMatch } | null>();
|
||||
private probedDoc: Text | null = null;
|
||||
private providerEpoch = -1;
|
||||
private probing: string | null = null;
|
||||
@@ -609,34 +598,16 @@ const linkPlugin = ViewPlugin.fromClass(
|
||||
this.set({ from: target.from, to: target.to, info: null });
|
||||
return;
|
||||
}
|
||||
if (
|
||||
this.probedDoc !== view.state.doc ||
|
||||
this.providerEpoch !== navigationEpoch() ||
|
||||
this.revision !== configurationNavigationRevision()
|
||||
) {
|
||||
if (this.probedDoc !== view.state.doc || this.providerEpoch !== navigationEpoch()) {
|
||||
this.providerEpoch = navigationEpoch();
|
||||
this.revision = configurationNavigationRevision();
|
||||
this.probeVersion++;
|
||||
clearTimeout(this.probeTimer);
|
||||
this.probing = null;
|
||||
this.probed.clear();
|
||||
this.probedDoc = view.state.doc;
|
||||
}
|
||||
const key = `${target.from}:${target.to}`;
|
||||
const hit = this.probed.get(key);
|
||||
// Configuration targets appear as the Java import progresses: they expire, and a
|
||||
// remembered target must still be in the shared results. Other results last until an edit.
|
||||
const config = isConfigurationDocument(view);
|
||||
if (
|
||||
hit &&
|
||||
(!config || Date.now() - hit.at < (hit.result ? CONFIGURATION_NAVIGATION_MAX_AGE : 1000)) &&
|
||||
(!hit.result || !config || hasConfigurationNavigation(view, target.from))
|
||||
) {
|
||||
const found = hit.result;
|
||||
if (this.probed.has(key)) {
|
||||
const hit = this.probed.get(key);
|
||||
this.set(
|
||||
found
|
||||
? { from: found.plugin?.from ?? target.from, to: found.plugin?.to ?? target.to, info: found.info }
|
||||
: null,
|
||||
hit ? { from: hit.plugin?.from ?? target.from, to: hit.plugin?.to ?? target.to, info: hit.info } : null,
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -655,34 +626,28 @@ const linkPlugin = ViewPlugin.fromClass(
|
||||
}, 3000);
|
||||
const docAt = view.state.doc;
|
||||
const epochAt = navigationEpoch();
|
||||
const revision = this.revision;
|
||||
void probeNavigation(view, target.from)
|
||||
.then((result) => {
|
||||
if (
|
||||
this.disposed ||
|
||||
view.state.doc !== docAt ||
|
||||
this.probeVersion !== version ||
|
||||
epochAt !== navigationEpoch() ||
|
||||
revision !== configurationNavigationRevision()
|
||||
epochAt !== navigationEpoch()
|
||||
)
|
||||
return;
|
||||
clearTimeout(this.probeTimer);
|
||||
if (this.probed.size >= 128) this.probed.delete(this.probed.keys().next().value!);
|
||||
this.probed.set(key, { result, at: Date.now() });
|
||||
this.probed.set(key, result);
|
||||
if (this.probing !== key) return;
|
||||
this.probing = null;
|
||||
if (!result) this.set(null);
|
||||
if (result) {
|
||||
this.set({ from: result.plugin?.from ?? target.from, to: result.plugin?.to ?? target.to, info: null });
|
||||
// Configuration navigation is a link gesture. Plain hover still
|
||||
// shows schema/type documentation; do not cover the key with it here.
|
||||
if (result.plugin || isConfigurationDocument(view)) return;
|
||||
if (result.plugin) return;
|
||||
// Documentation must never delay the link cursor or underline.
|
||||
void requestHover(view, target.from)
|
||||
.then((hover) => {
|
||||
if (this.disposed || view.state.doc !== docAt || this.probeVersion !== version || !hover) return;
|
||||
const info = declarationSummary(hover.contents);
|
||||
this.probed.set(key, { result: { info }, at: Date.now() });
|
||||
this.probed.set(key, { info });
|
||||
this.set({ from: target.from, to: target.to, info });
|
||||
})
|
||||
.catch(() => {});
|
||||
@@ -926,10 +891,7 @@ const highlightPlugin = ViewPlugin.fromClass(
|
||||
export function navigationExtension(): Extension {
|
||||
return [
|
||||
EditorView.updateListener.of((u) => {
|
||||
if (u.docChanged) {
|
||||
editedAt.set(u.view, performance.now());
|
||||
invalidateConfigurationNavigation();
|
||||
}
|
||||
if (u.docChanged) editedAt.set(u.view, performance.now());
|
||||
}),
|
||||
linkField,
|
||||
linkPlugin,
|
||||
|
||||
@@ -45,7 +45,6 @@ const fb = await import("./syntaxFallback");
|
||||
const { gotoTargets, navigationExtension, highlightUsages } = await import("./navigation");
|
||||
const { startRename, renameNamePart } = await import("./rename");
|
||||
const { lspDoc } = await import("./lsp");
|
||||
const { invalidateConfigurationNavigation } = await import("./configurationNavigation");
|
||||
const { useLspPopup, closePopup } = await import("./popupStore");
|
||||
|
||||
const r = (line: number, col: number, endCol: number): Range => ({ start: { line, col }, end: { line, col: endCol } });
|
||||
@@ -97,7 +96,6 @@ function editor(doc: string, language = "typescript", anchor = 0, path = "/p/a.t
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
invalidateConfigurationNavigation();
|
||||
for (const f of Object.values(cmd)) f.mockClear();
|
||||
openFile.mockClear();
|
||||
closePopup();
|
||||
@@ -605,79 +603,6 @@ describe("modifier-hover navigation recovery", () => {
|
||||
);
|
||||
}
|
||||
|
||||
it.each(["yaml", "properties"])(
|
||||
"%s hover underlines without a popup and clicking reuses the target",
|
||||
async (language) => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([target]));
|
||||
const view = editor("port: 8080", language);
|
||||
move(view, 1);
|
||||
await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")?.textContent).toBe("port"));
|
||||
expect(cmd.lspHover).not.toHaveBeenCalled();
|
||||
view.contentDOM.dispatchEvent(
|
||||
new MouseEvent("mousedown", {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
metaKey: mac,
|
||||
ctrlKey: !mac,
|
||||
}),
|
||||
);
|
||||
await vi.waitFor(() => expect(openFile).toHaveBeenCalledOnce());
|
||||
expect(cmd.lspGoto).toHaveBeenCalledOnce();
|
||||
expect(view.dom.querySelector(".cm-lsp-nav-info")).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["yaml", "properties"])("%s underlines the entire hyphenated configuration name", async (language) => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([target]));
|
||||
const view = editor("driver-class-name: example.Driver", language);
|
||||
for (const pos of [1, 6, 8, 12, 15]) {
|
||||
move(view, pos);
|
||||
await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")?.textContent).toBe("driver-class-name"));
|
||||
}
|
||||
await gotoTargets(view, "definition", 14);
|
||||
expect(cmd.lspGoto).toHaveBeenCalledOnce();
|
||||
expect(openFile).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("invalidates the hover marker after dependencies change", async () => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([target]));
|
||||
const view = editor("port: 8080", "yaml");
|
||||
move(view, 1);
|
||||
await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")).not.toBeNull());
|
||||
invalidateConfigurationNavigation();
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
move(view, 1);
|
||||
await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")).toBeNull());
|
||||
expect(cmd.lspGoto).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("retries a stuck configuration probe without retaining the late response", async () => {
|
||||
let finish!: (value: Awaited<R<unknown>>) => void;
|
||||
cmd.lspGoto.mockReturnValueOnce(
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
const view = editor("port: 8080", "yaml");
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
move(view, 1);
|
||||
await vi.advanceTimersByTimeAsync(3001);
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([target]));
|
||||
move(view, 1);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(cmd.lspGoto).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")).not.toBeNull());
|
||||
finish({ status: "ok", data: [] });
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
await gotoTargets(view, "definition", 1);
|
||||
expect(cmd.lspGoto).toHaveBeenCalledTimes(2);
|
||||
expect(openFile).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("shows the link without waiting for documentation", async () => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([target]));
|
||||
cmd.lspHover.mockReturnValueOnce(new Promise(() => {}));
|
||||
|
||||
@@ -3,7 +3,7 @@ import { EditorState, Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { history, undo } from "@codemirror/commands";
|
||||
import type { MessageRequest } from "@/workbench/messages";
|
||||
import type { LocalSymbol, Location, Locals, OutlineItem, Pos, Range, StructuralRanges, SyntaxNode } from "@/bindings";
|
||||
import type { LocalSymbol, Location, Locals, OutlineItem, Range, StructuralRanges, SyntaxNode } from "@/bindings";
|
||||
|
||||
// --- backend fakes ---------------------------------------------------------
|
||||
|
||||
@@ -15,12 +15,11 @@ const unavailable = () => ({ status: "error" as const, error: { kind: "unavailab
|
||||
|
||||
let goto: Answer<Location[]> = ok([]);
|
||||
let outline: Answer<OutlineItem[]> = ok([]);
|
||||
/** Called with the position searched from. */
|
||||
let references: (pos: Pos) => ReturnType<Answer<Location[]>> = ok([]);
|
||||
let references: Answer<Location[]> = ok([]);
|
||||
const lspGoto = vi.fn(async () => goto());
|
||||
const docOutline = vi.fn(async () => outline());
|
||||
const lspReferences = vi.fn(async (_request: number, _doc: number, pos: Pos) => {
|
||||
const r = references(pos);
|
||||
const lspReferences = vi.fn(async () => {
|
||||
const r = references();
|
||||
return r.status === "ok" ? { status: "ok" as const, data: { locations: r.data, incomplete: null } } : r;
|
||||
});
|
||||
const lspCodeActions = vi.fn(async () => ({ status: "ok", data: [] }));
|
||||
@@ -412,78 +411,6 @@ describe("fileUsages", () => {
|
||||
expect(docClose).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
// #1656: packages and namespaces are shared with other files; their members are what the file declares.
|
||||
describe("searches members of packages and namespaces, not the container", () => {
|
||||
const at = (path: string, line: number): Location => ({
|
||||
path,
|
||||
range: { start: { line, col: 0 }, end: { line, col: 1 } },
|
||||
});
|
||||
const within = (parent: OutlineItem, ...children: OutlineItem[]): OutlineItem => ({ ...parent, children });
|
||||
/** References per searched name; `searched` records the order. */
|
||||
function serve(text: string, refs: Record<string, Location[]>) {
|
||||
const searched: string[] = [];
|
||||
references = (pos) => {
|
||||
const off = doc(text).line(pos.line + 1).from + pos.col;
|
||||
const name = Object.keys(refs).find((n) => text.startsWith(n, off)) ?? "?";
|
||||
searched.push(name);
|
||||
return { status: "ok", data: refs[name] ?? [] };
|
||||
};
|
||||
return searched;
|
||||
}
|
||||
|
||||
it("Java: the package's other classes imported elsewhere are not usages", async () => {
|
||||
const text = "package com.example.config;\n\npublic class MessageSourceConfig {}\n";
|
||||
outline = ok([
|
||||
item(text, "com.example.config", "package com.example.config;", "package"),
|
||||
item(text, "MessageSourceConfig", "public class MessageSourceConfig {}", "class"),
|
||||
]);
|
||||
// References to the package: an import of its sibling class CommunicationConfig.
|
||||
const searched = serve(text, {
|
||||
"com.example.config": [at("/p/server/CommandSender.java", 2)],
|
||||
MessageSourceConfig: [],
|
||||
});
|
||||
expect(await fileUsages(["/p/config/MessageSourceConfig.java"])).toEqual({ status: "ok", usages: [] });
|
||||
expect(searched).toEqual(["MessageSourceConfig"]);
|
||||
});
|
||||
|
||||
it("C++: a class inside a namespace is searched", async () => {
|
||||
const text = "namespace config {\nclass Used {};\nnamespace detail {\nint helper();\n}\n}\n";
|
||||
const ns = item(
|
||||
text,
|
||||
"config",
|
||||
"namespace config {\nclass Used {};\nnamespace detail {\nint helper();\n}\n}",
|
||||
"namespace",
|
||||
);
|
||||
const detail = item(text, "detail", "namespace detail {\nint helper();\n}", "namespace");
|
||||
outline = ok([
|
||||
within(
|
||||
ns,
|
||||
item(text, "Used", "class Used {};", "class"),
|
||||
within(detail, item(text, "helper", "int helper();")),
|
||||
),
|
||||
]);
|
||||
const searched = serve(text, { Used: [at("/p/main.cpp", 4)], helper: [at("/p/main.cpp", 5)] });
|
||||
expect(await fileUsages(["/p/config/used.h"])).toEqual({
|
||||
status: "ok",
|
||||
usages: [at("/p/main.cpp", 4), at("/p/main.cpp", 5)],
|
||||
});
|
||||
expect(searched).toEqual(["Used", "helper"]);
|
||||
});
|
||||
|
||||
it("modules a file declares (TS namespace, Rust mod) are still searched", async () => {
|
||||
const text = "export namespace Utils {\n export const version = 1;\n}\n";
|
||||
outline = ok([
|
||||
within(
|
||||
item(text, "Utils", "export namespace Utils {\n export const version = 1;\n}", "module"),
|
||||
item(text, "version", "version = 1", "variable"),
|
||||
),
|
||||
]);
|
||||
const searched = serve(text, { Utils: [at("/p/main.ts", 5)] });
|
||||
expect(await fileUsages(["/p/lib/ns.ts"])).toEqual({ status: "ok", usages: [at("/p/main.ts", 5)] });
|
||||
expect(searched).toEqual(["Utils"]);
|
||||
});
|
||||
});
|
||||
|
||||
it("is unsupported when the language server can't search", async () => {
|
||||
outline = ok([item(text, "a", "pub fn a() {}")]);
|
||||
references = unavailable;
|
||||
|
||||
@@ -507,20 +507,9 @@ export type FileUsages =
|
||||
/** The language server can't tell (none running, no document symbols…). */
|
||||
| { status: "unsupported"; reason: string };
|
||||
|
||||
/** At most this many symbols per file are searched. */
|
||||
/** At most this many top-level symbols per file are searched. */
|
||||
const MAX_SYMBOLS = 60;
|
||||
|
||||
/**
|
||||
* The symbols a file declares at its top level. Packages and namespaces are shared
|
||||
* with other files (IDEA searches a Java file's classes, not its package), so their
|
||||
* members stand in for them.
|
||||
*/
|
||||
function declaredSymbols(items: readonly OutlineItem[]): OutlineItem[] {
|
||||
return items.flatMap((it) =>
|
||||
it.kind === "package" || it.kind === "namespace" ? declaredSymbols(it.children) : [it],
|
||||
);
|
||||
}
|
||||
|
||||
async function withDoc<T>(path: string, fn: (doc: number) => Promise<T>): Promise<T> {
|
||||
const open = editorsFor(path)[0];
|
||||
if (open) return fn(open.ctx.doc);
|
||||
@@ -533,7 +522,7 @@ async function withDoc<T>(path: string, fn: (doc: number) => Promise<T>): Promis
|
||||
}
|
||||
|
||||
/**
|
||||
* References from outside `paths` to the symbols the files declare ({@link declaredSymbols}).
|
||||
* References from outside `paths` to the top-level symbols the files declare.
|
||||
* Unsupported when no reference search could run for any of them.
|
||||
*/
|
||||
export async function fileUsages(paths: readonly string[], signal?: AbortSignal): Promise<FileUsages> {
|
||||
@@ -547,7 +536,7 @@ export async function fileUsages(paths: readonly string[], signal?: AbortSignal)
|
||||
try {
|
||||
await withDoc(path, async (doc) => {
|
||||
const outline = await call(commands.docOutline(doc));
|
||||
for (const item of declaredSymbols(outline).slice(0, MAX_SYMBOLS)) {
|
||||
for (const item of outline.slice(0, MAX_SYMBOLS)) {
|
||||
if (signal?.aborted) return;
|
||||
let refs: Location[];
|
||||
try {
|
||||
|
||||
@@ -1,23 +1,15 @@
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { clearMocks, mockIPC } from "@tauri-apps/api/mocks";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import { Markdown } from "./Markdown";
|
||||
|
||||
const { openFile, openExternalUrl } = vi.hoisted(() => ({
|
||||
openFile: vi.fn().mockResolvedValue(undefined),
|
||||
openExternalUrl: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
const readImage = vi.fn<(path: string) => Promise<string>>();
|
||||
const PIXEL = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
|
||||
vi.mock("@/workbench/contributions", () => ({ editorService: () => ({ openFile }) }));
|
||||
vi.mock("@/platform/openUrl", () => ({ openExternalUrl }));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
readImage.mockReset().mockResolvedValue(PIXEL);
|
||||
mockIPC((cmd, args) => (cmd === "fs_read_image" ? readImage((args as { path: string }).path) : null));
|
||||
});
|
||||
afterEach(clearMocks);
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it.each([
|
||||
"<style>body{outline:7px solid red}</style>",
|
||||
@@ -79,90 +71,3 @@ it.each(["#section", "//example.com/image.jpg", "javascript:alert(1)", "/tmp/%ZZ
|
||||
expect(openExternalUrl).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["/Users/thomas/vmos-shots/tiktok-home.jpg", "/repo", "/Users/thomas/vmos-shots/tiktok-home.jpg"],
|
||||
["images/home.jpg", "/repo", "/repo/images/home.jpg"],
|
||||
["/tmp/截图%20one.jpg", "/repo", "/tmp/截图 one.jpg"],
|
||||
["file:///tmp/auth%20code.png", "/repo", "/tmp/auth code.png"],
|
||||
["C:/shots/code.png", "C:/repo", "C:/shots/code.png"],
|
||||
["file:///C:/shots/code.png", "C:/repo", "C:/shots/code.png"],
|
||||
])("loads a reply image from the project host: %s", async (src, cwd, path) => {
|
||||
render(<Markdown text={``} cwd={cwd} />);
|
||||
await waitFor(() => expect(readImage).toHaveBeenCalledWith(path));
|
||||
await waitFor(() => expect(screen.getByRole("img", { name: "QR code" })).toHaveAttribute("src", PIXEL));
|
||||
});
|
||||
|
||||
it("loads raw HTML images without allowing alternate sources or forged paths", async () => {
|
||||
const { container } = render(
|
||||
<Markdown
|
||||
text={
|
||||
'<picture><source srcset="/wrong.png"><img alt="QR" src="/tmp/code.png" srcset="/wrong.png 2x" data-image-src="/forged.png" onerror="alert(1)"></picture>'
|
||||
}
|
||||
cwd="/repo"
|
||||
/>,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByRole("img")).toHaveAttribute("src", PIXEL));
|
||||
expect(readImage).toHaveBeenCalledExactlyOnceWith("/tmp/code.png");
|
||||
expect(container.querySelector("source, [srcset], [onerror]")).toBeNull();
|
||||
});
|
||||
|
||||
it.each([PIXEL, "https://example.com/code.png", "http://localhost:9000/code.png"])(
|
||||
"keeps an inline or web image: %s",
|
||||
(src) => {
|
||||
render(<Markdown text={``} cwd="/repo" />);
|
||||
expect(screen.getByRole("img")).toHaveAttribute("src", src);
|
||||
expect(screen.getByRole("img")).toHaveAttribute("referrerpolicy", "no-referrer");
|
||||
expect(readImage).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("reuses image reads while a reply streams, but reads again for another message", async () => {
|
||||
const { rerender, unmount } = render(<Markdown text="" cwd="/repo" />);
|
||||
await waitFor(() => expect(screen.getByRole("img")).toHaveAttribute("src", PIXEL));
|
||||
rerender(<Markdown text="\n\nScan to authorize." cwd="/repo" />);
|
||||
await waitFor(() => expect(screen.getByRole("img")).toHaveAttribute("src", PIXEL));
|
||||
expect(readImage).toHaveBeenCalledTimes(1);
|
||||
unmount();
|
||||
render(<Markdown text="" cwd="/repo" />);
|
||||
await waitFor(() => expect(readImage).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
|
||||
it("reports read failure and retries on the next render", async () => {
|
||||
readImage.mockRejectedValueOnce({ kind: "io", message: "missing", data: null });
|
||||
const { rerender } = render(<Markdown text="" cwd="/repo" />);
|
||||
await waitFor(() => expect(screen.getByRole("img")).toHaveAttribute("alt", "Unable to load image: /tmp/missing.png"));
|
||||
expect(screen.getByRole("img")).not.toHaveAttribute("src");
|
||||
rerender(<Markdown text="\n\nNow saved." cwd="/repo" />);
|
||||
await waitFor(() => expect(screen.getByRole("img")).toHaveAttribute("src", PIXEL));
|
||||
});
|
||||
|
||||
it("does not update detached images after a streamed reply replaces them", async () => {
|
||||
let resolve!: (data: string) => void;
|
||||
readImage.mockReturnValueOnce(
|
||||
new Promise((done) => {
|
||||
resolve = done;
|
||||
}),
|
||||
);
|
||||
const { rerender } = render(<Markdown text="" cwd="/repo" />);
|
||||
const oldImage = screen.getByRole("img");
|
||||
rerender(<Markdown text="Image removed." cwd="/repo" />);
|
||||
await act(async () => resolve(PIXEL));
|
||||
expect(oldImage).not.toHaveAttribute("src");
|
||||
});
|
||||
|
||||
it.each(["javascript:alert(1)", "data:text/html,test", "/tmp/%ZZ.png", "/tmp/code%00.png"])(
|
||||
"does not load unsafe or malformed image sources: %s",
|
||||
(src) => {
|
||||
render(<Markdown text={`<img alt="QR" src="${src}">`} cwd="/repo" />);
|
||||
expect(screen.getByRole("img")).not.toHaveAttribute("src");
|
||||
expect(readImage).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("reports network or decode failures without leaving a broken source", () => {
|
||||
render(<Markdown text="" cwd="/repo" />);
|
||||
fireEvent.error(screen.getByRole("img"));
|
||||
expect(screen.getByRole("img")).not.toHaveAttribute("src");
|
||||
expect(screen.getByRole("img")).toHaveAttribute("alt", "Unable to load image: https://example.com/gone.png");
|
||||
});
|
||||
@@ -13,7 +13,6 @@ import { openExternalUrl } from "@/platform/openUrl";
|
||||
import { copyText } from "@/ui";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { fileHref, pathLink, type PathLink } from "./conversation";
|
||||
import { loadImages } from "./markdownImages";
|
||||
import styles from "./Session.module.css";
|
||||
|
||||
const marked = new Marked({ gfm: true, breaks: true });
|
||||
@@ -22,26 +21,6 @@ const marked = new Marked({ gfm: true, breaks: true });
|
||||
const rendered = new Map<string, string>();
|
||||
const RENDERED_MAX = 500;
|
||||
|
||||
let purifier: ReturnType<typeof DOMPurify> | null = null;
|
||||
|
||||
function purify(): ReturnType<typeof DOMPurify> {
|
||||
if (purifier) return purifier;
|
||||
const p = DOMPurify(window);
|
||||
const sources = new WeakMap<Node, string>();
|
||||
// Preserve image-only file URLs without relaxing URI sanitizing for links or other tags.
|
||||
p.addHook("beforeSanitizeAttributes", (node) => {
|
||||
if (node.tagName !== "IMG") return;
|
||||
sources.set(node, node.getAttribute("src") ?? "");
|
||||
node.removeAttribute("src");
|
||||
});
|
||||
p.addHook("afterSanitizeAttributes", (node) => {
|
||||
const src = sources.get(node);
|
||||
if (src) node.setAttribute("data-image-src", src);
|
||||
});
|
||||
purifier = p;
|
||||
return p;
|
||||
}
|
||||
|
||||
export function markdownHtml(text: string): string {
|
||||
let html = rendered.get(text);
|
||||
if (html === undefined) {
|
||||
@@ -56,11 +35,11 @@ function renderHtml(text: string): string {
|
||||
const html = marked.parse(text, { async: false }) as string;
|
||||
// Replies can quote repository content. Styles would reach the whole IDE, and the click
|
||||
// handlers below trust `data-copy` / `data-path`, which only `enhance` may set.
|
||||
const root = purify().sanitize(html, {
|
||||
const root = DOMPurify.sanitize(html, {
|
||||
USE_PROFILES: { html: true },
|
||||
RETURN_DOM: true,
|
||||
FORBID_TAGS: ["style", "form", "source"],
|
||||
FORBID_ATTR: ["style", "srcset"],
|
||||
FORBID_TAGS: ["style", "form"],
|
||||
FORBID_ATTR: ["style"],
|
||||
ALLOW_DATA_ATTR: false,
|
||||
}) as HTMLElement;
|
||||
root.querySelectorAll("li").forEach(wrapLooseText);
|
||||
@@ -113,9 +92,8 @@ export function openPathLink(link: PathLink) {
|
||||
}
|
||||
|
||||
/** Highlighting, Copy buttons and file links over freshly rendered `root`. */
|
||||
function enhance(root: HTMLElement, cwd: string, images: Map<string, Promise<string>>): () => void {
|
||||
function enhance(root: HTMLElement, cwd: string): () => void {
|
||||
let alive = true;
|
||||
const disposeImages = loadImages(root, cwd, images);
|
||||
root.querySelectorAll<HTMLElement>("pre > code").forEach((code) => {
|
||||
const pre = code.parentElement!;
|
||||
const lang = [...code.classList].find((c) => c.startsWith("language-"))?.slice("language-".length) ?? null;
|
||||
@@ -147,15 +125,13 @@ function enhance(root: HTMLElement, cwd: string, images: Map<string, Promise<str
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
disposeImages();
|
||||
};
|
||||
}
|
||||
|
||||
export function Markdown({ text, cwd }: { text: string; cwd: string }) {
|
||||
const html = useMemo(() => markdownHtml(text), [text]);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const images = useRef(new Map<string, Promise<string>>());
|
||||
useLayoutEffect(() => (ref.current ? enhance(ref.current, cwd, images.current) : undefined), [html, cwd]);
|
||||
useLayoutEffect(() => (ref.current ? enhance(ref.current, cwd) : undefined), [html, cwd]);
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { imageTarget } from "./markdownImages";
|
||||
|
||||
it.each([
|
||||
["images/code.png", "/repo", "/repo/images/code.png"],
|
||||
["../code.png?v=2#preview", "/repo", "/repo/../code.png"],
|
||||
["/tmp/截图%20one%23.png", "/repo", "/tmp/截图 one#.png"],
|
||||
["file://localhost/tmp/code.png", "/repo", "/tmp/code.png"],
|
||||
["C:/shots/code.png", "/repo", "C:/shots/code.png"],
|
||||
[String.raw`C:\shots\code.png`, "C:/repo", "C:/shots/code.png"],
|
||||
[String.raw`images\code.png`, String.raw`C:\repo`, "C:/repo/images/code.png"],
|
||||
[String.raw`\\server\share\code.png`, "C:/repo", "//server/share/code.png"],
|
||||
["file://server/share/code.png", "C:/repo", "//server/share/code.png"],
|
||||
["file:///C:/shots/code%20one.png", "C:/repo", "C:/shots/code one.png"],
|
||||
])("resolves host image paths: %s", (src, cwd, path) => {
|
||||
expect(imageTarget(src, cwd)).toEqual({ path });
|
||||
});
|
||||
|
||||
it.each([
|
||||
"",
|
||||
"#section",
|
||||
"javascript:alert(1)",
|
||||
"JaVaScRiPt:alert(1)",
|
||||
"data:text/html,test",
|
||||
"ftp://example.com/x.png",
|
||||
"/tmp/%ZZ.png",
|
||||
"/tmp/code%00.png",
|
||||
"file:///tmp/%ZZ.png",
|
||||
"https://",
|
||||
"https://example.com/\ncode.png",
|
||||
])("rejects unsupported or malformed sources: %s", (src) => {
|
||||
expect(imageTarget(src, "/repo")).toBeNull();
|
||||
});
|
||||
|
||||
it("treats protocol-relative URLs as HTTPS, rather than host files", () => {
|
||||
expect(imageTarget("//example.com/code.png", "/repo")).toEqual({ url: "https://example.com/code.png" });
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
const hasControl = (text: string) => [...text].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127);
|
||||
|
||||
type ImageTarget = { url: string } | { path: string };
|
||||
|
||||
/** Images name host files, not paths relative to the webview's own origin. */
|
||||
export function imageTarget(source: string, cwd: string): ImageTarget | null {
|
||||
const src = source.trim();
|
||||
if (!src || hasControl(src)) return null;
|
||||
if (/^data:image\//i.test(src)) return { url: src };
|
||||
try {
|
||||
if (/^https?:\/\//i.test(src) || src.startsWith("//")) {
|
||||
const url = src.startsWith("//") ? `https:${src}` : src;
|
||||
new URL(url);
|
||||
return { url };
|
||||
}
|
||||
let path: string;
|
||||
if (/^file:/i.test(src)) {
|
||||
const url = new URL(src);
|
||||
path = decodeURIComponent(url.pathname);
|
||||
if (/^\/[a-z]:\//i.test(path)) path = path.slice(1);
|
||||
if (url.hostname && url.hostname !== "localhost") path = `//${url.hostname}${path}`;
|
||||
} else {
|
||||
if (/^[a-z][a-z\d+.-]*:/i.test(src) && !/^[a-z]:[\\/]/i.test(src)) return null;
|
||||
path = ipcPath(decodeURIComponent(src.split(/[?#]/, 1)[0]!));
|
||||
}
|
||||
if (!path || hasControl(path)) return null;
|
||||
if (path.startsWith("/") || /^[a-z]:\//i.test(path)) return { path };
|
||||
const base = ipcPath(cwd).replace(/\/$/, "");
|
||||
if (/^[a-z]:\//i.test(base) || base.startsWith("//")) path = path.replace(/\\/g, "/");
|
||||
return { path: `${base}/${path}` };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Cache belongs to one message: streaming reuses reads, later replies can show a new QR at the same path. */
|
||||
export function loadImages(root: HTMLElement, cwd: string, cache: Map<string, Promise<string>>): () => void {
|
||||
let alive = true;
|
||||
const images = [...root.querySelectorAll<HTMLImageElement>("img")];
|
||||
for (const img of images) {
|
||||
const source = img.dataset.imageSrc ?? "";
|
||||
const fail = () => {
|
||||
if (!alive) return;
|
||||
img.onerror = null;
|
||||
img.removeAttribute("src");
|
||||
img.alt = tx`Unable to load image: ${source}`;
|
||||
};
|
||||
img.setAttribute("referrerpolicy", "no-referrer");
|
||||
img.onerror = fail;
|
||||
const target = imageTarget(source, cwd);
|
||||
if (!target) {
|
||||
fail();
|
||||
} else if ("url" in target) {
|
||||
img.src = target.url;
|
||||
} else {
|
||||
let pending = cache.get(target.path);
|
||||
if (!pending) {
|
||||
pending = call(commands.fsReadImage(target.path));
|
||||
cache.set(target.path, pending);
|
||||
void pending.catch(() => cache.delete(target.path));
|
||||
}
|
||||
void pending.then((url) => {
|
||||
if (alive) img.src = url;
|
||||
}, fail);
|
||||
}
|
||||
}
|
||||
return () => {
|
||||
alive = false;
|
||||
for (const img of images) img.onerror = null;
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Settings, UpdateCheck, UpdateProgress } from "@/bindings";
|
||||
import type { UpdateCheck, UpdateProgress } from "@/bindings";
|
||||
import type { NotificationService } from "@/workbench/contributions";
|
||||
|
||||
vi.mock("@tauri-apps/api/core", () => ({
|
||||
@@ -20,7 +20,7 @@ function deferred<T>() {
|
||||
let install: ReturnType<typeof deferred<Result<null>>>;
|
||||
let check: ReturnType<typeof deferred<Result<UpdateCheck>>>;
|
||||
let channel: Channel | null;
|
||||
const appInstallUpdate = vi.fn((_source: string, _request: number, ch: Channel) => {
|
||||
const appInstallUpdate = vi.fn((_request: number, ch: Channel) => {
|
||||
channel = ch;
|
||||
return install.promise;
|
||||
});
|
||||
@@ -28,35 +28,18 @@ const appCheckUpdate = vi.fn(() => check.promise);
|
||||
const appRestart = vi.fn(async () => null);
|
||||
const cancelRequest = vi.fn(async () => null);
|
||||
const appBuildInfo = vi.fn(async () => ({ version: "0.1.21" }));
|
||||
const settingsSet = vi.fn(async () => ({ status: "ok", data: { general: {}, appearance: {} } }));
|
||||
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const actual = await orig<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...actual,
|
||||
isTauri: () => true,
|
||||
commands: {
|
||||
...actual.commands,
|
||||
appInstallUpdate,
|
||||
appCheckUpdate,
|
||||
appRestart,
|
||||
cancelRequest,
|
||||
appBuildInfo,
|
||||
settingsSet,
|
||||
},
|
||||
commands: { ...actual.commands, appInstallUpdate, appCheckUpdate, appRestart, cancelRequest, appBuildInfo },
|
||||
};
|
||||
});
|
||||
|
||||
const {
|
||||
checkForUpdates,
|
||||
installUpdate,
|
||||
notifyUpdate,
|
||||
progressText,
|
||||
updateSource,
|
||||
CHECK_TASK_ID,
|
||||
INSTALL_TASK_ID,
|
||||
UPDATE_KEY,
|
||||
} = await import("../updates");
|
||||
const { checkForUpdates, installUpdate, notifyUpdate, progressText, CHECK_TASK_ID, INSTALL_TASK_ID, UPDATE_KEY } =
|
||||
await import("../updates");
|
||||
const { provideNotificationService } = await import("@/workbench/contributions");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
const { useTasks } = await import("@/workbench/tasks");
|
||||
@@ -77,7 +60,7 @@ beforeEach(() => {
|
||||
check = deferred();
|
||||
provideNotificationService({ notify: (n) => void notes.push(n), expire: (k) => void expired.push(k) });
|
||||
useTasks.setState({ tasks: [] });
|
||||
useProject.setState({ project: null, lightEdit: false, settings: null });
|
||||
useProject.setState({ project: null, lightEdit: false });
|
||||
});
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
@@ -145,33 +128,12 @@ describe("Install and Restart", () => {
|
||||
install = deferred();
|
||||
const cancelled = installUpdate("0.1.22");
|
||||
task(INSTALL_TASK_ID)!.cancel!();
|
||||
expect(cancelRequest).toHaveBeenCalledWith(appInstallUpdate.mock.calls.at(-1)![1]);
|
||||
expect(cancelRequest).toHaveBeenCalledWith(appInstallUpdate.mock.calls.at(-1)![0]);
|
||||
install.resolve({ status: "error", error: { kind: "cancelled", message: "cancelled" } });
|
||||
await cancelled;
|
||||
expect(notes.at(-1)).toMatchObject({ level: "info", title: "Update cancelled", key: UPDATE_KEY });
|
||||
expect(appRestart).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a failed", "unavailable", "github", "CNB", "cnb"],
|
||||
["a failed", "unavailable", "cnb", "GitHub", "github"],
|
||||
["a cancelled (likely slow)", "cancelled", "cnb", "GitHub", "github"],
|
||||
])("offers %s download from %s again from the other source", async (_case, kind, from, label, to) => {
|
||||
useProject.setState({ settings: { general: { updateSource: from }, appearance: {} } as unknown as Settings });
|
||||
const first = installUpdate("0.1.22");
|
||||
install.resolve({ status: "error", error: { kind, message: kind } });
|
||||
await first;
|
||||
const action = notes.at(-1)!.actions!.at(-1)!;
|
||||
expect(action.label).toBe(`Retry with ${label}`);
|
||||
|
||||
install = deferred();
|
||||
action.run();
|
||||
await tick();
|
||||
expect(settingsSet).toHaveBeenCalledWith("global", "general.updateSource", JSON.stringify(to));
|
||||
expect(appInstallUpdate.mock.calls.at(-1)![0]).toBe(to);
|
||||
install.resolve(ok(null));
|
||||
await tick();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Check for Updates", () => {
|
||||
@@ -222,36 +184,6 @@ describe("Check for Updates", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateSource", () => {
|
||||
const withSettings = (updateSource: string | undefined, locale: string | undefined) =>
|
||||
useProject.setState({ settings: { general: { updateSource }, appearance: { locale } } as unknown as Settings });
|
||||
|
||||
it.each([
|
||||
["auto", "zh", "cnb"],
|
||||
["auto", "zh-CN", "cnb"],
|
||||
["auto", "en", "github"],
|
||||
["auto", "ko", "github"],
|
||||
[undefined, "zh", "cnb"],
|
||||
["github", "zh", "github"],
|
||||
["cnb", "en", "cnb"],
|
||||
["bogus", "en", "github"],
|
||||
])("%s with the %s UI uses %s", (setting, locale, expected) => {
|
||||
withSettings(setting, locale);
|
||||
expect(updateSource()).toBe(expected);
|
||||
});
|
||||
|
||||
it("is passed to the check and the install", async () => {
|
||||
withSettings("cnb", "en");
|
||||
void checkForUpdates();
|
||||
expect(appCheckUpdate).toHaveBeenCalledWith("cnb");
|
||||
check.resolve(ok({ enabled: true, update: null }));
|
||||
void installUpdate("0.1.22");
|
||||
expect(appInstallUpdate.mock.calls.at(-1)![0]).toBe("cnb");
|
||||
install.resolve(ok(null));
|
||||
await tick();
|
||||
});
|
||||
});
|
||||
|
||||
describe("progressText", () => {
|
||||
it("formats known and unknown lengths", () => {
|
||||
expect(progressText({ type: "downloading", downloaded: 1024 * 1024, total: null })).toEqual({
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* repeated click joins the running check or install instead of starting another.
|
||||
*/
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import { resolveLocale, t } from "@/platform/i18n";
|
||||
import { t } from "@/platform/i18n";
|
||||
import {
|
||||
call,
|
||||
commands,
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
nextRequestId,
|
||||
type UpdateInfo,
|
||||
type UpdateProgress,
|
||||
type UpdateSource,
|
||||
} from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
@@ -31,39 +30,6 @@ function errorText(e: unknown) {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
/** System Settings › Updates › Update source; `auto` picks the CNB mirror for the Chinese UI. */
|
||||
export function updateSource(): UpdateSource {
|
||||
const { settings } = useProject.getState();
|
||||
const chosen = settings?.general?.updateSource;
|
||||
if (chosen === "github" || chosen === "cnb") return chosen;
|
||||
return resolveLocale(settings?.appearance?.locale) === "zh" ? "cnb" : "github";
|
||||
}
|
||||
|
||||
const SOURCE_NAMES: Record<UpdateSource, string> = { github: "GitHub", cnb: "CNB" };
|
||||
|
||||
/** Makes `source` the update source; the retry it precedes uses it even if saving fails. */
|
||||
async function chooseSource(source: UpdateSource) {
|
||||
try {
|
||||
useProject.setState({
|
||||
settings: await call(commands.settingsSet("global", "general.updateSource", JSON.stringify(source))),
|
||||
});
|
||||
} catch {
|
||||
/* the choice still applies to this retry */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Offered once a download failed or was cancelled (likely too slow): the same install from
|
||||
* the other source. A check never needs it, since it already falls back to the other source.
|
||||
*/
|
||||
function otherSourceAction(version: string, source: UpdateSource) {
|
||||
const other: UpdateSource = source === "cnb" ? "github" : "cnb";
|
||||
return {
|
||||
label: t("app.update.retryWith", { source: SOURCE_NAMES[other] }),
|
||||
run: () => void chooseSource(other).then(() => installUpdate(version, other)),
|
||||
};
|
||||
}
|
||||
|
||||
let checking: Promise<void> | null = null;
|
||||
let installing: Promise<void> | null = null;
|
||||
|
||||
@@ -90,7 +56,7 @@ async function runCheck() {
|
||||
key: UPDATE_KEY,
|
||||
});
|
||||
try {
|
||||
const r = await Promise.race([call(commands.appCheckUpdate(updateSource())), abandoned]);
|
||||
const r = await Promise.race([call(commands.appCheckUpdate()), abandoned]);
|
||||
if (r === "cancelled") return;
|
||||
if (!r.enabled) {
|
||||
notifications().notify({
|
||||
@@ -119,7 +85,7 @@ async function runCheck() {
|
||||
/** Silent check once per app start; only an available update is shown. */
|
||||
export async function checkForUpdatesOnStartup(): Promise<void> {
|
||||
if (!isTauri()) return;
|
||||
const update = await commands.appStartupUpdateCheck(updateSource()).catch(() => null);
|
||||
const update = await commands.appStartupUpdateCheck().catch(() => null);
|
||||
if (update) notifyUpdate(update);
|
||||
}
|
||||
|
||||
@@ -152,13 +118,13 @@ export function progressText(p: UpdateProgress): { message: string; fraction: nu
|
||||
}
|
||||
|
||||
/** Downloads and installs `version`, then restarts. A second call while one runs joins it. */
|
||||
export function installUpdate(version: string, source = updateSource()): Promise<void> {
|
||||
export function installUpdate(version: string): Promise<void> {
|
||||
if (!isTauri()) return Promise.resolve();
|
||||
installing ??= runInstall(version, source).finally(() => (installing = null));
|
||||
installing ??= runInstall(version).finally(() => (installing = null));
|
||||
return installing;
|
||||
}
|
||||
|
||||
async function runInstall(version: string, source: UpdateSource) {
|
||||
async function runInstall(version: string) {
|
||||
const title = t("app.update.downloading", { version });
|
||||
const request = nextRequestId();
|
||||
const cancel = () => void commands.cancelRequest(request).catch(() => {});
|
||||
@@ -194,25 +160,17 @@ async function runInstall(version: string, source: UpdateSource) {
|
||||
// Replaces the notification whose action is now spent.
|
||||
balloon([{ label: t("app.update.cancel"), run: cancel }]);
|
||||
try {
|
||||
await call(commands.appInstallUpdate(source, request, channel));
|
||||
await call(commands.appInstallUpdate(request, channel));
|
||||
} catch (e) {
|
||||
if (isCancelled(e)) {
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
title: t("app.update.cancelled"),
|
||||
key: UPDATE_KEY,
|
||||
actions: [otherSourceAction(version, source)],
|
||||
});
|
||||
notifications().notify({ level: "info", title: t("app.update.cancelled"), key: UPDATE_KEY });
|
||||
} else {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: t("app.update.installFailed"),
|
||||
body: errorText(e),
|
||||
key: UPDATE_KEY,
|
||||
actions: [
|
||||
{ label: t("app.update.retry"), run: () => void installUpdate(version, source) },
|
||||
otherSourceAction(version, source),
|
||||
],
|
||||
actions: [{ label: t("app.update.retry"), run: () => void installUpdate(version) }],
|
||||
});
|
||||
}
|
||||
return;
|
||||
|
||||
@@ -53,7 +53,7 @@ import { executeAction, getAction } from "@/platform/actions";
|
||||
import { intellijMacos } from "@/platform/keymaps/intellij-macos";
|
||||
import type { DebugCapabilities } from "@/platform/ipc";
|
||||
import { registerDebugActions } from "../actions";
|
||||
import { breakpointsOf, loadBreakpoints, toggleBreakpoint } from "../breakpoints/store";
|
||||
import { breakpointsOf, loadBreakpoints } from "../breakpoints/store";
|
||||
import { loadSpecialBreakpoints, removeAllSpecial, useSpecialBreakpoints } from "../breakpoints/special";
|
||||
import { publishContext, updateExecutionPoint, useExecutionPoint, useDebug, type DebugSession } from "../state";
|
||||
import { focusDebugView, blurDebugView } from "../ui/focusedView";
|
||||
@@ -253,21 +253,6 @@ describe("debugger actions (IDEA parity)", () => {
|
||||
expect(opened.at(-1)).toEqual({ path: "/p/app.py", focus: true });
|
||||
});
|
||||
|
||||
it("puts no new breakpoint on a blank line", async () => {
|
||||
for (const action of ["debug.toggleBreakpoint", "debug.toggleTemporaryBreakpoint"]) {
|
||||
for (const line of [1, 2]) {
|
||||
caret("/p/a.py", "python", "x = 1\n\n \ny = 2", line);
|
||||
await executeAction(action);
|
||||
}
|
||||
expect(breakpointsOf("/p/a.py"), action).toHaveLength(0);
|
||||
}
|
||||
// One placed before the line went blank can still be toggled off.
|
||||
toggleBreakpoint("/p/a.py", 1);
|
||||
caret("/p/a.py", "python", "x = 1\n\n \ny = 2", 1);
|
||||
await executeAction("debug.toggleBreakpoint");
|
||||
expect(breakpointsOf("/p/a.py")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("toggles temporary, method and field breakpoints at the caret", async () => {
|
||||
caret("/p/a.py", "python", "x = 1\ndef run():\n pass", 0);
|
||||
await executeAction("debug.toggleTemporaryBreakpoint");
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { java } from "@codemirror/lang-java";
|
||||
import { lineHasCode } from "../breakpoints/codeLines";
|
||||
|
||||
const lines = (state: EditorState) => Array.from({ length: state.doc.lines }, (_, i) => lineHasCode(state, i));
|
||||
|
||||
describe("lines that take a breakpoint", () => {
|
||||
it("skips blank and comment-only lines", () => {
|
||||
const doc = [
|
||||
"class A {",
|
||||
"",
|
||||
" \t",
|
||||
" // note",
|
||||
" /** doc",
|
||||
" * more",
|
||||
" */",
|
||||
" int f() { return 1; } // trailing",
|
||||
" /* a */ int x = 1;",
|
||||
" /* a */ /* b */",
|
||||
"}",
|
||||
].join("\n");
|
||||
const state = EditorState.create({ doc, extensions: [java()] });
|
||||
expect(lines(state)).toEqual([true, false, false, false, false, false, false, true, true, false, true]);
|
||||
});
|
||||
|
||||
it("only skips blank lines in a file without a parser", () => {
|
||||
expect(lines(EditorState.create({ doc: "x\n\n \n// y" }))).toEqual([true, false, false, true]);
|
||||
});
|
||||
});
|
||||
@@ -3,14 +3,8 @@ import { EditorState } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, gutter, lineNumbers } from "@codemirror/view";
|
||||
import { breakpointGutter, lookOf } from "../editor/breakpointGutter";
|
||||
import { executionPoint } from "../editor/execution";
|
||||
import {
|
||||
breakpointsOf,
|
||||
loadBreakpoints,
|
||||
toggleBreakpoint,
|
||||
updateBreakpoint,
|
||||
useBreakpoints,
|
||||
} from "../breakpoints/store";
|
||||
import { adoptSession, useExecutionPoint, useDebug, handleDebugEvent, type DebugSession } from "../state";
|
||||
import { breakpointsOf, loadBreakpoints, toggleBreakpoint, updateBreakpoint } from "../breakpoints/store";
|
||||
import { adoptSession, useExecutionPoint, useDebug, handleDebugEvent } from "../state";
|
||||
import { getContext } from "@/platform/context";
|
||||
import styles from "../editor/editor.module.css";
|
||||
|
||||
@@ -59,38 +53,6 @@ describe("breakpoint gutter", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("breakpoint gutter redraws", () => {
|
||||
it("follows a session starting and ending, not every update of a running one", async () => {
|
||||
localStorage.clear();
|
||||
loadBreakpoints("/proj");
|
||||
useDebug.setState({ sessions: {} });
|
||||
const view = makeView("a\nb");
|
||||
toggleBreakpoint(ctx.path, 0);
|
||||
const id = breakpointsOf(ctx.path)[0]!.id;
|
||||
useBreakpoints.setState({ status: { [id]: { verified: true, message: null, line: 0 } } });
|
||||
await flush();
|
||||
expect(view.dom.querySelector(`.${styles.verified}`)).toBeNull();
|
||||
|
||||
const session = { id: 9, status: "running" } as DebugSession;
|
||||
useDebug.setState({ sessions: { 9: session } });
|
||||
await flush();
|
||||
expect(view.dom.querySelector(`.${styles.verified}`)).not.toBeNull();
|
||||
|
||||
const reads = vi.spyOn(useBreakpoints, "getState");
|
||||
useDebug.setState({ sessions: { 9: { ...session, status: "paused" } } });
|
||||
useBreakpoints.setState({
|
||||
status: { [id]: useBreakpoints.getState().status[id]!, other: { verified: true, message: null, line: 3 } },
|
||||
});
|
||||
reads.mockClear();
|
||||
await flush();
|
||||
expect(reads).not.toHaveBeenCalled();
|
||||
|
||||
useDebug.setState({ sessions: { 9: { ...session, status: "terminated" } } });
|
||||
await flush();
|
||||
expect(view.dom.querySelector(`.${styles.verified}`)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("output class gutter", () => {
|
||||
it("disables ordinary, temporary and logging breakpoints and explains why", () => {
|
||||
loadBreakpoints("/proj");
|
||||
@@ -191,17 +153,6 @@ describe("breakpoint gutter clicks", () => {
|
||||
expect(breakpointsOf(ctx.path)[0]).toMatchObject({ line: 0, temporary: true });
|
||||
});
|
||||
|
||||
it("adds nothing on a blank line but still removes a breakpoint there", () => {
|
||||
localStorage.clear();
|
||||
loadBreakpoints("/proj");
|
||||
const view = makeView("\na");
|
||||
for (const init of [{}, { altKey: true }, { shiftKey: true }]) click(view, init);
|
||||
expect(breakpointsOf(ctx.path)).toHaveLength(0);
|
||||
toggleBreakpoint(ctx.path, 0);
|
||||
click(view, {});
|
||||
expect(breakpointsOf(ctx.path)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("middle-click enables / disables an existing breakpoint", () => {
|
||||
localStorage.clear();
|
||||
loadBreakpoints("/proj");
|
||||
|
||||
@@ -7,7 +7,6 @@ import { activeEditor } from "@/editor/api";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { maybeEditorService, notifications, showStatusInfo, toolWindowService } from "@/workbench/contributions";
|
||||
import { classFileBreakpointReason } from "@/platform/classFiles";
|
||||
import { lineHasCode } from "./breakpoints/codeLines";
|
||||
import { canPlaceBreakpoint } from "./breakpoints/languages";
|
||||
import {
|
||||
removeAllBreakpoints,
|
||||
@@ -629,9 +628,6 @@ export function registerDebugActions(): () => void {
|
||||
return;
|
||||
}
|
||||
const ed = activeEditor();
|
||||
// Like IDEA, no new breakpoint on a blank or comment-only line; an existing one still goes.
|
||||
const taken = exists || specialAt(c.path).some((b) => b.line === c.line);
|
||||
if (!taken && ed && !lineHasCode(ed.view.state, c.line)) return;
|
||||
if (ed) toggleBreakpointSmart(c.path, c.line, language, ed.view.state.doc.toString());
|
||||
else toggleBreakpoint(c.path, c.line);
|
||||
},
|
||||
@@ -644,11 +640,8 @@ export function registerDebugActions(): () => void {
|
||||
description: "A line breakpoint that is removed after it is hit",
|
||||
run: () => {
|
||||
const c = cursor();
|
||||
const ed = activeEditor();
|
||||
if (!c || !breakpointPathAllowed(c.path) || !canPlaceBreakpoint(ed?.ctx.language ?? "", c.path)) return;
|
||||
const exists = useBreakpoints.getState().byFile[c.path]?.some((b) => b.line === c.line);
|
||||
if (!exists && ed && !lineHasCode(ed.view.state, c.line)) return;
|
||||
toggleTemporaryBreakpoint(c.path, c.line);
|
||||
if (c && breakpointPathAllowed(c.path) && canPlaceBreakpoint(activeEditor()?.ctx.language ?? "", c.path))
|
||||
toggleTemporaryBreakpoint(c.path, c.line);
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
/**
|
||||
* IDEA puts a new line breakpoint only where there is code: a gutter click or Toggle Line
|
||||
* Breakpoint on a blank or comment-only line does nothing. Comments come from the syntax
|
||||
* tree; in a file without a parser only blank lines are skipped.
|
||||
*/
|
||||
import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";
|
||||
import type { EditorState } from "@codemirror/state";
|
||||
import type { SyntaxNode, Tree } from "@lezer/common";
|
||||
|
||||
const PARSE_BUDGET_MS = 20;
|
||||
|
||||
function commentAt(tree: Tree, pos: number): SyntaxNode | null {
|
||||
for (let n: SyntaxNode | null = tree.resolveInner(pos, 1); n; n = n.parent) if (/comment/i.test(n.name)) return n;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Whether `line` (0-based) has anything besides whitespace and comments. */
|
||||
export function lineHasCode(state: EditorState, line: number): boolean {
|
||||
if (line < 0 || line >= state.doc.lines) return false;
|
||||
const { from, to, text } = state.doc.line(line + 1);
|
||||
if (!/\S/.test(text)) return false;
|
||||
const tree = ensureSyntaxTree(state, to, PARSE_BUDGET_MS) ?? syntaxTree(state);
|
||||
for (let pos = from; pos < to;) {
|
||||
if (/\s/.test(text[pos - from]!)) {
|
||||
pos++;
|
||||
continue;
|
||||
}
|
||||
const comment = commentAt(tree, pos);
|
||||
if (!comment) return true;
|
||||
pos = Math.max(pos + 1, comment.to);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
import { classFileBreakpointReason } from "@/platform/classFiles";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { showStatusInfo } from "@/workbench/contributions";
|
||||
import { lineHasCode } from "../breakpoints/codeLines";
|
||||
import { canPlaceBreakpoint } from "../breakpoints/languages";
|
||||
import {
|
||||
removeSpecial,
|
||||
@@ -186,19 +185,14 @@ export function breakpointGutter(ctx: EditorDocContext): Extension {
|
||||
private unsubs: Array<() => void>;
|
||||
private pending = false;
|
||||
private destroyed = false;
|
||||
private running = sessionsRunning();
|
||||
constructor(readonly view: EditorView) {
|
||||
this.unsubs = [
|
||||
useBreakpoints.subscribe((s, prev) => {
|
||||
// States arrive per file: another file's don't change this one's markers.
|
||||
const states = (s.byFile[path] ?? []).some((b) => s.status[b.id] !== prev.status[b.id]);
|
||||
if (s.byFile[path] !== prev.byFile[path] || states || s.muted !== prev.muted) this.scheduleRebuild();
|
||||
if (s.byFile[path] !== prev.byFile[path] || s.status !== prev.status || s.muted !== prev.muted)
|
||||
this.scheduleRebuild();
|
||||
}),
|
||||
// The markers only show whether a session runs, while each step updates `sessions` several times.
|
||||
useDebug.subscribe((s, prev) => {
|
||||
if (s.sessions === prev.sessions || sessionsRunning() === this.running) return;
|
||||
this.running = !this.running;
|
||||
this.scheduleRebuild();
|
||||
if (s.sessions !== prev.sessions) this.scheduleRebuild();
|
||||
}),
|
||||
useSpecialBreakpoints.subscribe((s, prev) => {
|
||||
if (s.methods !== prev.methods || s.fields !== prev.fields || s.status !== prev.status)
|
||||
@@ -238,10 +232,9 @@ export function breakpointGutter(ctx: EditorDocContext): Extension {
|
||||
}
|
||||
|
||||
/**
|
||||
* IDEA's gutter clicks: click toggles; on a line without a breakpoint ⇧-click adds a
|
||||
* non-suspending logging breakpoint and opens its properties, ⌥-click a temporary one.
|
||||
* Blank and comment-only lines take none. On an existing breakpoint only a plain
|
||||
* (or ⌘/Ctrl) click removes it; middle-click enables/disables.
|
||||
* IDEA's gutter clicks: click toggles; on an empty line ⇧-click adds a non-suspending
|
||||
* logging breakpoint and opens its properties, ⌥-click a temporary one. On an existing
|
||||
* breakpoint only a plain (or ⌘/Ctrl) click removes it; middle-click enables/disables.
|
||||
*/
|
||||
onMouseDown = (e: MouseEvent) => {
|
||||
if ((e.button !== 0 && e.button !== 1) || !inBreakpointArea(e)) return;
|
||||
@@ -278,7 +271,6 @@ export function breakpointGutter(ctx: EditorDocContext): Extension {
|
||||
else removeBreakpoint(path, bp!.id);
|
||||
return;
|
||||
}
|
||||
if (!lineHasCode(this.view.state, line)) return;
|
||||
if (e.altKey) {
|
||||
addBreakpoint(path, line, { temporary: true });
|
||||
return;
|
||||
|
||||
@@ -50,11 +50,8 @@ export interface DateFormatValid {
|
||||
pretty: boolean;
|
||||
}
|
||||
|
||||
export type UpdateSourceSetting = "auto" | "github" | "cnb";
|
||||
|
||||
export interface GeneralExtras {
|
||||
openProjectIn: OpenProjectIn;
|
||||
updateSource: UpdateSourceSetting;
|
||||
defaultProjectDirectory: string;
|
||||
saveOnIdle: boolean;
|
||||
idleSeconds: number;
|
||||
@@ -103,7 +100,6 @@ export const DEFAULT_APPEARANCE_EXTRAS: AppearanceExtras = {
|
||||
|
||||
export const DEFAULT_GENERAL_EXTRAS: GeneralExtras = {
|
||||
openProjectIn: "ask",
|
||||
updateSource: "auto",
|
||||
defaultProjectDirectory: "",
|
||||
saveOnIdle: false,
|
||||
idleSeconds: 15,
|
||||
@@ -164,7 +160,6 @@ export function validateGeneralExtras(raw: unknown): GeneralExtras {
|
||||
const df = obj(g.dateFormat);
|
||||
return {
|
||||
openProjectIn: oneOf(g.openProjectIn, ["ask", "new", "same", "attach"] as const, d.openProjectIn),
|
||||
updateSource: oneOf(g.updateSource, ["auto", "github", "cnb"] as const, d.updateSource),
|
||||
defaultProjectDirectory: typeof g.defaultProjectDirectory === "string" ? g.defaultProjectDirectory : "",
|
||||
saveOnIdle: bool(g.saveOnIdle, d.saveOnIdle),
|
||||
idleSeconds: int(g.idleSeconds, d.idleSeconds, IDLE_LIMITS),
|
||||
|
||||
@@ -26,7 +26,6 @@ import {
|
||||
type NotificationDisplay,
|
||||
type NotificationGroupValid,
|
||||
type OpenProjectIn,
|
||||
type UpdateSourceSetting,
|
||||
} from "../model/behaviorSchema";
|
||||
import { ACCENT_PRESETS, LIMITS, type ThemeId } from "../model/schema";
|
||||
import type { PageSpec } from "./spec";
|
||||
@@ -382,12 +381,6 @@ const OPEN_IN: Array<{ value: OpenProjectIn; label: string }> = [
|
||||
{ value: "ask", label: "Ask" },
|
||||
];
|
||||
|
||||
const UPDATE_SOURCES: SelectOption<UpdateSourceSetting>[] = [
|
||||
{ value: "auto", label: "Automatic" },
|
||||
{ value: "github", label: "GitHub" },
|
||||
{ value: "cnb", label: "CNB (China mirror)" },
|
||||
];
|
||||
|
||||
function OpenProjectInRow() {
|
||||
const [value, set] = useSetting<OpenProjectIn>("general.openProjectIn");
|
||||
const name = useId();
|
||||
@@ -731,18 +724,6 @@ export const BEHAVIOR_PAGES: PageSpec[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Updates",
|
||||
options: [
|
||||
{
|
||||
kind: "select",
|
||||
key: "general.updateSource",
|
||||
label: "Update source",
|
||||
hint: "Where updates are downloaded from. If it can't be reached, the other source is tried.",
|
||||
options: UPDATE_SOURCES,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Exit",
|
||||
options: [{ kind: "toggle", key: "general.confirmExit", label: "Confirm before exiting the IDE" }],
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
import { FontPicker } from "../components/FontPicker";
|
||||
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { quotePath } from "@/platform/commandLine";
|
||||
import { commands, isTauri } from "@/platform/ipc";
|
||||
import {
|
||||
DEFAULT_EXTERNAL_TOOL,
|
||||
@@ -111,7 +110,7 @@ function ShellPathRow() {
|
||||
const { open: pick } = await import("@tauri-apps/plugin-dialog");
|
||||
const picked = await pick({ multiple: false, title: "Shell Path" });
|
||||
const path = Array.isArray(picked) ? picked[0] : picked;
|
||||
if (path) set(quotePath(path));
|
||||
if (path) set(path);
|
||||
};
|
||||
return (
|
||||
<Row
|
||||
@@ -143,7 +142,7 @@ function ShellPathRow() {
|
||||
anchor={menuRef}
|
||||
placement="bottom-end"
|
||||
aria-label="Installed shells"
|
||||
items={shells.map((p) => ({ id: p, label: p, checked: quotePath(p) === value, run: () => set(quotePath(p)) }))}
|
||||
items={shells.map((p) => ({ id: p, label: p, checked: p === value, run: () => set(p) }))}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
|
||||
@@ -16,9 +16,9 @@ import { installTerminalPaste, pasteTerminalClipboard } from "./paste";
|
||||
import { ImeCommitGate } from "./imeCommit";
|
||||
import { ownTerminalInput } from "./imeInput";
|
||||
import { findTerminalLinks, resolvePath, type TerminalLink } from "./links";
|
||||
import { parseShellCommand } from "@/platform/commandLine";
|
||||
import { splitCommandLine } from "@/platform/commandLine";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { hostOs, useRemote } from "@/platform/remote";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { workflowSettings, type TerminalSettingsValid } from "@/platform/workflowSettings";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
@@ -530,7 +530,7 @@ export class TerminalSession {
|
||||
};
|
||||
try {
|
||||
const t = workflowSettings().terminal;
|
||||
const [shellPath, ...shellArgs] = parseShellCommand(t.shellPath, hostOs() === "windows");
|
||||
const [shellPath, ...shellArgs] = splitCommandLine(t.shellPath);
|
||||
const shell = custom ? custom.program : shellPath;
|
||||
const args = custom ? custom.args : shellArgs;
|
||||
const info = await call(
|
||||
|
||||
@@ -41,7 +41,6 @@ import {
|
||||
checkOf,
|
||||
filesOf,
|
||||
groupFileNodes,
|
||||
groupOf,
|
||||
ignoreTargets,
|
||||
isPartiallyStaged,
|
||||
planCommit,
|
||||
@@ -52,12 +51,9 @@ import {
|
||||
import { applyStash, commitChanges, deleteFiles, dropStash, showUnstashDialog, stashChanges } from "./changeOps";
|
||||
import { CommitOptionsPopup } from "./CommitOptions";
|
||||
import { DEFAULT_LIST_NAME, useChangelists, withListDefaults } from "./changelists";
|
||||
import { commitFiles, moveToChangelist } from "./changelistsUi";
|
||||
import { acceptSide } from "./conflictsUi";
|
||||
import { copyChangesAsPatch } from "./patches";
|
||||
import { moveToChangelist } from "./changelistsUi";
|
||||
import {
|
||||
messageHistory,
|
||||
pendingFixup,
|
||||
setAmend,
|
||||
setCommitDiffPreview,
|
||||
setDiffPreview,
|
||||
@@ -67,7 +63,6 @@ import {
|
||||
type CommitTab,
|
||||
} from "./commitStore";
|
||||
import { pushAfterCommit } from "./commitUi";
|
||||
import { rebaseAfterFixup } from "./rebase";
|
||||
import { stashTabOf, stashTabs, type ContentTab } from "./gitTabs";
|
||||
import { diffInput, openDiff, withChain, workingDiffData } from "./diffInput";
|
||||
import { DiffEditor } from "./DiffEditor";
|
||||
@@ -248,26 +243,6 @@ export function nodeMenu(nodes: ChangeNode[], repos: readonly string[]): MenuIte
|
||||
const toIgnore = ignoreTargets(nodes, repos);
|
||||
const conflicted = files.filter((f) => f.unstaged === "conflicted");
|
||||
const items: MenuItem[] = [
|
||||
...(conflicted.length
|
||||
? [
|
||||
{
|
||||
label: "Accept Yours",
|
||||
run: () => void Promise.all(conflicted.map((f) => acceptSide(f, "ours"))).then(() => refreshNow()),
|
||||
},
|
||||
{
|
||||
label: "Accept Theirs",
|
||||
run: () => void Promise.all(conflicted.map((f) => acceptSide(f, "theirs"))).then(() => refreshNow()),
|
||||
},
|
||||
{ kind: "separator" as const },
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: "Commit File…",
|
||||
icon: "commit",
|
||||
disabled: !files.some((f) => groupOf(f) === "changes"),
|
||||
run: () => commitFiles(paths),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{ kind: "action", action: "vcs.showDiff", arg: first?.path },
|
||||
{
|
||||
label: "Jump to Source",
|
||||
@@ -322,7 +297,6 @@ export function nodeMenu(nodes: ChangeNode[], repos: readonly string[]): MenuIte
|
||||
: []),
|
||||
{ kind: "action", action: "vcs.shelve", arg: paths },
|
||||
{ kind: "action", action: "vcs.createPatch", arg: paths },
|
||||
{ label: "Copy as Patch to Clipboard", run: () => void copyChangesAsPatch(paths) },
|
||||
{ kind: "separator" },
|
||||
{
|
||||
label: "Show History",
|
||||
@@ -788,7 +762,7 @@ export interface CommitRunner {
|
||||
clearEmptyError: () => void;
|
||||
/** Whether the Commit buttons are enabled. */
|
||||
canCommit: boolean;
|
||||
run: (push: boolean, rebaseFixup?: boolean) => Promise<void>;
|
||||
run: (push: boolean) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -800,7 +774,7 @@ export function useCommitRunner(included: number, onCommitted?: () => void): Com
|
||||
const merging = useVcs((s) => s.branch?.operation === "merge");
|
||||
const [emptyError, setEmptyError] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const run = async (push: boolean, rebaseFixup = false) => {
|
||||
const run = async (push: boolean) => {
|
||||
if (busy) return;
|
||||
// IDEA keeps Commit enabled and reports an empty message at the field.
|
||||
if (!useCommit.getState().message.trim() && !useCommit.getState().amend) {
|
||||
@@ -810,12 +784,10 @@ export function useCommitRunner(included: number, onCommitted?: () => void): Com
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const fixup = rebaseFixup ? pendingFixup(useCommit.getState().message, useCommit.getState().fixupTarget) : null;
|
||||
const id = await commitChanges();
|
||||
if (id === undefined) return;
|
||||
onCommitted?.();
|
||||
if (fixup) void rebaseAfterFixup(fixup);
|
||||
else if (push) void pushAfterCommit();
|
||||
if (push) void pushAfterCommit();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -978,8 +950,6 @@ function CommitPanel({ included }: { included: number }) {
|
||||
const [optionsOpen, setOptionsOpen] = useState(false);
|
||||
const runner = useCommitRunner(included);
|
||||
const { canCommit } = runner;
|
||||
// After Fixup… / Squash Into…, the second button commits and autosquashes the target.
|
||||
const fixup = useCommit((s) => pendingFixup(s.message, s.fixupTarget));
|
||||
|
||||
return (
|
||||
<div className={styles.commit}>
|
||||
@@ -988,29 +958,16 @@ function CommitPanel({ included }: { included: number }) {
|
||||
<Button variant="primary" disabled={!canCommit} onClick={() => void runner.run(false)} title="⌘↩">
|
||||
<T>{commitLabel(amend, checkProblems.length > 0)}</T>
|
||||
</Button>
|
||||
{fixup ? (
|
||||
<Button
|
||||
className={styles.pushButton}
|
||||
disabled={!canCommit}
|
||||
onClick={() => void runner.run(false, true)}
|
||||
title="Commit and Rebase"
|
||||
>
|
||||
<span>
|
||||
<T>Commit and Rebase</T>
|
||||
</span>
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
className={styles.pushButton}
|
||||
disabled={!canCommit || !!remoteBusy}
|
||||
onClick={() => void runner.run(true)}
|
||||
title="⌥⌘↩"
|
||||
>
|
||||
<span>
|
||||
<T>{commitAndPushLabel(amend)}</T>
|
||||
</span>
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
className={styles.pushButton}
|
||||
disabled={!canCommit || !!remoteBusy}
|
||||
onClick={() => void runner.run(true)}
|
||||
title="⌥⌘↩"
|
||||
>
|
||||
<span>
|
||||
<T>{commitAndPushLabel(amend)}</T>
|
||||
</span>
|
||||
</Button>
|
||||
<span className={styles.grow} />
|
||||
<IconButton
|
||||
ref={optionsRef}
|
||||
|
||||
@@ -68,15 +68,6 @@ describe("change list model", () => {
|
||||
expect(next.files).toEqual({ "src/b.ts": feature, "new.ts": feature });
|
||||
});
|
||||
|
||||
it("keeps the lists of files whose changes a merge, rebase or update put aside", () => {
|
||||
const { state, feature } = twoLists();
|
||||
// The rebase stashed every change: nothing looks changed until they come back.
|
||||
const aside = syncAssignments(state, [], true);
|
||||
expect(aside?.files ?? state.files).toEqual(state.files);
|
||||
const back = syncAssignments(aside ?? state, ["src/b.ts"]);
|
||||
expect((back ?? aside ?? state).files).toEqual({ "src/b.ts": feature });
|
||||
});
|
||||
|
||||
it("files without an assignment belong to the active list", () => {
|
||||
const { state, feature } = twoLists();
|
||||
expect(listOf(state, "src/b.ts")).toBe(feature);
|
||||
|
||||
@@ -197,14 +197,14 @@ describe("commit inclusion", () => {
|
||||
expect(initialCheck(status[5]!)).toBe("none");
|
||||
});
|
||||
|
||||
it("plans which changes the commit takes and which staged ones it leaves out", () => {
|
||||
it("plans staging so the index holds exactly the checked changes", () => {
|
||||
const checks = new Map<string, CheckState>([
|
||||
["/r/README.md", "none"],
|
||||
["/r/notes.txt", "all"],
|
||||
]);
|
||||
const plan = planCommit(status, checks);
|
||||
expect(plan.stage.sort()).toEqual(["/r/notes.txt", "/r/src/main/kotlin/App.kt"]);
|
||||
expect(plan.exclude).toEqual(["/r/README.md"]);
|
||||
expect(plan.unstage).toEqual(["/r/README.md"]);
|
||||
expect(plan.included.map((f) => f.relPath).sort()).toEqual([
|
||||
"notes.txt",
|
||||
"src/main/kotlin/App.kt",
|
||||
|
||||
@@ -2,7 +2,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const unstage = vi.hoisted(() => vi.fn());
|
||||
const stage = vi.hoisted(() => vi.fn());
|
||||
const commit = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
@@ -15,7 +14,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
...real.commands,
|
||||
vcsUnstage: unstage.mockImplementation(() => ok(null)),
|
||||
vcsStage: stage.mockImplementation(() => ok(null)),
|
||||
vcsCommit: commit.mockImplementation(() => ok("commit1")),
|
||||
vcsCommit: () => ok("commit1"),
|
||||
},
|
||||
};
|
||||
});
|
||||
@@ -40,7 +39,6 @@ describe("changes left out of a commit (#1539)", () => {
|
||||
localStorage.clear();
|
||||
unstage.mockClear();
|
||||
stage.mockClear();
|
||||
commit.mockClear();
|
||||
useVcs.setState({
|
||||
available: false,
|
||||
root: "/p",
|
||||
@@ -61,9 +59,8 @@ describe("changes left out of a commit (#1539)", () => {
|
||||
|
||||
it("keeps the 15 excluded files excluded instead of checking them again", async () => {
|
||||
expect(await commitChanges()).toBe("commit1");
|
||||
// Only the 5 checked files go into the commit; the index itself is not touched.
|
||||
expect(commit.mock.calls[0]?.[2].stage).toEqual(files.slice(0, 5).map((f) => f.path));
|
||||
expect(stage).not.toHaveBeenCalled();
|
||||
// Only the 5 checked files were staged for the commit.
|
||||
expect(stage.mock.calls[0]?.[0]).toEqual(files.slice(0, 5).map((f) => f.path));
|
||||
expect(unstage).not.toHaveBeenCalled();
|
||||
|
||||
const { checks, excludedHunks } = useCommit.getState();
|
||||
@@ -73,12 +70,4 @@ describe("changes left out of a commit (#1539)", () => {
|
||||
// Block exclusions of files still in the tree are kept too.
|
||||
expect(excludedHunks.get(files[5]!.path)).toEqual(new Set(["h1"]));
|
||||
});
|
||||
|
||||
it("leaves staged files out of the commit without unstaging them", async () => {
|
||||
const staged = { ...files[7]!, staged: "modified" as const, unstaged: null };
|
||||
useVcs.setState({ status: [...files.slice(0, 7), staged] });
|
||||
expect(await commitChanges()).toBe("commit1");
|
||||
expect(commit.mock.calls[0]?.[2].exclude).toEqual([staged.path]);
|
||||
expect(unstage).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -16,7 +16,7 @@ vi.mock("@/platform/workflowSettings", () => ({
|
||||
}));
|
||||
vi.mock("../store", async () => {
|
||||
const { create } = await import("zustand");
|
||||
return { useVcs: create(() => ({})), refreshNow: mocks.refresh, beginGitWork: () => () => {} };
|
||||
return { useVcs: create(() => ({})), refreshNow: mocks.refresh };
|
||||
});
|
||||
import { notifyFileOperation } from "@/platform/fileOps";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
@@ -84,9 +84,9 @@ describe("commit plan and rollback with renames", () => {
|
||||
expect(renamedFromPath(fs("a.ts"))).toBeNull();
|
||||
});
|
||||
|
||||
it("leaves both sides of an excluded rename out so the deletion is not committed alone", () => {
|
||||
it("unstages both sides of an excluded rename so the deletion is not committed alone", () => {
|
||||
const plan = planCommit([renamed], new Map([[renamed.path, "none"]]));
|
||||
expect(plan.exclude).toEqual(["/p/src/new.ts", "/p/src/old.ts"]);
|
||||
expect(plan.unstage).toEqual(["/p/src/new.ts", "/p/src/old.ts"]);
|
||||
expect(plan.included).toEqual([]);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
ask: vi.fn(),
|
||||
merge: vi.fn(),
|
||||
restore: vi.fn(),
|
||||
heads: {} as Record<string, string>,
|
||||
ops: {} as Record<string, string | null>,
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data });
|
||||
const fail = (message: string) => Promise.resolve({ status: "error" as const, error: { kind: "failed", message } });
|
||||
return {
|
||||
...real,
|
||||
isTauri: () => false,
|
||||
call: async (p: Promise<{ status: string; data?: unknown; error?: unknown }>) => {
|
||||
const r = await p;
|
||||
if (r.status === "error") throw r.error;
|
||||
return r.data;
|
||||
},
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsBranchInfo: (root: string) =>
|
||||
ok({ head: "main", headCommit: mocks.heads[root], operation: mocks.ops[root] ?? null }),
|
||||
vcsMerge: (root: string, branch: string) => {
|
||||
mocks.merge(root, branch);
|
||||
if (root === "/b") return fail("merge refused");
|
||||
mocks.heads[root] = `${root}-merged`;
|
||||
return ok(null);
|
||||
},
|
||||
vcsRestoreHead: (root: string, before: string, after: string) => {
|
||||
mocks.restore(root, before, after);
|
||||
return ok(null);
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@/workbench/messages", () => ({ ask: mocks.ask, showError: vi.fn() }));
|
||||
|
||||
import { mergeInRepos } from "../branchOps";
|
||||
import { pendingFixup } from "../commitStore";
|
||||
import type { Commit } from "@/bindings";
|
||||
|
||||
describe("an operation over several repositories that fails part way (IDEA's rollback proposal)", () => {
|
||||
beforeEach(() => {
|
||||
mocks.ask.mockReset();
|
||||
mocks.merge.mockReset();
|
||||
mocks.restore.mockReset();
|
||||
mocks.heads = { "/a": "a1", "/b": "b1", "/c": "c1" };
|
||||
mocks.ops = {};
|
||||
});
|
||||
|
||||
it("offers to reset the repositories it already merged, and does so on Rollback", async () => {
|
||||
mocks.ask.mockResolvedValue({ button: "rollback" });
|
||||
await mergeInRepos("feature", ["/a", "/b", "/c"]);
|
||||
expect(mocks.merge.mock.calls.map((c) => c[0])).toEqual(["/a", "/b"]);
|
||||
expect(mocks.ask).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.restore).toHaveBeenCalledWith("/a", "a1", "/a-merged");
|
||||
});
|
||||
|
||||
it("leaves them merged on Don't Rollback", async () => {
|
||||
mocks.ask.mockResolvedValue({ button: "keep" });
|
||||
await mergeInRepos("feature", ["/a", "/b"]);
|
||||
expect(mocks.restore).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("doesn't ask when the failed repository stopped on conflicts", async () => {
|
||||
mocks.ops = { "/b": "merge" };
|
||||
await mergeInRepos("feature", ["/a", "/b"]);
|
||||
expect(mocks.ask).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Commit and Rebase after Fixup…", () => {
|
||||
const target = { id: "c1", summary: "Add parser" } as Commit;
|
||||
it("is offered while the message is the one prepared for the target", () => {
|
||||
expect(pendingFixup("fixup! Add parser", target)).toBe(target);
|
||||
expect(pendingFixup("squash! Add parser\n\nmore", target)).toBe(target);
|
||||
expect(pendingFixup("Something else", target)).toBeNull();
|
||||
expect(pendingFixup("fixup! Add parser", null)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,121 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { RemoteOp } from "@/bindings";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
ask: vi.fn(),
|
||||
ops: [] as Array<{ repo: string | null; op: RemoteOp }>,
|
||||
/** Results of the coming pushes, in order: an error message, or null for success. */
|
||||
pushes: [] as Array<string | null>,
|
||||
settings: [] as Array<[string, string]>,
|
||||
}));
|
||||
|
||||
vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage: (line: string) => void = () => {};
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data });
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsBranchInfo: () =>
|
||||
ok({ head: "main", headCommit: "c1", upstream: "origin/main", ahead: 1, behind: 0, operation: null }),
|
||||
vcsRemote: (repo: string | null, _request: number, op: RemoteOp) => {
|
||||
mocks.ops.push({ repo, op });
|
||||
const error = op.op === "push" ? (mocks.pushes.shift() ?? null) : null;
|
||||
return error ? Promise.resolve({ status: "error", error: { kind: "failed", message: error } }) : ok(null);
|
||||
},
|
||||
vcsLog: () => ok([]),
|
||||
vcsStatus: () => ok([]),
|
||||
settingsSet: (_scope: string, key: string, value: string) => {
|
||||
mocks.settings.push([key, value]);
|
||||
return ok({});
|
||||
},
|
||||
cancelRequest: () => ok(null),
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@/workbench/messages", () => ({ ask: mocks.ask, showError: vi.fn() }));
|
||||
|
||||
import { provideNotificationService } from "@/workbench/contributions";
|
||||
import { pushWithAutoUpdate } from "../remoteUi";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const REJECTED = " ! [rejected] main -> main (fetch first)";
|
||||
const STALE = " ! [rejected] main -> main (stale info)";
|
||||
const push = { op: "push", force_with_lease: false, set_upstream: false, tags: null } as const;
|
||||
const kinds = () => mocks.ops.map((o) => (o.op.op === "pull" ? `pull:${o.op.rebase ? "rebase" : "merge"}` : o.op.op));
|
||||
type Note = { title: string; actions?: Array<{ label: string }> };
|
||||
let notes: Note[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.ask.mockReset();
|
||||
mocks.ops = [];
|
||||
mocks.pushes = [];
|
||||
mocks.settings = [];
|
||||
notes = [];
|
||||
useVcs.setState({ roots: ["/a", "/b"], remoteBusy: null });
|
||||
provideNotificationService({ notify: (n) => void notes.push(n as Note), expire: () => {} });
|
||||
});
|
||||
|
||||
describe("a push rejected because the remote has new commits", () => {
|
||||
it("asks how to update, updates every repository and pushes again", async () => {
|
||||
mocks.pushes = [REJECTED];
|
||||
mocks.ask.mockResolvedValue({ button: "rebase", checked: false });
|
||||
expect(await pushWithAutoUpdate(push, "main → origin/main", "/a")).toBe(true);
|
||||
expect(mocks.ask).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.ask.mock.calls[0]![0].title).toBe("Push Rejected");
|
||||
expect(kinds()).toEqual(["push", "pull:rebase", "pull:rebase", "push"]);
|
||||
expect(mocks.ops.filter((o) => o.op.op === "pull").map((o) => o.repo)).toEqual(["/a", "/b"]);
|
||||
// The chosen method becomes the update method; silent updates stay off.
|
||||
expect(mocks.settings).toEqual([["vcs.git.updateMethod", '"rebase"']]);
|
||||
});
|
||||
|
||||
it("keeps the chosen method while the push keeps being rejected, without asking again", async () => {
|
||||
mocks.pushes = [REJECTED, REJECTED];
|
||||
mocks.ask.mockResolvedValue({ button: "merge", checked: true });
|
||||
expect(await pushWithAutoUpdate(push, "", "/a")).toBe(true);
|
||||
expect(mocks.ask).toHaveBeenCalledTimes(1);
|
||||
expect(kinds()).toEqual(["push", "pull:merge", "pull:merge", "push", "pull:merge", "pull:merge", "push"]);
|
||||
expect(mocks.settings).toContainEqual(["vcs.git.autoUpdateOnPushRejected", "true"]);
|
||||
});
|
||||
|
||||
it("gives up after ten attempts", async () => {
|
||||
mocks.pushes = Array.from({ length: 20 }, () => REJECTED);
|
||||
mocks.ask.mockResolvedValue({ button: "merge", checked: false });
|
||||
expect(await pushWithAutoUpdate(push, "", "/a")).toBe(false);
|
||||
expect(kinds().filter((k) => k === "push")).toHaveLength(10);
|
||||
});
|
||||
|
||||
it("doesn't update on Cancel", async () => {
|
||||
mocks.pushes = [REJECTED];
|
||||
mocks.ask.mockResolvedValue({ button: "cancel", checked: false });
|
||||
expect(await pushWithAutoUpdate(push, "", "/a")).toBe(false);
|
||||
expect(kinds()).toEqual(["push"]);
|
||||
// The dialog, not an error balloon, reported the rejection; cancelling it leaves "Push rejected".
|
||||
expect(notes.map((n) => n.title).filter((t) => /fail|reject/i.test(t))).toEqual(["Push rejected"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a rejected forced push", () => {
|
||||
it("is not followed by an update; a stale lease offers to force push anyway", async () => {
|
||||
mocks.pushes = [STALE];
|
||||
expect(await pushWithAutoUpdate({ ...push, force_with_lease: true }, "", "/a")).toBe(false);
|
||||
expect(mocks.ask).not.toHaveBeenCalled();
|
||||
expect(kinds()).toEqual(["push"]);
|
||||
const offer = notes.at(-1)!;
|
||||
expect(offer.actions?.map((a) => a.label)).toEqual(["Force push anyway"]);
|
||||
});
|
||||
|
||||
it("with a lease rejected for another reason only reports it", async () => {
|
||||
mocks.pushes = [REJECTED];
|
||||
expect(await pushWithAutoUpdate({ ...push, force_with_lease: true }, "", "/a")).toBe(false);
|
||||
expect(mocks.ask).not.toHaveBeenCalled();
|
||||
expect(kinds()).toEqual(["push"]);
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,6 @@ import { linkifyIssues } from "../issueLinks";
|
||||
import {
|
||||
defaultPushChecked,
|
||||
isProtectedBranch,
|
||||
isLeaseRejected,
|
||||
isPushRejected,
|
||||
pushCandidates,
|
||||
pushRepoCommits,
|
||||
@@ -74,16 +73,6 @@ describe("git settings helpers", () => {
|
||||
it("recognises rejected pushes", () => {
|
||||
expect(isPushRejected(" ! [rejected] main -> main (fetch first)")).toBe(true);
|
||||
expect(isPushRejected("Permission denied (publickey)")).toBe(false);
|
||||
expect(isPushRejected(" ! [rejected] main -> main (non-fast-forward)")).toBe(true);
|
||||
// A tag that exists on the remote, a hook or the server refusing: updating doesn't help.
|
||||
expect(
|
||||
isPushRejected(
|
||||
" ! [rejected] v1 -> v1 (already exists)\nhint: Updates were rejected because the tag already exists in the remote.",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(isPushRejected(" ! [remote rejected] main -> main (pre-receive hook declined)")).toBe(false);
|
||||
expect(isPushRejected(" ! [rejected] main -> main (stale info)")).toBe(false);
|
||||
expect(isLeaseRejected(" ! [rejected] main -> main (stale info)")).toBe(true);
|
||||
});
|
||||
|
||||
it("propagates folder colours only when enabled", () => {
|
||||
|
||||
@@ -4,7 +4,6 @@ import { executeAction } from "@/platform/actions";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import { isFavoriteBranch } from "./branches";
|
||||
import {
|
||||
branchRef,
|
||||
checkoutAndRebase,
|
||||
checkoutBranch,
|
||||
checkoutDetached,
|
||||
@@ -12,9 +11,6 @@ import {
|
||||
deleteBranch,
|
||||
deleteInRepos,
|
||||
deleteRemoteBranch,
|
||||
deleteTag,
|
||||
knownRemotes,
|
||||
pushTag,
|
||||
mergeInRepos,
|
||||
newBranchInRepos,
|
||||
rebaseInRepos,
|
||||
@@ -85,11 +81,8 @@ export function branchMenu(b: Branch, current: string | null, done: () => void =
|
||||
{ label: "Show Diff with Working Tree", run: run(() => showDiffWithWorkingTree(b.name)) },
|
||||
history,
|
||||
{ kind: "separator" },
|
||||
{ label: tx`Rebase '${cur}' onto '${b.name}'`, run: run(() => rebaseOnto(b.name, branchRef(b.name, b.remote))) },
|
||||
{
|
||||
label: tx`Merge '${b.name}' into '${cur}'`,
|
||||
run: run(() => mergeIntoCurrent(b.name, undefined, branchRef(b.name, b.remote))),
|
||||
},
|
||||
{ label: tx`Rebase '${cur}' onto '${b.name}'`, run: run(() => rebaseOnto(b.name)) },
|
||||
{ label: tx`Merge '${b.name}' into '${cur}'`, run: run(() => mergeIntoCurrent(b.name)) },
|
||||
];
|
||||
if (b.remote)
|
||||
items.push(
|
||||
@@ -129,12 +122,6 @@ export function tagMenu(tag: string, done: () => void = () => {}): MenuItem[] {
|
||||
{ label: "Compare with Current", icon: "diff", run: run(() => showCompareBranches(tag)) },
|
||||
{ label: "Show Diff with Working Tree", run: run(() => showDiffWithWorkingTree(tag)) },
|
||||
{ label: "Show History", icon: "history", run: run(() => executeAction("vcs.showLog", { branch: tag })) },
|
||||
...knownRemotes().flatMap((remote, i): MenuItem[] => [
|
||||
...(i === 0 ? [{ kind: "separator" } as const] : []),
|
||||
{ label: tx`Push to ${remote}`, icon: "git-push", run: run(() => pushTag(tag, remote)) },
|
||||
]),
|
||||
{ kind: "separator" },
|
||||
{ label: "Delete", danger: true, icon: "trash", run: run(() => deleteTag(tag)) },
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Branch operations (checkout, create, merge, rebase, update, delete) with recents and favorites. */
|
||||
import { create } from "zustand";
|
||||
import type { Branch, BranchInfo, CheckoutOptions } from "@/bindings";
|
||||
import type { Branch, CheckoutOptions } from "@/bindings";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
@@ -98,16 +98,6 @@ async function performCheckout(
|
||||
});
|
||||
await openConflictsInstead();
|
||||
return true;
|
||||
case "untrackedFiles": {
|
||||
const files = outcome.files.join("\n");
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "error",
|
||||
title: "Untracked files prevent checkout",
|
||||
body: tx`The following untracked working tree files would be overwritten by checkout:\n${files}\nPlease move or remove them before you switch branches.`,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
case "localChanges": {
|
||||
const mode = await askSmartCheckout(outcome.files);
|
||||
if (!mode) return false;
|
||||
@@ -203,12 +193,8 @@ export async function checkoutRevision() {
|
||||
}
|
||||
|
||||
export function conflictActions(message: string) {
|
||||
if (conflictedFiles().length || /conflict/i.test(message))
|
||||
return [{ label: "Resolve Conflicts…", run: () => void executeAction("vcs.resolveConflicts") }];
|
||||
// Stopped for another reason (the status was refreshed by openConflictsInstead): Abort.
|
||||
const op = useVcs.getState().branch?.operation;
|
||||
return op === "rebase" || op === "merge"
|
||||
? [{ label: "Abort", run: () => void executeAction(`vcs.${op}.abort`) }]
|
||||
return conflictedFiles().length || /conflict/i.test(message)
|
||||
? [{ label: "Resolve Conflicts…", run: () => void executeAction("vcs.resolveConflicts") }]
|
||||
: [];
|
||||
}
|
||||
|
||||
@@ -223,26 +209,21 @@ export async function openConflictsInstead(): Promise<boolean> {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The full ref of a branch, so a tag of the same name isn't taken instead. */
|
||||
export function branchRef(name: string, remote: boolean): string {
|
||||
return remote ? `refs/remotes/${name}` : `refs/heads/${name}`;
|
||||
}
|
||||
|
||||
export async function mergeIntoCurrent(branch: string, repo: string | null = currentRepo(), ref = branch) {
|
||||
export async function mergeIntoCurrent(branch: string, repo: string | null = currentRepo()) {
|
||||
const current = (repo === currentRepo() ? useVcs.getState().branch?.head : null) ?? "HEAD";
|
||||
await saveAll();
|
||||
await runOp(tx`Merge ${branch} into ${current}`, () => call(commands.vcsMerge(repo, ref)), {
|
||||
await runOp(tx`Merge ${branch} into ${current}`, () => call(commands.vcsMerge(repo, branch)), {
|
||||
success: tx`Merged ${branch} into ${current}`,
|
||||
errorActions: conflictActions,
|
||||
onError: openConflictsInstead,
|
||||
});
|
||||
}
|
||||
|
||||
export async function rebaseOnto(branch: string, ref = branch) {
|
||||
export async function rebaseOnto(branch: string) {
|
||||
const repo = currentRepo();
|
||||
const current = useVcs.getState().branch?.head ?? "HEAD";
|
||||
await saveAll();
|
||||
await runOp(tx`Rebase ${current} onto ${branch}`, () => call(commands.vcsRebase(repo, ref)), {
|
||||
await runOp(tx`Rebase ${current} onto ${branch}`, () => call(commands.vcsRebase(repo, branch)), {
|
||||
success: tx`Rebased ${current} onto ${branch}`,
|
||||
errorActions: conflictActions,
|
||||
onError: openConflictsInstead,
|
||||
@@ -321,65 +302,6 @@ export async function deleteBranch(name: string) {
|
||||
});
|
||||
}
|
||||
|
||||
/** Remotes of the selected repository, as its remote-tracking branches name them. */
|
||||
export function knownRemotes(): string[] {
|
||||
const names = useVcs
|
||||
.getState()
|
||||
.branches.filter((b) => b.remote)
|
||||
.map((b) => b.name.slice(0, b.name.indexOf("/")))
|
||||
.filter(Boolean);
|
||||
return [...new Set(names)];
|
||||
}
|
||||
|
||||
/** Tag › Delete: deletes the local tag; the notification restores it or deletes it on the remotes too. */
|
||||
export async function deleteTag(name: string) {
|
||||
const repo = currentRepo();
|
||||
const deleted = await runOp(tx`Delete tag ${name}`, () => call(commands.vcsDeleteTag(repo, name)));
|
||||
if (!deleted) return;
|
||||
const remotes = knownRemotes();
|
||||
const key = `vcs.deletedTag.${name}`;
|
||||
const done = () => notifications().expire?.(key);
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "info",
|
||||
key,
|
||||
title: tx`Deleted tag ${name}`,
|
||||
actions: [
|
||||
{
|
||||
label: "Restore",
|
||||
run: () => {
|
||||
done();
|
||||
void runOp(tx`Restore tag ${name}`, () => call(commands.vcsRestoreTag(repo, deleted)), {
|
||||
success: tx`Restored tag ${name}`,
|
||||
});
|
||||
},
|
||||
},
|
||||
...(remotes.length
|
||||
? [
|
||||
{
|
||||
label: remotes.length === 1 ? "Delete on Remote" : "Delete on Remotes",
|
||||
run: () => {
|
||||
done();
|
||||
void deleteRemoteTag(name, remotes, repo);
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteRemoteTag(tag: string, remotes: readonly string[], repo: string | null) {
|
||||
for (const remote of remotes) {
|
||||
if (!(await runRemote({ op: "deleteRemoteTag", tag, remote }, `${remote}: ${tag}`, [repo]))) return;
|
||||
}
|
||||
}
|
||||
|
||||
/** Push Tag › Push to `remote`. */
|
||||
export async function pushTag(tag: string, remote: string) {
|
||||
await runRemote({ op: "pushTag", tag, remote }, `${tag} → ${remote}`);
|
||||
}
|
||||
|
||||
/** Deletes a branch on its remote (`git push <remote> --delete <name>`); `name` is e.g. `origin/feature`. */
|
||||
export async function deleteRemoteBranch(name: string) {
|
||||
const ok = await confirmDialog({
|
||||
@@ -401,7 +323,7 @@ export async function checkoutAndRebase(name: string) {
|
||||
rememberBranch(current);
|
||||
rememberBranch(name);
|
||||
await refreshNow();
|
||||
await rebaseOnto(current, branchRef(current, false));
|
||||
await rebaseOnto(current);
|
||||
}
|
||||
|
||||
/** Update for a branch other than the current one: fast-forwards it to its upstream. */
|
||||
@@ -422,86 +344,25 @@ function inRepos(done: number, total: number): string {
|
||||
return done === total ? `in ${total} repositories` : `in ${done} of ${total} repositories`;
|
||||
}
|
||||
|
||||
interface Rollback<T> {
|
||||
/** What rolling back does, for the question: "check out the previous branch again". */
|
||||
undo: string;
|
||||
run: (root: string, result: T, before: BranchInfo) => Promise<unknown>;
|
||||
}
|
||||
|
||||
const branchInfo = (root: string) => call(commands.vcsBranchInfo(root)).catch(() => null);
|
||||
|
||||
/**
|
||||
* Runs `step` in each repository in turn, stopping at the first one that fails (its
|
||||
* error is reported by `step`), then reports how many repositories it was done in.
|
||||
* When it failed after succeeding in some repositories, offers to roll those back so
|
||||
* the repositories don't diverge (not when the failed one stopped on conflicts).
|
||||
*/
|
||||
async function eachRepo<T>(
|
||||
roots: readonly string[],
|
||||
step: (root: string) => Promise<T | undefined>,
|
||||
title: string,
|
||||
rollback?: Rollback<T>,
|
||||
) {
|
||||
const done: { root: string; result: T; before: BranchInfo }[] = [];
|
||||
let failed: string | null = null;
|
||||
async function eachRepo(roots: readonly string[], step: (root: string) => Promise<boolean>, title: string) {
|
||||
let done = 0;
|
||||
for (const root of roots) {
|
||||
const before = await branchInfo(root);
|
||||
const result = await step(root);
|
||||
if (result === undefined || !before) {
|
||||
failed = root;
|
||||
break;
|
||||
}
|
||||
done.push({ root, result, before });
|
||||
if (!(await step(root))) break;
|
||||
done++;
|
||||
}
|
||||
await refreshNow();
|
||||
if (failed && done.length && rollback && !(await branchInfo(failed))?.operation) {
|
||||
const succeeded = done.map((d) => repoName(d.root)).join(", ");
|
||||
const failedName = repoName(failed);
|
||||
const r = await ask({
|
||||
title: "Rollback",
|
||||
body: tx`The operation failed in ${failedName}, but succeeded in ${succeeded}. Roll those back (${rollback.undo}) so the repositories don't diverge?`,
|
||||
icon: "warning",
|
||||
buttons: [
|
||||
{ id: "rollback", label: "Rollback", primary: true },
|
||||
{ id: "keep", label: "Don't Rollback" },
|
||||
],
|
||||
});
|
||||
if (r.button === "rollback") {
|
||||
for (const d of done.reverse()) {
|
||||
const repo = repoName(d.root);
|
||||
await runOp(tx`Rollback (${repo})`, () => rollback.run(d.root, d.result, d.before), { refresh: false });
|
||||
}
|
||||
await refreshNow();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (done.length)
|
||||
notifications().notify({ group: "vcs", level: "info", title: `${title} ${inRepos(done.length, roots.length)}` });
|
||||
}
|
||||
|
||||
/** HEAD as a checkout target: the branch, or the commit on a detached HEAD. */
|
||||
const headRef = (b: BranchInfo) => b.head ?? b.headCommit ?? "HEAD";
|
||||
|
||||
async function checkoutBack(root: string, before: BranchInfo) {
|
||||
await call(commands.vcsCheckout(root, headRef(before), false, { mode: "smart", diverged: null }));
|
||||
}
|
||||
|
||||
/** Moves HEAD back to where it was before a merge or rebase, keeping local changes. */
|
||||
async function resetBack(root: string, before: BranchInfo) {
|
||||
const after = (await branchInfo(root))?.headCommit;
|
||||
if (before.headCommit && after) await call(commands.vcsRestoreHead(root, before.headCommit, after));
|
||||
if (done) notifications().notify({ group: "vcs", level: "info", title: `${title} ${inRepos(done, roots.length)}` });
|
||||
}
|
||||
|
||||
/** Checks out `name` (local, or remote: its local namesake) in every repository of `roots`. */
|
||||
export async function checkoutInRepos(name: string, roots: readonly string[]) {
|
||||
const label = useVcs.getState().branches.some((b) => b.remote && b.name === name) ? shortRemoteName(name) : name;
|
||||
const previous = useVcs.getState().branch?.head;
|
||||
await eachRepo(
|
||||
roots,
|
||||
async (root) => ((await performCheckout(name, () => "", root, true)) ? true : undefined),
|
||||
`Checked out ${label}`,
|
||||
{ undo: tx("check out the previous branch again"), run: (root, _, before) => checkoutBack(root, before) },
|
||||
);
|
||||
await eachRepo(roots, (root) => performCheckout(name, () => "", root, true), `Checked out ${label}`);
|
||||
rememberBranch(previous);
|
||||
rememberBranch(useVcs.getState().branch?.head);
|
||||
}
|
||||
@@ -524,18 +385,15 @@ export async function newBranchInRepos(roots: readonly string[], from?: string)
|
||||
if (r.checked) await saveAll();
|
||||
await eachRepo(
|
||||
roots,
|
||||
(root) =>
|
||||
runOp(tx`Create branch ${name}`, () => call(commands.vcsCreateBranch(root, name, from ?? null, r.checked)), {
|
||||
refresh: false,
|
||||
}).then((done) => (done === undefined ? undefined : true)),
|
||||
async (root) =>
|
||||
(await runOp(
|
||||
tx`Create branch ${name}`,
|
||||
() => call(commands.vcsCreateBranch(root, name, from ?? null, r.checked)),
|
||||
{
|
||||
refresh: false,
|
||||
},
|
||||
)) !== undefined,
|
||||
r.checked ? `Created and checked out ${name}` : `Created branch ${name}`,
|
||||
{
|
||||
undo: tx`delete branch ${name}`,
|
||||
run: async (root, _, before) => {
|
||||
if (r.checked) await checkoutBack(root, before);
|
||||
await call(commands.vcsDeleteBranch(root, name));
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -544,14 +402,13 @@ export async function mergeInRepos(branch: string, roots: readonly string[]) {
|
||||
await saveAll();
|
||||
await eachRepo(
|
||||
roots,
|
||||
(root) =>
|
||||
runOp(tx`Merge ${branch} (${repoName(root)})`, () => call(commands.vcsMerge(root, branch)), {
|
||||
async (root) =>
|
||||
(await runOp(tx`Merge ${branch} (${repoName(root)})`, () => call(commands.vcsMerge(root, branch)), {
|
||||
refresh: false,
|
||||
errorActions: conflictActions,
|
||||
onError: openConflictsInstead,
|
||||
}).then((done) => (done === undefined ? undefined : true)),
|
||||
})) !== undefined,
|
||||
`Merged ${branch}`,
|
||||
{ undo: tx("reset to the commit before the merge"), run: (root, _, before) => resetBack(root, before) },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -560,14 +417,13 @@ export async function rebaseInRepos(branch: string, roots: readonly string[]) {
|
||||
await saveAll();
|
||||
await eachRepo(
|
||||
roots,
|
||||
(root) =>
|
||||
runOp(tx`Rebase onto ${branch} (${repoName(root)})`, () => call(commands.vcsRebase(root, branch)), {
|
||||
async (root) =>
|
||||
(await runOp(tx`Rebase onto ${branch} (${repoName(root)})`, () => call(commands.vcsRebase(root, branch)), {
|
||||
refresh: false,
|
||||
errorActions: conflictActions,
|
||||
onError: openConflictsInstead,
|
||||
}).then((done) => (done === undefined ? undefined : true)),
|
||||
})) !== undefined,
|
||||
`Rebased onto ${branch}`,
|
||||
{ undo: tx("reset to the commit before the rebase"), run: (root, _, before) => resetBack(root, before) },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -582,12 +438,11 @@ export async function deleteInRepos(name: string, roots: readonly string[]) {
|
||||
if (!ok) return;
|
||||
await eachRepo(
|
||||
roots,
|
||||
(root) =>
|
||||
runOp(tx`Delete branch ${name} (${repoName(root)})`, () => call(commands.vcsDeleteBranch(root, name)), {
|
||||
async (root) =>
|
||||
(await runOp(tx`Delete branch ${name} (${repoName(root)})`, () => call(commands.vcsDeleteBranch(root, name)), {
|
||||
refresh: false,
|
||||
}),
|
||||
})) !== undefined,
|
||||
`Deleted branch ${name}`,
|
||||
{ undo: tx`restore branch ${name}`, run: (root, deleted) => call(commands.vcsRestoreBranch(root, deleted)) },
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -76,21 +76,13 @@ export async function commitChanges(): Promise<string | undefined> {
|
||||
const id = await runOp(
|
||||
amend ? "Amend commit" : "Commit",
|
||||
async () => {
|
||||
// The commit is made from a copy of the index, so changes left out keep their
|
||||
// staged state and the other repositories' indexes stay as they are.
|
||||
if (plan.unstage.length) await call(commands.vcsUnstage(plan.unstage));
|
||||
const stage = [...plan.stage, ...partial.whole];
|
||||
if (stage.length) await call(commands.vcsStage(stage));
|
||||
let id = "";
|
||||
for (const repo of repos) {
|
||||
const inRepo = (path: string) => repos.length === 1 || (rootOf(path, roots) ?? null) === repo;
|
||||
const options = {
|
||||
amend,
|
||||
signOff,
|
||||
author: author.trim() || null,
|
||||
runHooks,
|
||||
partial: partial.files.filter((f) => inRepo(f.path)),
|
||||
stage: stage.filter(inRepo),
|
||||
exclude: plan.exclude.filter(inRepo),
|
||||
};
|
||||
const files = partial.files.filter((f) => (rootOf(f.path, roots) ?? null) === repo || repos.length === 1);
|
||||
const options = { amend, signOff, author: author.trim() || null, runHooks, partial: files };
|
||||
id = await call(commands.vcsCommit(repo, message.trim(), options));
|
||||
}
|
||||
return id;
|
||||
|
||||
@@ -11,7 +11,7 @@ import { setLocalChanges, type LocalChangelist } from "@/workbench/contributions
|
||||
import type { CheckState } from "./changes";
|
||||
import { groupOf } from "./changes";
|
||||
import { effectiveKind, relTo, stripSlash } from "./model";
|
||||
import { localChangesMayBeAside, useVcs } from "./store";
|
||||
import { useVcs } from "./store";
|
||||
|
||||
export const DEFAULT_LIST_ID = "default";
|
||||
export const DEFAULT_LIST_NAME = "Changes";
|
||||
@@ -32,20 +32,14 @@ export function activeList(state: ChangelistState): Changelist {
|
||||
|
||||
/**
|
||||
* Pins files that just became changed to the active list and forgets files that
|
||||
* are no longer changed, unless `keepGone`: while a merge, rebase or update has the
|
||||
* local changes put aside, their files keep their lists for when they come back.
|
||||
* Returns null when nothing changed.
|
||||
* are no longer changed. Returns null when nothing changed.
|
||||
*/
|
||||
export function syncAssignments(
|
||||
state: ChangelistState,
|
||||
changed: readonly string[],
|
||||
keepGone = false,
|
||||
): ChangelistState | null {
|
||||
export function syncAssignments(state: ChangelistState, changed: readonly string[]): ChangelistState | null {
|
||||
const live = new Set(changed);
|
||||
const files: Record<string, string> = {};
|
||||
let dirty = false;
|
||||
for (const [rel, id] of Object.entries(state.files ?? {})) {
|
||||
if ((keepGone || live.has(rel)) && state.lists.some((l) => l.id === id)) files[rel] = id;
|
||||
if (live.has(rel) && state.lists.some((l) => l.id === id)) files[rel] = id;
|
||||
else dirty = true;
|
||||
}
|
||||
for (const rel of changed) {
|
||||
@@ -201,7 +195,7 @@ export function installChangelists(): () => void {
|
||||
const sync = () => {
|
||||
const { status, root, available, statusLoaded } = useVcs.getState();
|
||||
if (!available || !root || !statusLoaded || !useChangelists.getState().loaded) return;
|
||||
const next = syncAssignments(useChangelists.getState().state, changedRels(status, root), localChangesMayBeAside());
|
||||
const next = syncAssignments(useChangelists.getState().state, changedRels(status, root));
|
||||
if (next) updateChangelists(() => next);
|
||||
};
|
||||
const load = () => {
|
||||
|
||||
@@ -15,10 +15,9 @@ import {
|
||||
useChangelists,
|
||||
validateListName,
|
||||
} from "./changelists";
|
||||
import { groupOf } from "./changes";
|
||||
import { useCommit } from "./commitStore";
|
||||
import { confirmDialog, openDialog } from "./dialogs";
|
||||
import { fileCount, stripSlash } from "./model";
|
||||
import { fileCount } from "./model";
|
||||
import { useVcs } from "./store";
|
||||
import styles from "./common.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -185,15 +184,6 @@ export function commitChangelist(id: string) {
|
||||
useCommit.setState((s) => ({ checks, tab: "changes", focusTick: s.focusTick + 1 }));
|
||||
}
|
||||
|
||||
/** Commit File…: include exactly these changes (absolute paths) and focus the message. */
|
||||
export function commitFiles(paths: readonly string[]) {
|
||||
const chosen = new Set(paths.map(stripSlash));
|
||||
const checks = new Map<string, "all" | "none">();
|
||||
for (const f of useVcs.getState().status)
|
||||
if (groupOf(f) === "changes") checks.set(f.path, chosen.has(stripSlash(f.path)) ? "all" : "none");
|
||||
useCommit.setState((s) => ({ checks, tab: "changes", focusTick: s.focusTick + 1 }));
|
||||
}
|
||||
|
||||
/** Moves files (absolute paths) to a list. */
|
||||
export function moveToChangelist(paths: readonly string[], id: string) {
|
||||
const rels = paths.map(relOf);
|
||||
@@ -206,94 +196,43 @@ export function showMoveToChangelist(paths: readonly string[]) {
|
||||
notifications().notify({ group: "vcs", level: "info", title: "Select changes to move" });
|
||||
return;
|
||||
}
|
||||
const rels = paths.map(relOf);
|
||||
openDialog((close) => (
|
||||
<TargetListDialog
|
||||
title="Move Changes to Another Changelist"
|
||||
hint={fileCount(paths.length)}
|
||||
exclude={paths.map(
|
||||
(p) => useChangelists.getState().state.files?.[relOf(p)] ?? useChangelists.getState().state.active,
|
||||
)}
|
||||
onClose={close}
|
||||
onChoose={(id) => updateChangelists((s) => moveFiles(s, rels, id))}
|
||||
/>
|
||||
));
|
||||
openDialog((close) => <MoveDialog paths={paths} onClose={close} />);
|
||||
}
|
||||
|
||||
/**
|
||||
* Select Target Changelist (Undo Commit): an existing list, or a new one named
|
||||
* `suggestedName`. Resolves the chosen list's id (created if new), or null.
|
||||
*/
|
||||
export function chooseTargetChangelist(suggestedName: string): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
let chosen: string | null = null;
|
||||
openDialog((close) => (
|
||||
<TargetListDialog
|
||||
title="Select Target Changelist"
|
||||
suggestedName={suggestedName}
|
||||
onClose={() => {
|
||||
close();
|
||||
resolve(chosen);
|
||||
}}
|
||||
onChoose={(id) => {
|
||||
chosen = id;
|
||||
}}
|
||||
/>
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
function TargetListDialog({
|
||||
title,
|
||||
hint,
|
||||
exclude = [],
|
||||
suggestedName = "",
|
||||
onChoose,
|
||||
onClose,
|
||||
}: {
|
||||
title: string;
|
||||
hint?: string;
|
||||
/** Lists the changes are all in already (not offered). */
|
||||
exclude?: readonly string[];
|
||||
suggestedName?: string;
|
||||
onChoose: (id: string) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
function MoveDialog({ paths, onClose }: { paths: readonly string[]; onClose: () => void }) {
|
||||
const state = useChangelists((s) => s.state);
|
||||
const [currentLists] = useState(() => new Set(exclude));
|
||||
const currentLists = new Set(paths.map((p) => state.files?.[relOf(p)] ?? state.active));
|
||||
const others = state.lists.filter((l) => !(currentLists.size === 1 && currentLists.has(l.id)));
|
||||
const [mode, setMode] = useState<"existing" | "new">(others.length ? "existing" : "new");
|
||||
const [target, setTarget] = useState((others.find((l) => l.id === state.active) ?? others[0])?.id ?? state.active);
|
||||
const [value, setValue] = useState<FormValue>({ name: suggestedName, comment: "", active: false });
|
||||
const [target, setTarget] = useState(others[0]?.id ?? state.active);
|
||||
const [value, setValue] = useState<FormValue>({ name: "", comment: "", active: false });
|
||||
const error = mode === "new" ? validateListName(state, value.name) : null;
|
||||
const choose = () => {
|
||||
const move = () => {
|
||||
if (error) return;
|
||||
onClose();
|
||||
const rels = paths.map(relOf);
|
||||
if (mode === "new") {
|
||||
let id = "";
|
||||
updateChangelists((s) => {
|
||||
const r = addList(s, value.name, { comment: value.comment, makeActive: value.active });
|
||||
id = r.id;
|
||||
return r.state;
|
||||
return moveFiles(r.state, rels, r.id);
|
||||
});
|
||||
onChoose(id);
|
||||
} else {
|
||||
onChoose(target);
|
||||
updateChangelists((s) => moveFiles(s, rels, target));
|
||||
}
|
||||
onClose();
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
title={title}
|
||||
title="Move Changes to Another Changelist"
|
||||
onClose={onClose}
|
||||
width={440}
|
||||
buttons={[
|
||||
{ label: "OK", role: "default", disabled: !!error, onClick: choose },
|
||||
{ label: "OK", role: "default", disabled: !!error, onClick: move },
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<div className={styles.form} role="radiogroup" aria-label={tx("Target changelist")}>
|
||||
{hint && <div className={styles.hint}>{hint}</div>}
|
||||
<div className={styles.hint}>{fileCount(paths.length)}</div>
|
||||
<label className={styles.radioRow}>
|
||||
<input
|
||||
type="radio"
|
||||
|
||||
@@ -327,10 +327,8 @@ export function groupFileNodes(roots: readonly ChangeNode[], node: ChangeNode):
|
||||
}
|
||||
|
||||
export interface CommitPlan {
|
||||
/** Included files committed with their working-tree content. */
|
||||
stage: string[];
|
||||
/** Staged files left out of the commit; they stay staged. */
|
||||
exclude: string[];
|
||||
unstage: string[];
|
||||
/** Files that end up in the commit. */
|
||||
included: FileStatus[];
|
||||
/** Absolute paths of included files committed with only some of their hunks. */
|
||||
@@ -359,19 +357,19 @@ export function renamedFromPath(fs: FileStatus): string | null {
|
||||
return root === null ? null : `${root}${fs.renamedFrom}`;
|
||||
}
|
||||
|
||||
/** What the commit takes beyond the index, and what staged changes it leaves out. */
|
||||
/** What to stage / unstage so the index holds exactly the included changes. */
|
||||
export function planCommit(status: readonly FileStatus[], checks: ReadonlyMap<string, CheckState>): CommitPlan {
|
||||
const plan: CommitPlan = { stage: [], exclude: [], included: [], partial: [] };
|
||||
const plan: CommitPlan = { stage: [], unstage: [], included: [], partial: [] };
|
||||
for (const fs of status) {
|
||||
if (!groupOf(fs)) continue;
|
||||
const c = checkOf(fs, checks);
|
||||
const path = stripSlash(fs.path);
|
||||
if (c === "none") {
|
||||
if (fs.staged && fs.staged !== "conflicted") {
|
||||
plan.exclude.push(path);
|
||||
// A staged rename is a deletion + addition: leaving the deletion in would commit it.
|
||||
plan.unstage.push(path);
|
||||
// A staged rename is a deletion + addition: leaving the deletion staged would commit it.
|
||||
const from = renamedFromPath(fs);
|
||||
if (from) plan.exclude.push(from);
|
||||
if (from) plan.unstage.push(from);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
/** Commit tool window state shared with actions (selection, message draft). */
|
||||
import { create } from "zustand";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import type { Commit } from "@/bindings";
|
||||
import type { CheckState } from "./changes";
|
||||
import type { CommitProblem } from "./commitChecks";
|
||||
import { currentRepo, useVcs } from "./store";
|
||||
@@ -38,8 +37,6 @@ interface CommitState {
|
||||
selectedList: string | null;
|
||||
/** Selected shelf tree key: shelf id, optionally followed by NUL and a file path. */
|
||||
selectedShelf: string | null;
|
||||
/** Commit a Fixup… / Squash Into… message was prepared for: offers Commit and Rebase. */
|
||||
fixupTarget: Commit | null;
|
||||
}
|
||||
|
||||
export type CommitTab = "changes" | "shelf" | "stashes";
|
||||
@@ -63,17 +60,8 @@ export const useCommit = create<CommitState>(() => ({
|
||||
tab: "changes",
|
||||
selectedList: null,
|
||||
selectedShelf: null,
|
||||
fixupTarget: null,
|
||||
}));
|
||||
|
||||
/** The Fixup… / Squash Into… target while the message still is the one prepared for it. */
|
||||
export function pendingFixup(message: string, target: Commit | null): Commit | null {
|
||||
if (!target) return null;
|
||||
return message.startsWith(`fixup! ${target.summary}`) || message.startsWith(`squash! ${target.summary}`)
|
||||
? target
|
||||
: null;
|
||||
}
|
||||
|
||||
function readBool(key: string, fallback: boolean): boolean {
|
||||
try {
|
||||
const v = localStorage.getItem(key);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** "Resolve Conflicts" dialog and in-editor conflict resolution actions. */
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import type { FileStatus } from "@/bindings";
|
||||
import { activeEditor } from "@/editor/api";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
@@ -9,28 +9,13 @@ import { blockAt, parseConflicts, resolutionText, type Resolution } from "./conf
|
||||
import { openDialog } from "./dialogs";
|
||||
import { mergeInput } from "./mergeKind";
|
||||
import { baseName, dirName, relTo, stripSlash } from "./model";
|
||||
import { controlLabel, controlOperation, inProgress, operationTitle, type InProgress } from "./operations";
|
||||
import { controlLabel, controlOperation, inProgress, operationTitle } from "./operations";
|
||||
import { runOp, writeFileText } from "./ops";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { conflictedFiles, useVcs } from "./store";
|
||||
import styles from "./common.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
/**
|
||||
* The stopped rebase / cherry-pick / revert whose conflicts are being resolved from the
|
||||
* Conflicts dialog (there or in the merge editor it opened): once the last one is
|
||||
* resolved the operation continues by itself, as IDEA does. Closing the dialog
|
||||
* without resolving them leaves it stopped.
|
||||
*/
|
||||
let continueWhenResolved: InProgress | null = null;
|
||||
|
||||
/** The operation to continue now that its conflicts are resolved, if any (only once). */
|
||||
export function takeContinueWhenResolved(): InProgress | null {
|
||||
const op = continueWhenResolved;
|
||||
continueWhenResolved = null;
|
||||
return op;
|
||||
}
|
||||
|
||||
export function showConflictsDialog() {
|
||||
if (!conflictedFiles().length) {
|
||||
notifications().notify({ group: "vcs", level: "info", title: "No merge conflicts" });
|
||||
@@ -43,8 +28,7 @@ export function openMergeEditor(path: string) {
|
||||
void editorService().openInput(mergeInput(stripSlash(path)), { focus: true });
|
||||
}
|
||||
|
||||
/** Accept Yours / Accept Theirs for a whole conflicted file. */
|
||||
export async function acceptSide(f: FileStatus, side: "ours" | "theirs") {
|
||||
async function acceptSide(f: FileStatus, side: "ours" | "theirs") {
|
||||
const path = stripSlash(f.path);
|
||||
await runOp(
|
||||
side === "ours" ? tx`Accept yours for ${baseName(path)}` : tx`Accept theirs for ${baseName(path)}`,
|
||||
@@ -67,20 +51,6 @@ function ConflictsDialog({ onClose }: { onClose: () => void }) {
|
||||
const files = useVcs((s) => s.status).filter((f) => f.unstaged === "conflicted");
|
||||
const root = useVcs((s) => s.root) ?? "";
|
||||
const op = useVcs((s) => inProgress(s.branch?.operation));
|
||||
useEffect(() => {
|
||||
continueWhenResolved = op && op !== "merge" ? op : null;
|
||||
}, [op]);
|
||||
// The last conflict resolved here: the operation continues (see onConflictsCleared), the dialog goes.
|
||||
const hadConflicts = useRef(files.length > 0);
|
||||
useEffect(() => {
|
||||
if (hadConflicts.current && !files.length && op && op !== "merge") onClose();
|
||||
hadConflicts.current = files.length > 0;
|
||||
}, [files.length, op, onClose]);
|
||||
// Closed without going on to resolve them: the operation stays stopped.
|
||||
const dismiss = () => {
|
||||
continueWhenResolved = null;
|
||||
onClose();
|
||||
};
|
||||
const head = useVcs((s) => s.branch?.head ?? null);
|
||||
const [active, setActive] = useState(0);
|
||||
const current = files[Math.min(active, files.length - 1)];
|
||||
@@ -95,7 +65,7 @@ function ConflictsDialog({ onClose }: { onClose: () => void }) {
|
||||
<Dialog
|
||||
open
|
||||
title="Conflicts"
|
||||
onClose={dismiss}
|
||||
onClose={onClose}
|
||||
width={600}
|
||||
footerStart={<span className={styles.hint}>{op ? operationTitle(op, head) : ""}</span>}
|
||||
buttons={[
|
||||
@@ -106,7 +76,7 @@ function ConflictsDialog({ onClose }: { onClose: () => void }) {
|
||||
role: "default" as const,
|
||||
autoFocus: true,
|
||||
onClick: () => {
|
||||
dismiss();
|
||||
onClose();
|
||||
conclude.run();
|
||||
},
|
||||
},
|
||||
|
||||
@@ -25,7 +25,7 @@ import { controlLabel, controlOperation, inProgress } from "./operations";
|
||||
import { annotationsShown, blameSlot } from "./blame";
|
||||
import { inlineBlame } from "./inlineBlame";
|
||||
import { BranchWidget, useBranchesPopup } from "./BranchWidget";
|
||||
import { showConflictsDialog, takeContinueWhenResolved } from "./conflictsUi";
|
||||
import { showConflictsDialog } from "./conflictsUi";
|
||||
import { registerCompareActions } from "./compare";
|
||||
import { DIFF_KIND, diffTitle, type DiffData } from "./diffInput";
|
||||
import { VcsDialogHost } from "./dialogs";
|
||||
@@ -186,13 +186,8 @@ export function activate(): () => void {
|
||||
|
||||
onConflictsCleared(() => {
|
||||
notifications().expire?.("vcs.conflicts");
|
||||
// As IDEA does once the last conflict is resolved: offer to continue the stopped operation.
|
||||
const op = inProgress();
|
||||
// Resolved from the Conflicts dialog: the stopped rebase / cherry-pick goes on by itself.
|
||||
if (op && takeContinueWhenResolved() === op) {
|
||||
void controlOperation("continue", op);
|
||||
return;
|
||||
}
|
||||
// Otherwise, as IDEA does once the last conflict is resolved: offer to continue it.
|
||||
if (op)
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
|
||||
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача