Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai a466ec7425 fix(i18n): translate the GitHub HTTPS failure hint 2026-12-01 01:52:23 +08:00
l0ng-ai 98e375f524 Merge remote-tracking branch 'origin/main' into pr7061 2026-12-01 01:46:38 +08:00
l0ng-ai 04a4d98d68 fix(vcs): open the Log User filter without waiting for every author (#7095)
The Log's User filter popup waited for git log --all to list every author before opening, which takes 8-10 s on a history of 500K+ commits, on every open.

The popup now opens at once with the authors already known (loaded commits plus each repository's last full list). The full list is fetched in the background, reusing a running fetch and a list younger than five minutes, and only Select..., which shows every author, waits for it.

Fixes #7064
2026-12-01 01:44:26 +08:00
l0ng-ai 9a984f64a3 fix(vcs): keep No Merges fast on long pull-request histories (#7094)
With No Merges on, a hidden commit's graph parents are projected onto its nearest shown ancestors. On a pull-request history (M_k = merge(M_k-1, F_k)) each hidden merge projected onto all older features, because the projection of M_k-1 was kept next to F_k although M_k-1 is F_k's own parent. The lists grew with every merge and the first page walked the whole history, so a 500K-commit repository never finished loading.

Before projecting through a hidden commit, parents that are ancestors of another of its parents are dropped (a bounded walk that keeps the parent when unsure). The graph builder and the filtered log view (path, date and author filters share the projection) both apply it.

Fixes #7063
2026-12-01 01:39:39 +08:00
l0ng-ai 38a964040b fix(vcs): guide GitHub HTTPS failures to project account settings 2026-11-30 22:01:40 +08:00
15 змінених файлів з 541 додано та 25 видалено

No files matched your search

+108 -2
Переглянути файл
@@ -920,6 +920,7 @@ fn log_indexed_rows(
text,
matches: HashMap::new(),
projected: HashMap::new(),
pruned: HashMap::new(),
cancel,
index,
table: table.as_ref(),
@@ -1010,6 +1011,7 @@ fn sort_subset(
let mut children = vec![0usize; ids.len()];
let mut times = Vec::with_capacity(ids.len());
let mut projected: HashMap<ObjectId, Vec<usize>> = HashMap::new();
let mut pruned: HashMap<ObjectId, Vec<ObjectId>> = HashMap::new();
for id in &ids {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
@@ -1071,11 +1073,27 @@ fn sort_subset(
.collect()
};
if !expanded {
let ancestors = without_redundant_parents(ancestors, cancel, |id| {
if let Some((ps, time)) = nodes.get(&id) {
return Ok(Some((
if shallow.contains(&id) { Vec::new() } else { ps.clone() },
*time,
)));
}
let Ok(commit) = repo.find_commit(id) else { return Ok(None) };
let parents = if shallow.contains(&id) {
Vec::new()
} else {
commit.parent_ids().map(|p| p.detach()).collect()
};
Ok(Some((parents, commit.time().map(|t| t.seconds).unwrap_or(0))))
})?;
stack.push((curr, true));
stack.extend(ancestors.iter().rev().map(|&p| (p, false)));
pruned.insert(curr, ancestors);
} else {
let mut combined = Vec::new();
for a in ancestors {
for a in pruned.remove(&curr).unwrap_or(ancestors) {
for &p in projected.get(&a).into_iter().flatten() {
if !combined.contains(&p) {
combined.push(p);
@@ -1177,6 +1195,70 @@ fn sort_subset(
/// Visibility and graph projection share exactly the same predicates. Revision parents
/// remain immutable; only graph parents skip hidden commits. Memoisation avoids walking
/// the same hidden ancestry for each visible child, without a truncation limit.
/// How many commits one ancestry check of [`without_redundant_parents`] may walk.
const REDUNDANT_PARENT_WALK: usize = 2_000;
/// `parents` of a commit the graph hides, without those that are ancestors of another of them:
/// whatever such a parent leads to is reached through the other one too. Without this, hiding the
/// merges of a pull-request history (`M_k = merge(M_k-1, F_k)`) projects every merge onto all older
/// features, so the projection grows with each merge and a long history never finishes.
/// `lookup` gives a commit's parents and time (`None`: not available). Each check walks back from
/// the other parent, skipping commits older than the candidate, for at most
/// [`REDUNDANT_PARENT_WALK`] commits; when unsure the parent is kept.
fn without_redundant_parents(
mut parents: Vec<ObjectId>,
cancel: &CancellationToken,
mut lookup: impl FnMut(ObjectId) -> IdeResult<Option<(Vec<ObjectId>, i64)>>,
) -> IdeResult<Vec<ObjectId>> {
let mut seen = HashSet::new();
parents.retain(|p| seen.insert(*p));
if parents.len() < 2 {
return Ok(parents);
}
let mut times = Vec::with_capacity(parents.len());
for p in &parents {
times.push(lookup(*p)?.map(|(_, t)| t));
}
let mut keep = vec![true; parents.len()];
for i in 0..parents.len() {
let Some(target_time) = times[i] else { continue };
for j in 0..parents.len() {
if i == j || !keep[j] || times[j].is_some_and(|t| t < target_time) {
continue;
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let (mut stack, mut visited) = (vec![parents[j]], HashSet::new());
let mut found = false;
while let Some(id) = stack.pop() {
if visited.len() >= REDUNDANT_PARENT_WALK {
break;
}
if !visited.insert(id) {
continue;
}
let Some((ps, time)) = lookup(id)? else { continue };
if id != parents[j] && time < target_time {
continue;
}
if ps.contains(&parents[i]) {
found = true;
break;
}
stack.extend(ps);
}
if found {
keep[i] = false;
break;
}
}
}
let mut keep = keep.into_iter();
parents.retain(|_| keep.next().unwrap_or(true));
Ok(parents)
}
struct Visibility<'a> {
speed_refs: &'a HashMap<ObjectId, Vec<String>>,
query: &'a LogQuery,
@@ -1186,6 +1268,8 @@ struct Visibility<'a> {
text: Option<TextFilter>,
matches: HashMap<ObjectId, bool>,
projected: HashMap<ObjectId, Vec<ObjectId>>,
/// The parents a hidden commit projects through, between its two visits.
pruned: HashMap<ObjectId, Vec<ObjectId>>,
cancel: &'a CancellationToken,
index: &'a mut crate::log_index::LogIndex,
table: Option<&'a redb::ReadOnlyTable<&'static str, &'static [u8]>>,
@@ -1272,6 +1356,26 @@ impl Visibility<'_> {
Ok(shown)
}
/// `parents` of a hidden commit without those reachable through another of them.
fn prune(&mut self, repo: &gix::Repository, parents: Vec<ObjectId>) -> IdeResult<Vec<ObjectId>> {
let (index, table, shallow) = (&mut *self.index, self.table, &self.shallow);
without_redundant_parents(parents, self.cancel, |id| {
if let Some((ps, time)) = index.nodes.get(&id) {
return Ok(Some((if shallow.contains(&id) { Vec::new() } else { ps.clone() }, *time)));
}
if !index.has_cached(&id) && !repo.has_object(id) {
return Ok(None);
}
let commit = index.get_with_table(repo, id, table)?;
let parents = if shallow.contains(&id) {
Vec::new()
} else {
commit.parents.iter().map(|p| ObjectId::from_hex(p.as_bytes()).map_err(gx)).collect::<IdeResult<_>>()?
};
Ok(Some((parents, (commit.commit_time_ms / 1000.0) as i64)))
})
}
fn parents(&mut self, repo: &gix::Repository, parents: &[ObjectId]) -> IdeResult<Vec<ObjectId>> {
let parents = if self.query.first_parent { &parents[..parents.len().min(1)] } else { parents };
let mut out = Vec::new();
@@ -1301,11 +1405,13 @@ impl Visibility<'_> {
.collect::<IdeResult<Vec<_>>>()?
};
if !expanded {
let ancestors = self.prune(repo, ancestors)?;
stack.push((id, true));
stack.extend(ancestors.iter().rev().map(|p| (*p, false)));
self.pruned.insert(id, ancestors);
} else {
let mut nearest = Vec::new();
for p in ancestors {
for p in self.pruned.remove(&id).unwrap_or(ancestors) {
for ancestor in self.projected.get(&p).into_iter().flatten() {
if !nearest.contains(ancestor) {
nearest.push(*ancestor);
+54
Переглянути файл
@@ -267,3 +267,57 @@ fn a_user_filter_links_shown_commits_past_hidden_ones() {
assert_eq!(next.iter().map(|c| c.id.clone()).collect::<Vec<_>>(), std::slice::from_ref(&m1));
let _ = m3;
}
/// A pull-request history: each feature commit `F_k` branches from merge `M_k-1` and is merged
/// back as `M_k = merge(M_k-1, F_k)`, written with `git fast-import`. Returns the feature commits
/// newest first.
fn pull_request_history(dir: &Path, merges: usize) -> Vec<String> {
git(dir, &["init", "-q"], None);
let mut stream =
String::from("commit refs/heads/main\nmark :1\ncommitter T <[email protected]> 1000 +0000\ndata 4\nroot\n");
let mut prev = 1;
let mut mark = 1;
for k in 0..merges {
let t = 1001 + 2 * k as i64;
let feature = mark + 1;
let merge = mark + 2;
stream += &format!(
"commit refs/heads/main\nmark :{feature}\ncommitter T <[email protected]> {t} +0000\ndata 1\nf\nfrom :{prev}\n\
commit refs/heads/main\nmark :{merge}\ncommitter T <t@example.com> {} +0000\ndata 1\nm\nfrom :{prev}\nmerge :{feature}\n",
t + 1
);
prev = merge;
mark = merge;
}
let mut child = Command::new("git")
.current_dir(dir)
.args(["fast-import", "--quiet", "--export-marks=marks"])
.stdin(std::process::Stdio::piped())
.spawn()
.unwrap();
std::io::Write::write_all(child.stdin.as_mut().unwrap(), stream.as_bytes()).unwrap();
assert!(child.wait().unwrap().success());
let marks: std::collections::HashMap<usize, String> = std::fs::read_to_string(dir.join("marks"))
.unwrap()
.lines()
.filter_map(|l| l.strip_prefix(':')?.split_once(' ').map(|(m, id)| (m.parse().unwrap(), id.to_string())))
.collect();
(0..merges).rev().map(|k| marks[&(2 + 2 * k)].clone()).collect()
}
#[test]
fn no_merges_on_a_long_pull_request_history_links_each_feature_to_the_previous_one() {
let tmp = tempfile::tempdir().unwrap();
let features = pull_request_history(tmp.path(), 3000);
let repo = Repo::discover(tmp.path()).unwrap().unwrap();
let started = std::time::Instant::now();
let out = repo
.log(&LogQuery { branches: vec!["main".into()], no_merges: true, limit: 100, ..Default::default() })
.unwrap();
let elapsed = started.elapsed();
assert_eq!(ids(&out)[..3], features[..3]);
// Every older feature is reachable through the previous one, so it is the only graph parent.
assert_eq!(parents_of(&out, &features[0]), vec![features[1].clone()]);
assert_eq!(parents_of(&out, &features[1]), vec![features[2].clone()]);
assert!(elapsed < std::time::Duration::from_secs(10), "took {elapsed:?}");
}
+54
Переглянути файл
@@ -51,6 +51,60 @@ test("suggests and configures a project-scoped GitHub account in Settings › Ve
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]);
});
test("Update failure offers project-scoped GitHub account selection", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
let configuredAccount = "";
const status = (): GhProjectAccountStatus => ({
ghInstalled: true,
accounts: [
{ login: "alice", active: true },
{ login: "alice-work", active: false },
],
configuredAccount,
effectiveAccount: configuredAccount || "alice",
suggestedAccount: configuredAccount ? null : "alice-work",
});
Object.assign(window.__ipc.handlers, {
vcs_branch_info: () => ({ head: "main", upstream: "origin/main", headCommit: "c1", operation: null }),
vcs_remote: () => {
throw {
kind: "invalid",
message: "remote: Repository not found.\nfatal: repository 'https://github.com/acme/private.git/' not found",
};
},
gh_project_account_status: () => status(),
gh_set_project_account: ({ account }: { account: string }) => {
configuredAccount = account;
return status();
},
settings_get_global: () => ({}),
window_open_settings: () => {
throw { kind: "unavailable", message: "separate settings window disabled in browser test" };
},
});
const opsModule = "/src/features/vcs/ops.ts";
const { runRemote } = await import(/* @vite-ignore */ opsModule);
await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/dev/acme-api"]);
});
await expect(page.getByText("Update failed", { exact: true })).toBeVisible();
await expect(page.getByText(/Repository not found/)).toBeVisible();
await expect(page.getByText(/alice may not have access/)).toBeVisible();
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([]);
const settingsLink = page.getByRole("button", { name: "GitHub Settings", exact: true });
await expect(settingsLink).toBeVisible();
if (process.env.CAPTURE_GH_AUTH_FAILURE) {
await page.screenshot({ path: process.env.CAPTURE_GH_AUTH_FAILURE, animations: "disabled" });
}
await settingsLink.click();
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("Automatic (alice)");
await dialog.getByRole("button", { name: "Use alice-work for this project" }).click();
await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("alice-work");
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]);
});
test("adds a GitHub account in Settings › Version Control › GitHub with OAuth device-code banner", async ({
workbench: page,
}) => {
+51
Переглянути файл
@@ -0,0 +1,51 @@
import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("@/platform/ipc", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/platform/ipc")>();
return {
...actual,
call: vi.fn(async (r: Promise<unknown>) => r),
commands: { ...actual.commands, vcsLogUsers: vi.fn() },
};
});
import { commands } from "@/platform/ipc";
import { fetchLogUsers, knownLogUsers, resetLogUsers } from "../log/logUsers";
const users = vi.mocked(commands.vcsLogUsers);
afterEach(() => {
resetLogUsers();
users.mockReset();
});
describe("Log User filter authors", () => {
it("knows nothing before the first list and reuses a running fetch", async () => {
let resolve!: (v: string[]) => void;
users.mockReturnValue(new Promise((r) => (resolve = r)) as never);
expect(knownLogUsers("/repo")).toEqual([]);
const a = fetchLogUsers("/repo");
const b = fetchLogUsers("/repo");
expect(users).toHaveBeenCalledTimes(1);
resolve(["Ann <a@x>"]);
expect(await a).toEqual(["Ann <a@x>"]);
expect(await b).toEqual(["Ann <a@x>"]);
expect(knownLogUsers("/repo")).toEqual(["Ann <a@x>"]);
});
it("answers from the known list while it is recent and fetches again later", async () => {
users.mockResolvedValueOnce(["Ann <a@x>"] as never).mockResolvedValueOnce(["Ann <a@x>", "Bob <b@x>"] as never);
await fetchLogUsers("/repo");
expect(await fetchLogUsers("/repo", Date.now() + 60_000)).toEqual(["Ann <a@x>"]);
expect(users).toHaveBeenCalledTimes(1);
expect(await fetchLogUsers("/repo", Date.now() + 10 * 60_000)).toEqual(["Ann <a@x>", "Bob <b@x>"]);
expect(users).toHaveBeenCalledTimes(2);
});
it("keeps the known list when a fetch fails", async () => {
users.mockResolvedValueOnce(["Ann <a@x>"] as never).mockRejectedValueOnce(new Error("git failed") as never);
await fetchLogUsers("/repo");
expect(await fetchLogUsers("/repo", Date.now() + 10 * 60_000)).toEqual(["Ann <a@x>"]);
expect(knownLogUsers("/other")).toEqual([]);
});
});
+108 -2
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { BranchInfo, FetchReport, PushReport, RemoteOp } from "@/bindings";
import type { BranchInfo, FetchReport, GhProjectAccountStatus, PushReport, RemoteOp } from "@/bindings";
let branch: Partial<BranchInfo> = {};
/** What a pull brings in: the head moves to `c2`, with these changed files and commits. */
@@ -10,6 +10,7 @@ let reports: Record<string, PushReport | FetchReport> = {};
let partialReport: PushReport | null = null;
let remoteGate: Promise<void> | null = null;
let remoteRepos: Array<string | null> = [];
const ghAccountStatus = vi.fn();
vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
...(await importOriginal<typeof import("@tauri-apps/api/core")>()),
@@ -51,6 +52,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
vcsDiffRevisions: async () => ({ status: "ok", data: Array.from({ length: pulled.files }, (_, i) => ({ i })) }),
vcsLog: async () => ({ status: "ok", data: Array.from({ length: pulled.commits }, (_, i) => ({ i })) }),
vcsFinishShelfBatch: async () => ({ status: "ok", data: null }),
ghProjectAccountStatus: () => ghAccountStatus(),
cancelRequest: async () => ({ status: "ok", data: null }),
},
};
@@ -73,11 +75,13 @@ import {
import { pushTargets } from "../remoteUi";
import { useVcs } from "../store";
type Note = { title: string; level: string; body?: string };
type Note = { title: string; level: string; body?: string; actions?: Array<{ label: string; run: () => void }> };
let notes: Note[] = [];
beforeEach(() => {
notes = [];
ghAccountStatus.mockReset();
ghAccountStatus.mockResolvedValue({ status: "ok", data: null });
provideNotificationService({ notify: (n) => void notes.push(n as Note), expire: () => {} });
});
@@ -101,6 +105,108 @@ const pushTitle = async () => {
return notes.at(-1)!.title;
};
describe("GitHub HTTPS authentication failure", () => {
const message =
"remote: Repository not found.\nfatal: repository 'https://github.com/example/private.git/' not found";
const multiAccount: GhProjectAccountStatus = {
ghInstalled: true,
accounts: [
{ login: "personal", active: true },
{ login: "work", active: false },
],
configuredAccount: "",
effectiveAccount: "personal",
suggestedAccount: "work",
};
it("preserves the Git error and opens project GitHub settings without changing accounts", async () => {
failure = { kind: "invalid", message };
ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount });
const settings = vi.fn();
const unregister = registerActions([{ id: "file.settings", title: "Settings", run: settings }]);
try {
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
const note = notes.at(-1)!;
expect(note.title).toBe("Update failed");
expect(note.body).toContain(message);
expect(note.body).toContain("personal may not have access");
expect(ghAccountStatus).toHaveBeenCalledTimes(1);
expect(settings).not.toHaveBeenCalled();
expect(remoteRepos).toEqual(["/p"]);
note.actions?.find((action) => action.label === "GitHub Settings")?.run();
await vi.waitFor(() => expect(settings).toHaveBeenCalledWith(expect.objectContaining({ arg: "vcs.github" })));
} finally {
unregister();
}
});
it.each([
"fatal: repository 'https://gitlab.com/example/private.git/' not found",
"fatal: repository 'https://github.com.evil.example/private.git/' not found",
"fatal: repository '[email protected]:example/private.git' not found",
"remote: Repository not found.",
"fatal: unable to access 'https://github.com/example/private.git/': Could not resolve host: github.com",
])("does not check gh for unrelated errors: %s", async (message) => {
failure = { kind: "invalid", message };
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
expect(ghAccountStatus).not.toHaveBeenCalled();
expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message });
});
it("keeps the original failure when only one account is signed in", async () => {
failure = { kind: "invalid", message };
ghAccountStatus.mockResolvedValue({
status: "ok",
data: { ...multiAccount, accounts: multiAccount.accounts.slice(0, 1) },
});
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message, actions: undefined });
});
it("keeps the original failure when account detection is unavailable", async () => {
failure = { kind: "invalid", message };
ghAccountStatus.mockRejectedValue(new Error("gh unavailable"));
expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false);
expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message, actions: undefined });
});
it("offers the same guidance for push failures without retrying", async () => {
failure = { kind: "invalid", message };
ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount });
expect(
await pushTargets([
{
repo: "/p",
op: {
op: "pushSelected",
selection: { branch: "main", revision: null, remote: "origin", target: "main" },
force_with_lease: false,
set_upstream: false,
tags: null,
no_verify: false,
},
},
]),
).toBe(false);
expect(notes.at(-1)).toMatchObject({
title: "Push failed",
body: expect.stringContaining("personal may not have access"),
actions: [expect.objectContaining({ label: "GitHub Settings" })],
});
expect(remoteRepos).toEqual(["/p"]);
});
it("offers the same guidance for fetch authentication failures", async () => {
failure = {
kind: "invalid",
message: "fatal: Authentication failed for 'https://github.com/example/private.git/'",
};
ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount });
expect(await runRemote({ op: "fetch" }, undefined, ["/p"])).toBe(false);
expect(notes.at(-1)?.actions?.map(({ label }) => label)).toEqual(["Show Git Console", "GitHub Settings"]);
});
});
describe("fetch result notification", () => {
it("keeps successful remotes and pruned refs visible when other remotes fail", async () => {
const showConsole = vi.fn();
+32 -1
Переглянути файл
@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({
checkout: vi.fn(),
notify: vi.fn(),
openWorktree: vi.fn(),
ghAccountStatus: vi.fn(),
}));
vi.mock("@/platform/actions", async (original) => ({
...(await original<typeof import("@/platform/actions")>()),
@@ -23,7 +24,15 @@ vi.mock("../ops", async (original) => ({
vi.mock("../openWorktree", () => ({ openWorktree: mocks.openWorktree }));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return { ...real, commands: { ...real.commands, vcsBranchInfo: mocks.head, vcsCheckout: mocks.checkout } };
return {
...real,
commands: {
...real.commands,
vcsBranchInfo: mocks.head,
vcsCheckout: mocks.checkout,
ghProjectAccountStatus: mocks.ghAccountStatus,
},
};
});
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
@@ -123,6 +132,28 @@ describe("Update Selected", () => {
expect(mocks.openWorktree).toHaveBeenCalledWith("/worktrees/topic", true);
});
it("offers GitHub account settings for an unchecked branch's HTTPS failure", async () => {
mocks.update.mockResolvedValue([
result("topic", "failed", "/p", "fatal: repository 'https://github.com/acme/private.git/' not found"),
]);
mocks.ghAccountStatus.mockResolvedValue({
status: "ok",
data: {
ghInstalled: true,
accounts: [
{ login: "personal", active: true },
{ login: "work", active: false },
],
effectiveAccount: "personal",
},
});
await updateBranches([target("topic", "/p")]);
const [action] = mocks.notify.mock.lastCall![0].actions;
expect(action.label).toBe("GitHub Settings");
action.run();
expect(mocks.execute).toHaveBeenCalledWith("file.settings", "vcs.github");
});
it("offers Update Selected in the context menu of a multi-selection", () => {
const selected = [target("a", "/p"), target("b", "/p")];
const items = branchMenu(selected[0]!.branch, "main", () => {}, { selected });
+13 -4
Переглянути файл
@@ -17,6 +17,7 @@ import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { notifications } from "@/workbench/contributions";
import { openWorktree } from "./openWorktree";
import { githubHttpsFailureHelp } from "./githubHttpsFailure";
import { activeRepository } from "./activeRepository";
import { ask, confirmChecked } from "@/workbench/messages";
import { branchNamePrefixes, isFavoriteBranch, isProtectedBranch, pushRecent, shortRemoteName } from "./branches";
@@ -1446,6 +1447,11 @@ export async function updateBranches(targets: readonly BranchUpdateTarget[]) {
const results = await runBranchUpdates(new Map([...byRepo].map(([repo, names]) => [repo, [...names]])));
if (!results || useProject.getState().project !== project) return;
const { lines, ...summary } = branchUpdateSummary(results, heads.length > 1);
const help = await githubHttpsFailureHelp(
results.flatMap((r) => (r.status === "failed" && r.message ? [r.message] : [])),
);
if (useProject.getState().project !== project) return;
if (help) lines.push(help.message);
const body = createElement(Fragment, null, ...lines.map((line) => createElement("div", { key: line }, line)));
const worktrees = [...new Set(results.flatMap((r) => (r.status === "failed" && r.worktree ? [r.worktree] : [])))];
notifications().notify({
@@ -1454,10 +1460,13 @@ export async function updateBranches(targets: readonly BranchUpdateTarget[]) {
userInitiated: true,
...summary,
body,
actions: worktrees.map((path) => {
const name = repoName(path);
return { label: tx`Open Worktree ${name}`, run: () => void openWorktree(path, true) };
}),
actions: [
...worktrees.map((path) => {
const name = repoName(path);
return { label: tx`Open Worktree ${name}`, run: () => void openWorktree(path, true) };
}),
...(help ? [help.action] : []),
],
});
}
if (current.length && useProject.getState().project === project) await runRemoteRound(current);
+37
Переглянути файл
@@ -0,0 +1,37 @@
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { useProject } from "@/platform/project";
/** GitHub deliberately uses "Repository not found" for inaccessible private repositories.
* Require Git's actual failing HTTPS URL: the same error from another host or SSH is unrelated
* to gh's HTTPS credential helper. Never infer a credential mismatch from the error alone.
*/
function isGithubHttpsFailure(message: string): boolean {
return /^fatal: (?:repository 'https:\/\/github\.com\/[^'\r\n]+' not found|Authentication failed for 'https:\/\/github\.com\/[^'\r\n]+')\.?(?:\r?$)/im.test(
message,
);
}
/** Diagnose only explicit failed remote operations. The existing project account settings
* handle selection; do not switch gh's global account, edit remotes, or retry a Git write.
*/
export async function githubHttpsFailureHelp(messages: readonly string[]) {
if (!messages.some(isGithubHttpsFailure)) return null;
const project = useProject.getState().project;
const status = await call(commands.ghProjectAccountStatus()).catch(() => null);
if (!status?.ghInstalled || status.accounts.length < 2 || useProject.getState().project !== project) return null;
return {
message: status.effectiveAccount
? tx`GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, ${status.effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.`
: tx(
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.",
),
action: {
label: "GitHub Settings",
run: () => {
if (useProject.getState().project === project) void executeAction("file.settings", "vcs.github");
},
},
};
}
+11 -7
Переглянути файл
@@ -1,5 +1,4 @@
import { tx, txPart } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { getAction, isActionEnabled } from "@/platform/actions";
import { useContextKeys } from "@/platform/context";
import { isMacHost } from "@/platform/keymap";
@@ -32,6 +31,7 @@ import { LogPathsEditor, chooseLogPaths } from "../PathFilterDialog";
import { openExternalLog } from "../RevisionBrowser";
import { currentRepo, repoName, useVcs } from "../store";
import { useDropdownMenu, useLogRepositories, useReadOnlyLog } from "./logHooks";
import { fetchLogUsers, knownLogUsers } from "./logUsers";
import { toggle } from "./shared";
// --- filters ----------------------------------------------------------------
@@ -198,16 +198,20 @@ export function FilterBar({ fileHistory = false }: { fileHistory?: boolean }) {
if (r) setLogBranches(r);
};
const openUser = async (anchor: HTMLElement) => {
const openUser = (anchor: HTMLElement) => {
const roots = filters.repositories?.length
? filters.repositories
: repositories.length
? repositories
: [currentRepo()];
const users = await Promise.all(roots.map((repo) => call(commands.vcsLogUsers(repo)).catch(() => [] as string[])));
const authors = [...new Set(users.flat().concat(commits.map((c) => `${c.author} <${c.email}>`)))].sort((a, b) =>
a.localeCompare(b),
);
// Listing every author of a large history takes seconds: open with the authors known so far
// (loaded commits and earlier lists) and let only Select… wait for the full list.
const fetching = Promise.all(roots.map((repo) => fetchLogUsers(repo)));
const authorsOf = (users: readonly (readonly string[])[]) =>
[...new Set(users.flat().concat(commits.map((c) => `${c.author} <${c.email}>`)))].sort((a, b) =>
a.localeCompare(b),
);
const authors = authorsOf(roots.map((repo) => knownLogUsers(repo)));
menuBelow(anchor, [
...recentFilterValues("authors").map((authors) => ({
verbatim: true,
@@ -228,7 +232,7 @@ export function FilterBar({ fileHistory = false }: { fileHistory?: boolean }) {
run: async () => {
const r = await chooseMany({
title: "Filter by User",
options: [ME, ...authors],
options: [ME, ...authorsOf(await fetching)],
initial: filters.authors,
customLabel: "Other names or emails (comma-separated):",
});
+41
Переглянути файл
@@ -0,0 +1,41 @@
/**
* Every author of a repository's history (`git log --all`) for the Log's User filter. On a large
* history listing them takes seconds, so the filter opens with what is already known and the list
* is fetched in the background, at most once per {@link REFRESH_MS} for each repository.
*/
import { call, commands } from "@/platform/ipc";
const REFRESH_MS = 5 * 60_000;
const known = new Map<string, { users: readonly string[]; at: number }>();
const pending = new Map<string, Promise<readonly string[]>>();
const key = (repo: string | null) => repo ?? "";
/** The authors of `repo`: the running fetch, else a new one unless the known list is recent. */
export function fetchLogUsers(repo: string | null, now = Date.now()): Promise<readonly string[]> {
const k = key(repo);
const running = pending.get(k);
if (running) return running;
const cached = known.get(k);
if (cached && now - cached.at < REFRESH_MS) return Promise.resolve(cached.users);
const fetch = call(commands.vcsLogUsers(repo))
.then((users) => {
known.set(k, { users, at: Date.now() });
return users as readonly string[];
})
.catch(() => known.get(k)?.users ?? [])
.finally(() => pending.delete(k));
pending.set(k, fetch);
return fetch;
}
/** The authors of `repo` fetched so far, without waiting. */
export function knownLogUsers(repo: string | null): readonly string[] {
return known.get(key(repo))?.users ?? [];
}
/** Test hook: forgets every fetched list. */
export function resetLogUsers() {
known.clear();
pending.clear();
}
+10 -2
Переглянути файл
@@ -24,6 +24,7 @@ import { flushChangelists } from "./changelists";
import { pushHistoryRepo, rememberPushTarget } from "./pushHistory";
import { describePush, formatPushOutcomes, partialPushReport, pushedCommits, type RepoPushOutcome } from "./pushReport";
import { cancelIncomingCheck } from "./incomingRequest";
import { githubHttpsFailureHelp } from "./githubHttpsFailure";
import { beginGitWork, conflictedFiles, currentRepo, refreshNow, repoName, repoOf, useVcs } from "./store";
// ---------------------------------------------------------------------------
@@ -551,6 +552,13 @@ export async function runRemoteRound<Op extends RemoteOp>(
: first.op === "unshallow"
? tx("Could not fetch full Git history")
: `${doneTitle} failed`;
const help = await githubHttpsFailureHelp(remaining.map(({ error }) => errorMessage(error)));
if (cancelRequested || useProject.getState().project !== project)
throw new IpcError({ kind: "cancelled", message: "cancelled" });
const actions = [
...(partial || isFetch ? [gitConsoleNotificationAction()] : []),
...(help ? [help.action] : []),
];
notify({
level: "error",
key: "vcs.remote",
@@ -561,9 +569,9 @@ export async function runRemoteRound<Op extends RemoteOp>(
? tx(message)
: message,
)
.concat(pruned)
.concat(pruned, help ? [help.message] : [])
.join("\n"),
actions: partial || isFetch ? [gitConsoleNotificationAction()] : undefined,
actions: actions.length ? actions : undefined,
});
}
if (!reported && isUpdate(first) && updated.length) await notifyUpdated(updated, "vcs.remote.updated");
+10 -4
Переглянути файл
@@ -26,6 +26,7 @@ import { openDialog } from "./dialogs";
import { useBranches } from "./gitMenuDialogs";
import { saveVcsSetting } from "./settingsUi";
import { formatTime } from "./model";
import { githubHttpsFailureHelp } from "./githubHttpsFailure";
import {
allRepos,
errorMessage,
@@ -1493,12 +1494,13 @@ function pushReviewActions(review: readonly PushReviewTarget[]) {
];
}
function pushFailed(
async function pushFailed(
failures: RemoteFailure<PushOp>[],
total: number,
rejected: boolean,
pushed: readonly RepoPushOutcome[],
): false {
): Promise<false> {
const project = useProject.getState().project;
const isPartial = ({ error }: RemoteFailure<PushOp>) => !!partialPushReport(error);
const names = (items: RemoteFailure<PushOp>[]) =>
items.flatMap(({ target }) => (target.repo ? [repoName(target.repo)] : [])).join(", ");
@@ -1521,7 +1523,11 @@ function pushFailed(
: tx(errorMessage(failures[0]!.error)),
);
}
const actions = pushReviewActions(review);
const help = await githubHttpsFailureHelp(failures.map(({ error }) => errorMessage(error)));
if (useProject.getState().project !== project) return false;
if (help) lines.push(help.message);
const actions = [...(pushReviewActions(review) ?? []), ...(help ? [help.action] : [])];
if (partiallyApplied.length) actions.push(gitConsoleNotificationAction());
notifications().notify({
group: "vcs",
level: "error",
@@ -1534,7 +1540,7 @@ function pushFailed(
? "Push rejected"
: "Push failed",
body: lines.join("\n"),
actions: partiallyApplied.length ? [...(actions ?? []), gitConsoleNotificationAction()] : actions,
actions: actions.length ? actions : undefined,
});
return false;
}
+4 -1
Переглянути файл
@@ -4830,5 +4830,8 @@
"Create Library": "Create Library",
"Library name": "Library name",
"Library name cannot be empty.": "Library name cannot be empty.",
"A library with this name already exists.": "A library with this name already exists."
"A library with this name already exists.": "A library with this name already exists.",
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.",
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.",
"GitHub Settings": "GitHub Settings"
}
+4 -1
Переглянути файл
@@ -9539,5 +9539,8 @@
"Create Library": "建立庫",
"Library name": "庫名稱",
"Library name cannot be empty.": "庫名稱不可為空。",
"A library with this name already exists.": "已存在同名的庫。"
"A library with this name already exists.": "已存在同名的庫。",
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登入了多個帳號。如果 Git 透過 gh 取得 HTTPS 憑證,{effectiveAccount} 可能沒有存取權限。請檢查遠端 URL,或在 GitHub 設定中選擇有權限的帳號後重試。",
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登入了多個帳號。如果 Git 透過 gh 取得 HTTPS 憑證,請檢查遠端 URL,或在 GitHub 設定中選擇有權限的帳號後重試。",
"GitHub Settings": "GitHub 設定"
}
+4 -1
Переглянути файл
@@ -11527,5 +11527,8 @@
"Create Library": "创建库",
"Library name": "库名称",
"Library name cannot be empty.": "库名称不能为空。",
"A library with this name already exists.": "已存在同名的库。"
"A library with this name already exists.": "已存在同名的库。",
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登录了多个账号。如果 Git 通过 gh 获取 HTTPS 凭据,{effectiveAccount} 可能没有访问权限。请检查远程 URL,或在 GitHub 设置中选择有权限的账号后重试。",
"GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登录了多个账号。如果 Git 通过 gh 获取 HTTPS 凭据,请检查远程 URL,或在 GitHub 设置中选择有权限的账号后重试。",
"GitHub Settings": "GitHub 设置"
}