How Angular combines Git Commit for version processing
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!
The picture above is the Test environment/development environment
version information displayed on the page. [Recommended related tutorials: "angular tutorial"]
will be introduced later
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 fileversion.txt in the root directory to store the submitted information; in the root directory Create a file
commit.js for manipulating submission information.
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()+'-'+(date.getMonth()+1)+'-'+date.getDate()+' '+date.getHours()+':'+date.getMinutes()}\n说明:${message}\n${new Array(80).join('*')}\n${versionStr}`; fs.writeFileSync(versionPath, versionStr); // 写入版本信息之后,自动将版本信息提交到当前分支的git上 if(autoPush) { // 这一步可以按照实际的需求来编写 execSync(`git add ${ versionPath }`); execSync(`git commit ${ versionPath } -m 自动提交版本信息`); execSync(`git push origin ${ execSync('git rev-parse --abbrev-ref HEAD').toString().trim() }`) } } if(fs.existsSync(buildPath)) { fs.writeFileSync(`${ buildPath }/${ versionPath }`, fs.readFileSync(versionPath)) }
node commit.js. In order to facilitate management, we add the command line to
package.json:
"scripts": { "commit": "node commit.js" }
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 throughcommit information
version .json is gone.
version.js to generate version data.
const execSync = require('child_process').execSync; const fs = require('fs') const targetFile = 'src/assets/version.json'; // 存储到的目标文件 const commit = execSync('git show -s --format=%h').toString().trim(); //当前提交的版本号,hash 值的前7位 let date = new Date(execSync('git show -s --format=%cd').toString()); // 日期 let message = execSync('git show -s --format=%s').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('Stringify Json data is saved.') })
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 environmentdevelopment, 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
config ├── default.json // 项目调用的配置文件 ├── development.json // 开发环境配置文件 ├── production.json // 生产环境配置文件 └── test.json // 测试环境配置文件
// 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 ofGenerate version information to generate different version information according to different environments. The specific code is as follows:
const execSync = require('child_process').execSync; const fs = require('fs') const targetFile = 'src/assets/version.json'; // 存储到的目标文件 const config = require('./config/default.json'); const commit = execSync('git show -s --format=%h').toString().trim(); //当前提交的版本号 let date = new Date(execSync('git show -s --format=%cd').toString()); // 日期 let message = execSync('git show -s --format=%s').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 === 'production') { versionObj.version = config.version } if(config.env === 'development') { versionObj.version = `${ config.version }:beta` } if(config.env === 'test') { versionObj.version = `${ config.version }-${ formatDay(date) }:${ commit }` } const data = JSON.stringify(versionObj); fs.writeFile(targetFile, data, (err) => { if(err) { throw err } console.log('Stringify Json data is saved.') })
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", }
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 withangular.
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 '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class VersionService { constructor( private http: HttpClient ) { } public getVersion():Observable<any> { return this.http.get('assets/version.json') } }
app.module.ts file
HttpClientModule Module:
import { HttpClientModule } from '@angular/common/http'; // ... imports: [ HttpClientModule ],
app.component.ts File:
import { Component } from '@angular/core'; import { VersionService } from './services/version.service'; // 引入版本服务 @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.less'] }) export class AppComponent { public version: string = '1.0.0' constructor( private readonly versionService: VersionService ) {} ngOnInit() { this.versionService.getVersion().subscribe({ next: (data: any) => { this.version = data.version // 更改版本信息 }, error: (error: any) => { console.error(error) } }) } }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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!

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

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!

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

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

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!

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!

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!
