дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
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]>
Цей коміт міститься в:
1 джерело
f40b645c8e
коміт
be7a0cfa5b
13 files changed
+305
-2
No files matched your search
@@ -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). */
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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) },
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in new issue
Заблокувати користувача