Path: blob/main/extensions/configuration-editing/src/importExportProfiles.ts
3291 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import { Octokit } from '@octokit/rest';6import * as vscode from 'vscode';7import { basename } from 'path';8import { agent } from './node/net';910class GitHubGistProfileContentHandler implements vscode.ProfileContentHandler {1112readonly name = vscode.l10n.t('GitHub');13readonly description = vscode.l10n.t('gist');1415private _octokit: Promise<Octokit> | undefined;16private getOctokit(): Promise<Octokit> {17if (!this._octokit) {18this._octokit = (async () => {19const session = await vscode.authentication.getSession('github', ['gist', 'user:email'], { createIfNone: true });20const token = session.accessToken;2122const { Octokit } = await import('@octokit/rest');2324return new Octokit({25request: { agent },26userAgent: 'GitHub VSCode',27auth: `token ${token}`28});29})();30}31return this._octokit;32}3334async saveProfile(name: string, content: string): Promise<{ readonly id: string; readonly link: vscode.Uri } | null> {35const octokit = await this.getOctokit();36const result = await octokit.gists.create({37public: false,38files: {39[name]: {40content41}42}43});44if (result.data.id && result.data.html_url) {45const link = vscode.Uri.parse(result.data.html_url);46return { id: result.data.id, link };47}48return null;49}5051private _public_octokit: Promise<Octokit> | undefined;52private getPublicOctokit(): Promise<Octokit> {53if (!this._public_octokit) {54this._public_octokit = (async () => {55const { Octokit } = await import('@octokit/rest');56return new Octokit({ request: { agent }, userAgent: 'GitHub VSCode' });57})();58}59return this._public_octokit;60}6162async readProfile(id: string): Promise<string | null>;63async readProfile(uri: vscode.Uri): Promise<string | null>;64async readProfile(arg: string | vscode.Uri): Promise<string | null> {65const gist_id = typeof arg === 'string' ? arg : basename(arg.path);66const octokit = await this.getPublicOctokit();67try {68const gist = await octokit.gists.get({ gist_id });69if (gist.data.files) {70return gist.data.files[Object.keys(gist.data.files)[0]]?.content ?? null;71}72} catch (error) {73// ignore74}75return null;76}7778}7980vscode.window.registerProfileContentHandler('github', new GitHubGistProfileContentHandler());818283