{/ Эта страница автоматически активируется из файлов функций SKILL.md с помощью сайта/scripts/generate-skill-docs.py. Редактируйте исходный SKILL.md, а не эту страницу. /}

Управление репозиторием GitHub

Клонирование/создание/форк репозиториев; управление удаленными репозиториями, релизами.

Метаданные навыки

Источник Встроенный (установлен по умолчанию)
Путь skills/github/github-repo-management
Версия 1.1.0
Автор Агент Гермес
Лицензия Массачусетский технологический институт
Платформы Linux, MacOS, Windows
Теги GitHub, Репозитории, Git, Релизы, Секреты, Конфигурация
Связанные навыки github-auth, github-pr-workflow, github-issues

Справочник: полный SKILL.md:::информация

Ниже приведено полное описание навыка, который загружает Гермес при активации этого навыка. Это то, что агент видит в качестве инструкций, когда навыки активны.

Управление репозиториями GitHub

Создание, клонирование, форк, настройка и управление репозиториями GitHub. В каждом разделе показано сначала команда «gh», а затем альтернатива «git» + «curl».

Предварительные требования

Настройка

if command -v gh &>/dev/null && gh auth status &>/dev/null; then
  AUTH="gh"
else
  AUTH="git"
  if [ -z "$GITHUB_TOKEN" ]; then
    if [ -f ~/.hermes/.env ] && grep -q "^GITHUB_TOKEN=" ~/.hermes/.env; then
      GITHUB_TOKEN=$(grep "^GITHUB_TOKEN=" ~/.hermes/.env | head -1 | cut -d= -f2 | tr -d '\n\r')
    elif grep -q "github.com" ~/.git-credentials 2>/dev/null; then
      GITHUB_TOKEN=$(grep "github.com" ~/.git-credentials 2>/dev/null | head -1 | sed 's|https://[^:]*:\([^@]*\)@.*|\1|')
    fi
  fi
fi

# Получить имя пользователя GitHub (требуется для нескольких операций)
if [ "$AUTH" = "gh" ]; then
  GH_USER=$(gh api user --jq '.login')
else
  GH_USER=$(curl -s -H "Authorization: token $GITHUB_TOKEN" https://api.github.com/user | python3 -c "import sys,json; print(json.load(sys.stdin)['login'])")
fi

Если вы уже находитесь внутри репозитория:

REMOTE_URL=$(git remote get-url origin)
OWNER_REPO=$(echo "$REMOTE_URL" | sed -E 's|.*github\.com[:/]||; s|\.git$||')
OWNER=$(echo "$OWNER_REPO" | cut -d/ -f1)
REPO=$(echo "$OWNER_REPO" | cut -d/ -f2)

1. Клонирование репозиториев

Клонирование — чисто git – работает одинаково в любом случае:

# Клонирование через HTTPS (работает с credential helper или URL со встроенным токеном)
git clone https://github.com/owner/repo-name.git

# Клонирование в конкретную директорию
git clone https://github.com/owner/repo-name.git./my-local-dir

# Поверхностное клонирование (быстрее для больших репозиториев)
git clone --depth 1 https://github.com/owner/repo-name.git

# Клонирование конкретной ветки
git clone --branch develop https://github.com/owner/repo-name.git

# Клонирование через SSH (если SSH настроен)
git clone git@github.com:owner/repo-name.git

С помощью gh (сокращённая форма):

gh repo clone owner/repo-name
gh repo clone owner/repo-name -- --depth 1

2. Создание репозиториев

С помощью gh:

# Создать публичный репозиторий и клонировать его
gh repo create my-new-project --public --clone

# Приватный, с описанием и лицензией
gh repo create my-new-project --private --description "Полезный инструмент" --license MIT --clone

# В организации
gh repo create my-org/my-new-project --public --clone

# Из существующей локальной директории
cd /path/to/existing/project
gh repo create my-project --source. --public --push

С помощью git + curl:

# Создать удалённый репозиторий через API
curl -s -X POST \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/user/repos \
  -d '{
    "name": "my-new-project",
    "description": "Полезный инструмент",
    "private": false,
    "auto_init": true,
    "license_template": "mit"
  }'

# Клонировать его
git clone https://github.com/$GH_USER/my-new-project.git
cd my-new-project

# -- ИЛИ -- отправить существующий локальный проект в новый репозиторий
cd /path/to/existing/project
git init
git add.
git commit -m "Начальный коммит"
git remote add origin https://github.com/$GH_USER/my-new-project.git
git push -u origin main

Чтобы создать репозиторий в организации:

curl -s -X POST \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/orgs/my-org/repos \
  -d '{"name": "my-new-project", "private": false}'

Из шаблона

С помощью gh:

gh repo create my-new-app --template owner/template-repo --public --clone

С помощью Curl:

curl -s -X POST \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/owner/template-repo/generate \
  -d '{"owner": "'"$GH_USER"'", "name": "my-new-app", "private": false}'

3. Форк репозиториев

С помощью gh:

gh repo fork owner/repo-name --clone

