Home  >  Article  >  Web Front-end  >  How Angular combines Git Commit for version processing

How Angular combines Git Commit for version processing

青灯夜游
青灯夜游forward
2022-03-28 11:36:152049browse

This article will take you to continue learning angular and introduce the method of Angular combined with Git Commit version processing. I hope it will be helpful to everyone!

How Angular combines Git Commit for version processing

How Angular combines Git Commit for version processing

The picture above is the Test environment/development environment version information displayed on the page. [Recommended related tutorials: "angular tutorial"]

will be introduced later

How Angular combines Git Commit for version processing

as shown in the picture above It is the Git Commit information of each commit. Of course, here I record every commit. You can record it every time you build.

So, let’s use Angular to achieve the next effect. The same is true for React and Vue.

Building the environment

Because the focus here is not to build the environment, we can directly use the angular-cli scaffolding to directly generate a project.

Step 1: Install scaffolding tools

npm install -g @angular/cli

Step 2: Create a project

# ng new PROJECT_NAME
ng new ng-commit

Step 3: Run the project

npm run start

When the project is running, it will listen to the 4200 port by default. Just open http://localhost:4200/ directly in the browser.

On the premise that port 4200 is not occupied

At this time, ng-commit the key folder of the project src The composition is as follows:

src
├── app                                               // 应用主体
│   ├── app-routing.module.ts                         // 路由模块
│   .
│   └── app.module.ts                                 // 应用模块
├── assets                                            // 静态资源
├── main.ts                                           // 入口文件
.
└── style.less                                        // 全局样式

The above directory structure, we will add services service directory under the app directory later, and # under the assets directory ##version.json file.

Record the information submitted each time

Create a file

version.txt in the root directory to store the submitted information; in the root directory Create a file commit.js for manipulating submission information.

The focus is on

commit.js, we go directly to the topic:

const execSync = require('child_process').execSync;
const fs = require('fs')
const versionPath = 'version.txt'
const buildPath = 'dist'
const autoPush = true;
const commit = execSync('git show -s --format=%H').toString().trim(); // 当前的版本号

let versionStr = ''; // 版本字符串

if(fs.existsSync(versionPath)) {
  versionStr = fs.readFileSync(versionPath).toString() + '\n';
}

if(versionStr.indexOf(commit) != -1) {
  console.warn('\x1B[33m%s\x1b[0m', 'warming: 当前的git版本数据已经存在了!\n')
} else {
  let name = execSync('git show -s --format=%cn').toString().trim(); // 姓名
  let email = execSync('git show -s --format=%ce').toString().trim(); // 邮箱
  let date = new Date(execSync('git show -s --format=%cd').toString()); // 日期
  let message = execSync('git show -s --format=%s').toString().trim(); // 说明
  versionStr = `git:${commit}\n作者:${name}<${email}>\n日期:${date.getFullYear()+&#39;-&#39;+(date.getMonth()+1)+&#39;-&#39;+date.getDate()+&#39; &#39;+date.getHours()+&#39;:&#39;+date.getMinutes()}\n说明:${message}\n${new Array(80).join(&#39;*&#39;)}\n${versionStr}`;
  fs.writeFileSync(versionPath, versionStr);
  // 写入版本信息之后,自动将版本信息提交到当前分支的git上
  if(autoPush) { // 这一步可以按照实际的需求来编写
    execSync(`git add ${ versionPath }`);
    execSync(`git commit ${ versionPath } -m 自动提交版本信息`);
    execSync(`git push origin ${ execSync(&#39;git rev-parse --abbrev-ref HEAD&#39;).toString().trim() }`)
  }
}

if(fs.existsSync(buildPath)) {
  fs.writeFileSync(`${ buildPath }/${ versionPath }`, fs.readFileSync(versionPath))
}

The above files can be processed directly through

node commit.js. In order to facilitate management, we add the command line to package.json:

"scripts": {
  "commit": "node commit.js"
}

Like this, use

npm run commit which is equivalent to node commit.js Effect.

Generate version information

With the above foundation, we can generate version information in the specified format through

commit informationversion .json is gone.

Create a new file in the root directory

version.js to generate version data.

