Skip to main content

Создание примера рабочего процесса

Узнайте, как создать базовый рабочий процесс, который активируется событием push-отправки.

Введение

В этом руководстве показано, как создать базовый рабочий процесс, который активируется при отправке кода в репозиторий.

Чтобы приступить к работе с предварительно настроенными рабочими процессами, просмотрите список шаблонов в репозитории actions/starter-workflows в репозитории ваш экземпляр GitHub Enterprise Server. Дополнительные сведения см. в разделе Использование шаблонов рабочих процессов.

Создание примера рабочего процесса

Для определения рабочего процесса GitHub Actions использует синтаксис YAML. Каждый рабочий процесс хранится как отдельный YAML-файл в репозитории кода в каталоге с именем .github/workflows.

Можно создать пример рабочего процесса в репозитории, который автоматически активирует ряд команд при отправке кода. В этом рабочем процессе GitHub Actions извлекает отправленный код, устанавливает платформу тестирования bats и выполняет базовую команду для вывода версии bats: bats -v.

  1. В репозитории создайте каталог .github/workflows/ для хранения файлов рабочего процесса.

  2. В каталоге .github/workflows/ создайте файл с именем learn-github-actions.yml и добавьте следующий код.

    YAML
    name: learn-github-actions
    run-name: ${{ github.actor }} is learning GitHub Actions
    on: [push]
    jobs:
      check-bats-version:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-node@v4
            with:
              node-version: '20'
          - run: npm install -g bats
          - run: bats -v
    
  3. Зафиксируйте эти изменения и отправьте их в репозиторий GitHub.

Новый файл рабочего процесса GitHub Actions теперь установлен в репозитории и будет выполняться автоматически каждый раз, когда кто-то отправляет изменения в репозиторий. Дополнительные сведения о журнале выполнения рабочего процесса см. в разделе "Просмотр действия для выполнения рабочего процесса".

Общие сведения о файле рабочего процесса

Чтобы понять, как используется синтаксис YAML для создания файла рабочего процесса, просмотрите объяснение каждой строки вводного примера.

YAML
name: learn-github-actions

Optional - The name of the workflow as it will appear in the "Actions" tab of the GitHub repository. If this field is omitted, the name of the workflow file will be used instead.

run-name: ${{ github.actor }} is learning GitHub Actions

Optional - The name for workflow runs generated from the workflow, which will appear in the list of workflow runs on your repository's "Actions" tab. This example uses an expression with the github context to display the username of the actor that triggered the workflow run. For more information, see "Синтаксис рабочего процесса для GitHub Actions."

on: [push]

Specifies the trigger for this workflow. This example uses the push event, so a workflow run is triggered every time someone pushes a change to the repository or merges a pull request. This is triggered by a push to every branch; for examples of syntax that runs only on pushes to specific branches, paths, or tags, see "Синтаксис рабочего процесса для GitHub Actions."

jobs:

Groups together all the jobs that run in the learn-github-actions workflow.

  check-bats-version:

Defines a job named check-bats-version. The child keys will define properties of the job.

    runs-on: ubuntu-latest

Configures the job to run on the latest version of an Ubuntu Linux runner. This means that the job will execute on a fresh virtual machine hosted by GitHub. For syntax examples using other runners, see "Синтаксис рабочего процесса для GitHub Actions"

    steps:

Groups together all the steps that run in the check-bats-version job. Each item nested under this section is a separate action or shell script.

      - uses: actions/checkout@v4

The uses keyword specifies that this step will run v4 of the actions/checkout action. This is an action that checks out your repository onto the runner, allowing you to run scripts or other actions against your code (such as build and test tools). You should use the checkout action any time your workflow will use the repository's code.

      - uses: actions/setup-node@v4
        with:
          node-version: '20'

This step uses the actions/setup-node@v4 action to install the specified version of the Node.js. (This example uses version 20.) This puts both the node and npm commands in your PATH.

      - run: npm install -g bats