С помощью git + curl:

# Создать форк через API
curl -s -X POST \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/owner/repo-name/forks

# Подождать немного, пока GitHub создаст форк, затем клонировать
sleep 3
git clone https://github.com/$GH_USER/repo-name.git
cd repo-name

# Добавить оригинальный репозиторий как удалённый "upstream"
git remote add upstream https://github.com/owner/repo-name.git

Синхронизация вилок

# Чистый git — работает везде
git fetch upstream
git checkout main
git merge upstream/main
git push origin main

С помощью gh (сокращение):

gh repo sync $GH_USER/repo-name

4. Информация о репозитории

С помощью gh:

gh repo view owner/repo-name
gh repo list --limit 20
gh search repos "machine learning" --language python --sort stars

С помощью Curl:

# Просмотр деталей репозитория
curl -s \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/$OWNER/$REPO \
  | python3 -c "
import sys, json
r = json.load(sys.stdin)
print(f\"Имя: {r['full_name']}\")
print(f\"Описание: {r['description']}\")
print(f\"Звёзды: {r['stargazers_count']}  Форки: {r['forks_count']}\")
print(f\"Ветка по умолчанию: {r['default_branch']}\")
print(f\"Язык: {r['language']}\")"

# Список ваших репозиториев
curl -s \
  -H "Authorization: token $GITHUB_TOKEN" \
  "https://api.github.com/user/repos?per_page=20&sort=updated" \
  | python3 -c "
import sys, json
for r in json.load(sys.stdin):
    vis = 'private' if r['private'] else 'public'
    print(f\"  {r['full_name']:40}  {vis:8}  {r.get('language', ''):10}  ★{r['stargazers_count']}\")"

# Поиск репозиториев
curl -s \
  "https://api.github.com/search/repositories?q=machine+learning+language:python&sort=stars&per_page=10" \
  | python3 -c "
import sys, json
for r in json.load(sys.stdin)['items']:
    print(f\"  {r['full_name']:40}  ★{r['stargazers_count']:6}  {r['description'][:60] if r['description'] else ''}\")"

5. Настройки репозитория

С помощью gh:

gh repo edit --description "Обновлённое описание" --visibility public
gh repo edit --enable-wiki=false --enable-issues=true
gh repo edit --default-branch main
gh repo edit --add-topic "machine-learning,python"
gh repo edit --enable-auto-merge

С помощью Curl:

curl -s -X PATCH \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/$OWNER/$REPO \
  -d '{
    "description": "Обновлённое описание",
    "has_wiki": false,
    "has_issues": true,
    "allow_auto_merge": true
  }'

# Обновление тем
curl -s -X PUT \
  -H "Authorization: token $GITHUB_TOKEN" \
  -H "Accept: application/vnd.github.mercy-preview+json" \
  https://api.github.com/repos/$OWNER/$REPO/topics \
  -d '{"names": ["machine-learning", "python", "automation"]}'

6. Защита веток

# Просмотр текущей защиты
curl -s \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/$OWNER/$REPO/branches/main/protection

# Настройка защиты ветки
curl -s -X PUT \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/$OWNER/$REPO/branches/main/protection \
  -d '{
    "required_status_checks": {
      "strict": true,
      "contexts": ["ci/test", "ci/lint"]
    },
    "enforce_admins": false,
    "required_pull_request_reviews": {
      "required_approving_review_count": 1
    },
    "restrictions": null
  }'

7. Управление секретами (GitHub Actions)

С помощью gh:

gh secret set API_KEY --body "ваше-секретное-значение"
gh secret set SSH_KEY < ~/.ssh/id_rsa
gh secret list
gh secret delete API_KEY

С помощью Curl:

Секреты требуют шифрования с открытым ключом репозитория — через API, это сложнее:

# Получить публичный ключ репозитория для шифрования секретов
curl -s \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/$OWNER/$REPO/actions/secrets/public-key

# Зашифровать и установить (требуется Python с PyNaCl)
python3 -c "
from base64 import b64encode
from nacl import encoding, public
import json, sys

# Получить публичный ключ
key_id = '<key_id_from_above>'
public_key = '<base64_key_from_above>'

# Зашифровать
sealed = public.SealedBox(
    public.PublicKey(public_key.encode('utf-8'), encoding.Base64Encoder)
).encrypt('ваше-секретное-значение'.encode('utf-8'))
print(json.dumps({
    'encrypted_value': b64encode(sealed).decode('utf-8'),
    'key_id': key_id
}))"

# Затем отправить зашифрованный секрет через PUT
curl -s -X PUT \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/$OWNER/$REPO/actions/secrets/API_KEY \
  -d '<вывод python скрипта выше>'

# Список секретов (только имена, значения скрыты)
curl -s \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/$OWNER/$REPO/actions/secrets \
  | python3 -c "
import sys, json
for s in json.load(sys.stdin)['secrets']:
    print(f\"  {s['name']:30}  обновлён: {s['updated_at']}\")"

Примечание: Для секретов gh secret set значительно проще. Если требуется установить секреты, а не ступеньку «gh», рекомендую установить «gh», хотя бы для этой операции.

8. Релизы

С помощью gh:

gh release create v1.0.0 --title "v1.0.0" --generate-notes
gh release create v2.0.0-rc1 --draft --prerelease --generate-notes
gh release create v1.0.0./dist/binary --title "v1.0.0" --notes "Заметки о релизе"
gh release list
gh release download v1.0.0 --dir./downloads

С помощью Curl:

# Создать релиз
curl -s -X POST \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/$OWNER/$REPO/releases \
  -d '{
    "tag_name": "v1.0.0",
    "name": "v1.0.0",
    "body": "## Список изменений\n- Функция A\n- Исправление ошибки B",
    "draft": false,
    "prerelease": false,
    "generate_release_notes": true
  }'

# Список релизов
curl -s \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/$OWNER/$REPO/releases \
  | python3 -c "
import sys, json
for r in json.load(sys.stdin):
    tag = r.get('tag_name', 'нет тега')
    print(f\"  {tag:15}  {r['name']:30}  {'черновик' if r['draft'] else 'опубликован'}\")"

# Загрузка ассета релиза (бинарного файла)
RELEASE_ID=<id_из_ответа_на_создание>
curl -s -X POST \
  -H "Authorization: token $GITHUB_TOKEN" \
  -H "Content-Type: application/octet-stream" \
  "https://uploads.github.com/repos/$OWNER/$REPO/releases/$RELEASE_ID/assets?name=binary-amd64" \
  --data-binary @./dist/binary-amd64

9. Рабочие процессы GitHub

С помощью gh:

gh workflow list
gh run list --limit 10
gh run view <RUN_ID>
gh run view <RUN_ID> --log-failed
gh run rerun <RUN_ID>
gh run rerun <RUN_ID> --failed
gh workflow run ci.yml --ref main
gh workflow run deploy.yml -f environment=staging

С помощью Curl:

# Список workflows
curl -s \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/$OWNER/$REPO/actions/workflows \
  | python3 -c "
import sys, json
for w in json.load(sys.stdin)['workflows']:
    print(f\"  {w['id']:10}  {w['name']:30}  {w['state']}\")"

# Список последних запусков
curl -s \
  -H "Authorization: token $GITHUB_TOKEN" \
  "https://api.github.com/repos/$OWNER/$REPO/actions/runs?per_page=10" \
  | python3 -c "
import sys, json
for r in json.load(sys.stdin)['workflow_runs']:
    print(f\"  Запуск {r['id']}  {r['name']:30}  {r['conclusion'] or r['status']}\")"

# Скачать логи неудачного запуска
RUN_ID=<run_id>
curl -s -L \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/$OWNER/$REPO/actions/runs/$RUN_ID/logs \
  -o /tmp/ci-logs.zip
cd /tmp && unzip -o ci-logs.zip -d ci-logs

# Повторно запустить неудачный workflow
curl -s -X POST \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/$OWNER/$REPO/actions/runs/$RUN_ID/rerun

# Повторно запустить только неудачные задания
curl -s -X POST \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/$OWNER/$REPO/actions/runs/$RUN_ID/rerun-failed-jobs

# Запустить workflow вручную (workflow_dispatch)
WORKFLOW_ID=<workflow_id_or_filename>
curl -s -X POST \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/$OWNER/$REPO/actions/workflows/$WORKFLOW_ID/dispatches \
  -d '{"ref": "main", "inputs": {"environment": "staging"}}'

10. Суть

С помощью gh:

gh gist create script.py --public --desc "Полезный скрипт"
gh gist list

С помощью Curl:

# Создать gist
curl -s -X POST \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/gists \
  -d '{
    "description": "Полезный скрипт",
    "public": true,
    "files": {
      "script.py": {"content": "print(\"hello\")"}
    }
  }'

# Список ваших gist
curl -s \
  -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/gists \
  | python3 -c "
import sys, json
for g in json.load(sys.stdin):
    files = ', '.join(g['files'].keys())
    print(f\"  {g['id']}  {g['description'] or '(без описания)':40}  {files}\")"

Краткая справочная таблица

Действие хх git + локон
Клонировать gh repo clone o/r git clone https://github.com/o/r.git
Создать репозиторий gh repo создать имя --public curl POST /user/repos
Форк gh repo fork o/r --clone curl POST /repos/o/r/forks + git clone
Информация о репозиториях gh просмотр репозитория o/r curl GET /repos/o/r
Редактировать настройки gh репо-секретарь --... curl PATCH /repos/o/r
Создать релиз gh релиз создать v1.0 curl POST /repos/o/r/releases
Список рабочих процессов список технологических процессов curl GET /repos/o/r/actions/workflows
Перезапустить CI gh активирует идентификатор повторного запуска curl POST /repos/o/r/actions/runs/ID/rerun
Установить секрет gh секретный набор KEY curl PUT /repos/o/r/actions/secrets/KEY (+ шифрование)