让小脚本帮你做哪些枯燥无味的git提交吧

5,796 阅读2分钟

睡前小故事

在某次开会的时候,组长说每次做完一个小需求和修改一个bug都要提交一个commit,下班前要将本地分支推送到远程仓库。没commit的,没push的都扣当月的绩效...,虽然觉得这样很烦躁,但是谁让自己是打工崽呢,又不敢说什么,只能照着做了,还能怎么办。之后就是每天不停的git status, git add . ,git commit -m 'xxxxx'...有时bug多的时候,一天输入几十次这样的命令,终于有一天我受不了,实在太没劲了(也许是自己懒吧),git,git,git的,代码还写不写啊。然后就想能不能输一个命令自动完成这几个步骤,接着就诞生了这个小脚本。

脚本的实现

脚本用shell写的

判断有没有安装git

if(!shell.which('git')) {
  shell.echo('你还没安装git,请先安装git')
  shell.exit(1)
}

判断有没有文件变动

if(shell.exec('git status').stdout.indexOf('working tree clean') !== -1) {
  shell.echo('没有变动文件')
  shell.exit(1)
}

查看哪些文件变动了

if(shell.exec('git status').code !== 0) {
  shell.echo('git status执行出错')
  shell.exit(1)
}

添加文件的追踪

if(shell.exec('git add .').code !== 0) {
  shell.echo('git add执行出错')
  shell.exit(1)
}

提交本地仓库

let intro = process.argv[2]

if(!intro) {
  shell.echo('请填写提交信息,格式为feat(xxxx):xxxxx')
  shell.exit(1)
}
if(shell.exec(`git commit -m ${intro}`).code !== 0) {
  shell.echo('git  commit执行出错')
  shell.exit(1)
}

推送远程仓库

let BranchName = shell.exec('git rev-parse --abbrev-ref HEAD')
// 因为我7点下班,七点后commit的都会推送到远程
if(new Date().getHours() >= 19) {
  if(shell.exec(`git push origin ${BranchName}`).code !== 0) {
    shell.echo('推送远程失败')
    shell.exit(1)
  }
  shell.echo('推送远程完成')
}

完整代码

let shell = require('shelljs')

if(!shell.which('git')) {
  shell.echo('你还没安装git,请先安装git')
  shell.exit(1)
}

shell.echo('查看哪些文件变动')

if(shell.exec('git status').stdout.indexOf('working tree clean') !== -1) {
  shell.echo('没有变动文件')
  shell.exit(1)
}

if(shell.exec('git status').code !== 0) {
  shell.echo('git status执行出错')
  shell.exit(1)
}

shell.echo('开始添加新文件追踪')

if(shell.exec('git add .').code !== 0) {
  shell.echo('git add执行出错')
  shell.exit(1)
}

let intro = process.argv[2]

if(!intro) {
  shell.echo('请填写提交信息,格式为feat(xxxx):xxxxx')
  shell.exit(1)
}

if(shell.exec(`git commit -m ${intro}`).code !== 0) {
  shell.echo('git  commit执行出错')
  shell.exit(1)
}

let BranchName = shell.exec('git rev-parse --abbrev-ref HEAD')

shell.echo(`代码提交到本地完成,当前分支是${BranchName}`)

if(new Date().getHours() >= 19) {
  if(shell.exec(`git push origin ${BranchName}`).code !== 0) {
    shell.echo('推送远程失败')
    shell.exit(1)
  }
  shell.echo('推送远程完成')
}

使用

 node git-commit.js(写上你脚本的文件) 'feat(xxx):xxxxx'(你要commit的描述)

效果

没变动

image.png

有变动

image.png

总结

程序猿懒就对。