前语

GitHub ActionsGitHub平台提供的一项功能,用于主动化构建、测验和布置软件项目。

它能够让咱们在特定的事情(如pushpull request 事情等)或条件产生(如特定时刻执行等)时执行自定义的作业流程。

本文将经过从 0-1 的方法带你布置一个自己的主动化作业流。(这是我的Demo库房,你能够作为参考)

新建库房

首要,你需求在 GitHub 上创建一个库房,该库房作为咱们的主动化作业流项目。

从0-1带你部署Github Actions自动化任务

装备主动化作业流

库房创建好之后,咱们能够找到库房的 Actions ,并运用推荐的作业流装备,它很简单和根底,咱们能够基于它定制咱们自己的作业流

从0-1带你部署Github Actions自动化任务

根底的作业流装备如下


name: CI

# Controls when the workflow will run
# 操控作业流何时运转
on:
 # Triggers the workflow on push or pull request events but only for the "main" branch
 # 当主分支存在 push 或许 pull request请 求时触发使命
  push:
   branches: [ "main" ]
  pull_request:
   branches: [ "main" ]

 # Allows you to run this workflow manually from the Actions tab
 # 答应, 从库房的 Actions 选项卡手动运转当时作业流
  workflow_dispatch:

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
# 作业流由一个或多个作业组成,这些作业能够次序运转,也能够并行运转
jobs:
  build:
  # 作业运转的体系环境(运转时环境)
   runs-on: ubuntu-latest

  # Steps represent a sequence of tasks that will be executed as part of the job
  # 过程,表示完结该作业的一些列原子操作/过程
   steps:
   # 跳转到当时库房的$GITHUB_WORKSPACE目录,以便拜访库房中的代码
    - uses: actions/checkout@v3

   # 运转一个shell指令
   # name 为过程名称,run 为运转shell脚本
    - name: Run a one-line script
     run: echo Hello, world!

   # 运转一组指令
    - name: Run a multi-line script
     run: |
      echo Add other actions to build,
      echo test, and deploy your project.

点右上角的Commit changes...按钮,将根底作业流提交到咱们的库房中

因为咱们提交了一个文件blank.yml到库房中,这时会触发 push 请求,所以也会主动触发咱们的使命。

从0-1带你部署Github Actions自动化任务

实战-版别号更新使命

咱们完结的使命是:当主分支有push或许pull request时,咱们就更新package.json中的版别号。

这应该是很长见的场景,下面咱们就来完结一下

1. 将库房克隆到本地,初始化npm

npm init -y

2. 新建updateVersion.js文件,编写更新版别号的脚本

const fsp = require("fs/promises");
const { exec } = require('child_process');
const path = require('path');
​
async function autoUpdateVersion() {
  // 读取 package.json 文件
  const PKG_PATH = path.resolve(__dirname, "package.json");
  try {
    const data = await fsp.readFile(PKG_PATH, { encoding: "utf-8" });
    const pkg = JSON.parse(data);
​
    // 更新版别号
    const currentVersion = pkg.version;
    const versionParts = currentVersion.split('.');
    let [major, minor, patch] = versionParts.map(Number);
    patch++;
    const newVersion = `${major}.${minor}.${patch}`;
​
    pkg.version = newVersion;
​
    await fsp.writeFile(PKG_PATH, JSON.stringify(pkg, null, 2), { encoding: "utf-8" });
    // 执行 Git 指令提交更新
    const commitMessage = `[AutoUpdateVersion] update version for ${newVersion}`;
    exec(`git commit -am "${commitMessage}"`, (error, stdout, stderr) => {
      if (error) {
        console.error('执行 Git 指令时犯错:', error);
       } else {
        console.log(`package.json 的版别号已更新为 ${newVersion}`);
        console.log('Git 提交成功!');
       }
     });
​
   } catch (error) {
    console.error(error);
    throw error;
   }
}
​
autoUpdateVersion();
​

