feat(vcs): SSH commit signing in Configure GPG Signature (#6724)

Configure GPG Signature gets a signing format (OpenPGP / SSH), saved as gpg.format in the repository config. With SSH, the key list shows ssh-agent's keys (`ssh-add -L`, saved as key::<public key>) and ~/.ssh/*.pub files, agent keys first, with a hint to ssh-add a key that isn't in the agent. Changing the format without a new key removes the old key, which belongs to the other format.

Closes #6712

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-29 13:36:06 +08:00
1 джерело 10242d2e58
коміт e4ec1978d8
12 files changed
+380 -51

No files matched your search

+17
Переглянути файл
@@ -2095,6 +2095,22 @@ pub async fn vcs_gpg_signing_keys(
result
}
/// Lists SSH public keys from ssh-agent and `~/.ssh` for SSH commit signing.
#[command(trust = trusted)]
pub async fn vcs_ssh_signing_keys(
host: &Host,
window: &str,
repo: PathBuf,
request: RequestId,
) -> IdeResult<Vec<SshSigningKey>> {
host.require_trust(window)?;
let project = host.project(window)?;
let cancel = host.begin_project_request(window, request);
let result = blocking(move || project.with_repo_at(Some(&repo), |repo| repo.ssh_signing_keys(&cancel))).await;
host.end_request(request);
result
}
/// Git LFS files of the repository still checked out as pointer files, and whether git-lfs runs.
#[command(trust = trusted)]
pub async fn vcs_lfs_status(host: &Host, window: &str, repo: PathBuf, request: RequestId) -> IdeResult<LfsStatus> {
@@ -3309,6 +3325,7 @@ ide_command::domain!(
vcs_signing_config,
vcs_lfs_status,
vcs_gpg_signing_keys,
vcs_ssh_signing_keys,
vcs_edit_signing,
vcs_watch_commit_messages,
vcs_set_user_identity,
+1 -1
Переглянути файл
@@ -1048,7 +1048,7 @@ pub use rebase_editor::{
};
pub use remotes::{FetchReport, Remote};
pub use roots::{ProjectUpdateTarget, Repos};
pub use signing::{GitSigningConfig, GitSigningEdit, GpgSigningKey};
pub use signing::{GitSigningConfig, GitSigningEdit, GpgSigningKey, SshSigningKey};
pub use staged_text::{StagedText, StagedTextEdit, StagingLineHunk, StagingLineHunks};
fn clone_args(url: &str, dest: &str, depth: Option<u32>, recurse_submodules: bool) -> IdeResult<Vec<String>> {
+153 -15
Переглянути файл
@@ -27,6 +27,18 @@ pub struct GpgSigningKey {
pub struct GitSigningEdit {
pub enabled: Option<bool>,
pub key: Option<String>,
/// `openpgp` or `ssh`.
pub format: Option<String>,
}
#[derive(Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SshSigningKey {
/// The `user.signingkey` value: a public key file path, or `key::` and the key itself.
pub key: String,
pub comment: Option<String>,
/// ssh-agent holds this key, so signing with it needs no passphrase prompt.
pub in_agent: bool,
}
impl Repo {
@@ -40,7 +52,7 @@ impl Repo {
pub fn gpg_signing_keys(&self, cancel: &CancellationToken) -> IdeResult<Vec<GpgSigningKey>> {
let _scope = self.execution_scope();
self.require_openpgp()?;
self.require_editable()?;
let program = gpg_program(self.root(), cancel)?;
let mut cmd = Command::new(&program);
cmd.current_dir(self.root()).args(["--batch", "--no-tty", "--with-colons", "--list-secret-keys"]);
@@ -56,14 +68,52 @@ impl Repo {
Ok(parse_keys(&out.stdout_str()))
}
/// Keys ssh-agent holds, then the public key files in `~/.ssh`.
pub fn ssh_signing_keys(&self, cancel: &CancellationToken) -> IdeResult<Vec<SshSigningKey>> {
let _scope = self.execution_scope();
self.require_editable()?;
let mut cmd = Command::new("ssh-add");
cmd.current_dir(self.root()).arg("-L");
ide_core::process::prepare(&mut cmd);
// ssh-add exits 1 without identities and 2 without an agent; both just mean no agent keys.
let agent = cli::capture_command(cmd, None, cancel, 1 << 20, "ssh-add")
.ok()
.filter(|out| out.code == Some(0))
.map(|out| out.stdout_str())
.unwrap_or_default();
let mut files = Vec::new();
if let Some(dir) = gix::path::env::home_dir().map(|home| home.join(".ssh"))
&& let Ok(entries) = std::fs::read_dir(dir)
{
for path in entries.flatten().map(|entry| entry.path()) {
if path.extension().is_some_and(|ext| ext == "pub")
&& let (Some(path), Ok(text)) = (path.to_str(), std::fs::read_to_string(&path))
{
files.push((path.to_owned(), text));
}
}
}
files.sort();
Ok(ssh_keys(&agent, &files))
}
pub fn edit_signing(&self, edit: GitSigningEdit) -> IdeResult<()> {
let _scope = self.execution_scope();
self.require_openpgp()?;
if edit.enabled.is_none() && edit.key.is_none() {
let current = self.require_editable()?;
if edit.enabled.is_none() && edit.key.is_none() && edit.format.is_none() {
return Ok(());
}
if edit.key.as_deref().is_some_and(|key| !valid_fingerprint(key)) {
return Err(IdeError::invalid("invalid OpenPGP fingerprint"));
let format = edit.format.as_deref().unwrap_or(&current);
if !matches!(format, "openpgp" | "ssh") {
return Err(IdeError::invalid("unsupported signing format"));
}
if let Some(key) = edit.key.as_deref() {
if format == "openpgp" && !valid_fingerprint(key) {
return Err(IdeError::invalid("invalid OpenPGP fingerprint"));
}
if format == "ssh" && (key.trim().is_empty() || key.chars().any(char::is_control)) {
return Err(IdeError::invalid("invalid SSH signing key"));
}
}
let config = self.metadata_dirs()?[1].join("config");
let mut lock = lock::File::acquire(&config, Fail::Immediately, None, 0, Some(&lock::acquire::resolve_symlink))
@@ -74,7 +124,11 @@ impl Repo {
let mut staged = tempfile::NamedTempFile::new_in(config.parent().expect("repository config directory"))?;
io::copy(&mut original, &mut staged)?;
let enabled = edit.enabled.map(|enabled| if enabled { "true" } else { "false" });
for (name, value) in [("commit.gpgsign", enabled), ("user.signingkey", edit.key.as_deref())] {
for (name, value) in [
("gpg.format", edit.format.as_deref()),
("commit.gpgsign", enabled),
("user.signingkey", edit.key.as_deref()),
] {
if let Some(value) = value {
cli::run(
self.root(),
@@ -91,6 +145,16 @@ impl Repo {
)?;
}
}
// A new format without a new key: the old key belongs to the other format.
if edit.format.as_deref().is_some_and(|format| format != current) && edit.key.is_none() {
let path = staged.path().to_str().ok_or_else(|| IdeError::invalid("non-UTF-8 Git config path"))?;
let args = ["config", "--file", path, "--unset-all", "user.signingkey"];
let out = cli::run_cancellable_raw(self.root(), &args, &CancellationToken::default())?;
// 5: the key was not set in this file.
if !matches!(out.code, Some(0 | 5)) {
return Err(cli::failure(&args, &out.stderr, &out.stdout, out.code));
}
}
// Git's config writer replaces the staging file, so reopen its final path.
let mut updated = std::fs::File::open(staged.path())?;
lock.with_mut(|file| {
@@ -102,14 +166,16 @@ impl Repo {
Ok(())
}
fn require_openpgp(&self) -> IdeResult<()> {
/// The repository's signing format, when the IDE can edit it (OpenPGP or SSH).
fn require_editable(&self) -> IdeResult<String> {
if !execution_allowed() {
return Err(IdeError::unavailable("Git signing configuration requires a trusted project"));
}
if self.config_get("gpg.format")?.is_some_and(|format| format != "openpgp") {
return Err(IdeError::invalid("the repository uses a signing format other than OpenPGP"));
let format = self.config_get("gpg.format")?.unwrap_or_else(|| "openpgp".into());
if !matches!(format.as_str(), "openpgp" | "ssh") {
return Err(IdeError::invalid("the repository uses a signing format other than OpenPGP or SSH"));
}
Ok(())
Ok(format)
}
}
@@ -142,6 +208,37 @@ fn gpg_program(root: &Path, cancel: &CancellationToken) -> IdeResult<PathBuf> {
Ok(if program.is_relative() && program.components().count() > 1 { root.join(program) } else { program })
}
/// `agent` is `ssh-add -L` output; `files` are `(path, contents)` of public key files.
/// A file whose key the agent holds replaces that agent entry.
fn ssh_keys(agent: &str, files: &[(String, String)]) -> Vec<SshSigningKey> {
// "<type> <base64> [comment]": the first two fields identify the key.
let split = |line: &str| {
let mut parts = line.trim().splitn(3, ' ');
let id = parts.next().zip(parts.next()).map(|(kind, blob)| format!("{kind} {blob}"));
id.map(|id| (id, parts.next().map(str::trim).filter(|c| !c.is_empty()).map(str::to_owned)))
};
let agent: Vec<_> = agent.lines().filter_map(split).collect();
let files: Vec<_> = files
.iter()
.filter_map(|(path, text)| {
let (id, comment) = text.lines().find(|line| !line.trim().is_empty()).and_then(split)?;
Some((id, SshSigningKey { key: path.clone(), comment, in_agent: false }))
})
.collect();
let mut keys: Vec<_> = agent
.iter()
.filter(|(id, _)| !files.iter().any(|(file, _)| file == id))
.map(|(id, comment)| SshSigningKey { key: format!("key::{id}"), comment: comment.clone(), in_agent: true })
.collect();
for (id, mut key) in files {
key.in_agent = agent.iter().any(|(held, _)| *held == id);
keys.push(key);
}
// Keys the agent holds first: they sign without a passphrase prompt.
keys.sort_by_key(|key| !key.in_agent);
keys
}
fn valid_fingerprint(value: &str) -> bool {
matches!(value.len(), 40 | 64) && value.bytes().all(|byte| byte.is_ascii_hexdigit())
}
@@ -239,7 +336,7 @@ mod tests {
git(&["config", "--local", "user.email", "[email protected]"]);
let repo = Repo::discover(dir.path()).unwrap().unwrap();
let enable = || GitSigningEdit { enabled: Some(true), key: Some(FINGERPRINT.into()) };
let enable = || GitSigningEdit { enabled: Some(true), key: Some(FINGERPRINT.into()), format: None };
assert!(repo.edit_signing(enable()).is_err());
assert!(repo.gpg_signing_keys(&CancellationToken::default()).is_err());
repo.set_execution_allowed(true);
@@ -254,13 +351,54 @@ mod tests {
assert_eq!(git(&["config", "--local", "--get", "user.email"]).trim(), "[email protected]");
assert!(repo.signing_config().unwrap().enabled);
repo.edit_signing(GitSigningEdit { enabled: Some(false), key: None }).unwrap();
repo.edit_signing(GitSigningEdit { enabled: Some(false), key: None, format: None }).unwrap();
assert!(!repo.signing_config().unwrap().enabled);
assert_eq!(git(&["config", "--local", "--get", "user.signingkey"]).trim(), FINGERPRINT);
git(&["config", "--local", "gpg.format", "ssh"]);
let ssh = GitSigningEdit {
enabled: Some(true),
key: Some("key::ssh-ed25519 AAAA".into()),
format: Some("ssh".into()),
};
repo.edit_signing(ssh).unwrap();
let config = repo.signing_config().unwrap();
assert_eq!((config.format.as_str(), config.enabled), ("ssh", true));
assert_eq!(config.key.as_deref(), Some("key::ssh-ed25519 AAAA"));
let bad = GitSigningEdit { enabled: None, key: Some("a\nb".into()), format: None };
assert!(repo.edit_signing(bad).is_err());
// Switching the format with signing off must not leave the other format's key behind.
repo.edit_signing(GitSigningEdit { enabled: Some(false), key: None, format: Some("openpgp".into()) }).unwrap();
repo.edit_signing(GitSigningEdit { enabled: Some(false), key: Some(FINGERPRINT.into()), format: None })
.unwrap();
repo.edit_signing(GitSigningEdit { enabled: None, key: None, format: Some("ssh".into()) }).unwrap();
assert_eq!(repo.signing_config().unwrap().key, None);
git(&["config", "--local", "gpg.format", "x509"]);
assert!(repo.edit_signing(enable()).is_err());
assert_eq!(repo.signing_config().unwrap().format, "ssh");
assert!(!repo.signing_config().unwrap().enabled);
assert_eq!(repo.signing_config().unwrap().format, "x509");
}
#[test]
fn lists_agent_keys_first_and_prefers_files_for_held_keys() {
let agent = "ssh-ed25519 AAAA held@host\nssh-rsa BBBB agent only\n";
let files = [
("/h/.ssh/a.pub".to_owned(), "ssh-ed25519 CCCC other\n".to_owned()),
("/h/.ssh/b.pub".to_owned(), "\nssh-ed25519 AAAA held@host\n".to_owned()),
("/h/.ssh/bad.pub".to_owned(), "garbage".to_owned()),
];
let key = |key: &str, comment: &str, in_agent| SshSigningKey {
key: key.into(),
comment: Some(comment.into()),
in_agent,
};
assert_eq!(
ssh_keys(agent, &files),
vec![
key("key::ssh-rsa BBBB", "agent only", true),
key("/h/.ssh/b.pub", "held@host", true),
key("/h/.ssh/a.pub", "other", false),
]
);
}
}
+4 -2
Переглянути файл
@@ -102,9 +102,11 @@ In the Commit tool window, choose a run configuration and turn on **Run Tests**
Before committing, OpenIDEA also warns about committing in detached HEAD or during a rebase, file names that cause problems on other systems, files larger than 50 MB, and CRLF line endings. A warning stops the commit once; click **Commit Anyway** to go ahead.
### Sign commits with GPG
### Sign commits with GPG or SSH
Open **Settings › Version Control › Git › Configure GPG Signature** in a trusted project. Choose the repository, enable **Sign commits with GPG**, and select an OpenPGP signing key. OpenIDEA saves the settings to that repository's Git config. Subsequent commits use the repository's configured signer.
Open **Settings › Version Control › Git › Configure GPG Signature** in a trusted project. Choose the repository and a **Signing format**, enable signing, and select a key. OpenIDEA saves the settings to that repository's Git config (`gpg.format`, `commit.gpgsign`, `user.signingkey`). Subsequent commits use the repository's configured signer.
For SSH, the list shows the keys ssh-agent holds, then the public keys in `~/.ssh`. A key with a passphrase must be in ssh-agent (`ssh-add`), since a commit from the IDE cannot ask for it. SSH signing needs Git 2.34 or later. To see your SSH-signed commits as verified in the log, list your key in the file that `gpg.ssh.allowedSignersFile` names, as on the command line.
### Modal commit
+4 -2
Переглянути файл
@@ -100,9 +100,11 @@ OpenIDEA 会找到包含项目的仓库,以及向下最多四层的嵌套仓
提交前,OpenIDEA 还会对以下情况发出警告:在分离 HEAD 或变基过程中提交、文件名在其他系统上可能有问题、文件大于 50 MB、CRLF 换行符。出现警告时第一次提交会被拦下,点击 **仍然提交** 继续。
### 使用 GPG 为提交签名
### 使用 GPG 或 SSH 为提交签名
在受信任的项目中打开 **设置 › 版本控制 › Git › 配置 GPG 签名**。选择仓库,开启 **使用 GPG 为提交签名**,然后选择 OpenPGP 签名密钥。OpenIDEA 将设置保存到所选仓库的 Git 配置,后续提交使用该仓库配置的签名程序。
在受信任的项目中打开 **设置 › 版本控制 › Git › 配置 GPG 签名**。选择仓库和 **签名格式**,开启签名,然后选择密钥。OpenIDEA 将设置保存到所选仓库的 Git 配置(`gpg.format`、`commit.gpgsign`、`user.signingkey`),后续提交使用该仓库配置的签名程序。
选择 SSH 时,列表先显示 ssh-agent 中的密钥,再显示 `~/.ssh` 中的公钥。设置了密码的密钥需要先加入 ssh-agent(`ssh-add`),因为在 IDE 中提交时无法输入密码。SSH 签名需要 Git 2.34 或更高版本。要让日志把你用 SSH 签名的提交显示为已验证,需要和命令行一样,把密钥写入 `gpg.ssh.allowedSignersFile` 指定的文件。
### 模态提交
+1
Переглянути файл
@@ -846,6 +846,7 @@ vcs_shelf_rename trusted project_host bin
vcs_shelve trusted project_host bindings async
vcs_shelves always project_host bindings async
vcs_signing_config always project_host bindings async
vcs_ssh_signing_keys trusted project_host bindings async
vcs_stage trusted project_host bindings async
vcs_stage_formatted_text trusted project_host bindings async
vcs_stage_hunks trusted project_host bindings async
+12
Переглянути файл
@@ -2390,6 +2390,8 @@ export const commands = {
vcsShelves: () => typedError<ShelvedChangeList[], IdeError>(__TAURI_INVOKE("vcs_shelves")),
/** The effective signing settings for one registered Git repository. */
vcsSigningConfig: (repo: string) => typedError<GitSigningConfig, IdeError>(__TAURI_INVOKE("vcs_signing_config", { repo })),
/** Lists SSH public keys from ssh-agent and `~/.ssh` for SSH commit signing. */
vcsSshSigningKeys: (repo: string, request: RequestId) => typedError<SshSigningKey[], IdeError>(__TAURI_INVOKE("vcs_ssh_signing_keys", { repo, request })),
vcsStage: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stage", { paths })),
vcsStageFormattedText: (path: string, before: string, after: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stage_formatted_text", { path, before, after })),
/**
@@ -8205,6 +8207,8 @@ export type GitSigningConfig = {
export type GitSigningEdit = {
enabled: boolean | null,
key: string | null,
/** `openpgp` or `ssh`. */
format: string | null,
};
/** Settings › Version Control › GitHub (`vcs.github`). */
@@ -14120,6 +14124,14 @@ export type SshSettings = {
configs?: SshConfiguration[],
};
export type SshSigningKey = {
/** The `user.signingkey` value: a public key file path, or `key::` and the key itself. */
key: string,
comment: string | null,
/** ssh-agent holds this key, so signing with it needs no passphrase prompt. */
inAgent: boolean,
};
export type StackFrame = {
id: number,
name: string,
+69
Переглянути файл
@@ -0,0 +1,69 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import type { GitSigningConfig } from "@/platform/ipc";
const FPR = "1234567890123456789012345678901234567890";
const SSH_KEY = "key::ssh-ed25519 AAAA";
let config: GitSigningConfig;
const editSigning = vi.fn(async (..._args: unknown[]) => ({ status: "ok", data: null }));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
commands: {
...real.commands,
vcsRoots: vi.fn(async () => ({ status: "ok", data: [{ root: "/project" }] })),
vcsSigningConfig: vi.fn(async () => ({ status: "ok", data: config })),
vcsGpgSigningKeys: vi.fn(async () => ({ status: "ok", data: [{ fingerprint: FPR, userId: "Me" }] })),
vcsSshSigningKeys: vi.fn(async () => ({
status: "ok",
data: [{ key: SSH_KEY, comment: "[email protected]", inAgent: true }],
})),
vcsEditSigning: (...args: unknown[]) => editSigning(...args),
cancelRequest: vi.fn(async () => ({ status: "ok", data: null })),
},
};
});
import { useProject } from "@/platform/project";
import { GitSigningRow } from "../pages/GitSigningRow";
async function openDialog() {
render(<GitSigningRow />);
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Configure GPG Signature…" })));
await screen.findByText("Signing format");
}
async function choose(current: string, option: string) {
await act(async () => fireEvent.click(screen.getByLabelText(new RegExp(current))));
await act(async () => fireEvent.click(await screen.findByRole("option", { name: new RegExp(option) })));
}
beforeEach(() => {
editSigning.mockClear();
useProject.setState({ project: { name: "demo", root: "/project", trusted: true } as never });
});
afterEach(() => useProject.setState({ project: null }));
describe("Configure GPG Signature", () => {
it("saves the SSH format with the chosen SSH key", async () => {
config = { format: "openpgp", enabled: true, key: FPR };
await openDialog();
await choose("Signing format", "SSH");
await screen.findByText("Sign commits with SSH");
await choose("Signing key", "[email protected]");
await act(async () => fireEvent.click(screen.getByRole("button", { name: "OK" })));
expect(editSigning).toHaveBeenCalledWith("/project", { enabled: null, key: SSH_KEY, format: "ssh" });
});
it("drops the OpenPGP key when the format changes with signing off", async () => {
config = { format: "openpgp", enabled: false, key: FPR };
await openDialog();
await choose("Signing format", "SSH");
await act(async () => fireEvent.click(screen.getByRole("button", { name: "OK" })));
expect(editSigning).toHaveBeenCalledWith("/project", { enabled: null, key: null, format: "ssh" });
});
});
+105 -31
Переглянути файл
@@ -7,6 +7,7 @@ import {
nextRequestId,
type GitSigningConfig,
type GpgSigningKey,
type SshSigningKey,
type VcsRoot,
} from "@/platform/ipc";
import { basename, useProject } from "@/platform/project";
@@ -96,55 +97,92 @@ function RepositorySigning({
}) {
const rootId = useId();
const keyId = useId();
const formatId = useId();
const [initial, setInitial] = useState<GitSigningConfig>();
const [format, setFormat] = useState<string>();
const [enabled, setEnabled] = useState(false);
const [key, setKey] = useState<string | null>(null);
const [keys, setKeys] = useState<GpgSigningKey[]>();
const [keysError, setKeysError] = useState<string>();
const [keys, setKeys] = useState<{
format: string;
gpg?: GpgSigningKey[];
ssh?: SshSigningKey[];
error?: string;
}>();
const [error, setError] = useState<string>();
const [saving, setSaving] = useState(false);
useEffect(() => {
let live = true;
let request: ReturnType<typeof nextRequestId> | undefined;
void call(commands.vcsSigningConfig(repo)).then(
(config) => {
if (!live) return;
setInitial(config);
setFormat(config.format);
setEnabled(config.enabled);
setKey(config.key);
if (config.format !== "openpgp") return;
request = nextRequestId();
void call(commands.vcsGpgSigningKeys(repo, request))
.then(
(keys) => live && setKeys(keys),
(error: unknown) => live && setKeysError(message(error)),
)
.finally(() => {
request = undefined;
});
},
(error: unknown) => live && setError(message(error)),
);
return () => {
live = false;
if (request !== undefined) void commands.cancelRequest(request).catch(() => undefined);
};
}, [repo]);
const supported = initial?.format === "openpgp";
const supported = initial?.format === "openpgp" || initial?.format === "ssh";
useEffect(() => {
if (!supported || !format) return;
let live = true;
let request: ReturnType<typeof nextRequestId> | undefined = nextRequestId();
const loaded =
format === "ssh"
? call(commands.vcsSshSigningKeys(repo, request)).then((ssh) => ({ format, ssh }))
: call(commands.vcsGpgSigningKeys(repo, request)).then((gpg) => ({ format, gpg }));
void loaded
.then(
(keys) => live && setKeys(keys),
(error: unknown) => live && setKeys({ format, error: message(error) }),
)
.finally(() => {
request = undefined;
});
return () => {
live = false;
if (request !== undefined) void commands.cancelRequest(request).catch(() => undefined);
};
}, [repo, format, supported]);
const ssh = format === "ssh";
const changedFormat = initial && format !== initial.format;
const changedEnabled = initial && enabled !== initial.enabled;
const changedKey = enabled && key !== initial?.key;
const dirty = changedEnabled || changedKey;
const options: SelectOption<string>[] = (keys ?? []).map((key) => ({
value: key.fingerprint,
label: key.userId || key.fingerprint,
verbatim: true,
detail: key.userId ? key.fingerprint : undefined,
verbatimDetail: true,
}));
if (initial?.key && !options.some((option) => option.value === initial.key)) {
options.unshift({ value: initial.key, label: initial.key, verbatim: true });
const changedKey = enabled && (key !== initial?.key || changedFormat);
const dirty = changedFormat || changedEnabled || changedKey;
const shown = keys?.format === format ? keys : undefined;
const keysError = shown?.error;
const options: SelectOption<string>[] = ssh
? (shown?.ssh ?? []).map((key) => ({
value: key.key,
label: key.comment || key.key,
verbatim: true,
detail: [key.key.startsWith("key::") ? undefined : key.key, key.inAgent ? "ssh-agent" : undefined]
.filter(Boolean)
.join(" · "),
verbatimDetail: true,
}))
: (shown?.gpg ?? []).map((key) => ({
value: key.fingerprint,
label: key.userId || key.fingerprint,
verbatim: true,
detail: key.userId ? key.fingerprint : undefined,
verbatimDetail: true,
}));
if (key && !options.some((option) => option.value === key)) {
options.unshift({ value: key, label: key, verbatim: true });
}
const outsideAgent = ssh && !!key && !!shown?.ssh && !shown.ssh.some((k) => k.key === key && k.inAgent);
function chooseFormat(next: string) {
setFormat(next);
setKey(next === initial?.format ? (initial?.key ?? null) : null);
}
async function save() {
@@ -153,7 +191,11 @@ function RepositorySigning({
setError(undefined);
try {
await call(
commands.vcsEditSigning(repo, { enabled: changedEnabled ? enabled : null, key: changedKey ? key : null }),
commands.vcsEditSigning(repo, {
enabled: changedEnabled ? enabled : null,
key: changedKey ? key : null,
format: changedFormat ? (format ?? null) : null,
}),
);
onClose();
} catch (error) {
@@ -208,7 +250,25 @@ function RepositorySigning({
{initial ? (
supported ? (
<>
<Toggle label="Sign commits with GPG" checked={enabled} onChange={setEnabled} disabled={saving} />
<Row label="Signing format" htmlFor={formatId} stacked>
<Select
id={formatId}
className={styles.signingPicker}
value={format ?? null}
options={[
{ value: "openpgp", label: "OpenPGP", verbatim: true },
{ value: "ssh", label: "SSH", verbatim: true },
]}
disabled={saving}
onChange={chooseFormat}
/>
</Row>
<Toggle
label={ssh ? "Sign commits with SSH" : "Sign commits with GPG"}
checked={enabled}
onChange={setEnabled}
disabled={saving}
/>
<Row
label="Signing key"
htmlFor={keyId}
@@ -218,8 +278,14 @@ function RepositorySigning({
<span className={workflow.error} role="alert">
{keysError}
</span>
) : keys?.length === 0 ? (
<T>No OpenPGP signing keys found.</T>
) : shown && !options.length ? (
ssh ? (
<T>No SSH public keys found in ssh-agent or ~/.ssh.</T>
) : (
<T>No OpenPGP signing keys found.</T>
)
) : outsideAgent && enabled ? (
<T>ssh-agent doesn't hold this key. If it has a passphrase, add it with ssh-add first.</T>
) : undefined
}
>
@@ -227,13 +293,21 @@ function RepositorySigning({
id={keyId}
className={styles.signingPicker}
value={key}
placeholder={keys || keysError ? "Select a signing key" : "Loading…"}
placeholder={shown ? "Select a signing key" : "Loading…"}
options={options}
disabled={!enabled || saving || !options.length}
onChange={setKey}
searchable
/>
</Row>
{ssh && (
<div className={styles.signingHint}>
<T>
To show SSH-signed commits as verified in the log, list the key in the file that
gpg.ssh.allowedSignersFile names.
</T>
</div>
)}
{dirty && (
<div className={styles.signingHint}>
<T>Changes are saved to this repository's Git config.</T>
+2
Переглянути файл
@@ -298,6 +298,8 @@ describe("catalogs", () => {
"12288 MB",
"16384 MB",
"Docker",
// The OpenPGP signing format, in Configure GPG Signature.
"OpenPGP",
"URL",
"ID:",
"Code Vision",
+6
Переглянути файл
@@ -3385,6 +3385,12 @@
"Signing key {key}": "Signing key {key}",
"Key fingerprint {fingerprint}": "Key fingerprint {fingerprint}",
"Signed by {signer}": "Signed by {signer}",
"OpenPGP": "OpenPGP",
"Signing format": "Signing format",
"Sign commits with SSH": "Sign commits with SSH",
"No SSH public keys found in ssh-agent or ~/.ssh.": "No SSH public keys found in ssh-agent or ~/.ssh.",
"ssh-agent doesn't hold this key. If it has a passphrase, add it with ssh-add first.": "ssh-agent doesn't hold this key. If it has a passphrase, add it with ssh-add first.",
"To show SSH-signed commits as verified in the log, list the key in the file that gpg.ssh.allowedSignersFile names.": "To show SSH-signed commits as verified in the log, list the key in the file that gpg.ssh.allowedSignersFile names.",
"Select a signing key": "Select a signing key",
"No OpenPGP signing keys found.": "No OpenPGP signing keys found.",
"Changes are saved to this repository's Git config.": "Changes are saved to this repository's Git config.",
+6
Переглянути файл
@@ -9936,6 +9936,12 @@
"Signing key {key}": "签名密钥 {key}",
"Key fingerprint {fingerprint}": "密钥指纹 {fingerprint}",
"Signed by {signer}": "签名者 {signer}",
"OpenPGP": "OpenPGP",
"Signing format": "签名格式",
"Sign commits with SSH": "使用 SSH 为提交签名",
"No SSH public keys found in ssh-agent or ~/.ssh.": "在 ssh-agent 和 ~/.ssh 中未找到 SSH 公钥。",
"ssh-agent doesn't hold this key. If it has a passphrase, add it with ssh-add first.": "ssh-agent 中没有这个密钥。如果它设置了密码,请先用 ssh-add 添加。",
"To show SSH-signed commits as verified in the log, list the key in the file that gpg.ssh.allowedSignersFile names.": "要在日志中把 SSH 签名的提交显示为已验证,请把该密钥写入 gpg.ssh.allowedSignersFile 指定的文件。",
"Select a signing key": "选择签名密钥",
"No OpenPGP signing keys found.": "未找到 OpenPGP 签名密钥。",
"Changes are saved to this repository's Git config.": "更改将保存到此仓库的 Git 配置。",