diff --git a/README.md b/README.md index d2865cc..88707df 100644 --- a/README.md +++ b/README.md @@ -239,6 +239,7 @@ The `Copy File to Gist` command is also available on the editor tab's context me In addition to the commands added to the editor context menu, GistPad also contributes the following commands to the editor's title bar menu (click the `...` in the upper right section of an editor window): - `Rename File` - Allows you to rename the current file. +- `Sync Gist` - Sync the current gist file to GitHub. Only available when `gistpad.autoSyncWhenSave` is disabled. ## Contributed Commands (Command Palette) @@ -303,3 +304,5 @@ In addition to the `Gists` view, this extension also provides the following comm - `GistPad > Showcase URL` - Specifies the URL to use when displaying the showcase entry. This allows teams/classrooms/etc. to create their own showcase and share it amongst themselves. - `GistPad > Tracing > Enable Output Channel` - When enabled, creates an Output trace channel at VSCode startup. + +- `GistPad > Auto Sync When Save` - Specifies whether or not to enable the auto sync feature when saving a file. Consider disabling this option when VS Code's `files.autoSave` is enabled to prevent frequent syncing operations. Defaults to `true`. diff --git a/package.json b/package.json index 4d920a4..a4d6ec9 100644 --- a/package.json +++ b/package.json @@ -119,6 +119,11 @@ "default": false, "type": "boolean", "description": "Specifies whether or not to enable the output channel for tracing." + }, + "gistpad.autoSyncWhenSave": { + "default": true, + "type": "boolean", + "description": "Specifies whether or not to enable the auto sync feature when saving a file. By default, this is enabled." } } }, @@ -534,6 +539,11 @@ { "command": "gistpad.viewForks", "title": "View Forks" + }, + { + "command": "gistpad.syncGist", + "title": "Sync Gist", + "icon": "$(sync)" } ], "menus": { @@ -1364,6 +1374,11 @@ { "command": "gistpad.renameRepositoryFile", "when": "resourceScheme == repo" + }, + { + "command": "gistpad.syncGist", + "when": "resourceScheme == gist && !gistpad.autoSyncWhenSave", + "group": "navigation@1" } ], "editor/title/context": [ diff --git a/src/commands/gist.ts b/src/commands/gist.ts index 8171b5b..cb5e00d 100644 --- a/src/commands/gist.ts +++ b/src/commands/gist.ts @@ -11,6 +11,7 @@ import { workspace } from "vscode"; import { EXTENSION_NAME } from "../constants"; +import { updateGistFiles } from "../fileSystem/api"; import { duplicateGist, exportToRepo } from "../fileSystem/git"; import { openRepo } from "../repos/store/actions"; import { Gist, GistFile, GroupType, SortOrder, store } from "../store"; @@ -41,9 +42,11 @@ import { encodeDirectoryName, fileNameToUri, getGistDescription, + getGistDetailsFromUri, getGistLabel, getGistWorkspaceId, isGistWorkspace, + isOwnedGist, openGist, openGistFiles, sortGists, @@ -51,6 +54,7 @@ import { withProgress } from "../utils"; const isBinaryPath = require("is-binary-path"); +const path = require("path"); const GIST_NAME_PATTERN = /(\/)?(?([a-z\d]+-)*[a-z\d]+)\/(?[^\/]+)$/i; @@ -118,6 +122,56 @@ async function newGistInternal(isPublic: boolean = true, description: string = " descriptionInputBox.show(); } +async function syncGistInternal() { + await ensureAuthenticated(); + + let error: Error | undefined; + const activeEditor = window.activeTextEditor; + if (!activeEditor) { + throw new Error("No active editor"); + } + + await window.withProgress( + { + location: ProgressLocation.Notification, + title: "Uploading to GitHub Gist..." + }, + async () => { + try { + const uri = activeEditor.document.uri; + const { gistId } = getGistDetailsFromUri(uri); + + if (!isOwnedGist(gistId)) { + throw new Error("You can't sync a Gist you don't own"); + } + + const content = activeEditor.document.getText(); + const filename = path.basename(uri.path); + + await updateGistFiles(gistId, [ + [filename, { + filename: filename, + content: content + }] + ]); + + await refreshGist(gistId); + + store.unsyncedFiles.delete(uri.toString()); + } catch (err) { + error = err as Error; + } + } + ); + + if (error) { + const message = error instanceof Error ? error.message : 'Unknown error occurred'; + window.showErrorMessage(`Failed to upload: ${message}`); + } else { + window.showInformationMessage("Successfully uploaded to GitHub Gist"); + } +} + const SIGN_IN_ITEM = "Sign in to view Gists..."; const CREATE_PUBLIC_GIST_ITEM = "$(gist-new) Create new public Gist..."; const CREATE_SECRET_GIST_ITEM = "$(gist-private) Create new secret Gist..."; @@ -697,4 +751,8 @@ export async function registerGistCommands(context: ExtensionContext) { } ) ); + + context.subscriptions.push( + commands.registerCommand(`${EXTENSION_NAME}.syncGist`, syncGistInternal) + ); } diff --git a/src/config.ts b/src/config.ts index 2b68269..7fa22ef 100644 --- a/src/config.ts +++ b/src/config.ts @@ -13,6 +13,7 @@ export function get(key: "scratchNotes.show"): boolean; export function get(key: "showcaseUrl"): string; export function get(key: "comments.showThread"): string; export function get(key: "output"): boolean; +export function get(key: "autoSyncWhenSave"): boolean; export function get(key: any) { const extensionConfig = vscode.workspace.getConfiguration(CONFIG_SECTION); return extensionConfig.get(key); diff --git a/src/fileSystem/index.ts b/src/fileSystem/index.ts index c3b0504..6d52117 100644 --- a/src/fileSystem/index.ts +++ b/src/fileSystem/index.ts @@ -12,10 +12,12 @@ import { FileSystemProvider, FileType, ProgressLocation, + TabInputText, Uri, window, workspace } from "vscode"; +import * as config from "../config"; import { DIRECTORY_SEPARATOR, ENCODED_DIRECTORY_SEPARATOR, @@ -23,7 +25,7 @@ import { ZERO_WIDTH_SPACE } from "../constants"; import { Gist, GistFile, Store } from "../store"; -import { forkGist, getGist } from "../store/actions"; +import { forkGist, getGist, refreshGist } from "../store/actions"; import { ensureAuthenticated } from "../store/auth"; import { byteArrayToString, @@ -54,6 +56,55 @@ export class GistFileSystemProvider implements FileSystemProvider { ._onDidChangeFile.event; constructor(private store: Store) { + + window.tabGroups.onDidChangeTabs(async (tabGroups) => { + if (tabGroups.closed.length === 0) { + return; + } + + for (const tab of tabGroups.closed) { + const input = tab.input as TabInputText; + if (!(input instanceof TabInputText) || !input.uri) { + continue; + } + + const uri = input.uri.toString(); + if (!uri.startsWith(FS_SCHEME) || !this.store.unsyncedFiles.has(uri)) { + continue; + } + + const filename = path.basename(Uri.parse(uri).path); + const { gistId } = getGistDetailsFromUri(Uri.parse(uri)); + + const result = await window.showWarningMessage( + `${filename} has changes that have not been synced to GitHub. Do you want to sync them now?`, + { modal: true }, + "Yes", + "Discard Changes" + ); + + if (result === "Yes") { + const document = workspace.textDocuments.find(doc => doc.uri.toString() === uri); + if (document) { + try { + await updateGistFiles(gistId, [ + [filename, { + filename, + content: document.getText() + }] + ]); + + await refreshGist(gistId); + } catch (err: any) { + window.showErrorMessage(`Failed to sync changes: ${err.message}`); + } + } + } + + this.store.unsyncedFiles.delete(uri); + } + }); + this._pendingWrites .pipe(buffer(this._pendingWrites.pipe(debounceTime(100)))) .subscribe((operations: WriteOperation[]) => { @@ -386,6 +437,13 @@ export class GistFileSystemProvider implements FileSystemProvider { const file = await this.getFileFromUri(uri); const type = file ? FileChangeType.Changed : FileChangeType.Created; + const autoSyncEnabled = config.get("autoSyncWhenSave"); + if (!autoSyncEnabled && type === FileChangeType.Changed) { + this.store.unsyncedFiles.add(uri.toString()); + this._onDidChangeFile.fire([{ type, uri }]); + return; + } + return new Promise((resolve) => { this._pendingWrites.next({ type, diff --git a/src/store/index.ts b/src/store/index.ts index 08dbaed..fe3ab21 100644 --- a/src/store/index.ts +++ b/src/store/index.ts @@ -116,6 +116,7 @@ export interface Store { starredGists: Gist[]; canCreateRepos: boolean; canDeleteRepos: boolean; + unsyncedFiles: Set; } export const store: Store = observable({ @@ -132,5 +133,6 @@ export const store: Store = observable({ groupType: GroupType.none, starredGists: [], canCreateRepos: false, - canDeleteRepos: false + canDeleteRepos: false, + unsyncedFiles: new Set() });