const execSync = require(&#39;child_process&#39;).execSync;
const fs = require(&#39;fs&#39;)
const targetFile = &#39;src/assets/version.json&#39;; // 存储到的目标文件

const commit = execSync(&#39;git show -s --format=%h&#39;).toString().trim(); //当前提交的版本号,hash 值的前7位
let date = new Date(execSync(&#39;git show -s --format=%cd&#39;).toString()); // 日期
let message = execSync(&#39;git show -s --format=%s&#39;).toString().trim(); // 说明

let versionObj = {
  "commit": commit,
  "date": date,
  "message": message
};

const data = JSON.stringify(versionObj);

fs.writeFile(targetFile, data, (err) => {
  if(err) {
    throw err
  }
  console.log(&#39;Stringify Json data is saved.&#39;)
})

We add a command line to

package.json to facilitate management:

"scripts": {
  "version": "node version.js"
}

Generate version information based on the environment

Different version information is generated for different environments. Suppose we have development environment

development, production environment production and car test environment test.

    The production environment version information is
  • major.minor.patch, such as: 1.1.0
  • The development environment version information is
  • major.minor.patch :beta, such as: 1.1.0:beta
  • The test environment version information is
  • major.minor.path-data:hash, such as: 1.1.0-2022.01.01: 4rtr5rg
To facilitate the management of different environments, we create a new file in the root directory of the project as follows:

config
├── default.json          // 项目调用的配置文件
├── development.json      // 开发环境配置文件
├── production.json       // 生产环境配置文件
└── test.json             // 测试环境配置文件

The relevant file contents are as follows:

// development.json
{
  "env": "development",
  "version": "1.3.0"
}
// production.json
{
  "env": "production",
  "version": "1.3.0"
}
// test.json
{
  "env": "test",
  "version": "1.3.0"
}

default .json Copy the configuration information of different environments based on the command line, and configure it in package.json:

"scripts": {
  "copyConfigProduction": "cp ./config/production.json ./config/default.json",
  "copyConfigDevelopment": "cp ./config/development.json ./config/default.json",
  "copyConfigTest": "cp ./config/test.json ./config/default.json",
}

Is easy Bro, right?

Integrate the contents of

Generate version information to generate different version information according to different environments. The specific code is as follows:

const execSync = require(&#39;child_process&#39;).execSync;
const fs = require(&#39;fs&#39;)
const targetFile = &#39;src/assets/version.json&#39;; // 存储到的目标文件
const config = require(&#39;./config/default.json&#39;);

const commit = execSync(&#39;git show -s --format=%h&#39;).toString().trim(); //当前提交的版本号
let date = new Date(execSync(&#39;git show -s --format=%cd&#39;).toString()); // 日期
let message = execSync(&#39;git show -s --format=%s&#39;).toString().trim(); // 说明

let versionObj = {
  "env": config.env,
  "version": "",
  "commit": commit,
  "date": date,
  "message": message
};

// 格式化日期
const formatDay = (date) => {
  let formatted_date = date.getFullYear() + "." + (date.getMonth()+1) + "." +date.getDate()
    return formatted_date;
}

if(config.env === &#39;production&#39;) {
  versionObj.version = config.version
}

if(config.env === &#39;development&#39;) {
  versionObj.version = `${ config.version }:beta`
}

if(config.env === &#39;test&#39;) {
  versionObj.version = `${ config.version }-${ formatDay(date) }:${ commit }`
}

const data = JSON.stringify(versionObj);

fs.writeFile(targetFile, data, (err) => {
  if(err) {
    throw err
  }
  console.log(&#39;Stringify Json data is saved.&#39;)
})

Add in

package.json Command lines in different environments: The version information generated by

"scripts": {
  "build:production": "npm run copyConfigProduction && npm run version",
  "build:development": "npm run copyConfigDevelopment && npm run version",
  "build:test": "npm run copyConfigTest && npm run version",
}

will be directly stored in

assets, and the specific path is src/assets/version.json.

Combined with Angular to display version information on the page

The last step is to display the version information on the page. This is combined with

angular.

Use

ng generate service version to generate the version service in the app/services directory. Add the request information in the generated version.service.ts file, as follows:

import { Injectable } from &#39;@angular/core&#39;;
import { HttpClient } from &#39;@angular/common/http&#39;;
import { Observable } from &#39;rxjs&#39;;

@Injectable({
  providedIn: &#39;root&#39;
})
export class VersionService {

  constructor(
    private http: HttpClient
  ) { }

  public getVersion():Observable<any> {
    return this.http.get(&#39;assets/version.json&#39;)
  }
}

Before using the request, you must mount the

app.module.ts file HttpClientModule Module:

import { HttpClientModule } from &#39;@angular/common/http&#39;;

// ...

imports: [
  HttpClientModule
],

Then just call it in the component. Here is

app.component.ts File:

import { Component } from &#39;@angular/core&#39;;
import { VersionService } from &#39;./services/version.service&#39;; // 引入版本服务

@Component({
  selector: &#39;app-root&#39;,
  templateUrl: &#39;./app.component.html&#39;,
  styleUrls: [&#39;./app.component.less&#39;]
})
export class AppComponent {

  public version: string = &#39;1.0.0&#39;

  constructor(
    private readonly versionService: VersionService
  ) {}

  ngOnInit() {
    this.versionService.getVersion().subscribe({
      next: (data: any) => {
        this.version = data.version // 更改版本信息
      },
      error: (error: any) => {
        console.error(error)
      }
    })
  }
}

At this point, we are done version information. Let’s finally adjust the commands of

package.json:

"scripts": {
  "start": "ng serve",
  "version": "node version.js",
  "commit": "node commit.js",
  "build": "ng build",
  "build:production": "npm run copyConfigProduction && npm run version && npm run build",
  "build:development": "npm run copyConfigDevelopment && npm run version && npm run build",
  "build:test": "npm run copyConfigTest && npm run version && npm run build",
  "copyConfigProduction": "cp ./config/production.json ./config/default.json",
  "copyConfigDevelopment": "cp ./config/development.json ./config/default.json",
  "copyConfigTest": "cp ./config/test.json ./config/default.json"
}

使用 scripts 一是为了方便管理,而是方便 jenkins 构建方便调用。对于 jenkins 部分,感兴趣者可以自行尝试。

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of How Angular combines Git Commit for version processing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete