[extension] Clone and open correct repo

This commit is contained in:
orosmatthew 2023-05-06 12:36:34 -04:00
parent 559666e34a
commit 5d48bd0b37
4 changed files with 152 additions and 66 deletions

View File

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

View File

@ -1,10 +1,14 @@
import * as vscode from 'vscode';
import { getNonce } from './getNonce';
import { cloneAndOpenRepo } from './extension';
export class SidebarProvider implements vscode.WebviewViewProvider {
_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) {
this._view = webviewView;
@ -20,6 +24,34 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
webviewView.webview.onDidReceiveMessage(async (data) => {
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': {
if (!data.value) {
return;
@ -38,7 +70,6 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
});
}
private _getHtmlForWebview(webview: vscode.Webview) {
const styleResetUri = webview.asWebviewUri(
vscode.Uri.joinPath(this._extensionUri, 'media', 'reset.css')

View File

@ -1,7 +1,5 @@
import * as vscode from 'vscode';
import { BWPanel } from './BWPanel';
import { SidebarProvider } from './SidebarProvider';
import { notDeepEqual } from 'assert';
import * as child_process from 'child_process';
import * as fs from 'fs-extra';
@ -21,11 +19,30 @@ function closeAllWorkspaces() {
}
}
async function cloneAndOpenRepo(baseUrl: string, path: string, contestId: number, teamId: number) {
const repoUrl = `${baseUrl}/${contestId.toString()}/${teamId.toString()}.git`;
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', '')!;
const clonedRepoPath = `${path}/${repoName}`;
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(
@ -40,12 +57,16 @@ async function cloneAndOpenRepo(baseUrl: string, path: string, contestId: number
fs.removeSync(clonedRepoPath);
}
child_process.exec(`git clone ${repoUrl}`, { cwd: path }, (error, stdout, stderr) => {
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,
@ -62,28 +83,12 @@ async function cloneAndOpenRepo(baseUrl: string, path: string, contestId: number
}
export function activate(context: vscode.ExtensionContext) {
const sidebarProvider = new SidebarProvider(context.extensionUri);
const sidebarProvider = new SidebarProvider(context.extensionUri, context);
context.subscriptions.push(
vscode.window.registerWebviewViewProvider('bwcontest-sidebar', sidebarProvider)
);
context.subscriptions.push(
vscode.commands.registerCommand('bwcontest.helloWorld', () => {
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;
}
cloneAndOpenRepo(currentSettings.repoBaseUrl, currentSettings.repoClonePath, 102, 1);
})
);
context.subscriptions.push(vscode.commands.registerCommand('bwcontest.helloWorld', () => {}));
context.subscriptions.push(
vscode.commands.registerCommand('bwcontest.askQuestion', async () => {

View File

@ -1,14 +1,41 @@
<script lang="ts">
function postMessage(message: any) {
import { onMount } from "svelte";
function postMessage(message: any) {
vscode.postMessage(message);
}
}
let teamname: HTMLInputElement;
let password: HTMLInputElement;
let teamname: 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 {
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
@ -23,27 +50,45 @@ async function onLogin() {
return;
}
sessionToken = data.token;
postMessage({type: 'onLogin', value: sessionToken});
} catch (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({
token: sessionToken,
})})
if (res.status !== 200) {
postMessage({type: 'onError', value: 'Error logging out'});
sessionToken = undefined;
return;
}
const data = await res.json();
if (data.success === true) {
postMessage({type: 'onInfo', value: 'BWContest: Logged out'});
sessionToken = undefined;
postMessage({type: 'onLogout'});
} else {
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>
<h1>Contest</h1>
@ -58,4 +103,9 @@ async function onLogout() {
<button on:click={onLogin}>Login</button>
{:else}
<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}