feat(github): create gists from the selection or files (#6765)

Adds Git > GitHub > Create Gist... From the editor it posts the selection, or the whole file without one; from the Project view and editor tabs it posts the selected files (folders are skipped). The dialog asks for a file name (single file only) and a description, with Secret (on by default), Open in browser and Copy URL; the choices are remembered. The gist is created with gh api under the project's GitHub account and a notification links to it.

Closes #6714

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-29 13:57:17 +08:00
1 джерело f40b645c8e
коміт be7a0cfa5b
13 files changed
+305 -2

No files matched your search

+2
Переглянути файл
@@ -759,6 +759,8 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("github.createPullRequest", "Create Pull Request…"),
act("github.checkoutPullRequest", "Checkout Pull Request…"),
act("github.openInBrowser", "Open on GitHub"),
SEP,
act("github.createGist", "Create Gist…"),
],
),
act("vcs.manageRemotes", "Manage Remotes…"),
+2
Переглянути файл
@@ -109,6 +109,8 @@ export function setCurrentRepository(
repo: (GHRepositoryCoordinates & { id: string | null; root?: string | null }) | null,
) {
current = repo;
// Disconnected: requests go to gh's default host again, not the last repository's.
if (!repo) host = null;
}
/** The connected repository: `owner`, `name` and its GraphQL node `id` (once loaded). */
+19
Переглянути файл
@@ -110,6 +110,25 @@ describe("a GitHub Enterprise Server repository", () => {
expect(await connect(s.remotes[1]!)).toBe(true);
expect(ghApi).toHaveBeenLastCalledWith("/w/app", expect.objectContaining({ host: null }));
});
it("stops sending requests to the server once disconnected (another project)", async () => {
layout = { "/w/app": [{ name: "origin", url: "[email protected]:acme/app.git" }] };
ghAvailability.mockReturnValue(
ok({ kind: "ready", repo: { nameWithOwner: "acme/app", url: "https://ghe.example.com/acme/app" }, login: "al" }),
);
ghApi.mockImplementation((_repo: string | null, req: { endpoint: string }) =>
ok(
req.endpoint === "user"
? JSON.stringify({ id: 1, node_id: "U1", login: "al", avatar_url: "", html_url: "" })
: JSON.stringify({ data: { repository: { id: "R1", owner: { login: "acme" }, name: "app" } } }),
),
);
await refreshConnection();
expect(useGhRepository.getState().connection?.coordinates.host).toBe("ghe.example.com");
resetConnection();
await rest("POST", "gists", {});
expect(ghApi).toHaveBeenLastCalledWith(null, expect.objectContaining({ endpoint: "gists", host: null }));
});
});
describe("GitHub Enterprise Server hosts beside github.com", () => {
+136
Переглянути файл
@@ -0,0 +1,136 @@
/**
* Create Gist…: posts the editor selection (else the whole file) or the files the menu
* targets as a gist through `gh api`, then opens / copies its URL as the dialog chose.
*/
import { useState } from "react";
import { activeEditor, editorsFor } from "@/editor/api";
import { writeClipboardText } from "@/platform/clipboard";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { openExternalUrl } from "@/platform/openUrl";
import { basename } from "@/platform/project";
import { Checkbox, Dialog, Input, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { errorMessage, rest } from "../api/client";
import { refreshConnection, useGhRepository } from "../data/repository";
import { openDialog } from "../ui/dialogs";
import styles from "../ui/ui.module.css";
import { gistBody, loadGistOptions, saveGistOptions, type GistFile, type GistOptions } from "./model";
/** The text of `path`: its open editor's (unsaved edits included), else the file on disk; null for folders and unreadable files. */
async function fileText(path: string): Promise<string | null> {
const open = editorsFor(path)[0];
if (open) return open.view.state.doc.toString();
try {
return await call(commands.fsReadText(path));
} catch {
return null;
}
}
/** The menu's paths (`arg`), else the active editor's selection or whole document. */
export async function gistFiles(arg: unknown): Promise<GistFile[]> {
const paths = typeof arg === "string" ? [arg] : Array.isArray(arg) ? arg.filter((p) => typeof p === "string") : [];
if (!paths.length) {
const ed = activeEditor();
if (!ed) return [];
const { state } = ed.view;
const sel = state.selection.main;
return [
{ name: basename(ed.ctx.path), content: sel.empty ? state.doc.toString() : state.sliceDoc(sel.from, sel.to) },
];
}
const texts = await Promise.all(paths.map(fileText));
return paths.flatMap((p, i) => (texts[i] === null ? [] : [{ name: basename(p), content: texts[i]! }]));
}
interface GistDialogResult extends GistOptions {
fileName: string;
description: string;
}
function GistDialog(props: { fileName: string | null; onDone: (v: GistDialogResult | null) => void }) {
const [fileName, setFileName] = useState(props.fileName ?? "");
const [description, setDescription] = useState("");
const [opts, setOpts] = useState(loadGistOptions);
const flag = (k: keyof GistOptions) => (v: boolean) => setOpts((o) => ({ ...o, [k]: v }));
return (
<Dialog
open
title="Create Gist"
onClose={() => props.onDone(null)}
width={460}
buttons={[
{
label: "Create Gist",
role: "default",
disabled: props.fileName !== null && !fileName.trim(),
onClick: () => props.onDone({ ...opts, fileName, description }),
},
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.form}>
{props.fileName !== null && (
<>
<label className={styles.fieldLabel}>
<T>Filename:</T>
</label>
<Input aria-label="Filename" value={fileName} onChange={(e) => setFileName(e.target.value)} />
</>
)}
<label className={styles.fieldLabel}>
<T>Description:</T>
</label>
<textarea
data-autofocus
aria-label={tx("Description")}
className={styles.textarea}
rows={4}
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<Checkbox label="Secret" checked={opts.secret} onChange={flag("secret")} />
<Checkbox label="Open in browser" checked={opts.openInBrowser} onChange={flag("openInBrowser")} />
<Checkbox label="Copy URL" checked={opts.copyUrl} onChange={flag("copyUrl")} />
</div>
</Dialog>
);
}
const notify = (n: Parameters<ReturnType<typeof notifications>["notify"]>[0]) =>
notifications().notify({ group: "vcs", key: "github-gist", userInitiated: true, ...n });
export async function createGist(arg: unknown): Promise<void> {
const files = (await gistFiles(arg)).filter((f) => f.content.trim());
if (!files.length) {
notify({ level: "warning", title: "Nothing to put in a gist", body: tx("Select some text or a non-empty file.") });
return;
}
const single = files.length === 1 ? files[0]!.name : null;
const choice = await openDialog<GistDialogResult>((done) => <GistDialog fileName={single} onDone={done} />);
if (!choice) return;
const { fileName, description, ...opts } = choice;
saveGistOptions(opts);
const named = single === null ? files : [{ ...files[0]!, name: fileName }];
let url: string;
try {
// A GitHub Enterprise project's gists go to its server: find the project's repository first.
if (!useGhRepository.getState().availability) await refreshConnection();
url = (await rest<{ html_url: string }>("POST", "gists", gistBody(named, description, opts.secret))).html_url;
} catch (e) {
notify({ level: "error", title: "Couldn't create the gist", body: errorMessage(e) });
return;
}
if (opts.copyUrl) await writeClipboardText(url);
if (opts.openInBrowser) await openExternalUrl(url);
notify({
level: "info",
title: opts.secret ? "Secret gist created" : "Public gist created",
body: url,
actions: [
{ label: "Open in Browser", run: () => void openExternalUrl(url) },
{ label: "Copy URL", run: () => void writeClipboardText(url) },
],
});
}
+40
Переглянути файл
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import { gistBody, parseGistOptions } from "./model";
describe("gistBody", () => {
it("is secret unless asked otherwise and keys files by name", () => {
expect(gistBody([{ name: "a.py", content: "print(1)\n" }], " demo ", true)).toEqual({
description: "demo",
public: false,
files: { "a.py": { content: "print(1)\n" } },
});
expect(gistBody([{ name: "a.py", content: "x" }], "", false).public).toBe(true);
});
it("drops blank files and makes repeated names unique", () => {
const body = gistBody(
[
{ name: "index.ts", content: "a" },
{ name: "index.ts", content: "b" },
{ name: "Makefile", content: "c" },
{ name: "Makefile", content: "d" },
{ name: "empty.txt", content: " \n" },
{ name: " ", content: "e" },
],
"",
true,
);
expect(Object.keys(body.files)).toEqual(["index.ts", "index (2).ts", "Makefile", "Makefile (2)", "snippet.txt"]);
});
});
describe("parseGistOptions", () => {
it("falls back to IntelliJ's defaults for missing or malformed values", () => {
expect(parseGistOptions(null)).toEqual({ secret: true, openInBrowser: true, copyUrl: false });
expect(parseGistOptions({ secret: false, copyUrl: "yes" })).toEqual({
secret: false,
openInBrowser: true,
copyUrl: false,
});
});
});
+62
Переглянути файл
@@ -0,0 +1,62 @@
/**
* Git › GitHub › Create Gist… (IntelliJ's `GithubCreateGistAction`): what goes into the
* gist and the dialog's remembered choices (`GithubSettings` `PRIVATE_GIST`,
* `OPEN_IN_BROWSER_GIST`, `COPY_URL_GIST`).
*/
export interface GistFile {
name: string;
content: string;
}
export interface GistOptions {
secret: boolean;
openInBrowser: boolean;
copyUrl: boolean;
}
const KEY = "openidea.github.gist.v1";
/** IntelliJ's defaults. */
const DEFAULTS: GistOptions = { secret: true, openInBrowser: true, copyUrl: false };
export function parseGistOptions(raw: unknown): GistOptions {
const o = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
const bool = (k: keyof GistOptions) => (typeof o[k] === "boolean" ? (o[k] as boolean) : DEFAULTS[k]);
return { secret: bool("secret"), openInBrowser: bool("openInBrowser"), copyUrl: bool("copyUrl") };
}
export function loadGistOptions(): GistOptions {
try {
return parseGistOptions(JSON.parse(globalThis.localStorage?.getItem(KEY) ?? "null"));
} catch {
return DEFAULTS;
}
}
export function saveGistOptions(o: GistOptions) {
try {
globalThis.localStorage?.setItem(KEY, JSON.stringify(o));
} catch {
// Storage full or unavailable: the choices are just not remembered.
}
}
/**
* The `POST /gists` body. GitHub rejects blank files and needs unique names, so blank
* files are dropped and repeated names get a ` (2)`-style suffix before the extension.
*/
export function gistBody(files: GistFile[], description: string, secret: boolean) {
const out: Record<string, { content: string }> = {};
for (const f of files) {
if (!f.content.trim()) continue;
const name = f.name.trim() || "snippet.txt";
let unique = name;
for (let n = 2; unique in out; n++) {
const dot = name.lastIndexOf(".");
unique = dot > 0 ? `${name.slice(0, dot)} (${n})${name.slice(dot)}` : `${name} (${n})`;
}
out[unique] = { content: f.content };
}
return { description: description.trim(), public: !secret, files: out };
}
+9
Переглянути файл
@@ -93,6 +93,15 @@ function actions(): ActionSpec[] {
icon: "external-link",
when: WHEN,
},
{
// Github.Create.Gist
id: "github.createGist",
title: "Create Gist…",
description: "Shares the selection, the file or the selected files as a GitHub gist.",
category: "GitHub",
keywords: ["github", "gist", "snippet", "share", "paste"],
when: WHEN,
},
{
// Github.PullRequest.List.Reload
id: "github.refresh",
+2
Переглянути файл
@@ -22,6 +22,7 @@ import { openCreatePullRequest, openPullRequest, selectOpenedPullRequest, showPu
import { changeRepository, headerMenu } from "./toolwindow/PullRequestsToolWindow";
import { contextPullRequest, resetTabs } from "./toolwindow/store";
import { activeTimelinePullRequest, openTimeline, timelineIcon, timelineTitle } from "./toolwindow/timelineInput";
import { createGist } from "./gist/createGist";
import { numberDialog } from "./ui/dialogs";
import { activateWorktreeReviews } from "./worktreeReviews";
@@ -57,6 +58,7 @@ export const runs: Record<string, Run> = {
const url = n !== null ? await prUrl(n) : useGhRepository.getState().connection?.repository.url;
if (url) await openInBrowser(url);
},
"github.createGist": ({ arg }) => createGist(arg),
"github.refresh": async () => {
await refreshConnection();
if (useGhRepository.getState().connection) await reloadList();
+1
Переглянути файл
@@ -442,6 +442,7 @@
"menu.github.createPullRequest": "Create Pull Request…",
"menu.github.checkoutPullRequest": "Checkout Pull Request…",
"menu.github.openInBrowser": "Open on GitHub",
"menu.github.createGist": "Create Gist…",
"menu.file.newProject": "Project…",
"menu.file.renameProject": "Rename Project…",
"menu.file.reloadAllFromDisk": "Reload All from Disk",
+15 -1
Переглянути файл
@@ -4541,5 +4541,19 @@
"Run commands using IDE": "Run commands using IDE",
"Highlights typed commands the IDE recognises (pytest, npm run, Gradle tasks…), so Run Highlighted Command Using IDE runs them in the Run tool window.": "Highlights typed commands the IDE recognises (pytest, npm run, Gradle tasks…), so Run Highlighted Command Using IDE runs them in the Run tool window.",
"Cannot run the command using the IDE": "Cannot run the command using the IDE",
"The shell did not clear its command line.": "The shell did not clear its command line."
"The shell did not clear its command line.": "The shell did not clear its command line.",
"Create Gist": "Create Gist",
"Filename:": "Filename:",
"Filename": "Filename",
"Description:": "Description:",
"Secret": "Secret",
"Open in browser": "Open in browser",
"Copy URL": "Copy URL",
"Nothing to put in a gist": "Nothing to put in a gist",
"Select some text or a non-empty file.": "Select some text or a non-empty file.",
"Couldn't create the gist": "Couldn't create the gist",
"Secret gist created": "Secret gist created",
"Public gist created": "Public gist created",
"Create Gist…": "Create Gist…",
"Shares the selection, the file or the selected files as a GitHub gist.": "Shares the selection, the file or the selected files as a GitHub gist."
}
+14 -1
Переглянути файл
@@ -11072,5 +11072,18 @@
"Run commands using IDE": "使用 IDE 运行命令",
"Highlights typed commands the IDE recognises (pytest, npm run, Gradle tasks…), so Run Highlighted Command Using IDE runs them in the Run tool window.": "高亮 IDE 能识别的已输入命令(pytest、npm run、Gradle 任务等),以便“使用 IDE 运行高亮的命令”在“运行”工具窗口中运行它们。",
"Cannot run the command using the IDE": "无法使用 IDE 运行该命令",
"The shell did not clear its command line.": "Shell 没有清空命令行。"
"The shell did not clear its command line.": "Shell 没有清空命令行。",
"Create Gist": "创建 Gist",
"Filename:": "文件名:",
"Filename": "文件名",
"Description:": "描述:",
"Secret": "私密",
"Copy URL": "复制 URL",
"Nothing to put in a gist": "没有可放入 Gist 的内容",
"Select some text or a non-empty file.": "请选择一段文本或一个非空文件。",
"Couldn't create the gist": "无法创建 Gist",
"Secret gist created": "已创建私密 Gist",
"Public gist created": "已创建公开 Gist",
"Create Gist…": "创建 Gist…",
"Shares the selection, the file or the selected files as a GitHub gist.": "将选区、当前文件或所选文件分享为 GitHub Gist。"
}
+1
Переглянути файл
@@ -442,6 +442,7 @@
"menu.github.createPullRequest": "创建拉取请求…",
"menu.github.checkoutPullRequest": "签出拉取请求…",
"menu.github.openInBrowser": "在 GitHub 上打开",
"menu.github.createGist": "创建 Gist…",
"menu.file.newProject": "项目…",
"menu.file.renameProject": "重命名项目…",
"menu.file.reloadAllFromDisk": "从磁盘全部重新加载",
+2
Переглянути файл
@@ -1664,6 +1664,8 @@ export function gitMenuItems({ paths, dirs, file, ignore, editorSelection }: Git
action("github.createPullRequest"),
action("github.checkoutPullRequest"),
action("github.openInBrowser"),
// The editor menu shares its selection (no argument); the others, their files.
editorSelection ? action("github.createGist") : act("github.createGist"),
]);
const items: (MenuItem | null)[] = [
single && !dirs?.[0] ? act("vcs.commit", "Commit File…") : act("vcs.commit", "Commit…"),