newsmode
search
Меню
arrow_back Назад

How to Update a GitHub Profile README Automatically

auto_awesomeКраткое саммари

Юджин Ян рассказывает, как настроить автоматическое обновление GitHub-профиля (README) свежими публикациями со своего сайта. Идею он позаимствовал у Simon Willison, который показал, как сделать это с помощью GitHub Actions. Процесс состоит из трёх шагов: получение последних записей из Atom-фида сайта с помощью библиотеки feedparser на Python, обновление секции «Recent Writing» в README через поиск и замену текста между маркерами-комментариями, и настройка GitHub Actions для запуска при каждом push и ежедневно в полночь по cron. Пара часов работы избавляет от ручного обновления README при каждом новом посте.

How to Update a GitHub Profile README Automatically

Как автоматически обновлять README GitHub-профиля

[ engineering python til ] · 3 min read

[ engineering python til ] · 3 мин чтения

Today I learnt how to set up my GitHub profile README to automatically update with the latest writing from this site. It’s now set to run every day at midnight.

Сегодня я узнал, как настроить README моего GitHub-профиля так, чтобы он автоматически обновлялся свежими публикациями с этого сайта. Теперь он запускается каждый день в полночь.

It’s nothing too complex. Simon Willison shared how to do this with GitHub Actions and it seemed like a fun afternoon project (and it was). And I thought an hour or two of work would save hours of future manual updates.

Ничего сложного. Simon Willison рассказал, как сделать это с помощью GitHub Actions, и это показалось забавным проектом на пару часов (так оно и было). Я подумал, что час-два работы сэкономят мне часы будущих ручных обновлений.

First, Pull From Your Site’s Feed

Сначала забираем данные из фида вашего сайта

This site is set up with an Atom feed that RSS readers (e.g., Feedly) can aggregate with. Getting the latest writing with Python’s feedparser is simple. Based on how your dates are formatted, you might need to update the regular expression.

Этот сайт настроен с Atom-фидом, который могут агрегировать RSS-ридеры (например, Feedly). Получить последние публикации с помощью Python-библиотеки feedparser просто. В зависимости от того, как отформатированы ваши даты, вам, возможно, придётся подправить регулярное выражение.

import feedparser def fetch_writing(): entries = feedparser.parse('https://eugeneyan.com/feed')['entries'][:5] return [ { 'title': entry['title'], 'url': entry['link'].split('#')[0], 'published': re.findall(r'(.*?)\s00:00', entry['published'])[0] } for entry in entries ]

import feedparser def fetch_writing(): entries = feedparser.parse('https://eugeneyan.com/feed')['entries'][:5] return [ { 'title': entry['title'], 'url': entry['link'].split('#')[0], 'published': re.findall(r'(.*?)\s00:00', entry['published'])[0] } for entry in entries ]

Next, Update The README Sections

Затем обновляем секции README

My README has a section for “📝 Recent Writing” which I update with the results from fetch_writing(). This is done by searching for comment blocks for “writing” (e.g., <!-- writing starts -->) and replacing everything between them.

В моём README есть секция «📝 Recent Writing», которую я обновляю результатами из fetch_writing(). Это делается путём поиска блоков-комментариев для «writing» (например, ) и замены всего, что находится между ними.

import re def replace_chunk(content, marker, chunk, inline=False): r = re.compile( r'<!\-\- {} starts \-\->.*<!\-\- {} ends \-\->'.format(marker, marker), re.DOTALL, ) if not inline: chunk = '\n{}\n'.format(chunk) chunk = '<!-- {} starts -->{}<!-- {} ends -->'.format(marker, chunk, marker) return r.sub(chunk, content)

import re def replace_chunk(content, marker, chunk, inline=False): r = re.compile( r'.*'.format(marker, marker), re.DOTALL, ) if not inline: chunk = '\n{}\n'.format(chunk) chunk = '{}'.format(marker, chunk, marker) return r.sub(chunk, content)

So far, running both methods will update the README file.

На данный момент запуск обоих методов обновит файл README.

Finally, Set Up GitHub Actions

Наконец, настраиваем GitHub Actions

We’ll want to set up GitHub Actions to run this workflow automatically. Currently, it runs with each push and at midnight daily. There’s also the ability for one-click build (which is pretty cool).

Нам нужно настроить GitHub Actions, чтобы этот воркфлоу запускался автоматически. Сейчас он выполняется при каждом push и ежедневно в полночь. Есть также возможность сборки в один клик (что довольно круто).

name: Build README on: push: workflow_dispatch: schedule: - cron: '0 0 * * *' jobs: build: runs-on: ubuntu-latest steps: - name: Check out repo uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.8 architecture: x64 - name: Install dependencies run: python -m pip install -r requirements.txt - name: Update README run: |- python build_readme.py cat README.md - name: Commit and push if changed run: |- git diff git config --global user.email "[email protected]" git config --global user.name "README-bot" git add -A git commit -m "Updated content" || exit 0 git push

name: Build README on: push: workflow_dispatch: schedule: - cron: '0 0 * * *' jobs: build: runs-on: ubuntu-latest steps: - name: Check out repo uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.8 architecture: x64 - name: Install dependencies run: python -m pip install -r requirements.txt - name: Update README run: |- python build_readme.py cat README.md - name: Commit and push if changed run: |- git diff git config --global user.email "[email protected]" git config --global user.name "README-bot" git add -A git commit -m "Updated content" || exit 0 git push

Chill and Let Automation Take Over

Расслабьтесь и позвольте автоматизации делать своё дело

Now that it’s set up, no more manual updating of the README with each new post. Here’s how it looks like now, without this current post.

Теперь, когда всё настроено, больше не нужно вручную обновлять README с каждым новым постом. Вот как это выглядит сейчас, без этого текущего поста.

My profile now; if it's the same when you visit it, my effort in this post failed.

Мой профиль сейчас; если он останется таким же, когда вы зайдёте на него, значит, мои усилия в этом посте провалились.

By the time you visit my GitHub profile, the “📝 Recent Writing” section will be updated to include this post, or (if you’re visiting it more than a month from now) be updated with a new set of recent posts.

К тому моменту, когда вы зайдёте на мой GitHub-профиль, секция «📝 Recent Writing» будет обновлена и будет включать этот пост, или (если вы посетите её больше чем через месяц) будет обновлена новым набором недавних постов.

If you found this useful, please cite this write-up as:

Если этот материал оказался полезным, пожалуйста, ссылайтесь на него так:

Yan, Ziyou. (Jul 2020). How to Update a GitHub Profile README Automatically. eugeneyan.com. https://eugeneyan.com/writing/how-to-update-github-profile-readme-automatically/.

Yan, Ziyou. (Jul 2020). How to Update a GitHub Profile README Automatically. eugeneyan.com. https://eugeneyan.com/writing/how-to-update-github-profile-readme-automatically/.

or

или

@article{yan2020github, title = {How to Update a GitHub Profile README Automatically}, author = {Yan, Ziyou}, journal = {eugeneyan.com}, year = {2020}, month = {Jul}, url = {https://eugeneyan.com/writing/how-to-update-github-profile-readme-automatically/} }

@article{yan2020github, title = {How to Update a GitHub Profile README Automatically}, author = {Yan, Ziyou}, journal = {eugeneyan.com}, year = {2020}, month = {Jul}, url = {https://eugeneyan.com/writing/how-to-update-github-profile-readme-automatically/} }



Join 11,800+ readers getting updates on machine learning, RecSys, LLMs, and engineering.

Присоединяйтесь к 11 800+ читателям, получающим обновления о машинном обучении, RecSys, LLM и инженерии.