The run keyword tells the job to execute a command on the runner. In this case, you are using npm to install the bats software testing package.

      - run: bats -v

Finally, you'll run the bats command with a parameter that outputs the software version.

# Optional - The name of the workflow as it will appear in the "Actions" tab of the GitHub repository. If this field is omitted, the name of the workflow file will be used instead.
name: learn-github-actions

# Optional - The name for workflow runs generated from the workflow, which will appear in the list of workflow runs on your repository's "Actions" tab. This example uses an expression with the `github` context to display the username of the actor that triggered the workflow run. For more information, see "[AUTOTITLE](/actions/using-workflows/workflow-syntax-for-github-actions#run-name)."
run-name: ${{ github.actor }} is learning GitHub Actions

# Specifies the trigger for this workflow. This example uses the `push` event, so a workflow run is triggered every time someone pushes a change to the repository or merges a pull request.  This is triggered by a push to every branch; for examples of syntax that runs only on pushes to specific branches, paths, or tags, see "[AUTOTITLE](/actions/reference/workflow-syntax-for-github-actions#onpushpull_requestpull_request_targetpathspaths-ignore)."
on: [push]

# Groups together all the jobs that run in the `learn-github-actions` workflow.
jobs:

# Defines a job named `check-bats-version`. The child keys will define properties of the job.
  check-bats-version:

# Configures the job to run on the latest version of an Ubuntu Linux runner. This means that the job will execute on a fresh virtual machine hosted by GitHub. For syntax examples using other runners, see "[AUTOTITLE](/actions/reference/workflow-syntax-for-github-actions#jobsjob_idruns-on)"
    runs-on: ubuntu-latest

# Groups together all the steps that run in the `check-bats-version` job. Each item nested under this section is a separate action or shell script.
    steps:

# The `uses` keyword specifies that this step will run `v4` of the `actions/checkout` action. This is an action that checks out your repository onto the runner, allowing you to run scripts or other actions against your code (such as build and test tools). You should use the checkout action any time your workflow will use the repository's code.
      - uses: actions/checkout@v4

# This step uses the `actions/setup-node@v4` action to install the specified version of the Node.js. (This example uses version 20.) This puts both the `node` and `npm` commands in your `PATH`.
      - uses: actions/setup-node@v4
        with:
          node-version: '20'

# The `run` keyword tells the job to execute a command on the runner. In this case, you are using `npm` to install the `bats` software testing package.
      - run: npm install -g bats

# Finally, you'll run the `bats` command with a parameter that outputs the software version.
      - run: bats -v

Визуализация файла рабочего процесса

На этой схеме показан только что созданный файл рабочего процесса и порядок организации компонентов GitHub Actions в иерархии. Каждый этап выполняет одно действие или скрипт оболочки. Этапы 1 и 2 выполняют действия, а этапы 3 и 4 выполняют скрипты оболочки. Дополнительные предварительно созданные действия для рабочих процессов см. в разделе "Использование стандартных блоков в рабочем процессе".

Схема, показывающая триггер, средство выполнения и задание рабочего процесса. Задание разбито на 4 шага.

Просмотр действия для выполнения рабочего процесса

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

  1. На GitHubперейдите на главную страницу репозитория.

  2. Под именем репозитория щелкните Actions.

    Снимок экрана: вкладки для репозитория github/docs. Вкладка "Действия" выделена оранжевым контуром.

  3. На левой боковой панели щелкните нужный рабочий процесс.

    Снимок экрана: левая боковая панель вкладки "Действия". Рабочий процесс CodeQL описывается в темно-оранжевый цвет.

  4. В списке запусков рабочего процесса щелкните имя запуска, чтобы просмотреть сводку по выполнению рабочего процесса.

  5. На левой боковой панели или в графе визуализации щелкните задание, которое нужно просмотреть.

  6. Чтобы просмотреть результаты шага, щелкните этот шаг.