当前位置: 首页 > 工具软件 > node-git > 使用案例 >

node脚本, 封装git命令

寿子默
2023-12-01

     最近有个需求每次提交版本都需要改变项目login页面的版本号,但是执行起来总是会忘记;
于是写了个node脚本,顺便学习了下shelljs, 代码如下


// require('shelljs/global'); 全局执行的shelljs 

const shell = require("shelljs");  // 执行文件操作
const argv = require('yargs').argv; // yargs 处理参数
const commit = argv._[0]

const path = `src\\pages\\login\\login.vue` // 要修改的文件路径

// 提取版本号最后的数字
function getLastStr(options) {
    return options.match(/\d+/g).slice(-1)[0]
}

// 替换版本号最后一位
function replaceLastStr(options, lastStr) {
    var arr = options.split('.')
    var lastIndex = arr.lastIndexOf(lastStr)
    arr.splice(lastIndex, 1, lastStr - 0 + 1)
    return arr.join('.')
}

// 获取文件里面匹配到的数据
var grepStr = shell.grep(/<version>.*<\/version>/, path).stdout

// 再次匹配解决grep匹配不精准的问题
var str = grepStr.match(/<version>.*<\/version>/)[0].replace('<version>', '').replace('</version>', '')

// 获取最后一位的版本号
var lastStr = getLastStr(str)

// 获取完整版本号
var repStr = replaceLastStr(str, lastStr)

// 执行git提交命令
shell.exec(`git pull`)

// 执行替换
shell.sed('-i', /<version>.*<\/version>/, `<version>${repStr}<\/version>`, path);

shell.exec('git add .')
shell.exec(`git commit -m "${commit}"`)
shell.exec(`git pull`)
shell.exec('git push')

脚本使用方式

执行 node 脚本文件名 "commit信息"的方式执行脚本
eg: node p '[fix]: xxxxx'

学习链接:

http://www.ruanyifeng.com/blog/2015/05/command-line-with-node.html
https://github.com/shelljs/shelljs

 类似资料: