Skip to content
Snippets Groups Projects
Select Git revision
  • b3cb415109fab22d573f99dbad89f567b7289a4a
  • main default protected
  • develop
3 results

README.md

Blame
  • gitMission.ts 3.95 KiB
    import { exec as execCallback } from 'child_process';
    import simpleGit, { SimpleGit, SimpleGitOptions } from 'simple-git';
    import { PROJECT_SRC_PATH } from './config';
    import UserConfig from './userConfig';
    import { log as customizableLog, error as customizableError } from '../recorder/utils/log';
    import { promisify } from 'util';
    
    const exec = promisify(execCallback);
    
    const defaultRemote = 'origin';
    
    export enum Branch {
      MASTER = 'master',
      DEFAULT = MASTER,
      LIVE = 'live',
    }
    
    export default class GitMission {
      private prefix = 'DEADLOCK-RECORDER';
      private git: SimpleGit;
    
      constructor(private userConfig: UserConfig) {
        const options: Partial<SimpleGitOptions> = {
          baseDir: PROJECT_SRC_PATH,
          binary: 'git',
          maxConcurrentProcesses: 2,
        };
    
        this.git = simpleGit(options);
      }
    
      log(message: any, ...args: any[]) {
        customizableLog(this.prefix, message, ...args);
      }
    
      error(message: any, ...args: any[]) {
        customizableError(this.prefix, message, ...args);
      }
    
      async setupSshAgent() {
        try {
          await exec(`ssh-add /tmp/.ssh/id_rsa`);
          await exec(
            `eval "$(ssh-agent -s)" && ssh-keyscan -p ${this.userConfig.getGiteaSshPort()} -H ${this.userConfig.getGiteaHost()} >> ~/.ssh/known_hosts`,
          );
        } catch (err) {
          this.log(err);
          if (err instanceof Error) {
            if (err) {
              this.error(err.message);
              throw err;
            }
          } else {
            this.log(`Unhandled error: ${err}`);
            throw err;
          }
        }
      }
    
      get author() {
        return this.userConfig.getUsername();
      }
    
      async init() {
        try {
          await this.setupSshAgent();
    
          await this.git.init();
    
          const remote = await this.readRemote();
    
          if (remote === defaultRemote) {
            return Promise.resolve(this);
          }
    
          const remotePath = this.getRemotePath();
    
          await this.git.addRemote(defaultRemote, remotePath);
          await this.git.addConfig('user.email', this.userConfig.getCurrentUserDetails().email, false, 'local');
          await this.git.addConfig(
            'user.name',
            `${this.userConfig.getCurrentUserDetails().lastName} ${this.userConfig.getCurrentUserDetails().firstName}`,
            false,
            'local',
          );
    
          return Promise.resolve(this);
        } catch (e) {
          this.error(e);
          return Promise.reject(e);
        }
      }
    
      private getRemotePath() {
        return `ssh://git@${this.userConfig.getGiteaHost()}:${this.userConfig.getGiteaSshPort()}/${this.userConfig.getRemoteGitUsername()}/${this.userConfig.getMissionId()}`;
      }
    
      async readRemote() {
        try {
          return ((await this.git.remote([])) || '').replace(/(\r\n|\n|\r)/gm, '');
        } catch (e) {
          this.error(e);
        }
        return '';
      }
    
      fetch() {
        return this.git.fetch(defaultRemote);
      }
    
      pull(branch?: string) {
        return this.git.pull(defaultRemote, branch ?? Branch.DEFAULT, { '--rebase': 'true' });
      }
    
      addAll() {
        return this.git.add('.');
      }
    
      commit(message: string, options?: string[]) {
        return this.git.commit(message, options ?? []);
      }
    
      push() {
        return this.git.push(defaultRemote);
      }
    
      createLocalBranch(branch: string) {
        return this.git.checkout(['-b', branch]);
      }
    
      createRemoteBranch(branch: string) {
        return this.git.push(['-u', defaultRemote, branch]);
      }
    
      setUpstream(branch: string) {
        return this.git.branch(['-u', defaultRemote, branch]);
      }
    
      createBranch(branch: string) {
        const createBranchLocally = this.createLocalBranch(branch);
        const createRemoteBranch = this.createRemoteBranch(branch);
    
        return Promise.all([createBranchLocally, createRemoteBranch]);
      }
    
      checkout(branch: string) {
        return this.git.checkout(branch);
      }
    
      merge(options?: string[]) {
        return this.git.merge(options ?? []);
      }
    
      async isRemoteRepoExist() {
        try {
          const remotes = await this.git.listRemote();
          return remotes.length !== 0;
        } catch {
          // error, Gitea throws Gitea: Unauthorized when not found
          return false;
        }
      }
    }