# Демо: Git workflow на GitHub Покрокова інструкція до демо на засіданні гуртка «DevOps/DevSecOps Practices». Сценарій той самий, що й для Azure DevOps: захищений `main` через ruleset, гілка, Conventional Commits, PR зі шаблоном, автоматичний рецензент через CODEOWNERS, squash merge, конфлікт злиття та його розв'язання через rebase. - Обліковий запис: `mykolaichuk` - Репозиторій: `git-demo` (новий, **публічний**) - Тривалість показу: ≈ 15 хв (після демо в Azure DevOps — швидше, акцент на відмінностях) ## Що знадобиться | Що | Навіщо | | --- | --- | | Git 2.40+ і Git Credential Manager або GitHub CLI (`gh auth login`, далі `gh auth setup-git`) | Клонування по HTTPS без паролів | | Другий обліковий запис GitHub — **рецензент** (тестовий або студент) | Автор не може схвалити власний PR | | Другий браузер або приватне вікно з входом рецензентом | Перемикання між ролями | | Тека `starter-github/` з цього комплекту | README, `.gitignore`, шаблон PR, CODEOWNERS | > Rulesets на GitHub Free доступні лише в **публічних** репозиторіях; для приватних потрібен GitHub Pro, Team або Enterprise. Тому `git-demo` створюється публічним. ## 0. Підготовка (до засідання, ≈ 10 хв) ### 0.1. Налаштування Git і приватність пошти Коміти публічного репозиторію показують email автора. Для GitHub варто використовувати адресу `noreply`: **Settings** → **Emails** → **Keep my email addresses private** — там вказана адреса вигляду `ID+mykolaichuk@users.noreply.github.com`. Усі налаштування Git задаються **лише для цього репозиторію** (без `--global`), щоб не змінювати інші репозиторії на комп'ютері. Тому команди `git config` виконуються після клонування — у кроці 0.4. ### 0.2. Створення репозиторію 1. **New repository** → Owner `mykolaichuk`, name `git-demo`, **Public**. 2. **Add a README** — увімкнено; `.gitignore` і License — None. 3. **Create repository**. ### 0.3. Налаштування репозиторію **Settings** → **Collaborators** → **Add people** → обліковий запис рецензента (він приймає запрошення з пошти або з github.com/notifications). Code owner мусить мати доступ на запис — роль collaborator його дає. **Settings** → **General** → **Pull Requests**: - **Allow merge commits** — вимкнено; - **Allow squash merging** — увімкнено, Default commit message: **Pull request title**; - **Allow rebase merging** — вимкнено; - **Automatically delete head branches** — увімкнено. ### 0.4. Клонування і стартовий коміт ```bash git clone https://github.com/mykolaichuk/git-demo.git cd git-demo git config user.name "Vadym Mykolaichuk" git config user.email "ID+mykolaichuk@users.noreply.github.com" git config pull.rebase true git config core.autocrlf input # Windows: true cp -r ../starter-github/. . ``` У `.github/CODEOWNERS` замінити `@REVIEWER` на логін рецензента (наприклад, `@student-login`). Далі: ```bash git add . git commit -m "chore: add starter files" git push ``` Стартовий коміт — останній, що потрапляє в `main` напряму. ## 1. Захист `main` через ruleset (≈ 3 хв на засіданні) **Settings** → **Rules** → **Rulesets** → **New ruleset** → **New branch ruleset**. | Поле / правило | Значення | Навіщо | | --- | --- | --- | | Ruleset name | `protect-main` | | | Enforcement status | **Active** | Evaluate лише показує, що було б заблоковано | | Bypass list | **порожній** | Навіть власник репозиторію проходить через PR | | Target branches | **Add target** → **Include default branch** | Правила діють для `main` | | Restrict deletions | увімкнено | `main` не видалити | | Require linear history | увімкнено | Жодних merge-комітів у `main` | | Require a pull request before merging | увімкнено | Зміни — лише через PR | | — Required approvals | **1** | | | — Dismiss stale pull request approvals when new commits are pushed | увімкнено | Новий коміт — нове схвалення | | — Require review from Code Owners | увімкнено | Схвалити має власник з CODEOWNERS | | — Require approval of the most recent reviewable push | увімкнено | Останній, хто пушив, не схвалює сам | | — Require conversation resolution before merging | увімкнено | Усі коментарі розв'язані | | — Allowed merge methods | лише **Squash** | Один PR = один коміт | | Block force pushes | увімкнено | Історію `main` не переписати | **Create**. | Azure DevOps | GitHub | | --- | --- | | Require a minimum number of reviewers | Required approvals | | Prohibit the most recent pusher from approving | Require approval of the most recent reviewable push | | Reset all approval votes | Dismiss stale pull request approvals | | Check for comment resolution | Require conversation resolution | | Limit merge types | Allowed merge methods | | Automatically included reviewers | CODEOWNERS + Require review from Code Owners | | Build validation | Require status checks to pass | ## 2. Перевірка: прямий push відхилено (≈ 1 хв) ```bash echo "" >> README.md git commit -am "test: direct push to main" git push ``` Очікуваний результат (скорочено): ```text remote: error: GH013: Repository rule violations found for refs/heads/main. remote: - Changes must be made through a pull request. ! [remote rejected] main -> main (push declined due to repository rule violations) ``` ```bash git reset --hard origin/main ``` ## 3. Гілка → коміт → push (≈ 2 хв) ```bash git switch -c docs/run-instructions ``` У `README.md` розділ «Як запустити» замінюється на: ```markdown ## Як запустити 1. Клонувати репозиторій. 2. Відкрити README.md. ``` ```bash git add README.md git commit -m "docs: add run instructions" git push -u origin HEAD ``` ## 4. Pull request і рев'ю (≈ 5 хв) ### Автор 1. Банер **Compare & pull request** (або **Pull requests** → **New pull request**), base `main` ← compare `docs/run-instructions`. 2. Title: `docs: add run instructions`; опис заповнений шаблоном. 3. Рецензент доданий автоматично з CODEOWNERS. **Create pull request**. 4. Внизу PR — блок стану: «Review required», «Merging is blocked». ### Рецензент 1. **Files changed** → **+** біля рядка `1. Клонувати репозиторій.` → «Додай команду `git clone` з URL» → **Start a review**. 2. **Finish your review** → **Request changes** → **Submit review**. ### Автор ```bash # у README.md рядок 1 стає: 1. Клонувати репозиторій: `git clone `. git commit -am "docs: add clone command" git push ``` Відповісти в розмові і натиснути **Resolve conversation**. ### Рецензент **Review changes** → **Approve** → **Submit review**. ### Автор: завершення **Squash and merge** — заголовок коміту вже взято з назви PR: `docs: add run instructions (#1)`. **Confirm squash and merge**. Гілка видаляється автоматично. ```bash git switch main git pull git log --oneline -3 ``` ## 5. Конфлікт злиття (≈ 4 хв) ```bash git switch main && git pull git switch -c docs/status-in-progress # README.md: Статус: у розробці git commit -am "docs: set status to in progress" git push -u origin HEAD git switch main git switch -c docs/status-mvp # README.md: Статус: MVP git commit -am "docs: set status to MVP" git push -u origin HEAD ``` 1. Два PR; рецензент схвалює обидва. 2. Squash and merge першого PR. 3. Другий PR показує **This branch has conflicts that must be resolved**. GitHub пропонує кнопку **Resolve conflicts** у вебредакторі — для простих конфліктів це працює, але на засіданні показується локальний шлях, бо він однаковий для будь-якої платформи: ```bash git switch docs/status-mvp git fetch origin git rebase origin/main # CONFLICT (content): Merge conflict in README.md ``` Лишити `Статус: MVP`, прибрати маркери `<<<<<<<`, `=======`, `>>>>>>>`: ```bash git add README.md git rebase --continue git push --force-with-lease ``` Force push до гілки `docs/status-mvp` дозволений: ruleset блокує його лише для `main`. Схвалення скинулося (Dismiss stale approvals) — рецензент схвалює повторно, автор робить squash and merge. ## 6. Прибирання (≈ 1 хв) ```bash git switch main git pull git fetch --prune git branch -D docs/run-instructions docs/status-in-progress docs/status-mvp ``` Віддалені гілки вже видалені налаштуванням **Automatically delete head branches**; `--prune` прибирає їхні локальні копії `origin/...`. ## Повторити демо з нуля **Settings** → **General** → **Danger Zone** → **Delete this repository**, далі — розділ 0.2. ## Типові проблеми | Симптом | Причина і рішення | | --- | --- | | Ruleset не з'являється або не діє | Репозиторій приватний на GitHub Free — зробити публічним | | Push у `main` пройшов | Ruleset у стані Evaluate або обліковий запис у Bypass list | | Рецензент не додається автоматично | Помилка в логіні в CODEOWNERS (перевірити вкладку файлу на GitHub) або рецензент ще не прийняв запрошення | | Approve рецензента не враховано | Після схвалення був новий push (Dismiss stale approvals) | | `remote: Permission to ... denied` | Немає входу: `gh auth login` і `gh auth setup-git` або налаштувати GCM | ## Джерела - [Available rules for rulesets](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets) - [About code owners](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners) - [Creating a pull request template](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/creating-a-pull-request-template-for-your-repository) - [Conventional Commits 1.0.0](https://www.conventionalcommits.org/)