Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to combine Angular with Git Commit for version processing

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to deal with the version of Angular combined with Git Commit, which is very detailed and has a certain reference value. Friends who are interested must finish it!

The image above shows the test environment / development environment version information shown on the page.

There is an introduction later.

The figure above shows the information of the Git Commit submitted each time. Of course, here I record every submission, which you can record every time you build.

So, let's next use Angular to achieve the effect, React and Vue are the same.

Build an environment

Since the focus here is not on building the environment, we can just use angular-cli scaffolding to generate a project directly.

Step 1: install scaffolding tools

Npm install-g @ angular/cli

Step 2: create a project

# ng new PROJECT_NAMEng new ng-commit

Step 3: run the project

Npm run start

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

Port 4200 is not occupied.

At this point, the ng-commit project focus folder src is composed as follows:

Src ├── app / / Application body │ ├── app-routing.module.ts / / routing module │. │ └── app.module.ts / / Application module ├── assets / / static resource ├── main.ts / / entry file. └── style.less / / Global style

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

Record the information submitted each time

Create a file version.txt in the root directory to store the submitted information, and a file commit.js in the root directory to manipulate the submitted information.

Focusing on commit.js, let's go straight 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 (); / / current version number let versionStr =''; / / version string if (fs.existsSync (versionPath)) {versionStr = fs.readFileSync (versionPath). ToString () +'\ n' } if (versionStr.indexOf (commit)! =-1) {console.warn ('\ x1B [33m% s\ x1b [0mm, 'warming: the current git version data already exists!\ n')} else {let name = execSync ('git show-s-format=%cn'). ToString (). Trim (); / / name let email = execSync (' git show-s-format=%ce'). ToString (). Trim () / / let date = new Date (execSync ('git show-s-- format=%cd'). ToString ()); / / date let message = execSync (' git show-s-- format=%s'). ToString () .trim () / / description versionStr = 'git:$ {commit}\ nauthor: ${name}\ ndate: ${date.getFullYear () +' -'+ (date.getMonth () + 1) +'- + date.getDate () +'+ date.getHours () +':'+ date.getMinutes ()}\ ndescription: ${message}\ n$ {new Array (80). Join ('*')}\ n$ {versionStr} `; fs.writeFileSync (versionPath, versionStr) / / after the version information is written, automatically submit the version information to the git of the current branch if (autoPush) {/ / this step can be used to write execSync (`version ${versionPath} `) according to the actual requirements; execSync (`git commit ${versionPath}-m automatically submit version information`) ExecSync (`git push origin ${execSync ('git rev-parse-- abbrev-ref HEAD'). ToString (). Trim ()} `)} if (fs.existsSync (buildPath)) {fs.writeFileSync (` ${buildPath} / ${versionPath} `, fs.readFileSync (versionPath))}

The above file can be done directly through node commit.js. To make it easier to manage, we added a command line to package.json:

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

That way, using npm run commit is equivalent to node commit.js.

Generate version information

With the above groundwork, we can use the information of commit to generate the version information version.json of the specified format.

Create a new file version.js in the root directory to generate the version of the data.

Const execSync = require ('child_process'). ExecSync;const fs = require (' fs') const targetFile = 'src/assets/version.json'; / / the target file const commit = execSync (' git show-s-format=%h'). ToString (). Trim (); / / the version number currently submitted, the first seven digits of the hash value let date = new Date (execSync ('git show-s-format=%cd'). ToString ()) / date let message = execSync ('git show-s-format=%s'). ToString (). Trim (); / explain 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.')})

We add a command line to package.json for easy management:

"scripts": {"version": "node version.js"} generate version information based on the environment

Generate different version information 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 new files in the root directory of the project as follows:

Config ├── default.json / / configuration file called by the project ├── development.json / / Development environment profile ├── production.json / / production environment profile └── test.json / / Test environment profile

The relevant documents 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 copies the configuration information of different environments based on the command line and configures 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 the generated 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'; / / stored to the target file const config = require ('. / config/default.json'); const commit = execSync ('git show-s-format=%h'). ToString (). Trim (); / / currently submitted version number let date = new Date (execSync (' git show-s-format=%cd'). ToString ()) / date let message = execSync ('git show-s-- format=%s'). ToString (). Trim (); / / explain let versionObj = {"env": config.env, "version": "", "commit": commit, "date": date, "message": message} / / format date 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.')})

Add command lines for different environments in package.json:

"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",}

The generated version information is stored directly in assets, and the specific path is src/assets/version.json.

Display version information on the page with Angular

The last step is to display the version information on the page, which is combined with angular.

Use ng generate service version to generate the version service in the app/services directory. Add the request information to 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 {return this.http.get ('assets/version.json')}}

Before using the request, mount the HttpClientModule module in the app.module.ts file:

Import {HttpClientModule} from'@ angular/common/http';//... imports: [HttpClientModule]

Then you can call it in the component, here is the app.component.ts file:

Import {Component} from'@ angular/core';import {VersionService} from'. / services/version.service' / / introduce 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 / / change version information} Error: (error: any) = > {console.error (error)}})}}

At this point, we have completed the version information. Finally, let's adjust the command 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"}

The first purpose of using scripts is to facilitate management, but to facilitate the construction of jenkins and easy to call. As for the jenkins section, interested parties can try it on their own.

The above is all the contents of the article "how to combine Angular with Git Commit for version processing". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report