diff --git a/.github/workflows/prs.yml b/.github/workflows/prs.yml index 9b4abb9..e1ab7c3 100644 --- a/.github/workflows/prs.yml +++ b/.github/workflows/prs.yml @@ -1,13 +1,12 @@ name: Push Build -on: - push: - branches: - - main - pull_request: - branches: - - main - +on: + push: + branches: + - main + pull_request: + branches: + - main jobs: build: @@ -17,17 +16,17 @@ jobs: steps: - uses: actions/checkout@v3 with: - fetch-depth: 0 - + fetch-depth: 0 + - name: Setup Npm - run: | - npm install && npm install -g typescript + run: | + npm install && npm install -g typescript - name: Setup Git - run: | - git config --global user.email "brian.orwe@gmail.com" - git config --global user.name "brian.orwe" - + run: | + git config --global user.email "brian.orwe@gmail.com" + git config --global user.name "brian.orwe" + - name: Test run: | - npm run test \ No newline at end of file + npm run test diff --git a/.vscode/extensions.json b/.vscode/extensions.json index dd01eb3..9e5e0b7 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,5 +1,9 @@ { // See http://go.microsoft.com/fwlink/?LinkId=827846 // for the documentation about the extensions.json format - "recommendations": ["dbaeumer.vscode-eslint", "amodio.tsl-problem-matcher", "ms-vscode.extension-test-runner"] + "recommendations": [ + "dbaeumer.vscode-eslint", + "amodio.tsl-problem-matcher", + "ms-vscode.extension-test-runner" + ] } diff --git a/.vscode/launch.json b/.vscode/launch.json index c42edc0..ccdb134 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -3,19 +3,15 @@ // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 { - "version": "0.2.0", - "configurations": [ - { - "name": "Run Extension", - "type": "extensionHost", - "request": "launch", - "args": [ - "--extensionDevelopmentPath=${workspaceFolder}" - ], - "outFiles": [ - "${workspaceFolder}/dist/**/*.js" - ], - "preLaunchTask": "${defaultBuildTask}" - } - ] + "version": "0.2.0", + "configurations": [ + { + "name": "Run Extension", + "type": "extensionHost", + "request": "launch", + "args": ["--extensionDevelopmentPath=${workspaceFolder}"], + "outFiles": ["${workspaceFolder}/dist/**/*.js"], + "preLaunchTask": "${defaultBuildTask}" + } + ] } diff --git a/.vscode/settings.json b/.vscode/settings.json index 0dfaf64..96d95ca 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,14 +1,14 @@ // Place your settings in this file to overwrite default and user settings. { - "files.exclude": { - "out": false, // set this to true to hide the "out" folder with the compiled JS files - "dist": false // set this to true to hide the "dist" folder with the compiled JS files - }, - "search.exclude": { - "out": true, // set this to false to include "out" folder in search results - "dist": true // set this to false to include "dist" folder in search results - }, - // Turn off tsc task auto detection since we have the necessary tasks as npm scripts - "typescript.tsc.autoDetect": "off", - "cmake.configureOnOpen": false -} \ No newline at end of file + "files.exclude": { + "out": false, // set this to true to hide the "out" folder with the compiled JS files + "dist": false // set this to true to hide the "dist" folder with the compiled JS files + }, + "search.exclude": { + "out": true, // set this to false to include "out" folder in search results + "dist": true // set this to false to include "dist" folder in search results + }, + // Turn off tsc task auto detection since we have the necessary tasks as npm scripts + "typescript.tsc.autoDetect": "off", + "cmake.configureOnOpen": false +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json index c2ab68a..9e3300b 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,40 +1,37 @@ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format { - "version": "2.0.0", - "tasks": [ - { - "type": "npm", - "script": "watch", - "problemMatcher": "$ts-webpack-watch", - "isBackground": true, - "presentation": { - "reveal": "never", - "group": "watchers" - }, - "group": { - "kind": "build", - "isDefault": true - } - }, - { - "type": "npm", - "script": "watch-tests", - "problemMatcher": "$tsc-watch", - "isBackground": true, - "presentation": { - "reveal": "never", - "group": "watchers" - }, - "group": "build" - }, - { - "label": "tasks: watch-tests", - "dependsOn": [ - "npm: watch", - "npm: watch-tests" - ], - "problemMatcher": [] - } - ] + "version": "2.0.0", + "tasks": [ + { + "type": "npm", + "script": "watch", + "problemMatcher": "$ts-webpack-watch", + "isBackground": true, + "presentation": { + "reveal": "never", + "group": "watchers" + }, + "group": { + "kind": "build", + "isDefault": true + } + }, + { + "type": "npm", + "script": "watch-tests", + "problemMatcher": "$tsc-watch", + "isBackground": true, + "presentation": { + "reveal": "never", + "group": "watchers" + }, + "group": "build" + }, + { + "label": "tasks: watch-tests", + "dependsOn": ["npm: watch", "npm: watch-tests"], + "problemMatcher": [] + } + ] } diff --git a/package-lock.json b/package-lock.json index 3fc25d6..ef715c3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,7 @@ "@vscode/test-electron": "^2.3.8", "dotenv": "^16.3.1", "eslint": "^8.56.0", + "prettier": "^3.2.5", "ts-loader": "^9.5.1", "typescript": "^5.3.3", "webpack": "^5.89.0", @@ -2842,6 +2843,21 @@ "node": ">= 0.8.0" } }, + "node_modules/prettier": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz", + "integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==", + "dev": true, + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/process-nextick-args": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", diff --git a/package.json b/package.json index 928ba28..cbcaa3e 100644 --- a/package.json +++ b/package.json @@ -39,6 +39,7 @@ "compile": "webpack", "watch": "webpack --watch", "package": "webpack --mode production --devtool hidden-source-map", + "format": "prettier --write 'src/**/*.ts'", "compile-tests": "tsc -p . --outDir out", "watch-tests": "tsc -p . -w --outDir out", "pretest": "npm run compile-tests && npm run compile && npm run lint", @@ -55,6 +56,7 @@ "@vscode/test-electron": "^2.3.8", "dotenv": "^16.3.1", "eslint": "^8.56.0", + "prettier": "^3.2.5", "ts-loader": "^9.5.1", "typescript": "^5.3.3", "webpack": "^5.89.0", diff --git a/src/extension.ts b/src/extension.ts index b221b13..b52fe88 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -1,14 +1,13 @@ // The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below -import * as vscode from 'vscode'; -import { Presenter } from './presenter'; +import * as vscode from "vscode"; +import { Presenter } from "./presenter"; // This method is called when your extension is activated // Your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { - - Presenter.getInstance().setupCommands(context) - console.log('Congratulations, your extension "save-me-baby" is now active!'); + Presenter.getInstance().setupCommands(context); + console.log('Congratulations, your extension "save-me-baby" is now active!'); } // This method is called when your extension is deactivated diff --git a/src/presenter.ts b/src/presenter.ts index e534719..09db8f7 100644 --- a/src/presenter.ts +++ b/src/presenter.ts @@ -1,119 +1,149 @@ -import * as vscode from 'vscode'; -import { dirGetLastLogMessage, dirIsGit, doGitMergeAndRebase, getParentDir, gitPush, startGitCommit } from './utils'; +import * as vscode from "vscode"; +import { + dirGetLastLogMessage, + dirIsGit, + doGitMergeAndRebase, + getParentDir, + gitPush, + startGitCommit, +} from "./utils"; export class Presenter { - private _enabled: boolean = false - private disposableForOnSaveListener: vscode.Disposable | null = null - private loaded = false; + private _enabled: boolean = false; + private disposableForOnSaveListener: vscode.Disposable | null = null; + private loaded = false; - private static instance: Presenter | null = null + private static instance: Presenter | null = null; - // Hold onSalve listener object - onSaveListener = false; + // Hold onSalve listener object + onSaveListener = false; - static getInstance(): Presenter { - if(!Presenter.instance){ - Presenter.instance = new Presenter() - } - return Presenter.instance - } - - get enabled(): boolean { return this._enabled } - /** Toggle to enable or disable saving */ - toggle(){ - this._enabled = !this._enabled + static getInstance(): Presenter { + if (!Presenter.instance) { + Presenter.instance = new Presenter(); } + return Presenter.instance; + } - gitCommit(logMsg: string | undefined, file: vscode.Uri){ - //start the git push and commit process here - if(this._enabled){ - startGitCommit(logMsg, file, (commitStatus)=>{ - if(commitStatus.status === "Comitted"){ - //start git push - gitPush(getParentDir(file)) - }else if(commitStatus.status === "Error"){ - //show popup of error - vscode.window.showErrorMessage("🤯 Error in commiting: "+commitStatus.error) - } - }) - } - } + get enabled(): boolean { + return this._enabled; + } + /** Toggle to enable or disable saving */ + toggle() { + this._enabled = !this._enabled; + } - setupCommands(context: vscode.ExtensionContext){ + gitCommit(logMsg: string | undefined, file: vscode.Uri) { + //start the git push and commit process here + if (this._enabled) { + startGitCommit(logMsg, file, (commitStatus) => { + if (commitStatus.status === "Comitted") { + //start git push + gitPush(getParentDir(file)); + } else if (commitStatus.status === "Error") { + //show popup of error + vscode.window.showErrorMessage( + "🤯 Error in commiting: " + commitStatus.error, + ); + } + }); + } + } - let disposable = vscode.commands.registerCommand('save-me-baby.start-saving', () => { - this._enabled=true; - this.disposableForOnSaveListener = vscode.workspace.onDidSaveTextDocument((doc)=>{ - if(this._enabled){ - //get the parent dir of the file - const parent_dir = getParentDir(doc.uri) - if(dirIsGit(parent_dir)){ - //if so then go and get last git log - let lastLog = dirGetLastLogMessage(parent_dir) - //create git commit - this.gitCommit(lastLog, doc.uri) - } - //Letter have a setting to allow initializing repo incase no git - } - }) - vscode.window.showInformationMessage('Starting to Save You 😄!'); - return true; - }); - context.subscriptions.push(disposable); - disposable = vscode.commands.registerCommand('save-me-baby.stop-saving', () => { - this.disposableForOnSaveListener?.dispose() - this.disposableForOnSaveListener = null - this._enabled=false; - vscode.window.showInformationMessage('Stoping to Save Save you 😥!'); - return true; - }); - context.subscriptions.push(disposable); + setupCommands(context: vscode.ExtensionContext) { + let disposable = vscode.commands.registerCommand( + "save-me-baby.start-saving", + () => { + this._enabled = true; + this.disposableForOnSaveListener = + vscode.workspace.onDidSaveTextDocument((doc) => { + if (this._enabled) { + //get the parent dir of the file + const parent_dir = getParentDir(doc.uri); + if (dirIsGit(parent_dir)) { + //if so then go and get last git log + let lastLog = dirGetLastLogMessage(parent_dir); + //create git commit + this.gitCommit(lastLog, doc.uri); + } + //Letter have a setting to allow initializing repo incase no git + } + }); + vscode.window.showInformationMessage("Starting to Save You 😄!"); + return true; + }, + ); + context.subscriptions.push(disposable); + disposable = vscode.commands.registerCommand( + "save-me-baby.stop-saving", + () => { + this.disposableForOnSaveListener?.dispose(); + this.disposableForOnSaveListener = null; + this._enabled = false; + vscode.window.showInformationMessage("Stoping to Save Save you 😥!"); + return true; + }, + ); + context.subscriptions.push(disposable); - disposable = vscode.commands.registerCommand('save-me-baby.toggle', () => { - this.toggle() - if(this.enabled){ - this.disposableForOnSaveListener?.dispose() - this.disposableForOnSaveListener = null - vscode.window.showInformationMessage('Stoping to Save Save you 😥!'); - }else{ - vscode.window.showInformationMessage('Starting to Save You 😄!'); - } - return true; - }); - context.subscriptions.push(disposable); + disposable = vscode.commands.registerCommand("save-me-baby.toggle", () => { + this.toggle(); + if (this.enabled) { + this.disposableForOnSaveListener?.dispose(); + this.disposableForOnSaveListener = null; + vscode.window.showInformationMessage("Stoping to Save Save you 😥!"); + } else { + vscode.window.showInformationMessage("Starting to Save You 😄!"); + } + return true; + }); + context.subscriptions.push(disposable); - disposable = vscode.commands.registerCommand("save-me-baby.compress", async ()=>{ - const result = await vscode.window.showInputBox({ - prompt: "Enter the the commit message to use", - title: "Rebase/Compress message" - }) + disposable = vscode.commands.registerCommand( + "save-me-baby.compress", + async () => { + const result = await vscode.window.showInputBox({ + prompt: "Enter the the commit message to use", + title: "Rebase/Compress message", + }); - if(result === undefined || result.length === 0 ){ - vscode.window.showInformationMessage("SaveMeBaby: Sorry, no commit message provided for compression") - return; - } + if (result === undefined || result.length === 0) { + vscode.window.showInformationMessage( + "SaveMeBaby: Sorry, no commit message provided for compression", + ); + return; + } - //get workspace - const workspaces = vscode.workspace.workspaceFolders - if( workspaces!== undefined && workspaces.length>0){ - const workspace = workspaces[0] - doGitMergeAndRebase(result, workspace.uri,(result)=>{ - if(result.pushed===true){ - vscode.window.showInformationMessage("SaveMeBaby: Push success") - }else if(result.commited===true && result.pushed===false){ - vscode.window.showInformationMessage("SaveMeBaby: Commited, but counldn't push pls 'git push -f'") - }else if(result.error !== undefined){ - vscode.window.showInformationMessage("SaveMeBaby: Error occured while compressing "+result.error) - } - }) - }else if(workspaces!== undefined && workspaces?.length > 1){ - vscode.window.showInformationMessage("SaveMeBaby: Please close all open folders, and stay with one for this to work") - }else{ - vscode.window.showInformationMessage("SaveMeBaby: Please open a folder before running this.") - } - }) - context.subscriptions.push(disposable); + //get workspace + const workspaces = vscode.workspace.workspaceFolders; + if (workspaces !== undefined && workspaces.length > 0) { + const workspace = workspaces[0]; + doGitMergeAndRebase(result, workspace.uri, (result) => { + if (result.pushed === true) { + vscode.window.showInformationMessage("SaveMeBaby: Push success"); + } else if (result.commited === true && result.pushed === false) { + vscode.window.showInformationMessage( + "SaveMeBaby: Commited, but counldn't push pls 'git push -f'", + ); + } else if (result.error !== undefined) { + vscode.window.showInformationMessage( + "SaveMeBaby: Error occured while compressing " + result.error, + ); + } + }); + } else if (workspaces !== undefined && workspaces?.length > 1) { + vscode.window.showInformationMessage( + "SaveMeBaby: Please close all open folders, and stay with one for this to work", + ); + } else { + vscode.window.showInformationMessage( + "SaveMeBaby: Please open a folder before running this.", + ); + } + }, + ); + context.subscriptions.push(disposable); - this.loaded = true; - } -} \ No newline at end of file + this.loaded = true; + } +} diff --git a/src/test/extension.test.ts b/src/test/extension.test.ts index 9b947d4..99de99e 100644 --- a/src/test/extension.test.ts +++ b/src/test/extension.test.ts @@ -1,83 +1,90 @@ -import * as assert from 'assert'; +import * as assert from "assert"; // You can import and use all API from the 'vscode' module // as well as import your extension to test it -import * as vscode from 'vscode'; -import path from 'path'; -import { CommitStatus, dirGetLastLogMessageCode } from '../utils'; -import { CallBackCompleteStatus, createTestDir, deleteDir, getOrCreateNoCommitDir } from './utils_for_tests'; -import { Presenter } from '../presenter'; +import * as vscode from "vscode"; +import path from "path"; +import { CommitStatus, dirGetLastLogMessageCode } from "../utils"; +import { + CallBackCompleteStatus, + createTestDir, + deleteDir, + getOrCreateNoCommitDir, +} from "./utils_for_tests"; +import { Presenter } from "../presenter"; // import * as myExtension from '../../extension'; -async function writeToFile(content: string, file: vscode.Uri){ - await vscode.workspace.fs.writeFile(file, Buffer.from(content)) - const doc = await vscode.workspace.openTextDocument(file) - const editor = await vscode.window.showTextDocument(doc) - await editor.edit((e)=>{ - e.insert(new vscode.Position(0,100),"YEEEEEEEHHHH WWOOOOOOOOOOOOOOOOOH") - }) - await editor.document.save() - console.log("File at: ",file.fsPath); +async function writeToFile(content: string, file: vscode.Uri) { + await vscode.workspace.fs.writeFile(file, Buffer.from(content)); + const doc = await vscode.workspace.openTextDocument(file); + const editor = await vscode.window.showTextDocument(doc); + await editor.edit((e) => { + e.insert(new vscode.Position(0, 100), "YEEEEEEEHHHH WWOOOOOOOOOOOOOOOOOH"); + }); + await editor.document.save(); + console.log("File at: ", file.fsPath); } -suite('Test commands', () => { +suite("Test commands", () => { + test("turning start_saving on and try saving on a none-git repo, it should not start commit", async () => { + const test_dir = createTestDir("test_dir"); + let result = await vscode.commands.executeCommand( + "save-me-baby.start-saving", + ); + assert.strictEqual(result, true); - test("turning start_saving on and try saving on a none-git repo, it should not start commit", async ()=>{ - const test_dir = createTestDir("test_dir") - let result = await vscode.commands.executeCommand('save-me-baby.start-saving') - assert.strictEqual(result, true) + const logCode = dirGetLastLogMessageCode(test_dir!); - const logCode = dirGetLastLogMessageCode(test_dir!) + //emit an open command to open new file + const file = vscode.Uri.file(path.join(test_dir.fsPath, "test.txt")); + //write some text to it and save the current file + await writeToFile("Hello", file); + //wait for 1 second + await new Promise((resolve) => { + setTimeout(() => { + resolve(1); + }, 1000); + return; + }); - //emit an open command to open new file - const file = vscode.Uri.file(path.join(test_dir.fsPath,"test.txt")) - //write some text to it and save the current file - await writeToFile("Hello", file); - //wait for 1 second - await new Promise((resolve)=>{ - setTimeout(() => { - resolve(1) - }, 1000); - return; - }) + //when here means there must be a new Promise in currentGitted + //for saving the file and executing git cmd, check it + //exists - //when here means there must be a new Promise in currentGitted - //for saving the file and executing git cmd, check it - //exists + const newlogCode = dirGetLastLogMessageCode(test_dir!); + assert.strictEqual(newlogCode, logCode); + deleteDir(test_dir); + }); - const newlogCode = dirGetLastLogMessageCode(test_dir!) - assert.strictEqual(newlogCode, logCode) - deleteDir(test_dir) - }) + test("turning start_saving on and try saving on a repo, it finish commit", async () => { + const result = await vscode.commands.executeCommand( + "save-me-baby.start-saving", + ); + assert.strictEqual(result, true); + //create testdir as git repo + const dir = getOrCreateNoCommitDir(); + assert.notEqual(dir, undefined, "Dir shouldn't be undefined"); - test("turning start_saving on and try saving on a repo, it finish commit", async ()=>{ - const result = await vscode.commands.executeCommand('save-me-baby.start-saving') - assert.strictEqual(result, true) + //emit an open command to open new file + const file = vscode.Uri.file(path.join(dir!.fsPath, "test.txt")); + //write some text to it and save the current file + await writeToFile("Yebooo baby!", file); + //wait for 1 second + await new Promise((resolve) => { + setTimeout(() => { + resolve(1); + }, 1000); + return; + }); - //create testdir as git repo - const dir = getOrCreateNoCommitDir() - assert.notEqual(dir, undefined, "Dir shouldn't be undefined") + //when here means there must be a new Promise in currentGitted + //for saving the file and executing git cmd, check it + //exists - //emit an open command to open new file - const file = vscode.Uri.file(path.join(dir!.fsPath,"test.txt")) - //write some text to it and save the current file - await writeToFile("Yebooo baby!", file); - //wait for 1 second - await new Promise((resolve)=>{ - setTimeout(() => { - resolve(1) - }, 1000); - return; - }) - - //when here means there must be a new Promise in currentGitted - //for saving the file and executing git cmd, check it - //exists - - const logCode = dirGetLastLogMessageCode(dir!) - assert.notEqual(logCode, undefined) - assert.strictEqual(logCode!.length>3, true) - deleteDir(dir!) - }) + const logCode = dirGetLastLogMessageCode(dir!); + assert.notEqual(logCode, undefined); + assert.strictEqual(logCode!.length > 3, true); + deleteDir(dir!); + }); }); diff --git a/src/test/utils.test.ts b/src/test/utils.test.ts index 4a0dd63..674cbfb 100644 --- a/src/test/utils.test.ts +++ b/src/test/utils.test.ts @@ -1,250 +1,280 @@ -import * as assert from 'assert' -import path from 'path' -import * as vscode from 'vscode' -import * as fs from 'fs' -import * as utils from '../utils' -import { homedir } from 'os' -import { CallBackCompleteStatus, deleteDir, getOrCreateNoCommitDir, getOrCreateNoCommitDirWithGitIgnore, getOrCreateOneCommitDir } from './utils_for_tests' -import { CommitStatus } from '../utils' - -suite("Testing Utils",()=>{ - test("Test getting parent dir", ()=>{ - const expected = vscode.Uri.file(__dirname) - const testingfile = vscode.Uri.file(path.join(__dirname, "testingfile.txt")) - let parentDir = utils.getParentDir(testingfile); - assert.strictEqual(parentDir.fsPath, expected.fsPath) - }) - - test("Test dir is Git true", ()=>{ - const testingfile = vscode.Uri.file(path.join(__dirname, "testingfile.txt")) - let parentDir = utils.getParentDir(testingfile); - const result = utils.dirIsGit(parentDir) - assert.strictEqual(result, true); - }) - - - test("Test dir is Git false since imaginary", ()=>{ - const testingfile = vscode.Uri.file(path.join(__dirname, "/hehehehhe/asdsadl/testingfile.txt")) - let parentDir = utils.getParentDir(testingfile); - const result = utils.dirIsGit(parentDir) - assert.strictEqual(result, false); - }) - - test("Test dir is not git, but it exists", ()=>{ - const home = vscode.Uri.file(homedir()) - const result = utils.dirIsGit(home) - //we are assuming nobody has set their home dir as a - // git repo, lol. - assert.strictEqual(result, false) - }) - - test("Test getting last log message of a git directory", ()=>{ - const projDir = vscode.Uri.file(path.join(__dirname, "../../")) - const msg = utils.dirGetLastLogMessage(projDir); - assert.notEqual(msg,undefined) - }) - - test("Test creating no commit dir", ()=>{ - const noCommitDir = getOrCreateNoCommitDir() - assert.notDeepEqual(noCommitDir, undefined) - test("Test deleting no commit dir", ()=>{ - deleteDir(noCommitDir!) - const exists = fs.existsSync(noCommitDir!.fsPath) - assert.equal(exists, false) - }) - }) - - test("Test getting last log message of a git directory with no previous commit", ()=>{ - const noCommitDir = getOrCreateNoCommitDir() - const msg = utils.dirGetLastLogMessage(noCommitDir!) - deleteDir(noCommitDir!) - assert.equal(msg, undefined) - }) - - test("Test if can Start Git Commit on none commited git dir succesfully", async ()=>{ - const noCommitDir = getOrCreateNoCommitDir() - const msg = utils.dirGetLastLogMessage(noCommitDir!) - assert.equal(msg, undefined) - //create file - const testFile = vscode.Uri.file(path.join(noCommitDir!.fsPath, "Test.txt")) - fs.writeFileSync(testFile.fsPath, "Hello") - let callbackResult: CallBackCompleteStatus = { - complete: false, - val: undefined - } - await utils.startGitCommit(msg, testFile, (commitStatus)=> { - callbackResult.complete = true - callbackResult.val = commitStatus - }) - const msgCommit = utils.dirGetLastLogMessage(noCommitDir!) - assert.strictEqual(msgCommit, "First Commit.") - process.chdir(__dirname) - deleteDir(noCommitDir!) - assert.equal(callbackResult.val!.status, "Comitted") - assert.equal(callbackResult.val!.error, undefined) - }) - - test("Test if can start Git Commit on dir with already previous commits", async ()=>{ - const oneCommitDir = getOrCreateOneCommitDir() //has one file, yolo.txt - assert.notEqual(oneCommitDir, undefined) - const msg = utils.dirGetLastLogMessage(oneCommitDir!) - assert.strictEqual(msg, "test commit") - const code = utils.dirGetLastLogMessageCode(oneCommitDir!) - assert.notEqual(code, undefined) - //create file - const testFile = vscode.Uri.file(path.join(oneCommitDir!.fsPath, "yolo.txt")) - fs.appendFileSync(testFile.fsPath, "\nHello and Yolo\n") - let callbackResult: CallBackCompleteStatus = { - complete: false, - val: undefined - } - await utils.startGitCommit(msg, testFile, (commitStatus)=> { - callbackResult.complete = true - callbackResult.val = commitStatus - }) - process.chdir(__dirname) - const newCode = utils.dirGetLastLogMessageCode(oneCommitDir!) - assert.notEqual(newCode, undefined) - assert.notEqual(newCode, code) - deleteDir(oneCommitDir!) - assert.equal(callbackResult.val!.status, "Comitted") - }) - - test("Test if can create commit on file that is inside .gitginore, should not", async()=>{ - const gitIgnoreContent = -`hehe.txt +import * as assert from "assert"; +import path from "path"; +import * as vscode from "vscode"; +import * as fs from "fs"; +import * as utils from "../utils"; +import { homedir } from "os"; +import { + CallBackCompleteStatus, + deleteDir, + getOrCreateNoCommitDir, + getOrCreateNoCommitDirWithGitIgnore, + getOrCreateOneCommitDir, +} from "./utils_for_tests"; +import { CommitStatus } from "../utils"; + +suite("Testing Utils", () => { + test("Test getting parent dir", () => { + const expected = vscode.Uri.file(__dirname); + const testingfile = vscode.Uri.file( + path.join(__dirname, "testingfile.txt"), + ); + let parentDir = utils.getParentDir(testingfile); + assert.strictEqual(parentDir.fsPath, expected.fsPath); + }); + + test("Test dir is Git true", () => { + const testingfile = vscode.Uri.file( + path.join(__dirname, "testingfile.txt"), + ); + let parentDir = utils.getParentDir(testingfile); + const result = utils.dirIsGit(parentDir); + assert.strictEqual(result, true); + }); + + test("Test dir is Git false since imaginary", () => { + const testingfile = vscode.Uri.file( + path.join(__dirname, "/hehehehhe/asdsadl/testingfile.txt"), + ); + let parentDir = utils.getParentDir(testingfile); + const result = utils.dirIsGit(parentDir); + assert.strictEqual(result, false); + }); + + test("Test dir is not git, but it exists", () => { + const home = vscode.Uri.file(homedir()); + const result = utils.dirIsGit(home); + //we are assuming nobody has set their home dir as a + // git repo, lol. + assert.strictEqual(result, false); + }); + + test("Test getting last log message of a git directory", () => { + const projDir = vscode.Uri.file(path.join(__dirname, "../../")); + const msg = utils.dirGetLastLogMessage(projDir); + assert.notEqual(msg, undefined); + }); + + test("Test creating no commit dir", () => { + const noCommitDir = getOrCreateNoCommitDir(); + assert.notDeepEqual(noCommitDir, undefined); + test("Test deleting no commit dir", () => { + deleteDir(noCommitDir!); + const exists = fs.existsSync(noCommitDir!.fsPath); + assert.equal(exists, false); + }); + }); + + test("Test getting last log message of a git directory with no previous commit", () => { + const noCommitDir = getOrCreateNoCommitDir(); + const msg = utils.dirGetLastLogMessage(noCommitDir!); + deleteDir(noCommitDir!); + assert.equal(msg, undefined); + }); + + test("Test if can Start Git Commit on none commited git dir succesfully", async () => { + const noCommitDir = getOrCreateNoCommitDir(); + const msg = utils.dirGetLastLogMessage(noCommitDir!); + assert.equal(msg, undefined); + //create file + const testFile = vscode.Uri.file( + path.join(noCommitDir!.fsPath, "Test.txt"), + ); + fs.writeFileSync(testFile.fsPath, "Hello"); + let callbackResult: CallBackCompleteStatus = { + complete: false, + val: undefined, + }; + await utils.startGitCommit(msg, testFile, (commitStatus) => { + callbackResult.complete = true; + callbackResult.val = commitStatus; + }); + const msgCommit = utils.dirGetLastLogMessage(noCommitDir!); + assert.strictEqual(msgCommit, "First Commit."); + process.chdir(__dirname); + deleteDir(noCommitDir!); + assert.equal(callbackResult.val!.status, "Comitted"); + assert.equal(callbackResult.val!.error, undefined); + }); + + test("Test if can start Git Commit on dir with already previous commits", async () => { + const oneCommitDir = getOrCreateOneCommitDir(); //has one file, yolo.txt + assert.notEqual(oneCommitDir, undefined); + const msg = utils.dirGetLastLogMessage(oneCommitDir!); + assert.strictEqual(msg, "test commit"); + const code = utils.dirGetLastLogMessageCode(oneCommitDir!); + assert.notEqual(code, undefined); + //create file + const testFile = vscode.Uri.file( + path.join(oneCommitDir!.fsPath, "yolo.txt"), + ); + fs.appendFileSync(testFile.fsPath, "\nHello and Yolo\n"); + let callbackResult: CallBackCompleteStatus = { + complete: false, + val: undefined, + }; + await utils.startGitCommit(msg, testFile, (commitStatus) => { + callbackResult.complete = true; + callbackResult.val = commitStatus; + }); + process.chdir(__dirname); + const newCode = utils.dirGetLastLogMessageCode(oneCommitDir!); + assert.notEqual(newCode, undefined); + assert.notEqual(newCode, code); + deleteDir(oneCommitDir!); + assert.equal(callbackResult.val!.status, "Comitted"); + }); + + test("Test if can create commit on file that is inside .gitginore, should not", async () => { + const gitIgnoreContent = `hehe.txt *.toIgnore -toIgnore/*` - const noCommitWithGitIgoreDir: vscode.Uri| undefined = getOrCreateNoCommitDirWithGitIgnore(gitIgnoreContent) - assert.notEqual(noCommitWithGitIgoreDir, undefined) - - //test saving hehe.txt - const heheFile = vscode.Uri.file(path.join(noCommitWithGitIgoreDir!.fsPath, "hehe.txt")) - fs.appendFileSync(heheFile.fsPath,"Hehehe baby\r\n") - let callbackResult: CallBackCompleteStatus = { - complete: false, - val: undefined - } - const msg = "Shouldn't commit" - await utils.startGitCommit(msg,heheFile,(commitResult)=>{ - callbackResult.complete = true - callbackResult.val = commitResult - }) - assert.strictEqual(callbackResult.complete, true) - assert.strictEqual(callbackResult.val!.status, "GitIgnored" ) - - //testing saving for *.toIgnore file - const toIgnoreFile = vscode.Uri.file(path.join(noCommitWithGitIgoreDir!.fsPath, "hehe.toIgnore")) - fs.appendFileSync(toIgnoreFile.fsPath,"Ignore This Baby\r\n") - const callbackResultIgnore: CallBackCompleteStatus = { - complete: false, - val: undefined - } - await utils.startGitCommit(msg,toIgnoreFile,(commitResult)=>{ - callbackResultIgnore.complete = true - callbackResultIgnore.val = commitResult - }) - assert.strictEqual(callbackResultIgnore.complete, true) - assert.strictEqual(callbackResultIgnore.val!.status, "GitIgnored" ) - - - //testing saving for *.toIgnore file - const toIgnoreFile2 = vscode.Uri.file(path.join(noCommitWithGitIgoreDir!.fsPath, "toIgnore/", "hehe.yolo")) - fs.mkdirSync(utils.getParentDir(toIgnoreFile2).fsPath) - fs.appendFileSync(toIgnoreFile2.fsPath,"Ignore This Baby Too\r\n") - const callbackResultIgnore2: CallBackCompleteStatus = { - complete: false, - val: undefined - } - await utils.startGitCommit(msg,toIgnoreFile2,(commitResult)=>{ - callbackResultIgnore2.complete = true - callbackResultIgnore2.val = commitResult - }) - assert.strictEqual(callbackResultIgnore2.complete, true) - assert.strictEqual(callbackResultIgnore2.val!.status, "GitIgnored" ) - - - //testing saving a file that isn't in gitignore, should pass - const notIgnore = vscode.Uri.file(path.join(noCommitWithGitIgoreDir!.fsPath, "notIgnore/", "not.yolo")) - fs.mkdirSync(utils.getParentDir(notIgnore).fsPath) - fs.appendFileSync(notIgnore.fsPath,"Don't ignore this Baby\r\n") - const callbackResultIgnore3: CallBackCompleteStatus = { - complete: false, - val: undefined - } - await utils.startGitCommit(msg,notIgnore,(commitResult)=>{ - callbackResultIgnore3.complete = true - callbackResultIgnore3.val = commitResult - }) - assert.strictEqual(callbackResultIgnore3.complete, true) - assert.strictEqual(callbackResultIgnore3.val!.status, "Comitted" ) - - deleteDir(noCommitWithGitIgoreDir!) - }) - - test("Compressing previous commits", async ()=>{ - const noCommit = getOrCreateNoCommitDir() - assert.notStrictEqual(noCommit, undefined) - - const heheFile = vscode.Uri.file(path.join(noCommit!.fsPath, "hehe_lol.txt")) - - let commitCallback: CallBackCompleteStatus = { - complete: false, - val: undefined - } - const reset = (commitCB: CallBackCompleteStatus)=>{ - commitCB.complete = false - commitCB.val = undefined - return commitCB - } - - //do a commit - fs.writeFileSync(heheFile.fsPath, "1\n") - const funcToDo = (commitResult: CommitStatus)=>{ - commitCallback.complete = true - commitCallback.val = commitResult - } - await utils.startGitCommit(undefined,heheFile,funcToDo) - assert.strictEqual(commitCallback.complete, true) - const msgLog = utils.dirGetLastLogMessage(noCommit!) - assert.notStrictEqual(msgLog, undefined) - - - //do another commit - fs.writeFileSync(heheFile.fsPath, "2\n") - commitCallback = reset(commitCallback) - await utils.startGitCommit(undefined,heheFile,funcToDo) - assert.strictEqual(commitCallback.complete, true) - assert.strictEqual(msgLog!,utils.dirGetLastLogMessage(noCommit!)) - - //do 3rd commit - fs.writeFileSync(heheFile.fsPath, "3\n") - commitCallback = reset(commitCallback) - await utils.startGitCommit(undefined,heheFile,funcToDo) - assert.strictEqual(commitCallback.complete, true) - assert.strictEqual(msgLog!,utils.dirGetLastLogMessage(noCommit!)) - - //do 4th commit - fs.writeFileSync(heheFile.fsPath, "4\n") - commitCallback = reset(commitCallback) - await utils.startGitCommit(undefined,heheFile,funcToDo) - assert.strictEqual(commitCallback.complete, true) - assert.strictEqual(msgLog!,utils.dirGetLastLogMessage(noCommit!)) - - const logMessages: Array = utils.dirGetAllLogMessages(noCommit!) - assert.strictEqual(logMessages.length, 4) - //do the merge/rebase with message - const msgToCommit = "Bind here BABY" - let result: utils.GitMergeOrRebase | undefined = undefined; - await utils.doGitMergeAndRebase(msgToCommit, noCommit!, (inResult: utils.GitMergeOrRebase)=>{ - result = inResult - }) - assert.notStrictEqual(result, undefined) - assert.strictEqual(result!.commited, true) //don't check for push, it's only possible on a real repo with a remote - const currentLogMessages: Array = utils.dirGetAllLogMessages(noCommit!) - assert.strictEqual(currentLogMessages.length = { + complete: false, + val: undefined, + }; + const msg = "Shouldn't commit"; + await utils.startGitCommit(msg, heheFile, (commitResult) => { + callbackResult.complete = true; + callbackResult.val = commitResult; + }); + assert.strictEqual(callbackResult.complete, true); + assert.strictEqual(callbackResult.val!.status, "GitIgnored"); + + //testing saving for *.toIgnore file + const toIgnoreFile = vscode.Uri.file( + path.join(noCommitWithGitIgoreDir!.fsPath, "hehe.toIgnore"), + ); + fs.appendFileSync(toIgnoreFile.fsPath, "Ignore This Baby\r\n"); + const callbackResultIgnore: CallBackCompleteStatus = { + complete: false, + val: undefined, + }; + await utils.startGitCommit(msg, toIgnoreFile, (commitResult) => { + callbackResultIgnore.complete = true; + callbackResultIgnore.val = commitResult; + }); + assert.strictEqual(callbackResultIgnore.complete, true); + assert.strictEqual(callbackResultIgnore.val!.status, "GitIgnored"); + + //testing saving for *.toIgnore file + const toIgnoreFile2 = vscode.Uri.file( + path.join(noCommitWithGitIgoreDir!.fsPath, "toIgnore/", "hehe.yolo"), + ); + fs.mkdirSync(utils.getParentDir(toIgnoreFile2).fsPath); + fs.appendFileSync(toIgnoreFile2.fsPath, "Ignore This Baby Too\r\n"); + const callbackResultIgnore2: CallBackCompleteStatus = { + complete: false, + val: undefined, + }; + await utils.startGitCommit(msg, toIgnoreFile2, (commitResult) => { + callbackResultIgnore2.complete = true; + callbackResultIgnore2.val = commitResult; + }); + assert.strictEqual(callbackResultIgnore2.complete, true); + assert.strictEqual(callbackResultIgnore2.val!.status, "GitIgnored"); + + //testing saving a file that isn't in gitignore, should pass + const notIgnore = vscode.Uri.file( + path.join(noCommitWithGitIgoreDir!.fsPath, "notIgnore/", "not.yolo"), + ); + fs.mkdirSync(utils.getParentDir(notIgnore).fsPath); + fs.appendFileSync(notIgnore.fsPath, "Don't ignore this Baby\r\n"); + const callbackResultIgnore3: CallBackCompleteStatus = { + complete: false, + val: undefined, + }; + await utils.startGitCommit(msg, notIgnore, (commitResult) => { + callbackResultIgnore3.complete = true; + callbackResultIgnore3.val = commitResult; + }); + assert.strictEqual(callbackResultIgnore3.complete, true); + assert.strictEqual(callbackResultIgnore3.val!.status, "Comitted"); + + deleteDir(noCommitWithGitIgoreDir!); + }); + + test("Compressing previous commits", async () => { + const noCommit = getOrCreateNoCommitDir(); + assert.notStrictEqual(noCommit, undefined); + + const heheFile = vscode.Uri.file( + path.join(noCommit!.fsPath, "hehe_lol.txt"), + ); + + let commitCallback: CallBackCompleteStatus = { + complete: false, + val: undefined, + }; + const reset = (commitCB: CallBackCompleteStatus) => { + commitCB.complete = false; + commitCB.val = undefined; + return commitCB; + }; + + //do a commit + fs.writeFileSync(heheFile.fsPath, "1\n"); + const funcToDo = (commitResult: CommitStatus) => { + commitCallback.complete = true; + commitCallback.val = commitResult; + }; + await utils.startGitCommit(undefined, heheFile, funcToDo); + assert.strictEqual(commitCallback.complete, true); + const msgLog = utils.dirGetLastLogMessage(noCommit!); + assert.notStrictEqual(msgLog, undefined); + + //do another commit + fs.writeFileSync(heheFile.fsPath, "2\n"); + commitCallback = reset(commitCallback); + await utils.startGitCommit(undefined, heheFile, funcToDo); + assert.strictEqual(commitCallback.complete, true); + assert.strictEqual(msgLog!, utils.dirGetLastLogMessage(noCommit!)); + + //do 3rd commit + fs.writeFileSync(heheFile.fsPath, "3\n"); + commitCallback = reset(commitCallback); + await utils.startGitCommit(undefined, heheFile, funcToDo); + assert.strictEqual(commitCallback.complete, true); + assert.strictEqual(msgLog!, utils.dirGetLastLogMessage(noCommit!)); + + //do 4th commit + fs.writeFileSync(heheFile.fsPath, "4\n"); + commitCallback = reset(commitCallback); + await utils.startGitCommit(undefined, heheFile, funcToDo); + assert.strictEqual(commitCallback.complete, true); + assert.strictEqual(msgLog!, utils.dirGetLastLogMessage(noCommit!)); + + const logMessages: Array = utils.dirGetAllLogMessages( + noCommit!, + ); + assert.strictEqual(logMessages.length, 4); + //do the merge/rebase with message + const msgToCommit = "Bind here BABY"; + let result: utils.GitMergeOrRebase | undefined = undefined; + await utils.doGitMergeAndRebase( + msgToCommit, + noCommit!, + (inResult: utils.GitMergeOrRebase) => { + result = inResult; + }, + ); + assert.notStrictEqual(result, undefined); + assert.strictEqual(result!.commited, true); //don't check for push, it's only possible on a real repo with a remote + const currentLogMessages: Array = utils.dirGetAllLogMessages( + noCommit!, + ); + assert.strictEqual(currentLogMessages.length < logMessages.length, true); + assert.strictEqual(currentLogMessages.length, 2); + const currentTopLog = utils.dirGetLastLogMessage(noCommit!); + assert.strictEqual(currentTopLog, msgToCommit); + }); +}); diff --git a/src/test/utils_for_tests.ts b/src/test/utils_for_tests.ts index 8a052ef..e897d2d 100644 --- a/src/test/utils_for_tests.ts +++ b/src/test/utils_for_tests.ts @@ -1,66 +1,69 @@ -import path from "path" -import * as vscode from "vscode" -import * as fs from "fs" -import { execSync } from "child_process" - +import path from "path"; +import * as vscode from "vscode"; +import * as fs from "fs"; +import { execSync } from "child_process"; export type CallBackCompleteStatus = { - complete: boolean, - val: T | undefined -} + complete: boolean; + val: T | undefined; +}; -export function getOrCreateNoCommitDirWithGitIgnore(gitIgnoreContent: string): vscode.Uri | undefined{ - const cwd = process.cwd() - const rootPath = path.join(__dirname, "../../") - try{ - const gitDir = createTestDir("test_withgitignore") - process.chdir(gitDir.fsPath) - execSync("git init") - fs.writeFileSync(path.join(gitDir.fsPath, ".gitignore"),gitIgnoreContent) - return gitDir - }catch(err){ - console.log("ERROR",err) - }finally{ - process.chdir(cwd) - } - return undefined +export function getOrCreateNoCommitDirWithGitIgnore( + gitIgnoreContent: string, +): vscode.Uri | undefined { + const cwd = process.cwd(); + const rootPath = path.join(__dirname, "../../"); + try { + const gitDir = createTestDir("test_withgitignore"); + process.chdir(gitDir.fsPath); + execSync("git init"); + fs.writeFileSync(path.join(gitDir.fsPath, ".gitignore"), gitIgnoreContent); + return gitDir; + } catch (err) { + console.log("ERROR", err); + } finally { + process.chdir(cwd); + } + return undefined; } export function createTestDir(dirName: string): vscode.Uri { - const mainDir = path.join(__dirname, "../../"+dirName) - fs.mkdirSync(mainDir, {recursive: true}) - return vscode.Uri.file(mainDir) + const mainDir = path.join(__dirname, "../../" + dirName); + fs.mkdirSync(mainDir, { recursive: true }); + return vscode.Uri.file(mainDir); } -export function getOrCreateNoCommitDir(): vscode.Uri | undefined{ - try{ - const mainDir = createTestDir("test_no_commit") - process.chdir(mainDir.fsPath) - execSync("git init") - return mainDir - }catch(err){}finally{ - process.chdir(__dirname) - } - return undefined +export function getOrCreateNoCommitDir(): vscode.Uri | undefined { + try { + const mainDir = createTestDir("test_no_commit"); + process.chdir(mainDir.fsPath); + execSync("git init"); + return mainDir; + } catch (err) { + } finally { + process.chdir(__dirname); + } + return undefined; } -export function getOrCreateOneCommitDir(): vscode.Uri | undefined { - try{ - const mainDir = createTestDir("test_one_commit") - process.chdir(mainDir.fsPath) - execSync("git init") - fs.writeFileSync(path.join(mainDir.fsPath,"yolo.txt"), "yolo baby") - execSync("git add "+path.join(mainDir.fsPath,"yolo.txt")) - execSync("git commit -m \"test commit\"") - return mainDir - }catch(err){}finally{ - process.chdir(__dirname) - } - return undefined +export function getOrCreateOneCommitDir(): vscode.Uri | undefined { + try { + const mainDir = createTestDir("test_one_commit"); + process.chdir(mainDir.fsPath); + execSync("git init"); + fs.writeFileSync(path.join(mainDir.fsPath, "yolo.txt"), "yolo baby"); + execSync("git add " + path.join(mainDir.fsPath, "yolo.txt")); + execSync('git commit -m "test commit"'); + return mainDir; + } catch (err) { + } finally { + process.chdir(__dirname); + } + return undefined; } export function deleteDir(dir: vscode.Uri) { - if(fs.existsSync(dir.fsPath)){ - fs.rmSync(dir.fsPath, { recursive: true }) - } -} \ No newline at end of file + if (fs.existsSync(dir.fsPath)) { + fs.rmSync(dir.fsPath, { recursive: true }); + } +} diff --git a/src/utils.ts b/src/utils.ts index c2ba5cb..a97b9ae 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,218 +1,233 @@ -import path from 'path' -import * as vscode from 'vscode' -import * as fs from 'fs' -import { execSync } from 'child_process' +import path from "path"; +import * as vscode from "vscode"; +import * as fs from "fs"; +import { execSync } from "child_process"; -export type CommitFunction = (commitStatus: CommitStatus) => void +export type CommitFunction = (commitStatus: CommitStatus) => void; -export type CommitStatusType = "Comitted" | "Error" | "None" | "GitIgnored"; +export type CommitStatusType = "Comitted" | "Error" | "None" | "GitIgnored"; export type CommitStatus = { - status: CommitStatusType - msg: string | undefined - error: string | undefined -} + status: CommitStatusType; + msg: string | undefined; + error: string | undefined; +}; export type LogInfo = { - code: string, - msg: string -} + code: string; + msg: string; +}; export type GitMergeOrRebase = { - commited: boolean, - pushed: boolean, - error: string | undefined -} + commited: boolean; + pushed: boolean; + error: string | undefined; +}; -export function getParentDir(uri: vscode.Uri): vscode.Uri{ - return vscode.Uri.file(path.join(uri.fsPath, "..")) +export function getParentDir(uri: vscode.Uri): vscode.Uri { + return vscode.Uri.file(path.join(uri.fsPath, "..")); } export function dirIsGit(uri: vscode.Uri): boolean { - const currDir = process.cwd() - if(!fs.existsSync(uri.fsPath)){ - return false; + const currDir = process.cwd(); + if (!fs.existsSync(uri.fsPath)) { + return false; + } + try { + process.chdir(uri.fsPath); + let buff = execSync("git status"); + let on = buff.indexOf("On"); + if (on >= 0 && on < 3) { + return true; } - try{ - process.chdir(uri.fsPath) - let buff = execSync("git status") - let on = buff.indexOf("On"); - if(on>=0 && on < 3){ - return true; - } - }catch(err){}finally{ - process.chdir(currDir) - } - return false + } catch (err) { + } finally { + process.chdir(currDir); + } + return false; } - export function dirGetLastLogMessage(uri: vscode.Uri): string | undefined { - const cwd = process.cwd() - process.chdir(uri.fsPath) - let result = "" - try{ - const exec = execSync("git log --oneline") - result = String(exec).split("\n")[0].trim() - }catch(err: any){ - result = String(err.stderr) - } - process.chdir(cwd) - if(result.includes("fatal: your current branch")){ - return undefined - } - let lastLogMessagePos = result.indexOf(" ") - let lastLogMessage = result.substring(lastLogMessagePos+1) - return lastLogMessage; + const cwd = process.cwd(); + process.chdir(uri.fsPath); + let result = ""; + try { + const exec = execSync("git log --oneline"); + result = String(exec).split("\n")[0].trim(); + } catch (err: any) { + result = String(err.stderr); + } + process.chdir(cwd); + if (result.includes("fatal: your current branch")) { + return undefined; + } + let lastLogMessagePos = result.indexOf(" "); + let lastLogMessage = result.substring(lastLogMessagePos + 1); + return lastLogMessage; } export function dirGetAllLogMessages(dir: vscode.Uri): Array { - let result: LogInfo[] = [] - const cwd = process.cwd() - process.chdir(dir.fsPath) - try{ - const exec = execSync("git log --oneline") - String(exec).split("\n").map((line)=>{ - let startMsgPos = line.indexOf(" ") - const msg = line.substring(startMsgPos).trim() - if(msg.length>0){ - const code = line.substring(0,startMsgPos) - result.push({ - code: code, - msg: msg - }) - } - }) - }catch(err){} - process.chdir(cwd) - return result + let result: LogInfo[] = []; + const cwd = process.cwd(); + process.chdir(dir.fsPath); + try { + const exec = execSync("git log --oneline"); + String(exec) + .split("\n") + .map((line) => { + let startMsgPos = line.indexOf(" "); + const msg = line.substring(startMsgPos).trim(); + if (msg.length > 0) { + const code = line.substring(0, startMsgPos); + result.push({ + code: code, + msg: msg, + }); + } + }); + } catch (err) {} + process.chdir(cwd); + return result; } -export function doGitMergeAndRebase(msgToCommit: string, dir: vscode.Uri, func: (result: GitMergeOrRebase)=>void){ - const logLists = dirGetAllLogMessages(dir) - const prev = logLists[0] - let commitToResetAtIndex = 0; - for(const log of logLists ){ - if(log.msg !== prev.msg){ - break; - } - commitToResetAtIndex++ +export function doGitMergeAndRebase( + msgToCommit: string, + dir: vscode.Uri, + func: (result: GitMergeOrRebase) => void, +) { + const logLists = dirGetAllLogMessages(dir); + const prev = logLists[0]; + let commitToResetAtIndex = 0; + for (const log of logLists) { + if (log.msg !== prev.msg) { + break; } - - commitToResetAtIndex -= 1 - - const logInfoToUse = logLists[commitToResetAtIndex] - const cwd = process.cwd() - try{ - process.chdir(dir.fsPath) - execSync("git reset --soft "+logInfoToUse.code) - execSync("git commit -m \""+msgToCommit+"\"") - execSync("git push -f") - func({ - error: undefined, - commited: true, - pushed: true - }) - }catch(err: any){ - if(String(err).includes("git push")){ - func({ - error: String(err), - commited: true, - pushed: false - }) - }else{ - func({ - error: String(err), - commited: false, - pushed: false - }) - } - }finally{ - process.chdir(cwd) + commitToResetAtIndex++; + } + + commitToResetAtIndex -= 1; + + const logInfoToUse = logLists[commitToResetAtIndex]; + const cwd = process.cwd(); + try { + process.chdir(dir.fsPath); + execSync("git reset --soft " + logInfoToUse.code); + execSync('git commit -m "' + msgToCommit + '"'); + execSync("git push -f"); + func({ + error: undefined, + commited: true, + pushed: true, + }); + } catch (err: any) { + if (String(err).includes("git push")) { + func({ + error: String(err), + commited: true, + pushed: false, + }); + } else { + func({ + error: String(err), + commited: false, + pushed: false, + }); } + } finally { + process.chdir(cwd); + } } - export function dirGetLastLogMessageCode(uri: vscode.Uri): string | undefined { - const cwd = process.cwd() - process.chdir(uri.fsPath) - let result = "" - try{ - const exec = execSync("git log --oneline") - result = String(exec).split("\n")[0].trim() - }catch(err: any){ - result = String(err.stderr) - } - process.chdir(cwd) - if(result.includes("fatal: your current branch")){ - return undefined - } - let lastLogMessagePos = result.indexOf(" "); - return result.substring(0,lastLogMessagePos) + const cwd = process.cwd(); + process.chdir(uri.fsPath); + let result = ""; + try { + const exec = execSync("git log --oneline"); + result = String(exec).split("\n")[0].trim(); + } catch (err: any) { + result = String(err.stderr); + } + process.chdir(cwd); + if (result.includes("fatal: your current branch")) { + return undefined; + } + let lastLogMessagePos = result.indexOf(" "); + return result.substring(0, lastLogMessagePos); } export async function gitPush(dir: vscode.Uri) { - const currDir = process.cwd() - process.chdir(dir.fsPath) - - try{ - execSync("git push") - const code = dirGetLastLogMessageCode(dir) - vscode.window.showInformationMessage("😄 SaveMeBaby: Git push success ["+code!+"]") - }catch(err: any){ - vscode.window.showErrorMessage("😞 SaveMeBaby: Git push failed, error: ["+err.stderr+"]") - } - process.chdir(currDir) + const currDir = process.cwd(); + process.chdir(dir.fsPath); + + try { + execSync("git push"); + const code = dirGetLastLogMessageCode(dir); + vscode.window.showInformationMessage( + "😄 SaveMeBaby: Git push success [" + code! + "]", + ); + } catch (err: any) { + vscode.window.showErrorMessage( + "😞 SaveMeBaby: Git push failed, error: [" + err.stderr + "]", + ); + } + process.chdir(currDir); } /** Returns the git code represntation of the commit, * if error occurs the string will contain the error message * and not the git commit code. */ -export async function startGitCommit(logMsg: string | undefined, file: vscode.Uri, func: CommitFunction){ - let commitStatus: CommitStatus = { - status: "None", - msg: undefined, - error: undefined +export async function startGitCommit( + logMsg: string | undefined, + file: vscode.Uri, + func: CommitFunction, +) { + let commitStatus: CommitStatus = { + status: "None", + msg: undefined, + error: undefined, + }; + //file does not exists + if (!fs.existsSync(file.fsPath)) { + commitStatus.status = "Error"; + commitStatus.error = + "File " + file.fragment + "Doesn't exist on disk yet, can't be commited"; + func(commitStatus); + return; + } + if (logMsg === undefined) { + logMsg = "First Commit."; + } + let currDir = process.cwd(); + try { + const parentDir = getParentDir(file); + process.chdir(parentDir.fsPath); + execSync("git add " + file.fsPath); + execSync('git commit -m "' + logMsg + '"'); + const gitCode = dirGetLastLogMessageCode(parentDir); + if (gitCode === undefined) { + commitStatus.status = "Error"; + commitStatus.error = + "Couldn't get last Log message, can't confirm commit"; + func(commitStatus); + return; } - //file does not exists - if(!fs.existsSync(file.fsPath)){ - commitStatus.status = "Error" - commitStatus.error = "File "+file.fragment+"Doesn't exist on disk yet, can't be commited" - func(commitStatus) - return - } - if(logMsg===undefined){ - logMsg="First Commit." - } - let currDir = process.cwd() - try{ - const parentDir = getParentDir(file) - process.chdir(parentDir.fsPath) - execSync("git add "+file.fsPath) - execSync("git commit -m \""+logMsg+"\"") - const gitCode = dirGetLastLogMessageCode(parentDir) - if(gitCode===undefined){ - commitStatus.status = "Error" - commitStatus.error = "Couldn't get last Log message, can't confirm commit" - func(commitStatus) - return - } - commitStatus.msg = gitCode! - commitStatus.status = "Comitted" - func(commitStatus) - return - }catch(err: any){ - const errString = String(err.stderr) - if(errString.includes("paths are ignored")){ - commitStatus.status = "GitIgnored" - }else{ - commitStatus.status = "Error" - } - commitStatus.error = errString - func(commitStatus) - return - }finally{ - process.chdir(currDir) + commitStatus.msg = gitCode!; + commitStatus.status = "Comitted"; + func(commitStatus); + return; + } catch (err: any) { + const errString = String(err.stderr); + if (errString.includes("paths are ignored")) { + commitStatus.status = "GitIgnored"; + } else { + commitStatus.status = "Error"; } -} \ No newline at end of file + commitStatus.error = errString; + func(commitStatus); + return; + } finally { + process.chdir(currDir); + } +}