How to include git revision into angular-cli application?

前端 未结 9 2192
甜味超标
甜味超标 2021-01-31 16:40

I need to display git revision on my angular2 application\'s about page. The project is based on angular-cli.

How can build be extended so git revision is put for exampl

9条回答
  •  醉酒成梦
    2021-01-31 16:42

    1. Add git-version.js to the root.This code will execute git commands and write the output to the git-version.json file.
    const childProcess = require('child_process');
    const { writeFileSync } = require('fs');
    
    const longSHA = childProcess.execSync("git rev-parse HEAD").toString().trim();
    const shortSHA = childProcess.execSync("git rev-parse --short HEAD").toString().trim();
    const branch = childProcess.execSync('git rev-parse --abbrev-ref HEAD').toString().trim();
    const authorName = childProcess.execSync("git log -1 --pretty=format:'%an'").toString().trim();
    const commitTime = childProcess.execSync("git log -1 --pretty=format:'%cd'").toString().trim();
    const commitMsg = childProcess.execSync("git log -1 --pretty=%B").toString().trim();
    const totalCommitCount = childProcess.execSync("git rev-list --count HEAD").toString().trim();
    
    const versionInfo = {
        shortSHA: shortSHA,
        SHA : longSHA,
        branch: branch,
        lastCommitAuthor: authorName,
        lastCommitTime: commitTime,
        lastCommitMessage: commitMsg,
        lastCommitNumber: totalCommitCount
    }
    
    const versionInfoJson = JSON.stringify(versionInfo, null, 2);
    
    writeFileSync('/src/git-version.json', versionInfoJson);
    

    This code will generate the git-version.json file :-

    {
      "shortSHA": "0e786d4",
      "SHA": "0e786d4ad3778463f6f30c28f254cc85c24eb4b3",
      "branch": "master",
      "lastCommitAuthor": "'saurabh'",
      "lastCommitTime": "'Thu Apr 9 12:59:16 2020 +0530'",
      "lastCommitMessage": "Commit message",
      "lastCommitNumber": "200"
    }
    

    Modify above code as per your requirements.

    Run: node git-version.js This will generate the git-version.json into src directory.

    1. To run this code before or after the build. add a new script to package.json
    "scripts": {
       "ng": "ng",
       "start": "ng serve",
       "build": "ng build",
       "test": "ng test",
       "lint": "ng lint",
       "e2e": "ng e2e",
       "build.prod": "node git-version.js && ng build --prod"
     }
    
    1. Run:- npm run build.prod

    suggestions for code improvement are welcome :)

提交回复
热议问题