利用 NPM 脚本自动化 Git 提交:简化提交变更的流程

20240720更新: 利用 Shell 脚本高效管理博客:从创建到推送 背景: 在完成一篇博客后,我们通常需要执行一系列命令:

  1. 预览博客(可选):hexo clean && hexo generate && hexo server
  2. 添加到暂存区:git add .
  3. 提交到本地仓库:git commit -m "update: 新博客 '博客标题' 提交时间"
  4. 推送到远程仓库:git push

痛点: 这样的流程繁琐不说,还需要手动编写提交消息,涉及时间和博客标题等信息,不够规范,也容易出错。

解决方法: 通过编辑package.json文件,添加一个自定义的npm脚本,可以自动执行以上步骤,避免了手动编写提交消息,并且使得流程更规范化。

1
2
3
4
5
{
  "scripts":{
    "new": "sh -c 'post_name=$1 && date=$(date \"+%Y-%m-%d %H:%M:%S\") && git add . && git commit -m \"update: 新博客 '\"$post_name\"' 提交时间 '\"$date\"'\" && git push' --"
  }
}

Bug修复: npm脚本过长导致阅读困难,进而导致编写错误和变量丢失(修复时间:2024-06-24 21:21) 为了解决上述问题,我们将相关代码抽取至blog_publish.sh中:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/bin/bash
post_name=$1
if [ ! -n "$post_name" ]; then
  echo "Usage: $0 [post_name] or pnpm new [post_name]"
  exit 1
fi
date=$(date "+%Y-%m-%d %H:%M:%S")
git add .
git commit -m "update:新博客 \"$post_name\" 提交时间 \"$date\""
git push

同时,我们对package.json进行如下修改:

1
2
3
4
5
{
  "scripts":{
    "new": "bash blog_publish.sh",
  }
}

这段脚本设置了两个变量:post_namedate,其中post_name接收命令行参数,date是格式化后的当前时间。 使用方法:

1
pnpm new [post_name]

局限性: 该方法目前仅适用于Linux系统,Windows系统需要编写兼容性代码。