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
.
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.
version.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.
commit 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" }
development, production environment
production and car test environment
test.
, such as: 1.1.0
, such as: 1.1.0:beta
, 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.
angular.
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!