Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Manual sync feature. #375

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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`.
15 changes: 15 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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."
}
}
},
Expand Down Expand Up @@ -534,6 +539,11 @@
{
"command": "gistpad.viewForks",
"title": "View Forks"
},
{
"command": "gistpad.syncGist",
"title": "Sync Gist",
"icon": "$(sync)"
}
],
"menus": {
Expand Down Expand Up @@ -1364,6 +1374,11 @@
{
"command": "gistpad.renameRepositoryFile",
"when": "resourceScheme == repo"
},
{
"command": "gistpad.syncGist",
"when": "resourceScheme == gist && !gistpad.autoSyncWhenSave",
"group": "navigation@1"
}
],
"editor/title/context": [
Expand Down
58 changes: 58 additions & 0 deletions src/commands/gist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -41,16 +42,19 @@ import {
encodeDirectoryName,
fileNameToUri,
getGistDescription,
getGistDetailsFromUri,
getGistLabel,
getGistWorkspaceId,
isGistWorkspace,
isOwnedGist,
openGist,
openGistFiles,
sortGists,
updateGistTags,
withProgress
} from "../utils";
const isBinaryPath = require("is-binary-path");
const path = require("path");

const GIST_NAME_PATTERN = /(\/)?(?<owner>([a-z\d]+-)*[a-z\d]+)\/(?<id>[^\/]+)$/i;

Expand Down Expand Up @@ -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...";
Expand Down Expand Up @@ -697,4 +751,8 @@ export async function registerGistCommands(context: ExtensionContext) {
}
)
);

context.subscriptions.push(
commands.registerCommand(`${EXTENSION_NAME}.syncGist`, syncGistInternal)
);
}
1 change: 1 addition & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
60 changes: 59 additions & 1 deletion src/fileSystem/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,20 @@ import {
FileSystemProvider,
FileType,
ProgressLocation,
TabInputText,
Uri,
window,
workspace
} from "vscode";
import * as config from "../config";
import {
DIRECTORY_SEPARATOR,
ENCODED_DIRECTORY_SEPARATOR,
FS_SCHEME,
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,
Expand Down Expand Up @@ -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[]) => {
Expand Down Expand Up @@ -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,
Expand Down
4 changes: 3 additions & 1 deletion src/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ export interface Store {
starredGists: Gist[];
canCreateRepos: boolean;
canDeleteRepos: boolean;
unsyncedFiles: Set<string>;
}

export const store: Store = observable({
Expand All @@ -132,5 +133,6 @@ export const store: Store = observable({
groupType: GroupType.none,
starredGists: [],
canCreateRepos: false,
canDeleteRepos: false
canDeleteRepos: false,
unsyncedFiles: new Set<string>()
});