1
0
mirror of synced 2025-12-25 20:02:09 -05:00

Merge pull request #21185 from github/repo-sync

repo sync
This commit is contained in:
Octomerger Bot
2022-10-07 11:25:16 -07:00
committed by GitHub
35 changed files with 1850 additions and 1738 deletions

View File

@@ -91,7 +91,7 @@ For information on creating or accessing your access key ID and secret key, see
- For the provider URL, use `https://oidc-configuration.audit-log.githubusercontent.com`.
- For "Audience", use `sts.amazonaws.com`.
1. Create a bucket, and block public access to the bucket. For more information, see [Creating, configuring, and working with Amazon S3 buckets](https://docs.aws.amazon.com/AmazonS3/latest/userguide/creating-buckets-s3.html) in the AWS documentation.
1. Create a policy that allows {% data variables.product.company_short %} to write to the bucket. {% data variables.product.prodname_dotcom %} requires only the following permissions.
1. Create a policy that allows {% data variables.product.company_short %} to write to the bucket by copying the following JSON and replacing `EXAMPLE-BUCKET` with the name of your bucket. {% data variables.product.prodname_dotcom %} requires only the permissions in this JSON.
```
{
@@ -103,7 +103,7 @@ For information on creating or accessing your access key ID and secret key, see
"Action": [
"s3:PutObject"
],
"Resource": "arn:aws:s3:::example-bucket/*"
"Resource": "arn:aws:s3:::EXAMPLE-BUCKET/*"
}
]
}

View File

@@ -1,6 +1,6 @@
---
title: Visualización de las contribuciones y logros privados en tu perfil
intro: 'Tu perfil {% data variables.product.product_name %} muestra un gráfico de las contribuciones a tu repositorio durante el último año. Puedes elegir mostrar actividad anonimizada desde repositorios {% ifversion fpt or ghes or ghec %}privados e internos{% else %}privados{% endif %}{% ifversion fpt or ghes or ghec %}adicionalmente a la actividad de los repositorios públicos{% endif %}.'
title: Showing your private contributions and achievements on your profile
intro: 'Your {% data variables.product.product_name %} profile shows a graph of your repository contributions over the past year. You can choose to show anonymized activity from {% ifversion fpt or ghes or ghec %}private and internal{% else %}private{% endif %} repositories{% ifversion fpt or ghes or ghec %} in addition to the activity from public repositories{% endif %}.'
redirect_from:
- /articles/publicizing-or-hiding-your-private-contributions-on-your-profile
- /github/setting-up-and-managing-your-github-profile/publicizing-or-hiding-your-private-contributions-on-your-profile
@@ -14,40 +14,42 @@ versions:
topics:
- Profiles
shortTitle: Private contributions and achievements
ms.openlocfilehash: b40e3835bf1548ff4ced75d1207de9a5b493dc90
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
ms.translationtype: HT
ms.contentlocale: es-ES
ms.lasthandoff: 09/05/2022
ms.locfileid: '147080447'
---
Si publicas tus contribuciones privadas, las personas sin acceso a los repositorios privados en los que trabajas no podrán ver los detalles de tus contribuciones privadas. En su lugar, verán la cantidad de contribuciones privadas que has realizado durante un determinado día. Tus contribuciones públicas incluirán información detallada. Para obtener más información, vea "[Visualización de contribuciones en la página del perfil](/articles/viewing-contributions-on-your-profile-page)".
If you publicize your private contributions, people without access to the private repositories you work in won't be able to see the details of your private contributions. Instead, they'll see the number of private contributions you made on any given day. Your public contributions will include detailed information. For more information, see "[Viewing contributions on your profile page](/articles/viewing-contributions-on-your-profile-page)."
{% note %}
**Nota**: {% ifversion fpt or ghes or ghec %}En {% ifversion fpt or ghec %}{% data variables.product.prodname_dotcom_the_website %}{% elsif ghes %}{% data variables.product.product_name %}{% endif %}, las contribuciones públicas en su perfil son visibles {% ifversion fpt or ghec %}para cualquiera en el mundo que pueda acceder a {% data variables.product.prodname_dotcom_the_website %}{% elsif ghes %}únicamente para otros usuarios de {% data variables.product.product_location%}{% endif %}.{% elsif ghae %}En {% data variables.product.prodname_ghe_managed %}, solo otros miembros de su empresa pueden ver las contribuciones en su perfil.{% endif %}
**Note:** {% ifversion fpt or ghes or ghec %}On {% ifversion fpt or ghec %}{% data variables.product.prodname_dotcom_the_website %}{% elsif ghes %}{% data variables.product.product_name %}{% endif %}, public contributions on your profile are visible {% ifversion fpt or ghec %}to anyone in the world who can access {% data variables.product.prodname_dotcom_the_website %}{% elsif ghes %}only to other users of {% data variables.product.product_location%}{% endif %}.{% elsif ghae %}On {% data variables.product.prodname_ghe_managed %}, only other members of your enterprise can see the contributions on your profile.{% endif %}
{% endnote %}
## Cambiar la visibilidad de tus contribuciones privadas
## Changing the visibility of your private contributions
{% data reusables.profile.access_profile %}
1. Divulga u oculta tus contribuciones privadas en tu perfil:
- Para divulgar las contribuciones privadas, encima del gráfico de contribuciones, use el menú desplegable **Contribution settings** (Configuración de contribución) y seleccione **Private contributions** (Contribuciones privadas). Los visitantes verán tus recuentos de contribuciones privadas sin más detalles.
![Habilitación para que los visitantes vean las contribuciones privadas desde el menú desplegable de configuración de contribuciones](/assets/images/help/profile/private-contributions-on.png)
- Para ocultar las contribuciones privadas, encima del gráfico de contribuciones, use el menú desplegable **Contribution settings** (Configuración de contribución) y anule la selección de **Private contributions** (Contribuciones privadas). Los visitantes solo verán sus contribuciones públicas.
![Habilitación para que los visitantes vean las contribuciones privadas desde el menú desplegable de configuración de contribuciones](/assets/images/help/profile/private-contributions-off.png)
1. Publicize or hide your private contributions on your profile:
- To publicize your private contributions, above your contributions graph, use the **Contribution settings** drop-down menu, and select **Private contributions**. Visitors will see your private contribution counts without further details.
![Enable visitors to see private contributions from contribution settings drop-down menu](/assets/images/help/profile/private-contributions-on.png)
- To hide your private contributions, above your contributions graph, use the **Contribution settings** drop-down menu, and unselect **Private contributions.** Visitors will only see your public contributions.
![Enable visitors to see private contributions from contribution settings drop-down menu](/assets/images/help/profile/private-contributions-off.png)
## Cambio de la visibilidad de los logros
## Changing the visibility of Achievements
{% data reusables.user-settings.access_settings %}
1. Mostrar u ocultar logros en tu perfil:
- Para mostrar logros en el perfil, ve a **Configuración de perfil** y activa la casilla situada junto a **Mostrar logros en mi perfil.**
![Permitir que los visitantes vean los logros desde la configuración del perfil](/assets/images/achievements-profile-settings-off.png)
- Para ocultar logros en el perfil, ve a **Configuración de perfil** y desactiva la casilla situada junto a **Mostrar logros en mi perfil.**
![Ocultar los logros a los visitantes en la configuración del perfil](/assets/images/achievements-profile-settings-on.png)
1. Show or hide Achievements on your profile:
- To show Achievements on your profile, navigate to **Profile settings**, and select the checkbox next to **Show Achievements on my profile.**
![Enable visitors to see Achievements from profile settings](/assets/images/help/profile/achievements-profile-settings-off.png)
- To hide Achievements from your profile, navigate to **Profile settings**, and unselect the checkbox next to **Show Achievements on my profile.**
![Hide Achievements from visitors in profile settings](/assets/images/help/profile/achievements-profile-settings-on.png)
{% ifversion hide-individual-achievements %}
1. Optionally, to hide individual Achievements from your profile:
{% data reusables.profile.access_profile %}
1. Navigate to the Achievements section on the left sidebar of your profile and select the Achievements header. ![Achievements on profile sidebar](/assets/images/help/profile/achievements-on-profile.png)
2. Open the detail view of the achievement you'd like to hide by clicking on the achievement.
3. Once in the detail view, click the {% octicon "eye" aria-label="The eye icon" %} icon to hide the achievement. ![Achievement detail view](/assets/images/help/profile/achievements-detail-view.png) When hidden, badges will be marked by the {% octicon "eye-closed" aria-label="The eye closed icon" %} icon and are only visible to you. ![Hidden achievements](/assets/images/help/profile/achievements-hidden.png)
## Información adicional
{% endif %}
## Further reading
- "[Visualización de contribuciones en la página del perfil](/articles/viewing-contributions-on-your-profile-page)"
- "[¿Por qué mis contribuciones no aparecen en mi perfil?](/articles/why-are-my-contributions-not-showing-up-on-my-profile)"
- "[Viewing contributions on your profile page](/articles/viewing-contributions-on-your-profile-page)"
- "[Why are my contributions not showing up on my profile?](/articles/why-are-my-contributions-not-showing-up-on-my-profile)"

View File

@@ -115,7 +115,7 @@ For more information, see "[Reusing workflows](/actions/learn-github-actions/reu
#### `on.workflow_call.inputs.<input_id>.type`
Required if input is defined for the `on.workflow_call` keyword. The value of this parameter is a string specifying the data type of the input. This must be one of: `boolean`, `number`, or `string`.
Required if input is defined for the `on.workflow_call` keyword. The value of this parameter is a string specifying the data type of the input. This must be one of: `boolean`, `number`, `string` or `choice`.
### `on.workflow_call.outputs`

View File

@@ -3,6 +3,7 @@ title: Administración de la seguridad del código para la empresa
shortTitle: Manage code security
intro: Puedes crear seguridad en el flujo de trabajo de los desarrolladores con características que mantienen secretos y vulnerabilidades fuera del código base y que mantienen la cadena de suministro de software.
versions:
ghec: '*'
ghes: '*'
ghae: '*'
topics:

View File

@@ -8,11 +8,14 @@ redirect_from:
- /admin/configuration/configuring-advanced-security-features
- /admin/advanced-security
versions:
ghec: '*'
ghes: '*'
ghae: '> 3.6'
topics:
- Enterprise
children:
- /enabling-github-advanced-security-for-your-enterprise
- /managing-github-advanced-security-features-for-your-enterprise
- /configuring-code-scanning-for-your-appliance
- /configuring-dependency-review-for-your-appliance
- /configuring-secret-scanning-for-your-appliance

View File

@@ -13,9 +13,9 @@ topics:
- Infrastructure
- Performance
---
## Enabling rate limits for {% data variables.product.prodname_enterprise_api %}
## Enabling rate limits for the {% data variables.product.prodname_enterprise_api %}
Enabling rate limits on {% data variables.product.prodname_enterprise_api %} can prevent overuse of resources by individual or unauthenticated users. For more information, see "[Resources in the REST API](/rest/overview/resources-in-the-rest-api#rate-limiting)."
Enabling rate limits on the {% data variables.product.prodname_enterprise_api %} can prevent overuse of resources by individual or unauthenticated users. For more information, see "[Resources in the REST API](/rest/overview/resources-in-the-rest-api#rate-limiting)."
{% ifversion ghes %}
You can exempt a list of users from API rate limits using the `ghe-config` utility in the administrative shell. For more information, see "[Command-line utilities](/enterprise/admin/configuration/command-line-utilities#ghe-config)."

View File

@@ -29,5 +29,5 @@ You can authorize an existing personal access token, or [create a new personal a
## Further reading
- "[Creating a personal access token](/github/authenticating-to-github/creating-a-personal-access-token)"
- "[Creating a personal access token](/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token)"
- "[About authentication with SAML single sign-on](/articles/about-authentication-with-saml-single-sign-on)"

View File

@@ -31,6 +31,7 @@ If you don't have a GPG key that matches your committer identity, you need to as
If you have multiple GPG keys, you need to tell Git which one to use.
{% data reusables.command_line.open_the_multi_os_terminal %}
{% data reusables.gpg.configure-gpg-signing %}
{% data reusables.gpg.list-keys-with-note %}
{% data reusables.gpg.copy-gpg-key-id %}
{% data reusables.gpg.paste-gpg-key-id %}
@@ -68,6 +69,7 @@ If you don't have a GPG key that matches your committer identity, you need to as
If you have multiple GPG keys, you need to tell Git which one to use.
{% data reusables.command_line.open_the_multi_os_terminal %}
{% data reusables.gpg.configure-gpg-signing %}
{% data reusables.gpg.list-keys-with-note %}
{% data reusables.gpg.copy-gpg-key-id %}
{% data reusables.gpg.paste-gpg-key-id %}
@@ -89,6 +91,7 @@ If you don't have a GPG key that matches your committer identity, you need to as
If you have multiple GPG keys, you need to tell Git which one to use.
{% data reusables.command_line.open_the_multi_os_terminal %}
{% data reusables.gpg.configure-gpg-signing %}
{% data reusables.gpg.list-keys-with-note %}
{% data reusables.gpg.copy-gpg-key-id %}
{% data reusables.gpg.paste-gpg-key-id %}

View File

@@ -1,6 +1,6 @@
---
title: Configuración del examen de secretos para los repositorios
intro: 'Puedes configurar la forma en la que {% data variables.product.prodname_dotcom %} escanea tus repositorios en búsqueda de secretos que coincidan con los patrones de seguridad avanzada.'
title: Configuring secret scanning for your repositories
intro: 'You can configure how {% data variables.product.prodname_dotcom %} scans your repositories for secrets that match advanced security patterns.'
product: '{% data reusables.gated-features.secret-scanning %}'
permissions: 'People with admin permissions to a repository can enable {% data variables.product.prodname_secret_scanning_GHAS %} for the repository.'
redirect_from:
@@ -17,59 +17,71 @@ topics:
- Advanced Security
- Repositories
shortTitle: Configure secret scans
ms.openlocfilehash: 00983398e326997b6472da319d342ab0758018d3
ms.sourcegitcommit: fb047f9450b41b24afc43d9512a5db2a2b750a2a
ms.translationtype: HT
ms.contentlocale: es-ES
ms.lasthandoff: 09/11/2022
ms.locfileid: '147885720'
---
{% data reusables.secret-scanning.beta %} {% data reusables.secret-scanning.enterprise-enable-secret-scanning %}
## Habilitación de {% data variables.product.prodname_secret_scanning_GHAS %}
{% data reusables.secret-scanning.beta %}
{% data reusables.secret-scanning.enterprise-enable-secret-scanning %}
Puedes habilitar {% data variables.product.prodname_secret_scanning_GHAS %} para cualquier repositorio que sea propiedad de una organización. Una vez que se habilite, {% data reusables.secret-scanning.secret-scanning-process %}
## Enabling {% data variables.product.prodname_secret_scanning_GHAS %}
{% data reusables.repositories.navigate-to-repo %} {% data reusables.repositories.sidebar-settings %} {% data reusables.repositories.navigate-to-code-security-and-analysis %}
4. Si {% data variables.product.prodname_advanced_security %} todavía no está habilitado para el repositorio, a la derecha de "{% data variables.product.prodname_GH_advanced_security %}", haz clic en **Habilitar**.
{% ifversion fpt or ghec %}![Habilitación de {% data variables.product.prodname_GH_advanced_security %} para el repositorio](/assets/images/help/repository/enable-ghas-dotcom.png) {% elsif ghes or ghae %}![Habilitación de {% data variables.product.prodname_GH_advanced_security %} para el repositorio](/assets/images/enterprise/3.1/help/repository/enable-ghas.png){% endif %}
5. Revisa el impacto de habilitar la {% data variables.product.prodname_advanced_security %} y luego haz clic en **Habilitar la {% data variables.product.prodname_GH_advanced_security %} para este repositorio**.
6. Cuando habilitas la {% data variables.product.prodname_advanced_security %}, puede que el {% data variables.product.prodname_secret_scanning %} se habilite en el repositorio debido a la configuración de la organización. Si "{% data variables.product.prodname_secret_scanning_caps %}" se muestra con un botón **Habilitar**, debes habilitar {% data variables.product.prodname_secret_scanning %} haciendo clic en **Habilitar**. Si ves un botón **Deshabilitar**, {% data variables.product.prodname_secret_scanning %} ya está habilitado.
![Habilitación de {% data variables.product.prodname_secret_scanning %} para el repositorio](/assets/images/help/repository/enable-secret-scanning-dotcom.png) {% ifversion secret-scanning-push-protection %}
7. Opcionalmente, si quieres habilitar la protección de los envíos de cambios, haz clic en **Habilitar** a la derecha de "Protección de envíos de cambios". {% data reusables.secret-scanning.push-protection-overview %} Para obtener más información, consulta "[Protección de envíos de cambios con {% data variables.product.prodname_secret_scanning %}](/code-security/secret-scanning/protecting-pushes-with-secret-scanning)".
![Habilitar la protección de envíos de cambios para el repositorio](/assets/images/help/repository/secret-scanning-enable-push-protection.png) {% endif %} {% ifversion ghae %}
1. Antes de que puedas habilitar el {% data variables.product.prodname_secret_scanning %}, necesitas habilitar primero la {% data variables.product.prodname_GH_advanced_security %}. A la derecha de "{% data variables.product.prodname_GH_advanced_security %}", haz clic en **Habilitar**.
![Habilitación de la {% data variables.product.prodname_GH_advanced_security %} para tu repositorio](/assets/images/enterprise/github-ae/repository/enable-ghas-ghae.png)
2. Haz clic en **Habilitar la {% data variables.product.prodname_GH_advanced_security %} para este repositorio** para confirmar la acción.
![Confirmar la habilitación de la {% data variables.product.prodname_GH_advanced_security %} para tu repositorio](/assets/images/enterprise/github-ae/repository/enable-ghas-confirmation-ghae.png)
3. A la derecha de "{% data variables.product.prodname_secret_scanning_caps %}", haz clic en **Habilitar**.
![Habilitar el {% data variables.product.prodname_secret_scanning %} para tu repositorio](/assets/images/enterprise/github-ae/repository/enable-secret-scanning-ghae.png) {% endif %}
You can enable {% data variables.product.prodname_secret_scanning_GHAS %} for any repository that is owned by an organization. Once enabled, {% data reusables.secret-scanning.secret-scanning-process %}
## Excluir directorios de la {% data variables.product.prodname_secret_scanning_GHAS %}
{% ifversion secret-scanning-enterprise-level %}
{% note %}
Puedes utilizar un archivo *secret_scanning.yml* para excluir los directorios de {% data variables.product.prodname_secret_scanning %}. Por ejemplo, puedes excluir directorios que contengan pruebas o contenido generado aleatoriamente.
**Note:** If your organization is owned by an enterprise account, an enterprise owner can also enable {% data variables.product.prodname_secret_scanning %} at the enterprise level. For more information, see "[Managing {% data variables.product.prodname_GH_advanced_security %} features for your enterprise](/admin/code-security/managing-github-advanced-security-for-your-enterprise/managing-github-advanced-security-features-for-your-enterprise)."
{% data reusables.repositories.navigate-to-repo %} {% data reusables.files.add-file %}
3. En el campo nombre de archivo, escribe *.github/secret_scanning.yml*.
4. En **Editar nuevo archivo**, escribe `paths-ignore:` seguido por las rutas de acceso que quieras excluir de {% data variables.product.prodname_secret_scanning %}.
{% endnote %}
{% endif %}
{% data reusables.repositories.navigate-to-repo %}
{% data reusables.repositories.sidebar-settings %}
{% data reusables.repositories.navigate-to-code-security-and-analysis %}
4. If {% data variables.product.prodname_advanced_security %} is not already enabled for the repository, to the right of "{% data variables.product.prodname_GH_advanced_security %}", click **Enable**.
{% ifversion fpt or ghec %}![Enable {% data variables.product.prodname_GH_advanced_security %} for your repository](/assets/images/help/repository/enable-ghas-dotcom.png)
{% elsif ghes or ghae %}![Enable {% data variables.product.prodname_GH_advanced_security %} for your repository](/assets/images/enterprise/3.1/help/repository/enable-ghas.png){% endif %}
5. Review the impact of enabling {% data variables.product.prodname_advanced_security %}, then click **Enable {% data variables.product.prodname_GH_advanced_security %} for this repository**.
6. When you enable {% data variables.product.prodname_advanced_security %}, {% data variables.product.prodname_secret_scanning %} may automatically be enabled for the repository due to the organization's settings. If "{% data variables.product.prodname_secret_scanning_caps %}" is shown with an **Enable** button, you still need to enable {% data variables.product.prodname_secret_scanning %} by clicking **Enable**. If you see a **Disable** button, {% data variables.product.prodname_secret_scanning %} is already enabled.
![Enable {% data variables.product.prodname_secret_scanning %} for your repository](/assets/images/help/repository/enable-secret-scanning-dotcom.png)
{% ifversion secret-scanning-push-protection %}
7. Optionally, if you want to enable push protection, click **Enable** to the right of "Push protection." {% data reusables.secret-scanning.push-protection-overview %} For more information, see "[Protecting pushes with {% data variables.product.prodname_secret_scanning %}](/code-security/secret-scanning/protecting-pushes-with-secret-scanning)."
![Enable push protection for your repository](/assets/images/help/repository/secret-scanning-enable-push-protection.png)
{% endif %}
{% ifversion ghae %}
1. Before you can enable {% data variables.product.prodname_secret_scanning %}, you need to enable {% data variables.product.prodname_GH_advanced_security %} first. To the right of "{% data variables.product.prodname_GH_advanced_security %}", click **Enable**.
![Enable {% data variables.product.prodname_GH_advanced_security %} for your repository](/assets/images/enterprise/github-ae/repository/enable-ghas-ghae.png)
2. Click **Enable {% data variables.product.prodname_GH_advanced_security %} for this repository** to confirm the action.
![Confirm enabling {% data variables.product.prodname_GH_advanced_security %} for your repository](/assets/images/enterprise/github-ae/repository/enable-ghas-confirmation-ghae.png)
3. To the right of "{% data variables.product.prodname_secret_scanning_caps %}", click **Enable**.
![Enable {% data variables.product.prodname_secret_scanning %} for your repository](/assets/images/enterprise/github-ae/repository/enable-secret-scanning-ghae.png)
{% endif %}
## Excluding directories from {% data variables.product.prodname_secret_scanning_GHAS %}
You can use a *secret_scanning.yml* file to exclude directories from {% data variables.product.prodname_secret_scanning %}. For example, you can exclude directories that contain tests or randomly generated content.
{% data reusables.repositories.navigate-to-repo %}
{% data reusables.files.add-file %}
3. In the file name field, type *.github/secret_scanning.yml*.
4. Under **Edit new file**, type `paths-ignore:` followed by the paths you want to exclude from {% data variables.product.prodname_secret_scanning %}.
``` yaml
paths-ignore:
- "foo/bar/*.js"
```
Puede usar caracteres especiales, como `*` para filtrar las rutas. Para obtener más información sobre los patrones de filtro, consulta "[Sintaxis de flujo de trabajo para Acciones de GitHub](/actions/reference/workflow-syntax-for-github-actions#filter-pattern-cheat-sheet)".
You can use special characters, such as `*` to filter paths. For more information about filter patterns, see "[Workflow syntax for GitHub Actions](/actions/reference/workflow-syntax-for-github-actions#filter-pattern-cheat-sheet)."
{% note %}
**Notas:**
- Si hay más de 1000 entradas en `paths-ignore`, {% data variables.product.prodname_secret_scanning %} solo excluirá los primeros 1000 directorios de los análisis.
- Si *secret_scanning.yml* es mayor que 1 MB, {% data variables.product.prodname_secret_scanning %} ignorará todo el archivo.
**Notes:**
- If there are more than 1,000 entries in `paths-ignore`, {% data variables.product.prodname_secret_scanning %} will only exclude the first 1,000 directories from scans.
- If *secret_scanning.yml* is larger than 1 MB, {% data variables.product.prodname_secret_scanning %} will ignore the entire file.
{% endnote %}
También puedes ignorar alertas individuales de {% data variables.product.prodname_secret_scanning %}. Para obtener más información, consulta "[Administración de alertas de {% data variables.product.prodname_secret_scanning %}](/github/administering-a-repository/managing-alerts-from-secret-scanning#managing-secret-scanning-alerts)".
You can also ignore individual alerts from {% data variables.product.prodname_secret_scanning %}. For more information, see "[Managing alerts from {% data variables.product.prodname_secret_scanning %}](/github/administering-a-repository/managing-alerts-from-secret-scanning#managing-secret-scanning-alerts)."
## Información adicional
## Further reading
- "[Administración de la configuración de seguridad y análisis de la organización](/organizations/keeping-your-organization-secure/managing-security-and-analysis-settings-for-your-organization)"
- "[Definición de patrones personalizados para el {% data variables.product.prodname_secret_scanning %}](/code-security/secret-security/defining-custom-patterns-for-secret-scanning)"
- "[Managing security and analysis settings for your organization](/organizations/keeping-your-organization-secure/managing-security-and-analysis-settings-for-your-organization)"
- "[Defining custom patterns for {% data variables.product.prodname_secret_scanning %}](/code-security/secret-security/defining-custom-patterns-for-secret-scanning)"

View File

@@ -85,6 +85,9 @@ The recommended formats explicitly define which versions are used for all direct
| Maven | Java, Scala | `pom.xml` | `pom.xml` |
| npm | JavaScript | `package-lock.json` | `package-lock.json`, `package.json`|
| pip | Python | `requirements.txt`, `pipfile.lock` | `requirements.txt`, `pipfile`, `pipfile.lock`, `setup.py`<sup>[‡]</sup> |
{%- ifversion dependency-graph-dart-support %}
| pub | Dart | `pubspec.lock` | `pubspec.yaml`, `pubspec.lock` |
{%- endif %}
{%- ifversion fpt or ghec or ghes > 3.3 or ghae > 3.3 %}
| Python Poetry | Python | `poetry.lock` | `poetry.lock`, `pyproject.toml` |
{%- endif %}

View File

@@ -1,6 +1,6 @@
---
title: Configurar tu ambiente de desarrollo para crear una GitHub App
intro: 'Aprende los fundamentos para extender y crear {% data variables.product.prodname_github_apps %} nuevas.'
title: Setting up your development environment to create a GitHub App
intro: 'Learn the foundations for extending and building new {% data variables.product.prodname_github_apps %}.'
redirect_from:
- /apps/quickstart-guides/setting-up-your-development-environment
- /developers/apps/setting-up-your-development-environment-to-create-a-github-app
@@ -12,151 +12,146 @@ versions:
topics:
- GitHub Apps
shortTitle: Development environment
ms.openlocfilehash: 61370cfa0643bcba91cfe78e077346cd40286e1e
ms.sourcegitcommit: fb047f9450b41b24afc43d9512a5db2a2b750a2a
ms.translationtype: HT
ms.contentlocale: es-ES
ms.lasthandoff: 09/11/2022
ms.locfileid: '145092199'
---
## Introducción
## Introduction
Esta guía te mostrará los pasos necesarios para configurar una GitHub App y para ejecutarla en un servidor. Las GitHub Apps necesitan algunos pasos de configuración para administrar eventos de webhook y así conectar el registro de la App en GitHub hacia tu código. La app en esta guía sirve como una base que puedes utilizar para extender y crear GitHub Apps nuevas.
This guide will walk through the steps needed to configure a GitHub App and run it on a server. GitHub Apps require some setup steps to manage webhook events and connect the app registration on GitHub to your code. The app in this guide serves as a foundation that you can use to extend and build new GitHub Apps.
Al finalizar esta guía habrás registrado una GitHub App y habrás configurado un servidor web para recibir eventos de webhook. Aprenderás como utilizar una herramienta llamada Smee para capturar las cargas útiles de los webhooks y reenviarlas a tu ambiente de desarrollo local. La aplicación de plantilla que configurará en esta sección todavía no hará nada especial, pero funcionará como un marco que puede usar para comenzar a escribir código de aplicaciones mediante la API, o bien para completar otras [guías de inicio rápido](/apps/quickstart-guides/). {% ifversion fpt or ghec %}Puede consultar ejemplos correctos de aplicaciones en [GitHub Marketplace](https://github.com/marketplace) y [Trabajos con GitHub](https://github.com/works-with).{% endif %}
By the end of this guide you'll have registered a GitHub App and set up a web server to receive webhook events. You'll learn how to use a tool called Smee to capture webhook payloads and forward them to your local development environment. The template app you'll configure in this section won't do anything special yet, but it will serve as a framework you can use to start writing app code using the API or complete other [quickstart guides](/apps/quickstart-guides/). {% ifversion fpt or ghec %}You can check out successful examples of apps on [GitHub Marketplace](https://github.com/marketplace) and [Works with GitHub](https://github.com/works-with).{% endif %}
Después de completar este proyecto entenderás cómo autenticarte como una GitHub App y como una instalación, así como la forma en que difieren estos métodos de autenticación.
After completing this project you will understand how to authenticate as a GitHub App and an installation, and how those authentication methods are different.
Aquí están los pasos que tomarás para configurar la plantilla de la GitHub App:
Here are the steps you'll take to configure the template GitHub App:
1. [Inicio de un canal de Smee nuevo ](#step-1-start-a-new-smee-channel)
1. [Registro de una aplicación de GitHub nueva](#step-2-register-a-new-github-app)
1. [Almacenamiento de la clave privada y el identificador de aplicación](#step-3-save-your-private-key-and-app-id)
1. [Preparación del entorno de ejecución](#step-4-prepare-the-runtime-environment)
1. [Revisión del código de la plantilla de aplicación de GitHub](#step-5-review-the-github-app-template-code)
1. [Inicio del servidor](#step-6-start-the-server)
1. [Instalación de la aplicación en la cuenta](#step-7-install-the-app-on-your-account)
1. [Start a new Smee channel](#step-1-start-a-new-smee-channel)
1. [Register a new GitHub App](#step-2-register-a-new-github-app)
1. [Save your private key and App ID](#step-3-save-your-private-key-and-app-id)
1. [Prepare the runtime environment](#step-4-prepare-the-runtime-environment)
1. [Review the GitHub App template code](#step-5-review-the-github-app-template-code)
1. [Start the server](#step-6-start-the-server)
1. [Install the app on your account](#step-7-install-the-app-on-your-account)
{% data reusables.apps.app-ruby-guides %}
## Prerrequisitos
## Prerequisites
Puede que te sea útil tener un entendimiento básico de lo siguiente:
You may find it helpful to have a basic understanding of the following:
* [Aplicaciones de GitHub](/apps/about-apps)
* [GitHub Apps](/apps/about-apps)
* [Webhooks](/webhooks)
* [Lenguaje de programación Ruby](https://www.ruby-lang.org/en/)
* [API de REST](/rest)
* [The Ruby programming language](https://www.ruby-lang.org/en/)
* [REST APIs](/rest)
* [Sinatra](http://sinatrarb.com/)
Pero puedes seguir esta guía sin importar tu nivel de experiencia. ¡Colocaremos enlaces para la información que requieras en cada fase!
But you can follow along at any experience level. We'll link out to information you need along the way!
Antes de comenzar, necesitarás clonar el repositorio con el código de la plantilla que se utiliza en esta guía de inicio rápido. Abre tu app de terminal y encuentra el directorio en donde quieras almacenar el código. Ejecute este comando para clonar el repositorio de [plantillas de aplicación de GitHub](https://github.com/github-developer/github-app-template):
Before you begin, you'll need to clone the repository with the template code used in this quickstart. Open your Terminal app and find a directory where you'd like to store the code. Run this command to clone the [GitHub App template](https://github.com/github-developer/github-app-template) repository:
```shell
$ git clone https://github.com/github-developer/github-app-template.git
```
## Paso 1. Inicia un canal nuevo de Smee
## Step 1. Start a new Smee channel
Para ayudar a que GitHub envíe webhooks a tu máquina local sin exponerla al internet, puedes utilizar una herramienta llamada Smee. En primer lugar, vaya a https://smee.io y haga clic en **Iniciar un nuevo canal**. Si ya está familiarizado con otras herramientas que exponen el equipo local a Internet como [`ngrok`](https://dashboard.ngrok.com/get-started) o [`localtunnel`](https://localtunnel.github.io/www/), no dude en usarlas.
To help GitHub send webhooks to your local machine without exposing it to the internet, you can use a tool called Smee. First, go to https://smee.io and click **Start a new channel**. If you're already comfortable with other tools that expose your local machine to the internet like [`ngrok`](https://dashboard.ngrok.com/get-started) or [`localtunnel`](https://localtunnel.github.io/www/), feel free to use those.
![El botón de nuevo canal de Smee](/assets/images/smee-new-channel.png)
![The Smee new channel button](/assets/images/smee-new-channel.png)
El iniciar un canal de Smee nuevo crea un dominio único en donde GitHub puede enviar cargas útiles de webhooks. Necesitas saber cuál es este dominio para continuar con el siguiente paso. Este es un ejemplo de un dominio único en `https://smee.io/qrfeVRbFbffd6vD`:
Starting a new Smee channel creates a unique domain where GitHub can send webhook payloads. You'll need to know this domain for the next step. Here is an example of a unique domain at `https://smee.io/qrfeVRbFbffd6vD`:
![Un canal de Smee único](/assets/images/smee-unique-domain.png)
![A Smee unique channel](/assets/images/smee-unique-domain.png)
Posteriormente, regresa a la terminal y sigue estos pasos para ejecutar el cliente de la interface de línea de comandos (CLI) de Smee:
Next, go back to the Terminal and follow these steps to run the Smee command-line interface (CLI) client:
{% note %}
**Nota:** Los pasos siguientes son ligeramente diferentes a las instrucciones de "Uso de la CLI" que verá en la página del canal de Smee. **No** es necesario seguir las instrucciones de "Uso del cliente de Node.js" ni "Uso del soporte integrado de Probot".
**Note:** The following steps are slightly different than the "Use the CLI" instructions you'll see in your Smee channel page. You do **not** need to follow the "Use the Node.js client" or "Using Probot's built-in support" instructions.
{% endnote %}
1. Instalar el cliente:
1. Install the client:
```shell
$ npm install --global smee-client
```
2. Ejecute el cliente (reemplace `https://smee.io/qrfeVRbFbffd6vD` por un dominio propio):
2. Run the client (replacing `https://smee.io/qrfeVRbFbffd6vD` with your own domain):
```shell
$ smee --url https://smee.io/qrfeVRbFbffd6vD --path /event_handler --port 3000
```
El resultado debe ser parecido a lo siguiente:
You should see output like the following:
```shell
Forwarding https://smee.io/qrfeVRbFbffd6vD to http://127.0.0.1:3000/event_handler
Connected https://smee.io/qrfeVRbFbffd6vD
```
El comando `smee --url <unique_channel>` indica a Smee que reenvíe todos los eventos de webhook recibidos por el canal Smee al cliente Smee que se ejecuta en el equipo. La opción `--path /event_handler` reenvía los eventos a la ruta `/event_handler`, que se describirá en una [sección posterior](#step-5-review-the-github-app-template-code). La opción `--port 3000` especifica el puerto 3000, que es al que escuchará el servidor. Si utilizas Smee, tu máquina no necesita estar abierta al internet público para recibir webhooks de GitHub. También puedes abrir la URL de Smee en tu buscador para inspeccionar las cargas útiles de los webhooks como vayan llegando.
The `smee --url <unique_channel>` command tells Smee to forward all webhook events received by the Smee channel to the Smee client running on your computer. The `--path /event_handler` option forwards events to the `/event_handler` route, which we'll cover in a [later section](#step-5-review-the-github-app-template-code). The `--port 3000` option specifies port 3000, which is the port your server will be listening to. Using Smee, your machine does not need to be open to the public internet to receive webhooks from GitHub. You can also open that Smee URL in your browser to inspect webhook payloads as they come in.
Te recomendamos dejar abierta esta ventana de terminal y mantener a Smee conectado mientras completas el resto de los pasos de esta guía. Aunque _puede_ desconectar y el cliente de Smee y volverlo a conectar sin perder el dominio único (a diferencia de `ngrok`), es posible que le resulte más sencillo dejarlo conectado y realizar otras tareas de la línea de comandos en otra ventana de terminal.
We recommend leaving this Terminal window open and keeping Smee connected while you complete the rest of the steps in this guide. Although you _can_ disconnect and reconnect the Smee client without losing your unique domain (unlike `ngrok`), you may find it easier to leave it connected and do other command-line tasks in a different Terminal window.
## Paso 2. Registra una GitHub App nueva
## Step 2. Register a new GitHub App
Si todavía no tiene una cuenta de GitHub, ahora es un [buen momento para unirse](https://github.com/join). ¡No te olvides de verificar tu dirección de correo electrónico antes de continuar! Para registrar una aplicación nueva, visite la [página de configuración de aplicaciones](https://github.com/settings/apps) en el perfil de GitHub y haga clic en **Nueva aplicación de GitHub**.
If you don't yet have a GitHub account, now is a [great time to join](https://github.com/join). Don't forget to verify your email before continuing! To register a new app, visit the [app settings page](https://github.com/settings/apps) in your GitHub profile, and click **New GitHub App**.
![El sitio web de Github, mostrando la **App Nueva**](/assets/images/new-app.png)
![GitHub website, showing the **New App**](/assets/images/new-app.png)
Verás un formato en el cual puedes ingresar detalles sobre tu app. Vea "[Creación de una aplicación de GitHub](/apps/building-github-apps/creating-a-github-app/)" para obtener información general sobre los campos de esta página. Para los fines de esta guía, necesitaras ingresar datos específicos en unos cuantos campos:
You'll see a form where you can enter details about your app. See "[Creating a GitHub App](/apps/building-github-apps/creating-a-github-app/)" for general information about the fields on this page. For the purposes of this guide, you'll need to enter specific data in a few fields:
{% note %}
**Nota:** Siempre puede actualizar esta configuración más adelante para que apunte a un servidor hospedado.
**Note:** You can always update these settings later to point to a hosted server.
{% endnote %}
* En "URL de la página principal", utiliza el dominio que emitió Smee. Por ejemplo:
* For the "Homepage URL", use the domain issued by Smee. For example:
![Formato completado con el dominio de Smee para la URL de una página principal](/assets/images/homepage-url.png)
![Form with Smee domain filled in for homepage URL](/assets/images/homepage-url.png)
* Para la "URL del webhook", utiliza nuevamente el dominio que emitió Smee. Por ejemplo:
* For the "Webhook URL", again use the domain issued by Smee. For example:
![Formato completado con el dominio de Smee para la URl de un webhook](/assets/images/webhook-url.png)
![Form with Smee domain filled in for webhook URL](/assets/images/webhook-url.png)
* Para el "Secreto del webhook", crea una contraseña para asegurar las terminales de tu webhook. Este debería ser algo que solo tú (y GitHub, a través de este formulario) sepas. El secreto es importante, ya que estarás recibiendo cargas útiles desde el internet público, y utilizarás este secreto para verificar el remitente del webhook. Nota que la configuración de la GitHub App dice que el secreto de webhook es opcional, lo cual es verdad en la mayoría de los casos, pero para que funcione el código de la plantilla de la app, debes configurar un secreto de webhook.
* For the "Webhook secret", create a password to secure your webhook endpoints. This should be something that only you (and GitHub, via this form) know. The secret is important because you will be receiving payloads from the public internet, and you'll use this secret to verify the webhook sender. Note that the GitHub App settings say the webhook secret is optional, which is true in most cases, but for the template app code to work, you must set a webhook secret.
![Formato completado con el secreto de un webhook](/assets/images/webhook-secret.png)
![Form with webhook secret filled in](/assets/images/webhook-secret.png)
* En la página Permisos y webhooks, puede especificar un conjunto de permisos para la aplicación, que determinan la cantidad de datos a los que tiene acceso. En la sección "Permisos de repositorio", desplácese hacia abajo hasta "Metadatos" y seleccione `Access: Read-only`. Si decides extender esta app de plantilla, puedes actualizar estos permisos más adelante.
* On the Permissions & Webhooks page, you can specify a set of permissions for your app, which determines how much data your app has access to. Under the "Repository permissions"
section, scroll down to "Metadata" and select `Access: Read-only`. If you decide to extend this template app, you can update these permissions later.
* En la parte inferior de la página Permisos y webhooks, especifique si es una aplicación privada o pública. Esto se refiere a quién puede instalarla: ¿solo tú, o alguien más en general? Por ahora, seleccione **Solo en esta cuenta** para dejar la aplicación como privada.
* At the bottom of the Permissions & Webhooks page, specify whether this is a private app or a public app. This refers to who can install it: just you, or anyone in the world? For now, leave the app as private by selecting **Only on this account**.
![Privacidad de GitHub App](/assets/images/create_app.png)
![GitHub App privacy](/assets/images/create_app.png)
Haga clic en **Crear aplicación de GitHub** para crear la aplicación.
Click **Create GitHub App** to create your app!
## Paso 3. Guarda tu llave privada e ID de tu App
## Step 3. Save your private key and App ID
Después de crear la aplicación, volverá a la [página de configuración de la aplicación](https://github.com/settings/apps). Tienes dos cosas más para hacer aquí:
After you create your app, you'll be taken back to the [app settings page](https://github.com/settings/apps). You have two more things to do here:
* **Generar una clave privada para la aplicación.** Esto es necesario para autenticar la aplicación más adelante. Desplácese hacia abajo en la página y haga clic en **Generar una clave privada**. Guarde el archivo `PEM` resultante (con un nombre similar a _`app-name`_ - _`date`_ -`private-key.pem`) en un directorio donde pueda encontrarlo después.
* **Generate a private key for your app.** This is necessary to authenticate your app later on. Scroll down on the page and click **Generate a private key**. Save the resulting `PEM` file (called something like _`app-name`_-_`date`_-`private-key.pem`) in a directory where you can find it again.
![El diálogo de generación de la llave privada](/assets/images/private_key.png)
![The private key generation dialog](/assets/images/private_key.png)
* **Anote el id. de la aplicación que GitHub ha asignado a la aplicación.** Lo necesitará para preparar el entorno de ejecución.
* **Note the app ID GitHub has assigned your app.** You'll need this to prepare your runtime environment.
<img src="/assets/images/app_id.png" alt="Your app's ID number" width="200px"/>
## Paso 4. Prepara el ambiente de ejecución
## Step 4. Prepare the runtime environment
Para mantener tu información segura, te recomendamos poner todos los secretos relacionados con tu app en la memoria de tu ordenador en donde tu app pueda encontrarlos, en vez de ponerlos directamente en tu código. Una herramienta de desarrollo útil denominada [dotenv](https://github.com/bkeepers/dotenv) carga variables de entorno específicas del proyecto desde un archivo `.env` a `ENV`. Nunca confirme el archivo `.env` en GitHub. Este es un archivo local que almacena la información sensible que no quieres sacar al internet público. El archivo `.env` ya está incluido en el archivo [`.gitignore`](/github/getting-started-with-github/ignoring-files/) del repositorio para evitarlo.
To keep your information secure, we recommend putting all your app-related secrets in your computer's memory where your app can find them, rather than putting them directly in your code. A handy development tool called [dotenv](https://github.com/bkeepers/dotenv) loads project-specific environment variables from a `.env` file to `ENV`. Never check your `.env` file into GitHub. This is a local file that stores sensitive information that you don't want on the public internet. The `.env` file is already included in the repository's [`.gitignore`](/github/getting-started-with-github/ignoring-files/) file to prevent that.
El código de plantilla que ha descargado en la sección [Requisitos previos](#prerequisites) ya tiene un archivo de ejemplo denominado `.env-example`. Cambie el nombre del archivo de ejemplo de `.env-example` a `.env`, o bien cree una copia del archivo `.env-example` con el nombre `.env`. Todavía no ha instalado dotenv, pero lo hará más adelante en este inicio rápido al ejecutar `bundle install`. **Nota:** Los inicios rápidos que hacen referencia a los pasos de esta guía pueden incluir variables de entorno adicionales en el archivo `.env-example`. Referencia la guía de inicio rápido para el proyecto que clonaste en GitHub para obtener orientación para configurar estas variables de ambiente adicionales.
The template code you downloaded in the [Prerequisites section](#prerequisites) already has an example file called `.env-example`. Rename the example file from `.env-example` to `.env` or create a copy of the `.env-example` file called `.env`. You haven't installed dotenv yet, but you will install it later in this quickstart when you run `bundle install`. **Note:** Quickstarts that reference the steps in this guide may include additional environment variables in the `.env-example` file. Reference the quickstart guide for the project you've cloned on GitHub for guidance setting those additional environment variables.
Debe agregar estas variables al archivo `.env`:
You need to add these variables to the `.env` file:
* _`GITHUB_PRIVATE_KEY`_ : agregue la clave privada que [ha generado y guardado antes](#step-3-save-your-private-key-and-app-id). Abra el archivo `.pem` con un editor de texto o use la línea de comandos para mostrar el contenido del archivo: `cat path/to/your/private-key.pem`. Copie todo el contenido del archivo como valor de `GITHUB_PRIVATE_KEY` en el archivo `.env`. **Nota:** Como el archivo PEM tiene más de una línea de código, tendrá que incluir el valor entre comillas como en el ejemplo siguiente.
* _`GITHUB_APP_IDENTIFIER`_ : use el id. de la aplicación que ha anotado en la sección anterior.
* _`GITHUB_WEBHOOK_SECRET`_ : agregue el secreto de webhook.
* _`GITHUB_PRIVATE_KEY`_: Add the private key you [generated and saved previously](#step-3-save-your-private-key-and-app-id). Open the `.pem` file with a text editor or use the command line to display the contents of the file: `cat path/to/your/private-key.pem`. Copy the entire contents of the file as the value of `GITHUB_PRIVATE_KEY` in your `.env` file. **Note:** Because the PEM file is more than one line you'll need to add quotes around the value like the example below.
* _`GITHUB_APP_IDENTIFIER`_: Use the app ID you noted in the previous section.
* _`GITHUB_WEBHOOK_SECRET`_: Add your webhook secret.
A continuación, se muestra un archivo `.env` de ejemplo:
Here is an example `.env` file:
```
GITHUB_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
@@ -168,26 +163,26 @@ GITHUB_APP_IDENTIFIER=12345
GITHUB_WEBHOOK_SECRET=your webhook secret
```
## Paso 5. Revisar el código de la GitHub App de plantilla
## Step 5. Review the GitHub App template code
Éste contiene código que todas las GitHub Apps necesitarán. Esta sección te muestra el código que ya existe en la plantilla de la GitHub App. No hay algún paso que necesites completar en esta sección. Si ya está familiarizado con el código de plantilla, puede pasar a "[Paso 6. Inicio del servidor](#step-6-start-the-server)".
The template app code already contains some code that every GitHub App will need. This sections walks you through the code that already exists in the GitHub App template. There aren't any steps that you need to complete in this section. If you're already familiar with the template code, you can skip ahead to "[Step 6. Start the server](#step-6-start-the-server)."
Abra el archivo `template_server.rb` en el editor de texto que prefiera. Verás los comentarios a lo largo de este archivo, los cuales proporcionan contexto adicional para el código de la plantilla. Te recomendamos leer estos comentarios cuidadosamente, e incluso, agregar tus propios comentarios para complementar el código que escribas.
Open up the `template_server.rb` file in your favorite text editor. You'll see comments throughout this file that provide additional context for the template code. We recommend reading those comments carefully and even adding your own comments to accompany new code you write.
En la parte superior del archivo verá `set :port 3000`, que establece el puerto que se usa al iniciar el servidor web para que coincida con el puerto al que haya redirigido las cargas de webhook en "[Paso 1. Inicio de un canal nuevo de Smee](#step-1-start-a-new-smee-channel)".
At the top of the file you'll see `set :port 3000`, which sets the port used when starting the web server to match the port you redirected your webhook payloads to in "[Step 1. Start a new Smee channel](#step-1-start-a-new-smee-channel)."
El código siguiente que verá es la declaración `class GHApp < Sinatra::Application`. Escribirás todo el código de tu GitHub App dentro de esta clase.
The next code you'll see is the `class GHApp < Sinatra::Application` declaration. You'll write all of the code for your GitHub App inside this class.
Fuera de esta caja, la clase en la plantilla realiza lo siguiente:
* [Lee las variables de entorno](#read-the-environment-variables)
* [Active el registro.](#turn-on-logging)
* [Define un filtro anterior](#define-a-before-filter)
* [Define el controlador de ruta](#define-a-route-handler)
* [Definición de métodos auxiliares](#define-the-helper-methods)
Out of the box, the class in the template does the following things:
* [Read the environment variables](#read-the-environment-variables)
* [Turn on logging](#turn-on-logging)
* [Define a before filter](#define-a-before-filter)
* [Define the route handler](#define-a-route-handler)
* [Define the helper methods](#define-the-helper-methods)
### Lee las variables de ambiente
### Read the environment variables
Lo primero que hace esta clase es leer las tres variables de entorno establecidas en "[Paso 4. Preparación del entorno de ejecución](#step-4-prepare-the-runtime-environment)" y las almacena en variables para usarlas después:
The first thing that this class does is read the three environment variables you set in "[Step 4. Prepare the runtime environment](#step-4-prepare-the-runtime-environment)" and store them in variables to use later:
``` ruby
# Expects that the private key in PEM format. Converts the newlines
@@ -201,9 +196,9 @@ WEBHOOK_SECRET = ENV['GITHUB_WEBHOOK_SECRET']
APP_IDENTIFIER = ENV['GITHUB_APP_IDENTIFIER']
```
### Active el registro.
### Turn on logging
Posteriormente, hay un bloqueo de código que habilita el inicio de sesión durante el desarrollo, el cual es el ambiente predeterminado en Sinatra. Este código activa el registro en el nivel `DEBUG` para mostrar una salida útil en la terminal mientras desarrolla la aplicación:
Next is a code block that enables logging during development, which is the default environment in Sinatra. This code turns on logging at the `DEBUG` level to show useful output in the Terminal while you are developing the app:
``` ruby
# Turn on Sinatra's verbose logging during development
@@ -212,9 +207,9 @@ configure :development do
end
```
### Define un filtro del antes
### Define a before filter
Sinatra usa [filtros anteriores](https://github.com/sinatra/sinatra#filters) que permiten ejecutar código antes del controlador de ruta. El bloque `before` de la plantilla llama a cuatro [métodos auxiliares](https://github.com/sinatra/sinatra#helpers). La aplicación de plantilla define esos métodos auxiliares en una [sección posterior](#define-the-helper-methods).
Sinatra uses [before filters](https://github.com/sinatra/sinatra#filters) that allow you to execute code before the route handler. The `before` block in the template calls four [helper methods](https://github.com/sinatra/sinatra#helpers). The template app defines those helper methods in a [later section](#define-the-helper-methods).
``` ruby
# Before each request to the `/event_handler` route
@@ -227,9 +222,9 @@ before '/event_handler' do
end
```
### Define el gestor de la ruta
### Define a route handler
Se incluye una ruta vacía en el código de la plantilla. Este código controla todas las solicitudes `POST` a la ruta `/event_handler`. No escribirá este controlador de eventos en este inicio rápido, pero vea las otras [guías de inicio rápido](/apps/quickstart-guides/) para obtener ejemplos de cómo ampliar esta aplicación de plantilla.
An empty route is included in the template code. This code handles all `POST` requests to the `/event_handler` route. You won't write this event handler in this quickstart, but see the other [quickstart guides](/apps/quickstart-guides/) for examples of how to extend this template app.
``` ruby
post '/event_handler' do
@@ -237,35 +232,35 @@ post '/event_handler' do
end
```
### Definición de métodos auxiliares
### Define the helper methods
Los métodos auxiliares en esta plantilla hacen la mayoria del trabajo pesado. Se definen cuatro métodos auxiliares en esta sección del código.
The helper methods in this template do most of the heavy lifting. Four helper methods are defined in this section of the code.
#### Gestionar la carga útil del webhok
#### Handling the webhook payload
El primer método `get_payload_request` captura la carga de webhook y la convierte a formato JSON, lo que facilita mucho el acceso a los datos de la carga.
The first method `get_payload_request` captures the webhook payload and converts it to JSON format, which makes accessing the payload's data much easier.
#### Verificar la firma del webhook
#### Verifying the webhook signature
El segundo método `verify_webhook_signature` realiza la comprobación de la firma de webhook para asegurarse de que GitHub ha generado el evento. Para más información sobre el código del método auxiliar `verify_webhook_signature`, vea "[Protección de los webhooks](/webhooks/securing/)". Si los webhooks son seguros, este método registrará todas las cárgas útiles en tu terminal. El código de registro es útil para verificar que tu servidor web esté trabajando, pero siempre lo puedes eliminar más adelante.
The second method `verify_webhook_signature` performs verification of the webhook signature to ensure that GitHub generated the event. To learn more about the code in the `verify_webhook_signature` helper method, see "[Securing your webhooks](/webhooks/securing/)." If the webhooks are secure, this method will log all incoming payloads to your Terminal. The logger code is helpful in verifying your web server is working but you can always remove it later.
#### Autenticarse como una GitHub App
#### Authenticating as a GitHub App
Para realizar llamadas API, usará la [biblioteca Octokit](http://octokit.github.io/octokit.rb/). Para que puedas hacer algo interesante con esta biblioteca necesitarás, o más bien, tu app necesitará autenticarse. GitHub Apps tiene dos métodos de autenticación:
To make API calls, you'll be using the [Octokit library](http://octokit.github.io/octokit.rb/). Doing anything interesting with this library will require you, or rather your app, to authenticate. GitHub Apps have two methods of authentication:
- Autenticación como una aplicación de GitHub mediante un [token web JSON (JWT)](https://jwt.io/introduction).
- Autenticación como una instalación específica de una GitHub App utilizando un token de acceso de instalación.
- Authenticating as a GitHub App using a [JSON Web Token (JWT)](https://jwt.io/introduction).
- Authenticating as a specific installation of a GitHub App using an installation access token.
Obtendrá información sobre la autenticación como una instalación en la [sección siguiente](#authenticating-as-an-installation).
You'll learn about authenticating as an installation in the [next section](#authenticating-as-an-installation).
La [autenticación como una aplicación de GitHub](/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) le permite realizar un par de tareas:
[Authenticating as a GitHub App](/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) lets you do a couple of things:
* Puedes recuperar información administrativa de alto nivel sobre tu GitHub App.
* Puedes solicitar tokens de acceso para una instalación de la app.
* You can retrieve high-level management information about your GitHub App.
* You can request access tokens for an installation of the app.
Por ejemplo, te podrías autenticar como una GitHub App para solicitar una lista de las cuentas (de organización y de persona) que han instalado tu app. Pero este método de autenticación no te permite hacer mucho con la API. Para acceder a los datos del repositorio y realizar operaciones en nombre de la instalación, necesitas autenticarte como una instalación. Para hacerlo, primero necesitarás autenticarte como una GitHub App para solicitar un token de acceso a la instalación.
For example, you would authenticate as a GitHub App to retrieve a list of the accounts (organization and personal) that have installed your app. But this authentication method doesn't allow you to do much with the API. To access a repository's data and perform operations on behalf of the installation, you need to authenticate as an installation. To do that, you'll need to authenticate as a GitHub App first to request an installation access token.
A fin de poder usar la biblioteca Octokit.rb para realizar llamadas API, tendrá que inicializar un [cliente de Octokit](http://octokit.github.io/octokit.rb/Octokit/Client.html) autenticado como una aplicación de GitHub. El método auxiliar `authenticate_app` se encarga precisamente de eso.
Before you can use the Octokit.rb library to make API calls, you'll need to initialize an [Octokit client](http://octokit.github.io/octokit.rb/Octokit/Client.html) authenticated as a GitHub App. The `authenticate_app` helper method does just that!
``` ruby
# Instantiate an Octokit client authenticated as a GitHub App.
@@ -293,11 +288,11 @@ def authenticate_app
end
```
El código anterior genera un [JSON Web Token (JWT)](https://jwt.io/introduction) y lo usa, junto con la clave privada de la aplicación, para inicializar el cliente de Octokit. GitHub revisa la autenticación de una solicitud verificando el token con la llave pública almacenada en la app. Para más información sobre cómo funciona este código, vea "[Autenticación como una aplicación de GitHub](/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app)".
The code above generates a [JSON Web Token (JWT)](https://jwt.io/introduction) and uses it (along with your app's private key) to initialize the Octokit client. GitHub checks a request's authentication by verifying the token with the app's stored public key. To learn more about how this code works, see "[Authenticating as a GitHub App](/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app)."
#### Autenticarse como una instalación
#### Authenticating as an installation
Una _instalación_ hace referencia a cualquier cuenta de usuario u organización que haya instalado la aplicación. Aún si alguien instala la app en más de un repositorio, esto únicamente cuenta como una instalación, ya que toma lugar en la misma cuenta. El último método auxiliar `authenticate_installation` inicializa un [cliente de Octokit](http://octokit.github.io/octokit.rb/Octokit/Client.html) autenticado como una instalación. Este cliente de Octokit es lo que utilizarás para hacer llamadas autenticadas a la API.
An _installation_ refers to any user or organization account that has installed the app. Even if someone installs the app on more than one repository, it only counts as one installation because it's within the same account. The last helper method `authenticate_installation` initializes an [Octokit client](http://octokit.github.io/octokit.rb/Octokit/Client.html) authenticated as an installation. This Octokit client is what you'd use to make authenticated API calls.
``` ruby
# Instantiate an Octokit client authenticated as an installation of a
@@ -309,40 +304,40 @@ def authenticate_installation(payload)
end
```
El método [`create_app_installation_access_token`](http://octokit.github.io/octokit.rb/Octokit/Client/Apps.html#create_app_installation_access_token-instance_method) de Octokit crea un token de instalación. Este método acepta dos argumentos:
The [`create_app_installation_access_token`](http://octokit.github.io/octokit.rb/Octokit/Client/Apps.html#create_app_installation_access_token-instance_method) Octokit method creates an installation token. This method accepts two arguments:
* Instalación (número entero): la ID de la instalación de una GitHub App
* Opciones (hash, el valor predeterminado es `{}`): un conjunto personalizable de opciones
* Installation (integer): The ID of a GitHub App installation
* Options (hash, defaults to `{}`): A customizable set of options
Cada vez que una aplicación de GitHub recibe un webhook, incluye un objeto `installation` con una instancia de `id`. Mediante el cliente autenticado como una aplicación de GitHub, este identificador se pasa al método `create_app_installation_access_token` a fin de generar un token de acceso para cada instalación. Ya que no estás pasando ninguna opción al método, ésta será un hash vacío predeterminadamente. Si examina [la documentación](/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation), puede ver que la respuesta para `create_app_installation_access_token` incluye dos campos: `token` y `expired_at`. El código de la plantilla selecciona al token en la respuesta e inicializa un cliente de instalación.
Any time a GitHub App receives a webhook, it includes an `installation` object with an `id`. Using the client authenticated as a GitHub App, you pass this ID to the `create_app_installation_access_token` method to generate an access token for each installation. Since you're not passing any options to the method, the options default to an empty hash. If you look back at [the docs](/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation), you can see the response for `create_app_installation_access_token` includes two fields: `token` and `expired_at`. The template code selects the token in the response and initializes an installation client.
Una vez teniendo listo este métido, cada vez que tu app reciba una nueva carga útil de un webhook, este creará un cliente para la instalación que activó dicho evento. Este proceso de autenticación habilita a tu GitHub App para que trabaje para todas las instalaciones en cualquier cuenta.
With this method in place, each time your app receives a new webhook payload, it creates a client for the installation that triggered the event. This authentication process enables your GitHub App to work for all installations on any account.
¡Ahora estás listo para comenzar a hacer llamadas a la API!
Now you're ready to start making API calls!
## Paso 6. Inicio del servidor
## Step 6. Start the server
La aplicación todavía no _hace_ nada, pero en este punto, puede hacer que se ejecute en el servidor.
Your app doesn't _do_ anything yet, but at this point, you can get it running on the server.
Mantén a Smee ejecutándose en la pestaña actual dentro de tu terminal. Abra una nueva pestaña y ejecute `cd` en el directorio donde [ha clonado el código de la aplicación de plantilla](#prerequisites). El código de Ruby de este repositorio iniciará un servidor web de [Sinatra](http://sinatrarb.com/). Este código tiene algunas cuantas dependencias. Puedes instalarlas si ejecutas:
Keep Smee running in the current tab in your Terminal. Open a new tab and `cd` into the directory where you [cloned the template app code](#prerequisites). The Ruby code in this repository will start up a [Sinatra](http://sinatrarb.com/) web server. This code has a few dependencies. You can install these by running:
```shell
$ gem install bundler
```
Seguido de:
Followed by:
```shell
$ bundle install
```
Con las dependencias instaladas, puedes iniciar el servidor:
With the dependencies installed, you can start the server:
```shell
$ bundle exec ruby template_server.rb
```
Debería obtener una respuesta similar a la siguiente:
You should see a response like:
```shell
> == Sinatra (v2.0.3) has taken the stage on 3000 for development with backup from Puma
@@ -354,25 +349,25 @@ Debería obtener una respuesta similar a la siguiente:
> Use Ctrl-C to stop
```
Si ve un error, asegúrese de que ha creado el archivo `.env` en el directorio que contiene `template_server.rb`.
If you see an error, make sure you've created the `.env` file in the directory that contains `template_server.rb`.
Una vez que el servidor esté en ejecución, puede probarlo si va a `http://localhost:3000` en el explorador. Si la app funciona como se espera, verás una página de error útil:
Once the server is running, you can test it by going to `http://localhost:3000` in your browser. If the app works as expected, you'll see a helpful error page:
<img src="/assets/images/sinatra-404.png" alt="Sinatra's 404 error page" width="500px"/>
¡Esto es bueno! Aunque es una página de error, es una página de error de _Sinatra_, lo que significa que la aplicación está conectada al servidor de la forma esperada. Estás viendo este mensaje porque no le has dado nada más que mostrar a la app.
This is good! Even though it's an error page, it's a _Sinatra_ error page, which means your app is connected to the server as expected. You're seeing this message because you haven't given the app anything else to show.
## Paso 7. Instala la app en tu cuenta
## Step 7. Install the app on your account
Puedes probar que el servidor está escuchando a tu app si activas un evento para que lo reciba. Un evento sencillo que puede probar consiste en instalar la aplicación en la cuenta de GitHub, que debe enviar el evento [`installation`](/webhooks/event-payloads/#installation). Si la aplicación lo recibe, debería ver alguna salida en la pestaña Terminal donde ha iniciado `template_server.rb`.
You can test that the server is listening to your app by triggering an event for it to receive. A simple event you can test is installing the app on your GitHub account, which should send the [`installation`](/webhooks/event-payloads/#installation) event. If the app receives it, you should see some output in the Terminal tab where you started `template_server.rb`.
Para instalar la aplicación, visite la [página de configuración de la aplicación](https://github.com/settings/apps), elija la aplicación y haga clic en **Instalar aplicación** en la barra lateral. Junto al nombre de usuario, haga clic en **Instalar**.
To install the app, visit the [app settings page](https://github.com/settings/apps), choose your app, and click **Install App** in the sidebar. Next to your username, click **Install**.
Se te solicitará si quieres instalar la app en todos los repositorios o solo en los seleccionados. No hay problema si no quiere instalar la aplicación en _todos_ los repositorios. Tal vez quieras crear un repositorio de entorno de pruebas para e instalar tu app ahí.
You'll be asked whether to install the app on all repositories or selected repositories. If you don't want to install the app on _all_ of your repositories, that's okay! You may want to create a sandbox repository for testing purposes and install your app there.
<img src="/assets/images/install_permissions.png" alt="App installation permissions" width="500px"/>
Después de hacer clic en **Instalar**, examine la salida en el terminal. Deberíamos ver algo parecido a lo siguiente:
After you click **Install**, look at the output in your Terminal. You should see something like this:
```shell
> D, [2018-06-29T15:45:43.773077 #30488] DEBUG -- : ---- received event integration_installation
@@ -383,31 +378,31 @@ Después de hacer clic en **Instalar**, examine la salida en el terminal. Deber
> 192.30.252.39 - - [29/Jun/2018:15:45:43 -0400] "POST / HTTP/2" 200 2 0.0019
```
¡Estas son buenas noticias! Esto significa que tu app recibió una notificación de que se instaló en tu cuenta de GitHub. Si ves algo como esto, tu app está ejecutándose en el servidor como lo esperabas. 🙌
This is good news! It means your app received a notification that it was installed on your GitHub account. If you see something like this, your app is running on the server as expected. 🙌
Si no ve la salida, asegúrese de que Smee se ejecuta correctamente en otra pestaña de terminal. Si tiene que reiniciar Smee, recuerde que también tendrá que _desinstalar_ la aplicación y _volverla a instalar_ para enviar el evento `installation` a la aplicación de nuevo y ver la salida en el terminal. Si Smee no es el problema, vea la sección "[Solución de problemas](#troubleshooting)" para obtener otras ideas.
If you don't see the output, make sure Smee is running correctly in another Terminal tab. If you need to restart Smee, note that you'll also need to _uninstall_ and _reinstall_ the app to send the `installation` event to your app again and see the output in Terminal. If Smee isn't the problem, see the "[Troubleshooting](#troubleshooting)" section for other ideas.
Si se pregunta de dónde procede la salida del terminal anterior, está escrita en el [código de plantilla de la aplicación](#prerequisites) en `template_server.rb`.
If you're wondering where the Terminal output above is coming from, it's written in the [app template code](#prerequisites) in `template_server.rb`.
## Solución de problemas
## Troubleshooting
Aquí te mostramos algunos problemas comunes y algunas soluciones sugeridas. Si te encuentras con cualquier otro problema, puedes pedir ayuda o consejo en el {% data variables.product.prodname_support_forum_with_url %}.
Here are a few common problems and some suggested solutions. If you run into any other trouble, you can ask for help or advice in the {% data reusables.support.prodname_support_forum_with_url %}.
* **P:** Cuando intento instalar el cliente de línea de comandos Smee, se produce el error siguiente:
* **Q:** When I try to install the Smee command-line client, I get the following error:
```shell
> npm: command not found
```
**R:** Parece que no ha instalado npm. La mejor forma de instalarlo consiste en descargar el paquete de Node.js en https://nodejs.org y seguir las instrucciones de instalación para el sistema. Se instalará npm junto con Node.js.
**A:** Looks like you don't have npm installed. The best way to install it is to download the Node.js package at https://nodejs.org and follow the installation instructions for your system. npm will be installed alongside Node.js.
* **P:** Cuando ejecuto el servidor, se produce el error siguiente:
* **Q:** When I run the server, I get the following error:
```shell
> server.rb:38:in `initialize': Neither PUB key nor PRIV key: header too long (OpenSSL::PKey::RSAError)
```
**R:** Probablemente no ha configurado la variable de entorno de clave privada de forma correcta. La variable `GITHUB_PRIVATE_KEY` debería tener este aspecto:
**A:** You probably haven't set up your private key environment variable quite right. Your `GITHUB_PRIVATE_KEY` variable should look like this:
```
GITHUB_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
@@ -417,42 +412,42 @@ Aquí te mostramos algunos problemas comunes y algunas soluciones sugeridas. Si
-----END RSA PRIVATE KEY-----"
```
Compruebe que ha copiado la clave pública correcta en el archivo `.env`.
Double-check that you've copied the correct public key into your `.env` file.
* **P:** Cuando ejecuto el servidor, se bloquea con este error:
* **Q:** When I run the server, it crashes with this error:
```shell
> Octokit::Unauthorized ... 401 - Bad credentials`
```
**R:** Es posible que se haya autenticado como una aplicación de GitHub, pero no como una instalación. Asegúrese de seguir todos los pasos descritos en "[Autenticación como instalación](#authenticating-as-an-installation)" y use la variable de instancia `@installation_client` (autenticada con un token de acceso de instalación) para las operaciones de API, no la variable de instancia `@app_client` (autenticada con un JWT). `@app_client` solo puede recuperar información general sobre la aplicación y obtener tokens de acceso de instalación. No puede más que esto en la API.
**A:** You may be authenticated as a GitHub App but not as an installation. Make sure you follow all the steps under "[Authenticate as an installation](#authenticating-as-an-installation)," and use the `@installation_client` instance variable (authenticated with an installation access token) for your API operations, not the `@app_client` instance variable (authenticated with a JWT). The `@app_client` can only retrieve high-level information about your app and obtain installation access tokens. It can't do much else in the API.
* **P:** Mi servidor no escucha eventos. El cliente de Smee está ejecutándose en una ventana de la terminal, y estoy instalando la app en un repositorio con GitHub, pero no veo ninguna salida en la ventana de la terminal en donde estoy ejecutando el servidor.
* **Q:** My server isn't listening to events! The Smee client is running in a Terminal window, and I'm installing the app on a repository on GitHub, but I don't see any output in the Terminal window where I'm running the server.
**R:** Es posible que el cliente de Smee no esté en ejecución, que ejecute el comando de Smee con los parámetros incorrectos, o bien que no tenga el dominio de Smee correcto en la configuración de la aplicación de GitHub. En primer lugar, compruebe que el cliente Smee se ejecuta en una pestaña Terminal. Si ese no es el problema, visite la [página de configuración de la aplicación](https://github.com/settings/apps) y compruebe los campos que se muestran en "[Paso 2. Registro de una nueva aplicación de GitHub](#step-2-register-a-new-github-app)". Asegúrese de que el dominio de esos campos coincide con el dominio que ha usado en el comando `smee -u <unique_channel>` en "[Paso 1. Inicio de un nuevo canal Smee](#step-1-start-a-new-smee-channel)". Si no funcionada nada de lo anterior, compruebe que ejecuta el comando de Smee completo, incluidas las opciones `--path` y `--port`, por ejemplo: `smee --url https://smee.io/qrfeVRbFbffd6vD --path /event_handler --port 3000` (reemplace `https://smee.io/qrfeVRbFbffd6vD` por un dominio de Smee propio).
**A:** You may not be running the Smee client, running the Smee command with the wrong parameters or you may not have the correct Smee domain in your GitHub App settings. First check to make sure the Smee client is running in a Terminal tab. If that's not the problem, visit your [app settings page](https://github.com/settings/apps) and check the fields shown in "[Step 2. Register a new GitHub App](#step-2-register-a-new-github-app)." Make sure the domain in those fields matches the domain you used in your `smee -u <unique_channel>` command in "[Step 1. Start a new Smee channel](#step-1-start-a-new-smee-channel)." If none of the above work, check that you are running the full Smee command including the `--path` and `--port` options, for example: `smee --url https://smee.io/qrfeVRbFbffd6vD --path /event_handler --port 3000` (replacing `https://smee.io/qrfeVRbFbffd6vD` with your own Smee domain).
* **P:** Se produce un error `Octokit::NotFound` 404 en la salida de depuración:
* **Q:** I'm getting an `Octokit::NotFound` 404 error in my debug output:
```
2018-12-06 15:00:56 - Octokit::NotFound - POST {% data variables.product.api_url_code %}/app/installations/500991/access_tokens: 404 - Not Found // See: /v3/apps/#create-a-new-installation-token:
```
**R:** Asegúrese de que las variables del archivo `.env` son correctas. Asegúrese de que no ha configurado variables idénticas en otros archivos de variable de entorno como `bash_profile`. Puede comprobar las variables de entorno que usa la aplicación si agrega instrucciones `puts` en el código de la aplicación y vuelve a ejecutar el código. Por ejemplo, para asegurarse de que ha establecido la clave privada correcta, podría agregar `puts PRIVATE_KEY` al código de la aplicación:
**A:** Ensure the variables in your `.env` file are correct. Make sure that you have not set identical variables in any other environment variable files like `bash_profile`. You can check the environment variables your app is using by adding `puts` statements to your app code and re-running the code. For example, to ensure you have the correct private key set, you could add `puts PRIVATE_KEY` to your app code:
```
PRIVATE_KEY = OpenSSL::PKey::RSA.new(ENV['GITHUB_PRIVATE_KEY'].gsub('\n', "\n"))
puts PRIVATE_KEY
```
## Conclusión
## Conclusion
Después de seguir esta guía, ¡habrás aprendido los fundamentos básicos para desarrollar GitHub Apps! Para hacer una revisión:
After walking through this guide, you've learned the basic building blocks for developing GitHub Apps! To review, you:
* Registrar una GitHub App nueva
* Utilizar Smee para recibir cargas útiles de los webhooks
* Ejecutar un servidor web simple a través de Sinatra
* Autenticarte como una GitHub App
* Autenticarte como una instalación
* Registered a new GitHub App
* Used Smee to receive webhook payloads
* Ran a simple web server via Sinatra
* Authenticated as a GitHub App
* Authenticated as an installation
## Pasos siguientes
## Next steps
Ahora tienes una GitHub App ejecutándose en un servidor. Todavía no hace nada especial, pero compruebe algunas de las formas de personalizar la plantilla de aplicación de GitHub en las otras [guías de inicio rápido](/apps/quickstart-guides/).
You now have a GitHub App running on a server. It doesn't do anything special yet, but check out some of the ways you can customize your GitHub App template in the other [quickstart guides](/apps/quickstart-guides/).

View File

@@ -1,6 +1,6 @@
---
title: Crear pruebas de IC con la API de Verificaciones
intro: 'Crea un servidor de integración continua para ejecutar pruebas utilizando una {% data variables.product.prodname_github_app %} y la API de Verificaciones.'
title: Creating CI tests with the Checks API
intro: 'Build a continuous integration server to run tests using a {% data variables.product.prodname_github_app %} and the Checks API.'
redirect_from:
- /apps/quickstart-guides/creating-ci-tests-with-the-checks-api
- /developers/apps/creating-ci-tests-with-the-checks-api
@@ -12,104 +12,98 @@ versions:
topics:
- GitHub Apps
shortTitle: CI tests using Checks API
ms.openlocfilehash: ef43456aa08813a0b3010c40ce1b7628c75c5b68
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
ms.translationtype: HT
ms.contentlocale: es-ES
ms.lasthandoff: 09/05/2022
ms.locfileid: '147081011'
---
## Introducción
## Introduction
Esta guía presenta las [aplicaciones de GitHub](/apps/) y la [API de comprobaciones](/rest/reference/checks), las cuales usará para crear un servidor de integración continua (CI) que ejecute pruebas.
This guide will introduce you to [GitHub Apps](/apps/) and the [Checks API](/rest/reference/checks), which you'll use to build a continuous integration (CI) server that runs tests.
La IC es una práctica de software que requiere código confirmado frecuente en un repositorio compartido. El código de confirmación generar errores de manera temprana frecuentemente, así como reduce la cantidad de código que necesita un desarrollador para hacer depuraciones cuando encuentra la fuente de un error. Las actualizaciones frecuentes de código facilitan también la fusión de cambios de diferentes miembros de un equipo de desarrollo de software. Esto es excelente para los desarrolladores, que pueden dedicar más tiempo a escribir el código y menos tiempo a depurar errores o resolver conflictos de fusión. 🙌
CI is a software practice that requires frequently committing code to a shared repository. Committing code more often raises errors sooner and reduces the amount of code a developer needs to debug when finding the source of an error. Frequent code updates also make it easier to merge changes from different members of a software development team. This is great for developers, who can spend more time writing code and less time debugging errors or resolving merge conflicts. 🙌
Un servidor de IC hospeda código que ejecuta pruebas de IC, tal como los limpíadores de código (que revisan el formato del estilo), revisiones de seguridad, cobertura de código, y otras verificaciones contra las confirmaciones de código nuevas que hay en un repositorio. Los servidores de IC incluso pueden crear y desplegar código en los servidores de pruebas y en los productivos. Para ver algunos ejemplos de los tipos de pruebas de CI que puede crear con una aplicación de GitHub, consulte las [aplicaciones de integración continua](https://github.com/marketplace/category/continuous-integration) disponibles en GitHub Marketplace.
A CI server hosts code that runs CI tests such as code linters (which check style formatting), security checks, code coverage, and other checks against new code commits in a repository. CI servers can even build and deploy code to staging or production servers. For some examples of the types of CI tests you can create with a GitHub App, check out the [continuous integration apps](https://github.com/marketplace/category/continuous-integration) available in GitHub Marketplace.
{% data reusables.apps.app-ruby-guides %}
### Resumen de la API de Verificaciones
### Checks API overview
La [API de comprobaciones](/rest/reference/checks) le permite configurar pruebas de CI que se ejecutan automáticamente en cada confirmación de código de un repositorio. La API de comprobaciones comunica información detallada sobre cada comprobación de GitHub en la pestaña **Checks** (Comprobaciones) de la solicitud de incorporación de cambios. Con la API de comprobaciones, puede crear anotaciones con detalles adicionales para líneas de código específicas. Las anotaciones están visibles en la pestaña **Checks** (Comprobaciones). Cuando se crean anotaciones para un archivo que forma parte de la solicitud de incorporación de cambios, las anotaciones también se muestran en la pestaña **Files changed** (Archivos modificados).
The [Checks API](/rest/reference/checks) allows you to set up CI tests that are automatically run against each code commit in a repository. The Checks API reports detailed information about each check on GitHub in the pull request's **Checks** tab. With the Checks API, you can create annotations with additional details for specific lines of code. Annotations are visible in the **Checks** tab. When you create an annotation for a file that is part of the pull request, the annotations are also shown in the **Files changed** tab.
Un _conjunto de comprobaciones_ es un grupo de _ejecuciones de comprobación_ (pruebas de CI individuales). Tanto el conjunto de comprobaciones como las ejecuciones contienen _estados_ que pueden visualizarse en una solicitud de incorporación de cambios en GitHub. Puedes utilizar estados para determinar cuando una confirmación de código introduce errores. El uso de estos estados con [ramas protegidas](/rest/reference/repos#branches) puede impedir que las personas combinen solicitudes de incorporación de cambios antes de tiempo. Consulte "[Acerca de las ramas protegidas](/github/administering-a-repository/about-protected-branches#require-status-checks-before-merging)" para obtener más información.
A _check suite_ is a group of _check runs_ (individual CI tests). Both the suite and the runs contain _statuses_ that are visible in a pull request on GitHub. You can use statuses to determine when a code commit introduces errors. Using these statuses with [protected branches](/rest/reference/repos#branches) can prevent people from merging pull requests prematurely. See "[About protected branches](/github/administering-a-repository/about-protected-branches#require-status-checks-before-merging)" for more details.
La API de comprobaciones envía el [evento de webhook `check_suite`](/webhooks/event-payloads/#check_suite) a todas las aplicaciones de GitHub instaladas en un repositorio cada vez que se inserta código nuevo en el repositorio. Para recibir todas las acciones de eventos de la API de comprobaciones, la aplicación debe tener el permiso `checks:write`. GitHub crea automáticamente eventos `check_suite` para nuevas confirmaciones de código en un repositorio mediante el flujo predeterminado, aunque puede [actualizar las preferencias del repositorio para los conjuntos de comprobaciones](/rest/reference/checks#update-repository-preferences-for-check-suites) si quiere. Aquí te mostramos cómo funciona el flujo predeterminado:
The Checks API sends the [`check_suite` webhook event](/webhooks/event-payloads/#check_suite) to all GitHub Apps installed on a repository each time new code is pushed to the repository. To receive all Checks API event actions, the app must have the `checks:write` permission. GitHub automatically creates `check_suite` events for new code commits in a repository using the default flow, although [Update repository preferences for check suites](/rest/reference/checks#update-repository-preferences-for-check-suites) if you'd like. Here's how the default flow works:
1. Cada vez que alguien inserta código en el repositorio, GitHub envía el evento `check_suite` con una acción `requested` a todas las aplicaciones de GitHub instaladas en el repositorio que tienen el permiso `checks:write`. Este evento permite a las apps saber que se cargó código y que GitHub creó un nuevo conjunto de verificaciones automáticamente.
1. Cuando la aplicación recibe este evento, puede [agregar ejecuciones de comprobación](/rest/reference/checks#create-a-check-run) a ese conjunto.
1. Las ejecuciones de comprobación pueden incluir [anotaciones](/rest/reference/checks#annotations-object) que se muestran en líneas de código específicas.
1. Whenever someone pushes code to the repository, GitHub sends the `check_suite` event with an action of `requested` to all GitHub Apps installed on the repository that have the `checks:write` permission. This event lets the apps know that code was pushed and that GitHub has automatically created a new check suite.
1. When your app receives this event, it can [add check runs](/rest/reference/checks#create-a-check-run) to that suite.
1. Your check runs can include [annotations](/rest/reference/checks#annotations-object) that are displayed on specific lines of code.
**En esta guía, aprenderá a:**
**In this guide, youll learn how to:**
* Parte 1: Configurar el marco de trabajo para un servidor de IC utilizando la API de Verificaciones.
* Configurar una GitHub App como un servidor que recibe los eventos de la API de Verificaciones.
* Crear ejecuciones de verificacion nuevas para las pruebas de IC cuando un repositorio recibe cargas nuevas de confirmaciones.
* Re-ejecutar ejecuciones de verificación cuando un usuario solicita esta acción en GitHub.
* Parte 2: Compilar en el marco de trabajo del servidor de IC que creaste agregando una prueba de limpieza de IC.
* Actualizar una ejecución de comprobación con detalles de `status`, `conclusion` y `output`.
* Crear anotaciones en líneas de código que GitHub muestra en las pestañas **Checks** (Comprobaciones) y **Files Changed** (Archivos modificados) de una solicitud de incorporación de cambios.
* Corregir automáticamente las recomendaciones del linter exponiendo el botón "Fix this" (Corregir esto) en la pestaña **Checks** (Comprobaciones) de la solicitud de extracción.
* Part 1: Set up the framework for a CI server using the Checks API.
* Configure a GitHub App as a server that receives Checks API events.
* Create new check runs for CI tests when a repository receives newly pushed commits.
* Re-run check runs when a user requests that action on GitHub.
* Part 2: Build on the CI server framework you created by adding a linter CI test.
* Update a check run with a `status`, `conclusion`, and `output` details.
* Create annotations on lines of code that GitHub displays in the **Checks** and **Files Changed** tab of a pull request.
* Automatically fix linter recommendations by exposing a "Fix this" button in the **Checks** tab of the pull request.
Para obtener una idea de lo que hará tu servidor de IC para la API de Verificaciones cuando completes este inicio rápido, revisa el siguiente demo:
To get an idea of what your Checks API CI server will do when you've completed this quickstart, check out the demo below:
![Demostración de la guía de inicio rápido para el servidor de IC de la API de Verificaciones](/assets/images/github-apps/github_apps_checks_api_ci_server.gif)
![Demo of Checks API CI sever quickstart](/assets/images/github-apps/github_apps_checks_api_ci_server.gif)
## Prerrequisitos
## Prerequisites
Antes de empezar, es posible que quiera familiarizarse con las [aplicaciones de GitHub](/apps/), los [webhooks](/webhooks) y la [API de comprobaciones](/rest/reference/checks), si aún no lo ha hecho. Encontrará más API en la [documentación de la API REST](/rest). La API de comprobaciones también está disponible para su uso en [GraphQL](/graphql), pero esta guía de inicio rápido se centra en REST. Consulte los objetos [CheckSuite](/graphql/reference/objects#checksuite) y [CheckRun](/graphql/reference/objects#checkrun) de GraphQL para obtener más detalles.
Before you get started, you may want to familiarize yourself with [GitHub Apps](/apps/), [Webhooks](/webhooks), and the [Checks API](/rest/reference/checks), if you're not already. You'll find more APIs in the [REST API docs](/rest). The Checks API is also available to use in [GraphQL](/graphql), but this quickstart focuses on REST. See the GraphQL [Checks Suite](/graphql/reference/objects#checksuite) and [Check Run](/graphql/reference/objects#checkrun) objects for more details.
Usará el [lenguaje de programación Ruby](https://www.ruby-lang.org/en/), el servicio [Smee](https://smee.io/) de entrega de cargas de webhook, la [biblioteca de Ruby Octokit.rb](http://octokit.github.io/octokit.rb/) para la API REST de GitHub y el [marco web de Sinatra](http://sinatrarb.com/) para crear la aplicación de servidor de CI de la API de comprobaciones.
You'll use the [Ruby programming language](https://www.ruby-lang.org/en/), the [Smee](https://smee.io/) webhook payload delivery service, the [Octokit.rb Ruby library](http://octokit.github.io/octokit.rb/) for the GitHub REST API, and the [Sinatra web framework](http://sinatrarb.com/) to create your Checks API CI server app.
No necesitas ser un experto en ninguna de estas herramientas o conceptos para completar este proyecto. Esta guía te mostrará todos los pasos requeridos a detalle. Antes de que comiences a crear pruebas de IC con la API de Verificaciones, necesitarás hacer lo siguiente:
You don't need to be an expert in any of these tools or concepts to complete this project. This guide will walk you through all the required steps. Before you begin creating CI tests with the Checks API, you'll need to do the following:
1. Clonar el repositorio [Creación de pruebas de CI con la API de comprobaciones](https://github.com/github-developer/creating-ci-tests-with-the-checks-api).
1. Clone the [Creating CI tests with the Checks API](https://github.com/github-developer/creating-ci-tests-with-the-checks-api) repository.
```shell
$ git clone https://github.com/github-developer/creating-ci-tests-with-the-checks-api.git
```
En el directorio, encontrará un archivo `template_server.rb` con el código de plantilla que usará en este inicio rápido y un archivo `server.rb` con el código del proyecto completado.
Inside the directory, you'll find a `template_server.rb` file with the template code you'll use in this quickstart and a `server.rb` file with the completed project code.
1. Siga los pasos de la guía de inicio rápido "[Configuración del entorno de desarrollo](/apps/quickstart-guides/setting-up-your-development-environment/)" para configurar y ejecutar el servidor de la aplicación. **Nota:** En lugar de [clonar el repositorio de plantillas de la aplicación de GitHub](/apps/quickstart-guides/setting-up-your-development-environment/#prerequisites), use el archivo `template_server.rb` del repositorio que ha clonado en el paso anterior de esta guía de inicio rápido.
1. Follow the steps in the "[Setting up your development environment](/apps/quickstart-guides/setting-up-your-development-environment/)" quickstart to configure and run the app server. **Note:** Instead of [cloning the GitHub App template repository](/apps/quickstart-guides/setting-up-your-development-environment/#prerequisites), use the `template_server.rb` file in the repository you cloned in the previous step in this quickstart.
Si ya ha completado antes una guía de inicio rápido para una aplicación de GitHub, asegúrese de registrar una _nueva_ aplicación de GitHub e inicie un nuevo canal de Smee para usarlo con esta guía de inicio rápido.
If you've completed a GitHub App quickstart before, make sure to register a _new_ GitHub App and start a new Smee channel to use with this quickstart.
Consulte la sección de [solución de problemas](/apps/quickstart-guides/setting-up-your-development-environment/#troubleshooting) si tiene problemas para configurar la aplicación de plantilla de GitHub.
See the [troubleshooting](/apps/quickstart-guides/setting-up-your-development-environment/#troubleshooting) section if you are running into problems setting up your template GitHub App.
## Parte 1. Crear la interface de la API de Verificaciones
## Part 1. Creating the Checks API interface
En esta parte, agregará el código necesario para recibir eventos del webhook `check_suite` y para crear y actualizar las ejecuciones de comprobación. También aprenderás cómo crear ejecuciones de verificación cuando se re-solicite una verificación en GitHub. Al final de esta sección, podrás ver la ejecución de verificación que creaste en una solicitud de extracción de GitHub.
In this part, you will add the code necessary to receive `check_suite` webhook events and create and update check runs. You'll also learn how to create check runs when a check was re-requested on GitHub. At the end of this section, you'll be able to view the check run you created in a GitHub pull request.
En esta sección, tu ejecución de verificación no realizará ninguna verificación de código. Agregará esa funcionalidad en la [parte 2: Creación de la prueba de CI de Octo RuboCop](#part-2-creating-the-octo-rubocop-ci-test).
Your check run will not be performing any checks on the code in this section. You'll add that functionality in [Part 2: Creating the Octo RuboCop CI test](#part-2-creating-the-octo-rubocop-ci-test).
Ya deberías haber configurado el canal de Smee que reenviará las cargas útiles del webhook a tu servidor local. Tu servidor deberá estar funcionando y también estar conectado con la GitHub App que registraste e instalaste ene un repositorio de prueba. Si no ha completado los pasos descritos en "[Configuración del entorno de desarrollo](/apps/quickstart-guides/setting-up-your-development-environment/)", deberá hacerlo para poder continuar.
You should already have a Smee channel configured that is forwarding webhook payloads to your local server. Your server should be running and connected to the GitHub App you registered and installed on a test repository. If you haven't completed the steps in "[Setting up your development environment](/apps/quickstart-guides/setting-up-your-development-environment/)," you'll need to do that before you can continue.
Comencemos. Estos son los pasos que completarás en la Parte 1:
Let's get started! These are the steps you'll complete in Part 1:
1. [Actualización de los permisos de la aplicación](#step-11-updating-app-permissions)
1. [Adición del control de eventos](#step-12-adding-event-handling)
1. [Creación de una ejecución de comprobación](#step-13-creating-a-check-run)
1. [Actualización de una ejecución de comprobación](#step-14-updating-a-check-run)
1. [Updating app permissions](#step-11-updating-app-permissions)
1. [Adding event handling](#step-12-adding-event-handling)
1. [Creating a check run](#step-13-creating-a-check-run)
1. [Updating a check run](#step-14-updating-a-check-run)
## Paso 1.1. Actualizar los permisos de la app
## Step 1.1. Updating app permissions
Cuando [registró por primera vez la aplicación](#prerequisites), aceptó los permisos predeterminados, lo que significa que la aplicación no tiene acceso a la mayoría de los recursos. Para este ejemplo, tu app necesitará el permiso de leer y escribir verificaciones.
When you [first registered your app](#prerequisites), you accepted the default permissions, which means your app doesn't have access to most resources. For this example, your app will need permission to read and write checks.
Para actualizar los permisos de tu app:
To update your app's permissions:
1. Seleccione la aplicación en la [página de configuración de la aplicación](https://github.com/settings/apps) y haga clic en **Permissions & Webhooks** (Permisos y webhooks) en la barra lateral.
1. En la sección "Permissions" (Permisos), busque "Checks" (Comprobaciones) y, al lado, seleccione **Read & write** (Lectura y escritura) en la lista desplegable Access (Acceso).
1. En la sección "Subscribe to events" (Suscribirse a eventos), seleccione **Check suite** (Conjunto de comprobaciones) y **Check run** (Ejecución de comprobación) para suscribirse a estos eventos.
1. Select your app from the [app settings page](https://github.com/settings/apps) and click **Permissions & Webhooks** in the sidebar.
1. In the "Permissions" section, find "Checks", and select **Read & write** in the Access dropdown next to it.
1. In the "Subscribe to events" section, select **Check suite** and **Check run** to subscribe to these events.
{% data reusables.apps.accept_new_permissions_steps %}
Magnífico. Tu app tiene permiso para realizar las tareas que quieres que haga. Ahora puedes agregar el código para que gestione los eventos.
Great! Your app has permission to do the tasks you want it to do. Now you can add the code to handle the events.
## Paso 1.2. Agregar la gestión de eventos
## Step 1.2. Adding event handling
Ahora que la aplicación está suscrita a los eventos **Check suite** (Conjunto de comprobaciones) y **Check run** (Ejecución de comprobación), comenzará a recibir los webhooks [`check_suite`](/webhooks/event-payloads/#check_suite) y [`check_run`](/webhooks/event-payloads/#check_run). GitHub envía cargas de webhook como solicitudes `POST`. Dado que ha reenviado las cargas de webhook de Smee a `http://localhost/event_handler:3000`, el servidor recibirá las cargas de solicitud `POST` en la ruta `post '/event_handler'`.
Now that your app is subscribed to the **Check suite** and **Check run** events, it will start receiving the [`check_suite`](/webhooks/event-payloads/#check_suite) and [`check_run`](/webhooks/event-payloads/#check_run) webhooks. GitHub sends webhook payloads as `POST` requests. Because you forwarded your Smee webhook payloads to `http://localhost/event_handler:3000`, your server will receive the `POST` request payloads at the `post '/event_handler'` route.
Ya se incluye una ruta vacía `post '/event_handler'` en el archivo `template_server.rb`, el cual ha descargado en la sección de [requisitos previos](#prerequisites). La ruta vacía se ve así:
An empty `post '/event_handler'` route is already included in the `template_server.rb` file, which you downloaded in the [prerequisites](#prerequisites) section. The empty route looks like this:
``` ruby
post '/event_handler' do
@@ -122,7 +116,7 @@ Ya se incluye una ruta vacía `post '/event_handler'` en el archivo `template_se
end
```
Use esta ruta para controlar el evento `check_suite`; para ello, agregue el código siguiente:
Use this route to handle the `check_suite` event by adding the following code:
``` ruby
# Get the event type from the HTTP_X_GITHUB_EVENT header
@@ -135,13 +129,13 @@ when 'check_suite'
end
```
Cada evento que GitHub envía incluye un encabezado de solicitud denominado `HTTP_X_GITHUB_EVENT`, que indica el tipo de evento en la solicitud `POST`. En este momento, solo le interesan los eventos de tipo `check_suite`, que se emiten cuando se crea un nuevo conjunto de comprobaciones. Cada evento tiene un campo `action` adicional que indica el tipo de acción que ha activado los eventos. Para `check_suite`, el campo `action` puede ser `requested`, `rerequested` o `completed`.
Every event that GitHub sends includes a request header called `HTTP_X_GITHUB_EVENT`, which indicates the type of event in the `POST` request. Right now, you're only interested in events of type `check_suite`, which are emitted when a new check suite is created. Each event has an additional `action` field that indicates the type of action that triggered the events. For `check_suite`, the `action` field can be `requested`, `rerequested`, or `completed`.
La acción `requested` solicita una ejecución de comprobación cada vez que el código se inserta en el repositorio, mientras que la acción `rerequested` solicita que se vuelva a ejecutar una comprobación para el código que ya existe en el repositorio. Dado que las acciones `requested` y `rerequested` requieren la creación de una ejecución de comprobación, llamará a un asistente denominado `create_check_run`. Vamos a escribir ese método ahora.
The `requested` action requests a check run each time code is pushed to the repository, while the `rerequested` action requests that you re-run a check for code that already exists in the repository. Because both the `requested` and `rerequested` actions require creating a check run, you'll call a helper called `create_check_run`. Let's write that method now.
## Paso 1.3. Crear una ejecución de verificación
## Step 1.3. Creating a check run
Agregará este nuevo método como [asistente de Sinatra](https://github.com/sinatra/sinatra#helpers) en caso de que quiera que otras rutas también lo usen. En `helpers do`, agregue este método `create_check_run`:
You'll add this new method as a [Sinatra helper](https://github.com/sinatra/sinatra#helpers) in case you want other routes to use it too. Under `helpers do`, add this `create_check_run` method:
``` ruby
# Create a new check run with the status queued
@@ -160,17 +154,17 @@ def create_check_run
end
```
Este código llama al punto de conexión "[Crear una ejecución de comprobación](/rest/reference/checks#create-a-check-run)" mediante el [método create_check_run](https://rdoc.info/gems/octokit/Octokit%2FClient%2FChecks:create_check_run).
This code calls the "[Create a check run](/rest/reference/checks#create-a-check-run)" endpoint using the [create_check_run method](https://rdoc.info/gems/octokit/Octokit%2FClient%2FChecks:create_check_run).
Para crear una ejecución de comprobación, solo se requieren dos parámetros de entrada: `name` y `head_sha`. Usaremos [RuboCop](https://rubocop.readthedocs.io/en/latest/) para implementar la prueba de CI más adelante en este inicio rápido, por eso se usa aquí el nombre "Octo RuboCop", pero puede elegir el nombre que quiera para la ejecución de comprobación.
To create a check run, only two input parameters are required: `name` and `head_sha`. We will use [RuboCop](https://rubocop.readthedocs.io/en/latest/) to implement the CI test later in this quickstart, which is why the name "Octo RuboCop" is used here, but you can choose any name you'd like for the check run.
Ahora mismo, solo estás proporcionando los parámetros requeridos para echar a andar la funcionalidad básica, pero actualizarás la ejecución de verificación más adelante mientras recolectes más información acerca de la ejecución de verificación. De forma predeterminada, GitHub establece `status` en `queued`.
You're only supplying the required parameters now to get the basic functionality working, but you'll update the check run later as you collect more information about the check run. By default, GitHub sets the `status` to `queued`.
GitHub crea una ejecución de comprobación para un SHA de confirmación específico, por lo que `head_sha` es un parámetro necesario. Puedes encontrar el SHA de la confirmación en la carga útil del webhook. Aunque solo va a crear una ejecución de comprobación para el evento `check_suite` en este momento, es bueno saber que `head_sha` se incluye tanto en los objetos `check_suite` como `check_run` en las cargas de eventos.
GitHub creates a check run for a specific commit SHA, which is why `head_sha` is a required parameter. You can find the commit SHA in the webhook payload. Although you're only creating a check run for the `check_suite` event right now, it's good to know that the `head_sha` is included in both the `check_suite` and `check_run` objects in the event payloads.
En el código anterior, se usa el [operador ternario](https://ruby-doc.org/core-2.3.0/doc/syntax/control_expressions_rdoc.html#label-Ternary+if), que funciona como una instrucción `if/else`, para comprobar si la carga contiene un objeto `check_run`. Si lo contiene, debe leer `head_sha` desde el objeto `check_run`; de lo contrario, lo leerá desde el objeto `check_suite`.
In the code above, you're using the [ternary operator](https://ruby-doc.org/core-2.3.0/doc/syntax/control_expressions_rdoc.html#label-Ternary+if), which works like an `if/else` statement, to check if the payload contains a `check_run` object. If it does, you read the `head_sha` from the `check_run` object, otherwise you read it from the `check_suite` object.
Para probar este código, reinicia el servidor desde tu terminal:
To test this code, restart the server from your terminal:
```shell
$ ruby template_server.rb
@@ -178,21 +172,21 @@ $ ruby template_server.rb
{% data reusables.apps.sinatra_restart_instructions %}
Ahora abre una solicitud de extracción en el repositorio en donde instalaste tu app. Tu app deberá responder creando una ejecución de verificación en tu solicitud de cambios. Haga clic en la pestaña **Checks** (Comprobaciones) y verá algo parecido a esto:
Now open a pull request in the repository where you installed your app. Your app should respond by creating a check run on your pull request. Click on the **Checks** tab, and you should see something like this:
![Ejecución de verificación en cola](/assets/images/github-apps/github_apps_queued_check_run.png)
![Queued check run](/assets/images/github-apps/github_apps_queued_check_run.png)
Si ve otras aplicaciones en la pestaña Checks (Comprobaciones), significa que tiene otras aplicaciones instaladas en el repositorio que tienen acceso de **lectura y escritura** a las comprobaciones y están suscritas a los eventos **Check suite** (Conjunto de comprobaciones) y **Check run** (Ejecución de comprobación).
If you see other apps in the Checks tab, it means you have other apps installed on your repository that have **Read & write** access to checks and are subscribed to **Check suite** and **Check run** events.
Magnífico. Le has dicho a GitHub que cree una ejecución de verificación. Puede ver que el estado de la ejecución de comprobación está establecido en `queued` junto a un icono amarillo. A continuación, deberás esperar a que GitHub cree la ejecución de verificación y actualice su estado.
Great! You've told GitHub to create a check run. You can see the check run status is set to `queued` next to a yellow icon. Next, you'll want to wait for GitHub to create the check run and update its status.
## Paso 1.4. Actualizar una ejecución de verificación
## Step 1.4. Updating a check run
Cuando se ejecuta el método `create_check_run`, pide a GitHub que cree una nueva ejecución de comprobación. Cuando GitHub termine de crear la ejecución de comprobación, recibirá el evento de webhook `check_run` con la acción `created`. Este evento es tu señal para comenzar a ejecutar la verificación.
When your `create_check_run` method runs, it asks GitHub to create a new check run. When GitHub finishes creating the check run, you'll receive the `check_run` webhook event with the `created` action. That event is your signal to begin running the check.
Le recomendamos que actualice el controlador de eventos para buscar la acción `created`. Mientras actualiza el controlador de eventos, puede agregar un condicional para la acción `rerequested`. Cuando alguien vuelve a ejecutar una sola prueba en GitHub, al hacer clic en el botón "Re-run" (Volver a ejecutar), GitHub envía el evento de ejecución de comprobación con el estado `rerequested` a la aplicación. Si una ejecución de comprobación tiene el estado `rerequested`, comience de nuevo todo el proceso y cree una nueva ejecución de comprobación.
You'll want to update your event handler to look for the `created` action. While you're updating the event handler, you can add a conditional for the `rerequested` action. When someone re-runs a single test on GitHub by clicking the "Re-run" button, GitHub sends the `rerequested` check run event to your app. When a check run is `rerequested`, you'll want to start the process all over and create a new check run.
Para incluir una condición para el evento `check_run` en la ruta `post '/event_handler'`, agregue el código siguiente en `case request.env['HTTP_X_GITHUB_EVENT']`:
To include a condition for the `check_run` event in the `post '/event_handler'` route, add the following code under `case request.env['HTTP_X_GITHUB_EVENT']`:
``` ruby
when 'check_run'
@@ -207,13 +201,13 @@ when 'check_run'
end
```
GitHub envía todos los eventos de las ejecuciones de comprobación con el estado `created` a todas las aplicaciones instaladas en un repositorio que tengan los permisos de comprobación necesarios. Esto significa que tu app recibirá las ejecuciones de verificación que creen otras apps. Una ejecución de comprobación `created` es un poco diferente de un conjunto de comprobaciones `requested` o `rerequested`, y GitHub solo la envía a las aplicaciones a las que se solicita que ejecuten una comprobación. El código anterior busca la ID de aplicación de la ejecución de verificación. Esto filtra todas las ejecuciones de verificación para otras apps en el repositorio.
GitHub sends all events for `created` check runs to every app installed on a repository that has the necessary checks permissions. That means that your app will receive check runs created by other apps. A `created` check run is a little different from a `requested` or `rerequested` check suite, which GitHub sends only to apps that are being requested to run a check. The code above looks for the check run's application ID. This filters out all check runs for other apps on the repository.
Después, escribirá el método `initiate_check_run`, que es donde actualizará el estado de la ejecución de comprobación y donde se preparará para iniciar la prueba de CI.
Next you'll write the `initiate_check_run` method, which is where you'll update the check run status and prepare to kick off your CI test.
En esta sección, aún no va a lanzar la prueba de CI, pero le mostraremos cómo actualizar el estado de la ejecución de comprobación de `queued` a `pending` y, después, de `pending` a `completed` para ver el flujo general de una ejecución de comprobación. En la [parte 2: "Creación de la prueba de CI de Octo RuboCop"](#part-2-creating-the-octo-rubocop-ci-test), agregará el código que ejecuta realmente la prueba de CI.
In this section, you're not going to kick off the CI test yet, but you'll walk through how to update the status of the check run from `queued` to `pending` and then from `pending` to `completed` to see the overall flow of a check run. In "[Part 2: Creating the Octo RuboCop CI test](#part-2-creating-the-octo-rubocop-ci-test)," you'll add the code that actually performs the CI test.
Vamos a crear el método `initiate_check_run` y a actualizar el estado de la ejecución de comprobación. Agrega el siguiente código a la sección de ayudantes:
Let's create the `initiate_check_run` method and update the status of the check run. Add the following code to the helpers section:
``` ruby
# Start the CI process
@@ -242,53 +236,53 @@ def initiate_check_run
end
```
El código anterior llama al punto de conexión de API "[Actualizar una ejecución de comprobación](/rest/reference/checks#update-a-check-run)" mediante el [método Octokit `update_check_run`](https://rdoc.info/gems/octokit/Octokit%2FClient%2FChecks:update_check_run) para actualizar la ejecución de comprobación que ya ha creado.
The code above calls the "[Update a check run](/rest/reference/checks#update-a-check-run)" API endpoint using the [`update_check_run` Octokit method](https://rdoc.info/gems/octokit/Octokit%2FClient%2FChecks:update_check_run) to update the check run that you already created.
Te explicamos lo que hace este código. En primer lugar, actualiza el estado de la ejecución de comprobación a `in_progress` y establece implícitamente la hora de `started_at` en la hora actual. En la [parte 2](#part-2-creating-the-octo-rubocop-ci-test) de este inicio rápido, agregará código que inicia una prueba de CI real en `***** RUN A CI TEST *****`. Por el momento, dejarás esta sección como un marcador de posición para que el código subsecuente simplemente estimule el éxito del proceso de IC y que todas las pruebas pasen. Por último, el código vuelve a actualizar el estado de la ejecución de comprobación a `completed`.
Here's what this code is doing. First, it updates the check run's status to `in_progress` and implicitly sets the `started_at` time to the current time. In [Part 2](#part-2-creating-the-octo-rubocop-ci-test) of this quickstart, you'll add code that kicks off a real CI test under `***** RUN A CI TEST *****`. For now, you'll leave that section as a placeholder, so the code that follows it will just simulate that the CI process succeeds and all tests pass. Finally, the code updates the status of the check run again to `completed`.
Observará que, en la documentación de "[Actualizar una ejecución de comprobación](/rest/reference/checks#update-a-check-run)", cuando se proporciona un estado `completed`, se requieren los parámetros `conclusion` y `completed_at`. El objeto `conclusion` resume el resultado de una ejecución de comprobación y puede ser `success`, `failure``neutral`, `cancelled`, `timed_out` o `action_required`. Por tanto, establecerá el estado de la conclusión en `success`, la hora de `completed_at` en la hora actual y el estado en `completed`.
You'll notice in the "[Update a check run](/rest/reference/checks#update-a-check-run)" docs that when you provide a status of `completed`, the `conclusion` and `completed_at` parameters are required. The `conclusion` summarizes the outcome of a check run and can be `success`, `failure`, `neutral`, `cancelled`, `timed_out`, or `action_required`. You'll set the conclusion to `success`, the `completed_at` time to the current time, and the status to `completed`.
También puedes proporcionar más detalles sobre lo que está haciendo tu verificación, pero eso lo abordaremos en la siguiente sección. Vamos a volver a probar este código ejecutando `template_server.rb` de nuevo:
You could also provide more details about what your check is doing, but you'll get to that in the next section. Let's test this code again by re-running `template_server.rb`:
```shell
$ ruby template_server.rb
```
Vaya a la solicitud de incorporación de cambios abierta y haga clic en la pestaña **Checks** (Comprobaciones). Luego, haga clic en el botón "Re-run all" (Volver a ejecutar todo) situado en la esquina superior izquierda. Debería ver que el estado de la ejecución de comprobación pasa de `pending` a `in_progress` y termina siendo `success`:
Head over to your open pull request and click the **Checks** tab. Click the "Re-run all" button in the upper left corner. You should see the check run move from `pending` to `in_progress` and end with `success`:
![Ejecución de verificación completada](/assets/images/github-apps/github_apps_complete_check_run.png)
![Completed check run](/assets/images/github-apps/github_apps_complete_check_run.png)
## Parte 2. Crear la prueba de IC de Octo RuboCop
## Part 2. Creating the Octo RuboCop CI test
[RuboCop](https://rubocop.readthedocs.io/en/latest/) es un linter de código de Ruby y un formateador. Comprueba el código de Ruby para asegurarse de que cumple con la "[Guía de estilo de Ruby](https://github.com/rubocop-hq/ruby-style-guide)". RuboCop tiene tres funciones prncipales:
[RuboCop](https://rubocop.readthedocs.io/en/latest/) is a Ruby code linter and formatter. It checks Ruby code to ensure that it complies with the "[Ruby Style Guide](https://github.com/rubocop-hq/ruby-style-guide)." RuboCop has three primary functions:
* Limpiar para revisar el estilo del código
* Formateo del código
* Reemplazar las funcionalidades nativas de linting de Ruby mediante `ruby -w`
* Linting to check code style
* Code formatting
* Replaces the native Ruby linting capabilities using `ruby -w`
Ahora que tienes la interface que se ha creado para recibir eventos de la API de verificaciones y para crear ejecuciones de verificción, puedes crear una ejecución de verificación que implemente una prueba de IC.
Now that you've got the interface created to receive Checks API events and create check runs, you can create a check run that implements a CI test.
Tu app ejecutará RuboCop en el servidor de IC y creará ejecuciones de verificación (en este caso, pruebas de IC) que reporten los resultados que RuboCop reporta a GitHub.
Your app will run RuboCop on the CI server and create check runs (CI tests in this case) that report the results that RuboCop reports to GitHub.
La API de Verificaciones te permite reportar detalles enriquecidos acerca de cada ejecución de verificación, incluyendo los estados, imágenes, resúmenes, y las acciones solicitadas.
The Checks API allows you to report rich details about each check run, including statuses, images, summaries, annotations, and requested actions.
Las anotaciones son información acerca de líneas de código específicas en un repositorio. Una anotación te permite identificar y visualizar las partes exactas del código para las cuales quieres mostrar información adicional. Esa puede ser cualquier información: por ejemplo, un comentario, un error, o una advertencia. Esta guía rápida utiliza anotaciones para visualizar los errores de RuboCop.
Annotations are information about specific lines of code in a repository. An annotation allows you to pinpoint and visualize the exact parts of the code you'd like to show additional information for. That information can be anything: for example, a comment, an error, or a warning. This quickstart uses annotations to visualize RuboCop errors.
Para aprovechar las acciones solicitadas, los desarrolladores de aplicaciones pueden crear botones en la pestaña **Checks** (Comprobaciones) de las solicitudes de incorporación de cambios. Cuando alguien hace clic en uno de estos botones, se envía un evento `requested_action` `check_run` a la aplicación de GitHub. El desarrollador de la app puede configurar íntegramente la acción que ésta toma. Esta guía de inicio rápido te mostrará cómo agregar un botón que permitirá a los usuarios solicitar que RuboCop corrija los errores que encuentre. RuboCop admite la corrección automática de errores mediante el uso de una opción de línea de comandos, por lo que configurará `requested_action` para aprovechar esta opción.
To take advantage of requested actions, app developers can create buttons in the **Checks** tab of pull requests. When someone clicks one of these buttons, the click sends a `requested_action` `check_run` event to the GitHub App. The action that the app takes is completely configurable by the app developer. This quickstart will walk you through adding a button that allows users to request that RuboCop fix the errors it finds. RuboCop supports automatically fixing errors using a command-line option, and you'll configure the `requested_action` to take advantage of this option.
Comencemos. Estos son los pasos que tendrás que completar en esta sección:
Let's get started! These are the steps you'll complete in this section:
1. [Adición de un archivo de Ruby](#step-21-adding-a-ruby-file)
1. [Clonación del repositorio](#step-22-cloning-the-repository)
1. [Ejecución de RuboCop](#step-23-running-rubocop)
1. [Recopilación de errores de RuboCop](#step-24-collecting-rubocop-errors)
1. [Actualización de la ejecución de comprobación con resultados de la prueba de CI](#step-25-updating-the-check-run-with-ci-test-results)
1. [Corrección automática de los errores de RuboCop](#step-26-automatically-fixing-rubocop-errors)
1. [Sugerencias de seguridad](#step-27-security-tips)
1. [Adding a Ruby file](#step-21-adding-a-ruby-file)
1. [Cloning the repository](#step-22-cloning-the-repository)
1. [Running RuboCop](#step-23-running-rubocop)
1. [Collecting RuboCop errors](#step-24-collecting-rubocop-errors)
1. [Updating the check run with CI test results](#step-25-updating-the-check-run-with-ci-test-results)
1. [Automatically fixing RuboCop errors](#step-26-automatically-fixing-rubocop-errors)
1. [Security tips](#step-27-security-tips)
## Paso 2.1. Agregar un archivo de Ruby
## Step 2.1. Adding a Ruby file
Puedes pasar archivos específicos o directorios completos para que los revise RuboCop. En esta guía de inicio rápido, ejecutarás a RuboCop en un directorio completo. Ya que RuboCop únicamente revisa el código de Ruby, querrás que por lo menos un archivo de Ruby en tu repositorio contenga errores. El archivo de ejemplo que te proporcionamos a continuación contiene unos cuantos errores. Agregue este archivo de Ruby de ejemplo al repositorio donde está instalada la aplicación (asegúrese de asignar un nombre al archivo con una extensión `.rb`, como `myfile.rb`):
You can pass specific files or entire directories for RuboCop to check. In this quickstart, you'll run RuboCop on an entire directory. Because RuboCop only checks Ruby code, you'll want at least one Ruby file in your repository that contains errors. The example file provided below contains a few errors. Add this example Ruby file to the repository where your app is installed (make sure to name the file with an `.rb` extension, as in `myfile.rb`):
```ruby
# The Octocat class tells you about different breeds of Octocat
@@ -310,31 +304,31 @@ m = Octocat.new("Mona", "cat", "octopus")
m.display
```
## Paso 2.2. Clonación del repositorio
## Step 2.2. Cloning the repository
RuboCop se encuentra disponible como una utilidad de línea de comandos. Eso significa que tu GitHub App necesitará clonar una copia local del repositorio en el servidor de IC para que RuboCop analice los archivos. Para ejecutar operaciones de Git en la aplicación de Ruby, puede usar la gema [ruby-git](https://github.com/ruby-git/ruby-git).
RuboCop is available as a command-line utility. That means your GitHub App will need to clone a local copy of the repository on the CI server so RuboCop can parse the files. To run Git operations in your Ruby app, you can use the [ruby-git](https://github.com/ruby-git/ruby-git) gem.
El elemento `Gemfile` del repositorio `building-a-checks-api-ci-server` ya incluye la gema ruby-git y se instaló cuando se ejecutó `bundle install` en los [pasos de requisitos previos](#prerequisites). Para usar la gema, agregue este código en la parte superior del archivo `template_server.rb`:
The `Gemfile` in the `building-a-checks-api-ci-server` repository already includes the ruby-git gem, and you installed it when you ran `bundle install` in the [prerequisite steps](#prerequisites). To use the gem, add this code to the top of your `template_server.rb` file:
``` ruby
require 'git'
```
Tu app necesita el permiso de lectura para "contenido de repositorio" si quieres que clone un repositorio. Más adelante en esta guía de inicio rápido, necesitarás cargar contenido a GitHub, lo cual requiere el permiso de escritura. Continúe y establezca ahora el permiso de "Repository contents" (Contenido del repositorio) de la aplicación en **Read & write** (Lectura y escritura) para que no tenga que actualizarlo de nuevo más tarde. Para actualizar los permisos de tu app:
Your app needs read permission for "Repository contents" to clone a repository. Later in this quickstart, you'll need to push contents to GitHub, which requires write permission. Go ahead and set your app's "Repository contents" permission to **Read & write** now so you don't need to update it again later. To update your app's permissions:
1. Seleccione la aplicación en la [página de configuración de la aplicación](https://github.com/settings/apps) y haga clic en **Permissions & Webhooks** (Permisos y webhooks) en la barra lateral.
1. En la sección "Permissions" (Permisos), busque "Repository contents" (Contenido del repositorio) y, al lado, seleccione **Read & write** (Lectura y escritura) en la lista desplegable "Access" (Acceso).
1. Select your app from the [app settings page](https://github.com/settings/apps) and click **Permissions & Webhooks** in the sidebar.
1. In the "Permissions" section, find "Repository contents", and select **Read & write** in the "Access" dropdown next to it.
{% data reusables.apps.accept_new_permissions_steps %}
Para clonar un repositorio mediante los permisos de la aplicación de GitHub, puede usar el token de instalación de la aplicación (`x-access-token:<token>`) que se muestra en el ejemplo siguiente:
To clone a repository using your GitHub App's permissions, you can use the app's installation token (`x-access-token:<token>`) shown in the example below:
```shell
git clone https://x-access-token:<token>@github.com/<owner>/<repo>.git
```
El código anterior clona un repositorio a través de HTTP. Éste necesita el nombre íntegro del repositorio, lo cual incluye al propietario del mismo (usuario u organización) y el nombre de éste. Por ejemplo, el nombre completo del repositorio [Hello-World de octocat](https://github.com/octocat/Hello-World) es `octocat/hello-world`.
The code above clones a repository over HTTP. It requires the full repository name, which includes the repository owner (user or organization) and the repository name. For example, the [octocat Hello-World](https://github.com/octocat/Hello-World) repository has a full name of `octocat/hello-world`.
Una vez que la aplicación clone el repositorio, debe extraer los cambios de código más recientes y una referencia específica de Git. El código para hacer todo esto se ajustará perfectamente a su propio método. Para llevar a cabo estas operaciones, el método necesita el nombre y nombre completo del repositorio y la ref de salida. La ref puede ser el SHA de una confirmación, una rama, o una etiqueta. Agregue el siguiente método nuevo a la sección del método del asistente en `template_server.rb`:
After your app clones the repository, it needs to pull the latest code changes and check out a specific Git ref. The code to do all of this will fit nicely into its own method. To perform these operations, the method needs the name and full name of the repository and the ref to checkout. The ref can be a commit SHA, branch, or tag. Add the following new method to the helper method section in `template_server.rb`:
``` ruby
# Clones the repository to the current working directory, updates the
@@ -353,11 +347,11 @@ def clone_repository(full_repo_name, repository, ref)
end
```
El código anterior usa la gema `ruby-git` para clonar el repositorio mediante el token de instalación de la aplicación. Este código clona el código en el mismo directorio que `template_server.rb`. Para ejecutar los comandos de Git en el repositorio, el código necesita cambiar el directorio del repositorio. Antes de cambiar los directorios, el código almacena el directorio de trabajo actual en una variable (`pwd`) para recordar a dónde debe volver antes de salir del método `clone_repository`.
The code above uses the `ruby-git` gem to clone the repository using the app's installation token. This code clones the code in the same directory as `template_server.rb`. To run Git commands in the repository, the code needs to change into the repository directory. Before changing directories, the code stores the current working directory in a variable (`pwd`) to remember where to return before exiting the `clone_repository` method.
En el directorio del repositorio, este código captura y combina los cambios más recientes (`@git.pull`), extrae la referencia (`@git.checkout(ref)`) y, después, vuelve a cambiar el directorio al directorio de trabajo original (`pwd`).
From the repository directory, this code fetches and merges the latest changes (`@git.pull`), checks out the ref (`@git.checkout(ref)`), then changes the directory back to the original working directory (`pwd`).
Ahora tiene un método que clona un repositorio y extrae una referencia. A continuación, debe agregar código para obtener los parámetros de entrada necesarios y llamar al nuevo método `clone_repository`. Agregue el código siguiente bajo el comentario `***** RUN A CI TEST *****` en el método del asistente `initiate_check_run`:
Now you've got a method that clones a repository and checks out a ref. Next, you need to add code to get the required input parameters and call the new `clone_repository` method. Add the following code under the `***** RUN A CI TEST *****` comment in your `initiate_check_run` helper method:
``` ruby
# ***** RUN A CI TEST *****
@@ -368,13 +362,13 @@ head_sha = @payload['check_run']['head_sha']
clone_repository(full_repo_name, repository, head_sha)
```
El código anterior obtiene el nombre completo del repositorio y el SHA de encabezado de la confirmación desde la carga útil del webhook `check_run`.
The code above gets the full repository name and the head SHA of the commit from the `check_run` webhook payload.
## Paso 2.3. Ejecutar RuboCop
## Step 2.3. Running RuboCop
Magnífico. Estás clonando el repositorio y creando ejecuciones de verificación al utilizar tu servidor de IC. Ahora se centrará en los detalles más minuciosos del [linter RuboCop](https://docs.rubocop.org/rubocop/usage/basic_usage.html#code-style-checker) y de las [anotaciones de la API de comprobaciones](/rest/reference/checks#create-a-check-run).
Great! You're cloning the repository and creating check runs using your CI server. Now you'll get into the nitty gritty details of the [RuboCop linter](https://docs.rubocop.org/rubocop/usage/basic_usage.html#code-style-checker) and [Checks API annotations](/rest/reference/checks#create-a-check-run).
El siguiente código ejecuta RuboCop y guarda los errores de estilo en el código con un formato JSON. Agregue este código debajo de la llamada a `clone_repository` que agregó en el [paso anterior](#step-22-cloning-the-repository) y encima del código que actualiza la ejecución de comprobación para completarse.
The following code runs RuboCop and saves the style code errors in JSON format. Add this code below the call to `clone_repository` you added in the [previous step](#step-22-cloning-the-repository) and above the code that updates the check run to complete.
``` ruby
# Run RuboCop on all files in the repository
@@ -384,23 +378,23 @@ logger.debug @report
@output = JSON.parse @report
```
Este código utiliza RuboCop en todos los archivos dentro del directorio del repositorio. La opción `--format json` es una forma práctica de guardar una copia de los resultados de linting en un formato analizable para una máquina. Consulte la [documentación sobre RuboCop](https://docs.rubocop.org/rubocop/formatters.html#json-formatter) para obtener más información y un ejemplo del formato JSON.
The code above runs RuboCop on all files in the repository's directory. The option `--format json` is a handy way to save a copy of the linting results in a machine-parsable format. See the [RuboCop docs](https://docs.rubocop.org/rubocop/formatters.html#json-formatter) for details and an example of the JSON format.
Dado que este código almacena los resultados de RuboCop en una variable `@report`, puede eliminar la salida del repositorio con seguridad. Este código también analiza el JSON para que pueda acceder fácilmente a las claves y los valores de su aplicación de GitHub mediante la variable `@output`.
Because this code stores the RuboCop results in a `@report` variable, it can safely remove the checkout of the repository. This code also parses the JSON so you can easily access the keys and values in your GitHub App using the `@output` variable.
{% note %}
**Nota:** El comando usado para quitar el repositorio (`rm -rf`) no se puede deshacer. Consulte el [paso 2.7. Sugerencias de seguridad](#step-27-security-tips) para aprender a comprobar los webhooks en busca de comandos malintencionados insertados que podrían usarse para quitar un directorio diferente del que quiere quitar la aplicación. Por ejemplo, si un actor malintencionado envía un webhook con el nombre de repositorio `./`, la aplicación quitará el directorio raíz. 😱 Si por alguna razón _no_ usa el método `verify_webhook_signature` (que se incluye en `template_server.rb`) para validar al emisor del webhook, asegúrese de revisar que el nombre del repositorio es válido.
**Note:** The command used to remove the repository (`rm -rf`) cannot be undone. See [Step 2.7. Security tips](#step-27-security-tips) to learn how to check webhooks for injected malicious commands that could be used to remove a different directory than intended by your app. For example, if a bad actor sent a webhook with the repository name `./`, your app would remove the root directory. 😱 If for some reason you're _not_ using the method `verify_webhook_signature` (which is included in `template_server.rb`) to validate the sender of the webhook, make sure you check that the repository name is valid.
{% endnote %}
Puedes probar que este código funcione y ver los errores que reporta RuboCop en la salida de depuración de tu servidor. Vuelva a iniciar el servidor `template_server.rb` y cree una nueva solicitud de incorporación de cambios en el repositorio donde va a probar la aplicación:
You can test that this code works and see the errors reported by RuboCop in your server's debug output. Start up the `template_server.rb` server again and create a new pull request in the repository where you're testing your app:
```shell
$ ruby template_server.rb
```
Deberías ver los errores de limpieza en la salida de depuración, aunque no se imprimen con formato. Puede usar una herramienta web como un [formateador de JSON](https://jsonformatter.org/) para dar formato a la salida JSON, como en esta salida de error de linting con formato:
You should see the linting errors in the debug output, although they aren't printed with formatting. You can use a web tool like [JSON formatter](https://jsonformatter.org/) to format your JSON output like this formatted linting error output:
```json
{
@@ -456,17 +450,17 @@ Deberías ver los errores de limpieza en la salida de depuración, aunque no se
}
```
## Paso 2.4. Recolectar los errores de RuboCop
## Step 2.4. Collecting RuboCop errors
La variable `@output` contiene los resultados JSON analizados del informe de RuboCop. Tal como se ha mostrado anteriormente, los resultados contienen una sección `summary` que el código puede usar para determinar rápidamente si hay algún error. El código siguiente establecerá el estado de la conclusión de la ejecución de comprobación en `success` cuando no se notifiquen errores. RuboCop notifica los errores para cada archivo de la matriz `files`, así que, si hay errores, necesitará extraer algunos datos del objeto de archivo.
The `@output` variable contains the parsed JSON results of the RuboCop report. As shown above, the results contain a `summary` section that your code can use to quickly determine if there are any errors. The following code will set the check run conclusion to `success` when there are no reported errors. RuboCop reports errors for each file in the `files` array, so if there are errors, you'll need to extract some data from the file object.
La API de Verificaciones te permite crear anotaciones para líneas de código específicas. Cuando creas o actualizas una ejecución de verificación, puedes agregar anotaciones. En este inicio rápido, va a [actualizar la ejecución de comprobación](/rest/reference/checks#update-a-check-run) con anotaciones.
The Checks API allows you to create annotations for specific lines of code. When you create or update a check run, you can add annotations. In this quickstart you are [updating the check run](/rest/reference/checks#update-a-check-run) with annotations.
La API de Verificaciones limita la cantidad de anotaciones a un máximo de 50 por solilcitud de API. Para crear más de 50 anotaciones, debe realizar varias solicitudes al punto de conexión [Actualizar una ejecución de comprobación](/rest/reference/checks#update-a-check-run). Por ejemplo, para crear 105 anotaciones, deberá llamar al punto de conexión [Actualizar una ejecución de comprobación](/rest/reference/checks#update-a-check-run) tres veces. Las primeras dos contarían por 50 anotaciones cada una, y la tercera incluiría las cinco restantes. Cada vez que actualices la ejecución de verificación, se adjuntan las anotaciones a la lista de anotaciones existente para la ejecución de verificación.
The Checks API limits the number of annotations to a maximum of 50 per API request. To create more than 50 annotations, you have to make multiple requests to the [Update a check run](/rest/reference/checks#update-a-check-run) endpoint. For example, to create 105 annotations you'd need to call the [Update a check run](/rest/reference/checks#update-a-check-run) endpoint three times. The first two requests would each have 50 annotations, and the third request would include the five remaining annotations. Each time you update the check run, annotations are appended to the list of annotations that already exist for the check run.
Una ejecución de verificación espera encontrar las anotaciones en una matriz de objetos. Cada objeto de anotación debe incluir los parámetros `path`, `start_line`, `end_line`, `annotation_level` y `message`. RuboCop también proporciona los parámetros adicionales `start_column`y `end_column`, por lo que puede incluirlos en la anotación. Las anotaciones solo admiten los parámetros `start_column` y `end_column` en la misma línea. Para más información, consulte la documentación de referencia del [objeto `annotations`](/rest/reference/checks#annotations-object-1).
A check run expects annotations as an array of objects. Each annotation object must include the `path`, `start_line`, `end_line`, `annotation_level`, and `message`. RuboCop provides the `start_column` and `end_column` too, so you can include those optional parameters in the annotation. Annotations only support `start_column` and `end_column` on the same line. See the [`annotations` object](/rest/reference/checks#annotations-object-1) reference documentation for details.
Extraerás la información requerida de RuboCop que necesites para crear cada anotación. Agregue el código siguiente al código que ha agregado en la [sección anterior](#step-23-running-rubocop):
You'll extract the required information from RuboCop needed to create each annotation. Append the following code to the code you added in the [previous section](#step-23-running-rubocop):
``` ruby
annotations = []
@@ -521,21 +515,21 @@ else
end
```
Este código limita la cantidad total de anotaciones a 50. Pero puedes modificarlo para actualizar la ejecución de verificación para cada lote de 50 anotaciones. El código anterior incluye la variable `max_annotations`, la cual establece el límite en 50 y se usa en el bucle que recorre en iteración las infracciones.
This code limits the total number of annotations to 50. But you can modify this code to update the check run for each batch of 50 annotations. The code above includes the variable `max_annotations` that sets the limit to 50, which is used in the loop that iterates through the offenses.
Cuando `offense_count` es cero, el resultado de la prueba de CI es `success`. Si hay errores, este código establece la conclusión en `neutral` para evitar que se apliquen estrictamente los errores de los linters de código. Pero puede cambiar la conclusión a `failure` si quiere asegurarse de que se produce un error en el conjunto de comprobaciones cuando hay errores de linting.
When the `offense_count` is zero, the CI test is a `success`. If there are errors, this code sets the conclusion to `neutral` in order to prevent strictly enforcing errors from code linters. But you can change the conclusion to `failure` if you would like to ensure that the check suite fails when there are linting errors.
Cuando se notifican errores, el código anterior recorre en iteración la matriz `files` del informe de RuboCop. Para cada archivo, extrae la ruta de acceso del mismo y establece el nivel de anotación en `notice`. Puede ir aún más allá y establecer niveles de advertencia específicos para cada tipo de [RuboCop Cop](https://docs.rubocop.org/rubocop/cops.html), pero para simplificar las cosas en este inicio rápido, todos los errores se establecen en un nivel `notice`.
When errors are reported, the code above iterates through the `files` array in the RuboCop report. For each file, it extracts the file path and sets the annotation level to `notice`. You could go even further and set specific warning levels for each type of [RuboCop Cop](https://docs.rubocop.org/rubocop/cops.html), but to keep things simpler in this quickstart, all errors are set to a level of `notice`.
Este código también recorre en iteración cada error de la matriz `offenses` y recopila la ubicación del mensaje de error y de la infracción. Después de extraer la información necesaria, el código crea una anotación para cada error y la almacena en la matriz `annotations`. Dado que las anotaciones solo admiten columnas de inicio y finalización en la misma línea, los elementos `start_column` y `end_column` solo se agregan al objeto `annotation` si los valores iniciales y finales de la línea son los mismos.
This code also iterates through each error in the `offenses` array and collects the location of the offense and error message. After extracting the information needed, the code creates an annotation for each error and stores it in the `annotations` array. Because annotations only support start and end columns on the same line, `start_column` and `end_column` are only added to the `annotation` object if the start and end line values are the same.
Este código aún no crea una anotación para la ejecución de verificación. Agregarás dicho código en la siguiente sección.
This code doesn't yet create an annotation for the check run. You'll add that code in the next section.
## Paso 2.5. Actualizar la ejecución de verificación con los resultados de la prueba de IC
## Step 2.5. Updating the check run with CI test results
Cada ejecución de comprobación de GitHub contiene un objeto `output` que incluye los parámetros `title`, `summary`, `text`, `annotations` y `images`. `summary` y `title` son los únicos parámetros necesarios para `output`, pero por sí solos no dan mucha información, por lo que en esta guía de inicio rápido también se agregan `text` y `annotations`. Este código no agrega una imagen, pero ¡no dudes en agregarla si así lo deseas!
Each check run from GitHub contains an `output` object that includes a `title`, `summary`, `text`, `annotations`, and `images`. The `summary` and `title` are the only required parameters for the `output`, but those alone don't offer much detail, so this quickstart adds `text` and `annotations` too. The code here doesn't add an image, but feel free to add one if you'd like!
En el caso de `summary`, en este ejemplo se usa la información de resumen de RuboCop y se agregan algunas líneas nuevas (`\n`) para dar formato a la salida. Puede personalizar la información que agrega al parámetro `text`, pero en este ejemplo se incluye en el parámetro `text` la versión de RuboCop. Para establecer los parámetros `summary` y `text`, agregue este código al código que ha agregado en la [sección anterior](#step-24-collecting-rubocop-errors):
For the `summary`, this example uses the summary information from RuboCop and adds some newlines (`\n`) to format the output. You can customize what you add to the `text` parameter, but this example sets the `text` parameter to the RuboCop version. To set the `summary` and `text`, append this code to the code you added in the [previous section](#step-24-collecting-rubocop-errors):
``` ruby
# Updated check run summary and text parameters
@@ -543,7 +537,7 @@ summary = "Octo RuboCop summary\n-Offense count: #{@output['summary']['offense_c
text = "Octo RuboCop version: #{@output['metadata']['rubocop_version']}"
```
Ahora tienes toda la información que necesitas para actualizar tu ejecución de verificación. En la [primera mitad de este inicio rápido](#step-14-updating-a-check-run), ha agregado este código para establecer el estado de la ejecución de comprobación en `success`:
Now you've got all the information you need to update your check run. In the [first half of this quickstart](#step-14-updating-a-check-run), you added this code to set the status of the check run to `success`:
``` ruby
# Mark the check run as complete!
@@ -556,7 +550,7 @@ Ahora tienes toda la información que necesitas para actualizar tu ejecución de
)
```
Deberá actualizar ese código para usar la variable `conclusion` establecida en función de los resultados de RuboCop (en `success` o `neutral`). Puedes actualizar el código con lo siguiente:
You'll need to update that code to use the `conclusion` variable you set based on the RuboCop results (to `success` or `neutral`). You can update the code with the following:
``` ruby
# Mark the check run as complete! And if there are warnings, share them.
@@ -580,48 +574,48 @@ Deberá actualizar ese código para usar la variable `conclusion` establecida en
)
```
Ahora que estás configurando una conclusión con base en el estado de la prueba de IC y has agregado la salida de los resultados de RuboCop, ¡has creado una prueba de IC! ¡Enhorabuena! 🙌
Now that you're setting a conclusion based on the status of the CI test and you've added the output from the RuboCop results, you've created a CI test! Congratulations. 🙌
El código anterior también agrega una característica al servidor de CI denominada [acciones solicitadas](https://developer.github.com/changes/2018-05-23-request-actions-on-checks/) por medio del objeto `actions`. {% ifversion fpt or ghec %}(Tenga en cuenta que esto no está relacionado con [Acciones de GitHub](/actions)).{% endif %}Las acciones solicitadas agregan un botón en la pestaña **Checks** (Comprobaciones) de GitHub que permite a los usuarios solicitar que la ejecución de comprobación realice acciones adicionales. Tu app puede configurar la acción adicional en su totalidd. Por ejemplo, ya que RuboCop tiene una característica para corregir automáticamente los errores que encuentre en el código de Ruby, tu servidor de IC puede utilizar un botón de acciones solicitadas para ayudar a que las personas soliciten correcciónes de errores automáticas. Cuando alguien hace clic en el botón, la aplicación recibe el evento `check_run` con una acción `requested_action`. Cada acción solicitada tiene un objeto `identifier` que la aplicación usa para determinar en qué botón se ha hecho clic.
The code above also adds a feature to your CI server called [requested actions](https://developer.github.com/changes/2018-05-23-request-actions-on-checks/) via the `actions` object. {% ifversion fpt or ghec %}(Note this is not related to [GitHub Actions](/actions).) {% endif %}Requested actions add a button in the **Checks** tab on GitHub that allows someone to request the check run to take additional action. The additional action is completely configurable by your app. For example, because RuboCop has a feature to automatically fix the errors it finds in Ruby code, your CI server can use a requested actions button to allow people to request automatic error fixes. When someone clicks the button, the app receives the `check_run` event with a `requested_action` action. Each requested action has an `identifier` that the app uses to determine which button was clicked.
El código anterior aún no hace que RuboCop corrija los errores automáticamente. Eso lo agregarás en la siguiente sección. Pero en primer lugar, eche un vistazo a la prueba de CI que acaba de crear iniciando el servidor `template_server.rb` de nuevo y creando una nueva solicitud de incorporación de cambios:
The code above doesn't have RuboCop automatically fix errors yet. You'll add that in the next section. But first, take a look at the CI test that you just created by starting up the `template_server.rb` server again and creating a new pull request:
```shell
$ ruby template_server.rb
```
Las anotaciones se mostrarán en la pestaña **Checks** (Comprobaciones).
The annotations will show up in the **Checks** tab.
![Anotaciones de la ejecución de verificación en la pestaña de verificaciones](/assets/images/github-apps/github_apps_checks_annotations.png)
![Check run annotations in the checks tab](/assets/images/github-apps/github_apps_checks_annotations.png)
Nota el botón de "Arreglar esto" que creaste al agregar la acción solicitada.
Notice the "Fix this" button that you created by adding a requested action.
![Botón de acción solicitada para la ejecución de verificación](/assets/images/github-apps/github_apps_checks_fix_this_button.png)
![Check run requested action button](/assets/images/github-apps/github_apps_checks_fix_this_button.png)
Si las anotaciones están relacionadas con un archivo ya incluido en la solicitud de incorporación de cambios, también se mostrarán en la pestaña **Files changed** (Archivos modificados).
If the annotations are related to a file already included in the PR, the annotations will also show up in the **Files changed** tab.
![Anotaciones de la ejecución de verificación en la pestaña de archivos cambiados](/assets/images/github-apps/github_apps_checks_annotation_diff.png)
![Check run annotations in the files changed tab](/assets/images/github-apps/github_apps_checks_annotation_diff.png)
## Paso 2.6. Corregir automáticamente los errores de RuboCop
## Step 2.6. Automatically fixing RuboCop errors
Si has llegado hasta aquí, ¡excelente! 👏 Ya ha creado una prueba de CI. En esta sección vas a agregar una característica más que utiliza a RuboCop para corregir automáticamente los errores que encuentre. Ya ha agregado el botón "Fix this" (Corregir esto) en la [sección anterior](#step-25-updating-the-check-run-with-ci-test-results). Ahora agregará el código para controlar el evento de ejecución de comprobación `requested_action` que se desencadena cuando alguien hace clic en el botón "Fix this" (Corregir esto).
If you've made it this far, kudos! 👏 You've already created a CI test. In this section, you'll add one more feature that uses RuboCop to automatically fix the errors it finds. You already added the "Fix this" button in the [previous section](#step-25-updating-the-check-run-with-ci-test-results). Now you'll add the code to handle the `requested_action` check run event triggered when someone clicks the "Fix this" button.
La herramienta RuboCop [ofrece](https://docs.rubocop.org/rubocop/usage/basic_usage.html#auto-correcting-offenses) la opción de línea de comandos `--auto-correct` para corregir automáticamente los errores que encuentra. Cuando se usa la característica `--auto-correct`, las actualizaciones se aplican en los archivos locales del servidor. Necesitarás cargar los cambios a GitHub después de que RuboCop haga su magia.
The RuboCop tool [offers](https://docs.rubocop.org/rubocop/usage/basic_usage.html#auto-correcting-offenses) the `--auto-correct` command-line option to automatically fix errors it finds. When you use the `--auto-correct` feature, the updates are applied to the local files on the server. You'll need to push the changes to GitHub after RuboCop does its magic.
Para cargar un repositorio, tu app debe tener permisos de escritura para "contenido de repositorio". Ya ha establecido ese permiso en el [paso 2.2. Clonación del repositorio](#step-22-cloning-the-repository) en **Read & write** (Lectura y escritura), por lo que no debe hacer nada más.
To push to a repository, your app must have write permissions for "Repository contents." You set that permission back in [Step 2.2. Cloning the repository](#step-22-cloning-the-repository) to **Read & write**, so you're all set.
Para confirmar archivos, Git debe saber qué [nombre de usuario](/github/getting-started-with-github/setting-your-username-in-git/) y [correo electrónico](/articles/setting-your-commit-email-address-in-git/) asociar con la confirmación. Agregue dos variables de entorno más en el archivo `.env` para almacenar la configuración del nombre (`GITHUB_APP_USER_NAME`) y del correo electrónico (`GITHUB_APP_USER_EMAIL`). Tu nombre puede ser aquél de tu app y la dirección de correo electrónico puede ser cualquiera para este ejemplo. Por ejemplo:
In order to commit files, Git must know which [username](/github/getting-started-with-github/setting-your-username-in-git/) and [email](/articles/setting-your-commit-email-address-in-git/) to associate with the commit. Add two more environment variables in your `.env` file to store the name (`GITHUB_APP_USER_NAME`) and email (`GITHUB_APP_USER_EMAIL`) settings. Your name can be the name of your app and the email can be any email you'd like for this example. For example:
```ini
GITHUB_APP_USER_NAME=Octoapp
GITHUB_APP_USER_EMAIL=octoapp@octo-org.com
```
Una vez que haya actualizado el archivo `.env` con el nombre y el correo electrónico del autor y del responsable de la confirmación, tendrá todo listo para agregar código para leer las variables de entorno y establecer la configuración de Git. Pronto agregarás este código.
Once you've updated your `.env` file with the name and email of the author and committer, you'll be ready to add code to read the environment variables and set the Git configuration. You'll add that code soon.
Cuando alguien hace clic en el botón "Fix this" (Corregir esto), la aplicación recibe el [webhook de ejecución de comprobación](/webhooks/event-payloads/#check_run) con el tipo de acción `requested_action`.
When someone clicks the "Fix this" button, your app receives the [check run webhook](/webhooks/event-payloads/#check_run) with the `requested_action` action type.
En el [paso 1.4. Actualización de una ejecución de comprobación,](#step-14-updating-a-check-run) ha actualizado el controlador de eventos (`event_handler`) para controlar la búsqueda de acciones en el evento `check_run`. Ya tiene una instrucción "case" para controlar los tipos de acción `created` y `rerequested`:
In [Step 1.4. Updating a check run](#step-14-updating-a-check-run) you updated the your `event_handler` to handle look for actions in the `check_run` event. You already have a case statement to handle the `created` and `rerequested` action types:
``` ruby
when 'check_run'
@@ -636,14 +630,14 @@ when 'check_run'
end
```
Agregue otra instrucción `when` después de la instrucción "case" `rerequested` para controlar el evento `rerequested_action`:
Add another `when` statement after the `rerequested` case to handle the `rerequested_action` event:
``` ruby
when 'requested_action'
take_requested_action
```
Este código llama a un nuevo método que controlará todos los eventos `requested_action` de la aplicación. Agrega el siguiente método a la sección de métodos del ayudante para tu código:
This code calls a new method that will handle all `requested_action` events for your app. Add the following method to the helper methods section of your code:
``` ruby
# Handles the check run `requested_action` event
@@ -678,11 +672,11 @@ def take_requested_action
end
```
El código anterior clona un repositorio, igual que el código que ha agregado en el [paso 2.2. Clonación del repositorio](#step-22-cloning-the-repository). Una instrucción `if` comprueba que el identificador de la acción solicitada coincide con el identificador del botón de RuboCop (`fix_rubocop_notices`). Cuando coinciden, el código clona el repositorio, establece el nombre de usuario y el correo electrónico de Git y ejecuta RuboCop con la opción `--auto-correct`. La opción `--auto-correct` aplica los cambios a los archivos locales del servidor de CI automáticamente.
The code above clones a repository just like the code you added in [Step 2.2. Cloning the repository](#step-22-cloning-the-repository). An `if` statement checks that the requested action's identifier matches the RuboCop button identifier (`fix_rubocop_notices`). When they match, the code clones the repository, sets the Git username and email, and runs RuboCop with the option `--auto-correct`. The `--auto-correct` option applies the changes to the local CI server files automatically.
Los archivos se cambian de manera local, pero aún necesitarás cargarlos a GitHub. Volverá a usar la útil gema `ruby-git` para confirmar todos los archivos. Git tiene un único comando que almacena provisionalmente todos los archivos modificados o eliminados y los confirma: `git commit -a`. Para hacer lo mismo con `ruby-git`, el código anterior usa el método `commit_all`. Después, el código inserta los archivos confirmados en GitHub mediante el token de instalación con el mismo método de autenticación que el comando `clone` de Git. Por último, elimina el directorio del repositorio para garantizar que el directorio de trabajo está preparado para el siguiente evento.
The files are changed locally, but you'll still need to push them to GitHub. You'll use the handy `ruby-git` gem again to commit all of the files. Git has a single command that stages all modified or deleted files and commits them: `git commit -a`. To do the same thing using `ruby-git`, the code above uses the `commit_all` method. Then the code pushes the committed files to GitHub using the installation token, using the same authentication method as the Git `clone` command. Finally, it removes the repository directory to ensure the working directory is prepared for the next event.
Eso es todo. El código que escribiste ahora completa tu servidor de IC para la API de Verificaciones. 💪 Reinicie el servidor `template_server.rb` de nuevo y cree una nueva solicitud de incorporación de cambios:
That's it! The code you have written now completes your Checks API CI server. 💪 Restart your `template_server.rb` server again and create a new pull request:
```shell
$ ruby template_server.rb
@@ -690,21 +684,21 @@ $ ruby template_server.rb
{% data reusables.apps.sinatra_restart_instructions %}
Esta vez, haga clic en el botón "Fix this" (Corregir esto) para corregir automáticamente los errores que RuboCop ha encontrado en la pestaña **Checks** (Comprobaciones).
This time, click the "Fix this" button to automatically fix the errors RuboCop found from the **Checks** tab.
En la pestaña **Commits** (Confirmaciones), verá una nueva confirmación con el nombre de usuario que ha establecido en la configuración de Git. Puede que necesites actualizar tu buscador para ver esto.
In the **Commits** tab, you'll see a brand new commit by the username you set in your Git configuration. You may need to refresh your browser to see the update.
![Una confirmación nueva para corregir los avisos de Octo RuboCop automáticamente](/assets/images/github-apps/github_apps_new_requested_action_commit.png)
![A new commit to automatically fix Octo RuboCop notices](/assets/images/github-apps/github_apps_new_requested_action_commit.png)
Dado que se ha insertado una nueva confirmación en el repositorio, verá un nuevo conjunto de comprobaciones para Octo RuboCop en la pestaña **Checks** (Comprobaciones). Pero esta vez no hay errores porque RuboCop los ha corregido todos. 🎉
Because a new commit was pushed to the repo, you'll see a new check suite for Octo RuboCop in the **Checks** tab. But this time there are no errors because RuboCop fixed them all. 🎉
![Sin errores en los conjuntos de verificaciones o en la ejecución de verificación](/assets/images/github-apps/github_apps_checks_api_success.png)
![No check suite or check run errors](/assets/images/github-apps/github_apps_checks_api_success.png)
Puede encontrar el código completado para la aplicación que acaba de compilar en el archivo `server.rb` del repositorio [Creación de pruebas de CI con la API de comprobaciones](https://github.com/github-developer/creating-ci-tests-with-the-checks-api).
You can find the completed code for the app you just built in the `server.rb` file in the [Creating CI tests with the Checks API](https://github.com/github-developer/creating-ci-tests-with-the-checks-api) repository.
## Paso 2.7. Sugerencias de seguridad
## Step 2.7. Security tips
El código de la plantilla de la GitHub App ya tiene un método para verificar las cargas útiles de webhook entrantes para garantizar que vengan de una fuente confiable. Si no estás validando las cargas útiles de los webhooks, necesitarás garantizar que, cuando los nombres de repositorio se incluyan en éstas, el webhook no contenga comandos arbitrarios que puedan usarse con malas intenciones. El siguiente código valida que el nombre del repositorio solo contenga caracteres alfabeticos latinos, guiones y guiones bajos. Para proporcionarle un ejemplo completo, el código de `server.rb` completo disponible en el [repositorio complementario](https://github.com/github-developer/creating-ci-tests-with-the-checks-api) de esta guía de inicio rápido incluye tanto el método de validación de cargas de webhook entrantes como esta comprobación para verificar el nombre del repositorio.
The template GitHub App code already has a method to verify incoming webhook payloads to ensure they are from a trusted source. If you are not validating webhook payloads, you'll need to ensure that when repository names are included in the webhook payload, the webhook does not contain arbitrary commands that could be used maliciously. The code below validates that the repository name only contains Latin alphabetic characters, hyphens, and underscores. To provide you with a complete example, the complete `server.rb` code available in the [companion repository](https://github.com/github-developer/creating-ci-tests-with-the-checks-api) for this quickstart includes both the method of validating incoming webhook payloads and this check to verify the repository name.
``` ruby
# This quickstart example uses the repository name in the webhook with
@@ -718,43 +712,43 @@ unless @payload['repository'].nil?
end
```
## Solución de problemas
## Troubleshooting
Aquí te mostramos algunos problemas comunes y algunas soluciones sugeridas. Si te encuentras con cualquier otro problema, puedes pedir ayuda o consejo en el {% data variables.product.prodname_support_forum_with_url %}.
Here are a few common problems and some suggested solutions. If you run into any other trouble, you can ask for help or advice in the {% data reusables.support.prodname_support_forum_with_url %}.
* **P:** Mi aplicación no inserta código en GitHub. !No veo las correcciones que RuboCop hace automáticamente!
* **Q:** My app isn't pushing code to GitHub. I don't see the fixes that RuboCop automatically makes!
**R:** Asegúrese de que tiene establecidos los permisos **Read & write** (Lectura y escritura) en "Repository contents" (Contenido del repositorio) y de que va a clonar el repositorio con el token de instalación. Consulte el [paso 2.2. Clonación del repositorio](#step-22-cloning-the-repository) para obtener más información.
**A:** Make sure you have **Read & write** permissions for "Repository contents," and that you are cloning the repository with your installation token. See [Step 2.2. Cloning the repository](#step-22-cloning-the-repository) for details.
* **P:** Veo un error en la salida del registro de depuración `template_server.rb` relacionado con la clonación de mi repositorio.
* **Q:** I see an error in the `template_server.rb` debug output related to cloning my repository.
**R:** Si ve el siguiente error es que no ha eliminado la salida del repositorio en uno de los métodos `initiate_check_run` o `take_requested_action`, o en ambos:
**A:** If you see the following error, you haven't deleted the checkout of the repository in one or both of the `initiate_check_run` or `take_requested_action` methods:
```shell
2018-11-26 16:55:13 - Git::GitExecuteError - git clone '--' 'https://x-access-token:ghs_9b2080277016f797074c4dEbD350745f4257@github.com/codertocat/octocat-breeds.git' 'Octocat-breeds' 2>&1:fatal: destination path 'Octocat-breeds' already exists and is not an empty directory.:
```
Compare su código con el archivo `server.rb` para asegurarse de que tiene el mismo código en los métodos `initiate_check_run` y `take_requested_action`.
Compare your code to the `server.rb` file to ensure you have the same code in your `initiate_check_run` and `take_requested_action` methods.
* **P:** Las nuevas ejecuciones de comprobación no se muestran en la pestaña "Checks" de GitHub.
* **Q:** New check runs are not showing up in the "Checks" tab on GitHub.
**R:** Reinicie Smee y vuelva a ejecutar el servidor `template_server.rb`.
**A:** Restart Smee and re-run your `template_server.rb` server.
* **P:** No veo el botón "Re-run all" en la pestaña "Checks" de GitHub.
* **Q:** I do not see the "Re-run all" button in the "Checks" tab on GitHub.
**R:** Reinicie Smee y vuelva a ejecutar el servidor `template_server.rb`.
**A:** Restart Smee and re-run your `template_server.rb` server.
## Conclusión
## Conclusion
Después de seguir esta guía, ¡aprendiste los puntos básicos de utilizar la API de Verificaciones para crear un servidor de IC! Para hacer una revisión:
After walking through this guide, you've learned the basics of using the Checks API to create a CI server! To review, you:
* Configuraste tu servidor para recibir eventos de la API de Verificaciones y creaste ejecuciones de verificación.
* Utilizaste RuboCop para verificar el código en los repositorios y creaste anotaciones para los errores.
* Iplementaste una accion solicitada que corrijió automáticamente los errores de limpieza.
* Configured your server to receive Checks API events and create check runs.
* Used RuboCop to check code in repositories and create annotations for the errors.
* Implemented a requested action that automatically fixes linter errors.
## Pasos siguientes
## Next steps
Aquí tienes algunas ideas para lo que puedes hacer después:
Here are some ideas for what you can do next:
* Actualmente, el botón "Arreglar esto" siempre se muestra. Actualiza el código que escribiste para que muestre el botón de "Arreglar esto" únicamente cuando RuboCop encuentre errores.
* Si prefiere que RuboCop no confirme archivos directamente en la rama principal, puede actualizar el código para [crear una solicitud de incorporación de cambios](/rest/reference/pulls#create-a-pull-request) con una nueva rama basada en la rama principal.
* Currently, the "Fix this" button is always displayed. Update the code you wrote to display the "Fix this" button only when RuboCop finds errors.
* If you'd prefer that RuboCop doesn't commit files directly to the head branch, you can update the code to [create a pull request](/rest/reference/pulls#create-a-pull-request) with a new branch based on the head branch.

View File

@@ -1,6 +1,6 @@
---
title: Utilizar la API de GitHub en tu app
intro: Aprende cómo configurar tu app para que escuche los eventos y utilice la biblioteca de Octokit para hacer operaciones de la API de REST.
title: Using the GitHub API in your app
intro: Learn how to set up your app to listen for events and use the Octokit library to perform REST API operations.
redirect_from:
- /apps/building-your-first-github-app
- /apps/quickstart-guides/using-the-github-api-in-your-app
@@ -13,94 +13,88 @@ versions:
topics:
- GitHub Apps
shortTitle: Build an app with the REST API
ms.openlocfilehash: 93679e41fe145406ed1eb99e2daaba6bf8e10e76
ms.sourcegitcommit: 872c4751a3fc255671295a5dea6a2081c66b7b71
ms.translationtype: HT
ms.contentlocale: es-ES
ms.lasthandoff: 08/30/2022
ms.locfileid: '145092191'
---
## Introducción
## Introduction
Esta guía te ayudará a crear una GitHub App y a ejecutarla en un servidor. La app que crees agregará una etiqueta a todos los informes de problemas nuevos que estén abiertos en el repositorio en donde ésta se instale.
This guide will help you build a GitHub App and run it on a server. The app you build will add a label to all new issues opened in the repository where the app is installed.
Este proyecto te mostrará cómo hacer lo siguiente:
This project will walk you through the following:
* Programar tu app para escuchar eventos
* Utilizar la biblioteca de Octokit para hacer operaciones de la API de REST
* Programming your app to listen for events
* Using the Octokit.rb library to do REST API operations
{% data reusables.apps.app-ruby-guides %}
Una vez que hayas seguido estos pasos, estarás listo para desarrollar otros tipos de integraciones utilizando la suite completa de las API de GItHub. {% ifversion fpt or ghec %}Puedes consultar ejemplos correctos de aplicaciones en [GitHub Marketplace](https://github.com/marketplace) y [Trabajos con GitHub](https://github.com/works-with).{% endif %}
Once you've worked through the steps, you'll be ready to develop other kinds of integrations using the full suite of GitHub APIs. {% ifversion fpt or ghec %}You can check out successful examples of apps on [GitHub Marketplace](https://github.com/marketplace) and [Works with GitHub](https://github.com/works-with).{% endif %}
## Prerrequisitos
## Prerequisites
Puede que te sea útil tener un entendimiento básico de lo siguiente:
You may find it helpful to have a basic understanding of the following:
* [Aplicaciones de GitHub](/apps/about-apps)
* [GitHub Apps](/apps/about-apps)
* [Webhooks](/webhooks)
* [Lenguaje de programación Ruby](https://www.ruby-lang.org/en/)
* [API de REST](/rest)
* [The Ruby programming language](https://www.ruby-lang.org/en/)
* [REST APIs](/rest)
* [Sinatra](http://sinatrarb.com/)
Pero puedes seguir esta guía sin importar tu nivel de experiencia. ¡Colocaremos enlaces para la información que requieras en cada fase!
But you can follow along at any experience level. We'll link out to information you need along the way!
Antes de que comiences, necesitas hacer lo siguiente:
Before you begin, you'll need to do the following:
1. Clone el repositorio [Uso de la API de GitHub en la aplicación](https://github.com/github-developer/using-the-github-api-in-your-app).
1. Clone the [Using the GitHub API in your app](https://github.com/github-developer/using-the-github-api-in-your-app) repository.
```shell
$ git clone https://github.com/github-developer/using-the-github-api-in-your-app.git
```
En el directorio, encontrarás un archivo `template_server.rb` con el código de plantilla que usarás en este inicio rápido y un archivo `server.rb` con el código del proyecto completado.
Inside the directory, you'll find a `template_server.rb` file with the template code you'll use in this quickstart and a `server.rb` file with the completed project code.
1. Sigue los pasos de la guía de inicio rápido [Configuración del entorno de desarrollo](/apps/quickstart-guides/setting-up-your-development-environment/) para configurar y ejecutar el servidor de la aplicación `template_server.rb`. Si anteriormente has completado un inicio rápido de aplicación de GitHub diferente de [Configuración del entorno de desarrollo](/apps/quickstart-guides/setting-up-your-development-environment/), debes registrar una _nueva_ aplicación de GitHub e iniciar un nuevo canal Smee para usarlo con este inicio rápido.
1. Follow the steps in the [Setting up your development environment](/apps/quickstart-guides/setting-up-your-development-environment/) quickstart to configure and run the `template_server.rb` app server. If you've previously completed a GitHub App quickstart other than [Setting up your development environment](/apps/quickstart-guides/setting-up-your-development-environment/), you should register a _new_ GitHub App and start a new Smee channel to use with this quickstart.
Este inicio rápido incluye el mismo código `template_server.rb` que el inicio rápido [Configuración del entorno de desarrollo](/apps/quickstart-guides/setting-up-your-development-environment/). **Nota:** A medida que sigas el inicio rápido [Configuración del entorno de desarrollo](/apps/quickstart-guides/setting-up-your-development-environment/), asegúrate de usar los archivos del proyecto incluidos en el repositorio [Uso de la API de GitHub en la aplicación](https://github.com/github-developer/using-the-github-api-in-your-app).
This quickstart includes the same `template_server.rb` code as the [Setting up your development environment](/apps/quickstart-guides/setting-up-your-development-environment/) quickstart. **Note:** As you follow along with the [Setting up your development environment](/apps/quickstart-guides/setting-up-your-development-environment/) quickstart, make sure to use the project files included in the [Using the GitHub API in your app](https://github.com/github-developer/using-the-github-api-in-your-app) repository.
Consulta la sección [Solución de problemas](/apps/quickstart-guides/setting-up-your-development-environment/#troubleshooting) si tienes problemas para configurar la aplicación de plantilla de GitHub.
See the [Troubleshooting](/apps/quickstart-guides/setting-up-your-development-environment/#troubleshooting) section if you are running into problems setting up your template GitHub App.
## Crear la app
## Building the app
Ahora que estás familiarizado con el código `template_server.rb`, crearás código que agrega automáticamente la etiqueta `needs-response` a todas las propuestas abiertas en el repositorio en el que está instalada la aplicación.
Now that you're familiar with the `template_server.rb` code, you're going to create code that automatically adds the `needs-response` label to all issues opened in the repository where the app is installed.
El archivo `template_server.rb` contiene código de plantilla de aplicación que aún no se ha personalizado. En este archivo, verás código de marcador de posición para gestionar eventos de webhook y algún otro tipo de código para inicializar el cliente de Octokit.rb.
The `template_server.rb` file contains app template code that has not yet been customized. In this file, you'll see some placeholder code for handling webhook events and some other code for initializing an Octokit.rb client.
{% note %}
**Nota:** `template_server.rb` contiene muchos comentarios de código que complementan esta guía y explican detalles técnicos adicionales. Es posible que le resulte útil leer los comentarios de ese archivo ahora, antes de continuar con esta sección, para obtener resumen de cómo funciona el código.
**Note:** `template_server.rb` contains many code comments that complement this guide and explain additional technical details. You may find it helpful to read through the comments in that file now, before continuing with this section, to get an overview of how the code works.
El código personalizado final que crearás al final de esta guía se proporciona en [`server.rb`](https://github.com/github-developer/using-the-github-api-in-your-app/blob/master/server.rb). Pero, ¡intenta esperar hasta que termines para darle un vistazo!
The final customized code that you'll create by the end of this guide is provided in [`server.rb`](https://github.com/github-developer/using-the-github-api-in-your-app/blob/master/server.rb). Try waiting until the end to look at it, though!
{% endnote %}
Estos son los pasos que tendrás que completar para crear tu primer GitHub App:
These are the steps you'll complete to create your first GitHub App:
1. [Actualización de los permisos de la aplicación](#step-1-update-app-permissions)
2. [Agregar la gestión de eventos](#step-2-add-event-handling)
3. [Creación de una nueva etiqueta](#step-3-create-a-new-label)
4. [Agregar la gestión de etiquetas](#step-4-add-label-handling)
1. [Update app permissions](#step-1-update-app-permissions)
2. [Add event handling](#step-2-add-event-handling)
3. [Create a new label](#step-3-create-a-new-label)
4. [Add label handling](#step-4-add-label-handling)
## Paso 1. Actualización de los permisos de la aplicación
## Step 1. Update app permissions
Cuando [registraste por primera vez la aplicación](/apps/quickstart-guides/setting-up-your-development-environment/#step-2-register-a-new-github-app), aceptaste los permisos predeterminados, lo que significa que la aplicación no tiene acceso a la mayoría de los recursos. Para este ejemplo, tu app necesitará el permiso para leer los informes de problemas y escribir etiquetas.
When you [first registered your app](/apps/quickstart-guides/setting-up-your-development-environment/#step-2-register-a-new-github-app), you accepted the default permissions, which means your app doesn't have access to most resources. For this example, your app will need permission to read issues and write labels.
Para actualizar los permisos de tu app:
To update your app's permissions:
1. Selecciona la aplicación en la [página de configuración de la aplicación](https://github.com/settings/apps) y haz clic en **Permisos y webhooks** en la barra lateral.
1. En la sección "Permisos", busca "Propuestas" y, al lado, selecciona **Lectura y escritura** en la lista desplegable "Acceso". La descripción dice que esta opción otorga acceso tanto a informes de problemas como a etiquetas, que es exactamente lo que buscas.
1. En la sección "Suscribirse a eventos", selecciona **Propuestas** para suscribirte al evento.
1. Select your app from the [app settings page](https://github.com/settings/apps) and click **Permissions & Webhooks** in the sidebar.
1. In the "Permissions" section, find "Issues," and select **Read & Write** in the "Access" dropdown next to it. The description says this option grants access to both issues and labels, which is just what you need.
1. In the "Subscribe to events" section, select **Issues** to subscribe to the event.
{% data reusables.apps.accept_new_permissions_steps %}
Magnífico. Tu app tiene permiso para realizar las tareas que quieres que haga. Ahora puedes agregar el código para que funcione.
Great! Your app has permission to do the tasks you want it to do. Now you can add the code to make it work.
## Paso 2. Agregar la gestión de eventos
## Step 2. Add event handling
Lo primero que tiene que hacer tu app es escuchar si se han abierto informes de problemas nuevos. Ahora que te has suscrito al evento **Propuestas**, empezarás a recibir el webhook [`issues`](/webhooks/event-payloads/#issues), que se desencadena cuando se producen determinadas acciones relacionadas con la propuesta. Puedes filtrar este tipo de evento para la acción específica que quieres en tu código.
The first thing your app needs to do is listen for new issues that are opened. Now that you've subscribed to the **Issues** event, you'll start receiving the [`issues`](/webhooks/event-payloads/#issues) webhook, which is triggered when certain issue-related actions occur. You can filter this event type for the specific action you want in your code.
GitHub envía cargas de webhook como solicitudes `POST`. Dado que has reenviado las cargas de webhook de Smee a `http://localhost/event_handler:3000`, el servidor recibirá las cargas de solicitud `POST` en la ruta `post '/event_handler'`.
GitHub sends webhook payloads as `POST` requests. Because you forwarded your Smee webhook payloads to `http://localhost/event_handler:3000`, your server will receive the `POST` request payloads in the `post '/event_handler'` route.
Ya se incluye una ruta vacía `post '/event_handler'` en el archivo `template_server.rb`, que has descargado en la sección de [requisitos previos](#prerequisites). La ruta vacía se ve así:
An empty `post '/event_handler'` route is already included in the `template_server.rb` file, which you downloaded in the [prerequisites](#prerequisites) section. The empty route looks like this:
``` ruby
post '/event_handler' do
@@ -113,7 +107,7 @@ Ya se incluye una ruta vacía `post '/event_handler'` en el archivo `template_se
end
```
Use esta ruta para controlar el evento `issues`; para ello, agregue el código siguiente:
Use this route to handle the `issues` event by adding the following code:
``` ruby
case request.env['HTTP_X_GITHUB_EVENT']
@@ -124,9 +118,9 @@ when 'issues'
end
```
Cada evento que GitHub envía incluye un encabezado de solicitud denominado `HTTP_X_GITHUB_EVENT`, que indica el tipo de evento en la solicitud `POST`. En este momento, solo te interesan los tipos de eventos `issues`. Cada evento tiene un campo `action` adicional que indica el tipo de acción que ha activado los eventos. Para `issues`, el campo `action` puede ser `assigned`, `unassigned`, `labeled`, `unlabeled`, `opened`, `edited`, `milestoned`, `demilestoned`, `closed` o `reopened`.
Every event that GitHub sends includes a request header called `HTTP_X_GITHUB_EVENT`, which indicates the type of event in the `POST` request. Right now, you're only interested in `issues` event types. Each event has an additional `action` field that indicates the type of action that triggered the events. For `issues`, the `action` field can be `assigned`, `unassigned`, `labeled`, `unlabeled`, `opened`, `edited`, `milestoned`, `demilestoned`, `closed`, or `reopened`.
Para probar tu gestor de eventos, intenta agregar un método auxiliar temporal. Se actualizará más adelante cuando [agregues la gestión de etiquetas](#step-4-add-label-handling). Por ahora, agrega el código siguiente dentro de la sección `helpers do` del código. Puedes poner el método nuevo arriba o abajo de cualquiera de los métodos auxiliares. El orden no importa.
To test your event handler, try adding a temporary helper method. You'll update later when you [Add label handling](#step-4-add-label-handling). For now, add the following code inside the `helpers do` section of the code. You can put the new method above or below any of the other helper methods. Order doesn't matter.
``` ruby
def handle_issue_opened_event(payload)
@@ -134,37 +128,37 @@ def handle_issue_opened_event(payload)
end
```
Este método recibe una carga útil de evento formateada con JSON a manera de argumento. Esto significa que puedes analizar la carga útil en el método y profundizar hacia cualquier tipo de datos específico que necesites. Es posible que te resulte útil inspeccionar la carga completa en algún momento: intenta cambiar `logger.debug 'An issue was opened!` a `logger.debug payload`. La estructura de carga que verás debe coincidir con lo que [se muestra en la documentación del evento de webhook `issues`](/webhooks/event-payloads/#issues).
This method receives a JSON-formatted event payload as an argument. This means you can parse the payload in the method and drill down to any specific data you need. You may find it helpful to inspect the full payload at some point: try changing `logger.debug 'An issue was opened!` to `logger.debug payload`. The payload structure you see should match what's [shown in the `issues` webhook event docs](/webhooks/event-payloads/#issues).
Magnífico. Es momento de probar los cambios.
Great! It's time to test the changes.
{% data reusables.apps.sinatra_restart_instructions %}
En tu buscador, visita el repositorio en donde instalaste tu app. Abre un informe de problemas nuevo en este repositorio. El informe de problemas puede decir lo que gustes. Esto es solo para hacer la prueba.
In your browser, visit the repository where you installed your app. Open a new issue in this repository. The issue can say anything you like. It's just for testing.
Al mirar de nuevo el terminal, deberías ver un mensaje en la salida que dice "`An issue was opened!` ¡Felicidades!". Acabas de agregar un gestor de eventos a tu app. 💪
When you look back at your Terminal, you should see a message in the output that says, `An issue was opened!` Congrats! You've added an event handler to your app. 💪
## Paso 3. Creación de una nueva etiqueta
## Step 3. Create a new label
Bien, tu app puede decirte qué informes de problemas están abiertos. Ahora quieres que agregue la etiqueta `needs-response` a cualquier nueva propuesta abierta en un repositorio en el que la aplicación está instalada.
Okay, your app can tell when issues are opened. Now you want it to add the label `needs-response` to any newly opened issue in a repository the app is installed in.
Para _poder agregar_ la etiqueta en cualquier lugar, deberás _crear_ la etiqueta personalizada en el repositorio. Solo necesitas hacer esto una vez. Para fines de esta guía, crea la etiqueta manualmente en GitHub. En el repositorio, haz clic en **Propuestas**, luego en **Etiquetas** y, por último, en **Nueva etiqueta**. Asigna el nombre `needs-response` a la etiqueta nueva.
Before the label can be _added_ anywhere, you'll need to _create_ the custom label in your repository. You'll only need to do this one time. For the purposes of this guide, create the label manually on GitHub. In your repository, click **Issues**, then **Labels**, then click **New label**. Name the new label `needs-response`.
{% tip %}
**Sugerencia**: ¿No sería genial si la aplicación pudiera crear la etiqueta mediante programación? [¡Sí puede!](/rest/reference/issues#create-a-label) Intenta agregar tú mismo el código para que lo haga después de que completes los pasos en esta guía.
**Tip**: Wouldn't it be great if your app could create the label programmatically? [It can](/rest/reference/issues#create-a-label)! Try adding the code to do that on your own after you finish the steps in this guide.
{% endtip %}
Ahora que la etiqueta existe, puedes programar la aplicación para que use la API de REST para [agregar la etiqueta a cualquier propuesta recién abierta](/rest/reference/issues#add-labels-to-an-issue).
Now that the label exists, you can program your app to use the REST API to [add the label to any newly opened issue](/rest/reference/issues#add-labels-to-an-issue).
## Paso 4. Agregar la gestión de etiquetas
## Step 4. Add label handling
Felicidades—llegste al último paso: agregar la gestión de etiquetas a tu app. Para esta tarea, querrás usar la [biblioteca de Ruby Octokit.rb](http://octokit.github.io/octokit.rb/).
Congrats—you've made it to the final step: adding label handling to your app. For this task, you'll want to use the [Octokit.rb Ruby library](http://octokit.github.io/octokit.rb/).
En la documentación de Octokit.rb, busca la lista de [métodos de etiqueta](http://octokit.github.io/octokit.rb/Octokit/Client/Labels.html). El método que querrás usar es [`add_labels_to_an_issue`](http://octokit.github.io/octokit.rb/Octokit/Client/Labels.html#add_labels_to_an_issue-instance_method).
In the Octokit.rb docs, find the list of [label methods](http://octokit.github.io/octokit.rb/Octokit/Client/Labels.html). The method you'll want to use is [`add_labels_to_an_issue`](http://octokit.github.io/octokit.rb/Octokit/Client/Labels.html#add_labels_to_an_issue-instance_method).
De nuevo en `template_server.rb`, busca el método que has definido anteriormente:
Back in `template_server.rb`, find the method you defined previously:
``` ruby
def handle_issue_opened_event(payload)
@@ -172,13 +166,13 @@ def handle_issue_opened_event(payload)
end
```
La documentación de [`add_labels_to_an_issue`](http://octokit.github.io/octokit.rb/Octokit/Client/Labels.html#add_labels_to_an_issue-instance_method) muestra que deberás pasar tres argumentos a este método:
The [`add_labels_to_an_issue`](http://octokit.github.io/octokit.rb/Octokit/Client/Labels.html#add_labels_to_an_issue-instance_method) docs show you'll need to pass three arguments to this method:
* Repositorio (cadena en formato `"owner/name"`)
* Número de informe de problemas (número entero)
* Etiquetas (matriz)
* Repo (string in `"owner/name"` format)
* Issue number (integer)
* Labels (array)
Puedes analizar la carga útil para obtener tanto el repo y el número de informe de problemas. Dado que el nombre de la etiqueta siempre será el mismo (`needs-response`), puedes pasarlo como una cadena codificada de forma rígida en la matriz de etiquetas. Al juntar estas piezas, tu método actualizado se podría ver más o menos así:
You can parse the payload to get both the repo and the issue number. Since the label name will always be the same (`needs-response`), you can pass it as a hardcoded string in the labels array. Putting these pieces together, your updated method might look like this:
``` ruby
# When an issue is opened, add a label
@@ -189,56 +183,56 @@ def handle_issue_opened_event(payload)
end
```
¡Intenta abrir un informe de problemas nuevo en tu repositorio de prueba y ver lo que pasa! Si no pasa nada de inmediato, intenta actualizarlo.
Try opening a new issue in your test repository and see what happens! If nothing happens right away, try refreshing.
No verás mucho contenido en el terminal, _pero_ deberías ver que el usuario bot ha agregado una etiqueta a la propuesta.
You won't see much in the Terminal, _but_ you should see that a bot user has added a label to the issue.
{% note %}
**Nota:** Cuando las aplicaciones de GitHub realizan acciones a través de la API, como agregar etiquetas, GitHub muestra estas acciones como si las realizaran cuentas de _bot_. Para obtener más información, consulta "[Comparación entre cuentas de máquina y cuentas de bot](/apps/differences-between-apps/#machine-vs-bot-accounts)".
**Note:** When GitHub Apps take actions via the API, such as adding labels, GitHub shows these actions as being performed by _bot_ accounts. For more information, see "[Machine vs. bot accounts](/apps/differences-between-apps/#machine-vs-bot-accounts)."
{% endnote %}
Si es así, ¡felicidades! ¡Has creado una app funcional exitosamente! 🎉
If so, congrats! You've successfully built a working app! 🎉
Puedes ver el código final en `server.rb` en el [repositorio de plantillas de la aplicación](https://github.com/github-developer/using-the-github-api-in-your-app).
You can see the final code in `server.rb` in the [app template repository](https://github.com/github-developer/using-the-github-api-in-your-app).
Consulta "[Pasos siguientes](#next-steps)" para obtener ideas sobre cómo puedes continuar.
See "[Next steps](#next-steps)" for ideas about where you can go from here.
## Solución de problemas
## Troubleshooting
Aquí te mostramos algunos problemas comunes y algunas soluciones sugeridas. Si te encuentras con cualquier otro problema, puedes pedir ayuda o consejo en el {% data variables.product.prodname_support_forum_with_url %}.
Here are a few common problems and some suggested solutions. If you run into any other trouble, you can ask for help or advice in the {% data reusables.support.prodname_support_forum_with_url %}.
* **P:** Mi servidor no escucha eventos. El cliente de Smee está ejecutándose en una ventana de la terminal, y estoy enviando eventos en GitHub.com mediante la apertura de informes de problemas nuevos, pero no veo ninguna salida en la ventana de la terminal en donde estoy ejecutando el servidor.
* **Q:** My server isn't listening to events! The Smee client is running in a Terminal window, and I'm sending events on GitHub.com by opening new issues, but I don't see any output in the Terminal window where I'm running the server.
**R:** Es posible que no tengas el dominio de Smee correcto en la configuración de la aplicación. Visita la [página de configuración de la aplicación](https://github.com/settings/apps) y vuelve a comprobar los campos que se muestran en "[Registrar una nueva aplicación con GitHub](/apps/quickstart-guides/setting-up-your-development-environment/#step-2-register-a-new-github-app)". Asegúrate de que el dominio de esos campos coincida con el dominio que has usado en el comando `smee -u <unique_channel>` en "[Inicio de un nuevo canal Smee](/apps/quickstart-guides/setting-up-your-development-environment/#step-1-start-a-new-smee-channel)".
**A:** You may not have the correct Smee domain in your app settings. Visit your [app settings page](https://github.com/settings/apps) and double-check the fields shown in "[Register a new app with GitHub](/apps/quickstart-guides/setting-up-your-development-environment/#step-2-register-a-new-github-app)." Make sure the domain in those fields matches the domain you used in your `smee -u <unique_channel>` command in "[Start a new Smee channel](/apps/quickstart-guides/setting-up-your-development-environment/#step-1-start-a-new-smee-channel)."
* **P:** Mi aplicación no funciona. Abrí un nuevo informe de problemas, pero aún después de actualizar, no se le ha agregado ninguna etiqueta.
* **Q:** My app doesn't work! I opened a new issue, but even after refreshing, no label has been added to it.
**R:** Asegúrate de que todo lo siguiente sea cierto:
**A:** Make sure all of the following are true:
* Has [instalado la aplicación](/apps/quickstart-guides/setting-up-your-development-environment/#step-7-install-the-app-on-your-account) en el repositorio en el que vas a abrir la propuesta.
* El [cliente Smee se ejecuta](/apps/quickstart-guides/setting-up-your-development-environment/#step-1-start-a-new-smee-channel) en una ventana del Terminal.
* El [servidor web se ejecuta](/apps/quickstart-guides/setting-up-your-development-environment/#step-6-start-the-server) sin errores en otra ventana del Terminal.
* La aplicación tiene [permisos de lectura y escritura en propuestas y está suscrita a eventos de propuesta](/apps/quickstart-guides/setting-up-your-development-environment/#step-1-start-a-new-smee-channel).
* Has [comprobado el correo electrónico](#step-1-update-app-permissions) después de actualizar los permisos y has aceptado los nuevos permisos.
* You [installed the app](/apps/quickstart-guides/setting-up-your-development-environment/#step-7-install-the-app-on-your-account) on the repository where you're opening the issue.
* Your [Smee client is running](/apps/quickstart-guides/setting-up-your-development-environment/#step-1-start-a-new-smee-channel) in a Terminal window.
* Your [web server is running](/apps/quickstart-guides/setting-up-your-development-environment/#step-6-start-the-server) with no errors in another Terminal window.
* Your app has [read & write permissions on issues and is subscribed to issue events](/apps/quickstart-guides/setting-up-your-development-environment/#step-1-start-a-new-smee-channel).
* You [checked your email](#step-1-update-app-permissions) after updating the permissions and accepted the new permissions.
## Conclusión
## Conclusion
Después de seguir esta guía, ¡habrás aprendido los fundamentos básicos para desarrollar GitHub Apps! Para hacer una revisión:
After walking through this guide, you've learned the basic building blocks for developing GitHub Apps! To review, you:
* Programaste tu app para escuchar eventos
* Utilizaste la biblioteca de Octokit para hacer operaciones de la API de REST
* Programmed your app to listen for events
* Used the Octokit.rb library to do REST API operations
## Pasos siguientes
## Next steps
Aquí tienes algunas ideas para lo que puedes hacer después:
Here are some ideas for what you can do next:
* [Vuelve a escribir la aplicación con GraphQL](https://developer.github.com/changes/2018-04-30-graphql-supports-github-apps/).
* Vuelve a escribir la aplicación en Node.js con [Probot](https://github.com/probot/probot).
* Haz que la aplicación compruebe si la etiqueta `needs-response` ya existe en la propuesta y, si no es así, agrégala.
* Cuando el bot agregue la etiqueta exitosamente, muestra un mensaje en la terminal. (Pista: compara la ID de la etiqueta `needs-response` con la ID de la etiqueta en la carga útil como una condición para tu mensaje, para que así, el mensaje solo muestre cuando la etiqueta relevante se agregue y no lo haga con otra etiqueta).
* Agrega una página de aterrizaje a la aplicación y conecta una [ruta de Sinatra](https://github.com/sinatra/sinatra#routes) para ella.
* Migra tu código a un servidor hospedado (como Heroku). No olvides actualizar la configuración de tu app con el dominio nuevo.
* Comparte el proyecto u obtén consejos en {% data variables.product.prodname_support_forum_with_url %}{% ifversion fpt or ghec %}
* ¿Has creado una nueva y reluciente app que crees que pueda ser útil para otros? [Agrégala a GitHub Marketplace](/apps/marketplace/creating-and-submitting-your-app-for-approval/).{% endif %}
* [Rewrite your app using GraphQL](https://developer.github.com/changes/2018-04-30-graphql-supports-github-apps/)!
* Rewrite your app in Node.js using [Probot](https://github.com/probot/probot)!
* Have the app check whether the `needs-response` label already exists on the issue, and if not, add it.
* When the bot successfully adds the label, show a message in the Terminal. (Hint: compare the `needs-response` label ID with the ID of the label in the payload as a condition for your message, so that the message only displays when the relevant label is added and not some other label.)
* Add a landing page to your app and hook up a [Sinatra route](https://github.com/sinatra/sinatra#routes) for it.
* Move your code to a hosted server (like Heroku). Don't forget to update your app settings with the new domain.
* Share your project or get advice in the {% data reusables.support.prodname_support_forum_with_url %}{% ifversion fpt or ghec %}
* Have you built a shiny new app you think others might find useful? [Add it to GitHub Marketplace](/apps/marketplace/creating-and-submitting-your-app-for-approval/)!{% endif %}

View File

@@ -317,6 +317,24 @@ Webhook events are triggered based on the specificity of the domain you register
{{ webhookPayloadsForCurrentVersion.delete }}
{% ifversion fpt or ghec %}
## dependabot_alert
{% data reusables.webhooks.dependabot_alert_description %}
### Availability
{% data reusables.webhooks.dependabot_alert_availability %}
### Webhook payload object
{% data reusables.webhooks.dependabot_alert_payload %}
### Webhook payload example
{{ webhookPayloadsForCurrentVersion.dependabot_alert.fixed }}
{% endif %}
## deploy_key
{% data reusables.webhooks.deploy_key_short_desc %}
@@ -1591,7 +1609,7 @@ This event occurs when someone triggers a workflow run on GitHub or sends a `POS
| Key | Type | Description |
|-----|-----|-----|
| `inputs` | `object` | Inputs to the workflow. Each key represents the name of the input while it's value represents the value of that input. |
| `inputs` | `object` | Inputs to the workflow. Each key represents the name of the input while its value represents the value of that input. |
{% data reusables.webhooks.org_desc %}
| `ref` | `string` | The branch ref from which the workflow was run. |
{% data reusables.webhooks.repo_desc %}

View File

@@ -1,15 +1,7 @@
---
ms.openlocfilehash: 01490f812c6a7b54293806a24023f25af2831d8e
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
ms.translationtype: HT
ms.contentlocale: es-ES
ms.lasthandoff: 09/05/2022
ms.locfileid: "147432084"
---
Para las preguntas, reportes de errores y debates sobre las {% data variables.product.prodname_github_apps %}, {% data variables.product.prodname_oauth_apps %} y el desarrollo de la API, explora el {% data variables.product.prodname_support_forum_with_url %}. Los debates se moderan y mantienen con el personal de {% data variables.product.company_short %}, pero no se garantiza que el personal de {% data variables.product.company_short %} responda las preguntas que se publiquen en el foro.
For questions, bug reports, and discussions about {% data variables.product.prodname_github_apps %}, {% data variables.product.prodname_oauth_apps %}, and API development, explore the {% data reusables.support.prodname_support_forum_with_url %}. The discussions are moderated and maintained by {% data variables.product.company_short %} staff, but questions posted to the forum are not guaranteed to receive a reply from {% data variables.product.company_short %} staff.
Considera la posibilidad de ponerse en contacto con [Soporte de GitHub](https://support.github.com/) directamente mediante el formulario de contacto para:
- respuestas garantizadas del personal de {% data variables.product.product_name %}
- solicitudes de soporte que involucren preocupaciones sobre datos sensibles o privados
- solicitudes de características
- retroalimentación sobre los productos de {% data variables.product.product_name %}
Consider reaching out to [GitHub Support](https://support.github.com/) directly using the contact form for:
- guaranteed response from {% data variables.product.product_name %} staff
- support requests involving sensitive data or private concerns
- feature requests
- feedback about {% data variables.product.product_name %} products

View File

@@ -1,9 +1,7 @@
---
ms.openlocfilehash: 004cf3f20495daaec9413026c03e5514211c906d
ms.sourcegitcommit: fcf3546b7cc208155fb8acdf68b81be28afc3d2d
ms.translationtype: HT
ms.contentlocale: es-ES
ms.lasthandoff: 09/10/2022
ms.locfileid: "145070186"
---
Actividad relacionada con las alertas de vulnerabilidades de seguridad en un repositorio. {% data reusables.webhooks.action_type_desc %} Para más información, vea "[Acerca de {% data variables.product.prodname_dependabot_alerts %}](/github/managing-security-vulnerabilities/about-alerts-for-vulnerable-dependencies/)".
{% warning %}
**Deprecation note**: The `repository_vulnerability_alert` webhook events described below are deprecated and are documented here for reference only. Use [`dependabot_alert`](#dependabot_alert) as an alternative.
{% endwarning %}
Activity related to security vulnerability alerts in a repository. {% data reusables.webhooks.action_type_desc %} For more information, see the "[About {% data variables.product.prodname_dependabot_alerts %}](/github/managing-security-vulnerabilities/about-alerts-for-vulnerable-dependencies/)".

View File

@@ -1,5 +1,5 @@
---
title: プロフィールに非公開のコントリビューションとアチーブメントを表示する
title: Showing your private contributions and achievements on your profile
intro: 'Your {% data variables.product.product_name %} profile shows a graph of your repository contributions over the past year. You can choose to show anonymized activity from {% ifversion fpt or ghes or ghec %}private and internal{% else %}private{% endif %} repositories{% ifversion fpt or ghes or ghec %} in addition to the activity from public repositories{% endif %}.'
redirect_from:
- /articles/publicizing-or-hiding-your-private-contributions-on-your-profile
@@ -14,40 +14,42 @@ versions:
topics:
- Profiles
shortTitle: Private contributions and achievements
ms.openlocfilehash: b40e3835bf1548ff4ced75d1207de9a5b493dc90
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 09/05/2022
ms.locfileid: '147079951'
---
プライベートコントリビューションを公開しても、あなたが作業しているプライベートリポジトリへのアクセス権がないユーザーがあなたのプライベートコントリビューションを見ることはできません。 かわりに、特定の日におけるプライベートコントリビューションの数だけを見ることができます。 パブリックコントリビューションには、詳細な情報が含まれます。 詳細については、[プロファイル ページでの投稿の表示](/articles/viewing-contributions-on-your-profile-page)に関する説明を参照してください。
If you publicize your private contributions, people without access to the private repositories you work in won't be able to see the details of your private contributions. Instead, they'll see the number of private contributions you made on any given day. Your public contributions will include detailed information. For more information, see "[Viewing contributions on your profile page](/articles/viewing-contributions-on-your-profile-page)."
{% note %}
**:** {% ifversion fpt or ghes or ghec %}{% ifversion fpt or ghec %}{% data variables.product.prodname_dotcom_the_website %}{% elsif ghes %}{% data variables.product.product_name %}{% endif %} で、ご自分のプロファイル上のパブリック コントリビューションは、{% ifversion fpt or ghec %}{% data variables.product.prodname_dotcom_the_website %}{% elsif ghes %} にアクセスできる世界中のすべてのユーザーが参照できます。{% data variables.product.product_location%}{% endif %}の他のユーザーのみ。{% elsif ghae %}{% data variables.product.prodname_ghe_managed %} で、ご自分のプロファイル上のコントリビューションは、ご自分のエンタープライズのその他のメンバーのみが参照できます。{% endif %}
**Note:** {% ifversion fpt or ghes or ghec %}On {% ifversion fpt or ghec %}{% data variables.product.prodname_dotcom_the_website %}{% elsif ghes %}{% data variables.product.product_name %}{% endif %}, public contributions on your profile are visible {% ifversion fpt or ghec %}to anyone in the world who can access {% data variables.product.prodname_dotcom_the_website %}{% elsif ghes %}only to other users of {% data variables.product.product_location%}{% endif %}.{% elsif ghae %}On {% data variables.product.prodname_ghe_managed %}, only other members of your enterprise can see the contributions on your profile.{% endif %}
{% endnote %}
## プライベートコントリビューションの可視性を変更する
## Changing the visibility of your private contributions
{% data reusables.profile.access_profile %}
1. プライベートコントリビューションをプロフィールで公開または非公開にする
- プライベート コントリビューションを公開するには、コントリビューション グラフの上にある **[コントリビューションの設定]** ドロップダウン メニューを使用して、 **[プライベート コントリビューション]** を選択します。 訪問者には、プライベートコントリビューションの数だけが表示され、それ以上の詳細は表示されません。
![[コントリビューションの設定] ドロップダウン メニューで、閲覧者がプライベート コントリビューションを見られるようにする](/assets/images/help/profile/private-contributions-on.png)
- プライベート コントリビューションを非公開にするには、コントリビューション グラフの上にある **[コントリビューションの設定]** ドロップダウン メニューを使用して、 **[プライベート コントリビューション]** を選択解除します。 閲覧者には、公開されたコントリビューションのみが表示されます。
![[コントリビューションの設定] ドロップダウン メニューで、閲覧者がプライベート コントリビューションを見られるようにする](/assets/images/help/profile/private-contributions-off.png)
1. Publicize or hide your private contributions on your profile:
- To publicize your private contributions, above your contributions graph, use the **Contribution settings** drop-down menu, and select **Private contributions**. Visitors will see your private contribution counts without further details.
![Enable visitors to see private contributions from contribution settings drop-down menu](/assets/images/help/profile/private-contributions-on.png)
- To hide your private contributions, above your contributions graph, use the **Contribution settings** drop-down menu, and unselect **Private contributions.** Visitors will only see your public contributions.
![Enable visitors to see private contributions from contribution settings drop-down menu](/assets/images/help/profile/private-contributions-off.png)
## アチーブメントの表示を変更する
## Changing the visibility of Achievements
{% data reusables.user-settings.access_settings %}
1. プロフィールでアチーブメントを表示または非表示にします。
- プロフィールにアチーブメントを表示するには、 **[プロフィールの設定]** に移動し、 **[自分のプロフィールにアチーブメントを表示する]** チェックボックスをオンにします。
![プロフィールの設定で、訪問者がアチーブメントを見られるようにする](/assets/images/achievements-profile-settings-off.png)
- プロフィールにアチーブメントが表示されないようにするには、 **[プロフィールの設定]** に移動し、 **[自分のプロフィールにアチーブメントを表示する]** チェックボックスをオフにします。
![プロフィールの設定で、訪問者に対してアチーブメントを非表示にする](/assets/images/achievements-profile-settings-on.png)
1. Show or hide Achievements on your profile:
- To show Achievements on your profile, navigate to **Profile settings**, and select the checkbox next to **Show Achievements on my profile.**
![Enable visitors to see Achievements from profile settings](/assets/images/help/profile/achievements-profile-settings-off.png)
- To hide Achievements from your profile, navigate to **Profile settings**, and unselect the checkbox next to **Show Achievements on my profile.**
![Hide Achievements from visitors in profile settings](/assets/images/help/profile/achievements-profile-settings-on.png)
{% ifversion hide-individual-achievements %}
1. Optionally, to hide individual Achievements from your profile:
{% data reusables.profile.access_profile %}
1. Navigate to the Achievements section on the left sidebar of your profile and select the Achievements header. ![Achievements on profile sidebar](/assets/images/help/profile/achievements-on-profile.png)
2. Open the detail view of the achievement you'd like to hide by clicking on the achievement.
3. Once in the detail view, click the {% octicon "eye" aria-label="The eye icon" %} icon to hide the achievement. ![Achievement detail view](/assets/images/help/profile/achievements-detail-view.png) When hidden, badges will be marked by the {% octicon "eye-closed" aria-label="The eye closed icon" %} icon and are only visible to you. ![Hidden achievements](/assets/images/help/profile/achievements-hidden.png)
## 参考資料
{% endif %}
## Further reading
- "[プロフィール ページでコントリビューションを表示する](/articles/viewing-contributions-on-your-profile-page)"
- "[コントリビューションがプロフィールに表示されないのはなぜですか?](/articles/why-are-my-contributions-not-showing-up-on-my-profile)"
- "[Viewing contributions on your profile page](/articles/viewing-contributions-on-your-profile-page)"
- "[Why are my contributions not showing up on my profile?](/articles/why-are-my-contributions-not-showing-up-on-my-profile)"

View File

@@ -115,7 +115,7 @@ For more information, see "[Reusing workflows](/actions/learn-github-actions/reu
#### `on.workflow_call.inputs.<input_id>.type`
Required if input is defined for the `on.workflow_call` keyword. The value of this parameter is a string specifying the data type of the input. This must be one of: `boolean`, `number`, or `string`.
Required if input is defined for the `on.workflow_call` keyword. The value of this parameter is a string specifying the data type of the input. This must be one of: `boolean`, `number`, `string` or `choice`.
### `on.workflow_call.outputs`

View File

@@ -3,6 +3,7 @@ title: Enterprise のコード セキュリティの管理
shortTitle: Manage code security
intro: コードベースからシークレットと脆弱性を排除し、ソフトウェア サプライ チェーンを維持する機能を使用して、開発者のワークフローにセキュリティを組み込むことができます。
versions:
ghec: '*'
ghes: '*'
ghae: '*'
topics:

View File

@@ -8,11 +8,14 @@ redirect_from:
- /admin/configuration/configuring-advanced-security-features
- /admin/advanced-security
versions:
ghec: '*'
ghes: '*'
ghae: '> 3.6'
topics:
- Enterprise
children:
- /enabling-github-advanced-security-for-your-enterprise
- /managing-github-advanced-security-features-for-your-enterprise
- /configuring-code-scanning-for-your-appliance
- /configuring-dependency-review-for-your-appliance
- /configuring-secret-scanning-for-your-appliance

View File

@@ -13,9 +13,9 @@ topics:
- Infrastructure
- Performance
---
## Enabling rate limits for {% data variables.product.prodname_enterprise_api %}
## Enabling rate limits for the {% data variables.product.prodname_enterprise_api %}
Enabling rate limits on {% data variables.product.prodname_enterprise_api %} can prevent overuse of resources by individual or unauthenticated users. For more information, see "[Resources in the REST API](/rest/overview/resources-in-the-rest-api#rate-limiting)."
Enabling rate limits on the {% data variables.product.prodname_enterprise_api %} can prevent overuse of resources by individual or unauthenticated users. For more information, see "[Resources in the REST API](/rest/overview/resources-in-the-rest-api#rate-limiting)."
{% ifversion ghes %}
You can exempt a list of users from API rate limits using the `ghe-config` utility in the administrative shell. For more information, see "[Command-line utilities](/enterprise/admin/configuration/command-line-utilities#ghe-config)."

View File

@@ -29,5 +29,5 @@ You can authorize an existing personal access token, or [create a new personal a
## Further reading
- "[Creating a personal access token](/github/authenticating-to-github/creating-a-personal-access-token)"
- "[Creating a personal access token](/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token)"
- "[About authentication with SAML single sign-on](/articles/about-authentication-with-saml-single-sign-on)"

View File

@@ -1,6 +1,6 @@
---
title: Git へ署名キーを伝える
intro: 'ローカル環境でコミットに署名するには、使う GPG{% ifversion ssh-commit-verification %}SSH{% endif %} または X.509 キーがあることを Git に知らせる必要があります。'
title: Telling Git about your signing key
intro: 'To sign commits locally, you need to inform Git that there''s a GPG{% ifversion ssh-commit-verification %}, SSH,{% endif %} or X.509 key you''d like to use.'
redirect_from:
- /articles/telling-git-about-your-gpg-key
- /articles/telling-git-about-your-signing-key
@@ -15,39 +15,37 @@ topics:
- Identity
- Access management
shortTitle: Tell Git your signing key
ms.openlocfilehash: d40605c196e685e6e5929b5f1ce8e5e85bb197c5
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 09/05/2022
ms.locfileid: '147653355'
---
{% mac %}
## Git へ GPG キーを伝える
## Telling Git about your GPG key
コミッターの ID と、{% ifversion ghae %}{% data variables.product.product_name %}{% else %}{% data variables.product.product_location %}{% endif %} でのアカウントに関連付けられた検証済みのメール アドレスに一致する GPG キーを使っている場合、コミットやタグへの署名を始めることができます。
If you're using a GPG key that matches your committer identity and your verified email address associated with your account on {% ifversion ghae %}{% data variables.product.product_name %}{% else %}{% data variables.product.product_location %}{% endif %}, then you can begin signing commits and signing tags.
{% note %}
コミッターアイデンティティにマッチする GPG キーを持っていない場合、既存のキーとメールアドレスを関連付ける必要があります。 詳細については、「[メールと GPG キーの関連付け](/articles/associating-an-email-with-your-gpg-key)」を参照してください。
If you don't have a GPG key that matches your committer identity, you need to associate an email with an existing key. For more information, see "[Associating an email with your GPG key](/articles/associating-an-email-with-your-gpg-key)".
{% endnote %}
複数の GPG キーを持っている場合、どれを使うかを Git に伝える必要があります。
If you have multiple GPG keys, you need to tell Git which one to use.
{% data reusables.command_line.open_the_multi_os_terminal %} {% data reusables.gpg.list-keys-with-note %} {% data reusables.gpg.copy-gpg-key-id %} {% data reusables.gpg.paste-gpg-key-id %}
1. GPG スイートを使用していない場合は、`zsh` シェルで次のコマンドを実行して、存在する場合は `.zshrc` ファイル、または `.zprofile` ファイルに GPG キーを追加します。
{% data reusables.command_line.open_the_multi_os_terminal %}
{% data reusables.gpg.configure-gpg-signing %}
{% data reusables.gpg.list-keys-with-note %}
{% data reusables.gpg.copy-gpg-key-id %}
{% data reusables.gpg.paste-gpg-key-id %}
1. If you aren't using the GPG suite, run the following command in the `zsh` shell to add the GPG key to your `.zshrc` file, if it exists, or your `.zprofile` file:
```shell
$ if [ -r ~/.zshrc ]; then echo 'export GPG_TTY=$(tty)' >> ~/.zshrc; \
else echo 'export GPG_TTY=$(tty)' >> ~/.zprofile; fi
```
または、`bash` シェルを使用する場合は、次のコマンドを実行します。
Alternatively, if you use the `bash` shell, run this command:
```shell
$ if [ -r ~/.bash_profile ]; then echo 'export GPG_TTY=$(tty)' >> ~/.bash_profile; \
else echo 'export GPG_TTY=$(tty)' >> ~/.profile; fi
```
1. 必要に応じて、PIN またはパスフレーズの入力を求めるメッセージを表示するには、`pinentry-mac` をインストールします。 たとえば、[Homebrew](https://brew.sh/) を使用すると、次のようになります。
1. Optionally, to prompt you to enter a PIN or passphrase when required, install `pinentry-mac`. For example, using [Homebrew](https://brew.sh/):
```shell
$ brew install pinentry-mac
$ echo "pinentry-program $(which pinentry-mac)" >> ~/.gnupg/gpg-agent.conf
@@ -58,56 +56,68 @@ ms.locfileid: '147653355'
{% windows %}
## Git へ GPG キーを伝える
## Telling Git about your GPG key
コミッターの ID と、{% ifversion ghae %}{% data variables.product.product_name %}{% else %}{% data variables.product.product_location %}{% endif %} でのアカウントに関連付けられた検証済みのメール アドレスに一致する GPG キーを使っている場合、コミットやタグへの署名を始めることができます。
If you're using a GPG key that matches your committer identity and your verified email address associated with your account on {% ifversion ghae %}{% data variables.product.product_name %}{% else %}{% data variables.product.product_location %}{% endif %}, then you can begin signing commits and signing tags.
{% note %}
コミッターアイデンティティにマッチする GPG キーを持っていない場合、既存のキーとメールアドレスを関連付ける必要があります。 詳細については、「[メールと GPG キーの関連付け](/articles/associating-an-email-with-your-gpg-key)」を参照してください。
If you don't have a GPG key that matches your committer identity, you need to associate an email with an existing key. For more information, see "[Associating an email with your GPG key](/articles/associating-an-email-with-your-gpg-key)".
{% endnote %}
複数の GPG キーを持っている場合、どれを使うかを Git に伝える必要があります。
If you have multiple GPG keys, you need to tell Git which one to use.
{% data reusables.command_line.open_the_multi_os_terminal %} {% data reusables.gpg.list-keys-with-note %} {% data reusables.gpg.copy-gpg-key-id %} {% data reusables.gpg.paste-gpg-key-id %}
{% data reusables.command_line.open_the_multi_os_terminal %}
{% data reusables.gpg.configure-gpg-signing %}
{% data reusables.gpg.list-keys-with-note %}
{% data reusables.gpg.copy-gpg-key-id %}
{% data reusables.gpg.paste-gpg-key-id %}
{% endwindows %}
{% linux %}
## Git へ GPG キーを伝える
## Telling Git about your GPG key
コミッターの ID と、{% ifversion ghae %}{% data variables.product.product_name %}{% else %}{% data variables.product.product_location %}{% endif %} でのアカウントに関連付けられた検証済みのメール アドレスに一致する GPG キーを使っている場合、コミットやタグへの署名を始めることができます。
If you're using a GPG key that matches your committer identity and your verified email address associated with your account on {% ifversion ghae %}{% data variables.product.product_name %}{% else %}{% data variables.product.product_location %}{% endif %}, then you can begin signing commits and signing tags.
{% note %}
コミッターアイデンティティにマッチする GPG キーを持っていない場合、既存のキーとメールアドレスを関連付ける必要があります。 詳細については、「[メールと GPG キーの関連付け](/articles/associating-an-email-with-your-gpg-key)」を参照してください。
If you don't have a GPG key that matches your committer identity, you need to associate an email with an existing key. For more information, see "[Associating an email with your GPG key](/articles/associating-an-email-with-your-gpg-key)".
{% endnote %}
複数の GPG キーを持っている場合、どれを使うかを Git に伝える必要があります。
If you have multiple GPG keys, you need to tell Git which one to use.
{% data reusables.command_line.open_the_multi_os_terminal %} {% data reusables.gpg.list-keys-with-note %} {% data reusables.gpg.copy-gpg-key-id %} {% data reusables.gpg.paste-gpg-key-id %}
1. GPG キーを `.bashrc` スタートアップ ファイルに追加するには、次のコマンドを実行します。
{% data reusables.command_line.open_the_multi_os_terminal %}
{% data reusables.gpg.configure-gpg-signing %}
{% data reusables.gpg.list-keys-with-note %}
{% data reusables.gpg.copy-gpg-key-id %}
{% data reusables.gpg.paste-gpg-key-id %}
1. To add your GPG key to your `.bashrc` startup file, run the following command:
```bash
$ [ -f ~/.bashrc ] && echo 'export GPG_TTY=$(tty)' >> ~/.bashrc
```
{% endlinux %} {% ifversion ssh-commit-verification %}
{% endlinux %}
{% ifversion ssh-commit-verification %}
## Git に SSH キーについて知らせる
## Telling Git about your SSH key
既存の SSH キーを使ってコミットとタグに署名することも、署名専用に新しいキーを生成することもできます。 詳細については、「[新しい SSH キーを生成して ssh-agent に追加する](/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent)」を参照してください。
You can use an existing SSH key to sign commits and tags, or generate a new one specifically for signing. For more information, see "[Generating a new SSH key and adding it to the ssh-agent](/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent)."
{% data reusables.gpg.ssh-git-version %}
{% data reusables.command_line.open_the_multi_os_terminal %} {% data reusables.gpg.configure-ssh-signing %} {% data reusables.gpg.copy-ssh-public-key %} {% data reusables.gpg.paste-ssh-public-key %}
{% data reusables.command_line.open_the_multi_os_terminal %}
{% data reusables.gpg.configure-ssh-signing %}
{% data reusables.gpg.copy-ssh-public-key %}
{% data reusables.gpg.paste-ssh-public-key %}
{% endif %}
{% data reusables.gpg.x-509-key %}
## 関連項目
## Further reading
- [GitHub アカウントへの新しい SSH キーの追加](/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account)
- [コミットに署名する](/articles/signing-commits)
- [タグに署名する](/articles/signing-tags)
- "[Adding a new SSH key to your GitHub account](/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account)."
- "[Signing commits](/articles/signing-commits)"
- "[Signing tags](/articles/signing-tags)"

View File

@@ -1,6 +1,6 @@
---
title: リポジトリのシークレット スキャンの構成
intro: '高度なセキュリティ パターンに一致するシークレットを探すためにリポジトリをスキャンする方法を {% data variables.product.prodname_dotcom %} で構成することができます。'
title: Configuring secret scanning for your repositories
intro: 'You can configure how {% data variables.product.prodname_dotcom %} scans your repositories for secrets that match advanced security patterns.'
product: '{% data reusables.gated-features.secret-scanning %}'
permissions: 'People with admin permissions to a repository can enable {% data variables.product.prodname_secret_scanning_GHAS %} for the repository.'
redirect_from:
@@ -17,59 +17,71 @@ topics:
- Advanced Security
- Repositories
shortTitle: Configure secret scans
ms.openlocfilehash: 00983398e326997b6472da319d342ab0758018d3
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 09/05/2022
ms.locfileid: '147062003'
---
{% data reusables.secret-scanning.beta %} {% data reusables.secret-scanning.enterprise-enable-secret-scanning %}
## {% data variables.product.prodname_secret_scanning_GHAS %}の有効化
{% data reusables.secret-scanning.beta %}
{% data reusables.secret-scanning.enterprise-enable-secret-scanning %}
{% data variables.product.prodname_secret_scanning_GHAS %}は、組織が所有する任意のリポジトリで有効化できます。 有効にすると、{% data reusables.secret-scanning.secret-scanning-process %}
## Enabling {% data variables.product.prodname_secret_scanning_GHAS %}
{% data reusables.repositories.navigate-to-repo %} {% data reusables.repositories.sidebar-settings %} {% data reusables.repositories.navigate-to-code-security-and-analysis %}
4. {% data variables.product.prodname_advanced_security %} がまだリポジトリで有効化されていなければ、[{% data variables.product.prodname_GH_advanced_security %}] の右側で **[有効化]** をクリックしてください。
{% ifversion fpt or ghec %}![リポジトリで {% data variables.product.prodname_GH_advanced_security %} を有効にする](/assets/images/help/repository/enable-ghas-dotcom.png) {% elsif ghes or ghae %}![リポジトリで {% data variables.product.prodname_GH_advanced_security %} を有効にする](/assets/images/enterprise/3.1/help/repository/enable-ghas.png){% endif %}
5. {% data variables.product.prodname_advanced_security %}の有効化の影響をレビューしてから、 **[このリポジトリで {% data variables.product.prodname_GH_advanced_security %} を有効化]** をクリックしてください。
6. {% data variables.product.prodname_advanced_security %}を有効化すると、Organizationの設定によってはリポジトリで{% data variables.product.prodname_secret_scanning %}が自動的に有効化されることがあります。 "{% data variables.product.prodname_secret_scanning_caps %}" が **[有効]** ボタンと共に表示されている場合でも、 **[有効]** をクリックして{% data variables.product.prodname_secret_scanning %}を有効にする必要があります。 **[無効]** ボタンが表示された場合、{% data variables.product.prodname_secret_scanning %}は既に有効になっています。
![リポジトリで {% data variables.product.prodname_secret_scanning %}を有効にする](/assets/images/help/repository/enable-secret-scanning-dotcom.png) {% ifversion secret-scanning-push-protection %}
7. 必要に応じて、プッシュ保護を有効にする場合は、[プッシュ保護] の右側にある **[有効]** をクリックします。 {% data reusables.secret-scanning.push-protection-overview %} 詳細については、「[ {% data variables.product.prodname_secret_scanning %}を使用したプッシュの保護](/code-security/secret-scanning/protecting-pushes-with-secret-scanning)」を参照してください。
![リポジトリのプッシュ保護を有効にする](/assets/images/help/repository/secret-scanning-enable-push-protection.png) {% endif %} {% ifversion ghae %}
1. {% data variables.product.prodname_secret_scanning %} を有効化する前に、まず {% data variables.product.prodname_GH_advanced_security %} を有効化する必要があります。 [{% data variables.product.prodname_GH_advanced_security %}] の右側にある **[有効]** をクリックします。
![リポジトリで {% data variables.product.prodname_GH_advanced_security %} を有効化する](/assets/images/enterprise/github-ae/repository/enable-ghas-ghae.png)
2. **[このリポジトリで {% data variables.product.prodname_GH_advanced_security %} を有効化する]** をクリックしてアクションを確認します。
![リポジトリで {% data variables.product.prodname_GH_advanced_security %} の有効化を確認する](/assets/images/enterprise/github-ae/repository/enable-ghas-confirmation-ghae.png)
3. [{% data variables.product.prodname_secret_scanning_caps %}] の横にある **[有効]** をクリックします。
![リポジトリで {% data variables.product.prodname_secret_scanning %}を有効化する](/assets/images/enterprise/github-ae/repository/enable-secret-scanning-ghae.png) {% endif %}
You can enable {% data variables.product.prodname_secret_scanning_GHAS %} for any repository that is owned by an organization. Once enabled, {% data reusables.secret-scanning.secret-scanning-process %}
## {% data variables.product.prodname_secret_scanning_GHAS %}からディレクトリを除外する
{% ifversion secret-scanning-enterprise-level %}
{% note %}
*secret_scanning.yml* ファイルを使用して、{% data variables.product.prodname_secret_scanning %}からディレクトリを除外できます。 たとえば、テストまたはランダムに生成されたコンテンツを含むディレクトリを除外できます。
**Note:** If your organization is owned by an enterprise account, an enterprise owner can also enable {% data variables.product.prodname_secret_scanning %} at the enterprise level. For more information, see "[Managing {% data variables.product.prodname_GH_advanced_security %} features for your enterprise](/admin/code-security/managing-github-advanced-security-for-your-enterprise/managing-github-advanced-security-features-for-your-enterprise)."
{% data reusables.repositories.navigate-to-repo %} {% data reusables.files.add-file %}
3. ファイル名フィールドに「 *.github/secret_scanning.yml*」と入力します。
4. **[新しいファイルの編集]** で、`paths-ignore:` と入力してから、{% data variables.product.prodname_secret_scanning %}から除外するパスを入力します。
{% endnote %}
{% endif %}
{% data reusables.repositories.navigate-to-repo %}
{% data reusables.repositories.sidebar-settings %}
{% data reusables.repositories.navigate-to-code-security-and-analysis %}
4. If {% data variables.product.prodname_advanced_security %} is not already enabled for the repository, to the right of "{% data variables.product.prodname_GH_advanced_security %}", click **Enable**.
{% ifversion fpt or ghec %}![Enable {% data variables.product.prodname_GH_advanced_security %} for your repository](/assets/images/help/repository/enable-ghas-dotcom.png)
{% elsif ghes or ghae %}![Enable {% data variables.product.prodname_GH_advanced_security %} for your repository](/assets/images/enterprise/3.1/help/repository/enable-ghas.png){% endif %}
5. Review the impact of enabling {% data variables.product.prodname_advanced_security %}, then click **Enable {% data variables.product.prodname_GH_advanced_security %} for this repository**.
6. When you enable {% data variables.product.prodname_advanced_security %}, {% data variables.product.prodname_secret_scanning %} may automatically be enabled for the repository due to the organization's settings. If "{% data variables.product.prodname_secret_scanning_caps %}" is shown with an **Enable** button, you still need to enable {% data variables.product.prodname_secret_scanning %} by clicking **Enable**. If you see a **Disable** button, {% data variables.product.prodname_secret_scanning %} is already enabled.
![Enable {% data variables.product.prodname_secret_scanning %} for your repository](/assets/images/help/repository/enable-secret-scanning-dotcom.png)
{% ifversion secret-scanning-push-protection %}
7. Optionally, if you want to enable push protection, click **Enable** to the right of "Push protection." {% data reusables.secret-scanning.push-protection-overview %} For more information, see "[Protecting pushes with {% data variables.product.prodname_secret_scanning %}](/code-security/secret-scanning/protecting-pushes-with-secret-scanning)."
![Enable push protection for your repository](/assets/images/help/repository/secret-scanning-enable-push-protection.png)
{% endif %}
{% ifversion ghae %}
1. Before you can enable {% data variables.product.prodname_secret_scanning %}, you need to enable {% data variables.product.prodname_GH_advanced_security %} first. To the right of "{% data variables.product.prodname_GH_advanced_security %}", click **Enable**.
![Enable {% data variables.product.prodname_GH_advanced_security %} for your repository](/assets/images/enterprise/github-ae/repository/enable-ghas-ghae.png)
2. Click **Enable {% data variables.product.prodname_GH_advanced_security %} for this repository** to confirm the action.
![Confirm enabling {% data variables.product.prodname_GH_advanced_security %} for your repository](/assets/images/enterprise/github-ae/repository/enable-ghas-confirmation-ghae.png)
3. To the right of "{% data variables.product.prodname_secret_scanning_caps %}", click **Enable**.
![Enable {% data variables.product.prodname_secret_scanning %} for your repository](/assets/images/enterprise/github-ae/repository/enable-secret-scanning-ghae.png)
{% endif %}
## Excluding directories from {% data variables.product.prodname_secret_scanning_GHAS %}
You can use a *secret_scanning.yml* file to exclude directories from {% data variables.product.prodname_secret_scanning %}. For example, you can exclude directories that contain tests or randomly generated content.
{% data reusables.repositories.navigate-to-repo %}
{% data reusables.files.add-file %}
3. In the file name field, type *.github/secret_scanning.yml*.
4. Under **Edit new file**, type `paths-ignore:` followed by the paths you want to exclude from {% data variables.product.prodname_secret_scanning %}.
``` yaml
paths-ignore:
- "foo/bar/*.js"
```
`*` などの特殊文字を使用して、パスをフィルター処理することができます。 フィルター パターンの詳細については、「[GitHub Actions のワークフロー構文](/actions/reference/workflow-syntax-for-github-actions#filter-pattern-cheat-sheet)」を参照してください。
You can use special characters, such as `*` to filter paths. For more information about filter patterns, see "[Workflow syntax for GitHub Actions](/actions/reference/workflow-syntax-for-github-actions#filter-pattern-cheat-sheet)."
{% note %}
**:**
- `paths-ignore` に 1,000 を超えるエントリがある場合、{% data variables.product.prodname_secret_scanning %}では、最初の 1,000 個のディレクトリのみがスキャンから除外されます。
- *secret_scanning.yml* が 1 MB を超える場合、{% data variables.product.prodname_secret_scanning %}ではファイル全体を無視します。
**Notes:**
- If there are more than 1,000 entries in `paths-ignore`, {% data variables.product.prodname_secret_scanning %} will only exclude the first 1,000 directories from scans.
- If *secret_scanning.yml* is larger than 1 MB, {% data variables.product.prodname_secret_scanning %} will ignore the entire file.
{% endnote %}
{% data variables.product.prodname_secret_scanning %} からの個々のアラートを無視することもできます。 詳細については、「[{% data variables.product.prodname_secret_scanning %}からのアラートの管理](/github/administering-a-repository/managing-alerts-from-secret-scanning#managing-secret-scanning-alerts)」を参照してください。
You can also ignore individual alerts from {% data variables.product.prodname_secret_scanning %}. For more information, see "[Managing alerts from {% data variables.product.prodname_secret_scanning %}](/github/administering-a-repository/managing-alerts-from-secret-scanning#managing-secret-scanning-alerts)."
## 参考資料
## Further reading
- [Organization のセキュリティおよび分析設定を管理する](/organizations/keeping-your-organization-secure/managing-security-and-analysis-settings-for-your-organization)
- [{% data variables.product.prodname_secret_scanning %} のカスタム パターンの定義](/code-security/secret-security/defining-custom-patterns-for-secret-scanning)
- "[Managing security and analysis settings for your organization](/organizations/keeping-your-organization-secure/managing-security-and-analysis-settings-for-your-organization)"
- "[Defining custom patterns for {% data variables.product.prodname_secret_scanning %}](/code-security/secret-security/defining-custom-patterns-for-secret-scanning)"

View File

@@ -85,6 +85,9 @@ The recommended formats explicitly define which versions are used for all direct
| Maven | Java, Scala | `pom.xml` | `pom.xml` |
| npm | JavaScript | `package-lock.json` | `package-lock.json`, `package.json`|
| pip | Python | `requirements.txt`, `pipfile.lock` | `requirements.txt`, `pipfile`, `pipfile.lock`, `setup.py`<sup>[‡]</sup> |
{%- ifversion dependency-graph-dart-support %}
| pub | Dart | `pubspec.lock` | `pubspec.yaml`, `pubspec.lock` |
{%- endif %}
{%- ifversion fpt or ghec or ghes > 3.3 or ghae > 3.3 %}
| Python Poetry | Python | `poetry.lock` | `poetry.lock`, `pyproject.toml` |
{%- endif %}

View File

@@ -1,6 +1,6 @@
---
title: GitHub Appを作成するための開発環境のセットアップ
intro: '新しい{% data variables.product.prodname_github_apps %}を拡張して構築するための基礎を学んでください。'
title: Setting up your development environment to create a GitHub App
intro: 'Learn the foundations for extending and building new {% data variables.product.prodname_github_apps %}.'
redirect_from:
- /apps/quickstart-guides/setting-up-your-development-environment
- /developers/apps/setting-up-your-development-environment-to-create-a-github-app
@@ -12,151 +12,146 @@ versions:
topics:
- GitHub Apps
shortTitle: Development environment
ms.openlocfilehash: 61370cfa0643bcba91cfe78e077346cd40286e1e
ms.sourcegitcommit: fb047f9450b41b24afc43d9512a5db2a2b750a2a
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 09/11/2022
ms.locfileid: '145089943'
---
## はじめに
## Introduction
このガイドは、GitHub Appを設定してサーバー上で実行するために必要なステップを案内します。 GitHub Appには、webhookイベントを管理し、GitHub上のアプリケーションの登録をコードに接続するためのセットアップのステップが必要です。 このガイドのアプリケーションは、拡張して新しいGitHub Appを構築するための基盤の役目を果たします。
This guide will walk through the steps needed to configure a GitHub App and run it on a server. GitHub Apps require some setup steps to manage webhook events and connect the app registration on GitHub to your code. The app in this guide serves as a foundation that you can use to extend and build new GitHub Apps.
このガイドを終えれば、GitHub Appを登録し、webhookイベントを受信するためのWebサーバーをセットアップできます。 Smeeというツールを使ってwebhookペイロードをキャプチャし、ローカルの開発環境に転送する方法を学びます。 このセクションで設定するテンプレートのアプリケーションでは特別な処理は実施されませんが、API を使ってアプリケーション コードの作成を開始し、他の[クイックスタート ガイド](/apps/quickstart-guides/)を完了するために使用できるフレームワークとして機能します。 {% ifversion fpt or ghec %}[GitHub Marketplace](https://github.com/marketplace) と「[GitHub での作業](https://github.com/works-with)」でアプリの成功事例を確認できます。{% endif %}
By the end of this guide you'll have registered a GitHub App and set up a web server to receive webhook events. You'll learn how to use a tool called Smee to capture webhook payloads and forward them to your local development environment. The template app you'll configure in this section won't do anything special yet, but it will serve as a framework you can use to start writing app code using the API or complete other [quickstart guides](/apps/quickstart-guides/). {% ifversion fpt or ghec %}You can check out successful examples of apps on [GitHub Marketplace](https://github.com/marketplace) and [Works with GitHub](https://github.com/works-with).{% endif %}
このプロジェクトを完了すると、GitHub App及びインストールとして認証を受ける方法と、それらの認証方法の違いを理解できます。
After completing this project you will understand how to authenticate as a GitHub App and an installation, and how those authentication methods are different.
以下のステップで、テンプレートのGitHub Appを設定できます。
Here are the steps you'll take to configure the template GitHub App:
1. [新しい Smee チャンネルの開始](#step-1-start-a-new-smee-channel)
1. [新しい GitHub アプリの登録](#step-2-register-a-new-github-app)
1. [秘密キーとアプリ IDの保存](#step-3-save-your-private-key-and-app-id)
1. [ランタイム環境の準備](#step-4-prepare-the-runtime-environment)
1. [GitHub アプリのテンプレート コードのレビュー](#step-5-review-the-github-app-template-code)
1. [サーバーの起動](#step-6-start-the-server)
1. [アカウントへのアプリのインストール](#step-7-install-the-app-on-your-account)
1. [Start a new Smee channel](#step-1-start-a-new-smee-channel)
1. [Register a new GitHub App](#step-2-register-a-new-github-app)
1. [Save your private key and App ID](#step-3-save-your-private-key-and-app-id)
1. [Prepare the runtime environment](#step-4-prepare-the-runtime-environment)
1. [Review the GitHub App template code](#step-5-review-the-github-app-template-code)
1. [Start the server](#step-6-start-the-server)
1. [Install the app on your account](#step-7-install-the-app-on-your-account)
{% data reusables.apps.app-ruby-guides %}
## 前提条件
## Prerequisites
以下に関する基本的な理解があると役立つでしょう。
You may find it helpful to have a basic understanding of the following:
* [GitHub アプリ](/apps/about-apps)
* [Webhook](/webhooks)
* [プログラミング言語の Ruby](https://www.ruby-lang.org/en/)
* [REST API](/rest)
* [GitHub Apps](/apps/about-apps)
* [Webhooks](/webhooks)
* [The Ruby programming language](https://www.ruby-lang.org/en/)
* [REST APIs](/rest)
* [Sinatra](http://sinatrarb.com/)
とはいえ、経験のレベルにかかわらず見ていくことはできます。 その過程で必要な情報にはリンクしていきます!
But you can follow along at any experience level. We'll link out to information you need along the way!
始める前に、このクイックスタートで使われるテンプレートコードのリポジトリをクローンする必要があります。 ターミナルアプリケーションを開いて、コードを保存したいディレクトリに移動してください。 次のコマンドを実行して、[GitHub App template](https://github.com/github-developer/github-app-template) リポジトリを複製します。
Before you begin, you'll need to clone the repository with the template code used in this quickstart. Open your Terminal app and find a directory where you'd like to store the code. Run this command to clone the [GitHub App template](https://github.com/github-developer/github-app-template) repository:
```shell
$ git clone https://github.com/github-developer/github-app-template.git
```
## 手順 1. 新しいSmeeチャンネルの開始
## Step 1. Start a new Smee channel
ローカルのマシンをインターネットに公開することなく、GitHubがwebhookを送信するのを支援するために、Smeeというツールが利用できます。 まず https://smee.io に移動し、 **[新しいチャンネルの開始]** をクリックします。 ローカル コンピューターをインターネットに公開する他のツール ([`ngrok`](https://dashboard.ngrok.com/get-started) [`localtunnel`](https://localtunnel.github.io/www/) など) に既に慣れている場合は、自由に使用してください。
To help GitHub send webhooks to your local machine without exposing it to the internet, you can use a tool called Smee. First, go to https://smee.io and click **Start a new channel**. If you're already comfortable with other tools that expose your local machine to the internet like [`ngrok`](https://dashboard.ngrok.com/get-started) or [`localtunnel`](https://localtunnel.github.io/www/), feel free to use those.
![Smeeの新規チャンネルボタン](/assets/images/smee-new-channel.png)
![The Smee new channel button](/assets/images/smee-new-channel.png)
新しいSmeeのチャンネルを起動すると、GitHubがwebhookペイロードを送信できるユニークなドメインが作成されます。 次のステップで必要なので、このドメインを知っておく必要があります。 `https://smee.io/qrfeVRbFbffd6vD` の一意のドメインの例を次に示します。
Starting a new Smee channel creates a unique domain where GitHub can send webhook payloads. You'll need to know this domain for the next step. Here is an example of a unique domain at `https://smee.io/qrfeVRbFbffd6vD`:
![Smeeのユニークなチャンネル](/assets/images/smee-unique-domain.png)
![A Smee unique channel](/assets/images/smee-unique-domain.png)
次に、ターミナルに戻って以下のステップに従い、SmeeのコマンドラインインターフェースCLIクライアントを実行してください。
Next, go back to the Terminal and follow these steps to run the Smee command-line interface (CLI) client:
{% note %}
**注:** 以下の手順は、Smee チャンネルのページに表示される「CLI の使用」の指示とは多少異なります。 「Node.js クライアントを使用する」または「Probot の組み込みサポートを使用する」の指示に従う必要は **ありません**
**Note:** The following steps are slightly different than the "Use the CLI" instructions you'll see in your Smee channel page. You do **not** need to follow the "Use the Node.js client" or "Using Probot's built-in support" instructions.
{% endnote %}
1. クライアントをインストールします。
1. Install the client:
```shell
$ npm install --global smee-client
```
2. クライアントを実行します (`https://smee.io/qrfeVRbFbffd6vD` を自分のドメインに置き換えます)。
2. Run the client (replacing `https://smee.io/qrfeVRbFbffd6vD` with your own domain):
```shell
$ smee --url https://smee.io/qrfeVRbFbffd6vD --path /event_handler --port 3000
```
次のような出力結果が表示されます。
You should see output like the following:
```shell
Forwarding https://smee.io/qrfeVRbFbffd6vD to http://127.0.0.1:3000/event_handler
Connected https://smee.io/qrfeVRbFbffd6vD
```
`smee --url <unique_channel>` コマンドは、Smee チャンネルによって受信されるすべての Webhook イベントをコンピューター上で稼働している Smee クライアントに転送するように Smee に指示します。 `--path /event_handler` オプションでは、イベントが `/event_handler` ルートに転送されます。これについては、[後のセクション](#step-5-review-the-github-app-template-code)で説明します。 `--port 3000` オプションでは、サーバーがリッスンするポートのポート 3000 が指定されます。 Smeeを使えば、GitHubからのwebhookを受信するためにあなたのマシンがパブリックなインターネットに対してオープンである必要はありません。 また、ブラウザでSmeeURLを開いて、受信したwebhookのペイロードを調べることもできます。
The `smee --url <unique_channel>` command tells Smee to forward all webhook events received by the Smee channel to the Smee client running on your computer. The `--path /event_handler` option forwards events to the `/event_handler` route, which we'll cover in a [later section](#step-5-review-the-github-app-template-code). The `--port 3000` option specifies port 3000, which is the port your server will be listening to. Using Smee, your machine does not need to be open to the public internet to receive webhooks from GitHub. You can also open that Smee URL in your browser to inspect webhook payloads as they come in.
このターミナルのウィンドウは開いたままにしておき、このガイドの残りのステップを完了させるまでの間、Smeeに接続したままにしておくことをおすすめします。 一意のドメインを失うことなく (`ngrok`とは異なります) Smee クライアントの接続を切り、再接続することも _できます_ が、これは接続したままにしておいて、別のターミナル ウィンドウで他のコマンド ラインのタスクを実行する方が簡単な場合もあります。
We recommend leaving this Terminal window open and keeping Smee connected while you complete the rest of the steps in this guide. Although you _can_ disconnect and reconnect the Smee client without losing your unique domain (unlike `ngrok`), you may find it easier to leave it connected and do other command-line tasks in a different Terminal window.
## 手順 2. 新しいGitHub Appの登録
## Step 2. Register a new GitHub App
まだ GitHub アカウントをお持ちでない場合は、今すぐ[作成してください](https://github.com/join)。 続行する前にメールを確認するのを忘れないようにしてください! 新しいアプリを登録するには、GitHub プロファイルの [アプリ設定ページ](https://github.com/settings/apps)にアクセスし、 **[新しい GitHub アプリ]** をクリックします。
If you don't yet have a GitHub account, now is a [great time to join](https://github.com/join). Don't forget to verify your email before continuing! To register a new app, visit the [app settings page](https://github.com/settings/apps) in your GitHub profile, and click **New GitHub App**.
![**New App**を表示しているGitHubのWebサイト](/assets/images/new-app.png)
![GitHub website, showing the **New App**](/assets/images/new-app.png)
表示されるフォームで、アプリケーションの詳細を入力できます。 このページのフィールドに関する一般的な情報については、「[GitHub アプリの作成](/apps/building-github-apps/creating-a-github-app/)」を参照してください。 このガイドについては、いくつかのフィールドに特定のデータを入力する必要があります。
You'll see a form where you can enter details about your app. See "[Creating a GitHub App](/apps/building-github-apps/creating-a-github-app/)" for general information about the fields on this page. For the purposes of this guide, you'll need to enter specific data in a few fields:
{% note %}
**注:** これらの設定は後でいつでも更新して、ホストされたサーバーを指すようにできます。
**Note:** You can always update these settings later to point to a hosted server.
{% endnote %}
* "Homepage URLホームページのURL"には、Smeeが発行したドメインを使用してください。 次に例を示します。
* For the "Homepage URL", use the domain issued by Smee. For example:
![ホームページURLにSmeeのドメインが入力されたフォーム](/assets/images/homepage-url.png)
![Form with Smee domain filled in for homepage URL](/assets/images/homepage-url.png)
* "Webhook URLwebhookのURL"には、やはりSmeeが発行したドメインを使ってください。 次に例を示します。
* For the "Webhook URL", again use the domain issued by Smee. For example:
![webhookURLにSmeeのドメインが入力されたフォーム](/assets/images/webhook-url.png)
![Form with Smee domain filled in for webhook URL](/assets/images/webhook-url.png)
* "Webhook secretwebhookのシークレット"には、webhookのエンドポイントを保護するパスワードを作成してください。 これは、あなたそしてこのフォームを介してGitHubだけが知っているものにするべきです。 パブリックなインターネットから受信したペイロードで、webhookの送信者を検証するのに使われるので、このシークレットは重要です。 GitHub Appの設定ではこのwebhookのシークレットはオプションとなっており、これはほとんどの場合正しいですが、このテンプレートのアプリケーションコードを動作させるためには、webhookのシークレットは設定しなければなりません。
* For the "Webhook secret", create a password to secure your webhook endpoints. This should be something that only you (and GitHub, via this form) know. The secret is important because you will be receiving payloads from the public internet, and you'll use this secret to verify the webhook sender. Note that the GitHub App settings say the webhook secret is optional, which is true in most cases, but for the template app code to work, you must set a webhook secret.
![webhookのシークレットが入力されたフォーム](/assets/images/webhook-secret.png)
![Form with webhook secret filled in](/assets/images/webhook-secret.png)
* [アクセス許可と Webhook] のページでは、アプリケーションの一連のアクセス許可を指定できます。これにより、アプリケーションがどれだけのデータにアクセスできるかが決まります。 [リポジトリのアクセス許可] セクションで、下にある [メタデータ] にスクロールして、`Access: Read-only` を選択します。 このテンプレートアプリケーションを拡張することにしたら、後でこれらの権限を更新できます。
* On the Permissions & Webhooks page, you can specify a set of permissions for your app, which determines how much data your app has access to. Under the "Repository permissions"
section, scroll down to "Metadata" and select `Access: Read-only`. If you decide to extend this template app, you can update these permissions later.
* [アクセス許可と Webhook] のページの下部で、これがプライベートのアプリケーションなのかパブリックのアプリケーションなのかを指定します。 これは、アプリケーションを誰がインストールできるのか、すなわちあなただけなのか、誰でもできるのかを指します。 ここでは、 **[このアカウントでのみ]** を選択して、アプリをプライベートのままにします。
* At the bottom of the Permissions & Webhooks page, specify whether this is a private app or a public app. This refers to who can install it: just you, or anyone in the world? For now, leave the app as private by selecting **Only on this account**.
![GitHub Appのプライバシー](/assets/images/create_app.png)
![GitHub App privacy](/assets/images/create_app.png)
**[GitHub アプリの作成]** をクリックしてアプリを作成します。
Click **Create GitHub App** to create your app!
## 手順 3. 秘密鍵とApp IDの保存
## Step 3. Save your private key and App ID
アプリを作成すると、[アプリ設定ページ](https://github.com/settings/apps)に戻ります。 ここで行うことがあと2つあります。
After you create your app, you'll be taken back to the [app settings page](https://github.com/settings/apps). You have two more things to do here:
* **アプリケーションの秘密鍵を生成してください。** これは、後でアプリを認証するために必要です。 ページを下にスクロールし、 **[秘密キーの生成]** をクリックします。 生成される `PEM` ファイル ( _`app-name`_ - _`date`_ -`private-key.pem` など) をディレクトリに保存すると、このディレクトリで再確認できます。
* **Generate a private key for your app.** This is necessary to authenticate your app later on. Scroll down on the page and click **Generate a private key**. Save the resulting `PEM` file (called something like _`app-name`_-_`date`_-`private-key.pem`) in a directory where you can find it again.
![秘密鍵の生成ダイアログ](/assets/images/private_key.png)
![The private key generation dialog](/assets/images/private_key.png)
* **GitHub がアプリに設定したアプリ ID を確認してください。** ランタイム環境を準備するにはこれが必要です。
* **Note the app ID GitHub has assigned your app.** You'll need this to prepare your runtime environment.
<img src="/assets/images/app_id.png" alt="Your app's ID number" width="200px"/>
## 手順 4. ランタイム環境の準備
## Step 4. Prepare the runtime environment
情報を保護するために、アプリケーションに関するすべてのシークレットは、直接コードに埋め込むのではなく、アプリケーションが見つけることができるコンピュータのメモリ中に置いておくことをおすすめします。 [dotenv](https://github.com/bkeepers/dotenv) と呼ばれる便利な開発ツールは、プロジェクト固有の環境変数を `.env` ファイルから `ENV` にロードします。 `.env` ファイルを GitHub にチェックインしないでください。 これは、パブリックなインターネット上にさらしたくない機密情報を保存するローカルファイルです。 これを防止するために、`.env` ファイルがリポジトリの [`.gitignore`](/github/getting-started-with-github/ignoring-files/) ファイルに既に含まれています。
To keep your information secure, we recommend putting all your app-related secrets in your computer's memory where your app can find them, rather than putting them directly in your code. A handy development tool called [dotenv](https://github.com/bkeepers/dotenv) loads project-specific environment variables from a `.env` file to `ENV`. Never check your `.env` file into GitHub. This is a local file that stores sensitive information that you don't want on the public internet. The `.env` file is already included in the repository's [`.gitignore`](/github/getting-started-with-github/ignoring-files/) file to prevent that.
[[前提条件] セクション](#prerequisites)でダウンロードしたテンプレート コードには、既に `.env-example` という名前のサンプル ファイルが含まれています。 サンプル ファイルの名前を `.env-example` から `.env` に変更するか、`.env` という名前の `.env-example` ファイルのコピーを作成します。 まだ dotenv をインストールしていませんが、`bundle install` を実行するときは、このクイック スタートの後半でインストールします。 **注:** このガイドの手順を参照するクイック スタートには、`.env-example` ファイルに追加の環境変数が含まれている場合があります。 それらの追加の環境変数を設定するためのガイダンスについては、GitHub上でクローンしたプロジェクトのクイックスタートガイドを参照してください。
The template code you downloaded in the [Prerequisites section](#prerequisites) already has an example file called `.env-example`. Rename the example file from `.env-example` to `.env` or create a copy of the `.env-example` file called `.env`. You haven't installed dotenv yet, but you will install it later in this quickstart when you run `bundle install`. **Note:** Quickstarts that reference the steps in this guide may include additional environment variables in the `.env-example` file. Reference the quickstart guide for the project you've cloned on GitHub for guidance setting those additional environment variables.
次の変数を `.env` ファイルに追加する必要があります。
You need to add these variables to the `.env` file:
* _`GITHUB_PRIVATE_KEY`_ : [前に生成して保存した](#step-3-save-your-private-key-and-app-id)秘密キーを追加します。 テキスト エディターで `.pem` ファイルを開くか、次のコマンド ラインを使用してファイルの内容を表示します: `cat path/to/your/private-key.pem`。 ファイルの内容全体を `.env` ファイル内の `GITHUB_PRIVATE_KEY` の値としてコピーします。 **注:** PEM ファイルには複数行があるため、以下の例のように値の周りに引用符を追加しなければなりません。
* _`GITHUB_APP_IDENTIFIER`_ : 前のセクションで説明したアプリ ID を使用します。
* _`GITHUB_WEBHOOK_SECRET`_ : Webhook シークレットを追加します。
* _`GITHUB_PRIVATE_KEY`_: Add the private key you [generated and saved previously](#step-3-save-your-private-key-and-app-id). Open the `.pem` file with a text editor or use the command line to display the contents of the file: `cat path/to/your/private-key.pem`. Copy the entire contents of the file as the value of `GITHUB_PRIVATE_KEY` in your `.env` file. **Note:** Because the PEM file is more than one line you'll need to add quotes around the value like the example below.
* _`GITHUB_APP_IDENTIFIER`_: Use the app ID you noted in the previous section.
* _`GITHUB_WEBHOOK_SECRET`_: Add your webhook secret.
`.env` ファイルの例を次に示します。
Here is an example `.env` file:
```
GITHUB_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
@@ -168,26 +163,26 @@ GITHUB_APP_IDENTIFIER=12345
GITHUB_WEBHOOK_SECRET=your webhook secret
```
## 手順 5. GitHub Appのテンプレートコードのレビュー
## Step 5. Review the GitHub App template code
テンプレートのアプリケーションコードには、すべてのGitHub Appが必要とする多少のコードがすでに含まれています。 このセクションでは、GitHub Appのテンプレートにすでにあるコードを見ていきます。 このセクションで完了しなければならないステップはありません。 テンプレート コードについて既にご存知の場合は、手順をスキップして「[手順 6. サーバーを起動する](#step-6-start-the-server)」に進んでください。
The template app code already contains some code that every GitHub App will need. This sections walks you through the code that already exists in the GitHub App template. There aren't any steps that you need to complete in this section. If you're already familiar with the template code, you can skip ahead to "[Step 6. Start the server](#step-6-start-the-server)."
任意のテキスト エディターで `template_server.rb` ファイルを開きます。 このファイルには、全体を通じてテンプレートコードの追加のコンテキストを提供するコメントがあります。 これらのコメントを注意深く読んで、さらには作成する新しいコードに添えて独自のコメントを追加することをおすすめします。
Open up the `template_server.rb` file in your favorite text editor. You'll see comments throughout this file that provide additional context for the template code. We recommend reading those comments carefully and even adding your own comments to accompany new code you write.
ファイルの先頭には `set :port 3000` があります。これにより、Web サーバーを起動するときに使われるポートを設定して、「[手順1. 新しい Smee チャンネル の開始](#step-1-start-a-new-smee-channel)」で Webhook ペイロードをリダイレクトしたポートとマッチさせることができます。
At the top of the file you'll see `set :port 3000`, which sets the port used when starting the web server to match the port you redirected your webhook payloads to in "[Step 1. Start a new Smee channel](#step-1-start-a-new-smee-channel)."
次に表示されるコードは `class GHApp < Sinatra::Application` の宣言です。 GitHub Appのすべてのコードは、このクラスの中に書いていきます。
The next code you'll see is the `class GHApp < Sinatra::Application` declaration. You'll write all of the code for your GitHub App inside this class.
そのままの状態では、テンプレート中のこのクラスは以下のことを行います。
* [環境変数を読み取る](#read-the-environment-variables)
* [ログ記録を有効にする](#turn-on-logging)
* [ビフォア フィルターを定義する](#define-a-before-filter)
* [ルート ハンドラーを定義する](#define-a-route-handler)
* [ヘルパー メソッドを定義する](#define-the-helper-methods)
Out of the box, the class in the template does the following things:
* [Read the environment variables](#read-the-environment-variables)
* [Turn on logging](#turn-on-logging)
* [Define a before filter](#define-a-before-filter)
* [Define the route handler](#define-a-route-handler)
* [Define the helper methods](#define-the-helper-methods)
### 環境変数の読み取り
### Read the environment variables
このクラスで最初に行うことは、「[手順 4. ランタイム環境を準備](#step-4-prepare-the-runtime-environment)」で設定した 3 つの環境変数を読み取り、後で使用するために変数に格納します。
The first thing that this class does is read the three environment variables you set in "[Step 4. Prepare the runtime environment](#step-4-prepare-the-runtime-environment)" and store them in variables to use later:
``` ruby
# Expects that the private key in PEM format. Converts the newlines
@@ -201,9 +196,9 @@ WEBHOOK_SECRET = ENV['GITHUB_WEBHOOK_SECRET']
APP_IDENTIFIER = ENV['GITHUB_APP_IDENTIFIER']
```
### ログ記録を有効にする
### Turn on logging
次は、Sinatraにおけるデフォルトの環境である開発の間、ロギングを有効にするコードブロックです。 このコードは `DEBUG` レベルでログを有効化し、アプリケーションの開発中にターミナルに有益な出力を表示します。
Next is a code block that enables logging during development, which is the default environment in Sinatra. This code turns on logging at the `DEBUG` level to show useful output in the Terminal while you are developing the app:
``` ruby
# Turn on Sinatra's verbose logging during development
@@ -212,9 +207,9 @@ configure :development do
end
```
### ビフォアフィルタの定義
### Define a before filter
Sinatra では、ルート ハンドラーの前にコードを実行できる[ビフォア フィルター](https://github.com/sinatra/sinatra#filters)を使用します。 テンプレートの `before` ブロックは、4 つの[ヘルパー メソッド](https://github.com/sinatra/sinatra#helpers)を呼び出します。 テンプレート アプリでは、[後のセクション](#define-the-helper-methods)でこれらのヘルパー メソッドが定義されます。
Sinatra uses [before filters](https://github.com/sinatra/sinatra#filters) that allow you to execute code before the route handler. The `before` block in the template calls four [helper methods](https://github.com/sinatra/sinatra#helpers). The template app defines those helper methods in a [later section](#define-the-helper-methods).
``` ruby
# Before each request to the `/event_handler` route
@@ -227,9 +222,9 @@ before '/event_handler' do
end
```
### ルートハンドラの定義
### Define a route handler
テンプレートコードには、空のルートが含まれています。 このコードは、`/event_handler` ルートへのすべての `POST` 要求を処理します。 このクイックスタートではこのイベント ハンドラーに関する記述はありませんが、このテンプレート アプリを拡張する方法の例については、他の[クイックスタート ガイド](/apps/quickstart-guides/)を参照してください。
An empty route is included in the template code. This code handles all `POST` requests to the `/event_handler` route. You won't write this event handler in this quickstart, but see the other [quickstart guides](/apps/quickstart-guides/) for examples of how to extend this template app.
``` ruby
post '/event_handler' do
@@ -237,35 +232,35 @@ post '/event_handler' do
end
```
### ヘルパー メソッドを定義する
### Define the helper methods
このテンプレートのヘルパーメソッドは、最も難しい処理のほとんどを行います。 コードのこのセクションでは、4つのヘルパーメソッドが定義されています。
The helper methods in this template do most of the heavy lifting. Four helper methods are defined in this section of the code.
#### webhookペイロードの処理
#### Handling the webhook payload
最初のメソッドの `get_payload_request` は、Webhook ペイロードをキャプチャし、JSON 形式に変換します。これにより、ペイロードのデータへのアクセスがはるかに簡単になります。
The first method `get_payload_request` captures the webhook payload and converts it to JSON format, which makes accessing the payload's data much easier.
#### webhookの署名の検証
#### Verifying the webhook signature
2 番目のメソッドの `verify_webhook_signature` は Webhook シグネチャの検証を実行して、GitHub がこのイベントを生成したことを確認します。 `verify_webhook_signature` ヘルパー メソッドのコードの詳細については、「[Webhook のセキュリティ保護](/webhooks/securing/)」を参照してください。 webhookがセキュアであれば、このメソッドは受け取ったペイロードのすべてをターミナルに出力します。 ロガーのコードはWebサーバーが動作していることを確認するのに役立ちますが、後でいつでも取り除くことができます。
The second method `verify_webhook_signature` performs verification of the webhook signature to ensure that GitHub generated the event. To learn more about the code in the `verify_webhook_signature` helper method, see "[Securing your webhooks](/webhooks/securing/)." If the webhooks are secure, this method will log all incoming payloads to your Terminal. The logger code is helpful in verifying your web server is working but you can always remove it later.
#### GitHub Appとしての認証
#### Authenticating as a GitHub App
API 呼び出しを行うには、[Octokit ライブラリ](http://octokit.github.io/octokit.rb/)を使用します。 このライブラリで何か面白いことを行うには、あなた、あるいはむしろアプリケーションが認証を受ける必要があります。 GitHub Appには2つの認証方法があります。
To make API calls, you'll be using the [Octokit library](http://octokit.github.io/octokit.rb/). Doing anything interesting with this library will require you, or rather your app, to authenticate. GitHub Apps have two methods of authentication:
- [JSON Web トークン (JWT)](https://jwt.io/introduction) を使用した GitHub アプリとしての認証。
- インストールアクセストークンを使って特定のGitHub Appのインストールとして認証を受ける。
- Authenticating as a GitHub App using a [JSON Web Token (JWT)](https://jwt.io/introduction).
- Authenticating as a specific installation of a GitHub App using an installation access token.
[次のセクション](#authenticating-as-an-installation)では、インストールとしての認証について説明します。
You'll learn about authenticating as an installation in the [next section](#authenticating-as-an-installation).
[GitHub アプリとしての認証](/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app)を実施すると、次のいくつかの操作を実行できます。
[Authenticating as a GitHub App](/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) lets you do a couple of things:
* GitHub Appに関する高レベルの管理情報を取得できます。
* アプリケーションのインストールのため、アクセストークンをリクエストできます。
* You can retrieve high-level management information about your GitHub App.
* You can request access tokens for an installation of the app.
たとえば、GitHub Appとして認証を受けて、そのアプリケーションをインストールしたアカウントOrganization及び個人のリストを取得できます。 しかし、この認証方法ではAPIを使って多くのことは行えません。 インストールの代わりにリポジトリのデータにアクセスして操作を行うには、インストールとして認証を受けなければなりません。 そのためには、まずGitHub Appとして認証を受けて、インストールアクセストークンをリクエストしなければなりません。
For example, you would authenticate as a GitHub App to retrieve a list of the accounts (organization and personal) that have installed your app. But this authentication method doesn't allow you to do much with the API. To access a repository's data and perform operations on behalf of the installation, you need to authenticate as an installation. To do that, you'll need to authenticate as a GitHub App first to request an installation access token.
Octokit.rb ライブラリを使用して API 呼び出しを行う前に、GitHub アプリとして認証された [Octokit クライアント](http://octokit.github.io/octokit.rb/Octokit/Client.html)を初期化する必要があります。 `authenticate_app` ヘルパー メソッドでこの処理が行われます。
Before you can use the Octokit.rb library to make API calls, you'll need to initialize an [Octokit client](http://octokit.github.io/octokit.rb/Octokit/Client.html) authenticated as a GitHub App. The `authenticate_app` helper method does just that!
``` ruby
# Instantiate an Octokit client authenticated as a GitHub App.
@@ -293,11 +288,11 @@ def authenticate_app
end
```
上記のコードは [JSON Web トークン (JWT)](https://jwt.io/introduction) を生成し、これを (アプリの秘密キーと共に) 使用して Octokit クライアントを初期化します。 GitHubは、保存されたアプリケーションの公開鍵でトークンを検証することによって、リクエストの認証を確認します。 このコードの仕組みの詳細については、「[GitHub アプリとしての認証](/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app)」を参照してください。
The code above generates a [JSON Web Token (JWT)](https://jwt.io/introduction) and uses it (along with your app's private key) to initialize the Octokit client. GitHub checks a request's authentication by verifying the token with the app's stored public key. To learn more about how this code works, see "[Authenticating as a GitHub App](/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app)."
#### インストールとして認証を行う
#### Authenticating as an installation
_インストール_ とは、アプリをインストールしたユーザーまたは組織のアカウントを指します。 ある人がアプリケーションを複数のリポジトリにインストールした場合でも、それらは同じアカウント内なので1つのインストールとしかカウントされません。 最後のヘルパー メソッドの `authenticate_installation` は、インストールとして認証された [Octokit クライアント](http://octokit.github.io/octokit.rb/Octokit/Client.html)を初期化します。 このOctokitクライアントは、認証されたAPI呼び出しを行うために使われます。
An _installation_ refers to any user or organization account that has installed the app. Even if someone installs the app on more than one repository, it only counts as one installation because it's within the same account. The last helper method `authenticate_installation` initializes an [Octokit client](http://octokit.github.io/octokit.rb/Octokit/Client.html) authenticated as an installation. This Octokit client is what you'd use to make authenticated API calls.
``` ruby
# Instantiate an Octokit client authenticated as an installation of a
@@ -309,40 +304,40 @@ def authenticate_installation(payload)
end
```
[`create_app_installation_access_token`](http://octokit.github.io/octokit.rb/Octokit/Client/Apps.html#create_app_installation_access_token-instance_method) Octokit メソッドはインストール トークンを作成します。 このメソッドは、2つの引数を取ります。
The [`create_app_installation_access_token`](http://octokit.github.io/octokit.rb/Octokit/Client/Apps.html#create_app_installation_access_token-instance_method) Octokit method creates an installation token. This method accepts two arguments:
* Installation (integer): GitHub AppのインストールのID
* オプション (ハッシュ、既定値 `{}`): カスタマイズ可能な一連のオプション
* Installation (integer): The ID of a GitHub App installation
* Options (hash, defaults to `{}`): A customizable set of options
GitHub アプリが Webhook を受け取るたびに、`id` とともに `installation` オブジェクト が含まれます。 GitHub アプリとして認証されたクライアントを使用すると、この ID を `create_app_installation_access_token` メソッドに渡して、インストールごとにアクセス トークンを生成できます。 メソッドにはオプションを渡していないので、オプションはデフォルトの空のハッシュになります。 [ドキュメント](/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation)を再確認すると、`create_app_installation_access_token` の応答に 2 つのフィールド (`token` `expired_at`) が含まれることを確認できます。 テンプレートのコードはレスポンス中のトークンを選択し、インストールクライアントを初期化します。
Any time a GitHub App receives a webhook, it includes an `installation` object with an `id`. Using the client authenticated as a GitHub App, you pass this ID to the `create_app_installation_access_token` method to generate an access token for each installation. Since you're not passing any options to the method, the options default to an empty hash. If you look back at [the docs](/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation), you can see the response for `create_app_installation_access_token` includes two fields: `token` and `expired_at`. The template code selects the token in the response and initializes an installation client.
このメソッドを利用して、アプリケーションは新しいwebhookのペイロードを受信するたびに、そのイベントをトリガーしたインストールのためのクライアントを作成します。 この認証プロセスによって、GitHub Appは任意のアカウントのすべてのインストールで動作できます。
With this method in place, each time your app receives a new webhook payload, it creates a client for the installation that triggered the event. This authentication process enables your GitHub App to work for all installations on any account.
これでAPI呼び出しを発行する準備ができました!
Now you're ready to start making API calls!
## 手順 6. サーバーを起動する
## Step 6. Start the server
このアプリケーションではまだ何も _実行_ できませんが、この時点でサーバー上で稼働させることができます。
Your app doesn't _do_ anything yet, but at this point, you can get it running on the server.
Smeeは、ターミナルの現在のタブで動作させ続けておいてください。 新しいタブを開き、[テンプレート アプリ コードを複製した](#prerequisites)ディレクトリで `cd` を実施します。 このリポジトリの Ruby コードにより、[Sinatra](http://sinatrarb.com/) Web サーバーが起動されます。 このコードにはいくつかの依存関係があります。 それらは以下のようにしてインストールできます。
Keep Smee running in the current tab in your Terminal. Open a new tab and `cd` into the directory where you [cloned the template app code](#prerequisites). The Ruby code in this repository will start up a [Sinatra](http://sinatrarb.com/) web server. This code has a few dependencies. You can install these by running:
```shell
$ gem install bundler
```
続けて次を入力します。
Followed by:
```shell
$ bundle install
```
依存関係をインストールしたら、サーバーを起動できます。
With the dependencies installed, you can start the server:
```shell
$ bundle exec ruby template_server.rb
```
次のように、応答が表示されます。
You should see a response like:
```shell
> == Sinatra (v2.0.3) has taken the stage on 3000 for development with backup from Puma
@@ -354,25 +349,25 @@ $ bundle exec ruby template_server.rb
> Use Ctrl-C to stop
```
エラーが表示された場合は、`template_server.rb` を含むディレクトリに `.env` ファイルが作成されていることを確認します。
If you see an error, make sure you've created the `.env` file in the directory that contains `template_server.rb`.
サーバーが稼働すると、ブラウザーで `http://localhost:3000` に移動してテストを実施できます。 アプリケーションが期待どおりに動作していれば、役に立つエラーページが表示されます。
Once the server is running, you can test it by going to `http://localhost:3000` in your browser. If the app works as expected, you'll see a helpful error page:
<img src="/assets/images/sinatra-404.png" alt="Sinatra's 404 error page" width="500px"/>
うまくいっています! これはエラー ページですが、_Sinatra_ のエラー ページであるため、期待どおりにアプリケーションがサーバーに接続されています。 このメッセージが表示されているのは、他に表示するものを何もアプリケーションに加えていないからです。
This is good! Even though it's an error page, it's a _Sinatra_ error page, which means your app is connected to the server as expected. You're seeing this message because you haven't given the app anything else to show.
## 手順 7. アカウントへのアプリケーションのインストール
## Step 7. Install the app on your account
サーバーがアプリケーションを待ち受けているかは、受信するイベントをトリガーすればテストできます。 テストできる簡単なイベントは、GitHub アカウントにアプリをインストールすることです。この場合、[`installation`](/webhooks/event-payloads/#installation) イベントを送信する必要があります。 アプリがイベントを受け取ると、`template_server.rb` を開始した [ターミナル] タブにいくつかの出力が表示されます。
You can test that the server is listening to your app by triggering an event for it to receive. A simple event you can test is installing the app on your GitHub account, which should send the [`installation`](/webhooks/event-payloads/#installation) event. If the app receives it, you should see some output in the Terminal tab where you started `template_server.rb`.
アプリをインストールするには、[アプリ設定ページ](https://github.com/settings/apps)にアクセスし、アプリを選択し、サイドバーの **[アプリのインストール]** をクリックします。 ユーザー名の横にある **[インストール]** をクリックします。
To install the app, visit the [app settings page](https://github.com/settings/apps), choose your app, and click **Install App** in the sidebar. Next to your username, click **Install**.
アプリケーションをすべてのリポジトリにインストールするか、選択したリポジトリにインストールするかを尋ねられます。 _すべての_ リポジトリにアプリをインストールしたくない場合は、それでも問題ありません。 テスト用にサンドボックスリポジトリを作成し、そこにアプリケーションをインストールしても良いでしょう。
You'll be asked whether to install the app on all repositories or selected repositories. If you don't want to install the app on _all_ of your repositories, that's okay! You may want to create a sandbox repository for testing purposes and install your app there.
<img src="/assets/images/install_permissions.png" alt="App installation permissions" width="500px"/>
**[インストール]** をクリックした後、ターミナルの出力を確認します。 次のような結果が表示されます。
After you click **Install**, look at the output in your Terminal. You should see something like this:
```shell
> D, [2018-06-29T15:45:43.773077 #30488] DEBUG -- : ---- received event integration_installation
@@ -383,31 +378,31 @@ $ bundle exec ruby template_server.rb
> 192.30.252.39 - - [29/Jun/2018:15:45:43 -0400] "POST / HTTP/2" 200 2 0.0019
```
うまくいっています! これは、GitHubアカウントにアプリケーションがインストールされたという通知をアプリケーションが受信したということです。 このような出力があれば、アプリケーションはサーバー上で期待どおりに動作しています。 🙌
This is good news! It means your app received a notification that it was installed on your GitHub account. If you see something like this, your app is running on the server as expected. 🙌
出力が表示されない場合は、Smee が別の [ターミナル] タブで正しく実行されていることを確認します。Smee を再起動する必要がある場合は、アプリを _アンインストール_ して _再インストール_ することで、もう一度アプリに `installation` イベントを送信し、ターミナルで出力を確認する必要があることに注意してください。 Smee に問題がない場合は、「[トラブルシューティング](#troubleshooting)」セクションで他のアイデアを参照してください。
If you don't see the output, make sure Smee is running correctly in another Terminal tab. If you need to restart Smee, note that you'll also need to _uninstall_ and _reinstall_ the app to send the `installation` event to your app again and see the output in Terminal. If Smee isn't the problem, see the "[Troubleshooting](#troubleshooting)" section for other ideas.
上記のターミナル出力がどこから来ているのか疑問に思う場合は、`template_server.rb` の[アプリのテンプレート コード](#prerequisites)に記述されています。
If you're wondering where the Terminal output above is coming from, it's written in the [app template code](#prerequisites) in `template_server.rb`.
## トラブルシューティング
## Troubleshooting
以下は、いくつかの一般的な問題と推奨される解決策です。 他の問題が生じた場合は、{% data variables.product.prodname_support_forum_with_url %}で助けやアドバイスを求めることができます。
Here are a few common problems and some suggested solutions. If you run into any other trouble, you can ask for help or advice in the {% data reusables.support.prodname_support_forum_with_url %}.
* **Q:** Smee コマンド ライン クライアントをインストールしようとすると、次のエラーが表示されます。
* **Q:** When I try to install the Smee command-line client, I get the following error:
```shell
> npm: command not found
```
**A:** npm がインストールされていないようです。 npm をインストールする最もよい方法は、 https://nodejs.org から Node.js パッケージをダウンロードし、使用中のシステムのインストールの指示に従うことです。 npmはNode.jsと併せてインストールされます。
**A:** Looks like you don't have npm installed. The best way to install it is to download the Node.js package at https://nodejs.org and follow the installation instructions for your system. npm will be installed alongside Node.js.
* **Q:** サーバーを実行すると、次のエラーが表示されます。
* **Q:** When I run the server, I get the following error:
```shell
> server.rb:38:in `initialize': Neither PUB key nor PRIV key: header too long (OpenSSL::PKey::RSAError)
```
**A:** おそらく、秘密キーの環境変数を適切に設定していないと思われます。 `GITHUB_PRIVATE_KEY` 変数は次のようになるはずです。
**A:** You probably haven't set up your private key environment variable quite right. Your `GITHUB_PRIVATE_KEY` variable should look like this:
```
GITHUB_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
@@ -417,42 +412,42 @@ $ bundle exec ruby template_server.rb
-----END RSA PRIVATE KEY-----"
```
正しい公開キーが `.env` ファイルにコピーされていることを再確認します。
Double-check that you've copied the correct public key into your `.env` file.
* **Q:** サーバーを実行すると、次のエラーでクラッシュします。
* **Q:** When I run the server, it crashes with this error:
```shell
> Octokit::Unauthorized ... 401 - Bad credentials`
```
**A:** GitHub アプリとして認証されているものの、インストールとして認証されていない可能性があります。 「[インストールとして認証を行う](#authenticating-as-an-installation)」のすべての手順に従い、`@app_client` インスタンス変数 (JWT で認証) ではなく、API 操作のための `@installation_client` インスタンス変数 (インストール アクセス トークンで認証) を使用してください。 `@app_client` はアプリケーションに関する高レベルの情報のみを抽出し、インストール アクセス トークンを取得できます。 それ以外のことをAPIで行うことはあまりできません。
**A:** You may be authenticated as a GitHub App but not as an installation. Make sure you follow all the steps under "[Authenticate as an installation](#authenticating-as-an-installation)," and use the `@installation_client` instance variable (authenticated with an installation access token) for your API operations, not the `@app_client` instance variable (authenticated with a JWT). The `@app_client` can only retrieve high-level information about your app and obtain installation access tokens. It can't do much else in the API.
* **Q:** サーバーがイベントをリッスンしていません。 Smeeクライアントはターミナルウィンドウで動作していて、アプリケーションをGitHubのリポジトリにインストールしていますが、サーバーを動作させているターミナルウィンドウに出力がありません。
* **Q:** My server isn't listening to events! The Smee client is running in a Terminal window, and I'm installing the app on a repository on GitHub, but I don't see any output in the Terminal window where I'm running the server.
**A:** Smee コマンドのパラメーターが間違っていて Smee クライアントが動作していないか、GitHub アプリの設定に正しい Smee のドメインがないかもしれません。 まず、Smee クライアントが [ターミナル] タブで実行されていることを確認します。問題がない場合は、[アプリ設定ページ](https://github.com/settings/apps)にアクセスし、「[手順 2. 新しい GitHub アプリの登録](#step-2-register-a-new-github-app)」で表示されるフィールドをクリックします。 これらのフィールドのドメインが、「[手順 1. 新しい Smee チャンネルの開始](#step-1-start-a-new-smee-channel)」の `smee -u <unique_channel>` コマンドで 使用したドメインと一致していることを確認します。 上記の方法でもうまくいかない場合は、`--path` `--port` のオプションを含む完全な Smee コマンド (`smee --url https://smee.io/qrfeVRbFbffd6vD --path /event_handler --port 3000` など) を実行していることを確認します (`https://smee.io/qrfeVRbFbffd6vD` を独自の Smee ドメインに置き換えてください)。
**A:** You may not be running the Smee client, running the Smee command with the wrong parameters or you may not have the correct Smee domain in your GitHub App settings. First check to make sure the Smee client is running in a Terminal tab. If that's not the problem, visit your [app settings page](https://github.com/settings/apps) and check the fields shown in "[Step 2. Register a new GitHub App](#step-2-register-a-new-github-app)." Make sure the domain in those fields matches the domain you used in your `smee -u <unique_channel>` command in "[Step 1. Start a new Smee channel](#step-1-start-a-new-smee-channel)." If none of the above work, check that you are running the full Smee command including the `--path` and `--port` options, for example: `smee --url https://smee.io/qrfeVRbFbffd6vD --path /event_handler --port 3000` (replacing `https://smee.io/qrfeVRbFbffd6vD` with your own Smee domain).
* **Q:** デバッグ出力で `Octokit::NotFound` 404 エラーが発生します。
* **Q:** I'm getting an `Octokit::NotFound` 404 error in my debug output:
```
2018-12-06 15:00:56 - Octokit::NotFound - POST {% data variables.product.api_url_code %}/app/installations/500991/access_tokens: 404 - Not Found // See: /v3/apps/#create-a-new-installation-token:
```
**A:** `.env` ファイル内の変数が正しいことを確認します。 `bash_profile` のような他の環境変数ファイルで同じ変数を設定していないことを確認してください。 アプリケーションが使用している環境変数は、アプリケーションのコードに `puts` 文を追加して実行し直すことで確認できます。 たとえば、正しい秘密キーが設定されているかを確認するには、アプリケーションのコードに `puts PRIVATE_KEY` を追加できます。
**A:** Ensure the variables in your `.env` file are correct. Make sure that you have not set identical variables in any other environment variable files like `bash_profile`. You can check the environment variables your app is using by adding `puts` statements to your app code and re-running the code. For example, to ensure you have the correct private key set, you could add `puts PRIVATE_KEY` to your app code:
```
PRIVATE_KEY = OpenSSL::PKey::RSA.new(ENV['GITHUB_PRIVATE_KEY'].gsub('\n', "\n"))
puts PRIVATE_KEY
```
## まとめ
## Conclusion
このガイドを見終えれば、GitHub Appを開発するための基本的なビルディングブロックを学んだことになります! 振り返ると、以下を行いました。
After walking through this guide, you've learned the basic building blocks for developing GitHub Apps! To review, you:
* 新しいGitHub Appの登録
* Smeeを使ってwebhookのペイロードを受信
* SinatraでシンプルなWebサーバーを実行
* GitHub Appとして認証
* インストールとして認証
* Registered a new GitHub App
* Used Smee to receive webhook payloads
* Ran a simple web server via Sinatra
* Authenticated as a GitHub App
* Authenticated as an installation
## 次の手順
## Next steps
これでGitHub Appをサーバー上で動作させることができました。 これだけでは特別な処理は何も実施していませんが、他の[クイックスタート ガイド](/apps/quickstart-guides/)で GitHub アプリ テンプレートをカスタマイズする方法を確認できます。
You now have a GitHub App running on a server. It doesn't do anything special yet, but check out some of the ways you can customize your GitHub App template in the other [quickstart guides](/apps/quickstart-guides/).

View File

@@ -1,6 +1,6 @@
---
title: Checks API で CI テストを作成する
intro: '{% data variables.product.prodname_github_app %} Checks API を使用して、テストを実行するための継続的インテグレーションサーバーを構築します。'
title: Creating CI tests with the Checks API
intro: 'Build a continuous integration server to run tests using a {% data variables.product.prodname_github_app %} and the Checks API.'
redirect_from:
- /apps/quickstart-guides/creating-ci-tests-with-the-checks-api
- /developers/apps/creating-ci-tests-with-the-checks-api
@@ -12,104 +12,98 @@ versions:
topics:
- GitHub Apps
shortTitle: CI tests using Checks API
ms.openlocfilehash: ef43456aa08813a0b3010c40ce1b7628c75c5b68
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 09/05/2022
ms.locfileid: '147080993'
---
## はじめに
## Introduction
このガイドでは、[GitHub App](/apps/) [Checks API](/rest/reference/checks) について説明します。これらを使って、テストを実行する継続的インテグレーション (CI) サーバーを構築します。
This guide will introduce you to [GitHub Apps](/apps/) and the [Checks API](/rest/reference/checks), which you'll use to build a continuous integration (CI) server that runs tests.
CI とは、ソフトウェアの開発においてコードを頻繁に共有リポジトリにコミットする手法のことです。 コードをコミットする頻度が高いほどエラーの発生が早くなり、開発者がエラーの原因を見つけようとしてデバッグする必要性も減ります。 コードの更新が頻繁であれば、ソフトウェア開発チームの他のメンバーによる変更をマージするのも、それだけ容易になります。 コードの記述により多くの時間をかけられるようになり、エラーのデバッグやマージコンフリクトの解決にかける時間が減るので、これは開発者にとって素晴らしいやり方です。 🙌
CI is a software practice that requires frequently committing code to a shared repository. Committing code more often raises errors sooner and reduces the amount of code a developer needs to debug when finding the source of an error. Frequent code updates also make it easier to merge changes from different members of a software development team. This is great for developers, who can spend more time writing code and less time debugging errors or resolving merge conflicts. 🙌
CI サーバーは、コードの文法チェッカー (スタイルフォーマットをチェックする)、セキュリティチェック、コード網羅率、その他のチェックといった CI テストをリポジトリの新しいコードコミットに対して実行するコードをホストします。 CI サーバーは、ステージングサーバーや本番サーバーにコードを構築しデプロイすることも可能です。 GitHub App で作ることができる CI テストの種類の例については、GitHub Marketplace で手に入る[継続的インテグレーション アプリ](https://github.com/marketplace/category/continuous-integration)を確認してください。
A CI server hosts code that runs CI tests such as code linters (which check style formatting), security checks, code coverage, and other checks against new code commits in a repository. CI servers can even build and deploy code to staging or production servers. For some examples of the types of CI tests you can create with a GitHub App, check out the [continuous integration apps](https://github.com/marketplace/category/continuous-integration) available in GitHub Marketplace.
{% data reusables.apps.app-ruby-guides %}
### Checks API の概要
### Checks API overview
[Checks API](/rest/reference/checks) を使うと、リポジトリでコードがコミットされるたびに自動的に実行される CI テストを設定できます。 Checks API により、GitHub での各チェックについての詳細情報が、pull request の **[チェック]** タブで報告されます。Checks API を使うと、コードの特定の行に対して、追加情報を含むアノテーションを作成できます。 アノテーションは **[チェック]** タブに表示されます。pull request の一部であるファイルに対してアノテーションを作成すると、そのアノテーションは **[変更されたファイル]** タブにも表示されます。
The [Checks API](/rest/reference/checks) allows you to set up CI tests that are automatically run against each code commit in a repository. The Checks API reports detailed information about each check on GitHub in the pull request's **Checks** tab. With the Checks API, you can create annotations with additional details for specific lines of code. Annotations are visible in the **Checks** tab. When you create an annotation for a file that is part of the pull request, the annotations are also shown in the **Files changed** tab.
_チェック スイート_ は、_チェック実行_ のグループ (個々の CI テスト) です。 スイートと実行の両方に、GitHubのプル要求に表示される _状態_ が含まれています。 ステータスを使用して、コードコミットがエラーを発生させるタイミングを決定できます。 これらのステータスを[保護されたブランチ](/rest/reference/repos#branches)で使うと、pull request の早すぎるマージを防ぐことができます。 詳しくは、「[保護されたブランチについて](/github/administering-a-repository/about-protected-branches#require-status-checks-before-merging)」をご覧ください。
A _check suite_ is a group of _check runs_ (individual CI tests). Both the suite and the runs contain _statuses_ that are visible in a pull request on GitHub. You can use statuses to determine when a code commit introduces errors. Using these statuses with [protected branches](/rest/reference/repos#branches) can prevent people from merging pull requests prematurely. See "[About protected branches](/github/administering-a-repository/about-protected-branches#require-status-checks-before-merging)" for more details.
Checks API は、新しいコードがリポジトリにプッシュされるたびに、リポジトリにインストールされているすべての GitHub App に [`check_suite` Webhook イベント](/webhooks/event-payloads/#check_suite)を送信します。 Checks API イベントのすべてのアクションを受信するには、アプリに `checks:write` アクセス許可が必要です。 GitHub は既定のフローを使ってリポジトリでの新しいコードのコミットに対する `check_suite` イベントを自動的に作成しますが、必要に応じて[チェック スイートに関するリポジトリ設定を更新](/rest/reference/checks#update-repository-preferences-for-check-suites)できます。 デフォルトのフローは以下の通りです。
The Checks API sends the [`check_suite` webhook event](/webhooks/event-payloads/#check_suite) to all GitHub Apps installed on a repository each time new code is pushed to the repository. To receive all Checks API event actions, the app must have the `checks:write` permission. GitHub automatically creates `check_suite` events for new code commits in a repository using the default flow, although [Update repository preferences for check suites](/rest/reference/checks#update-repository-preferences-for-check-suites) if you'd like. Here's how the default flow works:
1. リポジトリにコードがプッシュされるたびに、GitHub は、リポジトリにインストールされていて `checks:write` アクセス許可を持つすべての GitHub App に、`requested` アクションを含む `check_suite` イベントを送信します。 このイベントにより、コードがプッシュされたことと、GitHub が新しいチェックスイートを自動的に作成したことがアプリケーションに通知されます。
1. アプリでは、このイベントを受信したら、そのスイートに[チェック実行を追加](/rest/reference/checks#create-a-check-run)できます。
1. チェック実行には、特定のコード行に表示される[アノテーション](/rest/reference/checks#annotations-object)を含めることができます。
1. Whenever someone pushes code to the repository, GitHub sends the `check_suite` event with an action of `requested` to all GitHub Apps installed on the repository that have the `checks:write` permission. This event lets the apps know that code was pushed and that GitHub has automatically created a new check suite.
1. When your app receives this event, it can [add check runs](/rest/reference/checks#create-a-check-run) to that suite.
1. Your check runs can include [annotations](/rest/reference/checks#annotations-object) that are displayed on specific lines of code.
**このガイドでは、次の方法について説明します。**
**In this guide, youll learn how to:**
* パート 1: Checks API を使用して CI サーバー用のフレームワークをセットアップする。
* Checks API イベントを受信するサーバーとして GitHub App を構成します。
* 新たにプッシュされたコミットをリポジトリが受信した時に、CI テスト用の新しいチェック実行を作成します。
* ユーザが GitHub でチェック実行のアクションをリクエストした時に、チェック実行を再実行します。
* パート 2: 文法チェッカー CI テストを追加して、作成した CI サーバーフレームワークを基に構築する。
* `status``conclusion``output` の詳細を使って、チェック実行を更新します。
* pull request の **[チェック]** および **[変更されたファイル]** タブに表示されるコード行のアノテーションを作成します。
* pull request の **[チェック]** タブに [これを修正する] ボタンを表示して、リンターによる推奨事項を自動的に修正します。
* Part 1: Set up the framework for a CI server using the Checks API.
* Configure a GitHub App as a server that receives Checks API events.
* Create new check runs for CI tests when a repository receives newly pushed commits.
* Re-run check runs when a user requests that action on GitHub.
* Part 2: Build on the CI server framework you created by adding a linter CI test.
* Update a check run with a `status`, `conclusion`, and `output` details.
* Create annotations on lines of code that GitHub displays in the **Checks** and **Files Changed** tab of a pull request.
* Automatically fix linter recommendations by exposing a "Fix this" button in the **Checks** tab of the pull request.
このクイックスタートを完了したときに Checks API CI サーバーがどのように動作するかを理解するには、以下のデモをご覧ください。
To get an idea of what your Checks API CI server will do when you've completed this quickstart, check out the demo below:
![Checks API CI サーバークイックスタートのデモ](/assets/images/github-apps/github_apps_checks_api_ci_server.gif)
![Demo of Checks API CI sever quickstart](/assets/images/github-apps/github_apps_checks_api_ci_server.gif)
## 前提条件
## Prerequisites
[GitHub アプリ](/apps/)[Webhook](/webhooks)[Checks API](/rest/reference/checks) のことをまだ理解していない場合は、作業を始める前に理解しておいてください。 [REST API ドキュメント](/rest)には、さらに API が記載されています。Checks API は [GraphQL](/graphql) でも使用できますが、このクイックスタートでは REST に焦点を当てます。 詳しくは、GraphQL [Checks Suite](/graphql/reference/objects#checksuite) および [Check Run](/graphql/reference/objects#checkrun) オブジェクトをご覧ください。
Before you get started, you may want to familiarize yourself with [GitHub Apps](/apps/), [Webhooks](/webhooks), and the [Checks API](/rest/reference/checks), if you're not already. You'll find more APIs in the [REST API docs](/rest). The Checks API is also available to use in [GraphQL](/graphql), but this quickstart focuses on REST. See the GraphQL [Checks Suite](/graphql/reference/objects#checksuite) and [Check Run](/graphql/reference/objects#checkrun) objects for more details.
Checks API CI サーバー アプリを作るには、[Ruby プログラミング言語](https://www.ruby-lang.org/en/)[Smee](https://smee.io/) Webhook ペイロード配信サービス、GitHub REST API 用の [Octokit.rb Ruby ライブラリ](http://octokit.github.io/octokit.rb/)[Sinatra Web フレームワーク](http://sinatrarb.com/)を使います。
You'll use the [Ruby programming language](https://www.ruby-lang.org/en/), the [Smee](https://smee.io/) webhook payload delivery service, the [Octokit.rb Ruby library](http://octokit.github.io/octokit.rb/) for the GitHub REST API, and the [Sinatra web framework](http://sinatrarb.com/) to create your Checks API CI server app.
このプロジェクトを完了するために、これらのツールや概念のエキスパートである必要はありません。 このガイドでは、必要なステップを順番に説明していきます。 Checks API で CI テストを作成する前に、以下を行う必要があります。
You don't need to be an expert in any of these tools or concepts to complete this project. This guide will walk you through all the required steps. Before you begin creating CI tests with the Checks API, you'll need to do the following:
1. 「[Checks API で CI テストを作成する](https://github.com/github-developer/creating-ci-tests-with-the-checks-api)」のリポジトリをクローンします。
1. Clone the [Creating CI tests with the Checks API](https://github.com/github-developer/creating-ci-tests-with-the-checks-api) repository.
```shell
$ git clone https://github.com/github-developer/creating-ci-tests-with-the-checks-api.git
```
ディレクトリの中には、このクイックスタートで使うテンプレート コードを含む `template_server.rb` ファイルと、完成したプロジェクト コードを含む `server.rb` ファイルがあります。
Inside the directory, you'll find a `template_server.rb` file with the template code you'll use in this quickstart and a `server.rb` file with the completed project code.
1. [開発環境のセットアップ](/apps/quickstart-guides/setting-up-your-development-environment/)に関するクイックスタートの手順に従い、アプリ サーバーを構成して実行します。 **注:** [GitHub App のテンプレート リポジトリをクローンする](/apps/quickstart-guides/setting-up-your-development-environment/#prerequisites)のではなく、このクイックスタートの前のステップでクローンしたリポジトリにある `template_server.rb` ファイルを使います。
1. Follow the steps in the "[Setting up your development environment](/apps/quickstart-guides/setting-up-your-development-environment/)" quickstart to configure and run the app server. **Note:** Instead of [cloning the GitHub App template repository](/apps/quickstart-guides/setting-up-your-development-environment/#prerequisites), use the `template_server.rb` file in the repository you cloned in the previous step in this quickstart.
GitHub App クイックスタート ガイドを以前に完了している場合は、必ず _新しい_ GitHub App を登録し、このクイックスタートで使う新しい Smee チャネルを開始してください。
If you've completed a GitHub App quickstart before, make sure to register a _new_ GitHub App and start a new Smee channel to use with this quickstart.
テンプレート GitHub App の設定で問題が発生する場合は、「[トラブルシューティング](/apps/quickstart-guides/setting-up-your-development-environment/#troubleshooting)」セクションをご覧ください。
See the [troubleshooting](/apps/quickstart-guides/setting-up-your-development-environment/#troubleshooting) section if you are running into problems setting up your template GitHub App.
## 第 1 部 Checks API インターフェースを作成する
## Part 1. Creating the Checks API interface
このパートでは、`check_suite` Webhook イベントを受信してチェック実行を作成および更新するために必要なコードを追加します。 また、GitHub でチェックが再リクエストされた場合にチェック実行を作成する方法についても学びます。 このセクションの最後では、GitHub プルリクエストで作成したチェック実行を表示できるようになります。
In this part, you will add the code necessary to receive `check_suite` webhook events and create and update check runs. You'll also learn how to create check runs when a check was re-requested on GitHub. At the end of this section, you'll be able to view the check run you created in a GitHub pull request.
このセクションでは、作成したチェック実行はコードでチェックを実行しません。 その機能は、「[パート 2: Octo RuboCop CI テストを作成する](#part-2-creating-the-octo-rubocop-ci-test)」で追加します。
Your check run will not be performing any checks on the code in this section. You'll add that functionality in [Part 2: Creating the Octo RuboCop CI test](#part-2-creating-the-octo-rubocop-ci-test).
ローカルサーバーにwebhook ペイロードを転送するよう Smee チャンネルが構成されているでしょうか。 サーバーは実行中で、登録済みかつテストリポジトリにインストールした GitHub App に接続している必要があります。 [開発環境のセットアップ](/apps/quickstart-guides/setting-up-your-development-environment/)に関する記事の手順を完了していない場合は、続ける前にそれを行う必要があります。
You should already have a Smee channel configured that is forwarding webhook payloads to your local server. Your server should be running and connected to the GitHub App you registered and installed on a test repository. If you haven't completed the steps in "[Setting up your development environment](/apps/quickstart-guides/setting-up-your-development-environment/)," you'll need to do that before you can continue.
それでは作業を始めましょう。 パート 1 では、以下のステップを完了させます。
Let's get started! These are the steps you'll complete in Part 1:
1. [アプリのアクセス許可を更新する](#step-11-updating-app-permissions)
1. [イベントの処理を追加する](#step-12-adding-event-handling)
1. [チェック実行を作成する](#step-13-creating-a-check-run)
1. [チェック実行を更新する](#step-14-updating-a-check-run)
1. [Updating app permissions](#step-11-updating-app-permissions)
1. [Adding event handling](#step-12-adding-event-handling)
1. [Creating a check run](#step-13-creating-a-check-run)
1. [Updating a check run](#step-14-updating-a-check-run)
## ステップ 1.1. アプリケーションの権限を更新する
## Step 1.1. Updating app permissions
[最初にアプリを登録](#prerequisites)したときは、既定のアクセス許可を受け入れました。これは、アプリがほとんどのリソースにアクセスできないことを意味します。 この例においては、アプリケーションにはチェックを読み取りおよび書き込みする権限が必要となります。
When you [first registered your app](#prerequisites), you accepted the default permissions, which means your app doesn't have access to most resources. For this example, your app will need permission to read and write checks.
アプリケーションの権限を更新するには、以下の手順に従います。
To update your app's permissions:
1. [アプリの設定ページ](https://github.com/settings/apps)でアプリを選び、サイドバーの **[アクセス許可と Webhook]** をクリックします。
1. [アクセス許可] セクションで [チェック] を探し、その横にある [アクセス] ドロップダウンで **[読み取りと書き込み]** を選びます。
1. [イベントへのサブスクライブ] セクションで、 **[チェック スイート]** と **[チェック実行]** を選んで、これらのイベントにサブスクライブします。
1. Select your app from the [app settings page](https://github.com/settings/apps) and click **Permissions & Webhooks** in the sidebar.
1. In the "Permissions" section, find "Checks", and select **Read & write** in the Access dropdown next to it.
1. In the "Subscribe to events" section, select **Check suite** and **Check run** to subscribe to these events.
{% data reusables.apps.accept_new_permissions_steps %}
すばらしい。 アプリケーションは必要なタスクを実行する権限を所有しています。 これでイベントを処理するコードを追加できるようになりました。
Great! Your app has permission to do the tasks you want it to do. Now you can add the code to handle the events.
## ステップ 1.2. イベントの処理を追加する
## Step 1.2. Adding event handling
アプリが **チェック スイート** **チェック実行** イベントにサブスクライブされたので、[`check_suite`](/webhooks/event-payloads/#check_suite) および [`check_run`](/webhooks/event-payloads/#check_run) Webhook の受信が始まります。 GitHub は、Webhook ペイロードを `POST` 要求として送信します。 Smee Webhook ペイロードを `http://localhost/event_handler:3000` に転送したため、サーバーは `post '/event_handler'` ルートで `POST` 要求のペイロードを受信します。
Now that your app is subscribed to the **Check suite** and **Check run** events, it will start receiving the [`check_suite`](/webhooks/event-payloads/#check_suite) and [`check_run`](/webhooks/event-payloads/#check_run) webhooks. GitHub sends webhook payloads as `POST` requests. Because you forwarded your Smee webhook payloads to `http://localhost/event_handler:3000`, your server will receive the `POST` request payloads at the `post '/event_handler'` route.
空の `post '/event_handler'` ルートは、「[前提条件](#prerequisites)」セクションでダウンロードした `template_server.rb` ファイルに既に含まれています。 空のルートは次のようになっています。
An empty `post '/event_handler'` route is already included in the `template_server.rb` file, which you downloaded in the [prerequisites](#prerequisites) section. The empty route looks like this:
``` ruby
post '/event_handler' do
@@ -122,7 +116,7 @@ Checks API CI サーバー アプリを作るには、[Ruby プログラミン
end
```
以下のコードを追加することで、このルートを使って `check_suite` イベントを処理します。
Use this route to handle the `check_suite` event by adding the following code:
``` ruby
# Get the event type from the HTTP_X_GITHUB_EVENT header
@@ -135,13 +129,13 @@ when 'check_suite'
end
```
GitHub が送信する全てのイベントには、`HTTP_X_GITHUB_EVENT` という要求ヘッダーが含まれており、これは `POST` 要求でのイベントの種類を示します。 ここで関心のあるイベントの種類は `check_suite` だけであり、これは新しいチェック スイートが作成されると出力されます。 各イベントには、イベントをトリガーしたアクションの種類を示す追加の `action` フィールドがあります。 `check_suite` の場合、`action` フィールドは `requested``rerequested`、または `completed` になります。
Every event that GitHub sends includes a request header called `HTTP_X_GITHUB_EVENT`, which indicates the type of event in the `POST` request. Right now, you're only interested in events of type `check_suite`, which are emitted when a new check suite is created. Each event has an additional `action` field that indicates the type of action that triggered the events. For `check_suite`, the `action` field can be `requested`, `rerequested`, or `completed`.
`requested` アクションはリポジトリにコードがプッシュされるたびにチェック実行を要求し、`rerequested` アクションはリポジトリに既に存在するコードのチェックの再実行を要求します。 `requested` `rerequested` のどちらのアクションでもチェック実行を作成する必要があるため、`create_check_run` というヘルパーを呼び出します。 では、このメソッドを書いてみましょう。
The `requested` action requests a check run each time code is pushed to the repository, while the `rerequested` action requests that you re-run a check for code that already exists in the repository. Because both the `requested` and `rerequested` actions require creating a check run, you'll call a helper called `create_check_run`. Let's write that method now.
## ステップ 1.3. チェック実行を作成する
## Step 1.3. Creating a check run
他のルートでも使う場合に備えて、この新しいメソッドを [Sinatra ヘルパー](https://github.com/sinatra/sinatra#helpers)として追加します。 `helpers do` の下に、次の `create_check_run` メソッドを追加します。
You'll add this new method as a [Sinatra helper](https://github.com/sinatra/sinatra#helpers) in case you want other routes to use it too. Under `helpers do`, add this `create_check_run` method:
``` ruby
# Create a new check run with the status queued
@@ -160,17 +154,17 @@ def create_check_run
end
```
このコードは、[create_check_run メソッド](https://rdoc.info/gems/octokit/Octokit%2FClient%2FChecks:create_check_run)を使って "[チェック実行を作成する](/rest/reference/checks#create-a-check-run)" エンドポイントを呼び出します。
This code calls the "[Create a check run](/rest/reference/checks#create-a-check-run)" endpoint using the [create_check_run method](https://rdoc.info/gems/octokit/Octokit%2FClient%2FChecks:create_check_run).
チェック実行を作成するために必要な入力パラメーターは、`name` `head_sha` の 2 つのみです。 このクイックスタートでは、後で [RuboCop](https://rubocop.readthedocs.io/en/latest/) を使って CI テストを実装します。そのため、ここでは "Octo RuboCop" という名前を使いますが、チェック実行には任意の名前を選べます。
To create a check run, only two input parameters are required: `name` and `head_sha`. We will use [RuboCop](https://rubocop.readthedocs.io/en/latest/) to implement the CI test later in this quickstart, which is why the name "Octo RuboCop" is used here, but you can choose any name you'd like for the check run.
ここでは基本的な機能を実行するため必要なパラメータのみを指定していますが、チェック実行について必要な情報を収集するため、後でチェック実行を更新することになります。 既定では、`status` `queued` に設定されます。
You're only supplying the required parameters now to get the basic functionality working, but you'll update the check run later as you collect more information about the check run. By default, GitHub sets the `status` to `queued`.
GitHub によって特定のコミット SHA に対するチェック実行が作成されるため、`head_sha` は必須パラメーターです。 コミット SHA は、webhook ペイロードで確認できます。 今は `check_suite` イベントのためのチェック実行だけを作成していますが、`head_sha` はイベント ペイロードの `check_suite` オブジェクトと `check_run` オブジェクトの両方に含まれることを覚えておいてください。
GitHub creates a check run for a specific commit SHA, which is why `head_sha` is a required parameter. You can find the commit SHA in the webhook payload. Although you're only creating a check run for the `check_suite` event right now, it's good to know that the `head_sha` is included in both the `check_suite` and `check_run` objects in the event payloads.
上のコードでは、`if/else` ステートメントのように機能する[三項演算子](https://ruby-doc.org/core-2.3.0/doc/syntax/control_expressions_rdoc.html#label-Ternary+if)を使って、ペイロードに `check_run` オブジェクトが含まれるかどうかを調べています。 そうである場合は `check_run` オブジェクトから `head_sha` を読み取り、そうでない場合は `check_suite` オブジェクトから読み取ります。
In the code above, you're using the [ternary operator](https://ruby-doc.org/core-2.3.0/doc/syntax/control_expressions_rdoc.html#label-Ternary+if), which works like an `if/else` statement, to check if the payload contains a `check_run` object. If it does, you read the `head_sha` from the `check_run` object, otherwise you read it from the `check_suite` object.
このコードをテストするには、サーバーをターミナルから再起動します。
To test this code, restart the server from your terminal:
```shell
$ ruby template_server.rb
@@ -178,21 +172,21 @@ $ ruby template_server.rb
{% data reusables.apps.sinatra_restart_instructions %}
さて、それではアプリケーションをインストールしたリポジトリにあるプルリクエストを開いてください。 アプリケーションは応答し、プルリクエストのチェック実行を作成するはずです。 **[チェック]** タブをクリックすると、次のような内容が表示されます。
Now open a pull request in the repository where you installed your app. Your app should respond by creating a check run on your pull request. Click on the **Checks** tab, and you should see something like this:
![キューに入ったチェック実行](/assets/images/github-apps/github_apps_queued_check_run.png)
![Queued check run](/assets/images/github-apps/github_apps_queued_check_run.png)
[チェック] タブに他のアプリが表示される場合は、チェックに対する **読み取りと書き込み** アクセス権を持ち、**チェック スイート** および **チェック実行** イベントにサブスクライブしている他のアプリが、リポジトリにインストールされていることを意味します。
If you see other apps in the Checks tab, it means you have other apps installed on your repository that have **Read & write** access to checks and are subscribed to **Check suite** and **Check run** events.
すばらしい。 ここまでで、GitHub にチェック実行を作成するよう指示しました。 黄色のアイコンの横で、チェック実行のステータスが `queued` に設定されていることを確認できます。 次は、GitHub がチェック実行を作成し、ステータスを更新するのを待てばよいでしょう。
Great! You've told GitHub to create a check run. You can see the check run status is set to `queued` next to a yellow icon. Next, you'll want to wait for GitHub to create the check run and update its status.
## ステップ 1.4. チェック実行を更新する
## Step 1.4. Updating a check run
`create_check_run` メソッドは実行すると、GitHub に新しいチェック実行の作成を要求します。 GitHub でチェック実行の作成が完了すると、`created` アクションを含む `check_run` Webhook イベントを受け取ります。 このイベントは、チェックの実行を開始する合図です。
When your `create_check_run` method runs, it asks GitHub to create a new check run. When GitHub finishes creating the check run, you'll receive the `check_run` webhook event with the `created` action. That event is your signal to begin running the check.
`created` アクションを待つように、イベント ハンドラーを更新します。 イベント ハンドラーを更新するときに、`rerequested` アクションに対する条件を追加できます。 [再実行] ボタンをクリックして GitHub 上で単一のテストを再実行すると、GitHub からアプリに `rerequested` チェック実行イベントが送信されます。 チェック実行が `rerequested` の場合は、すべてのプロセスを開始してから、新しいチェック実行を作成します。
You'll want to update your event handler to look for the `created` action. While you're updating the event handler, you can add a conditional for the `rerequested` action. When someone re-runs a single test on GitHub by clicking the "Re-run" button, GitHub sends the `rerequested` check run event to your app. When a check run is `rerequested`, you'll want to start the process all over and create a new check run.
`post '/event_handler'` ルートに `check_run` イベントの条件を含めるには、`case request.env['HTTP_X_GITHUB_EVENT']` の下に次のコードを追加します。
To include a condition for the `check_run` event in the `post '/event_handler'` route, add the following code under `case request.env['HTTP_X_GITHUB_EVENT']`:
``` ruby
when 'check_run'
@@ -207,13 +201,13 @@ when 'check_run'
end
```
GitHub `created` チェック実行に関するすべてのイベントを、リポジトリにインストールされていて必要なチェック アクセス許可を持つすべてのアプリに送信します。 これはつまり、あなたのアプリケーションが他のアプリケーションにより作成されたチェック実行を受信するということです。 `created` チェック実行は、チェックの実行を要求されているアプリのみに GitHub が送信する `requested` `rerequested` チェック スイートとは少し違います。 上記のコードは、チェック実行のアプリケーション ID を待ち受けます。 リポジトリの他のアプリケーションに対するチェック実行はすべて遮断されます。
GitHub sends all events for `created` check runs to every app installed on a repository that has the necessary checks permissions. That means that your app will receive check runs created by other apps. A `created` check run is a little different from a `requested` or `rerequested` check suite, which GitHub sends only to apps that are being requested to run a check. The code above looks for the check run's application ID. This filters out all check runs for other apps on the repository.
次に、`initiate_check_run` メソッドを作成します。そこでは、チェック実行のステータスを更新して、CI テストの開始を準備します。
Next you'll write the `initiate_check_run` method, which is where you'll update the check run status and prepare to kick off your CI test.
このセクションでは、CI テストはまだ開始しませんが、チェック実行のステータスを `queued` から `pending` に更新し、さらに `pending` から `completed` に更新する手順を調べることで、チェック実行のフロー全体を確認します。 「[パート 2: Octo RuboCop CI テストを作成する](#part-2-creating-the-octo-rubocop-ci-test)」で、CI テストを実際に実行するコードを追加します。
In this section, you're not going to kick off the CI test yet, but you'll walk through how to update the status of the check run from `queued` to `pending` and then from `pending` to `completed` to see the overall flow of a check run. In "[Part 2: Creating the Octo RuboCop CI test](#part-2-creating-the-octo-rubocop-ci-test)," you'll add the code that actually performs the CI test.
`initiate_check_run` メソッドを作成し、チェック実行のステータスを更新しましょう。 以下のコードを helpers セクションに追加します。
Let's create the `initiate_check_run` method and update the status of the check run. Add the following code to the helpers section:
``` ruby
# Start the CI process
@@ -242,53 +236,53 @@ def initiate_check_run
end
```
上のコードでは、[`update_check_run` Octokit メソッド](https://rdoc.info/gems/octokit/Octokit%2FClient%2FChecks:update_check_run)を使って "[チェック実行を更新する](/rest/reference/checks#update-a-check-run)" API エンドポイントを呼び出し、既に作成したチェック実行を更新しています。
The code above calls the "[Update a check run](/rest/reference/checks#update-a-check-run)" API endpoint using the [`update_check_run` Octokit method](https://rdoc.info/gems/octokit/Octokit%2FClient%2FChecks:update_check_run) to update the check run that you already created.
このコードがしていることを説明しましょう。 まず、チェック実行のステータスを `in_progress` に更新し、`started_at` の日時を現在の日時に暗黙的に設定します。 このクイックスタートの「[パート 2](#part-2-creating-the-octo-rubocop-ci-test)」では、実際の CI テストを開始するコードを `***** RUN A CI TEST *****` の下に追加します。 今はこのセクションをプレースホルダーとして残しておきましょう。そうすると、続くコードが CI のプロセスを成功させ、すべてのテストに合格したことをシミュレートすることになります。 最後に、コードでチェック実行のステータスを再び `completed` に更新します。
Here's what this code is doing. First, it updates the check run's status to `in_progress` and implicitly sets the `started_at` time to the current time. In [Part 2](#part-2-creating-the-octo-rubocop-ci-test) of this quickstart, you'll add code that kicks off a real CI test under `***** RUN A CI TEST *****`. For now, you'll leave that section as a placeholder, so the code that follows it will just simulate that the CI process succeeds and all tests pass. Finally, the code updates the status of the check run again to `completed`.
「[チェック実行を更新する](/rest/reference/checks#update-a-check-run)」のドキュメントを見ると、`completed` ステータスを指定するときは、`conclusion` `completed_at` パラメーターが必須であることがわかります。 `conclusion` はチェック実行の結果の要約であり、`success``failure``neutral``cancelled``timed_out`、または `action_required` を指定できます。 conclusion `success` に、`completed_at` の日時は現在の日時に、ステータスは `completed` に設定します。
You'll notice in the "[Update a check run](/rest/reference/checks#update-a-check-run)" docs that when you provide a status of `completed`, the `conclusion` and `completed_at` parameters are required. The `conclusion` summarizes the outcome of a check run and can be `success`, `failure`, `neutral`, `cancelled`, `timed_out`, or `action_required`. You'll set the conclusion to `success`, the `completed_at` time to the current time, and the status to `completed`.
チェックが行っていることについてより詳しく指定することもできますが、それは次のセクションで行うことにします。 `template_server.rb` を実行し直して、このコードをもう一度テストしてみましょう。
You could also provide more details about what your check is doing, but you'll get to that in the next section. Let's test this code again by re-running `template_server.rb`:
```shell
$ ruby template_server.rb
```
開いている pull request に移動し、 **[チェック]** タブをクリックします。左上隅にある [すべて再実行] ボタンをクリックします。 チェック実行が `pending` から `in_progress` に変わり、`success` で終わることを確認できるはずです。
Head over to your open pull request and click the **Checks** tab. Click the "Re-run all" button in the upper left corner. You should see the check run move from `pending` to `in_progress` and end with `success`:
![完了したチェック実行](/assets/images/github-apps/github_apps_complete_check_run.png)
![Completed check run](/assets/images/github-apps/github_apps_complete_check_run.png)
## 第 2 部 Octo RuboCop CI テストを作成する
## Part 2. Creating the Octo RuboCop CI test
[RuboCop](https://rubocop.readthedocs.io/en/latest/) Ruby コードのリンターおよびフォーマッタです。 Ruby のコードが「[Ruby スタイル ガイド](https://github.com/rubocop-hq/ruby-style-guide)」に準拠していることをチェックします。 RuboCop の主な機能は、以下の 3 つです。
[RuboCop](https://rubocop.readthedocs.io/en/latest/) is a Ruby code linter and formatter. It checks Ruby code to ensure that it complies with the "[Ruby Style Guide](https://github.com/rubocop-hq/ruby-style-guide)." RuboCop has three primary functions:
* コードのスタイルを確認する文法チェック
* コードのフォーマット
* `ruby -w` を使って Ruby のネイティブ リンティング機能を置き換える
* Linting to check code style
* Code formatting
* Replaces the native Ruby linting capabilities using `ruby -w`
さて、Checks API を受信し、チェック実行を作成するために作ったインターフェースができあがったところで、今度は CI テストを実装するチェック実行を作成しましょう。
Now that you've got the interface created to receive Checks API events and create check runs, you can create a check run that implements a CI test.
あなたのアプリケーションは CI サーバー上の RuboCop で実行され、結果を RuboCop が GitHub に報告するチェック実行 (ここでは CI テスト) を作成します。
Your app will run RuboCop on the CI server and create check runs (CI tests in this case) that report the results that RuboCop reports to GitHub.
Checks API を使用すると、ステータス、画像、要約、アノテーション、リクエストされたアクションなどの、各チェック実行の詳細情報を報告できます。
The Checks API allows you to report rich details about each check run, including statuses, images, summaries, annotations, and requested actions.
アノテーションとは、リポジトリのコードの特定の行についての情報です。 アノテーションを使用すると、追加情報を表示したいコードの部分を細かく指定して、それを視覚化できます。 この情報は、たとえばコメント、エラー、警告など何でも構いません。 このクイックスタートでは、RuboCop のエラーを視覚化するためにアノテーションを使用します。
Annotations are information about specific lines of code in a repository. An annotation allows you to pinpoint and visualize the exact parts of the code you'd like to show additional information for. That information can be anything: for example, a comment, an error, or a warning. This quickstart uses annotations to visualize RuboCop errors.
要求されたアクションを利用するため、アプリ開発者は pull request の **[チェック]** タブにボタンを作成できます。 これらのボタンをクリックすると、クリックから GitHub アプリに `requested_action` `check_run` イベントが送信されます。 アプリケーションが実行するアクションは、アプリケーション開発者が自由に設定できます。 このクイックスタートでは、RuboCop が見つけたエラーを修正するようユーザがリクエストするためのボタンを追加する方法について説明します。 RuboCop はコマンド ライン オプションを使ったエラーの自動修正をサポートしており、ここでは `requested_action` を構成してこのオプションを利用します。
To take advantage of requested actions, app developers can create buttons in the **Checks** tab of pull requests. When someone clicks one of these buttons, the click sends a `requested_action` `check_run` event to the GitHub App. The action that the app takes is completely configurable by the app developer. This quickstart will walk you through adding a button that allows users to request that RuboCop fix the errors it finds. RuboCop supports automatically fixing errors using a command-line option, and you'll configure the `requested_action` to take advantage of this option.
それでは作業を始めましょう。 このセクションでは、以下のステップを完了させます。
Let's get started! These are the steps you'll complete in this section:
1. [Ruby ファイルを追加する](#step-21-adding-a-ruby-file)
1. [リポジトリの複製](#step-22-cloning-the-repository)
1. [RuboCop を実行する](#step-23-running-rubocop)
1. [RuboCop のエラーを収集する](#step-24-collecting-rubocop-errors)
1. [CI テスト結果でチェック実行を更新する](#step-25-updating-the-check-run-with-ci-test-results)
1. [RuboCop のエラーを自動的に修正する](#step-26-automatically-fixing-rubocop-errors)
1. [セキュリティのヒント](#step-27-security-tips)
1. [Adding a Ruby file](#step-21-adding-a-ruby-file)
1. [Cloning the repository](#step-22-cloning-the-repository)
1. [Running RuboCop](#step-23-running-rubocop)
1. [Collecting RuboCop errors](#step-24-collecting-rubocop-errors)
1. [Updating the check run with CI test results](#step-25-updating-the-check-run-with-ci-test-results)
1. [Automatically fixing RuboCop errors](#step-26-automatically-fixing-rubocop-errors)
1. [Security tips](#step-27-security-tips)
## ステップ 2.1. Ruby ファイルを追加する
## Step 2.1. Adding a Ruby file
RuboCop がチェックするため、特定のファイルまたはディレクトリ全体を渡すことができます。 このクイックスタートでは、ディレクトリ全体で RuboCop を実行します。 RuboCop がチェックするのは Ruby のコードのみなので、エラーが含まれる Ruby ファイルをリポジトリ内に最低 1 つ置くとよいでしょう。 以下に示すサンプルのファイルには、いくつかのエラーが含まれています。 この例の Ruby ファイルを、アプリがインストールされているリポジトリに追加します (`myfile.rb` のように、ファイル名には必ず `.rb` 拡張子を付けます)。
You can pass specific files or entire directories for RuboCop to check. In this quickstart, you'll run RuboCop on an entire directory. Because RuboCop only checks Ruby code, you'll want at least one Ruby file in your repository that contains errors. The example file provided below contains a few errors. Add this example Ruby file to the repository where your app is installed (make sure to name the file with an `.rb` extension, as in `myfile.rb`):
```ruby
# The Octocat class tells you about different breeds of Octocat
@@ -310,31 +304,31 @@ m = Octocat.new("Mona", "cat", "octopus")
m.display
```
## ステップ 2.2. リポジトリの複製
## Step 2.2. Cloning the repository
RuboCop はコマンドラインユーティリティとして使用できます。 これはつまり、RuboCop がファイルを解析するためには、GitHub App が CI サーバー上のリポジトリのローカルコピーをクローンする必要があるということです。 Ruby アプリで Git の操作を実行するには、[ruby-git](https://github.com/ruby-git/ruby-git) gem を使えます。
RuboCop is available as a command-line utility. That means your GitHub App will need to clone a local copy of the repository on the CI server so RuboCop can parse the files. To run Git operations in your Ruby app, you can use the [ruby-git](https://github.com/ruby-git/ruby-git) gem.
`building-a-checks-api-ci-server` リポジトリの `Gemfile` には既に ruby-git gem が含まれており、[前提条件ステップ](#prerequisites)で `bundle install` を実行したときにインストール済みです。 gem を使うには、次のコードを `template_server.rb` ファイルの先頭に追加します。
The `Gemfile` in the `building-a-checks-api-ci-server` repository already includes the ruby-git gem, and you installed it when you ran `bundle install` in the [prerequisite steps](#prerequisites). To use the gem, add this code to the top of your `template_server.rb` file:
``` ruby
require 'git'
```
リポジトリをクローンするには、アプリケーションに「リポジトリコンテンツ」の読み取り権限が必要です。 このクイックスタートでは、後ほどコンテンツを GitHub にプッシュする必要がありますが、そのためには書き込み権限が必要です。 ここでアプリの "リポジトリの内容" のアクセス許可を **[読み取りと書き込み]** に設定しておけば、後で再び変更する必要がなくなります。 アプリケーションの権限を更新するには、以下の手順に従います。
Your app needs read permission for "Repository contents" to clone a repository. Later in this quickstart, you'll need to push contents to GitHub, which requires write permission. Go ahead and set your app's "Repository contents" permission to **Read & write** now so you don't need to update it again later. To update your app's permissions:
1. [アプリの設定ページ](https://github.com/settings/apps)でアプリを選び、サイドバーの **[アクセス許可と Webhook]** をクリックします。
1. [アクセス許可] セクションで "リポジトリの内容" を探し、その横にある [アクセス] ドロップダウンで **[読み取りと書き込み]** を選びます。
1. Select your app from the [app settings page](https://github.com/settings/apps) and click **Permissions & Webhooks** in the sidebar.
1. In the "Permissions" section, find "Repository contents", and select **Read & write** in the "Access" dropdown next to it.
{% data reusables.apps.accept_new_permissions_steps %}
GitHub App のアクセス許可を使ってリポジトリをクローンするには、次の例で示すアプリのインストール トークン (`x-access-token:<token>`) を使えます。
To clone a repository using your GitHub App's permissions, you can use the app's installation token (`x-access-token:<token>`) shown in the example below:
```shell
git clone https://x-access-token:<token>@github.com/<owner>/<repo>.git
```
上記のコードは、HTTP 経由でリポジトリをクローンします。 コードには、リポジトリの所有者 (ユーザまたは Organization) およびリポジトリ名を含む、リポジトリのフルネームを入力する必要があります。 たとえば、[octocat Hello-World](https://github.com/octocat/Hello-World) リポジトリのフル ネームは `octocat/hello-world` です。
The code above clones a repository over HTTP. It requires the full repository name, which includes the repository owner (user or organization) and the repository name. For example, the [octocat Hello-World](https://github.com/octocat/Hello-World) repository has a full name of `octocat/hello-world`.
アプリでは、リポジトリをクローンした後、最新のコード変更をプルし、特定の Git ref をチェックアウトする必要があります。これらのすべてを行うコードは、専用のメソッドにするのに最適です。 メソッドがこれらの操作を実行するには、リポジトリの名前とフルネーム、チェックアウトする ref が必要です。 ref にはコミット SHA、ブランチ、タグ名を指定できます。 次の新しいメソッドを `template_server.rb` のヘルパー メソッド セクションに追加します。
After your app clones the repository, it needs to pull the latest code changes and check out a specific Git ref. The code to do all of this will fit nicely into its own method. To perform these operations, the method needs the name and full name of the repository and the ref to checkout. The ref can be a commit SHA, branch, or tag. Add the following new method to the helper method section in `template_server.rb`:
``` ruby
# Clones the repository to the current working directory, updates the
@@ -353,11 +347,11 @@ def clone_repository(full_repo_name, repository, ref)
end
```
上のコードでは、`ruby-git` gem を使い、アプリのインストール トークンを使ってリポジトリをクローンしています。 このコードでは、`template_server.rb` と同じディレクトリにコードがクローンされます。 リポジトリで Git コマンドを実行するには、コードをリポジトリのディレクトリに変更する必要があります。 ディレクトリを変更する前に、コードで現在の作業ディレクトリを変数 (`pwd`) に保存して戻る場所を記憶した後、`clone_repository` メソッドを終了します。
The code above uses the `ruby-git` gem to clone the repository using the app's installation token. This code clones the code in the same directory as `template_server.rb`. To run Git commands in the repository, the code needs to change into the repository directory. Before changing directories, the code stores the current working directory in a variable (`pwd`) to remember where to return before exiting the `clone_repository` method.
このコードは、リポジトリのディレクトリから最新の変更をフェッチしてマージし (`@git.pull`)、ref をチェックアウトしてから (`@git.checkout(ref)`)、元の作業ディレクトリに戻ります (`pwd`)
From the repository directory, this code fetches and merges the latest changes (`@git.pull`), checks out the ref (`@git.checkout(ref)`), then changes the directory back to the original working directory (`pwd`).
これで、リポジトリをクローンして ref をチェックアウトするメソッドができました。次に、必要な入力パラメーターを取得して新しい `clone_repository` メソッドを呼び出すコードを追加する必要があります。 `initiate_check_run` ヘルパー メソッドの `***** RUN A CI TEST *****` というコメントの下に、次のコードを追加します。
Now you've got a method that clones a repository and checks out a ref. Next, you need to add code to get the required input parameters and call the new `clone_repository` method. Add the following code under the `***** RUN A CI TEST *****` comment in your `initiate_check_run` helper method:
``` ruby
# ***** RUN A CI TEST *****
@@ -368,13 +362,13 @@ head_sha = @payload['check_run']['head_sha']
clone_repository(full_repo_name, repository, head_sha)
```
上のコードは、リポジトリのフル ネームとコミットのヘッド SHA を、`check_run` Webhook ペイロードから取得します。
The code above gets the full repository name and the head SHA of the commit from the `check_run` webhook payload.
## ステップ 2.3. RuboCop を実行する
## Step 2.3. Running RuboCop
すばらしい。 リポジトリをクローンし、CI サーバーを使用してチェック実行を作成しようという段階にまで到達しました。 ここでは、[RuboCop リンター](https://docs.rubocop.org/rubocop/usage/basic_usage.html#code-style-checker) [Checks API ノーテーション](/rest/reference/checks#create-a-check-run)の核心部分に踏み込みます。
Great! You're cloning the repository and creating check runs using your CI server. Now you'll get into the nitty gritty details of the [RuboCop linter](https://docs.rubocop.org/rubocop/usage/basic_usage.html#code-style-checker) and [Checks API annotations](/rest/reference/checks#create-a-check-run).
次のコードは、RuboCop を実行し、スタイル コード エラーを JSON フォーマットで保存します。 [前のステップ](#step-22-cloning-the-repository)で追加した `clone_repository` の呼び出しの下、チェック実行を更新するコードの上に、このコードを追加して完了です。
The following code runs RuboCop and saves the style code errors in JSON format. Add this code below the call to `clone_repository` you added in the [previous step](#step-22-cloning-the-repository) and above the code that updates the check run to complete.
``` ruby
# Run RuboCop on all files in the repository
@@ -384,23 +378,23 @@ logger.debug @report
@output = JSON.parse @report
```
上記のコードは、リポジトリのディレクトリにある全てのファイルで RuboCop を実行します。 オプション `--format json` は、リンティングの結果のコピーをコンピューターで解析可能な形式で保存する便利な方法です。 JSON 形式の詳細と例については、[RuboCop のドキュメント](https://docs.rubocop.org/rubocop/formatters.html#json-formatter)をご覧ください。
The code above runs RuboCop on all files in the repository's directory. The option `--format json` is a handy way to save a copy of the linting results in a machine-parsable format. See the [RuboCop docs](https://docs.rubocop.org/rubocop/formatters.html#json-formatter) for details and an example of the JSON format.
このコードは RuboCop の結果を `@report` 変数に格納するため、リポジトリのチェックアウトを安全に削除できます。 また、このコードは JSON も解析するため、`@output` 変数を使って GitHub App のキーと変数に簡単にアクセスできます。
Because this code stores the RuboCop results in a `@report` variable, it can safely remove the checkout of the repository. This code also parses the JSON so you can easily access the keys and values in your GitHub App using the `@output` variable.
{% note %}
**注:** リポジトリの削除に使うコマンド (`rm -rf`) を元に戻すことはできません。 アプリで意図したものとは異なるディレクトリを削除するために使われる可能性がある悪意のあるコマンドの挿入を Webhook で調べる方法については、「[ステップ 2.7. セキュリティのヒント](#step-27-security-tips)」をご覧ください。 たとえば、悪意のあるアクターが `./` というリポジトリ名を使って Webhook を送信した場合、アプリはルート ディレクトリを削除します。 😱何らかの理由で _メソッド_ (に含まれている) を使用して Webhook の送信者を検証`verify_webhook_signature`していない`template_server.rb`場合は、リポジトリ名が有効であることを確認してください。
**Note:** The command used to remove the repository (`rm -rf`) cannot be undone. See [Step 2.7. Security tips](#step-27-security-tips) to learn how to check webhooks for injected malicious commands that could be used to remove a different directory than intended by your app. For example, if a bad actor sent a webhook with the repository name `./`, your app would remove the root directory. 😱 If for some reason you're _not_ using the method `verify_webhook_signature` (which is included in `template_server.rb`) to validate the sender of the webhook, make sure you check that the repository name is valid.
{% endnote %}
このコードが動作することをテストし、サーバーのデバッグ出力で RuboCop により報告されたエラーを確認できます。 `template_server.rb` サーバーを再起動し、アプリをテストしているリポジトリで新しい pull request を作成します。
You can test that this code works and see the errors reported by RuboCop in your server's debug output. Start up the `template_server.rb` server again and create a new pull request in the repository where you're testing your app:
```shell
$ ruby template_server.rb
```
デバッグ出力に文法エラーが表示されているはずです。ただし、出力は整形されていません。 [JSON フォーマッタ](https://jsonformatter.org/)のような Web ツールを使うと、JSON 出力を次のように書式設定されたリンティング エラー出力に整形できます。
You should see the linting errors in the debug output, although they aren't printed with formatting. You can use a web tool like [JSON formatter](https://jsonformatter.org/) to format your JSON output like this formatted linting error output:
```json
{
@@ -456,17 +450,17 @@ $ ruby template_server.rb
}
```
## ステップ 2.4. RuboCop のエラーを収集する
## Step 2.4. Collecting RuboCop errors
`@output` 変数には、RuboCop レポートの解析済みの JSON の結果が含まれます。 上で示すように、結果には `summary` セクションが含まれており、コードでエラーがあるかどうかを迅速に判断するために使えます。 次のコードは、エラーが報告されないときは、チェック実行の結果を `success` に設定します。 RuboCop は `files` 配列で各ファイルのエラーを報告するので、エラーがある場合、file オブジェクトからデータを抽出する必要があります。
The `@output` variable contains the parsed JSON results of the RuboCop report. As shown above, the results contain a `summary` section that your code can use to quickly determine if there are any errors. The following code will set the check run conclusion to `success` when there are no reported errors. RuboCop reports errors for each file in the `files` array, so if there are errors, you'll need to extract some data from the file object.
Checks API により、コードの特定の行に対してアノテーションを作成することができます。 チェック実行を作成または更新する際に、アノテーションを追加できます。 このクイックスタートでは、アノテーションを使って[チェック実行を更新](/rest/reference/checks#update-a-check-run)しています。
The Checks API allows you to create annotations for specific lines of code. When you create or update a check run, you can add annotations. In this quickstart you are [updating the check run](/rest/reference/checks#update-a-check-run) with annotations.
Checks API では、アノテーションの数は API の 1 リクエストあたり最大 50 に制限されています。 51 個以上のアノテーションを作るには、"[チェック実行を更新する](/rest/reference/checks#update-a-check-run)" エンドポイントに対して要求を複数回行う必要があります。 たとえば、105 個のアノテーションを作るには、"[チェック実行を更新する](/rest/reference/checks#update-a-check-run)" エンドポイントを 3 回呼び出す必要があります。 始めの 2 回のリクエストでそれぞれ 50 個のアテーションが作成され、3 回目のリクエストで残り 5 つのアノテーションが作成されます。 チェック実行を更新するたびに、アノテーションは既存のチェック実行にあるアノテーションのリストに追加されます。
The Checks API limits the number of annotations to a maximum of 50 per API request. To create more than 50 annotations, you have to make multiple requests to the [Update a check run](/rest/reference/checks#update-a-check-run) endpoint. For example, to create 105 annotations you'd need to call the [Update a check run](/rest/reference/checks#update-a-check-run) endpoint three times. The first two requests would each have 50 annotations, and the third request would include the five remaining annotations. Each time you update the check run, annotations are appended to the list of annotations that already exist for the check run.
チェック実行は、アノテーションをオブジェクトの配列として受け取ります。 各アノテーション オブジェクトには、`path``start_line``end_line``annotation_level``message` が含まれている必要があります。 RuboCop により `start_column` `end_column` も提供されるので、それらのオプションのパラメーターをアノテーションに含めることができます。 アノテーションの `start_column` `end_column` は、同じ行でのみサポートされます。 詳しくは、[`annotations` オブジェクト](/rest/reference/checks#annotations-object-1)の参照ドキュメントをご覧ください。
A check run expects annotations as an array of objects. Each annotation object must include the `path`, `start_line`, `end_line`, `annotation_level`, and `message`. RuboCop provides the `start_column` and `end_column` too, so you can include those optional parameters in the annotation. Annotations only support `start_column` and `end_column` on the same line. See the [`annotations` object](/rest/reference/checks#annotations-object-1) reference documentation for details.
各アノテーションを作成するために必要な RuboCop から、必須の情報を抽出します。 [前のセクション](#step-23-running-rubocop)で追加したコードの後に次のコードを追加します。
You'll extract the required information from RuboCop needed to create each annotation. Append the following code to the code you added in the [previous section](#step-23-running-rubocop):
``` ruby
annotations = []
@@ -521,21 +515,21 @@ else
end
```
このコードでは、アノテーションの合計数を 50 に制限しています。 このコードを、50 のアノテーションごとにチェック実行を更新するよう変更することも可能です。 上のコードには、違反を反復処理するループで使われる変数 `max_annotations` が含まれていて、制限が 50 に設定されています。
This code limits the total number of annotations to 50. But you can modify this code to update the check run for each batch of 50 annotations. The code above includes the variable `max_annotations` that sets the limit to 50, which is used in the loop that iterates through the offenses.
`offense_count` が 0 の場合、CI テストは `success` になります。 エラーがある場合、このコードは結果を `neutral` に設定します。これは、コード リンターによってエラーが厳格に強制されるのを防ぐためです。 ただし、リンティング エラーがある場合にチェックスイートが失敗になるようにしたい場合は、結果を `failure` に変更できます。
When the `offense_count` is zero, the CI test is a `success`. If there are errors, this code sets the conclusion to `neutral` in order to prevent strictly enforcing errors from code linters. But you can change the conclusion to `failure` if you would like to ensure that the check suite fails when there are linting errors.
エラーが報告されると、上のコードは RuboCop レポートの `files` 配列を反復処理します。 各ファイルについて、ファイル パスが抽出され、アノテーション レベルが `notice` に設定されます。 さらに細かく、[RuboCop Cop](https://docs.rubocop.org/rubocop/cops.html) の各種類に特定の警告レベルを設定することもできますが、このクイックスタートでは簡単さを優先し、すべてのエラーを `notice` のレベルに設定します。
When errors are reported, the code above iterates through the `files` array in the RuboCop report. For each file, it extracts the file path and sets the annotation level to `notice`. You could go even further and set specific warning levels for each type of [RuboCop Cop](https://docs.rubocop.org/rubocop/cops.html), but to keep things simpler in this quickstart, all errors are set to a level of `notice`.
このコードでは、また、`offenses` 配列の各エラーを反復処理し、違反の場所とエラー メッセージを収集します。 必要な情報を抽出した後、コードでエラーごとにアノテーションを作成して、`annotations` 配列に格納します。 アノテーションは開始列と終了列が同じ行にある場合にのみサポートされるため、開始行と終了行の値が同じ場合にだけ、`start_column` `end_column` `annotation` オブジェクトに追加されます。
This code also iterates through each error in the `offenses` array and collects the location of the offense and error message. After extracting the information needed, the code creates an annotation for each error and stores it in the `annotations` array. Because annotations only support start and end columns on the same line, `start_column` and `end_column` are only added to the `annotation` object if the start and end line values are the same.
このコードはまだチェック実行のアノテーションを作成しません。 それを作成するコードは、次のセクションで追加します。
This code doesn't yet create an annotation for the check run. You'll add that code in the next section.
## ステップ 2.5. CI テスト結果でチェック実行を更新する
## Step 2.5. Updating the check run with CI test results
GitHub からの各チェック実行には、`title``summary``text``annotations``images` を含む `output` オブジェクトが含まれます。 `output` の必須パラメーターは `summary``title` だけですが、それらだけでは十分に詳細な情報が提供されないので、このクイックスタートでは `text` `annotations` も追加します。 ここに挙げるコードでは画像は追加しませんが、追加したければぜひどうぞ。
Each check run from GitHub contains an `output` object that includes a `title`, `summary`, `text`, `annotations`, and `images`. The `summary` and `title` are the only required parameters for the `output`, but those alone don't offer much detail, so this quickstart adds `text` and `annotations` too. The code here doesn't add an image, but feel free to add one if you'd like!
`summary` については、この例では RuboCop からの概要情報を使い、出力の書式を設定するために改行 (`\n`) をいくつか追加します。 `text` パラメーターに追加するものはカスタマイズできますが、この例では RuboCop のバージョンを `text` パラメーターに設定します。 `summary` `text` を設定するには、[前のセクション](#step-24-collecting-rubocop-errors)で追加したコードに次のコードを追加します。
For the `summary`, this example uses the summary information from RuboCop and adds some newlines (`\n`) to format the output. You can customize what you add to the `text` parameter, but this example sets the `text` parameter to the RuboCop version. To set the `summary` and `text`, append this code to the code you added in the [previous section](#step-24-collecting-rubocop-errors):
``` ruby
# Updated check run summary and text parameters
@@ -543,7 +537,7 @@ summary = "Octo RuboCop summary\n-Offense count: #{@output['summary']['offense_c
text = "Octo RuboCop version: #{@output['metadata']['rubocop_version']}"
```
さて、これでチェック実行を更新するために必要な情報がすべて揃いました。 [このクイックスタートの前半](#step-14-updating-a-check-run)では、チェック実行のステータスを `success` に設定するためにこのコードを追加しました。
Now you've got all the information you need to update your check run. In the [first half of this quickstart](#step-14-updating-a-check-run), you added this code to set the status of the check run to `success`:
``` ruby
# Mark the check run as complete!
@@ -556,7 +550,7 @@ text = "Octo RuboCop version: #{@output['metadata']['rubocop_version']}"
)
```
そのコードを、RuboCop の結果に基づいて (`success` または `neutral` に) 設定した `conclusion` 変数を使うように、更新する必要があります。 コードは以下のようにして更新できます。
You'll need to update that code to use the `conclusion` variable you set based on the RuboCop results (to `success` or `neutral`). You can update the code with the following:
``` ruby
# Mark the check run as complete! And if there are warnings, share them.
@@ -580,48 +574,48 @@ text = "Octo RuboCop version: #{@output['metadata']['rubocop_version']}"
)
```
さて、これで CI テストのステータスに基づいて結論を設定し、RuboCop の結果からの出力を追加しました。あなたは CI テストを作成したのです。 お疲れさまでした。 🙌
Now that you're setting a conclusion based on the status of the CI test and you've added the output from the RuboCop results, you've created a CI test! Congratulations. 🙌
また、上のコードでは、`actions` オブジェクトによって CI サーバーに[要求されたアクション](https://developer.github.com/changes/2018-05-23-request-actions-on-checks/)という機能も追加されます。 {% ifversion fpt or ghec %}(これは [GitHub Actions](/actions) には関係がないことに注意してください)。{% endif %}"要求されたアクション" により、追加アクションの実行をチェック実行に要求できるボタンが GitHub の **[チェック]** タブに追加されます。 追加のアクションは、アプリケーションが自由に設定できます。 たとえば、RuboCop には Ruby のコードで見つかったエラーを自動的に修正する機能があるので、CI サーバーはリクエストされたアクションボタンを使用して、自動的なエラー修正をユーザが許可することができます。 このボタンをクリックすると、アプリは `requested_action` アクションを含む `check_run` イベントを受け取ります。 アプリでは、各要求されたアクションに含まれる `identifier` を使って、クリックされたボタンを特定します。
The code above also adds a feature to your CI server called [requested actions](https://developer.github.com/changes/2018-05-23-request-actions-on-checks/) via the `actions` object. {% ifversion fpt or ghec %}(Note this is not related to [GitHub Actions](/actions).) {% endif %}Requested actions add a button in the **Checks** tab on GitHub that allows someone to request the check run to take additional action. The additional action is completely configurable by your app. For example, because RuboCop has a feature to automatically fix the errors it finds in Ruby code, your CI server can use a requested actions button to allow people to request automatic error fixes. When someone clicks the button, the app receives the `check_run` event with a `requested_action` action. Each requested action has an `identifier` that the app uses to determine which button was clicked.
上記のコードには、まだ RuboCop が自動的にエラーを修正する処理がありません。 この処理については、次のセクションで追加します。 ただし、まず、`template_server.rb` サーバーをもう一度起動して新しい pull request を作成することで、作成した CI テストを見てみましょう。
The code above doesn't have RuboCop automatically fix errors yet. You'll add that in the next section. But first, take a look at the CI test that you just created by starting up the `template_server.rb` server again and creating a new pull request:
```shell
$ ruby template_server.rb
```
アノテーションが **[チェック]** タブに表示されます。
The annotations will show up in the **Checks** tab.
![[Checks] タブのチェック実行アノテーション](/assets/images/github-apps/github_apps_checks_annotations.png)
![Check run annotations in the checks tab](/assets/images/github-apps/github_apps_checks_annotations.png)
リクエストされたアクションを追加することにより作成された [Fix this] ボタンに注目してください。
Notice the "Fix this" button that you created by adding a requested action.
![チェック実行のリクエストされたアクションのボタン](/assets/images/github-apps/github_apps_checks_fix_this_button.png)
![Check run requested action button](/assets/images/github-apps/github_apps_checks_fix_this_button.png)
既に PR に含まれるファイルにアノテーションが関連している場合、 **[変更されたファイル]** タブにもそのアノテーションが表示されます。
If the annotations are related to a file already included in the PR, the annotations will also show up in the **Files changed** tab.
![ファイルが変更されたタブのチェック実行アノテーション](/assets/images/github-apps/github_apps_checks_annotation_diff.png)
![Check run annotations in the files changed tab](/assets/images/github-apps/github_apps_checks_annotation_diff.png)
## ステップ 2.6. RuboCop のエラーを自動的に修正する
## Step 2.6. Automatically fixing RuboCop errors
ここまで来たのはすごいですよ! 👏 CI テストの作成は済んでいます。 このセクションでは、もう 1 つの機能を追加します。RuboCop を使用して、見つけたエラーを自動的に修正するために使用するための機能です。 [これを修正する] ボタンは、[前のセクション](#step-25-updating-the-check-run-with-ci-test-results)で既に追加しました。 ここでは、[これを修正する] ボタンがクリックされるとトリガーされる `requested_action` チェック実行イベントを処理するコードを追加します。
If you've made it this far, kudos! 👏 You've already created a CI test. In this section, you'll add one more feature that uses RuboCop to automatically fix the errors it finds. You already added the "Fix this" button in the [previous section](#step-25-updating-the-check-run-with-ci-test-results). Now you'll add the code to handle the `requested_action` check run event triggered when someone clicks the "Fix this" button.
RuboCop ツールには、検出されたエラーを自動的に修正するための `--auto-correct` コマンド ライン オプションが[用意されています](https://docs.rubocop.org/rubocop/usage/basic_usage.html#auto-correcting-offenses) `--auto-correct` 機能を使うと、サーバー上のローカル ファイルに更新が適用されます。 RuboCop がこの作業をやってのけた後は、その変更を GitHub にプッシュする必要があります。
The RuboCop tool [offers](https://docs.rubocop.org/rubocop/usage/basic_usage.html#auto-correcting-offenses) the `--auto-correct` command-line option to automatically fix errors it finds. When you use the `--auto-correct` feature, the updates are applied to the local files on the server. You'll need to push the changes to GitHub after RuboCop does its magic.
リポジトリにブッシュするには、アプリケーションに [Repository contents] への書き込み権限が必要です。 このアクセス許可は、「[ステップ 2.2. リポジトリの複製](#step-22-cloning-the-repository)」で既に **読み取りと書き込み** に設定してあるので、準備はすべて整っています。
To push to a repository, your app must have write permissions for "Repository contents." You set that permission back in [Step 2.2. Cloning the repository](#step-22-cloning-the-repository) to **Read & write**, so you're all set.
ファイルをコミットするには、Git はコミットに関連付ける[ユーザー名](/github/getting-started-with-github/setting-your-username-in-git/)と[メール アドレス](/articles/setting-your-commit-email-address-in-git/)を認識する必要があります。 名前 (`GITHUB_APP_USER_NAME`) とメール アドレス (`GITHUB_APP_USER_EMAIL`) の設定を格納するための 2 つの環境変数を、`.env` ファイルに追加します。 アプリケーションにはあなたの名前を付けることもできます。この例では、メールアドレスは何でも構いません。 次に例を示します。
In order to commit files, Git must know which [username](/github/getting-started-with-github/setting-your-username-in-git/) and [email](/articles/setting-your-commit-email-address-in-git/) to associate with the commit. Add two more environment variables in your `.env` file to store the name (`GITHUB_APP_USER_NAME`) and email (`GITHUB_APP_USER_EMAIL`) settings. Your name can be the name of your app and the email can be any email you'd like for this example. For example:
```ini
GITHUB_APP_USER_NAME=Octoapp
GITHUB_APP_USER_EMAIL=octoapp@octo-org.com
```
作成者およびコミットしたユーザーの名前とメール アドレスで `.env` ファイルを更新したら、環境変数を読み取って Git 構成を設定するコードを追加する準備が整います。 このコードは、もうすぐ追加することになります。
Once you've updated your `.env` file with the name and email of the author and committer, you'll be ready to add code to read the environment variables and set the Git configuration. You'll add that code soon.
[これを修正する] ボタンをクリックすると、アプリは `requested_action` アクションの種類を含む[チェック実行 Webhook](/webhooks/event-payloads/#check_run) を受信します。
When someone clicks the "Fix this" button, your app receives the [check run webhook](/webhooks/event-payloads/#check_run) with the `requested_action` action type.
「[ステップ 1.4. チェック実行を更新する](#step-14-updating-a-check-run)」で、`check_run` イベント内のアクションを検索するように `event_handler` を更新しました。 `created` `rerequested` のアクションの種類を処理する case ステートメントは既に存在します。
In [Step 1.4. Updating a check run](#step-14-updating-a-check-run) you updated the your `event_handler` to handle look for actions in the `check_run` event. You already have a case statement to handle the `created` and `rerequested` action types:
``` ruby
when 'check_run'
@@ -636,14 +630,14 @@ when 'check_run'
end
```
`rerequested_action` イベントを処理するための別の `when` ステートメントを、`rerequested` ケースの後に追加します。
Add another `when` statement after the `rerequested` case to handle the `rerequested_action` event:
``` ruby
when 'requested_action'
take_requested_action
```
このコードは、アプリに対するすべての `requested_action` イベントを処理する新しいメソッドを呼び出します。 以下のメソッドをコードのヘルパーメソッドセクションに追加します。
This code calls a new method that will handle all `requested_action` events for your app. Add the following method to the helper methods section of your code:
``` ruby
# Handles the check run `requested_action` event
@@ -678,11 +672,11 @@ def take_requested_action
end
```
上のコードは、「[ステップ 2.2. リポジトリの複製](#step-22-cloning-the-repository)」で追加したコードと同じようにリポジトリをクローンします。 `if` ステートメントは、要求されたアクションの識別子が RuboCop のボタン識別子 (`fix_rubocop_notices`) と一致することを確認します。 それらが一致する場合、コードはリポジトリをクローンし、Git のユーザー名とメール アドレスを設定してから、オプション `--auto-correct` を指定して RuboCop を実行します。 `--auto-correct` オプションは、ローカル環境の CI サーバー ファイルに変更を自動的に適用します。
The code above clones a repository just like the code you added in [Step 2.2. Cloning the repository](#step-22-cloning-the-repository). An `if` statement checks that the requested action's identifier matches the RuboCop button identifier (`fix_rubocop_notices`). When they match, the code clones the repository, sets the Git username and email, and runs RuboCop with the option `--auto-correct`. The `--auto-correct` option applies the changes to the local CI server files automatically.
ファイルはローカルで変更されますが、それを GitHub にプッシュする必要はあります。 もう一度便利な `ruby-git` gem を使って、すべてのファイルをコミットします。 Git には、変更または削除されたすべてのファイルをステージングし、それらをコミットする `git commit -a` というコマンドがあります。 `ruby-git` を使って同じことを行うため、上のコードでは `commit_all` メソッドを使っています。 その後、Git の `clone` コマンドと同じ認証方法を使い、インストール トークンを使って GitHub にコミットしたファイルをプッシュします。 最後に、リポジトリディレクトリを削除して、ワーキングディレクトリが次のイベントに備えるようにします。
The files are changed locally, but you'll still need to push them to GitHub. You'll use the handy `ruby-git` gem again to commit all of the files. Git has a single command that stages all modified or deleted files and commits them: `git commit -a`. To do the same thing using `ruby-git`, the code above uses the `commit_all` method. Then the code pushes the committed files to GitHub using the installation token, using the same authentication method as the Git `clone` command. Finally, it removes the repository directory to ensure the working directory is prepared for the next event.
これで完了です。 Checks API CI サーバーのコードがついに完成しました。 💪 `template_server.rb` サーバーをもう一度再起動し、新しい pull request を作成します。
That's it! The code you have written now completes your Checks API CI server. 💪 Restart your `template_server.rb` server again and create a new pull request:
```shell
$ ruby template_server.rb
@@ -690,21 +684,21 @@ $ ruby template_server.rb
{% data reusables.apps.sinatra_restart_instructions %}
今回は、[これを修正する] ボタンをクリックすると、RuboCop が **[チェック]** タブで検出したエラーが自動的に修正されます。
This time, click the "Fix this" button to automatically fix the errors RuboCop found from the **Checks** tab.
**[コミット]** タブには、Git の構成で設定したユーザー名で新しいコミットが表示されます。 更新を確認するには、ブラウザを更新する必要がある場合があります。
In the **Commits** tab, you'll see a brand new commit by the username you set in your Git configuration. You may need to refresh your browser to see the update.
![Octo RuboCop の通知を自動的に修正する新しいコミット](/assets/images/github-apps/github_apps_new_requested_action_commit.png)
![A new commit to automatically fix Octo RuboCop notices](/assets/images/github-apps/github_apps_new_requested_action_commit.png)
新しいコミットがリポジトリにプッシュされたので、 **[チェック]** タブに Octo RuboCop の新しいチェック スイートが表示されています。しかし、今回は RuboCop によってすべて修正されたためエラーはありません。 🎉
Because a new commit was pushed to the repo, you'll see a new check suite for Octo RuboCop in the **Checks** tab. But this time there are no errors because RuboCop fixed them all. 🎉
![チェックスイート、チェック実行のエラーなし](/assets/images/github-apps/github_apps_checks_api_success.png)
![No check suite or check run errors](/assets/images/github-apps/github_apps_checks_api_success.png)
作成したアプリの完成したコードは、「[Checks API で CI テストを作成する](https://github.com/github-developer/creating-ci-tests-with-the-checks-api)」のリポジトリの `server.rb` ファイルにあります。
You can find the completed code for the app you just built in the `server.rb` file in the [Creating CI tests with the Checks API](https://github.com/github-developer/creating-ci-tests-with-the-checks-api) repository.
## ステップ 2.7. セキュリティのヒント
## Step 2.7. Security tips
GitHub App コードのテンプレートには、受信した webhook ペイロードを検証して、信頼できるソースからのものであることを確認するためのメソッドが最初から用意されています。 webhook ペイロードを検証しない場合、リポジトリ名が webhook ペイロードに含まれる際には、その webhook が悪意をもって使用されかねない任意のコマンドを確実に含まないようにする必要があります。 以下のコードは、リポジトリ名に含まれる文字がラテン文字、ハイフン、アンダースコアのみであることを検証します。 完全な例を提供するため、このクイックスタートの[コンパニオン リポジトリ](https://github.com/github-developer/creating-ci-tests-with-the-checks-api)で入手できる完全な `server.rb` のコードには、受信した Webhook ペイロードを検証するメソッドと、リポジトリ名を検証するためのこのチェックの両方が含まれています。
The template GitHub App code already has a method to verify incoming webhook payloads to ensure they are from a trusted source. If you are not validating webhook payloads, you'll need to ensure that when repository names are included in the webhook payload, the webhook does not contain arbitrary commands that could be used maliciously. The code below validates that the repository name only contains Latin alphabetic characters, hyphens, and underscores. To provide you with a complete example, the complete `server.rb` code available in the [companion repository](https://github.com/github-developer/creating-ci-tests-with-the-checks-api) for this quickstart includes both the method of validating incoming webhook payloads and this check to verify the repository name.
``` ruby
# This quickstart example uses the repository name in the webhook with
@@ -718,43 +712,43 @@ unless @payload['repository'].nil?
end
```
## トラブルシューティング
## Troubleshooting
以下は、いくつかの一般的な問題と推奨される解決策です。 他の問題が生じた場合は、{% data variables.product.prodname_support_forum_with_url %}で助けやアドバイスを求めることができます。
Here are a few common problems and some suggested solutions. If you run into any other trouble, you can ask for help or advice in the {% data reusables.support.prodname_support_forum_with_url %}.
* **Q:** アプリで GitHub にコードがプッシュされません。 RuboCop が自動的に行う修正が表示されません。
* **Q:** My app isn't pushing code to GitHub. I don't see the fixes that RuboCop automatically makes!
**A:** "リポジトリの内容" に対する **読み取りと書き込み** アクセス許可があること、およびインストール トークンを使ってリポジトリをクローンしていることを確認します。 詳しくは、「[ステップ 2.2. リポジトリの複製](#step-22-cloning-the-repository)」をご覧ください。
**A:** Make sure you have **Read & write** permissions for "Repository contents," and that you are cloning the repository with your installation token. See [Step 2.2. Cloning the repository](#step-22-cloning-the-repository) for details.
* **Q:** `template_server.rb` のデバッグ出力に、リポジトリのクローンに関するエラーが表示されます。
* **Q:** I see an error in the `template_server.rb` debug output related to cloning my repository.
**A:** 以下のエラーが表示される場合、`initiate_check_run` `take_requested_action` メソッドの一方または両方で、リポジトリのチェックアウトを削除していません。
**A:** If you see the following error, you haven't deleted the checkout of the repository in one or both of the `initiate_check_run` or `take_requested_action` methods:
```shell
2018-11-26 16:55:13 - Git::GitExecuteError - git clone '--' 'https://x-access-token:ghs_9b2080277016f797074c4dEbD350745f4257@github.com/codertocat/octocat-breeds.git' 'Octocat-breeds' 2>&1:fatal: destination path 'Octocat-breeds' already exists and is not an empty directory.:
```
自分のコードを `server.rb` ファイルと比較し、`initiate_check_run` および `take_requested_action` メソッドのコードが同じであることを確認してください。
Compare your code to the `server.rb` file to ensure you have the same code in your `initiate_check_run` and `take_requested_action` methods.
* **Q:** 新しいチェック実行が、GitHub の [チェック] タブに表示されません。
* **Q:** New check runs are not showing up in the "Checks" tab on GitHub.
**A:** Smee を再起動し、`template_server.rb` サーバーを実行し直してください。
**A:** Restart Smee and re-run your `template_server.rb` server.
* **Q:** [すべて再実行] ボタンが GitHub の [チェック] タブに表示されません。
* **Q:** I do not see the "Re-run all" button in the "Checks" tab on GitHub.
**A:** Smee を再起動し、`template_server.rb` サーバーを実行し直してください。
**A:** Restart Smee and re-run your `template_server.rb` server.
## まとめ
## Conclusion
このガイドの手順を一通り終えたら、Checks API を使用して CI サーバーを作成することの基本が習得できています。 振り返ると、以下を行いました。
After walking through this guide, you've learned the basics of using the Checks API to create a CI server! To review, you:
* Checks API イベントを受信し、チェック実行を作成するようサーバーを設定しました。
* リポジトリ内のコードをチェックし、エラーのアノテーションを作成するため RuboCop を使用しました。
* 文法エラーを自動的に修正する、リクエストされたアクションを実装しました。
* Configured your server to receive Checks API events and create check runs.
* Used RuboCop to check code in repositories and create annotations for the errors.
* Implemented a requested action that automatically fixes linter errors.
## 次の手順
## Next steps
以下は、次に行えることのいくつかのアイデアです。
Here are some ideas for what you can do next:
* 現在、[Fix this] ボタンは常に表示されています。 ここまで書いたコードを更新し、RuboCop がエラーを見つけた時にのみ [Fix this] ボタンが表示されるようにしましょう。
* RuboCop で head ブランチにファイルを直接コミットしたくない場合は、head ブランチに基づいて新しいブランチで [pull request を作成する](/rest/reference/pulls#create-a-pull-request)ようにコードを更新できます。
* Currently, the "Fix this" button is always displayed. Update the code you wrote to display the "Fix this" button only when RuboCop finds errors.
* If you'd prefer that RuboCop doesn't commit files directly to the head branch, you can update the code to [create a pull request](/rest/reference/pulls#create-a-pull-request) with a new branch based on the head branch.

View File

@@ -1,6 +1,6 @@
---
title: アプリケーションでのGitHub APIの利用
intro: イベントを待ち受けるアプリケーションのセットアップと、Octokitライブラリを使ったREST APIの操作の方法を学んでください。
title: Using the GitHub API in your app
intro: Learn how to set up your app to listen for events and use the Octokit library to perform REST API operations.
redirect_from:
- /apps/building-your-first-github-app
- /apps/quickstart-guides/using-the-github-api-in-your-app
@@ -13,94 +13,88 @@ versions:
topics:
- GitHub Apps
shortTitle: Build an app with the REST API
ms.openlocfilehash: 93679e41fe145406ed1eb99e2daaba6bf8e10e76
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 09/05/2022
ms.locfileid: '145089911'
---
## はじめに
## Introduction
このガイドは、GitHub Appをビルドしてサーバー上で実行するのに役立ちます。 ビルドするアプリケーションは、アプリケーションがインストールされたリポジトリでオープンされたすべての新しいIssueにラベルを付けます。
This guide will help you build a GitHub App and run it on a server. The app you build will add a label to all new issues opened in the repository where the app is installed.
このプロジェクトでは、以下を見ていきます。
This project will walk you through the following:
* イベントを待ち受けるアプリケーションのプログラミング
* Octokit.rbライブラリを使ったREST APIの操作の実行
* Programming your app to listen for events
* Using the Octokit.rb library to do REST API operations
{% data reusables.apps.app-ruby-guides %}
以下のステップを行っていけば、GitHub APIの完全な一式を使って他の種類のインテグレーションを開発する準備が整います。 {% ifversion fpt or ghec %}[GitHub Marketplace](https://github.com/marketplace) と「[GitHub での作業](https://github.com/works-with)」でアプリの成功事例を確認できます。{% endif %}
Once you've worked through the steps, you'll be ready to develop other kinds of integrations using the full suite of GitHub APIs. {% ifversion fpt or ghec %}You can check out successful examples of apps on [GitHub Marketplace](https://github.com/marketplace) and [Works with GitHub](https://github.com/works-with).{% endif %}
## 前提条件
## Prerequisites
以下に関する基本的な理解があると役立つでしょう。
You may find it helpful to have a basic understanding of the following:
* [GitHub アプリ](/apps/about-apps)
* [Webhook](/webhooks)
* [プログラミング言語の Ruby](https://www.ruby-lang.org/en/)
* [REST API](/rest)
* [GitHub Apps](/apps/about-apps)
* [Webhooks](/webhooks)
* [The Ruby programming language](https://www.ruby-lang.org/en/)
* [REST APIs](/rest)
* [Sinatra](http://sinatrarb.com/)
とはいえ、経験のレベルにかかわらず見ていくことはできます。 その過程で必要な情報にはリンクしていきます!
But you can follow along at any experience level. We'll link out to information you need along the way!
始める前に、以下を行っておく必要があります。
Before you begin, you'll need to do the following:
1. [アプリでの GitHub API の使用](https://github.com/github-developer/using-the-github-api-in-your-app)リポジトリをクローンします。
1. Clone the [Using the GitHub API in your app](https://github.com/github-developer/using-the-github-api-in-your-app) repository.
```shell
$ git clone https://github.com/github-developer/using-the-github-api-in-your-app.git
```
ディレクトリの中には、このクイックスタートで使うテンプレート コードを含む `template_server.rb` ファイルと、完成したプロジェクト コードを含む `server.rb` ファイルがあります。
Inside the directory, you'll find a `template_server.rb` file with the template code you'll use in this quickstart and a `server.rb` file with the completed project code.
1. [開発環境のセットアップ](/apps/quickstart-guides/setting-up-your-development-environment/)に関するクイックスタートの手順に従い、`template_server.rb` アプリ サーバーを構成して実行します。 [開発環境のセットアップ](/apps/quickstart-guides/setting-up-your-development-environment/)以外の GitHub App のクイックスタートを以前に完了している場合は、 _"新しい"_ GitHub App を登録し、このクイックスタートで使用する新しい Smee チャネルを開始する必要があります。
1. Follow the steps in the [Setting up your development environment](/apps/quickstart-guides/setting-up-your-development-environment/) quickstart to configure and run the `template_server.rb` app server. If you've previously completed a GitHub App quickstart other than [Setting up your development environment](/apps/quickstart-guides/setting-up-your-development-environment/), you should register a _new_ GitHub App and start a new Smee channel to use with this quickstart.
このクイックスタートには、[開発環境のセットアップ](/apps/quickstart-guides/setting-up-your-development-environment/)に関するクイックスタートと同じ `template_server.rb` コードが含まれています。 **注:** [開発環境のセットアップ](/apps/quickstart-guides/setting-up-your-development-environment/)に関するクイックスタートに従って、[アプリでの GitHub API の使用](https://github.com/github-developer/using-the-github-api-in-your-app)リポジトリに含まれているプロジェクト ファイルを必ず使用してください。
This quickstart includes the same `template_server.rb` code as the [Setting up your development environment](/apps/quickstart-guides/setting-up-your-development-environment/) quickstart. **Note:** As you follow along with the [Setting up your development environment](/apps/quickstart-guides/setting-up-your-development-environment/) quickstart, make sure to use the project files included in the [Using the GitHub API in your app](https://github.com/github-developer/using-the-github-api-in-your-app) repository.
テンプレート GitHub App の設定で問題が発生する場合は、「[トラブルシューティング](/apps/quickstart-guides/setting-up-your-development-environment/#troubleshooting)」セクションをご覧ください。
See the [Troubleshooting](/apps/quickstart-guides/setting-up-your-development-environment/#troubleshooting) section if you are running into problems setting up your template GitHub App.
## アプリケーションのビルド
## Building the app
`template_server.rb` のコードに馴染んだところで、アプリケーションがインストールされたリポジトリでオープンされたすべての issue に自動的に `needs-response` ラベルを追加するコードを作成しましょう。
Now that you're familiar with the `template_server.rb` code, you're going to create code that automatically adds the `needs-response` label to all issues opened in the repository where the app is installed.
この `template_server.rb` ファイルには、まだカスタマイズされていないアプリ テンプレート コードが含まれています。 このファイルには、webhookイベントを処理するためのプレースホルダーのコードや、Octokit.rbクライアントを初期化する他のコードが含まれています。
The `template_server.rb` file contains app template code that has not yet been customized. In this file, you'll see some placeholder code for handling webhook events and some other code for initializing an Octokit.rb client.
{% note %}
**:** `template_server.rb` には、このガイドを補完し、追加の技術的な詳細を説明する多くのコード コメントが含まれています。 このセクションの先に進む前に、コードの動作の概要をつかむために、この時点でこのファイル中のコメントを読み通しておくと役立つかもしれません。
**Note:** `template_server.rb` contains many code comments that complement this guide and explain additional technical details. You may find it helpful to read through the comments in that file now, before continuing with this section, to get an overview of how the code works.
このガイドの終わりまでに作成するカスタマイズされた最終コードは、[`server.rb`](https://github.com/github-developer/using-the-github-api-in-your-app/blob/master/server.rb) にあります。 とはいえ、最後までそれを見るのは待ってみてください!
The final customized code that you'll create by the end of this guide is provided in [`server.rb`](https://github.com/github-developer/using-the-github-api-in-your-app/blob/master/server.rb). Try waiting until the end to look at it, though!
{% endnote %}
以下が、最初のGitHub Appを作成するまでに行うステップです。
These are the steps you'll complete to create your first GitHub App:
1. [アプリのアクセス許可を更新する](#step-1-update-app-permissions)
2. [イベント処理の追加](#step-2-add-event-handling)
3. [新しいラベルの作成](#step-3-create-a-new-label)
4. [ラベルの処理の追加](#step-4-add-label-handling)
1. [Update app permissions](#step-1-update-app-permissions)
2. [Add event handling](#step-2-add-event-handling)
3. [Create a new label](#step-3-create-a-new-label)
4. [Add label handling](#step-4-add-label-handling)
## 手順 1. アプリのアクセス許可を更新する
## Step 1. Update app permissions
[最初にアプリを登録](/apps/quickstart-guides/setting-up-your-development-environment/#step-2-register-a-new-github-app)したときは、既定のアクセス許可を受け入れました。これは、アプリがほとんどのリソースにアクセスできないことを意味します。 この例においては、アプリケーションはIssueを読み、ラベルを書く権限を必要とします。
When you [first registered your app](/apps/quickstart-guides/setting-up-your-development-environment/#step-2-register-a-new-github-app), you accepted the default permissions, which means your app doesn't have access to most resources. For this example, your app will need permission to read issues and write labels.
アプリケーションの権限を更新するには、以下の手順に従います。
To update your app's permissions:
1. [アプリの設定ページ](https://github.com/settings/apps)でアプリを選び、サイドバーの **[アクセス許可と Webhook]** をクリックします。
1. [アクセス許可] セクションで [Issue] を探し、その横にある [アクセス] ドロップダウンで **[読み取りと書き込み]** を選びます。 このオプションはIssueとラベルの両方へのアクセスを許可するものと説明されており、これはまさに必要なことです。
1. [イベントのサブスクライブ] セクションで、 **[Issue]** を選んでイベントをサブスクライブします。
1. Select your app from the [app settings page](https://github.com/settings/apps) and click **Permissions & Webhooks** in the sidebar.
1. In the "Permissions" section, find "Issues," and select **Read & Write** in the "Access" dropdown next to it. The description says this option grants access to both issues and labels, which is just what you need.
1. In the "Subscribe to events" section, select **Issues** to subscribe to the event.
{% data reusables.apps.accept_new_permissions_steps %}
すばらしい。 アプリケーションは必要なタスクを実行する権限を所有しています。 これで、アプリケーションを動作させるコードを追加できるようになりました。
Great! Your app has permission to do the tasks you want it to do. Now you can add the code to make it work.
## 手順 2. イベント処理の追加
## Step 2. Add event handling
アプリケーションが最初にやらなければならないのは、オープンされた新しいIssueを待ち受けることです。 **Issue** イベントをサブスクライブしたので、特定の issue 関連のアクションが発生したときにトリガーされる [`issues`](/webhooks/event-payloads/#issues) Webhook の受信を開始します。 コード中にほしい特定のアクションに対してこのイベントの種類をフィルターできます。
The first thing your app needs to do is listen for new issues that are opened. Now that you've subscribed to the **Issues** event, you'll start receiving the [`issues`](/webhooks/event-payloads/#issues) webhook, which is triggered when certain issue-related actions occur. You can filter this event type for the specific action you want in your code.
GitHub は、Webhook ペイロードを `POST` 要求として送信します。 Smee Webhook ペイロードを `http://localhost/event_handler:3000` に転送したため、サーバーは `post '/event_handler'` ルートで `POST` 要求のペイロードを受信します。
GitHub sends webhook payloads as `POST` requests. Because you forwarded your Smee webhook payloads to `http://localhost/event_handler:3000`, your server will receive the `POST` request payloads in the `post '/event_handler'` route.
空の `post '/event_handler'` ルートは、「[前提条件](#prerequisites)」セクションでダウンロードした `template_server.rb` ファイルに既に含まれています。 空のルートは次のようになっています。
An empty `post '/event_handler'` route is already included in the `template_server.rb` file, which you downloaded in the [prerequisites](#prerequisites) section. The empty route looks like this:
``` ruby
post '/event_handler' do
@@ -113,7 +107,7 @@ GitHub は、Webhook ペイロードを `POST` 要求として送信します。
end
```
以下のコードを追加することで、このルートを使って `issues` イベントを処理します。
Use this route to handle the `issues` event by adding the following code:
``` ruby
case request.env['HTTP_X_GITHUB_EVENT']
@@ -124,9 +118,9 @@ when 'issues'
end
```
GitHub が送信する全てのイベントには、`HTTP_X_GITHUB_EVENT` という要求ヘッダーが含まれており、これは `POST` 要求でのイベントの種類を示します。 この時点では、関心があるのは`issues` というイベントの種類だけです。 各イベントには、イベントをトリガーしたアクションの種類を示す追加の `action` フィールドがあります。 `issues` の場合、`action` フィールドは `assigned``unassigned``labeled``unlabeled``opened``edited``milestoned``demilestoned``closed`、または `reopened` になります。
Every event that GitHub sends includes a request header called `HTTP_X_GITHUB_EVENT`, which indicates the type of event in the `POST` request. Right now, you're only interested in `issues` event types. Each event has an additional `action` field that indicates the type of action that triggered the events. For `issues`, the `action` field can be `assigned`, `unassigned`, `labeled`, `unlabeled`, `opened`, `edited`, `milestoned`, `demilestoned`, `closed`, or `reopened`.
イベントハンドラをテストするには、一時的なヘルパーメソッドを追加してみてください。 [後でラベル処理を追加](#step-4-add-label-handling)するときに更新します。 この時点では、コードの `helpers do` セクションの中に以下のコードを追加してください。 他の任意のヘルパーメソッドの前後に新しいメソッドを追加できます。 順序は問題ではありません。
To test your event handler, try adding a temporary helper method. You'll update later when you [Add label handling](#step-4-add-label-handling). For now, add the following code inside the `helpers do` section of the code. You can put the new method above or below any of the other helper methods. Order doesn't matter.
``` ruby
def handle_issue_opened_event(payload)
@@ -134,37 +128,37 @@ def handle_issue_opened_event(payload)
end
```
このメソッドはJSON形式のイベントペイロードを引数として受け取ります。 これは、メソッド中でペイロードをパースして、任意の必要なデータへとドリルダウンしていけるということです。 どこかの時点でペイロード全体を調べると役立つかもしれません。`logger.debug 'An issue was opened!` `logger.debug payload` に変更してみてください。 表示されるペイロード構造は、[`issues` Webhook イベント ドキュメントに表示されているもの](/webhooks/event-payloads/#issues)と一致している必要があります。
This method receives a JSON-formatted event payload as an argument. This means you can parse the payload in the method and drill down to any specific data you need. You may find it helpful to inspect the full payload at some point: try changing `logger.debug 'An issue was opened!` to `logger.debug payload`. The payload structure you see should match what's [shown in the `issues` webhook event docs](/webhooks/event-payloads/#issues).
すばらしい。 変更をテストしてみましょう。
Great! It's time to test the changes.
{% data reusables.apps.sinatra_restart_instructions %}
ブラウザで、アプリケーションをインストールしたリポジトリにアクセスしてください。 そのリポジトリで新しいIssueをオープンしてください。 そのIssueは好きな内容でかまいません。 これは単にテストにすぎません。
In your browser, visit the repository where you installed your app. Open a new issue in this repository. The issue can say anything you like. It's just for testing.
ターミナルを見直してみれば、`An issue was opened!` というメッセージが出力にあるはずです。おめでとうございます! アプリケーションにイベントハンドラを追加できました。 💪
When you look back at your Terminal, you should see a message in the output that says, `An issue was opened!` Congrats! You've added an event handler to your app. 💪
## 手順 3. 新しいラベルの作成
## Step 3. Create a new label
これで、アプリケーションはIssueがオープンされたときを示せるようになりました。 今度は、アプリケーションがインストールされたリポジトリの新しくオープンされた任意の issue に `needs-response` というラベルを追加しましょう。
Okay, your app can tell when issues are opened. Now you want it to add the label `needs-response` to any newly opened issue in a repository the app is installed in.
ラベルを任意の場所に _追加_ する前に、リポジトリにカスタム ラベルを _作成_ する必要があります。 これをする必要があるのは一度だけです。 このガイドのためには、ラベルをGitHub上で手動で作成します。 リポジトリで、 **[Issue]** 、 **[ラベル]** 、 **[新しいラベル]** の順にクリックします。 新しいラベルに `needs-response` という名前を付けます。
Before the label can be _added_ anywhere, you'll need to _create_ the custom label in your repository. You'll only need to do this one time. For the purposes of this guide, create the label manually on GitHub. In your repository, click **Issues**, then **Labels**, then click **New label**. Name the new label `needs-response`.
{% tip %}
**ヒント**: アプリでラベルをプログラムから作成できたら素晴らしいのではないでしょうか? [できます](/rest/reference/issues#create-a-label)。 このガイドのステップを終えた後に、自分でそのためのコードを追加してみてください。
**Tip**: Wouldn't it be great if your app could create the label programmatically? [It can](/rest/reference/issues#create-a-label)! Try adding the code to do that on your own after you finish the steps in this guide.
{% endtip %}
ラベルが存在するようになったので、REST API を使用して [新しくオープンした issue にラベルを追加するように](/rest/reference/issues#add-labels-to-an-issue)アプリをプログラミングできます。
Now that the label exists, you can program your app to use the REST API to [add the label to any newly opened issue](/rest/reference/issues#add-labels-to-an-issue).
## 手順 4. ラベルの処理の追加
## Step 4. Add label handling
おめでとうございます。最後のステップである、アプリケーションへのラベル処理の追加にまで来ました。 このタスクでは、[Octokit.rb Ruby ライブラリ](http://octokit.github.io/octokit.rb/)を使用します。
Congrats—you've made it to the final step: adding label handling to your app. For this task, you'll want to use the [Octokit.rb Ruby library](http://octokit.github.io/octokit.rb/).
Octokit.rb ドキュメントで、[ メソッド](http://octokit.github.io/octokit.rb/Octokit/Client/Labels.html)の一覧を見つけます。 使用するメソッドは [`add_labels_to_an_issue`](http://octokit.github.io/octokit.rb/Octokit/Client/Labels.html#add_labels_to_an_issue-instance_method) です。
In the Octokit.rb docs, find the list of [label methods](http://octokit.github.io/octokit.rb/Octokit/Client/Labels.html). The method you'll want to use is [`add_labels_to_an_issue`](http://octokit.github.io/octokit.rb/Octokit/Client/Labels.html#add_labels_to_an_issue-instance_method).
`template_server.rb` に戻って、前に定義したメソッドを見つけます。
Back in `template_server.rb`, find the method you defined previously:
``` ruby
def handle_issue_opened_event(payload)
@@ -172,13 +166,13 @@ def handle_issue_opened_event(payload)
end
```
[`add_labels_to_an_issue`](http://octokit.github.io/octokit.rb/Octokit/Client/Labels.html#add_labels_to_an_issue-instance_method) ドキュメントでは、このメソッドに 3 つの引数を渡す必要があることがわかります。
The [`add_labels_to_an_issue`](http://octokit.github.io/octokit.rb/Octokit/Client/Labels.html#add_labels_to_an_issue-instance_method) docs show you'll need to pass three arguments to this method:
* リポジトリ (`"owner/name"` 形式の文字列)
* Issue number(integer)
* Repo (string in `"owner/name"` format)
* Issue number (integer)
* Labels (array)
ペイロードをパースすれば、リポジトリとIssue番号を取得できます。 ラベル名は常に同じ (`needs-response`) なので、labels 配列にハードコードした文字列で渡せます。 これらのピースをまとめると、更新されたメソッドは以下のようになるでしょう。
You can parse the payload to get both the repo and the issue number. Since the label name will always be the same (`needs-response`), you can pass it as a hardcoded string in the labels array. Putting these pieces together, your updated method might look like this:
``` ruby
# When an issue is opened, add a label
@@ -189,56 +183,56 @@ def handle_issue_opened_event(payload)
end
```
新しいIssueをテストのリポジトリでオープンして、何が起こるか見てみてください! もしすぐには何も起こらなければ、リフレッシュしてみてください。
Try opening a new issue in your test repository and see what happens! If nothing happens right away, try refreshing.
ターミナルにはあまり表示されません __ 、ボット ユーザーが問題にラベルを追加していることがわかります。
You won't see much in the Terminal, _but_ you should see that a bot user has added a label to the issue.
{% note %}
**メモ:** GitHub Apps が API を介してラベルの追加などのアクションを実行すると、これらのアクションが _ボット_ アカウントによって実行されていると表示GitHub。 詳しくは、「[マシンアカウントとボット アカウント](/apps/differences-between-apps/#machine-vs-bot-accounts)」をご覧ください。
**Note:** When GitHub Apps take actions via the API, such as adding labels, GitHub shows these actions as being performed by _bot_ accounts. For more information, see "[Machine vs. bot accounts](/apps/differences-between-apps/#machine-vs-bot-accounts)."
{% endnote %}
そうなっていたら、おめでとうございます! 動作するアプリケーションの構築に成功しました! 🎉
If so, congrats! You've successfully built a working app! 🎉
最終的なコードは、`server.rb`アプリ テンプレート リポジトリ[](https://github.com/github-developer/using-the-github-api-in-your-app)確認できます。
You can see the final code in `server.rb` in the [app template repository](https://github.com/github-developer/using-the-github-api-in-your-app).
ここから移動できる場所に関するアイデアについては、「[次のステップ](#next-steps)」を参照してください。
See "[Next steps](#next-steps)" for ideas about where you can go from here.
## トラブルシューティング
## Troubleshooting
以下は、いくつかの一般的な問題と推奨される解決策です。 他の問題が生じた場合は、{% data variables.product.prodname_support_forum_with_url %}で助けやアドバイスを求めることができます。
Here are a few common problems and some suggested solutions. If you run into any other trouble, you can ask for help or advice in the {% data reusables.support.prodname_support_forum_with_url %}.
* **Q:** サーバーがイベントをリッスンしていません。 Smeeクライアントはターミナルウィンドウで動作していて、新しいIssueをオープンしてGitHub.com上でイベントを送信していますが、サーバーを動作させているターミナルウィンドウに出力がありません。
* **Q:** My server isn't listening to events! The Smee client is running in a Terminal window, and I'm sending events on GitHub.com by opening new issues, but I don't see any output in the Terminal window where I'm running the server.
**A:** アプリ設定の Smee ドメインが正しくないかもしれません。 [アプリ設定ページ](https://github.com/settings/apps)にアクセスし、「[新しいアプリを GitHub に登録する](/apps/quickstart-guides/setting-up-your-development-environment/#step-2-register-a-new-github-app)」に示されているフィールドを再確認します。 これらのフィールドのドメインが、「[新しい Smee チャンネルの開始](/apps/quickstart-guides/setting-up-your-development-environment/#step-1-start-a-new-smee-channel)」の `smee -u <unique_channel>` コマンドで使用したドメインと一致していることを確認します。
**A:** You may not have the correct Smee domain in your app settings. Visit your [app settings page](https://github.com/settings/apps) and double-check the fields shown in "[Register a new app with GitHub](/apps/quickstart-guides/setting-up-your-development-environment/#step-2-register-a-new-github-app)." Make sure the domain in those fields matches the domain you used in your `smee -u <unique_channel>` command in "[Start a new Smee channel](/apps/quickstart-guides/setting-up-your-development-environment/#step-1-start-a-new-smee-channel)."
* **Q:** アプリが機能しません。 新しいIssueをオープンしましたが、リフレッシュしてもラベルが追加されません。
* **Q:** My app doesn't work! I opened a new issue, but even after refreshing, no label has been added to it.
**A:** 次のすべてに該当することを確認してください。
**A:** Make sure all of the following are true:
* issue を開いているリポジトリに[アプリをインストールした](/apps/quickstart-guides/setting-up-your-development-environment/#step-7-install-the-app-on-your-account)
* [Smee クライアント](/apps/quickstart-guides/setting-up-your-development-environment/#step-1-start-a-new-smee-channel)がターミナル ウィンドウで実行されている。
* [Web サーバーが](/apps/quickstart-guides/setting-up-your-development-environment/#step-6-start-the-server)別のターミナル ウィンドウでエラーなしで実行されている。
* アプリには、[issue に対する読み取りおよび書き込みアクセス許可があり、issue イベントをサブスクライブしている](/apps/quickstart-guides/setting-up-your-development-environment/#step-1-start-a-new-smee-channel)
* アクセス許可を更新した後に[メールを確認](#step-1-update-app-permissions)し、新しいアクセス許可を受け入れた。
* You [installed the app](/apps/quickstart-guides/setting-up-your-development-environment/#step-7-install-the-app-on-your-account) on the repository where you're opening the issue.
* Your [Smee client is running](/apps/quickstart-guides/setting-up-your-development-environment/#step-1-start-a-new-smee-channel) in a Terminal window.
* Your [web server is running](/apps/quickstart-guides/setting-up-your-development-environment/#step-6-start-the-server) with no errors in another Terminal window.
* Your app has [read & write permissions on issues and is subscribed to issue events](/apps/quickstart-guides/setting-up-your-development-environment/#step-1-start-a-new-smee-channel).
* You [checked your email](#step-1-update-app-permissions) after updating the permissions and accepted the new permissions.
## まとめ
## Conclusion
このガイドを見終えれば、GitHub Appを開発するための基本的なビルディングブロックを学んだことになります! 振り返ると、以下を行いました。
After walking through this guide, you've learned the basic building blocks for developing GitHub Apps! To review, you:
* イベントを待ち受けるようにアプリケーションをプログラム
* Octokit.rbライブラリを使ったREST APIの操作
* Programmed your app to listen for events
* Used the Octokit.rb library to do REST API operations
## 次の手順
## Next steps
以下は、次に行えることのいくつかのアイデアです。
Here are some ideas for what you can do next:
* [GraphQL を使用してアプリを書き換える](https://developer.github.com/changes/2018-04-30-graphql-supports-github-apps/)
* [Probot](https://github.com/probot/probot) を使用して Node.js でアプリを書き換える。
* `needs-response` ラベルが issue に既にあるかをアプリで確認して、なければ追加する。
* ボットがラベルを追加できたら、ターミナルにメッセージを表示する。 (ヒント: メッセージの条件として `needs-response` ラベルの ID をペイロードのラベルの ID と比較し、他のラベルではなく関連するラベルが追加されたときにのみメッセージが表示されるようにします)
* ランディング ページをアプリに追加し、それに対する [Sinatra ルート](https://github.com/sinatra/sinatra#routes)を接続する。
* コードをホストされたサーバーHerokuのようなに移す。 新しいドメインでアプリケーションの設定を更新するのを忘れないようにしてください。
* {% data variables.product.prodname_support_forum_with_url %} でプロジェクトを共有したりアドバイスをもらったりする。{% ifversion fpt or ghec %}
* 他の人の役に立つかもと思うような、新しい輝くアプリケーションを構築しましたか? [GitHub Marketplace に追加する](/apps/marketplace/creating-and-submitting-your-app-for-approval/){% endif %}
* [Rewrite your app using GraphQL](https://developer.github.com/changes/2018-04-30-graphql-supports-github-apps/)!
* Rewrite your app in Node.js using [Probot](https://github.com/probot/probot)!
* Have the app check whether the `needs-response` label already exists on the issue, and if not, add it.
* When the bot successfully adds the label, show a message in the Terminal. (Hint: compare the `needs-response` label ID with the ID of the label in the payload as a condition for your message, so that the message only displays when the relevant label is added and not some other label.)
* Add a landing page to your app and hook up a [Sinatra route](https://github.com/sinatra/sinatra#routes) for it.
* Move your code to a hosted server (like Heroku). Don't forget to update your app settings with the new domain.
* Share your project or get advice in the {% data reusables.support.prodname_support_forum_with_url %}{% ifversion fpt or ghec %}
* Have you built a shiny new app you think others might find useful? [Add it to GitHub Marketplace](/apps/marketplace/creating-and-submitting-your-app-for-approval/)!{% endif %}

View File

@@ -317,6 +317,24 @@ Webhook events are triggered based on the specificity of the domain you register
{{ webhookPayloadsForCurrentVersion.delete }}
{% ifversion fpt or ghec %}
## dependabot_alert
{% data reusables.webhooks.dependabot_alert_description %}
### Availability
{% data reusables.webhooks.dependabot_alert_availability %}
### Webhook payload object
{% data reusables.webhooks.dependabot_alert_payload %}
### Webhook payload example
{{ webhookPayloadsForCurrentVersion.dependabot_alert.fixed }}
{% endif %}
## deploy_key
{% data reusables.webhooks.deploy_key_short_desc %}
@@ -1591,7 +1609,7 @@ This event occurs when someone triggers a workflow run on GitHub or sends a `POS
| Key | Type | Description |
|-----|-----|-----|
| `inputs` | `object` | Inputs to the workflow. Each key represents the name of the input while it's value represents the value of that input. |
| `inputs` | `object` | Inputs to the workflow. Each key represents the name of the input while its value represents the value of that input. |
{% data reusables.webhooks.org_desc %}
| `ref` | `string` | The branch ref from which the workflow was run. |
{% data reusables.webhooks.repo_desc %}

View File

@@ -1,15 +1,7 @@
---
ms.openlocfilehash: 01490f812c6a7b54293806a24023f25af2831d8e
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 09/05/2022
ms.locfileid: "147432081"
---
{% data variables.product.prodname_github_apps %}、{% data variables.product.prodname_oauth_apps %}、および API 開発に関する疑問、バグ レポート、議論については、{% data variables.product.prodname_support_forum_with_url %} を調べてください。 このディスカッションは {% data variables.product.company_short %} のスタッフによって進行および管理されていますが、フォーラムに投稿された質問に {% data variables.product.company_short %} のスタッフが必ずしも返答するとは限りません。
For questions, bug reports, and discussions about {% data variables.product.prodname_github_apps %}, {% data variables.product.prodname_oauth_apps %}, and API development, explore the {% data reusables.support.prodname_support_forum_with_url %}. The discussions are moderated and maintained by {% data variables.product.company_short %} staff, but questions posted to the forum are not guaranteed to receive a reply from {% data variables.product.company_short %} staff.
次の場合は、お問い合わせフォームを使用して [GitHub サポート](https://support.github.com/)に直接連絡することを検討してください。
- {% data variables.product.product_name %}のスタッフからの反応を確実に得たい場合
- センシティブなデータやプライベートな懸念事項に関わるサポートリクエスト
- 機能リクエスト
- {% data variables.product.product_name %}の製品に関するフィードバック
Consider reaching out to [GitHub Support](https://support.github.com/) directly using the contact form for:
- guaranteed response from {% data variables.product.product_name %} staff
- support requests involving sensitive data or private concerns
- feature requests
- feedback about {% data variables.product.product_name %} products

View File

@@ -1,9 +1,7 @@
---
ms.openlocfilehash: 004cf3f20495daaec9413026c03e5514211c906d
ms.sourcegitcommit: fb047f9450b41b24afc43d9512a5db2a2b750a2a
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 09/11/2022
ms.locfileid: "145069136"
---
リポジトリ内のセキュリティ脆弱性アラートに関連するアクティビティ。 {% data reusables.webhooks.action_type_desc %} 詳細については、「[{% data variables.product.prodname_dependabot_alerts %} について](/github/managing-security-vulnerabilities/about-alerts-for-vulnerable-dependencies/)」を参照してください。
{% warning %}
**Deprecation note**: The `repository_vulnerability_alert` webhook events described below are deprecated and are documented here for reference only. Use [`dependabot_alert`](#dependabot_alert) as an alternative.
{% endwarning %}
Activity related to security vulnerability alerts in a repository. {% data reusables.webhooks.action_type_desc %} For more information, see the "[About {% data variables.product.prodname_dependabot_alerts %}](/github/managing-security-vulnerabilities/about-alerts-for-vulnerable-dependencies/)".

View File

@@ -256,6 +256,7 @@ translations/es-ES/content/account-and-profile/managing-subscriptions-and-notifi
translations/es-ES/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/about-your-organizations-profile.md,rendering error
translations/es-ES/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/managing-your-profile-readme.md,broken liquid tags
translations/es-ES/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/setting-your-profile-to-private.md,broken liquid tags
translations/es-ES/content/account-and-profile/setting-up-and-managing-your-github-profile/managing-contribution-settings-on-your-profile/showing-your-private-contributions-and-achievements-on-your-profile.md,broken liquid tags
translations/es-ES/content/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-access-to-your-personal-repositories/inviting-collaborators-to-a-personal-repository.md,rendering error
translations/es-ES/content/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-access-to-your-personal-repositories/removing-a-collaborator-from-a-personal-repository.md,rendering error
translations/es-ES/content/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-access-to-your-personal-repositories/removing-yourself-from-a-collaborators-repository.md,rendering error
@@ -317,8 +318,8 @@ translations/es-ES/content/admin/policies/enforcing-policies-for-your-enterprise
translations/es-ES/content/admin/policies/enforcing-policies-for-your-enterprise/enforcing-policies-for-security-settings-in-your-enterprise.md,rendering error
translations/es-ES/content/admin/policies/enforcing-policies-for-your-enterprise/enforcing-repository-management-policies-in-your-enterprise.md,broken liquid tags
translations/es-ES/content/admin/user-management/managing-users-in-your-enterprise/viewing-people-in-your-enterprise.md,rendering error
translations/es-ES/content/authentication/authenticating-with-saml-single-sign-on/authorizing-a-personal-access-token-for-use-with-saml-single-sign-on.md,broken liquid tags
translations/es-ES/content/authentication/authenticating-with-saml-single-sign-on/authorizing-an-ssh-key-for-use-with-saml-single-sign-on.md,broken liquid tags
translations/es-ES/content/authentication/authenticating-with-saml-single-sign-on/authorizing-a-personal-access-token-for-use-with-saml-single-sign-on.md,rendering error
translations/es-ES/content/authentication/authenticating-with-saml-single-sign-on/authorizing-an-ssh-key-for-use-with-saml-single-sign-on.md,rendering error
translations/es-ES/content/authentication/connecting-to-github-with-ssh/about-ssh.md,broken liquid tags
translations/es-ES/content/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account.md,rendering error
translations/es-ES/content/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent.md,rendering error
@@ -368,16 +369,17 @@ translations/es-ES/content/code-security/getting-started/github-security-feature
translations/es-ES/content/code-security/getting-started/securing-your-repository.md,rendering error
translations/es-ES/content/code-security/repository-security-advisories/about-coordinated-disclosure-of-security-vulnerabilities.md,rendering error
translations/es-ES/content/code-security/secret-scanning/about-secret-scanning.md,rendering error
translations/es-ES/content/code-security/secret-scanning/configuring-secret-scanning-for-your-repositories.md,broken liquid tags
translations/es-ES/content/code-security/secret-scanning/defining-custom-patterns-for-secret-scanning.md,rendering error
translations/es-ES/content/code-security/secret-scanning/managing-alerts-from-secret-scanning.md,rendering error
translations/es-ES/content/code-security/security-overview/about-the-security-overview.md,rendering error
translations/es-ES/content/code-security/security-overview/filtering-alerts-in-the-security-overview.md,broken liquid tags
translations/es-ES/content/code-security/security-overview/filtering-alerts-in-the-security-overview.md,rendering error
translations/es-ES/content/code-security/security-overview/viewing-the-security-overview.md,rendering error
translations/es-ES/content/code-security/supply-chain-security/end-to-end-supply-chain/securing-code.md,rendering error
translations/es-ES/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review.md,rendering error
translations/es-ES/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-supply-chain-security.md,rendering error
translations/es-ES/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-the-dependency-graph.md,rendering error
translations/es-ES/content/code-security/supply-chain-security/understanding-your-software-supply-chain/configuring-dependency-review.md,broken liquid tags
translations/es-ES/content/code-security/supply-chain-security/understanding-your-software-supply-chain/configuring-dependency-review.md,rendering error
translations/es-ES/content/codespaces/codespaces-reference/allowing-your-codespace-to-access-a-private-image-registry.md,broken liquid tags
translations/es-ES/content/codespaces/codespaces-reference/disaster-recovery-for-github-codespaces.md,broken liquid tags
translations/es-ES/content/codespaces/codespaces-reference/security-in-github-codespaces.md,broken liquid tags
@@ -439,8 +441,12 @@ translations/es-ES/content/copilot/getting-started-with-github-copilot/getting-s
translations/es-ES/content/copilot/quickstart.md,broken liquid tags
translations/es-ES/content/desktop/contributing-and-collaborating-using-github-desktop/making-changes-in-a-branch/index.md,broken liquid tags
translations/es-ES/content/developers/apps/getting-started-with-apps/differences-between-github-apps-and-oauth-apps.md,broken liquid tags
translations/es-ES/content/developers/apps/getting-started-with-apps/setting-up-your-development-environment-to-create-a-github-app.md,broken liquid tags
translations/es-ES/content/developers/apps/guides/creating-ci-tests-with-the-checks-api.md,broken liquid tags
translations/es-ES/content/developers/apps/guides/using-the-github-api-in-your-app.md,broken liquid tags
translations/es-ES/content/developers/overview/about-githubs-apis.md,broken liquid tags
translations/es-ES/content/developers/overview/managing-deploy-keys.md,broken liquid tags
translations/es-ES/content/developers/webhooks-and-events/events/issue-event-types.md,broken liquid tags
translations/es-ES/content/developers/webhooks-and-events/webhooks/webhook-events-and-payloads.md,rendering error
translations/es-ES/content/discussions/collaborating-with-your-community-using-discussions/collaborating-with-maintainers-using-discussions.md,broken liquid tags
translations/es-ES/content/discussions/collaborating-with-your-community-using-discussions/participating-in-a-discussion.md,broken liquid tags
@@ -460,7 +466,7 @@ translations/es-ES/content/get-started/writing-on-github/getting-started-with-wr
translations/es-ES/content/get-started/writing-on-github/working-with-advanced-formatting/attaching-files.md,broken liquid tags
translations/es-ES/content/get-started/writing-on-github/working-with-advanced-formatting/writing-mathematical-expressions.md,rendering error
translations/es-ES/content/graphql/guides/migrating-from-rest-to-graphql.md,broken liquid tags
translations/es-ES/content/graphql/overview/about-the-graphql-api.md,broken liquid tags
translations/es-ES/content/graphql/overview/about-the-graphql-api.md,rendering error
translations/es-ES/content/issues/planning-and-tracking-with-projects/automating-your-project/using-the-api-to-manage-projects.md,broken liquid tags
translations/es-ES/content/issues/planning-and-tracking-with-projects/managing-your-project/managing-access-to-your-projects.md,broken liquid tags
translations/es-ES/content/issues/tracking-your-work-with-issues/filtering-and-searching-issues-and-pull-requests.md,rendering error
@@ -653,6 +659,7 @@ translations/es-ES/data/reusables/secret-scanning/partner-secret-list-private-re
translations/es-ES/data/reusables/secret-scanning/secret-list-private-push-protection.md,rendering error
translations/es-ES/data/reusables/security-overview/permissions.md,rendering error
translations/es-ES/data/reusables/sponsors/feedback.md,broken liquid tags
translations/es-ES/data/reusables/support/help_resources.md,broken liquid tags
translations/es-ES/data/reusables/user-settings/access_applications.md,rendering error
translations/es-ES/data/reusables/user-settings/account_settings.md,rendering error
translations/es-ES/data/reusables/user-settings/appearance-settings.md,rendering error
@@ -666,4 +673,5 @@ translations/es-ES/data/reusables/user-settings/security.md,rendering error
translations/es-ES/data/reusables/user-settings/ssh.md,rendering error
translations/es-ES/data/reusables/webhooks/pull_request_properties.md,broken liquid tags
translations/es-ES/data/reusables/webhooks/pull_request_webhook_properties.md,broken liquid tags
translations/es-ES/data/reusables/webhooks/repository_vulnerability_alert_short_desc.md,broken liquid tags
translations/es-ES/data/reusables/webhooks/workflow_run_properties.md,broken liquid tags
1 file reason
256 translations/es-ES/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/about-your-organizations-profile.md rendering error
257 translations/es-ES/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/managing-your-profile-readme.md broken liquid tags
258 translations/es-ES/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/setting-your-profile-to-private.md broken liquid tags
259 translations/es-ES/content/account-and-profile/setting-up-and-managing-your-github-profile/managing-contribution-settings-on-your-profile/showing-your-private-contributions-and-achievements-on-your-profile.md broken liquid tags
260 translations/es-ES/content/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-access-to-your-personal-repositories/inviting-collaborators-to-a-personal-repository.md rendering error
261 translations/es-ES/content/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-access-to-your-personal-repositories/removing-a-collaborator-from-a-personal-repository.md rendering error
262 translations/es-ES/content/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-access-to-your-personal-repositories/removing-yourself-from-a-collaborators-repository.md rendering error
318 translations/es-ES/content/admin/policies/enforcing-policies-for-your-enterprise/enforcing-policies-for-security-settings-in-your-enterprise.md rendering error
319 translations/es-ES/content/admin/policies/enforcing-policies-for-your-enterprise/enforcing-repository-management-policies-in-your-enterprise.md broken liquid tags
320 translations/es-ES/content/admin/user-management/managing-users-in-your-enterprise/viewing-people-in-your-enterprise.md rendering error
321 translations/es-ES/content/authentication/authenticating-with-saml-single-sign-on/authorizing-a-personal-access-token-for-use-with-saml-single-sign-on.md broken liquid tags rendering error
322 translations/es-ES/content/authentication/authenticating-with-saml-single-sign-on/authorizing-an-ssh-key-for-use-with-saml-single-sign-on.md broken liquid tags rendering error
323 translations/es-ES/content/authentication/connecting-to-github-with-ssh/about-ssh.md broken liquid tags
324 translations/es-ES/content/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account.md rendering error
325 translations/es-ES/content/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent.md rendering error
369 translations/es-ES/content/code-security/getting-started/securing-your-repository.md rendering error
370 translations/es-ES/content/code-security/repository-security-advisories/about-coordinated-disclosure-of-security-vulnerabilities.md rendering error
371 translations/es-ES/content/code-security/secret-scanning/about-secret-scanning.md rendering error
372 translations/es-ES/content/code-security/secret-scanning/configuring-secret-scanning-for-your-repositories.md broken liquid tags
373 translations/es-ES/content/code-security/secret-scanning/defining-custom-patterns-for-secret-scanning.md rendering error
374 translations/es-ES/content/code-security/secret-scanning/managing-alerts-from-secret-scanning.md rendering error
375 translations/es-ES/content/code-security/security-overview/about-the-security-overview.md rendering error
376 translations/es-ES/content/code-security/security-overview/filtering-alerts-in-the-security-overview.md broken liquid tags rendering error
377 translations/es-ES/content/code-security/security-overview/viewing-the-security-overview.md rendering error
378 translations/es-ES/content/code-security/supply-chain-security/end-to-end-supply-chain/securing-code.md rendering error
379 translations/es-ES/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review.md rendering error
380 translations/es-ES/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-supply-chain-security.md rendering error
381 translations/es-ES/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-the-dependency-graph.md rendering error
382 translations/es-ES/content/code-security/supply-chain-security/understanding-your-software-supply-chain/configuring-dependency-review.md broken liquid tags rendering error
383 translations/es-ES/content/codespaces/codespaces-reference/allowing-your-codespace-to-access-a-private-image-registry.md broken liquid tags
384 translations/es-ES/content/codespaces/codespaces-reference/disaster-recovery-for-github-codespaces.md broken liquid tags
385 translations/es-ES/content/codespaces/codespaces-reference/security-in-github-codespaces.md broken liquid tags
441 translations/es-ES/content/copilot/quickstart.md broken liquid tags
442 translations/es-ES/content/desktop/contributing-and-collaborating-using-github-desktop/making-changes-in-a-branch/index.md broken liquid tags
443 translations/es-ES/content/developers/apps/getting-started-with-apps/differences-between-github-apps-and-oauth-apps.md broken liquid tags
444 translations/es-ES/content/developers/apps/getting-started-with-apps/setting-up-your-development-environment-to-create-a-github-app.md broken liquid tags
445 translations/es-ES/content/developers/apps/guides/creating-ci-tests-with-the-checks-api.md broken liquid tags
446 translations/es-ES/content/developers/apps/guides/using-the-github-api-in-your-app.md broken liquid tags
447 translations/es-ES/content/developers/overview/about-githubs-apis.md broken liquid tags
448 translations/es-ES/content/developers/overview/managing-deploy-keys.md broken liquid tags
449 translations/es-ES/content/developers/webhooks-and-events/events/issue-event-types.md broken liquid tags
450 translations/es-ES/content/developers/webhooks-and-events/webhooks/webhook-events-and-payloads.md rendering error
451 translations/es-ES/content/discussions/collaborating-with-your-community-using-discussions/collaborating-with-maintainers-using-discussions.md broken liquid tags
452 translations/es-ES/content/discussions/collaborating-with-your-community-using-discussions/participating-in-a-discussion.md broken liquid tags
466 translations/es-ES/content/get-started/writing-on-github/working-with-advanced-formatting/attaching-files.md broken liquid tags
467 translations/es-ES/content/get-started/writing-on-github/working-with-advanced-formatting/writing-mathematical-expressions.md rendering error
468 translations/es-ES/content/graphql/guides/migrating-from-rest-to-graphql.md broken liquid tags
469 translations/es-ES/content/graphql/overview/about-the-graphql-api.md broken liquid tags rendering error
470 translations/es-ES/content/issues/planning-and-tracking-with-projects/automating-your-project/using-the-api-to-manage-projects.md broken liquid tags
471 translations/es-ES/content/issues/planning-and-tracking-with-projects/managing-your-project/managing-access-to-your-projects.md broken liquid tags
472 translations/es-ES/content/issues/tracking-your-work-with-issues/filtering-and-searching-issues-and-pull-requests.md rendering error
659 translations/es-ES/data/reusables/secret-scanning/secret-list-private-push-protection.md rendering error
660 translations/es-ES/data/reusables/security-overview/permissions.md rendering error
661 translations/es-ES/data/reusables/sponsors/feedback.md broken liquid tags
662 translations/es-ES/data/reusables/support/help_resources.md broken liquid tags
663 translations/es-ES/data/reusables/user-settings/access_applications.md rendering error
664 translations/es-ES/data/reusables/user-settings/account_settings.md rendering error
665 translations/es-ES/data/reusables/user-settings/appearance-settings.md rendering error
673 translations/es-ES/data/reusables/user-settings/ssh.md rendering error
674 translations/es-ES/data/reusables/webhooks/pull_request_properties.md broken liquid tags
675 translations/es-ES/data/reusables/webhooks/pull_request_webhook_properties.md broken liquid tags
676 translations/es-ES/data/reusables/webhooks/repository_vulnerability_alert_short_desc.md broken liquid tags
677 translations/es-ES/data/reusables/webhooks/workflow_run_properties.md broken liquid tags

View File

@@ -252,6 +252,7 @@ translations/ja-JP/content/account-and-profile/managing-subscriptions-and-notifi
translations/ja-JP/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/about-your-organizations-profile.md,rendering error
translations/ja-JP/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/managing-your-profile-readme.md,broken liquid tags
translations/ja-JP/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/setting-your-profile-to-private.md,broken liquid tags
translations/ja-JP/content/account-and-profile/setting-up-and-managing-your-github-profile/managing-contribution-settings-on-your-profile/showing-your-private-contributions-and-achievements-on-your-profile.md,broken liquid tags
translations/ja-JP/content/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-access-to-your-personal-repositories/inviting-collaborators-to-a-personal-repository.md,rendering error
translations/ja-JP/content/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-access-to-your-personal-repositories/removing-a-collaborator-from-a-personal-repository.md,rendering error
translations/ja-JP/content/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-access-to-your-personal-repositories/removing-yourself-from-a-collaborators-repository.md,rendering error
@@ -316,11 +317,12 @@ translations/ja-JP/content/admin/policies/enforcing-policies-for-your-enterprise
translations/ja-JP/content/admin/policies/enforcing-policies-for-your-enterprise/enforcing-policies-for-security-settings-in-your-enterprise.md,rendering error
translations/ja-JP/content/admin/policies/enforcing-policies-for-your-enterprise/enforcing-repository-management-policies-in-your-enterprise.md,broken liquid tags
translations/ja-JP/content/admin/user-management/managing-users-in-your-enterprise/viewing-people-in-your-enterprise.md,rendering error
translations/ja-JP/content/authentication/authenticating-with-saml-single-sign-on/authorizing-a-personal-access-token-for-use-with-saml-single-sign-on.md,broken liquid tags
translations/ja-JP/content/authentication/authenticating-with-saml-single-sign-on/authorizing-an-ssh-key-for-use-with-saml-single-sign-on.md,broken liquid tags
translations/ja-JP/content/authentication/authenticating-with-saml-single-sign-on/authorizing-a-personal-access-token-for-use-with-saml-single-sign-on.md,rendering error
translations/ja-JP/content/authentication/authenticating-with-saml-single-sign-on/authorizing-an-ssh-key-for-use-with-saml-single-sign-on.md,rendering error
translations/ja-JP/content/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent.md,rendering error
translations/ja-JP/content/authentication/keeping-your-account-and-data-secure/reviewing-your-deploy-keys.md,rendering error
translations/ja-JP/content/authentication/keeping-your-account-and-data-secure/reviewing-your-security-log.md,rendering error
translations/ja-JP/content/authentication/managing-commit-signature-verification/telling-git-about-your-signing-key.md,broken liquid tags
translations/ja-JP/content/billing/managing-billing-for-github-actions/about-billing-for-github-actions.md,broken liquid tags
translations/ja-JP/content/billing/managing-billing-for-github-advanced-security/about-billing-for-github-advanced-security.md,broken liquid tags
translations/ja-JP/content/billing/managing-billing-for-github-advanced-security/viewing-your-github-advanced-security-usage.md,rendering error
@@ -360,16 +362,17 @@ translations/ja-JP/content/code-security/getting-started/github-security-feature
translations/ja-JP/content/code-security/getting-started/securing-your-organization.md,rendering error
translations/ja-JP/content/code-security/getting-started/securing-your-repository.md,rendering error
translations/ja-JP/content/code-security/secret-scanning/about-secret-scanning.md,rendering error
translations/ja-JP/content/code-security/secret-scanning/configuring-secret-scanning-for-your-repositories.md,broken liquid tags
translations/ja-JP/content/code-security/secret-scanning/defining-custom-patterns-for-secret-scanning.md,rendering error
translations/ja-JP/content/code-security/secret-scanning/managing-alerts-from-secret-scanning.md,rendering error
translations/ja-JP/content/code-security/security-overview/about-the-security-overview.md,rendering error
translations/ja-JP/content/code-security/security-overview/filtering-alerts-in-the-security-overview.md,broken liquid tags
translations/ja-JP/content/code-security/security-overview/filtering-alerts-in-the-security-overview.md,rendering error
translations/ja-JP/content/code-security/security-overview/viewing-the-security-overview.md,rendering error
translations/ja-JP/content/code-security/supply-chain-security/end-to-end-supply-chain/securing-code.md,rendering error
translations/ja-JP/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review.md,rendering error
translations/ja-JP/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-supply-chain-security.md,rendering error
translations/ja-JP/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-the-dependency-graph.md,rendering error
translations/ja-JP/content/code-security/supply-chain-security/understanding-your-software-supply-chain/configuring-dependency-review.md,broken liquid tags
translations/ja-JP/content/code-security/supply-chain-security/understanding-your-software-supply-chain/configuring-dependency-review.md,rendering error
translations/ja-JP/content/codespaces/codespaces-reference/allowing-your-codespace-to-access-a-private-image-registry.md,broken liquid tags
translations/ja-JP/content/codespaces/codespaces-reference/disaster-recovery-for-github-codespaces.md,broken liquid tags
translations/ja-JP/content/codespaces/codespaces-reference/security-in-github-codespaces.md,broken liquid tags
@@ -429,8 +432,12 @@ translations/ja-JP/content/copilot/quickstart.md,broken liquid tags
translations/ja-JP/content/desktop/contributing-and-collaborating-using-github-desktop/making-changes-in-a-branch/index.md,broken liquid tags
translations/ja-JP/content/desktop/installing-and-configuring-github-desktop/installing-and-authenticating-to-github-desktop/authenticating-to-github.md,rendering error
translations/ja-JP/content/developers/apps/getting-started-with-apps/differences-between-github-apps-and-oauth-apps.md,broken liquid tags
translations/ja-JP/content/developers/apps/getting-started-with-apps/setting-up-your-development-environment-to-create-a-github-app.md,broken liquid tags
translations/ja-JP/content/developers/apps/guides/creating-ci-tests-with-the-checks-api.md,broken liquid tags
translations/ja-JP/content/developers/apps/guides/using-the-github-api-in-your-app.md,broken liquid tags
translations/ja-JP/content/developers/overview/about-githubs-apis.md,broken liquid tags
translations/ja-JP/content/developers/overview/managing-deploy-keys.md,broken liquid tags
translations/ja-JP/content/developers/webhooks-and-events/events/issue-event-types.md,broken liquid tags
translations/ja-JP/content/developers/webhooks-and-events/webhooks/webhook-events-and-payloads.md,rendering error
translations/ja-JP/content/discussions/collaborating-with-your-community-using-discussions/collaborating-with-maintainers-using-discussions.md,broken liquid tags
translations/ja-JP/content/discussions/collaborating-with-your-community-using-discussions/participating-in-a-discussion.md,broken liquid tags
@@ -450,7 +457,7 @@ translations/ja-JP/content/get-started/writing-on-github/getting-started-with-wr
translations/ja-JP/content/get-started/writing-on-github/working-with-advanced-formatting/attaching-files.md,broken liquid tags
translations/ja-JP/content/get-started/writing-on-github/working-with-advanced-formatting/writing-mathematical-expressions.md,rendering error
translations/ja-JP/content/graphql/guides/migrating-from-rest-to-graphql.md,broken liquid tags
translations/ja-JP/content/graphql/overview/about-the-graphql-api.md,broken liquid tags
translations/ja-JP/content/graphql/overview/about-the-graphql-api.md,rendering error
translations/ja-JP/content/issues/planning-and-tracking-with-projects/automating-your-project/using-the-api-to-manage-projects.md,broken liquid tags
translations/ja-JP/content/issues/planning-and-tracking-with-projects/managing-your-project/managing-access-to-your-projects.md,broken liquid tags
translations/ja-JP/content/issues/tracking-your-work-with-issues/filtering-and-searching-issues-and-pull-requests.md,rendering error
@@ -644,6 +651,7 @@ translations/ja-JP/data/reusables/search/syntax_tips.md,broken liquid tags
translations/ja-JP/data/reusables/secret-scanning/partner-secret-list-private-repo.md,rendering error
translations/ja-JP/data/reusables/secret-scanning/secret-list-private-push-protection.md,rendering error
translations/ja-JP/data/reusables/security-overview/permissions.md,rendering error
translations/ja-JP/data/reusables/support/help_resources.md,broken liquid tags
translations/ja-JP/data/reusables/user-settings/access_applications.md,rendering error
translations/ja-JP/data/reusables/user-settings/account_settings.md,rendering error
translations/ja-JP/data/reusables/user-settings/appearance-settings.md,rendering error
@@ -657,4 +665,5 @@ translations/ja-JP/data/reusables/user-settings/security.md,rendering error
translations/ja-JP/data/reusables/user-settings/ssh.md,rendering error
translations/ja-JP/data/reusables/webhooks/pull_request_properties.md,broken liquid tags
translations/ja-JP/data/reusables/webhooks/pull_request_webhook_properties.md,broken liquid tags
translations/ja-JP/data/reusables/webhooks/repository_vulnerability_alert_short_desc.md,broken liquid tags
translations/ja-JP/data/reusables/webhooks/workflow_run_properties.md,broken liquid tags
1 file reason
252 translations/ja-JP/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/about-your-organizations-profile.md rendering error
253 translations/ja-JP/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/managing-your-profile-readme.md broken liquid tags
254 translations/ja-JP/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/setting-your-profile-to-private.md broken liquid tags
255 translations/ja-JP/content/account-and-profile/setting-up-and-managing-your-github-profile/managing-contribution-settings-on-your-profile/showing-your-private-contributions-and-achievements-on-your-profile.md broken liquid tags
256 translations/ja-JP/content/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-access-to-your-personal-repositories/inviting-collaborators-to-a-personal-repository.md rendering error
257 translations/ja-JP/content/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-access-to-your-personal-repositories/removing-a-collaborator-from-a-personal-repository.md rendering error
258 translations/ja-JP/content/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-access-to-your-personal-repositories/removing-yourself-from-a-collaborators-repository.md rendering error
317 translations/ja-JP/content/admin/policies/enforcing-policies-for-your-enterprise/enforcing-policies-for-security-settings-in-your-enterprise.md rendering error
318 translations/ja-JP/content/admin/policies/enforcing-policies-for-your-enterprise/enforcing-repository-management-policies-in-your-enterprise.md broken liquid tags
319 translations/ja-JP/content/admin/user-management/managing-users-in-your-enterprise/viewing-people-in-your-enterprise.md rendering error
320 translations/ja-JP/content/authentication/authenticating-with-saml-single-sign-on/authorizing-a-personal-access-token-for-use-with-saml-single-sign-on.md broken liquid tags rendering error
321 translations/ja-JP/content/authentication/authenticating-with-saml-single-sign-on/authorizing-an-ssh-key-for-use-with-saml-single-sign-on.md broken liquid tags rendering error
322 translations/ja-JP/content/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent.md rendering error
323 translations/ja-JP/content/authentication/keeping-your-account-and-data-secure/reviewing-your-deploy-keys.md rendering error
324 translations/ja-JP/content/authentication/keeping-your-account-and-data-secure/reviewing-your-security-log.md rendering error
325 translations/ja-JP/content/authentication/managing-commit-signature-verification/telling-git-about-your-signing-key.md broken liquid tags
326 translations/ja-JP/content/billing/managing-billing-for-github-actions/about-billing-for-github-actions.md broken liquid tags
327 translations/ja-JP/content/billing/managing-billing-for-github-advanced-security/about-billing-for-github-advanced-security.md broken liquid tags
328 translations/ja-JP/content/billing/managing-billing-for-github-advanced-security/viewing-your-github-advanced-security-usage.md rendering error
362 translations/ja-JP/content/code-security/getting-started/securing-your-organization.md rendering error
363 translations/ja-JP/content/code-security/getting-started/securing-your-repository.md rendering error
364 translations/ja-JP/content/code-security/secret-scanning/about-secret-scanning.md rendering error
365 translations/ja-JP/content/code-security/secret-scanning/configuring-secret-scanning-for-your-repositories.md broken liquid tags
366 translations/ja-JP/content/code-security/secret-scanning/defining-custom-patterns-for-secret-scanning.md rendering error
367 translations/ja-JP/content/code-security/secret-scanning/managing-alerts-from-secret-scanning.md rendering error
368 translations/ja-JP/content/code-security/security-overview/about-the-security-overview.md rendering error
369 translations/ja-JP/content/code-security/security-overview/filtering-alerts-in-the-security-overview.md broken liquid tags rendering error
370 translations/ja-JP/content/code-security/security-overview/viewing-the-security-overview.md rendering error
371 translations/ja-JP/content/code-security/supply-chain-security/end-to-end-supply-chain/securing-code.md rendering error
372 translations/ja-JP/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review.md rendering error
373 translations/ja-JP/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-supply-chain-security.md rendering error
374 translations/ja-JP/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-the-dependency-graph.md rendering error
375 translations/ja-JP/content/code-security/supply-chain-security/understanding-your-software-supply-chain/configuring-dependency-review.md broken liquid tags rendering error
376 translations/ja-JP/content/codespaces/codespaces-reference/allowing-your-codespace-to-access-a-private-image-registry.md broken liquid tags
377 translations/ja-JP/content/codespaces/codespaces-reference/disaster-recovery-for-github-codespaces.md broken liquid tags
378 translations/ja-JP/content/codespaces/codespaces-reference/security-in-github-codespaces.md broken liquid tags
432 translations/ja-JP/content/desktop/contributing-and-collaborating-using-github-desktop/making-changes-in-a-branch/index.md broken liquid tags
433 translations/ja-JP/content/desktop/installing-and-configuring-github-desktop/installing-and-authenticating-to-github-desktop/authenticating-to-github.md rendering error
434 translations/ja-JP/content/developers/apps/getting-started-with-apps/differences-between-github-apps-and-oauth-apps.md broken liquid tags
435 translations/ja-JP/content/developers/apps/getting-started-with-apps/setting-up-your-development-environment-to-create-a-github-app.md broken liquid tags
436 translations/ja-JP/content/developers/apps/guides/creating-ci-tests-with-the-checks-api.md broken liquid tags
437 translations/ja-JP/content/developers/apps/guides/using-the-github-api-in-your-app.md broken liquid tags
438 translations/ja-JP/content/developers/overview/about-githubs-apis.md broken liquid tags
439 translations/ja-JP/content/developers/overview/managing-deploy-keys.md broken liquid tags
440 translations/ja-JP/content/developers/webhooks-and-events/events/issue-event-types.md broken liquid tags
441 translations/ja-JP/content/developers/webhooks-and-events/webhooks/webhook-events-and-payloads.md rendering error
442 translations/ja-JP/content/discussions/collaborating-with-your-community-using-discussions/collaborating-with-maintainers-using-discussions.md broken liquid tags
443 translations/ja-JP/content/discussions/collaborating-with-your-community-using-discussions/participating-in-a-discussion.md broken liquid tags
457 translations/ja-JP/content/get-started/writing-on-github/working-with-advanced-formatting/attaching-files.md broken liquid tags
458 translations/ja-JP/content/get-started/writing-on-github/working-with-advanced-formatting/writing-mathematical-expressions.md rendering error
459 translations/ja-JP/content/graphql/guides/migrating-from-rest-to-graphql.md broken liquid tags
460 translations/ja-JP/content/graphql/overview/about-the-graphql-api.md broken liquid tags rendering error
461 translations/ja-JP/content/issues/planning-and-tracking-with-projects/automating-your-project/using-the-api-to-manage-projects.md broken liquid tags
462 translations/ja-JP/content/issues/planning-and-tracking-with-projects/managing-your-project/managing-access-to-your-projects.md broken liquid tags
463 translations/ja-JP/content/issues/tracking-your-work-with-issues/filtering-and-searching-issues-and-pull-requests.md rendering error
651 translations/ja-JP/data/reusables/secret-scanning/partner-secret-list-private-repo.md rendering error
652 translations/ja-JP/data/reusables/secret-scanning/secret-list-private-push-protection.md rendering error
653 translations/ja-JP/data/reusables/security-overview/permissions.md rendering error
654 translations/ja-JP/data/reusables/support/help_resources.md broken liquid tags
655 translations/ja-JP/data/reusables/user-settings/access_applications.md rendering error
656 translations/ja-JP/data/reusables/user-settings/account_settings.md rendering error
657 translations/ja-JP/data/reusables/user-settings/appearance-settings.md rendering error
665 translations/ja-JP/data/reusables/user-settings/ssh.md rendering error
666 translations/ja-JP/data/reusables/webhooks/pull_request_properties.md broken liquid tags
667 translations/ja-JP/data/reusables/webhooks/pull_request_webhook_properties.md broken liquid tags
668 translations/ja-JP/data/reusables/webhooks/repository_vulnerability_alert_short_desc.md broken liquid tags
669 translations/ja-JP/data/reusables/webhooks/workflow_run_properties.md broken liquid tags