preface

Github Actions repository to automatically synchronize Gitee and update documentation – Nuggets (juejin. Cn) article introduction describes the author open source a tool library. Git Push manually, rollup package, and update the version value in package.json files are required each time medash-npm (nPMjs.com) is updated. I wrote 50+ lines of code to free my hands.

Realize terminal interactive selection version number

Version number changes are only considered in four cases:

  1. Update the major version number, for example, 1.0.0 to 2.0.0
  2. Update the subversion number, for example, 1.0.0 to 1.1.0
  3. Phase version number, for example, 1.0.0 changed to 1.0.1
  4. Beta version, such as 1.0.0 changed to 1.0.0-beta.1

The naming rules for version numbers are defined by. Concatenate, so you can use the re to get the version information out.

First, the version number information is stored in the package. jsonVersion field value, and the code uses TypeScript Chinese language · TypeScript — a superset of JavaScript (tslatter.cn). When Ts is executed, es6 modularity is compiled into CommonJS modularity supported in the Node environment. Import PKG from “.. /package.json”; Const PKG = require(“.. / package. Json “). The CommonJS standard states that when importing Json files, the Json file will be deserialized, so the read Json has been deserialized and no json.parse operation is required.

import pkg from ".. /package.json";
const version = pkg.version;
const reg = / [1-9]) \. ([0-9]) \. ([0-9]? :(\-\w*)\.([1-9]+))? /g;
const execs = reg.exec(version) as Array<any>;
Copy the code

NPM Install Inquirer then installs Inquirer, which is a toolkit that provides terminal interaction.

The version number selection list provided by the program can be divided into two cases:

  1. The version number contains beta;
  2. The version number does not contain beta.

Whether there is beta is determined by the presence of execs[4].

/ /...
const onSelectVersion = async() = > {const beta = execs[4];
    // Handle the case where the version contains beta
    const lists = beta ? getBetaVersionLists(beta) : getVersionlists();
    inquirer.prompt([{
        name: 'list'.type: 'list'.message: 'Please select release version :'.choices: lists,
        default: [lists[0]]}])/ /...
}
Copy the code

Handle the case with beta

const getBetaVersionLists = (beta) = > ([
    getVersion([execs[1], execs[2], execs[3]]),
    getVersion([execs[1], execs[2], execs[3+]])`${beta}.${addOne(execs[5])}`
])
Copy the code

Handle cases where there is no beta

const getVersionlists = () = > ([
    getVersion([addOne(execs[1]), execs[2], execs[3]]),
    getVersion([execs[1], addOne(execs[2]), execs[3]]),
    getVersion([execs[1], execs[2], addOne(execs[3]]]])Copy the code

The getVersion and addOne methods are used to concatenate the complete version number and the number +1, respectively

const addOne = (num) = > Number(num) + 1;
const getVersion = ([major, minor, patch]) = > `v${major}.${minor}.${patch}`
Copy the code

Effects without beta:

The effect of beta:

Note: The code language is TypeScript, so we need ts-Node-npm (npmjs.com) to compile it for us.

NPM run release is a custom command that can be configured under scripts of the package.json file.

/ /...
    "scripts": {
        / /..
        "release": "ts-node scripts/release.ts"
    },
/ /...
Copy the code

Finally, import the Node file module, re-assign the selected version number to Version, and write package.json

/ /...
import path from "path";
import fs from "fs";
/ /...
const onSelectVersion = async() = > {const beta = execs[4];
    // Handle the case where the version contains beta
    const lists = beta ? getBetaVersionLists(beta) : getVersionlists();
    inquirer.prompt([{
        name: 'list'.type: 'list'.message: 'Please select release version :'.choices: lists,
        default: [lists[0]]
    }]).then(async ({ list }) => {
        pkg.version = list
        / /...
        fs.writeFile(path.join(__dirname, '.. /package.json'), String(JSON.stringify(pkg)), 'utf8'.async (error) => {
            if (error) {
                return;
            }
            / /...}); })}Copy the code

Now, a version selection feature is complete.

Say goodbye to the Shell language

The version selection is complete, then you need to deal with a series of Git command submission code, Git automatic Tag and update to Npm.

The following commands need to be processed:

Git add. Git commit -m xx git tag ** git push origin ** git push origin branch NPM run build NPM publish // NPM publishCopy the code

Where NPM Run build will perform rullop packaging

To automate the execution of some commands in the terminal, Shell is needed, and Shell files are created to complete the corresponding logic. As a front-end engineer, you need to learn the Shell, there are learning costs.

In keeping with the idea of finally implementing in Js what can be implemented in Js, the Node child_process child module provides an API for executing Shell commands.

There is, of course, a more convenient tool called ZX, which is open-source by Google.

NPM I zx install zx, import zx #! /usr/bin/env zx is required by ZX.

#! /usr/bin/env zx
/...
import{$}from 'zx';

Copy the code

Get the current Git branch by regular matching:

const onSelectVersion = async() = > {const beta = execs[4];
    // Handle the case where the version contains beta
    const lists = beta ? getBetaVersionLists(beta) : getVersionlists();
    inquirer.prompt([{
   / /...
    }]).then(async ({ list }) => {
        pkg.version = list
        let branch = await $`git branch`;
        const { stdout } = branch;
        const reg = /\*\D(.+)\D/g;
        branch = (reg.exec(stdout) as any[[])1];
        fs.writeFile(path.join(__dirname, '.. /package.json'), String(JSON.stringify(pkg)), 'utf8'.async (error) => {
            if (error) {
                return;
            }
            / /...}); })}Copy the code

Execute commands in sequence

const onSelectVersion = async() = > {/ /..
    inquirer.prompt([{
     / /...
    }]).then(async ({ list }) => {
      / /...
        fs.writeFile(path.join(__dirname, '.. /package.json'), String(JSON.stringify(pkg)), 'utf8'.async (error) => {
            if (error) {
                return;
            }
            await $`git add .`;
            await $`git commit -m ${list}`;
            await $`git tag ${list}`;
            await $`git push origin ${list}`;
            await $`git push origin ${branch}`;
            await $`npm run build&&npm publish`; }); })}Copy the code

The zX method $works by using the spawn method in the child_process child module

At this point, a simple script is complete, with a total of 50+ lines counting overhead lines.

The last

The implementation logic is very simple and has no difficulty. At work, there are certain things that need to be done over and over again, and we need to think about whether we can simplify it and learn to be a “lazy” tool person.

Thanks for reading, the code involved in this article is open source, please download and try release.ts.