Table of Contents
Building the environment
Record the information submitted each time
Generate version information
Generate version information based on the environment
Combined with Angular to display version information on the page
Home Web Front-end JS Tutorial How Angular combines Git Commit for version processing

How Angular combines Git Commit for version processing

Mar 28, 2022 am 11:36 AM
angular

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
Copy after login

Step 2: Create a project

# ng new PROJECT_NAME
ng new ng-commit
Copy after login

Step 3: Run the project

npm run start
Copy after login

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                                        // 全局样式
Copy after login

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))
}
Copy after login

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"
}
Copy after login

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;)
})
Copy after login

We add a command line to

package.json to facilitate management:

"scripts": {
  "version": "node version.js"
}
Copy after login

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             // 测试环境配置文件
Copy after login

The relevant file contents are as follows:

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

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",
}
Copy after login

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;)
})
Copy after login

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",
}
Copy after login

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;)
  }
}
Copy after login

Before using the request, you must mount the

app.module.ts file HttpClientModule Module:

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

// ...

imports: [
  HttpClientModule
],
Copy after login

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)
      }
    })
  }
}
Copy after login

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"
}
Copy after login

使用 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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Let's talk about metadata and decorators in Angular Let's talk about metadata and decorators in Angular Feb 28, 2022 am 11:10 AM

This article continues the learning of Angular, takes you to understand the metadata and decorators in Angular, and briefly understands their usage. I hope it will be helpful to everyone!

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

Angular + NG-ZORRO quickly develop a backend system Angular + NG-ZORRO quickly develop a backend system Apr 21, 2022 am 10:45 AM

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

See all articles