likes
comments
collection
share

2023-04-24 如何使用 GitHub Action 自动更新 README 文件

作者站长头像
站长
· 阅读数 6

温馨提示:本文使用 ChatGPT 润色

参考链接:

GitHub Actions 文档:docs.github.com/zh/actions

管理个人资料自述文件:docs.github.com/zh/account-…

草梅友仁的自述文件:github.com/CaoMeiYouRe…

前言

近期我想要优化自己的自述文件,计划将最新博客自动同步至 GitHub 的 README 文件中。在经过一番研究之后,我发现可以使用 GitHub Actions 来实现这个功能,特此记录。

正文

基础介绍

在此之前,需要先了解下什么是个人资料自述文件、[GitHub Actions](GitHub Actions),对此不太了解的可点击参考链接了解详细内容。

个人资料自述文件

2023-04-24 如何使用 GitHub Action 自动更新 README 文件

GitHub Action

2023-04-24 如何使用 GitHub Action 自动更新 README 文件

目的和好处

使用个人资料自述文件的目的是为了让访问你的 GitHub 主页的人快速了解你的相关信息,这有利于他们关注你。

而使用 GitHub Actions 则是为了借助 GitHub 提供的免费 CI/CD 能力,自动同步博客或其他内容,从而减少工作量。

详细步骤

使用 GitHub Action 可以更新任意仓库的 README 文件,在此以个人资料自述文件的仓库为例。

  1. 新建一个和 GitHub 用户名同名的公共仓库,并且添加一个 README.md

  2. 在 README.md 合适的位置添加占位符,例如<!-- BLOG_START --><!-- BLOG_END -->。HTML 注释在 markdown 文件中不会展示出来,所以可以用于占位符,告知要替换内容的位置。

    2023-04-24 如何使用 GitHub Action 自动更新 README 文件

  3. 编写代码,获取博客链接,生成内容,写入到 README.md 中

    'use strict';
    
    var fs = require('fs-extra');
    var Parser = require('rss-parser');
    
    const rssParser = new Parser();
    async function start() {
        const blogResp = await rssParser.parseURL('https://blog.cmyr.ltd/atom.xml');
        if (Date.now() - new Date(blogResp.lastBuildDate).getTime() > 48 * 60 * 60 * 1000) {
            console.log('最近48小时内没有博客更新,跳过本次更新');
            return;
        }
        const items = [...blogResp.items.slice(0, 5)];
        const text = items.map((e) => `- [${e.title}](${e.link})`).join('\n');
        const readme = await fs.readFile('README.md', 'utf-8');
        const newReadme = readme.replace(/<!-- BLOG_START -->([\s\S]*?)<!-- BLOG_END -->/, `<!-- BLOG_START -->\n${text}\n<!-- BLOG_END -->`);
        await fs.writeFile('README.md', newReadme);
        console.log('更新博客链接成功');
    }
    start();
    
    
    

    以上是一个简单的 Node.JS 例子,用 Python 等语言同理

  4. 添加 GitHub Action,设置好定时任务,自动执行更新。

# .github\workflows\blog.yml
name: Blog
on:
  workflow_dispatch:
  schedule:
    - cron: "0 20 * * *" # 注意,GitHub Action的时区为UTC+0,与北京时间(UTC+8)存在时差,所以需要换算下时间。
jobs:
  blog:
    name: Blog
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          persist-credentials: false # otherwise, the token used is the GITHUB_TOKEN, instead of your personal access token.
          fetch-depth: 0 # otherwise, there would be errors pushing refs to the destination repository.
      - name: Setup Node.js environment
        uses: actions/setup-node@v3
        with:
          node-version: "16"
      - name: Get yarn cache directory path
        id: yarn-cache-dir-path
        run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT
      - uses: actions/cache@v3
        id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
        with:
          path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
          key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
          restore-keys: ${{ runner.os }}-yarn-
      - run: yarn
      - run: npm run start
      - name: Commit files 
        id: commit-files
        run: |
          if [ -n "$(git status --porcelain README.md)" ]; then
            git config --local user.email "github-actions[bot]@users.noreply.github.com"
            git config --local user.name "github-actions[bot]"
            git add README.md
            git commit -m "docs: update blog"
            echo "hasChange=true" >> $GITHUB_OUTPUT
          else
            echo "No changes detected"
          fi
      - name: Push changes
        uses: ad-m/github-push-action@master
        if: ${{ steps.commit-files.outputs.hasChange == 'true' }}
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          branch: ${{ github.ref }}

请注意 Commit files 部分,这里只指定了在更新 README.md 文件时才会进行 commit,否则不会 commit。而在 Push changes 部分,只有在 hasChange 的情况下才会执行,避免了在没有更新时提交 commit 导致出错的问题。

总结

本文介绍了如何使用 GitHub Action 自动更新 README 文件。GitHub Action 是 GitHub 提供的免费 CI/CD 能力,可以帮助自动同步博客或其他内容,从而减少工作量。使用个人资料自述文件的目的是为了让访问你的 GitHub 主页的人快速了解你的相关信息,这有利于他们关注你。使用 GitHub Action 可以更新任意仓库的 README 文件。具体步骤包括新建一个和 GitHub 用户名同名的公共仓库,添加一个 README.md 文件并在适当的位置添加占位符,然后编写代码,获取博客链接,生成内容,写入到 README.md 中,最后添加 GitHub Action,设置好定时任务,自动执行更新。

【总结由 ChatGPT 生成】

本文作者:草梅友仁 本文地址:blog.cmyr.ltd/archives/bd… 版权声明:转载请注明出处!

转载自:https://juejin.cn/post/7225569023828574263
评论
请登录