Recent Posts
Recent Comments
Link
Today
Total
05-20 06:06
관리 메뉴

채린씨의 티스토리

[GitHub] 레포지토리의 파일 수 README.md에 자동 업데이트 본문

Git

[GitHub] 레포지토리의 파일 수 README.md에 자동 업데이트

채린씨 2022. 3. 31. 01:11

요즘 코딩테스트 대비 알고리즘 스터디를 하고 있는데, 스터디장님께서 이슈를 공유해주셨다.

혹시 몰라서 모자이크 처리했습니다..

 

터미널에서 각 폴더의 파일 수를 확인하는 방법을 제안하긴 했으나..

 

매번 수정사항이 있을 때마다 로컬 저장소에 업데이트 한 뒤 확인해야 하고, 직접 README 파일을 수정해야 한다는 단점이 있었다.. 아주 번거로운 과정은 아니지만, 자동화를 해야겠다는 욕심이 생겼다! 그래서 '깃허브 README 자동 업데이트'에 대해 구글링을 해봤더니 좋은 블로그 글이 있었다!

 

https://somjang.tistory.com/entry/GitHub-github-actions%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%98%EC%97%AC-push-%ED%95%A0-%EB%95%8C-%EB%A7%88%EB%8B%A4-READMEmd-%EC%97%85%EB%8D%B0%EC%9D%B4%ED%8A%B8-%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95-feat-%EC%BD%94%EB%94%A9-1%EC%9D%BC-1%EB%AC%B8%EC%A0%9C

 

[GitHub] github actions를 활용하여 push 할 때 마다 README.md 업데이트 하는 방법! ( feat. 코딩 1일 1문제! )

2020년 2월 부터 현재까지 매일 하루에 최소 코딩 문제 1개씩은 꼭 풀자라는 취지로 시작한 코딩 1일 1문제! GitHub - SOMJANG/CODINGTEST_PRACTICE: 1일 1문제 since 2020.02.07 1일 1문제 since 2020.02.07. Co..

somjang.tistory.com

 

큰 틀은 이 블로그를 참고하되, 우리 레포지토리의 상황에 맞게 코드를 많이 수정했다. 테스트를 위해 임시 레포지토리를 만들었는데, 여기서 진행한 내용을 공유해보겠다!

 


1. 자동으로 업데이트되는 README를 적용할 레포지토리를 생성한다.

 

2. 해당 레포지토리에 utils 폴더를 만들고, 그 안에 count_files.py 파일을 생성한다.

from collections import Counter
from datetime import datetime
import os


def count_files():
    files_info = []
    total_file_count = 0
    directory_list = [directory for directory in os.listdir("./") if "Folder" in directory]
    for directory in directory_list:
        file_list = os.listdir(f"./{directory}")
        file_count = len(file_list)
        temp = [directory, file_count]
        files_info.append(temp)
        total_file_count += file_count
    return files_info, total_file_count
  
  
def make_info(files_info, total_file_count):
    info = f"## Files Count In Folders\nTotal File Count: {total_file_count}\n"
    for directory_files_info in files_info:
        temp = f"- {directory_files_info[0]}: {directory_files_info[1]}\n"
        info += temp
    return info
    


def make_read_me(info):
    return f"""# Self-Updating-Readme
Push할 때마다 폴더 별 파일 수를 리드미에 자동으로 업데이트<br>
Automatically update the number of files per folder to Readme whenever you push.<br><br>
{info}
"""


def update_readme():
    files_info, total_file_count = count_files()
    info = make_info(files_info, total_file_count)
    readme = make_read_me(info)
    return readme


if __name__ == "__main__":
    readme = update_readme()
    with open("./README.md", 'w', encoding='utf-8') as f:
        f.write(readme)
  • count_files(): 이름에 "Folder"문자열을 포함하는 각 폴더의 파일 개수file_count에 저장한다. 각 폴더의 이름과 파일 개수를 이차원 배열 files_info에 저장한다. 이름에 "Folder"문자열을 포함하는 모든 폴더의 전체 파일 개수 total_file_count에 저장한다.
  • make_info(files_info, total_file_count):  count_files()에서 만들어진 files_info, total_file_count를 이용해 전체 파일 개수, 각 폴더의 이름과 파일 개수를 문자열 info를 저장한다.
  • make_read_me(info): make_info(files_info, total_file_count)에서 만들어진 info를 이용해 README에 보일 내용을 작성한다.

 

3. 레포지토리의 Actions 탭에서 Python application의 Configure 버튼을 눌러 python-app.yml 파일을 수정한다.

# This workflow will install Python dependencies, run tests and lint with a single version of Python
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions

name: Python application

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2
    - name: Set up Python 3.9
      uses: actions/setup-python@v2
      with:
        python-version: 3.9
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
    - name: Run Update Python Script 
      run: |
        python utils/count_files.py
    - name: Run Update README.md File
      run: |
        git add .
        git diff
        git config --local user.email "chaerin.dev@gmail.com"
        git config --local user.name "chaerin-dev"
        git commit -m "Automatically Update README.md file"
        git push
  • main branch에서 push나 pull request가 발생할 때 자동 업데이트가 수행되도록 했다.
  • user.email과 user.name 에는 자신의 이메일과 깃허브 유저네임을 적어주면 된다. 이 부분 때문에 내가 아닌 다른 사람이 push나 pull request를 할 때 어떻게 될지 모르겠다.. 이 부분은 나중에 수정하게 될 수도..? -> 문제 없음 확인 완료!

 

4. 폴더/파일을 추가하고 push나 pull request를 진행한다.

이때, 단순 커밋으로 폴더/파일을 추가하면 안 되고, push나 pull request를 해야 자동 업데이트가 수행된다! 나는 임시 branch를 만들어서 폴더/파일을 추가한 후 main branch에 pull request 했다. pull request 이후에 Action탭에 들어가 보면 자동 업데이트가 잘 진행되는지 실시간으로 확인할 수 있다. 오류가 생긴 경우 어떤 코드에서 오류가 발생했는지도 확인할 수 있다!

무수한 시행착오의 흔적..

 

5. README가 잘 업데이트되었는지 확인한다!

README에 전체 파일 수와 폴더별 파일 수가 잘 나타나는 것을 확인할 수 있다!

 

* 전체 코드와 파일 구조는 여기에서 확인!

https://github.com/chaerin-dev/Self-Updating-Readme

 

GitHub - chaerin-dev/Self-Updating-Readme: Push할 때마다 폴더 별 파일 수를 리드미에 자동으로 업데이트 (Au

Push할 때마다 폴더 별 파일 수를 리드미에 자동으로 업데이트 (Automatically update the number of files per folder to Readme whenever you push.) - GitHub - chaerin-dev/Self-Updating-Readme: Push할 때마다 폴더 별 파일 수를 리

github.com

 

+ .gitignore에 관련 폴더들을 추가할 경우 작동하지 않는다.

 


 

파이썬을 너무 오랜만에 접해서 기본적인 for문과 배열 메서드를 구글링 해가면서 문제를 해결했다.. 오늘은 이제 코딩테스트만 보면 하루가 끝날 것 같지만.. 그래도 뿌듯하다! 원하는 것을 코드로 얼마든지 구현할 수 있다는 게 코딩의 매력이 아닐까!!! ٩( ᐛ )و

 

 

 

Comments