This commit is contained in:
Admin 2023-05-06 12:36:53 -04:00
commit 631fb2b040
10 changed files with 1316 additions and 234 deletions

View File

@ -1,24 +0,0 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {
"@typescript-eslint/naming-convention": "warn",
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off"
},
"ignorePatterns": [
"out",
"dist",
"**/*.d.ts"
]
}

View File

@ -1,10 +1,2 @@
.vscode/** node_modules
.vscode-test/** .vscode
src/**
.gitignore
.yarnrc
vsc-extension-quickstart.md
**/tsconfig.json
**/.eslintrc.json
**/*.map
**/*.ts

View File

@ -1,71 +0,0 @@
# bwcontest README
This is the README for your extension "bwcontest". After writing up a brief description, we recommend including the following sections.
## Features
Describe specific features of your extension including screenshots of your extension in action. Image paths are relative to this README file.
For example if there is an image subfolder under your extension project workspace:
\!\[feature X\]\(images/feature-x.png\)
> Tip: Many popular extensions utilize animations. This is an excellent way to show off your extension! We recommend short, focused animations that are easy to follow.
## Requirements
If you have any requirements or dependencies, add a section describing those and how to install and configure them.
## Extension Settings
Include if your extension adds any VS Code settings through the `contributes.configuration` extension point.
For example:
This extension contributes the following settings:
* `myExtension.enable`: Enable/disable this extension.
* `myExtension.thing`: Set to `blah` to do something.
## Known Issues
Calling out known issues can help limit users opening duplicate issues against your extension.
## Release Notes
Users appreciate release notes as you update your extension.
### 1.0.0
Initial release of ...
### 1.0.1
Fixed issue #.
### 1.1.0
Added features X, Y, and Z.
---
## Following extension guidelines
Ensure that you've read through the extensions guidelines and follow the best practices for creating your extension.
* [Extension Guidelines](https://code.visualstudio.com/api/references/extension-guidelines)
## Working with Markdown
You can author your README using Visual Studio Code. Here are some useful editor keyboard shortcuts:
* Split the editor (`Cmd+\` on macOS or `Ctrl+\` on Windows and Linux).
* Toggle preview (`Shift+Cmd+V` on macOS or `Shift+Ctrl+V` on Windows and Linux).
* Press `Ctrl+Space` (Windows, Linux, macOS) to see a list of Markdown snippets.
## For more information
* [Visual Studio Code's Markdown Support](http://code.visualstudio.com/docs/languages/markdown)
* [Markdown Syntax Reference](https://help.github.com/articles/markdown-basics/)
**Enjoy!**

File diff suppressed because it is too large Load Diff

View File

@ -12,6 +12,21 @@
"activationEvents": [], "activationEvents": [],
"main": "./out/extension.js", "main": "./out/extension.js",
"contributes": { "contributes": {
"configuration": {
"title": "BWContest",
"properties": {
"BWContest.repoBaseUrl": {
"type": "string",
"default": "",
"description": "Base URL for where to clone repos from"
},
"BWContest.repoClonePath": {
"type": "string",
"default": "",
"description": "The path where the repos are cloned to"
}
}
},
"viewsContainers": { "viewsContainers": {
"activitybar": [ "activitybar": [
{ {
@ -58,6 +73,7 @@
"@rollup/plugin-node-resolve": "^15.0.2", "@rollup/plugin-node-resolve": "^15.0.2",
"@rollup/plugin-typescript": "^11.1.0", "@rollup/plugin-typescript": "^11.1.0",
"@tsconfig/svelte": "^4.0.1", "@tsconfig/svelte": "^4.0.1",
"@types/fs-extra": "^11.0.1",
"@types/glob": "^8.1.0", "@types/glob": "^8.1.0",
"@types/mocha": "^10.0.1", "@types/mocha": "^10.0.1",
"@types/node": "16.x", "@types/node": "16.x",
@ -80,6 +96,8 @@
"typescript": "^5.0.4" "typescript": "^5.0.4"
}, },
"dependencies": { "dependencies": {
"axios": "^1.4.0" "axios": "^1.4.0",
"fs-extra": "^11.1.1",
"vsce": "^2.15.0"
} }
} }

View File

@ -28,7 +28,7 @@ export class BWPanel {
// Otherwise, create a new panel. // Otherwise, create a new panel.
const panel = vscode.window.createWebviewPanel( const panel = vscode.window.createWebviewPanel(
BWPanel.viewType, BWPanel.viewType,
'VSinder', 'BWContest',
column || vscode.ViewColumn.One, column || vscode.ViewColumn.One,
{ {
// Enable javascript in the webview // Enable javascript in the webview

View File

@ -1,10 +1,14 @@
import * as vscode from 'vscode'; import * as vscode from 'vscode';
import { getNonce } from './getNonce'; import { getNonce } from './getNonce';
import { cloneAndOpenRepo } from './extension';
export class SidebarProvider implements vscode.WebviewViewProvider { export class SidebarProvider implements vscode.WebviewViewProvider {
_view?: vscode.WebviewView; _view?: vscode.WebviewView;
_context?: vscode.ExtensionContext;
constructor(private readonly _extensionUri: vscode.Uri) {} constructor(private readonly _extensionUri: vscode.Uri, context: vscode.ExtensionContext) {
this._context = context;
}
public resolveWebviewView(webviewView: vscode.WebviewView) { public resolveWebviewView(webviewView: vscode.WebviewView) {
this._view = webviewView; this._view = webviewView;
@ -20,6 +24,34 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
webviewView.webview.onDidReceiveMessage(async (data) => { webviewView.webview.onDidReceiveMessage(async (data) => {
switch (data.type) { switch (data.type) {
case 'onStartup': {
const token: string | undefined = this._context?.globalState.get('token');
if (token) {
this._view?.webview.postMessage({
type: 'onSession',
value: token
});
}
break;
}
case 'onClone': {
if (!data.value || !data.value.contestId || !data.value.teamId) {
return;
}
await cloneAndOpenRepo(parseInt(data.value.contestId), parseInt(data.value.teamId));
break;
}
case 'onLogin': {
if (!data.value) {
return;
}
this._context?.globalState.update('token', data.value);
break;
}
case 'onLogout': {
this._context?.globalState.update('token', null);
break;
}
case 'onInfo': { case 'onInfo': {
if (!data.value) { if (!data.value) {
return; return;
@ -38,7 +70,6 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
}); });
} }
private _getHtmlForWebview(webview: vscode.Webview) { private _getHtmlForWebview(webview: vscode.Webview) {
const styleResetUri = webview.asWebviewUri( const styleResetUri = webview.asWebviewUri(
vscode.Uri.joinPath(this._extensionUri, 'media', 'reset.css') vscode.Uri.joinPath(this._extensionUri, 'media', 'reset.css')

View File

@ -1,18 +1,94 @@
import * as vscode from 'vscode'; import * as vscode from 'vscode';
import { BWPanel } from './BWPanel';
import { SidebarProvider } from './SidebarProvider'; import { SidebarProvider } from './SidebarProvider';
import { notDeepEqual } from 'assert'; import * as child_process from 'child_process';
import * as fs from 'fs-extra';
interface BWContestSettings {
repoBaseUrl: string;
repoClonePath: string;
}
function closeAllWorkspaces() {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders) {
return;
}
const removedFolders = vscode.workspace.updateWorkspaceFolders(0, workspaceFolders.length);
if (!removedFolders) {
return;
}
}
export async function cloneAndOpenRepo(contestId: number, teamId: number) {
const currentSettings = vscode.workspace.getConfiguration().get<BWContestSettings>('BWContest');
if (!currentSettings || currentSettings.repoBaseUrl == '') {
vscode.window.showErrorMessage('BWContest: BWContest.repoBaseURL not set');
return;
}
if (!currentSettings || currentSettings.repoClonePath == '') {
vscode.window.showErrorMessage('BWContest: BWContest.repoClonePath not set');
return;
}
const repoUrl = `${currentSettings.repoBaseUrl}/${contestId.toString()}/${teamId.toString()}.git`;
const repoName = repoUrl.split('/').pop()?.replace('.git', '')!;
if (!fs.existsSync(`${currentSettings.repoClonePath}/BWContest`)) {
fs.mkdirSync(`${currentSettings.repoClonePath}/BWContest`);
}
if (!fs.existsSync(`${currentSettings.repoClonePath}/BWContest/${contestId.toString()}`)) {
fs.mkdirSync(`${currentSettings.repoClonePath}/BWContest/${contestId.toString()}`);
}
const clonedRepoPath = `${currentSettings.repoClonePath}/BWContest/${contestId.toString()}/${repoName}`;
if (fs.existsSync(clonedRepoPath)) {
const confirm = await vscode.window.showWarningMessage(
'The repo already exists. Do you want to replace it?',
'Delete and Replace',
'Cancel'
);
if (confirm !== 'Delete and Replace') {
return;
}
closeAllWorkspaces();
fs.removeSync(clonedRepoPath);
}
child_process.exec(
`git clone ${repoUrl}`,
{ cwd: `${currentSettings.repoClonePath}/BWContest/${contestId.toString()}` },
(error, stdout, stderr) => {
if (error) {
vscode.window.showErrorMessage(`BWContest: Failed to clone repo: ${error.message}`);
return;
}
}
);
const addedFolder = vscode.workspace.updateWorkspaceFolders(
vscode.workspace.workspaceFolders?.length ?? 0,
0,
{ uri: vscode.Uri.file(clonedRepoPath), name: 'BWContest' }
);
if (!addedFolder) {
vscode.window.showErrorMessage('BWContest: Failed to open cloned repo');
return;
}
vscode.window.showInformationMessage('BWContest: Repo cloned and opened');
}
export function activate(context: vscode.ExtensionContext) { export function activate(context: vscode.ExtensionContext) {
const sidebarProvider = new SidebarProvider(context.extensionUri); const sidebarProvider = new SidebarProvider(context.extensionUri, context);
context.subscriptions.push( context.subscriptions.push(
vscode.window.registerWebviewViewProvider('bwcontest-sidebar', sidebarProvider) vscode.window.registerWebviewViewProvider('bwcontest-sidebar', sidebarProvider)
); );
context.subscriptions.push( context.subscriptions.push(vscode.commands.registerCommand('bwcontest.helloWorld', () => {}));
vscode.commands.registerCommand('bwcontest.helloWorld', () => {
})
);
context.subscriptions.push( context.subscriptions.push(
vscode.commands.registerCommand('bwcontest.askQuestion', async () => { vscode.commands.registerCommand('bwcontest.askQuestion', async () => {

View File

@ -1,42 +0,0 @@
# Welcome to your VS Code Extension
## What's in the folder
* This folder contains all of the files necessary for your extension.
* `package.json` - this is the manifest file in which you declare your extension and command.
* The sample plugin registers a command and defines its title and command name. With this information VS Code can show the command in the command palette. It doesnt yet need to load the plugin.
* `src/extension.ts` - this is the main file where you will provide the implementation of your command.
* The file exports one function, `activate`, which is called the very first time your extension is activated (in this case by executing the command). Inside the `activate` function we call `registerCommand`.
* We pass the function containing the implementation of the command as the second parameter to `registerCommand`.
## Get up and running straight away
* Press `F5` to open a new window with your extension loaded.
* Run your command from the command palette by pressing (`Ctrl+Shift+P` or `Cmd+Shift+P` on Mac) and typing `Hello World`.
* Set breakpoints in your code inside `src/extension.ts` to debug your extension.
* Find output from your extension in the debug console.
## Make changes
* You can relaunch the extension from the debug toolbar after changing code in `src/extension.ts`.
* You can also reload (`Ctrl+R` or `Cmd+R` on Mac) the VS Code window with your extension to load your changes.
## Explore the API
* You can open the full set of our API when you open the file `node_modules/@types/vscode/index.d.ts`.
## Run tests
* Open the debug viewlet (`Ctrl+Shift+D` or `Cmd+Shift+D` on Mac) and from the launch configuration dropdown pick `Extension Tests`.
* Press `F5` to run the tests in a new window with your extension loaded.
* See the output of the test result in the debug console.
* Make changes to `src/test/suite/extension.test.ts` or create new test files inside the `test/suite` folder.
* The provided test runner will only consider files matching the name pattern `**.test.ts`.
* You can create folders inside the `test` folder to structure your tests any way you want.
## Go further
* [Follow UX guidelines](https://code.visualstudio.com/api/ux-guidelines/overview) to create extensions that seamlessly integrate with VS Code's native interface and patterns.
* Reduce the extension size and improve the startup time by [bundling your extension](https://code.visualstudio.com/api/working-with-extensions/bundling-extension).
* [Publish your extension](https://code.visualstudio.com/api/working-with-extensions/publishing-extension) on the VS Code extension marketplace.
* Automate builds by setting up [Continuous Integration](https://code.visualstudio.com/api/working-with-extensions/continuous-integration).

View File

@ -1,14 +1,41 @@
<script lang="ts"> <script lang="ts">
function postMessage(message: any) { import { onMount } from "svelte";
function postMessage(message: any) {
vscode.postMessage(message); vscode.postMessage(message);
} }
let teamname: HTMLInputElement; let teamname: HTMLInputElement;
let password: HTMLInputElement; let password: HTMLInputElement;
let sessionToken: string | undefined; let sessionToken: string | undefined;
async function onLogin() { interface TeamData {
teamId: number,
contestId: number
}
let teamData: TeamData | undefined;
async function fetchTeamData() {
if (sessionToken) {
const res = await fetch(`http://localhost:5173/api/team/${sessionToken}`, {method: "GET"});
const data = await res.json();
if (!data.success) {
postMessage({type: 'onError', value: "BWContest: Failed to fetch team data"});
return;
}
teamData = data.data as TeamData;
}
}
async function onClone() {
if (teamData) {
postMessage({type: 'onClone', value: {contestId: teamData.contestId, teamId: teamData.teamId}});
}
}
async function onLogin() {
try { try {
const res = await fetch("http://localhost:5173/api/team/login", {method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ const res = await fetch("http://localhost:5173/api/team/login", {method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({
teamname: teamname.value, password: password.value teamname: teamname.value, password: password.value
@ -23,27 +50,45 @@ async function onLogin() {
return; return;
} }
sessionToken = data.token; sessionToken = data.token;
postMessage({type: 'onLogin', value: sessionToken});
} catch (err) { } catch (err) {
console.error('Failed to fetch:', err); console.error('Failed to fetch:', err);
} }
} fetchTeamData();
}
async function onLogout() { async function onLogout() {
const res = await fetch("http://localhost:5173/api/team/logout", {method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ const res = await fetch("http://localhost:5173/api/team/logout", {method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({
token: sessionToken, token: sessionToken,
})}) })})
if (res.status !== 200) { if (res.status !== 200) {
postMessage({type: 'onError', value: 'Error logging out'}); postMessage({type: 'onError', value: 'Error logging out'});
sessionToken = undefined;
return; return;
} }
const data = await res.json(); const data = await res.json();
if (data.success === true) { if (data.success === true) {
postMessage({type: 'onInfo', value: 'BWContest: Logged out'}); postMessage({type: 'onInfo', value: 'BWContest: Logged out'});
sessionToken = undefined; sessionToken = undefined;
postMessage({type: 'onLogout'});
} else { } else {
postMessage({type: 'onError', value: 'Log out unsuccessful'}); postMessage({type: 'onError', value: 'Log out unsuccessful'});
} }
} }
window.addEventListener("message", event => {
const message = (event as MessageEvent).data;
if (message.type === "onSession") {
if (message.value !== "") {
sessionToken = message.value;
fetchTeamData();
}
}
})
onMount(() => {
postMessage({type: "onStartup"});
})
</script> </script>
<h1>Contest</h1> <h1>Contest</h1>
@ -58,4 +103,9 @@ async function onLogout() {
<button on:click={onLogin}>Login</button> <button on:click={onLogin}>Login</button>
{:else} {:else}
<button on:click={onLogout}>Logout</button> <button on:click={onLogout}>Logout</button>
{#if teamData}
<p>TeamID: {teamData.teamId}</p>
<p>ContestID: {teamData.contestId}</p>
<button on:click={onClone}>Clone and Open Repo</button>
{/if}
{/if} {/if}