Github

티스토리 글 작성과 Commit 연동하기 (GithubAction)

orange_mj 2025. 2. 10. 03:38

오늘은 티스토리 글 작성을 깃허브 커밋으로 연동되도록 해보려고 합니다!
평소에 게시물을 많이 작성해보려는 것과 더불어, 깃헙 커밋과 연동된다면 더욱 신나서 글을 작성할 것 같아서 예전부터 생각해왔는데요
프로젝트가 성공적으로 끝났기 때문에 ,, 이젠 더이상 미루지 말자 ! 의미로 당장 시작해보려고 합니다 ㅎㅎ 

 

 

 

Tistory RSS 설정

티스토리 > 관리  를 들어간다.

관리 탭 > 블로그 를 누르면,

이렇게 설정을 해준 후, 
{자신의 tistory URL}/rss 로 접속해서 확인했을 때 잘 나오는지 확인한다.
내 tistory 의 경우 다음과 같이 접속이 가능하다. 
-> 

 

GITHUB Action 세팅

나는 깃헙 리드미에 최신 글 3개를 보여줄 수 있도록 연동해보려고 한다. 

1. 내 README.md 가 들어있는 레포를 클론 받는다.

다음과 같이 레포 url 을 복사해서, webStorm 의 버전 복사를 진행한다. (vsCode 의 경우 방법이 다르니, 참고해주세요!)

2. rss-parser 를 위한 npm 설치를 진행한다.

npm init -y
npm i rss-parser

npm init -y
npm i rss-parser

node_modules 가 생기는게 좀 맘에 안 들긴 했지만,,

3. package.json 을 수정한다.

{ ...
"main": "index.js",
  "type": "module", // X
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start" : "node readmeUpdate.js" // X
  },
...
}

주석으로 X 써있는 곳이 수정한 곳이다.

 

4. readmeUpdate.js 를 생성한 후, 코드를 작성한다.

import { readFileSync, writeFileSync } from "node:fs";
import Parser from "rss-parser";

// README.md 파일 읽기
const readmePath = "README.md";
let readmeContent = readFileSync(readmePath, "utf8");

// RSS 파서 생성
const parser = new Parser({
  headers: {
    Accept: "application/rss+xml, application/xml, text/xml; q=0.1",
  },
});

// 최신 블로그 포스트 추가
(async () => {
  // RSS 피드 가져오기
  const feed = await parser.parseURL("https://orange-mj.tistory.com/rss");

  // 최신 3개의 글의 제목과 링크를 추가할 텍스트 생성
  let latestPosts = "### 🌱 Blog Posting\n\n";
  for (let i = 0; i < 3 && i < feed.items.length; i++) {
    const { title, link } = feed.items[i];
    latestPosts += `- [${title}](${link})\n`;
  }

  // 기존 README.md에 최신 블로그 포스트 추가
  const newReadmeContent = readmeContent.includes("### 🌱 Blog Posting")
    ? readmeContent.replace(
      /### 🌱 Blog Posting[\s\S]*?(?=\n\n## |\n$)/,
      latestPosts
    )
    : readmeContent + latestPosts;

  if (newReadmeContent !== readmeContent) {
    writeFileSync(readmePath, newReadmeContent, "utf8");
    console.log("README.md 업데이트 완료");
  } else {
    console.log("새로운 블로그 포스트가 없습니다. README.md 파일이 업데이트되지 않았습니다.");
  }
})();

참고 ) https://dawonny.tistory.com/468

 

5. Github Action Permission 설정

해당 워크플로우를 실행할 레포의 settings 에 들어간다.

Code and automtion > Actions > General 에서, 

 

다음과 같이 수정한다. 

 

 

 

Github Action 세팅

다음과 같이 깃헙 폴더를 만들고, workflows 폴더를 만든다.

update-readme.yml 파일을 만들고, 다음과 같은 코드를 작성했다.

name: Update README

on:
  schedule:
    - cron: "0 */1 * * *" # 매 시간 정각에 실행
  push:
    branches:
      - main

jobs:
  update-readme:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: "16"

      - name: Install dependencies
        run: npm ci

      - name: Run update script
        run: npm start

      - name: Commit README
        run: |
          git config --local user.name 'your-name' # 수정
          git config --local user.email 'your-email' # 수정
          if [ -n "$(git status --porcelain)" ]; then
            git add README.md
            git commit -m 'Update README with latest blog posts'
            git push
          else
            echo "No changes to commit"
          fi
        env:
          github_token: ${{ secrets.GITHUB_TOKEN }}

 

 

 

잊지말고 .gitIgnore 만들어서 넣어준다.

 

자 이렇게 하고, git push 를 하면 !!!!

다음과 같이 나의 리드미에 올라오는 것을 확인할 수 있다 !!