3.装备版别号更新使命

下面是完结版别号更新使命的装备,我做了比较详细的备注,都比较好理解。

其间,装备里用到了几个环境变量secrets.GITHUB_TOKENsecrets.NAMEsecrets.EMAIL

secrets.GITHUB_TOKEN 属于Github库房的内置环境变量

secrets.NAMEsecrets.EMAIL 是自定义的环境变量

关于环境变量,我会在后面进行说明

name: AutoUpdateVersion

# Controls when the workflow will run
# 操控作业流何时运转
on:
 # Triggers the workflow on push or pull request events but only for the "main" branch
 # 当主分支存在 push 或许 pull请 求时触发使命
  push:
   branches: ["main"]
  pull_request:
   branches: ["main"]

 # Allows you to run this workflow manually from the Actions tab
 # 答应, 从库房的 Actions 选项卡手动运转当时作业流
  workflow_dispatch:

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
# 作业流由一个或多个作业组成,这些作业能够次序运转,也能够并行运转
jobs:
  build:
  # 作业运转的体系环境(运转时环境)
   runs-on: ubuntu-latest

  # Steps represent a sequence of tasks that will be executed as part of the job
  # 过程,表示完结该作业的一些列原子操作/过程
   steps:
   # 切到库房的workspace(根目录)
    - name: Checkout repository
     uses: actions/checkout@v3

   # 装备Git用户
    - name: Configure Git
     env:
      GIT_USERNAME: ${{ secrets.NAME }}
      GIT_EMAIL: ${{ secrets.EMAIL }}
     run: |
      git config --global user.name "${GIT_USERNAME}"
      git config --global user.email "${GIT_EMAIL}"

   # 查看是否需求更新版别
    - name: Check if version update is needed
     id: version-check
     run: |
      # 获取最近的提交信息
      latest_commit_message=$(git log --pretty=format:%s -1)

      # 查看提交信息是否包含 [AutoUpdateVersion],首要用于防止产生使命死循环
      # 如果最新提交时更新版别号,则无需再触发使命,直接退出
      if [[ $latest_commit_message == *"[AutoUpdateVersion]"* ]]; then
       echo "Skip version update as it was triggered by an automated commit"
       exit 78
      else
       echo "Version update is needed"
      fi

   # 更新版别号并提交
    - name: Update version and commit changes
     if: steps.version-check.outcome == 'success'
     run: |
      # 执行更新版别号
      node updateVersion.js

   # 同步提交
    - name: Push changes to main branch
     if: steps.version-check.outcome == 'success'
    # 引用第三方使命以完结push操作
     uses: ad-m/github-push-action@master
     with:
      branch: main
      github_token: ${{ secrets.GITHUB_TOKEN }}

4. 装备环境变量

GITHUB_TOKEN

作业流中咱们运用secrets.GITHUB_TOKEN 环境变量,它用于作业流权限操控,每个库房都默许存在。

因为咱们在作业流中修改了package.json文件,而且运用第三方使命(ad-m/github-push-action@master)来执行 push 操作。所以需求给作业流以 写入权限

默许情况下选中的是只读权限,因而,咱们需求勾选读和写的权限,以答应 push 操作

从0-1带你部署Github Actions自动化任务

自定义环境变量NAMEEMAIL

当时库房的自定义环境变量,能够经过 Actions -> Secrets and Variables 进行装备,之后就能够在作业流中进行运用了;

值得一提的是:添加自定义环境变量是保证信息安全的常规操作,当咱们要执行一个主动化使命时,如果需求在代码中传入灵敏信息,比如用户名暗码之类,一般主张选择运用环境变量的方法,以保证灵敏信息不回暴露在库房源码中。

从0-1带你部署Github Actions自动化任务

最终

完结以上所有内容之后,就能够提交这些文件修改了。

当你看到版别号更新的commit时,那么恭喜你完结了一个主动化使命^_^

从0-1带你部署Github Actions自动化任务