//
// Keep versions of files in EECS 482 github repos
//
const vscode = require('vscode');
const os = require('os');
const fs = require('fs');
const path = require('path');
const child_process = require('child_process');
const version = 'vscode-20261015';
const minTimeVersion = 10; // minimum time between versions
const minTimePush = 60; // minimum time between pushes
const minTimeCheck = 600; // minimum time between checking version482 repos
const autoOpenFileName = 'version482VscodeAutoOpen';
// filename to tell vscode to open a file on restart
const terminalOutputFileName = 'version482VscodeTerminalOutput';
// filename to store terminal output
const aiExtensions = [
'Anthropic.claude-code',
'openai.chatgpt',
'GitHub.copilot-chat',
'saoudrizwan.claude-dev',
'saoudrizwan.cline-nightly',
'RooVeterinaryInc.roo-cline',
'amazonwebservices.amazon-q-vscode',
'AndrePimenta.claude-code-chat',
'openai.codex-audio',
];
let versionTime = {}; // last time each file was written
let pushTime = {}; // last time each repo was pushed
let checkTime = 0; // last time version482 repos were checked
let versionDir = {}; // .version482 directory name for each source file directory
let timer = {};
let saveTerminal = undefined;
exports.activate = () => {
vscode.workspace.textDocuments.forEach(doc => initVersionDir(doc));
vscode.workspace.onDidOpenTextDocument(doc => {
onChangeDocument(doc);
});
vscode.workspace.onDidChangeTextDocument(e => {
onChangeDocument(e.document);
});
vscode.workspace.onDidSaveTextDocument(doc => {
onSaveDocument(doc);
});
if (vscode.workspace.workspaceFolders) {
const autoOpen = vscode.workspace.workspaceFolders[0].uri.fsPath + path.sep + autoOpenFileName;
// see if a prior instance of vscode has asked to open a file
if (fs.existsSync(autoOpen)) {
const autoOpenString = fs.readFileSync(autoOpen).toString();
fs.unlinkSync(autoOpen);
console.log('version482: auto-opening ' + autoOpenString);
const fileUri = vscode.Uri.file(autoOpenString);
vscode.workspace.openTextDocument(fileUri).then(doc => {
vscode.window.showTextDocument(doc);
});
}
} else {
console.log('version482: no workspace folders');
}
}
// return current time in seconds
function time() {
return(Math.trunc(Date.now()/1000));
}
async function onSaveDocument(doc) {
await saveFile(doc);
}
async function onChangeDocument(doc) {
await textChanged(doc);
}
// See if directory is in an EECS 482 git repo.
// Store .version482 directory name in versionDir, and make sure the .version482
// directory exists and is properly configured. If the directory isn't in an
// EECS 482 git repo, then set the versionDir entry to the empty string.
async function initVersionDir(doc) {
const dir = path.dirname(doc.fileName);
console.log('initVersionDir: dir=' + dir);
if (dir in versionDir) {
return;
}
// Set versionDir[dir] to the empty string for now. This prevents any
// concurrent calls to initVersionDir from conflicting with the
// ongoing work of this call.
versionDir[dir] = '';
let versionDirResult = '';
let date1 = new Date();
let dateString = date1.getFullYear().toString() + '.'
+ (date1.getMonth()+1).toString().padStart(2, '0') + '.'
+ date1.getDate().toString().padStart(2, '0') + '_'
+ date1.getHours().toString().padStart(2, '0') + '.'
+ date1.getMinutes().toString().padStart(2, '0') + '.'
+ date1.getSeconds().toString().padStart(2, '0');
let top = '';
let dirFound = '';
let protocol;
let repo;
let suffix;
// Check that the directory exists and is an EECS 482 repo
try {
// Make sure the directory exists.
// Windows VS Code may prepend extra directory components when WSL
// files are opened as local files). Fix this by removing directory
// components from the beginning of the directory name until I find a
// directory that exists.
if (fs.existsSync(dir)) {
dirFound = dir;
} else {
// Parse the directory name into components.
let dirRoot = dir;
let dirRootLast;
let basename = "";
let components = [];
do {
dirRootLast = dirRoot;
basename = path.basename(dirRoot);
if (basename != "") {
components.unshift(basename);
dirRoot = path.dirname(dirRoot);
}
} while (basename != "" && dirRoot != dirRootLast);
// Look for the directory, removing prefixes if needed.
for (let i=0; i<components.length && dirFound == ""; i++) {
const dir1 = dirRoot + components.slice(i).join(path.sep);
if (fs.existsSync(dir1)) {
dirFound = dir1;
}
}
}
if (dirFound == "") {
console.log('initVersionDir cannot find ' + dir);
throw new Error('initVersionDir: ' + dir + ' does not exist');
}
// Get top level of working tree
// This will throw an exception if git rev-parse fails, e.g., if
// the directory is not in a work tree
top = child_process.execSync('git -C "' + dirFound + '" rev-parse --show-toplevel').toString().trimEnd();
console.log('initVersionDir: top=' + top);
// Make sure top level is an eecs482 repo and get name of main repo
const origin = child_process.execSync('git -C "' + dirFound + '" remote get-url origin 2> /dev/null').toString();
console.log('initVersionDir: origin=' + origin);
const found = origin.match(/^(git@github.com:|https:\/\/.*github.com\/|ssh:\/\/git@github.com\/)(eecs482\/[a-z.]+\d+)(.*)/);
if (! found) {
throw new Error('File is not in an eecs482 project repository');
}
protocol = found[1];
repo = found[2];
suffix = found[3];
// Make sure main repo is not a version482 repo
if (origin.indexOf('version482') >= 0) {
// disallow editing of files in version482 repo
vscode.commands.executeCommand('workbench.action.closeActiveEditor');
throw new Error('File is in a version482 repo');
}
} catch (err) {
console.log('initVersionDir: ' + dir + ' is not in an EECS 482 git repo');
console.log(err);
return;
}
// This directory is in an EECS 482 git repo. If I encounter errors
// from this point on, delete versionDir[dir] so it gets tried again later.
try {
// Compute correct branch for this local repo. Treat all CAEN
// machines as a single host, since they use a shared file system.
let hostname = os.hostname().replace(/\..*/, "").replace(/^caen-vnc-mi[0-9]*/, "caen-vnc-mi");
let branch = os.userInfo().username + hostname + child_process.execSync('uname -s').toString().trimEnd();
if (fs.existsSync('/etc/os-release')) {
branch += child_process.execSync('grep "^ID=" /etc/os-release | sed "s/^.*=//"').toString().trimEnd();
}
branch += top;
branch = branch.replace(/[^a-zA-Z0-9]/g, "");
console.log('initVersionDir: branch=' + branch);
versionDirResult = top + path.sep + '.version482.' + branch;
console.log('initVersionDir: versionDirResult=' + versionDirResult);
// Check version482 repository and move it aside if broken
try {
// Make sure version482 exists and is a directory
if (! fs.existsSync(versionDirResult) || ! fs.statSync(versionDirResult).isDirectory()) {
throw new Error(versionDirResult + ' does not exist or is not a directory.');
}
console.log('initVersionDir: ' + versionDirResult + ' exists and is a directory');
// Make sure version482 is its own repo
const version482_top = child_process.execSync('git -C "' + versionDirResult + '" rev-parse --show-toplevel').toString().trimEnd();
console.log('initVersionDir: version482_top=' + version482_top);
if (version482_top != versionDirResult) {
throw new Error(versionDirResult + ' is not in its own repository.');
}
// Make sure origin for version482 repo is consistent with origin for
// main repo
const url = child_process.execSync('git -C "' + versionDirResult + '" remote get-url origin 2> /dev/null').toString().trimEnd();
console.log('initVersionDir: url=' + url);
if (url != protocol + repo + '.version482' + suffix) {
throw new Error('origin for ' + versionDirResult + ' is inconsistent with origin for main repo.');
}
// Make sure version482 repo is on the correct branch
const branch1 = child_process.execSync('git -C "' + versionDirResult + '" branch --show-current').toString().trimEnd();
console.log('initVersionDir: branch1=' + branch1);
if (branch1 != branch) {
throw new Error(versionDirResult + ' is on wrong branch ' + branch1);
}
// Make sure version482 repo's upstream is set to the corresponding
// branch on github
const remote = child_process.execSync('git -C "' + versionDirResult + '" rev-parse --abbrev-ref "@{upstream}" 2> /dev/null').toString().trimEnd();
console.log('initVersionDir: remote=' + remote);
if (remote != "origin/" + branch) {
throw new Error(versionDirResult + ' has the wrong upstream');
}
// Make sure version482 repo is not corrupted
child_process.execSync('git -C "' + versionDirResult + '" status > /dev/null');
console.log('initVersionDir: status succeeded');
// Make sure I can add a file in the version482 repo
child_process.execSync('touch "' + versionDirResult + path.sep + 'tmp.' + dateString + '"; git -C "' + versionDirResult + '" add -f "tmp.' + dateString + '" > /dev/null');
console.log('initVersionDir: touch and add succeeded');
// Make sure I can remove a file in the version482 repo
child_process.execSync('git -C "' + versionDirResult + '" rm -f -q "tmp.' + dateString + '" > /dev/null');
console.log('initVersionDir: rm succeeded');
} catch (err) {
// console.log(err);
if (fs.existsSync(versionDirResult)) {
console.log('initVersionDir: moving ' + versionDirResult + ' aside');
// Move broken version482 directory aside
let oldDir = versionDirResult + '.' + dateString;
while (fs.existsSync(oldDir)) {
oldDir += ".";
}
fs.renameSync(versionDirResult, oldDir);
}
}
if (! fs.existsSync(versionDirResult)) {
// Clone the version482 repo. This command requires github
// authentication, so send it via the vscode terminal.
// It would have been nice to use vscode's git extension, but
// that extension gets confused when asked to clone a version482
// repo, possibly because the name of the version482 repo has
// the same prefix as the main repo. I tried duplicating the
// terminal's environment variables and setting those in a child
// process, but that also failed.
const terminal = vscode.window.createTerminal({
name: 'version482',
shellPath: '/bin/sh',
hideFromUser: true,
});
const terminalClosed = new Promise((resolve) => {
const disposable = vscode.window.onDidCloseTerminal(
() => {
disposable.dispose();
resolve();
}
);
});
const outputFile = top + path.sep + terminalOutputFileName;
const cmd = 'git -C "' + top + '" clone "' + protocol + repo + '.version482' + suffix + '" "' + versionDirResult + '" > "' + outputFile + '" 2>&1 ; exit';
console.log('initVersionDir: ' + cmd);
terminal.sendText(cmd);
await terminalClosed;
const cloneOutput = fs.readFileSync(outputFile).toString();
fs.unlinkSync(outputFile);
console.log('outputFile: ' + cloneOutput);
if (fs.existsSync(versionDirResult)) {
console.log('initVersionDir: git clone succeeded');
} else {
// Clone failed.
console.log('initVersionDir: git clone failed. Output: ' + cloneOutput);
throw new Error('git clone failed: ' + cloneOutput);
}
// Configure the version482 repo to use the right branch
// (creating the branch if needed)
// Try to checkout branch, in case this branch already exists.
// This doesn't require github authentication.
try {
child_process.execSync('git -C "' + versionDirResult + '" checkout ' + branch + ' > /dev/null 2>&1');
console.log('initVersionDir: checkout branch succeeded');
} catch (err) {
// Branch didn't exist (this is the common case)
// Create new branch. This doesn't require github
// authentication.
child_process.execSync('git -C "' + versionDirResult + '" checkout -b ' + branch + ' --no-track > /dev/null');
console.log('initVersionDir: git checkout -b succeeded');
// Set upstream to github, and create branch on github.
// This command requires github authentication, so send it
// via the vscode terminal.
const terminal = vscode.window.createTerminal({
name: 'version482',
shellPath: '/bin/sh',
hideFromUser: true,
});
const terminalClosed = new Promise((resolve) => {
const disposable = vscode.window.onDidCloseTerminal(
() => {
disposable.dispose();
resolve();
}
);
});
const cmd = 'git -C "' + versionDirResult + '" push --set-upstream origin ' + branch + ' > "' + outputFile + '" 2>&1 ; exit';
console.log('initVersionDir: ' + cmd);
terminal.sendText(cmd);
await terminalClosed;
const checkoutOutput = fs.readFileSync(outputFile).toString();
fs.unlinkSync(outputFile);
console.log('outputFile: ' + checkoutOutput);
// Check that version482's repo's upstream was set correctly
const remote = child_process.execSync('git -C "' + versionDirResult + '" rev-parse --abbrev-ref "@{upstream}" 2> /dev/null').toString().trimEnd();
console.log('initVersionDir: remote=' + remote);
if (remote == "origin/" + branch) {
console.log('initVersionDir: git push --set-upstream origin succeeded');
} else {
// push --set-upstream origin failed
console.log('initVersionDir: git push --set-upstream origin failed: ' + checkoutOutput);
throw new Error('git push --set-upstream failed: ' + checkoutOutput);
}
}
}
} catch (err) {
// Encountered an error in cloning and configuring the version482
// directory. Usually this means there was an error authenticating
// to github.
console.log('initVersionDir(' + dir + ') caught exception when cloning or configuring version482 repository');
console.log(err);
// Delete the version482 directory in case it was partially set up.
child_process.execSync('rm -rf ' + versionDirResult);
// Delete versionDir[dir] to force a retry next time a file in this
// directory is opened.
delete versionDir[dir];
// Alert the user that there was an error, so they know to fix
// github authentication
vscode.window.showInformationMessage('version482 extension encountered error when cloning or configuring version482 repository: ' + err, {modal: true});
vscode.commands.executeCommand('workbench.action.closeActiveEditor');
return;
}
// The version482 repo is now set up.
console.log('initVersionDir: setting versionDir[' + dir + ']=' + versionDirResult);
versionDir[dir] = versionDirResult;
// Carry out miscellaneous tasks
try {
if (! vscode.workspace.workspaceFolders) {
// No workspace is open. Open the repo directory as a workspace.
// This will restart the extension, so arrange for the restarted
// extension to re-open the file by writing the file name to
// autoOpenFileName
console.log('initVersionDir: editing file without a workspace; re-opening file within a workspace');
fs.writeFileSync(top + path.sep + autoOpenFileName, doc.fileName);
vscode.commands.executeCommand('vscode.openFolder', vscode.Uri.file(top));
throw new Error('vscode.openFolder failed');
}
// Change workspace setting to disable copilot
let config = vscode.workspace.getConfiguration('chat');
if (! config.disableAIFeatures) {
config.update('disableAIFeatures', true, vscode.ConfigurationTarget.Workspace);
}
if (config.agent.enabled) {
config.update('agent.enabled', false, vscode.ConfigurationTarget.Workspace);
}
} catch (err) {
console.log('initVersionDir(' + dir + ') caught exception while trying to change workspace settings');
console.log(err);
}
// log extensions
try {
let out = '';
vscode.extensions.all.forEach(ext => {
aiExtensions.forEach((ext1) => {
if (ext.id == ext1) {
console.log('initVersionDir detected AI extension ' + ext1);
vscode.window.showInformationMessage('AI coding assistants are not allowed in EECS 482. Please disable ' + ext1 + ' for this workspace and restart VS Code.', {modal: true});
vscode.commands.executeCommand('workbench.action.closeActiveEditor');
}
});
let ext1 = {id: ext.id};
if ('packageJSON' in ext) {
if ('displayName' in ext.packageJSON) {
ext1.displayName = ext.packageJSON.displayName;
}
if ('isBuiltin' in ext.packageJSON) {
ext1.isBuiltin = ext.packageJSON.isBuiltin;
}
if ('description' in ext.packageJSON) {
ext1.description = ext.packageJSON.description;
}
if ('version' in ext.packageJSON) {
ext1.version= ext.packageJSON.version;
}
}
out += JSON.stringify(ext1) + "\n";
});
fs.writeFileSync(versionDirResult + path.sep + 'extensions.vscode', out);
child_process.execSync('git -C "' + versionDirResult + '" add -f extensions.vscode > /dev/null');
child_process.execSync('git -C "' + versionDirResult + '" commit --allow-empty -m "' + version + '" > /dev/null');
} catch (err) {
console.log('initVersionDir caught exception trying to log extensions');
console.log(err);
}
}
async function textChanged(doc) {
const now = time();
// Limit the rate of versioning events. Also save events where time has
// gone backward by more than minTimeVersion.
if (doc.fileName in versionTime
&& Math.abs(now - versionTime[doc.fileName]) < minTimeVersion) {
// replace any pending timer event for this file, so events don't pile up
if (doc.fileName in timer) {
clearTimeout(timer[doc.fileName]);
}
// make sure this version is eventually saved
timer[doc.fileName] = setTimeout(textChanged,
(minTimeVersion-(now-versionTime[doc.fileName]))*1000, doc);
return;
}
await initVersionDir(doc);
// make sure file is in an EECS 482 git repo
if (! (path.dirname(doc.fileName) in versionDir)
|| versionDir[path.dirname(doc.fileName)] == '') {
return;
}
console.log('textChanged: versionDir[' + path.dirname(doc.fileName) + ']=' + versionDir[path.dirname(doc.fileName)]);
const versionDirname = versionDir[path.dirname(doc.fileName)];
console.log('textChanged: versionDir[' + path.dirname(doc.fileName) + ']=' + versionDirname);
try {
// create/update file
const basename = path.basename(doc.fileName);
fs.writeFileSync(versionDirname + path.sep + basename, doc.getText());
console.log('textChanged: writeFileSync(' + versionDirname + path.sep + basename + ') succeeded');
// add file
child_process.execSync('git -C "' + versionDirname + '" add -f "' + basename + '" > /dev/null');
console.log('textChanged: git add succeeded');
// commit changes
child_process.execSync('git -C "' + versionDirname + '" commit --allow-empty -m "' + version + '" > /dev/null');
console.log('textChanged: git commit succeeded');
versionTime[doc.fileName] = now;
} catch (err) {
console.log('textChanged caught exception');
console.log(err);
}
}
// push commits to github
async function saveFile(doc) {
console.log('saveFile ' + doc.fileName);
const now = time();
// Clear versionDir every so often, so the version482 repo gets re-checked.
if (now - checkTime >= minTimeCheck) {
versionDir = {};
checkTime = now;
console.log('saveFile: cleared versionDir');
}
await initVersionDir(doc);
// make sure file is in an EECS 482 git repo
if (! (path.dirname(doc.fileName) in versionDir)
|| versionDir[path.dirname(doc.fileName)] == '') {
return;
}
const versionDirname = versionDir[path.dirname(doc.fileName)];
// limit the rate of pushing
if (versionDirname in pushTime
&& now - pushTime[versionDirname] < minTimePush) {
// replace any pending push for this directory, so events don't pile up
if (versionDirname in timer) {
clearTimeout(timer[versionDirname]);
}
// make sure this event is eventually pushed
timer[versionDirname] = setTimeout(saveFile,
(minTimePush-(now-pushTime[versionDirname]))*1000, doc);
return;
}
// add version482 entry, so it's as new as the saved file
await textChanged(doc);
// Push to github. This command requires github authentication, so
// send it via the vscode terminal.
try {
// Clean up terminals that have exited. This is just to be safe,
// since the onDidCloseTerminal event handler should do this.
if (saveTerminal !== undefined && saveTerminal.exitStatus !== undefined) {
saveTerminal.dispose();
saveTerminal = undefined;
}
if (saveTerminal === undefined) {
console.log('creating save terminal');
saveTerminal = vscode.window.createTerminal({
name: 'version482-save',
hideFromUser: true,
isTransient: true,
shellPath: '/bin/sh',
});
const disposable = vscode.window.onDidCloseTerminal(
t => {
if (t === saveTerminal) {
console.log('save terminal was closed');
disposable.dispose();
saveTerminal = undefined;
}
}
);
}
const cmd = 'git -C "' + versionDirname + '" push --quiet > /dev/null';
console.log('saveFile: ' + cmd);
saveTerminal.sendText(cmd);
console.log('saveFile: push initiated');
pushTime[versionDirname] = now;
} catch (err) {
console.log('saveFile: push failed');
console.log(err);
}
}