зеркало из https://github.com/github/docs.git
New translation batch for pt (#31553)
This commit is contained in:
Родитель
4f86ab71b4
Коммит
0a927e14cb
|
@ -64,6 +64,7 @@ translations/pt-BR/content/admin/identity-and-access-management/using-enterprise
|
|||
translations/pt-BR/content/admin/identity-and-access-management/using-enterprise-managed-users-and-saml-for-iam/configuring-scim-provisioning-for-enterprise-managed-users.md,file deleted because it no longer exists in main
|
||||
translations/pt-BR/content/admin/identity-and-access-management/using-enterprise-managed-users-and-saml-for-iam/index.md,file deleted because it no longer exists in main
|
||||
translations/pt-BR/content/admin/identity-and-access-management/using-enterprise-managed-users-and-saml-for-iam/managing-team-memberships-with-identity-provider-groups.md,file deleted because it no longer exists in main
|
||||
translations/pt-BR/content/admin/policies/enforcing-policies-for-your-enterprise/enforcing-policies-for-advanced-security-in-your-enterprise.md,file deleted because it no longer exists in main
|
||||
translations/pt-BR/content/admin/policies/enforcing-policies-for-your-enterprise/enforcing-project-board-policies-in-your-enterprise.md,file deleted because it no longer exists in main
|
||||
translations/pt-BR/content/admin/user-management/managing-organizations-in-your-enterprise/managing-unowned-organizations-in-your-enterprise.md,file deleted because it no longer exists in main
|
||||
translations/pt-BR/content/authentication/managing-commit-signature-verification/adding-a-new-gpg-key-to-your-github-account.md,file deleted because it no longer exists in main
|
||||
|
@ -240,6 +241,7 @@ translations/pt-BR/content/account-and-profile/managing-subscriptions-and-notifi
|
|||
translations/pt-BR/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/about-your-organizations-profile.md,rendering error
|
||||
translations/pt-BR/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/managing-your-profile-readme.md,broken liquid tags
|
||||
translations/pt-BR/content/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/setting-your-profile-to-private.md,broken liquid tags
|
||||
translations/pt-BR/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/pt-BR/content/account-and-profile/setting-up-and-managing-your-personal-account-on-github/index.md,broken liquid tags
|
||||
translations/pt-BR/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/pt-BR/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
|
||||
|
@ -313,8 +315,8 @@ translations/pt-BR/content/admin/policies/enforcing-policies-for-your-enterprise
|
|||
translations/pt-BR/content/admin/policies/enforcing-policies-for-your-enterprise/enforcing-policies-for-security-settings-in-your-enterprise.md,broken liquid tags
|
||||
translations/pt-BR/content/admin/policies/enforcing-policies-for-your-enterprise/enforcing-repository-management-policies-in-your-enterprise.md,broken liquid tags
|
||||
translations/pt-BR/content/admin/user-management/managing-users-in-your-enterprise/viewing-people-in-your-enterprise.md,rendering error
|
||||
translations/pt-BR/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/pt-BR/content/authentication/authenticating-with-saml-single-sign-on/authorizing-an-ssh-key-for-use-with-saml-single-sign-on.md,broken liquid tags
|
||||
translations/pt-BR/content/authentication/authenticating-with-saml-single-sign-on/authorizing-a-personal-access-token-for-use-with-saml-single-sign-on.md,rendering error
|
||||
translations/pt-BR/content/authentication/authenticating-with-saml-single-sign-on/authorizing-an-ssh-key-for-use-with-saml-single-sign-on.md,rendering error
|
||||
translations/pt-BR/content/authentication/connecting-to-github-with-ssh/about-ssh.md,broken liquid tags
|
||||
translations/pt-BR/content/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent.md,rendering error
|
||||
translations/pt-BR/content/authentication/keeping-your-account-and-data-secure/reviewing-your-deploy-keys.md,rendering error
|
||||
|
@ -363,18 +365,20 @@ translations/pt-BR/content/code-security/dependabot/working-with-dependabot/mana
|
|||
translations/pt-BR/content/code-security/getting-started/github-security-features.md,rendering error
|
||||
translations/pt-BR/content/code-security/getting-started/securing-your-repository.md,rendering error
|
||||
translations/pt-BR/content/code-security/secret-scanning/about-secret-scanning.md,rendering error
|
||||
translations/pt-BR/content/code-security/secret-scanning/configuring-secret-scanning-for-your-repositories.md,broken liquid tags
|
||||
translations/pt-BR/content/code-security/secret-scanning/defining-custom-patterns-for-secret-scanning.md,rendering error
|
||||
translations/pt-BR/content/code-security/secret-scanning/managing-alerts-from-secret-scanning.md,rendering error
|
||||
translations/pt-BR/content/code-security/secret-scanning/protecting-pushes-with-secret-scanning.md,rendering error
|
||||
translations/pt-BR/content/code-security/secret-scanning/pushing-a-branch-blocked-by-push-protection.md,rendering error
|
||||
translations/pt-BR/content/code-security/security-overview/about-the-security-overview.md,rendering error
|
||||
translations/pt-BR/content/code-security/security-overview/filtering-alerts-in-the-security-overview.md,broken liquid tags
|
||||
translations/pt-BR/content/code-security/security-overview/filtering-alerts-in-the-security-overview.md,rendering error
|
||||
translations/pt-BR/content/code-security/security-overview/viewing-the-security-overview.md,rendering error
|
||||
translations/pt-BR/content/code-security/supply-chain-security/end-to-end-supply-chain/securing-code.md,rendering error
|
||||
translations/pt-BR/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review.md,rendering error
|
||||
translations/pt-BR/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-supply-chain-security.md,rendering error
|
||||
translations/pt-BR/content/code-security/supply-chain-security/understanding-your-software-supply-chain/about-the-dependency-graph.md,rendering error
|
||||
translations/pt-BR/content/code-security/supply-chain-security/understanding-your-software-supply-chain/configuring-dependency-review.md,broken liquid tags
|
||||
translations/pt-BR/content/code-security/supply-chain-security/understanding-your-software-supply-chain/configuring-dependency-review.md,rendering error
|
||||
translations/pt-BR/content/code-security/supply-chain-security/understanding-your-software-supply-chain/configuring-the-dependency-graph.md,broken liquid tags
|
||||
translations/pt-BR/content/codespaces/codespaces-reference/allowing-your-codespace-to-access-a-private-image-registry.md,broken liquid tags
|
||||
translations/pt-BR/content/codespaces/codespaces-reference/disaster-recovery-for-github-codespaces.md,broken liquid tags
|
||||
translations/pt-BR/content/codespaces/codespaces-reference/security-in-github-codespaces.md,broken liquid tags
|
||||
|
@ -438,8 +442,12 @@ translations/pt-BR/content/desktop/contributing-and-collaborating-using-github-d
|
|||
translations/pt-BR/content/developers/apps/building-github-apps/authenticating-with-github-apps.md,rendering error
|
||||
translations/pt-BR/content/developers/apps/building-github-apps/managing-allowed-ip-addresses-for-a-github-app.md,rendering error
|
||||
translations/pt-BR/content/developers/apps/getting-started-with-apps/differences-between-github-apps-and-oauth-apps.md,broken liquid tags
|
||||
translations/pt-BR/content/developers/apps/getting-started-with-apps/setting-up-your-development-environment-to-create-a-github-app.md,broken liquid tags
|
||||
translations/pt-BR/content/developers/apps/guides/creating-ci-tests-with-the-checks-api.md,broken liquid tags
|
||||
translations/pt-BR/content/developers/apps/guides/using-the-github-api-in-your-app.md,broken liquid tags
|
||||
translations/pt-BR/content/developers/overview/about-githubs-apis.md,broken liquid tags
|
||||
translations/pt-BR/content/developers/overview/managing-deploy-keys.md,broken liquid tags
|
||||
translations/pt-BR/content/developers/webhooks-and-events/events/issue-event-types.md,broken liquid tags
|
||||
translations/pt-BR/content/developers/webhooks-and-events/webhooks/webhook-events-and-payloads.md,rendering error
|
||||
translations/pt-BR/content/discussions/collaborating-with-your-community-using-discussions/collaborating-with-maintainers-using-discussions.md,broken liquid tags
|
||||
translations/pt-BR/content/discussions/collaborating-with-your-community-using-discussions/participating-in-a-discussion.md,broken liquid tags
|
||||
|
@ -460,7 +468,7 @@ translations/pt-BR/content/get-started/writing-on-github/getting-started-with-wr
|
|||
translations/pt-BR/content/get-started/writing-on-github/working-with-advanced-formatting/attaching-files.md,broken liquid tags
|
||||
translations/pt-BR/content/get-started/writing-on-github/working-with-advanced-formatting/writing-mathematical-expressions.md,rendering error
|
||||
translations/pt-BR/content/graphql/guides/migrating-from-rest-to-graphql.md,broken liquid tags
|
||||
translations/pt-BR/content/graphql/overview/about-the-graphql-api.md,broken liquid tags
|
||||
translations/pt-BR/content/graphql/overview/about-the-graphql-api.md,rendering error
|
||||
translations/pt-BR/content/issues/planning-and-tracking-with-projects/automating-your-project/using-the-api-to-manage-projects.md,broken liquid tags
|
||||
translations/pt-BR/content/issues/planning-and-tracking-with-projects/managing-your-project/managing-access-to-your-projects.md,broken liquid tags
|
||||
translations/pt-BR/content/issues/planning-and-tracking-with-projects/managing-your-project/managing-visibility-of-your-projects.md,broken liquid tags
|
||||
|
@ -601,6 +609,7 @@ translations/pt-BR/data/reusables/actions/sidebar-secret.md,rendering error
|
|||
translations/pt-BR/data/reusables/actions/usage-workflow-run-time.md,rendering error
|
||||
translations/pt-BR/data/reusables/actions/workflow-basic-example-and-explanation.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/actions/workflow-dispatch-inputs.md,rendering error
|
||||
translations/pt-BR/data/reusables/advanced-security/about-ghas-organization-policy.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/advanced-security/secret-scanning-add-custom-pattern-details.md,rendering error
|
||||
translations/pt-BR/data/reusables/advanced-security/secret-scanning-create-custom-pattern.md,rendering error
|
||||
translations/pt-BR/data/reusables/advanced-security/secret-scanning-push-protection-org.md,broken liquid tags
|
||||
|
@ -609,6 +618,7 @@ translations/pt-BR/data/reusables/audit_log/audit_log_sidebar_for_org_admins.md,
|
|||
translations/pt-BR/data/reusables/audit_log/audit_log_sidebar_for_site_admins.md,rendering error
|
||||
translations/pt-BR/data/reusables/code-scanning/codeql-languages-bullets.md,rendering error
|
||||
translations/pt-BR/data/reusables/code-scanning/codeql-languages-keywords.md,rendering error
|
||||
translations/pt-BR/data/reusables/code-scanning/enterprise-enable-code-scanning.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/code-scanning/example-configuration-files.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/code-scanning/licensing-note.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/code-scanning/run-additional-queries.md,broken liquid tags
|
||||
|
@ -628,6 +638,7 @@ translations/pt-BR/data/reusables/codespaces/your-codespaces-procedure-step.md,b
|
|||
translations/pt-BR/data/reusables/dependabot/beta-security-and-version-updates.md,rendering error
|
||||
translations/pt-BR/data/reusables/dependabot/default-dependencies-allow-ignore.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/dependabot/enabling-disabling-dependency-graph-private-repo.md,rendering error
|
||||
translations/pt-BR/data/reusables/dependabot/enterprise-enable-dependabot.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/dotcom_billing/actions-packages-report-download-org-account.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/enterprise-accounts/actions-packages-report-download-enterprise-accounts.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/enterprise-accounts/billing-microsoft-ea-overview.md,broken liquid tags
|
||||
|
@ -639,7 +650,9 @@ translations/pt-BR/data/reusables/gated-features/codespaces-classroom-articles.m
|
|||
translations/pt-BR/data/reusables/gated-features/dependency-vulnerable-calls.md,rendering error
|
||||
translations/pt-BR/data/reusables/gated-features/secret-scanning-partner.md,rendering error
|
||||
translations/pt-BR/data/reusables/gated-features/secret-scanning.md,rendering error
|
||||
translations/pt-BR/data/reusables/getting-started/enterprise-advanced-security.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/identity-and-permissions/ip-allow-lists-enable.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/identity-and-permissions/vigilant-mode-beta-note.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/notifications-v2/custom-notification-types.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/notifications/vulnerable-dependency-notification-options.md,rendering error
|
||||
translations/pt-BR/data/reusables/organizations/billing_plans.md,rendering error
|
||||
|
@ -660,10 +673,12 @@ translations/pt-BR/data/reusables/repositories/navigate-to-commit-page.md,broken
|
|||
translations/pt-BR/data/reusables/repositories/repository-branches.md,rendering error
|
||||
translations/pt-BR/data/reusables/repositories/sidebar-notifications.md,rendering error
|
||||
translations/pt-BR/data/reusables/repositories/suggest-changes.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/secret-scanning/enterprise-enable-secret-scanning.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/secret-scanning/partner-secret-list-private-repo.md,rendering error
|
||||
translations/pt-BR/data/reusables/secret-scanning/push-protection-web-ui-choice.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/secret-scanning/secret-list-private-push-protection.md,rendering error
|
||||
translations/pt-BR/data/reusables/security-overview/permissions.md,rendering error
|
||||
translations/pt-BR/data/reusables/support/help_resources.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/user-settings/access_applications.md,rendering error
|
||||
translations/pt-BR/data/reusables/user-settings/account_settings.md,rendering error
|
||||
translations/pt-BR/data/reusables/user-settings/appearance-settings.md,rendering error
|
||||
|
@ -677,6 +692,7 @@ translations/pt-BR/data/reusables/user-settings/security.md,rendering error
|
|||
translations/pt-BR/data/reusables/user-settings/ssh.md,rendering error
|
||||
translations/pt-BR/data/reusables/webhooks/pull_request_properties.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/webhooks/pull_request_webhook_properties.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/webhooks/repository_vulnerability_alert_short_desc.md,broken liquid tags
|
||||
translations/pt-BR/data/reusables/webhooks/workflow_run_properties.md,broken liquid tags
|
||||
translations/pt-BR/data/variables/migrations.yml,broken liquid tags
|
||||
translations/pt-BR/data/variables/notifications.yml,broken liquid tags
|
||||
|
|
|
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
title: Como mostrar as contribuições e conquistas privadas em seu perfil
|
||||
intro: 'Seu perfil do {% data variables.product.product_name %} mostra um gráfico de contribuições no seu repositório no último ano. Você pode mostrar uma atividade anonimizada de {% ifversion fpt or ghes or ghec %}repositórios privados e internos{% else %}privados{% endif %}{% ifversion fpt or ghes or ghec %} além da atividade de repositórios 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: pt-BR
|
||||
ms.lasthandoff: 09/05/2022
|
||||
ms.locfileid: '147079408'
|
||||
---
|
||||
Se você mostrar suas contribuições privadas, pessoas sem acesso aos repositórios nos quais você trabalha não poderão ver os detalhes de suas contribuições privadas. Em vez disso, elas verão o número de contribuições privadas que você fez em determinado dia. Suas contribuições públicas incluirão informações detalhadas. Para obter mais informações, confira "[Como ver as contribuições na página do seu 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 %}
|
||||
|
||||
**Observação:** {% ifversion fpt or ghes or ghec %}No {% ifversion fpt or ghec %}{% data variables.product.prodname_dotcom_the_website %}{% elsif ghes %}{% data variables.product.product_name %}{% endif %}, as contribuições públicas no seu perfil são visíveis {% ifversion fpt or ghec %}para qualquer pessoa no mundo que possa acessar o {% data variables.product.prodname_dotcom_the_website %}{% elsif ghes %}apenas para outros usuários do {% data variables.product.product_location%}{% endif %}.{% elsif ghae %}No {% data variables.product.prodname_ghe_managed %}, somente outros membros da sua empresa podem ver as contribuições no seu 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 %}
|
||||
|
||||
## Alterar a visibilidade de suas contribuições privadas
|
||||
## Changing the visibility of your private contributions
|
||||
|
||||
{% data reusables.profile.access_profile %}
|
||||
1. Mostre ou oculte contribuições privadas no perfil:
|
||||
- Para divulgar suas contribuições privadas, acima do grafo de contribuições, use o menu suspenso **Configurações de contribuição** e selecione **Contribuições privadas**. Os visitantes verão sua contagem de contribuições privadas sem informações adicionais.
|
||||
![Permitir que os visitantes vejam as contribuições privadas no menu suspenso Configurações de contribuição](/assets/images/help/profile/private-contributions-on.png)
|
||||
- Para ocultar suas contribuições privadas, acima do grafo de contribuições, use o menu suspenso **Configurações de contribuição** e desmarque **Contribuições privadas.** Os visitantes só verão suas contribuições públicas.
|
||||
![Permitir que os visitantes vejam as contribuições privadas no menu suspenso Configurações de contribuição](/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)
|
||||
|
||||
## Como alterar a visibilidade das Conquistas
|
||||
## Changing the visibility of Achievements
|
||||
|
||||
{% data reusables.user-settings.access_settings %}
|
||||
1. Mostrar ou ocultar as Conquistas em seu perfil:
|
||||
- Para mostrar as Conquistas em seu perfil, acesse **Configurações de perfil** e marque a caixa de seleção ao lado de **Mostrar Conquistas no meu perfil.**
|
||||
![Permitir que os visitantes vejam as Conquistas nas configurações de perfil](/assets/images/achievements-profile-settings-off.png)
|
||||
- Para ocultar as Conquistas do seu perfil, acesse **Configurações de perfil** e desmarque a caixa de seleção ao lado de **Mostrar Conquistas no meu perfil.**
|
||||
![Ocultar as Conquistas dos visitantes nas configurações de 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)
|
||||
|
||||
## Leitura adicional
|
||||
{% endif %}
|
||||
## Further reading
|
||||
|
||||
- "[Como ver as contribuições na página do seu perfil](/articles/viewing-contributions-on-your-profile-page)"
|
||||
- "[Por que minhas contribuições não aparecem no meu 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)"
|
||||
|
|
|
@ -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`
|
||||
|
||||
|
|
|
@ -3,6 +3,7 @@ title: Gerenciando a segurança do código para sua empresa
|
|||
shortTitle: Manage code security
|
||||
intro: Você pode criar a segurança no fluxo de trabalho de seus desenvolvedores com funcionalidades que mantêm segredos e vulnerabilidades fora da base de código e isso mantém sua cadeia de suprimentos de software.
|
||||
versions:
|
||||
ghec: '*'
|
||||
ghes: '*'
|
||||
ghae: '*'
|
||||
topics:
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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)."
|
||||
|
|
|
@ -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/*"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
@ -1,40 +0,0 @@
|
|||
---
|
||||
title: Aplicar políticas de Segurança Avançada na sua empresa
|
||||
intro: 'Você pode exigir políticas para gerenciar as funcionalidades de {% data variables.product.prodname_GH_advanced_security %} dentro das organizações de sua empresa ou permitir que as políticas sejam definidas em cada organização.'
|
||||
permissions: 'Enterprise owners can enforce policies for {% data variables.product.prodname_GH_advanced_security %} in an enterprise.'
|
||||
product: '{% data reusables.gated-features.ghas %}'
|
||||
versions:
|
||||
ghec: '*'
|
||||
ghes: '*'
|
||||
ghae: '*'
|
||||
type: how_to
|
||||
topics:
|
||||
- Advanced Security
|
||||
- Code scanning
|
||||
- Enterprise
|
||||
- Policies
|
||||
- Secret scanning
|
||||
- Security
|
||||
redirect_from:
|
||||
- /admin/policies/enforcing-policies-for-advanced-security-in-your-enterprise
|
||||
- /github/setting-up-and-managing-your-enterprise/enforcing-policies-for-advanced-security-in-your-enterprise-account
|
||||
- /github/setting-up-and-managing-your-enterprise/setting-policies-for-organizations-in-your-enterprise-account/enforcing-policies-for-advanced-security-in-your-enterprise-account
|
||||
shortTitle: Advanced Security policies
|
||||
ms.openlocfilehash: 1858a854f78695b2fa36e0b84944f2fa05db0d00
|
||||
ms.sourcegitcommit: fcf3546b7cc208155fb8acdf68b81be28afc3d2d
|
||||
ms.translationtype: HT
|
||||
ms.contentlocale: pt-BR
|
||||
ms.lasthandoff: 09/10/2022
|
||||
ms.locfileid: '145094896'
|
||||
---
|
||||
## Sobre as políticas para {% data variables.product.prodname_GH_advanced_security %} na sua empresa
|
||||
|
||||
{% data reusables.advanced-security.ghas-helps-developers %} Para obter mais informações, confira "[Sobre o {% data variables.product.prodname_GH_advanced_security %}](/get-started/learning-about-github/about-github-advanced-security)".
|
||||
|
||||
{% ifversion ghes or ghec %}Se você comprar uma licença para {% data variables.product.prodname_GH_advanced_security %}, qualquer{% else %}Qualquer organização de{% endif %} em {% data variables.product.product_location %} pode usar funcionalidades de {% data variables.product.prodname_advanced_security %}. Você pode aplicar políticas para controlar como os integrantes da sua empresa em {% data variables.product.product_name %} usam {% data variables.product.prodname_advanced_security %}.
|
||||
|
||||
## Aplicando uma política para o uso de {% data variables.product.prodname_GH_advanced_security %} na sua empresa
|
||||
|
||||
{% data reusables.advanced-security.about-ghas-organization-policy %}
|
||||
|
||||
{% data reusables.enterprise-accounts.access-enterprise %} {% data reusables.enterprise-accounts.policies-tab %} {% data reusables.enterprise-accounts.advanced-security-policies %} {% data reusables.enterprise-accounts.advanced-security-organization-policy-drop-down %} {% data reusables.enterprise-accounts.advanced-security-individual-organization-policy-drop-down %}
|
|
@ -21,7 +21,7 @@ children:
|
|||
- /enforcing-policies-for-security-settings-in-your-enterprise
|
||||
- /enforcing-policies-for-dependency-insights-in-your-enterprise
|
||||
- /enforcing-policies-for-github-actions-in-your-enterprise
|
||||
- /enforcing-policies-for-advanced-security-in-your-enterprise
|
||||
- /enforcing-policies-for-code-security-and-analysis-for-your-enterprise
|
||||
shortTitle: Enforce policies
|
||||
ms.openlocfilehash: 045831c9b6e9632db2f7743f2cf30d965ee3c327
|
||||
ms.sourcegitcommit: 478f2931167988096ae6478a257f492ecaa11794
|
||||
|
|
|
@ -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)"
|
||||
|
|
|
@ -5,6 +5,7 @@ intro: You can enable vigilant mode for commit signature verification to mark al
|
|||
versions:
|
||||
fpt: '*'
|
||||
ghec: '*'
|
||||
ghes: '*'
|
||||
topics:
|
||||
- Identity
|
||||
- Access management
|
||||
|
@ -12,6 +13,7 @@ redirect_from:
|
|||
- /github/authenticating-to-github/displaying-verification-statuses-for-all-of-your-commits
|
||||
- /github/authenticating-to-github/managing-commit-signature-verification/displaying-verification-statuses-for-all-of-your-commits
|
||||
---
|
||||
|
||||
{% data reusables.identity-and-permissions.vigilant-mode-beta-note %}
|
||||
|
||||
## About vigilant mode
|
||||
|
|
|
@ -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 %}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
title: Configurar a verificação de segredo para seus repositórios
|
||||
intro: 'Você pode configurar como {% data variables.product.prodname_dotcom %} digitaliza os seus repositórios vom relação a segredos que correspondem a padrões avançados de segurança.'
|
||||
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: pt-BR
|
||||
ms.lasthandoff: 09/05/2022
|
||||
ms.locfileid: '147061999'
|
||||
---
|
||||
{% data reusables.secret-scanning.beta %} {% data reusables.secret-scanning.enterprise-enable-secret-scanning %}
|
||||
|
||||
## Como habilitar a {% data variables.product.prodname_secret_scanning_GHAS %}
|
||||
{% data reusables.secret-scanning.beta %}
|
||||
{% data reusables.secret-scanning.enterprise-enable-secret-scanning %}
|
||||
|
||||
Você pode habilitar a {% data variables.product.prodname_secret_scanning_GHAS %} em qualquer repositório pertencente a uma organização. Uma vez habilitado, {% 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. Se o {% data variables.product.prodname_advanced_security %} ainda não estiver habilitado no repositório, à direita de "{% data variables.product.prodname_GH_advanced_security %}", clique em **Habilitar**.
|
||||
{% ifversion fpt or ghec %}![Habilitar o {% data variables.product.prodname_GH_advanced_security %} no seu repositório](/assets/images/help/repository/enable-ghas-dotcom.png) {% elsif ghes or ghae %}![Habilitar o {% data variables.product.prodname_GH_advanced_security %} no seu repositório](/assets/images/enterprise/3.1/help/repository/enable-ghas.png){% endif %}
|
||||
5. Revise o impacto da habilitação do {% data variables.product.prodname_advanced_security %} e clique em **Habilitar o {% data variables.product.prodname_GH_advanced_security %} neste repositório**.
|
||||
6. Quando você habilitar {% data variables.product.prodname_advanced_security %}, {% data variables.product.prodname_secret_scanning %} pode ser habilitado automaticamente para o repositório, devido às configurações da organização. Se "{% data variables.product.prodname_secret_scanning_caps %}" for mostrado com um botão **Habilitar**, você ainda precisará habilitar a {% data variables.product.prodname_secret_scanning %} clicando em **Habilitar**. Se um botão **Desabilitar** for exibido, a {% data variables.product.prodname_secret_scanning %} já estará habilitada.
|
||||
![Habilitar a {% data variables.product.prodname_secret_scanning %} no repositório](/assets/images/help/repository/enable-secret-scanning-dotcom.png) {% ifversion secret-scanning-push-protection %}
|
||||
7. Opcionalmente, caso deseje habilitar a proteção por push, clique em **Habilitar** à direita de "Proteção por push". {% data reusables.secret-scanning.push-protection-overview %} Para obter mais informações, confira "[Como proteger pushes com a {% data variables.product.prodname_secret_scanning %}](/code-security/secret-scanning/protecting-pushes-with-secret-scanning)".
|
||||
![Habilitar a proteção por push no seu repositório](/assets/images/help/repository/secret-scanning-enable-push-protection.png) {% endif %} {% ifversion ghae %}
|
||||
1. Antes de habilitar {% data variables.product.prodname_secret_scanning %}, você precisa habilitar {% data variables.product.prodname_GH_advanced_security %} primeiro. À direita de "{% data variables.product.prodname_GH_advanced_security %}", clique em **Habilitar**.
|
||||
![Habilitar o {% data variables.product.prodname_GH_advanced_security %} no seu repositório](/assets/images/enterprise/github-ae/repository/enable-ghas-ghae.png)
|
||||
2. Clique em **Habilitar o {% data variables.product.prodname_GH_advanced_security %} neste repositório** para confirmar a ação.
|
||||
![Confirmar a habilitação do {% data variables.product.prodname_GH_advanced_security %} no seu repositório](/assets/images/enterprise/github-ae/repository/enable-ghas-confirmation-ghae.png)
|
||||
3. À direita de "{% data variables.product.prodname_secret_scanning_caps %}", clique em **Habilitar**.
|
||||
![Habilitar a {% data variables.product.prodname_secret_scanning %} no seu repositório](/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 %}
|
||||
|
||||
## Excluindo diretórios de {% data variables.product.prodname_secret_scanning_GHAS %}
|
||||
{% ifversion secret-scanning-enterprise-level %}
|
||||
{% note %}
|
||||
|
||||
Use um arquivo *secret_scanning.yml* para excluir diretórios da {% data variables.product.prodname_secret_scanning %}. Por exemplo, você pode excluir diretórios que contenham testes ou conteúdo gerado 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. No campo de nome do arquivo, digite *.github/secret_scanning.yml*.
|
||||
4. Em **Editar novo arquivo**, digite `paths-ignore:` seguido dos caminhos que deseja excluir da {% 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"
|
||||
```
|
||||
|
||||
Você pode usar caracteres especiais, como `*` para filtrar caminhos. Para obter mais informações sobre os padrões de filtro, confira "[Sintaxe de fluxo de trabalho do 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 %}
|
||||
|
||||
**Observações:**
|
||||
- Se houver mais de mil entradas em `paths-ignore`, a {% data variables.product.prodname_secret_scanning %} excluirá apenas os primeiros mil diretórios das verificações.
|
||||
- Se *secret_scanning.yml* for maior que 1 MB, a {% data variables.product.prodname_secret_scanning %} vai ignorar todo o arquivo.
|
||||
**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 %}
|
||||
|
||||
Você também pode ignorar alertas individuais de {% data variables.product.prodname_secret_scanning %}. Para obter mais informações, confira "[Como gerenciar alertas da {% 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)."
|
||||
|
||||
## Leitura adicional
|
||||
## Further reading
|
||||
|
||||
- "[Como gerenciar as configurações de segurança e análise da sua organização](/organizations/keeping-your-organization-secure/managing-security-and-analysis-settings-for-your-organization)"
|
||||
- "[Como definir padrões personalizados para {% 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)"
|
||||
|
|
|
@ -155,9 +155,11 @@ Before defining a custom pattern, you must ensure that you enable secret scannin
|
|||
{% endnote %}
|
||||
|
||||
{% data reusables.enterprise-accounts.access-enterprise %}
|
||||
{% data reusables.enterprise-accounts.policies-tab %}
|
||||
{% data reusables.enterprise-accounts.policies-tab %}{% ifversion security-feature-enablement-policies %}
|
||||
{% data reusables.enterprise-accounts.code-security-and-analysis-policies %}
|
||||
1. Under "Code security and analysis", click **Security features**.{% else %}
|
||||
{% data reusables.enterprise-accounts.advanced-security-policies %}
|
||||
{% data reusables.enterprise-accounts.advanced-security-security-features %}
|
||||
{% data reusables.enterprise-accounts.advanced-security-security-features %}{% endif %}
|
||||
1. Under "Secret scanning custom patterns", click {% ifversion ghes = 3.2 %}**New custom pattern**{% else %}**New pattern**{% endif %}.
|
||||
{% data reusables.advanced-security.secret-scanning-add-custom-pattern-details %}
|
||||
{%- ifversion secret-scanning-custom-enterprise-36 or custom-pattern-dry-run-ga %}
|
||||
|
|
|
@ -33,7 +33,9 @@ When you create a pull request containing changes to dependencies that targets t
|
|||
|
||||
## Dependency graph availability
|
||||
|
||||
{% ifversion fpt or ghec %}The dependency graph is available for every public repository that defines dependencies in a supported package ecosystem using a supported file format. Repository administrators can also set up the dependency graph for private repositories. For more information, see "[Configuring the dependency graph](/code-security/supply-chain-security/understanding-your-software-supply-chain/configuring-the-dependency-graph)."{% endif %}
|
||||
{% ifversion fpt or ghec %}The dependency graph is available for every public repository that defines dependencies in a supported package ecosystem using a supported file format. Repository administrators can also set up the dependency graph for private repositories. {% endif %}For more information {% ifversion ghes %}about configuration of the dependency graph{% endif %}, see "[Configuring the dependency graph](/code-security/supply-chain-security/understanding-your-software-supply-chain/configuring-the-dependency-graph)."
|
||||
|
||||
{% data reusables.code-scanning.enterprise-enable-dependency-graph %}
|
||||
|
||||
{% data reusables.dependabot.dependabot-alerts-dependency-graph-enterprise %}
|
||||
|
||||
|
@ -85,6 +87,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 %}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
title: Configurando o grafo de dependência
|
||||
intro: Você pode permitir que os usuários identifiquem as dependências dos seus projetos habilitando o gráfico de dependências.
|
||||
title: Configuring the dependency graph
|
||||
intro: You can allow users to identify their projects' dependencies by enabling the dependency graph.
|
||||
redirect_from:
|
||||
- /code-security/supply-chain-security/understanding-your-software-supply-chain/about-the-dependency-graph#enabling-the-dependency-graph
|
||||
versions:
|
||||
|
@ -14,37 +14,39 @@ topics:
|
|||
- Dependencies
|
||||
- Repositories
|
||||
shortTitle: Configure dependency graph
|
||||
ms.openlocfilehash: 24dcaac4ddd994d544f6caa7d04529e1e4a5d569
|
||||
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
|
||||
ms.translationtype: HT
|
||||
ms.contentlocale: pt-BR
|
||||
ms.lasthandoff: 09/05/2022
|
||||
ms.locfileid: '146684074'
|
||||
---
|
||||
## Sobre o gráfico de dependências
|
||||
## About the dependency graph
|
||||
|
||||
{% data reusables.dependabot.about-the-dependency-graph %}
|
||||
|
||||
Para obter mais informações, confira "[Sobre o grafo de dependência](/code-security/supply-chain-security/understanding-your-software-supply-chain/about-the-dependency-graph)".
|
||||
For more information, see "[About the dependency graph](/code-security/supply-chain-security/understanding-your-software-supply-chain/about-the-dependency-graph)."
|
||||
|
||||
{% ifversion fpt or ghec %}
|
||||
## Sobre a configuração do grafo de dependência
|
||||
Para gerar um grafo de dependência, o {% data variables.product.product_name %} precisa ter acesso somente leitura ao manifesto de dependência e aos arquivos de bloqueio de um repositório. O gráfico de dependências é gerado automaticamente para todos os repositórios públicos e você pode optar por habilitá-lo para repositórios privados. Para obter mais informações sobre a exibição do grafo de dependência, confira "[Como explorar as dependências de um repositório](/github/visualizing-repository-data-with-graphs/exploring-the-dependencies-of-a-repository)".
|
||||
## About configuring the dependency graph
|
||||
To generate a dependency graph, {% data variables.product.product_name %} needs read-only access to the dependency manifest and lock files for a repository. The dependency graph is automatically generated for all public repositories and you can choose to enable it for private repositories. For more information on viewing the dependency graph, see "[Exploring the dependencies of a repository](/github/visualizing-repository-data-with-graphs/exploring-the-dependencies-of-a-repository)."
|
||||
|
||||
{% data reusables.dependency-submission.dependency-submission-link %} {% endif %}
|
||||
{% data reusables.dependency-submission.dependency-submission-link %}
|
||||
{% endif %}
|
||||
|
||||
{% ifversion ghes %} ## Habilitando o grafo de dependência {% data reusables.dependabot.ghes-ghae-enabling-dependency-graph %}{% endif %}{% ifversion fpt or ghec %}
|
||||
{% ifversion ghes %} ## Enabling the dependency graph
|
||||
{% data reusables.code-scanning.enterprise-enable-dependency-graph %}
|
||||
{% data reusables.dependabot.ghes-ghae-enabling-dependency-graph %}{% endif %}{% ifversion fpt or ghec %}
|
||||
|
||||
### Habilitar e desabilitar o gráfico de dependências para um repositório privado
|
||||
### Enabling and disabling the dependency graph for a private repository
|
||||
|
||||
{% data reusables.dependabot.enabling-disabling-dependency-graph-private-repo %} {% endif %}
|
||||
{% data reusables.dependabot.enabling-disabling-dependency-graph-private-repo %}
|
||||
|
||||
Quando o gráfico de dependências é ativado pela primeira vez, todos manifesto e arquivos de bloqueio para ecossistemas suportados são analisados imediatamente. O gráfico geralmente é preenchido em minutos, mas isso pode levar mais tempo para repositórios com muitas dependências. Depois de habilitado, o gráfico é atualizado automaticamente a cada push no repositório{% ifversion fpt or ghec %} e a cada push para outros repositórios no grafo{% endif %}.
|
||||
{% data reusables.code-scanning.enterprise-enable-dependency-graph %}
|
||||
{% endif %}
|
||||
|
||||
{% ifversion ghes %} {% ifversion dependency-submission-api %}{% data reusables.dependency-submission.dependency-submission-link %}{% endif %} {% endif %}
|
||||
When the dependency graph is first enabled, any manifest and lock files for supported ecosystems are parsed immediately. The graph is usually populated within minutes but this may take longer for repositories with many dependencies. Once enabled, the graph is automatically updated with every push to the repository{% ifversion fpt or ghec %} and every push to other repositories in the graph{% endif %}.
|
||||
|
||||
## Leitura adicional
|
||||
{% ifversion ghes %}
|
||||
{% ifversion dependency-submission-api %}{% data reusables.dependency-submission.dependency-submission-link %}{% endif %}
|
||||
{% endif %}
|
||||
|
||||
{% ifversion ghec %}–"[Como ver os insights da sua organização](/organizations/collaborating-with-groups-in-organizations/viewing-insights-for-your-organization)"{% endif %}
|
||||
- "[Como ver e atualizar {% data variables.product.prodname_dependabot_alerts %}](/code-security/dependabot/dependabot-alerts/viewing-and-updating-dependabot-alerts)"
|
||||
- "[Solução de problemas de detecção de dependências vulneráveis](/github/managing-security-vulnerabilities/troubleshooting-the-detection-of-vulnerable-dependencies)"
|
||||
## Further reading
|
||||
|
||||
{% ifversion ghec %}- "[Viewing insights for your organization](/organizations/collaborating-with-groups-in-organizations/viewing-insights-for-your-organization)"{% endif %}
|
||||
- "[Viewing and updating {% data variables.product.prodname_dependabot_alerts %}](/code-security/dependabot/dependabot-alerts/viewing-and-updating-dependabot-alerts)"
|
||||
- "[Troubleshooting the detection of vulnerable dependencies](/github/managing-security-vulnerabilities/troubleshooting-the-detection-of-vulnerable-dependencies)"
|
||||
|
|
|
@ -18,7 +18,7 @@ redirect_from:
|
|||
|
||||
## Using {% data variables.product.prodname_copilot %}
|
||||
|
||||
[{% data variables.product.prodname_copilot %}](https://copilot.github.com/), an AI pair programmer, can be used in any codespace. To start using {% data variables.product.prodname_copilot %} in {% data variables.product.prodname_github_codespaces %}, install the [{% data variables.product.prodname_copilot %} extension from the {% data variables.product.prodname_vscode_marketplace %}](https://marketplace.visualstudio.com/items?itemName=GitHub.copilot).
|
||||
[{% data variables.product.prodname_copilot %}](https://copilot.github.com/), an AI pair programmer, can be used in any codespace. To start using {% data variables.product.prodname_copilot %} in {% data variables.product.prodname_github_codespaces %}, install the [{% data variables.product.prodname_copilot %} extension from the {% data variables.product.prodname_vscode_marketplace %}](https://marketplace.visualstudio.com/items?itemName=GitHub.copilot). For more information about {% data variables.product.prodname_copilot %} setup and usage, see the [{% data variables.product.prodname_copilot %} documentation](/copilot).
|
||||
|
||||
To include {% data variables.product.prodname_copilot %}, or other extensions, in all of your codespaces, enable Settings Sync. For more information, see "[Personalizing {% data variables.product.prodname_github_codespaces %} for your account](/codespaces/customizing-your-codespace/personalizing-github-codespaces-for-your-account#settings-sync)." Additionally, to include {% data variables.product.prodname_copilot %} in a given project for all users, you can specify `GitHub.copilot` as an extension in your `devcontainer.json` file. For information about configuring a `devcontainer.json` file, see "[Introduction to dev containers](/codespaces/customizing-your-codespace/configuring-codespaces-for-your-project#creating-a-custom-dev-container-configuration)."
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
title: Configurar seu ambiente de desenvolvimento para criar um aplicativo GitHub
|
||||
intro: 'Aprenda os princípios básicos para estender e criar um novo {% 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: pt-BR
|
||||
ms.lasthandoff: 09/11/2022
|
||||
ms.locfileid: '145084009'
|
||||
---
|
||||
## Introdução
|
||||
## Introduction
|
||||
|
||||
Este guia irá analisar os passos necessários para configurar um aplicativo GitHub e executá-lo em um servidor. Os aplicativos GitHub exigem algumas etapas de configuração para gerenciar eventos do webhook e conectar o registro do aplicativo no GitHub ao seu código. O aplicativo neste guia serve como base que você pode usar para estender e criar novos aplicativos no GitHub.
|
||||
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.
|
||||
|
||||
Ao final deste guia, você aprenderá a registrar um aplicativo GitHub e configurar um servidor web para receber eventos de webhook. Você aprenderá a usar uma ferramenta denominada Smee para capturar cargas do webhook e encaminhá-las para seu ambiente de desenvolvimento local. O aplicativo de modelo que você vai configurar nesta seção não fará nada especial ainda, mas servirá como uma estrutura que você poderá usar para começar a escrever o código do aplicativo usando a API ou para concluir outros [guias de início rápido](/apps/quickstart-guides/). {% ifversion fpt or ghec %}Confira exemplos bem-sucedidos de aplicativos no [GitHub Marketplace](https://github.com/marketplace) e [Compatível com o 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 %}
|
||||
|
||||
Após concluir este projeto, você entenderá como efetuar a autenticação como um aplicativo GitHub e uma instalação, bem como e como esses métodos de autenticação são diferentes.
|
||||
After completing this project you will understand how to authenticate as a GitHub App and an installation, and how those authentication methods are different.
|
||||
|
||||
Aqui estão as etapas que você vai seguir para configurar o modelo do aplicativo GitHub:
|
||||
Here are the steps you'll take to configure the template GitHub App:
|
||||
|
||||
1. [Iniciar um novo canal do Smee](#step-1-start-a-new-smee-channel)
|
||||
1. [Registrar um novo Aplicativo do GitHub](#step-2-register-a-new-github-app)
|
||||
1. [Salvar sua chave privada e a ID do Aplicativo](#step-3-save-your-private-key-and-app-id)
|
||||
1. [Preparar o ambiente do runtime](#step-4-prepare-the-runtime-environment)
|
||||
1. [Revisar o código do modelo do Aplicativo do GitHub](#step-5-review-the-github-app-template-code)
|
||||
1. [Iniciar o servidor](#step-6-start-the-server)
|
||||
1. [Instalar o aplicativo na sua conta](#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 %}
|
||||
|
||||
## Pré-requisitos
|
||||
## Prerequisites
|
||||
|
||||
Você pode achar útil ter um entendimento básico do seguinte:
|
||||
You may find it helpful to have a basic understanding of the following:
|
||||
|
||||
* [Aplicativos GitHub](/apps/about-apps)
|
||||
* [GitHub Apps](/apps/about-apps)
|
||||
* [Webhooks](/webhooks)
|
||||
* [A linguagem de programação Ruby](https://www.ruby-lang.org/en/)
|
||||
* [APIs REST](/rest)
|
||||
* [The Ruby programming language](https://www.ruby-lang.org/en/)
|
||||
* [REST APIs](/rest)
|
||||
* [Sinatra](http://sinatrarb.com/)
|
||||
|
||||
Mas é possível acompanhar o processo em qualquer nível de experiência. Nós vamos nos conectar a informações de que você precisa ao longo do caminho!
|
||||
But you can follow along at any experience level. We'll link out to information you need along the way!
|
||||
|
||||
Antes de começar, você precisa clonar o repositório com o código do modelo usado neste início rápido. Abra seu aplicativo de terminal e encontre um diretório em que você gostaria de armazenar o código. Execute este comando para clonar o repositório de [modelos de Aplicativos do 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
|
||||
```
|
||||
|
||||
## Etapa 1. Inicie um novo canal da Smee
|
||||
## Step 1. Start a new Smee channel
|
||||
|
||||
Para ajudar o GitHub a enviar webhooks para a sua máquina local sem expô-lo à internet, você pode usar uma ferramenta denominada Smee. Primeiro, acesse https://smee.io e clique em **Iniciar um novo canal**. Se já estiver familiarizado com outras ferramentas que expõem seu computador local à Internet, como [`ngrok`](https://dashboard.ngrok.com/get-started) e [`localtunnel`](https://localtunnel.github.io/www/), fique à vontade para usá-las.
|
||||
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.
|
||||
|
||||
![O botão do novo canal da Smee](/assets/images/smee-new-channel.png)
|
||||
![The Smee new channel button](/assets/images/smee-new-channel.png)
|
||||
|
||||
Iniciar um novo canal da Smee cria um domínio único em que o GitHub pode enviar cargas do webhook. Para a próxima etapa, você precisa conhecer este domínio. Veja um exemplo de um domínio exclusivo em `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`:
|
||||
|
||||
![Um canal único da Smee](/assets/images/smee-unique-domain.png)
|
||||
![A Smee unique channel](/assets/images/smee-unique-domain.png)
|
||||
|
||||
Em seguida, volte ao Terminal e siga estes passos para executar o cliente da interface da linha de comando da Smee (CLI):
|
||||
Next, go back to the Terminal and follow these steps to run the Smee command-line interface (CLI) client:
|
||||
|
||||
{% note %}
|
||||
|
||||
**Observação:** as etapas a seguir são ligeiramente diferentes das instruções descritas em "Usar a CLI" que você verá na página do seu canal do Smee. Você **não** precisa seguir as instruções descritas em "Usar o cliente Node.js" ou "Como usar o suporte interno do 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. Instale o cliente:
|
||||
1. Install the client:
|
||||
|
||||
```shell
|
||||
$ npm install --global smee-client
|
||||
```
|
||||
|
||||
2. Execute o cliente (substituindo `https://smee.io/qrfeVRbFbffd6vD` por um domínio próprio):
|
||||
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
|
||||
```
|
||||
|
||||
Você verá algo semelhante ao mostrado a seguir:
|
||||
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
|
||||
```
|
||||
|
||||
O comando `smee --url <unique_channel>` instrui o Smee a encaminhar todos os eventos de webhook recebidos pelo canal do Smee ao cliente do Smee em execução no computador. A opção `--path /event_handler` encaminha os eventos para a rota `/event_handler`, que abordaremos em uma [seção posterior](#step-5-review-the-github-app-template-code). A opção `--port 3000` especifica a porta 3000, que é a porta que o servidor ouvirá. Usando a Smee. A sua máquina não precisa estar conectada à internet pública para receber os webhooks do GitHub. Você também pode abrir a URL da Smee no seu navegador para inspecionar as cargas do webhook quando entrarem.
|
||||
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.
|
||||
|
||||
Recomendamos deixar esta janela de Terminal aberta e manter a Smee conectada enquanto você realiza as outras etapas deste guia. Embora você _possa_ desconectar e reconectar o cliente Smee sem perder seu domínio exclusivo (diferente do `ngrok`), talvez você ache mais fácil mantê-lo conectado e realizar outras tarefas de linha de comando em outra janela do 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.
|
||||
|
||||
## Etapa 2. Registre um novo aplicativo GitHub
|
||||
## Step 2. Register a new GitHub App
|
||||
|
||||
Se você ainda não tem uma conta do GitHub, agora é um [ótimo momento para começar](https://github.com/join). Não se esqueça de verificar seu e-mail antes de continuar! Para registrar um novo aplicativo, acesse a [página de configurações do aplicativo](https://github.com/settings/apps) no seu perfil do GitHub e clique em **Novo Aplicativo do 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**.
|
||||
|
||||
![Site do GitHub, que mostra o **Novo aplicativo**](/assets/images/new-app.png)
|
||||
![GitHub website, showing the **New App**](/assets/images/new-app.png)
|
||||
|
||||
Você verá um formulário em que poderá inserir informações sobre o seu aplicativo. Confira "[Como criar um Aplicativo do GitHub](/apps/building-github-apps/creating-a-github-app/)" para obter informações gerais sobre os campos dessa página. Para os objetivos deste guia, você deverá inserir dados específicos em alguns 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 %}
|
||||
|
||||
**Observação:** você sempre poderá atualizar essas configurações mais tarde para apontá-las para um servidor hospedado.
|
||||
**Note:** You can always update these settings later to point to a hosted server.
|
||||
|
||||
{% endnote %}
|
||||
|
||||
* Para a "URL da página inicial", use o domínio emitido pela Smee. Por exemplo:
|
||||
* For the "Homepage URL", use the domain issued by Smee. For example:
|
||||
|
||||
![Formulário com domínio da Smee preenchido para URL da página inicial](/assets/images/homepage-url.png)
|
||||
![Form with Smee domain filled in for homepage URL](/assets/images/homepage-url.png)
|
||||
|
||||
* Para a "URL do Webhook", use novamente o domínio emitido pela Smee. Por exemplo:
|
||||
* For the "Webhook URL", again use the domain issued by Smee. For example:
|
||||
|
||||
![Formulário com domínio da Smee preenchido para URL do webhook](/assets/images/webhook-url.png)
|
||||
![Form with Smee domain filled in for webhook URL](/assets/images/webhook-url.png)
|
||||
|
||||
* Para o "segredo do Webhook", crie uma senha para proteger seus pontos de extremidade do webhook. Isto deve ser algo que somente você (e o GitHub, por meio deste formulário) sabe. O segredo é importante porque você receberá cargas da internet pública, além de usar este segredo para verificar o remetente do webhook. Observe que as configurações do aplicativo GitHub informam que o segredo do webhook é opcional, o que é verdade na maioria dos casos, mas para que o código do aplicativo do modelo funcione, você deverá definir um segredo do 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.
|
||||
|
||||
![Formulário com segredo do webhook preenchido](/assets/images/webhook-secret.png)
|
||||
![Form with webhook secret filled in](/assets/images/webhook-secret.png)
|
||||
|
||||
* Na página Permissões e Webhooks, você pode especificar um conjunto de permissões para seu aplicativo, que determina o volume de dados aos quais seu aplicativo tem acesso. Na seção "Permissões do repositório", role a página para baixo até "Metadados" e selecione `Access: Read-only`. Se você decidir estender este aplicativo do modelo, você pode atualizar essas permissões mais tarde.
|
||||
* 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.
|
||||
|
||||
* Na parte inferior da página Permissões e Webhooks, especifique se este é um aplicativo privado ou público. Isto se refere a quem pode instalá-lo: apenas você ou qualquer pessoa? Por enquanto, mantenha o aplicativo como privado selecionando **Somente nesta conta**.
|
||||
* 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**.
|
||||
|
||||
![Privacidade do aplicativo GitHub](/assets/images/create_app.png)
|
||||
![GitHub App privacy](/assets/images/create_app.png)
|
||||
|
||||
Clique em **Criar um Aplicativo do GitHub** para criar seu aplicativo.
|
||||
Click **Create GitHub App** to create your app!
|
||||
|
||||
## Etapa 3. Salve sua chave privada e o ID do aplicativo
|
||||
## Step 3. Save your private key and App ID
|
||||
|
||||
Depois de criar seu aplicativo, você será levado novamente para a [página de configurações do aplicativo](https://github.com/settings/apps). Você tem mais duas coisas para fazer aqui:
|
||||
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:
|
||||
|
||||
* **Gerar uma chave privada para seu aplicativo.** Isso é necessário para autenticar seu aplicativo posteriormente. Role a página para baixo e clique em **Gerar uma chave privada**. Salve o arquivo resultante `PEM` (chamado algo como _`app-name`_ - _`date`_ -`private-key.pem`) em um diretório em que você possa encontrá-lo novamente.
|
||||
* **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.
|
||||
|
||||
![A caixa de diálogo de geração de chaves privadas](/assets/images/private_key.png)
|
||||
![The private key generation dialog](/assets/images/private_key.png)
|
||||
|
||||
* **Anote a ID do aplicativo que o GitHub atribuiu ao aplicativo.** Você precisará disso para preparar seu ambiente de runtime.
|
||||
* **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"/>
|
||||
|
||||
## Etapa 4. Prepare o ambiente do tempo de execução
|
||||
## Step 4. Prepare the runtime environment
|
||||
|
||||
Para manter suas informações seguras, recomendamos colocar todos os segredos referentes ao aplicativo na memória do computador onde seu aplicativo poderá encontrá-los, em vez de colocá-los diretamente no seu código. Uma ferramenta de desenvolvimento útil chamada [dotenv](https://github.com/bkeepers/dotenv) carrega as variáveis de ambiente específicas do projeto de um arquivo `.env` em `ENV`. Nunca faça check-in do arquivo `.env` no GitHub. Este é um arquivo local que armazena informações confidenciais que você não deseja que estejam na internet pública. O arquivo `.env` já está incluído no arquivo [`.gitignore`](/github/getting-started-with-github/ignoring-files/) do repositório para evitar isso.
|
||||
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.
|
||||
|
||||
O código de modelo baixado na [seção Pré-requisitos](#prerequisites) já tem um arquivo de exemplo chamado `.env-example`. Renomeie o arquivo de exemplo de `.env-example` para `.env` ou crie uma cópia do arquivo `.env-example` chamado `.env`. Você ainda não instalou o dotenv, mas vai instalá-lo mais adiante neste guia de início rápido quando executar o `bundle install`. **Observação:** os guias de início rápido que referenciam as etapas deste guia podem incluir variáveis de ambiente adicionais no arquivo `.env-example`. Faça referência ao guia de início rápido para o projeto que você clonou no GitHub para orientação que define essas variáveis de ambiente adicionais.
|
||||
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.
|
||||
|
||||
Você precisa adicionar essas variáveis ao arquivo `.env`:
|
||||
You need to add these variables to the `.env` file:
|
||||
|
||||
* _`GITHUB_PRIVATE_KEY`_ : adicione a chave privada [gerada e salva](#step-3-save-your-private-key-and-app-id). Abra o arquivo `.pem` com um editor de texto ou use a linha de comando para ver o conteúdo do arquivo: `cat path/to/your/private-key.pem`. Copie todo o conteúdo do arquivo como o valor de `GITHUB_PRIVATE_KEY` no arquivo `.env`. **Observação:** como o arquivo PEM tem mais de uma linha, você precisará colocar o valor entre aspas, conforme o exemplo abaixo.
|
||||
* _`GITHUB_APP_IDENTIFIER`_ : use a ID do aplicativo que você anotou na seção anterior.
|
||||
* _`GITHUB_WEBHOOK_SECRET`_ : adicione o segredo do 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.
|
||||
|
||||
Veja aqui um exemplo de arquivo `.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
|
||||
```
|
||||
|
||||
## Etapa 5. Revise o código do modelo do aplicativo GitHub
|
||||
## Step 5. Review the GitHub App template code
|
||||
|
||||
O código do aplicativo do modelo já contém algum código de que cada aplicativo GitHub vai precisar. Esta seção apresenta o código que já existe no modelo do aplicativo GitHub. Não há etapas que você precisa realizar para concluir esta seção. Se já estiver familiarizado com o código do modelo, vá para a "[Etapa 6. Iniciar o 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 o arquivo `template_server.rb` no seu editor de texto favorito. Você verá comentários em todo este arquivo que fornecem um contexto adicional para o código do modelo. Recomendamos ler esses comentários com atenção e até mesmo adicionar seus próprios comentários para acompanhar o novo código que você escrever.
|
||||
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.
|
||||
|
||||
No início do arquivo, você verá `set :port 3000`, que define a porta usada ao iniciar o servidor Web para corresponder à porta à qual você redirecionou as cargas de webhook na "[Etapa 1. Iniciar um novo canal do 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)."
|
||||
|
||||
O próximo código que você verá é a declaração `class GHApp < Sinatra::Application`. Você irá escrever todo o código para o seu aplicativo GitHub dentro desta classe.
|
||||
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.
|
||||
|
||||
Fora desta caixa, a classe do modelo faz o seguinte:
|
||||
* [Ler as variáveis de ambiente](#read-the-environment-variables)
|
||||
* [Ativar o registro em log](#turn-on-logging)
|
||||
* [Definir um pré-filtro](#define-a-before-filter)
|
||||
* [Definir o manipulador de rotas](#define-a-route-handler)
|
||||
* [Definir os 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)
|
||||
|
||||
### Lê as variáveis de ambiente
|
||||
### Read the environment variables
|
||||
|
||||
A primeira coisa que essa classe faz é ler as três variáveis de ambiente definidas na "[Etapa 4. Preparar o ambiente de runtime](#step-4-prepare-the-runtime-environment)" e armazená-las em variáveis para uso posterior:
|
||||
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']
|
||||
```
|
||||
|
||||
### Ativar o registro em log
|
||||
### Turn on logging
|
||||
|
||||
Em seguida, um bloco do código que habilita o login durante o desenvolvimento, que é o ambiente-padrão np Sinatra. Este código ativa o log no nível `DEBUG` para mostrar uma saída útil no terminal durante o desenvolvimento do aplicativo:
|
||||
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
|
||||
```
|
||||
|
||||
### Defina um pré-filtro
|
||||
### Define a before filter
|
||||
|
||||
O Sinatra usa [pré-filtros](https://github.com/sinatra/sinatra#filters) que permitem executar o código antes do manipulador de rotas. O bloco `before` no modelo chama quatro [métodos auxiliares](https://github.com/sinatra/sinatra#helpers). O aplicativo de modelo definirá esses métodos auxiliares em uma [seção 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
|
||||
```
|
||||
|
||||
### Defina um gerenciador de encaminhamento
|
||||
### Define a route handler
|
||||
|
||||
Um encaminhamento vazio está incluído no código do modelo. Esse código processa todas as solicitações `POST` para a rota `/event_handler`. Você não escreverá esse manipulador de eventos neste guia de início rápido, mas confira os outros [guias de início rápido](/apps/quickstart-guides/) para ver exemplos de como estender este aplicativo de modelo.
|
||||
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
|
||||
```
|
||||
|
||||
### Definir os métodos auxiliares
|
||||
### Define the helper methods
|
||||
|
||||
Os métodos de ajuda neste modelo fazem a maior parte do trabalho pesado. Nesta seção do código, são definidos quatro métodos de ajuda.
|
||||
The helper methods in this template do most of the heavy lifting. Four helper methods are defined in this section of the code.
|
||||
|
||||
#### Gerenciar a carga do webhook
|
||||
#### Handling the webhook payload
|
||||
|
||||
O primeiro método `get_payload_request` captura a carga de webhook e a converte no formato JSON, o que facilita muito o acesso aos dados da 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 a assinatura do webhook
|
||||
#### Verifying the webhook signature
|
||||
|
||||
O segundo método `verify_webhook_signature` faz a verificação da assinatura do webhook para garantir que o GitHub gerou o evento. Para saber mais sobre o código no método auxiliar `verify_webhook_signature`, confira "[Como proteger seus webhooks](/webhooks/securing/)". Se os webhooks estiverem seguros, este método registrará todos as cargas de entrada no seu Terminal. O código do registro é útil para verificar se o seu servidor web está funcionando, mas você sempre poderá removê-lo posteriormente.
|
||||
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.
|
||||
|
||||
#### Efetuar autenticação como um aplicativo GitHub
|
||||
#### Authenticating as a GitHub App
|
||||
|
||||
Para fazer chamadas à API, você usará a [biblioteca Octokit](http://octokit.github.io/octokit.rb/). Fazer qualquer coisa interessante com esta biblioteca irá exigir que você, ou melhor, seu aplicativo, efetue a autenticação. Os aplicativos GitHub têm dois métodos de autenticação:
|
||||
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:
|
||||
|
||||
- Autenticação como um Aplicativo do GitHub usando um [JWT (Token Web JSON)](https://jwt.io/introduction).
|
||||
- Efetuar a autenticação como uma instalação específica de um aplicativo GitHub usando um token de acesso de instalação.
|
||||
- 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.
|
||||
|
||||
Você aprenderá a se autenticar como uma instalação na [próxima seção](#authenticating-as-an-installation).
|
||||
You'll learn about authenticating as an installation in the [next section](#authenticating-as-an-installation).
|
||||
|
||||
A [autenticação como um Aplicativo do GitHub](/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app) permite que você realize algumas ações:
|
||||
[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:
|
||||
|
||||
* Você pode recuperar informações de gerenciamento de alto nível sobre seu aplicativo GitHub.
|
||||
* Você pode solicitar tokens de acesso para uma instalação do aplicativo.
|
||||
* You can retrieve high-level management information about your GitHub App.
|
||||
* You can request access tokens for an installation of the app.
|
||||
|
||||
Por exemplo, você irá efetuar a autenticação como um aplicativo GitHub para recuperar uma lista das contas (da organização e pessoal) que instalaram seu aplicativo. Mas esse método de autenticação não permite que você faça muitas coisas com a API. Para acessar os dados de um repositório e realizar operações em nome da instalação, você precisa efetuar a autenticação como uma instalação. Para fazer isso, você precisará efetuar a autenticação como um aplicativo GitHub primeiro para solicitar um token de acesso de instalação.
|
||||
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.
|
||||
|
||||
Para usar a biblioteca Octokit.rb a fim de fazer chamadas à API, você precisará inicializar um [cliente do Octokit](http://octokit.github.io/octokit.rb/Octokit/Client.html) autenticado como um Aplicativo do GitHub. O método auxiliar `authenticate_app` faz exatamente isso.
|
||||
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
|
||||
```
|
||||
|
||||
O código acima gera um [JWT (JSON Web Token)](https://jwt.io/introduction) e o usa (com a chave privada do seu aplicativo) para inicializar o cliente do Octokit. GitHub verifica a autenticação de uma solicitação, verificando o token com a chave pública armazenada no aplicativo. Para saber mais sobre como esse código funciona, confira "[Como se autenticar como um Aplicativo do 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)."
|
||||
|
||||
#### Autenticar como uma instalação
|
||||
#### Authenticating as an installation
|
||||
|
||||
Uma _instalação_ refere-se a qualquer conta de usuário ou de organização que instalou o aplicativo. Mesmo que alguém instale o app em mais de um repositório, ele só conta como uma instalação porque está dentro da mesma conta. O último método auxiliar `authenticate_installation` inicializa um [cliente do Octokit](http://octokit.github.io/octokit.rb/Octokit/Client.html) autenticado como uma instalação. Este cliente Octokit é o que você usaria para fazer chamadas de API autenticada.
|
||||
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
|
||||
```
|
||||
|
||||
O método [`create_app_installation_access_token`](http://octokit.github.io/octokit.rb/Octokit/Client/Apps.html#create_app_installation_access_token-instance_method) do Octokit cria um token de instalação. Este método aceita dois 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:
|
||||
|
||||
* Instalação (inteiro): O ID de uma instalação do aplicativo GitHub
|
||||
* Opções (hash, usa `{}` como padrão): um conjunto personalizável de opções
|
||||
* Installation (integer): The ID of a GitHub App installation
|
||||
* Options (hash, defaults to `{}`): A customizable set of options
|
||||
|
||||
Sempre que um Aplicativo do GitHub recebe um webhook, ele inclui um objeto `installation` com uma `id`. Ao usar o cliente autenticado como um Aplicativo do GitHub, transmita essa ID para o método `create_app_installation_access_token` a fim de gerar um token de acesso para cada instalação. Uma vez que você não está passando nenhuma opção para o método, as opções-padrão para um hash vazio. Se você examinar [a documentação](/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation), poderá ver que a resposta para `create_app_installation_access_token` inclui dois campos: `token` e `expired_at`. O código de modelo seleciona o token na resposta e inicializa um cliente de instalação.
|
||||
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.
|
||||
|
||||
Com este método em vigor, cada vez que seu aplicativo recebe uma nova carga de webhook, ele cria um cliente para a instalação que acionou o evento. Este processo de autenticação permite que seu aplicativo do GitHub funcione para todas as instalações de qualquer conta.
|
||||
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.
|
||||
|
||||
Agora você está pronto para começar a fazer chamadas de API!
|
||||
Now you're ready to start making API calls!
|
||||
|
||||
## Etapa 6. Iniciar o servidor
|
||||
## Step 6. Start the server
|
||||
|
||||
Seu aplicativo ainda não _faz_ nada, mas, neste momento, você pode executá-lo no servidor.
|
||||
Your app doesn't _do_ anything yet, but at this point, you can get it running on the server.
|
||||
|
||||
Mantenha a Smee em execução na aba atual no seu Terminal. Abra uma nova guia e use `cd` no diretório em que [clonou o código do aplicativo de modelo](#prerequisites). O código do Ruby nesse repositório iniciará um servidor Web do [Sinatra](http://sinatrarb.com/). Este código tem algumas dependências. Você pode instalá-las, executando:
|
||||
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 por:
|
||||
Followed by:
|
||||
|
||||
```shell
|
||||
$ bundle install
|
||||
```
|
||||
|
||||
Com as dependências instaladas, você pode iniciar o servidor:
|
||||
With the dependencies installed, you can start the server:
|
||||
|
||||
```shell
|
||||
$ bundle exec ruby template_server.rb
|
||||
```
|
||||
|
||||
Você verá uma resposta semelhante a essa:
|
||||
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 @@ Você verá uma resposta semelhante a essa:
|
|||
> Use Ctrl-C to stop
|
||||
```
|
||||
|
||||
Se você receber um erro, verifique se criou o arquivo `.env` no diretório que contém `template_server.rb`.
|
||||
If you see an error, make sure you've created the `.env` file in the directory that contains `template_server.rb`.
|
||||
|
||||
Depois que o servidor estiver em execução, teste-o acessando `http://localhost:3000` no navegador. Se o aplicativo funcionar como esperado, você verá uma página útil de erro:
|
||||
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"/>
|
||||
|
||||
Isto é bom! Mesmo sendo uma página de erro, é uma página de erro do _Sinatra_, o que significa que o seu aplicativo está conectado ao servidor, conforme esperado. Você está vendo essa mensagem porque você não deu ao aplicativo mais nada para mostrar.
|
||||
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.
|
||||
|
||||
## Etapa 7. Instale o aplicativo em sua conta
|
||||
## Step 7. Install the app on your account
|
||||
|
||||
Você pode testar se o servidor está ouvindo seu aplicativo acionando um evento para receber. Um evento simples que você pode testar é instalar o aplicativo em sua conta do GitHub, que deverá enviar o evento [`installation`](/webhooks/event-payloads/#installation). Se o aplicativo o receber, você verá uma saída na guia Terminal, em que iniciou `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 o aplicativo, acesse a [página de configurações do aplicativo](https://github.com/settings/apps), escolha seu aplicativo e clique em **Instalar Aplicativo** na barra lateral. Ao lado do seu nome de usuário, clique em **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**.
|
||||
|
||||
Será perguntado se você deseja instalar o aplicativo em todos os repositórios ou nos repositórios selecionados. Caso você não deseje instalar o aplicativo em _todos_ os repositórios, tudo bem! Você pode criar um repositório de sandbox para fins de teste e instalar seu aplicativo lá.
|
||||
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"/>
|
||||
|
||||
Depois de clicar em **Instalar**, dê uma olhada na saída no terminal. Você deverá ver algo como:
|
||||
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 @@ Depois de clicar em **Instalar**, dê uma olhada na saída no terminal. Você de
|
|||
> 192.30.252.39 - - [29/Jun/2018:15:45:43 -0400] "POST / HTTP/2" 200 2 0.0019
|
||||
```
|
||||
|
||||
Isto é bom! Isso significa que seu aplicativo recebeu uma notificação de que foi instalado na sua conta do GitHub. Se você vir algo assim, seu aplicativo estará em execução no servidor, conforme esperado. 🙌
|
||||
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. 🙌
|
||||
|
||||
Se você não vir a saída, verifique se o Smee está sendo executado corretamente em outra guia Terminal. Se precisar reiniciar o Smee, também precisará _desinstalar_ e _reinstalar_ o aplicativo para enviar o evento `installation` para seu aplicativo novamente e ver a saída no terminal. Se o Smee não for o problema, confira a seção "[Solução de problemas](#troubleshooting)" para ter outras ideias.
|
||||
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.
|
||||
|
||||
Se você estiver se perguntando de onde vem a saída do terminal acima, ela será gravada no [código do modelo de aplicativo](#prerequisites) em `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`.
|
||||
|
||||
## Solução de problemas
|
||||
## Troubleshooting
|
||||
|
||||
Aqui estão alguns problemas comuns e algumas soluções sugeridas. Se você tiver qualquer outro problema, poderá pedir ajuda ou orientação em {% 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:** Quando tento instalar o cliente de linha de comando Smee, recebo o seguinte erro:
|
||||
* **Q:** When I try to install the Smee command-line client, I get the following error:
|
||||
|
||||
```shell
|
||||
> npm: command not found
|
||||
```
|
||||
|
||||
**R:** Parece que você não tem o npm instalado. A melhor maneira de instalá-lo é baixar o pacote Node.js em https://nodejs.org e seguir as instruções de instalação para o seu sistema. O npm será instalado juntamente com o 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:** Quando executo o servidor, recebo o seguinte erro:
|
||||
* **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:** Provavelmente, você não configurou a variável de ambiente de chave privada da maneira correta. A variável `GITHUB_PRIVATE_KEY` deverá ficar assim:
|
||||
**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 @@ Aqui estão alguns problemas comuns e algumas soluções sugeridas. Se você tiv
|
|||
-----END RSA PRIVATE KEY-----"
|
||||
```
|
||||
|
||||
Verifique se você copiou a chave pública correta para o arquivo `.env`.
|
||||
Double-check that you've copied the correct public key into your `.env` file.
|
||||
|
||||
* **P:** Quando executo o servidor, ele falha com este erro:
|
||||
* **Q:** When I run the server, it crashes with this error:
|
||||
|
||||
```shell
|
||||
> Octokit::Unauthorized ... 401 - Bad credentials`
|
||||
```
|
||||
|
||||
**R:** Você pode estar autenticado como um Aplicativo do GitHub, mas não como uma instalação. Siga todas as etapas descritas em "[Autenticação como uma instalação](#authenticating-as-an-installation)" e use a variável de instância `@installation_client` (autenticada com um token de acesso de instalação) para suas operações de API, não a variável de instância `@app_client` (autenticada com um JWT). O `@app_client` só pode recuperar informações de alto nível sobre seu aplicativo e obter tokens de acesso da instalação. Ele não pode fazer muito mais na 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:** Meu servidor não está ouvindo eventos. O cliente da Smee está sendo executado em uma janela do Terminal, e eu estou instalando o aplicativo em um repositório no GitHub, mas não vejo nenhuma saída na janela do Terminal onde estou executando o 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:** Talvez você não esteja executando o cliente do Smee, executando o comando do Smee com os parâmetros incorretos ou não tenha o domínio correto do Smee nas configurações do Aplicativo do GitHub. Primeiro, verifique se o cliente Smee está em execução em uma guia do Terminal. Se esse não for o problema, acesse a [página de configurações do aplicativo](https://github.com/settings/apps) e verifique os campos mostrados na "[Etapa 2. Registrar um novo Aplicativo do GitHub](#step-2-register-a-new-github-app)". Verifique se o domínio nesses campos corresponde ao domínio usado no comando `smee -u <unique_channel>` na "[Etapa 1. Iniciar um novo canal do Smee](#step-1-start-a-new-smee-channel)". Se nenhuma das alternativas acima funcionar, verifique se você está executando o comando do Smee completo, incluindo as opções `--path` e `--port`, por exemplo: `smee --url https://smee.io/qrfeVRbFbffd6vD --path /event_handler --port 3000` (substituindo `https://smee.io/qrfeVRbFbffd6vD` pelo seu domínio do 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).
|
||||
|
||||
* **P:** Estou recebendo um erro `Octokit::NotFound` 404 na saída de depuração:
|
||||
* **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:** Verifique se as variáveis no arquivo `.env` estão corretas. Verifique se você não definiu variáveis idênticas em algum outro arquivo de variável de ambiente como `bash_profile`. Verifique as variáveis de ambiente que o seu aplicativo está usando adicionando instruções `puts` ao código do aplicativo e executando o código novamente. Por exemplo, para garantir que você tem a chave privada correta, adicione `puts PRIVATE_KEY` ao código do aplicativo:
|
||||
**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
|
||||
```
|
||||
|
||||
## Conclusão
|
||||
## Conclusion
|
||||
|
||||
Depois de analisar este guia, você aprendeu os componentes básicos para o desenvolvimento dos aplicativos GitHub! Para resumir, você:
|
||||
After walking through this guide, you've learned the basic building blocks for developing GitHub Apps! To review, you:
|
||||
|
||||
* Registrou um novo aplicativo GitHub
|
||||
* Usou a Smee para receber cargas de webhook
|
||||
* Executou um simples servidor web pelo Sinatra
|
||||
* Efetuou a autenticação como um aplicativo GitHub
|
||||
* Efetuou a autenticação como uma instalação
|
||||
* 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
|
||||
|
||||
## Próximas etapas
|
||||
## Next steps
|
||||
|
||||
Agora você tem um aplicativo GitHub em execução em um servidor. Ele ainda não faz nada de especial, mas confira algumas maneiras de personalizar seu modelo do Aplicativo do GitHub em outros [guias de início 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/).
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
title: Criar testes de CI com a API de verificações
|
||||
intro: 'Crie um servidor de integração contínua para executar testes usando um {% data variables.product.prodname_github_app %} e a API de verificações.'
|
||||
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: pt-BR
|
||||
ms.lasthandoff: 09/05/2022
|
||||
ms.locfileid: '147080988'
|
||||
---
|
||||
## Introdução
|
||||
## Introduction
|
||||
|
||||
Este guia lhe apresentará os [Aplicativos do Github](/apps/) e a [API de Verificações](/rest/reference/checks), que você usará para criar um servidor de CI (integração contínua) que executa testes.
|
||||
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.
|
||||
|
||||
A CI é uma prática de software que exige o commit do código em um repositório compartilhado. Fazer commits de códigos com frequência detecta erros com mais antecedência e reduz a quantidade de código necessária para depuração quando os desenvolvedores chegam à origem de um erro. As atualizações frequentes de código também facilitam o merge de alterações dos integrantes de uma equipe de desenvolvimento de software. Assim, os desenvolvedores podem se dedicar mais à gravação de códigos e se preocupar menos com erros de depuração ou conflitos de merge. 🙌
|
||||
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. 🙌
|
||||
|
||||
Um código de host do servidor de CI que executa testes de CI, como, por exemplo, linters de código (que verificam formatação de estilo), verificações de segurança, cobertura de código e outras verificações de novos commits de códigos em um repositório. OS ervidores de CI podem até criar e implementar código para servidores de treinamento ou produção. Para ver alguns exemplos dos tipos de testes de CI que você pode criar com um Aplicativo do GitHub, confira os [aplicativos de integração contínua](https://github.com/marketplace/category/continuous-integration) disponíveis no Marketplace do GitHub.
|
||||
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 %}
|
||||
|
||||
### Visão geral da API de verificação
|
||||
### Checks API overview
|
||||
|
||||
A [API de Verificações](/rest/reference/checks) permite que você configure testes de CI que são executados automaticamente em cada commit de código em um repositório. A API de Verificações relata informações detalhadas sobre cada verificação no GitHub na guia **Verificações** da solicitação de pull. Com a API de Verificações, você pode criar anotações com detalhes adicionais para linhas de código específicas. As anotações ficam visíveis na guia **Verificações**. Quando você cria uma anotação para um arquivo que faz parte da solicitação de pull, as anotações também são mostradas na guia **Arquivos alterados**.
|
||||
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.
|
||||
|
||||
Um _conjunto de verificação_ é um grupo de _execuções de verificação_ (testes de CI individuais). O conjunto e as execuções contêm _status_ que ficam visíveis em uma solicitação de pull no GitHub. Você pode usar os status para determinar quando um commit de código introduz erros. O uso desses status com [branches protegidos](/rest/reference/repos#branches) pode impedir que as pessoas mesclem solicitações de pull prematuramente. Confira "[Sobre branches protegidos](/github/administering-a-repository/about-protected-branches#require-status-checks-before-merging)" para obter mais detalhes.
|
||||
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.
|
||||
|
||||
A API de Verificações envia o [evento webhook `check_suite`](/webhooks/event-payloads/#check_suite) para todos os Aplicativos do GitHub instalados em um repositório sempre que o novo código é enviado por push para o repositório. Para receber todas as ações de evento da API de Verificações, o aplicativo deve ter a permissão `checks:write`. O GitHub cria eventos `check_suite` automaticamente para novos commits de código em um repositório usando o fluxo padrão, embora [atualize as preferências do repositório para conjuntos de verificação](/rest/reference/checks#update-repository-preferences-for-check-suites), se você desejar. Veja como funciona o fluxo-padrão:
|
||||
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. Sempre que alguém envia o código por push para o repositório, o GitHub envia o evento `check_suite` com uma ação de `requested` a todos os Aplicativos do GitHub instalados no repositório que têm a permissão `checks:write`. Este evento permite que os aplicativos saibam que o código foi enviado e que o GitHub criou um novo conjunto de verificações automaticamente.
|
||||
1. Quando seu aplicativo recebe esse evento, ele pode [adicionar execuções de verificação](/rest/reference/checks#create-a-check-run) a esse conjunto.
|
||||
1. As execuções de verificação podem incluir [anotações](/rest/reference/checks#annotations-object) exibidas em linhas 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.
|
||||
|
||||
**Neste guia, você aprenderá:**
|
||||
**In this guide, you’ll learn how to:**
|
||||
|
||||
* Parte 1: Configurar a estrutura para um servidor de CI usando a API de verificações.
|
||||
* Configurar um aplicativo GitHub como um servidor que recebe eventos de API de verificações.
|
||||
* Criar novas execuções de verificação para testes de CI quando um repositório recebe commits recém enviados.
|
||||
* Reexecutar a verificação quando um usuário solicita que a ação seja executada no GitHub.
|
||||
* Parte 2: Aproveitar a estrutura do servidor de CI que você criou adicionando um teste de CI de linter.
|
||||
* Atualizar uma execução de verificação com um `status`, `conclusion` e detalhes de `output`.
|
||||
* Criar anotações em linhas de código que são exibidas GitHub na guia **Verificações** e **Arquivos Alterados** de uma solicitação de pull.
|
||||
* Corrigir automaticamente as recomendações do linter expondo um botão "Corrigir isso" na guia **Verificações** da solicitação de pull.
|
||||
* 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 ter uma ideia do que seu servidor de CI da API de verificações fará quando você concluir este início rápido, confira a demonstração abaixo:
|
||||
To get an idea of what your Checks API CI server will do when you've completed this quickstart, check out the demo below:
|
||||
|
||||
![Demonstração do início rápido do servidor de CI da API de verificações](/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)
|
||||
|
||||
## Pré-requisitos
|
||||
## Prerequisites
|
||||
|
||||
Para começar, familiarize-se com os [Aplicativos do GitHub](/apps/), [Webhooks](/webhooks) e a [API de Verificações](/rest/reference/checks), caso ainda não esteja familiarizado. Você encontrará mais APIs nos [documentos da API REST](/rest). A API de Verificações também está disponível para uso no [GraphQL](/graphql), mas este início rápido se concentra na REST. Confira os objetos [Conjunto de Verificações](/graphql/reference/objects#checksuite) e [Verificar Execução](/graphql/reference/objects#checkrun) da GraphQL para obter mais detalhes.
|
||||
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.
|
||||
|
||||
Você usará a [linguagem de programação Ruby](https://www.ruby-lang.org/en/), o serviço de entrega de conteúdo do webhook [Smee](https://smee.io/), a [biblioteca Octokit.rb do Ruby](http://octokit.github.io/octokit.rb/) para a API REST do GitHub e o [framework Web Sinatra](http://sinatrarb.com/) para criar seu aplicativo de servidor de CI da API de Verificações.
|
||||
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.
|
||||
|
||||
Não é necessário ser um especialista em nenhuma dessas ferramentas ou conceitos para concluir este projeto. Este guia irá orientá-lo em todas as etapas necessárias. Antes de começar a criar testes de CI com a API de verificações, você deverá fazer o seguinte:
|
||||
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. Clone o repositório [Criação de testes de CI com a API de Verificações](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
|
||||
```
|
||||
|
||||
Dentro do diretório, você encontrará um arquivo `template_server.rb` com o código de modelo que será usado neste guia de início rápido e um arquivo `server.rb` com o código do projeto concluído.
|
||||
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 as etapas descritas no guia de início rápido "[Como configurar seu ambiente de desenvolvimento](/apps/quickstart-guides/setting-up-your-development-environment/)" para configurar e executar o servidor de aplicativos. **Observação:** em vez de [clonar o repositório de modelo do Aplicativo do GitHub](/apps/quickstart-guides/setting-up-your-development-environment/#prerequisites), use o arquivo `template_server.rb` no repositório clonado na etapa anterior deste início 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.
|
||||
|
||||
Se você concluiu um início rápido de Aplicativo do GitHub anteriormente, registre um _novo_ aplicativo do GitHub e inicie um novo canal do Smee para usar com este início 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.
|
||||
|
||||
Confira a seção [Solução de problemas](/apps/quickstart-guides/setting-up-your-development-environment/#troubleshooting) se você estiver tendo problemas ao configurar seu modelo de Aplicativo do 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. Criar a interface da API de verificações
|
||||
## Part 1. Creating the Checks API interface
|
||||
|
||||
Nesta parte, você adicionará o código necessário para receber eventos de webhook `check_suite` e criar e atualizar as execuções de verificação. Você também aprenderá como criar uma execução de verificação quando solicitou-se a verificação novamente no GitHub. Ao final desta seção, você poderá visualizar a execução de verificação que você criou em um pull request do 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.
|
||||
|
||||
Sua execução de verificação não realizará nenhuma verificação no código nesta seção. Você adicionará essa funcionalidade na [Parte 2: Criando o teste de CI do 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).
|
||||
|
||||
Você já deve ter um canal do Smee configurado que encaminha cargas do webhook para o seu servidor local. Seu servidor deve estar em execução e conectado ao aplicativo GitHub que você registrou e instalou em um repositório de teste. Se você ainda não concluiu as etapas em "[Configurando seu ambiente de desenvolvimento](/apps/quickstart-guides/setting-up-your-development-environment/)", faça isso antes de 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.
|
||||
|
||||
Vamos começar! Estas são as etapas que você concluirá na Parte 1:
|
||||
Let's get started! These are the steps you'll complete in Part 1:
|
||||
|
||||
1. [Atualizar as permissões de aplicativo](#step-11-updating-app-permissions)
|
||||
1. [Adicionar manipulação de evento](#step-12-adding-event-handling)
|
||||
1. [Criar uma execução de verificação](#step-13-creating-a-check-run)
|
||||
1. [Atualizar a execução de verificação](#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)
|
||||
|
||||
## Etapa 1.1. Atualizar as permissões do aplicativo
|
||||
## Step 1.1. Updating app permissions
|
||||
|
||||
Quando você [registrou seu aplicativo pela primeira vez](#prerequisites), aceitou as permissões padrão, o que significa que o aplicativo não tem acesso à maioria dos recursos. Para este exemplo, seu aplicativo precisará de permissão para ler e gravar verificações.
|
||||
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 atualizar as permissões do aplicativo:
|
||||
To update your app's permissions:
|
||||
|
||||
1. Selecione seu aplicativo na [página de configurações do aplicativo](https://github.com/settings/apps) e clique em **Permissões e Webhooks** na barra lateral.
|
||||
1. Na seção "Permissões", localize "Verificações" e selecione **Leitura e gravação** na lista suspensa de Acesso que está ao lado.
|
||||
1. Na seção "Assinar eventos", selecione **Verificar conjunto** e **Verificar execução** para assinar esses 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 %}
|
||||
|
||||
Ótimo! Seu aplicativo tem permissão para realizar as tarefas que você deseja que ele realize. Agora você pode adicionar o código para gerenciar os 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.
|
||||
|
||||
## Etapa 1.2. Adicionar manipulação de evento
|
||||
## Step 1.2. Adding event handling
|
||||
|
||||
Agora que o aplicativo está inscrito nos eventos **Verificar conjunto** e **Verificar execução**, ele começará a receber os webhooks [`check_suite`](/webhooks/event-payloads/#check_suite) e [`check_run`](/webhooks/event-payloads/#check_run). O GitHub envia as cargas de webhook como solicitações `POST`. Como você encaminhou o conteúdo do webhook do Smee para o `http://localhost/event_handler:3000`, o servidor receberá o conteúdo da solicitação `POST` na rota `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.
|
||||
|
||||
Uma rota `post '/event_handler'` vazia já está incluída no arquivo `template_server.rb`, que você baixou na seção [Pré-requisitos](#prerequisites). O encaminhamento vazio tem a seguinte forma:
|
||||
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 @@ Uma rota `post '/event_handler'` vazia já está incluída no arquivo `template_
|
|||
end
|
||||
```
|
||||
|
||||
Use essa rota para tratar o evento `check_suite` adicionando o seguinte código:
|
||||
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 enviado pelo GitHub inclui um cabeçalho de solicitação chamado `HTTP_X_GITHUB_EVENT`, que indica o tipo de evento na solicitação `POST`. Nesse momento, você só está interessado em eventos do tipo `check_suite`, que são emitidos quando um novo conjunto de verificação é criado. Cada evento tem um campo `action` adicional que indica o tipo de ação que disparou os eventos. Para `check_suite`, o campo `action` pode ser `requested`, `rerequested` ou `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`.
|
||||
|
||||
A ação `requested` solicita uma execução de verificação sempre que o código é enviado por push para o repositório, e a ação `rerequested` solicita que você execute novamente uma verificação do código que já está no repositório. Como as ações `requested` e `rerequested` exigem a criação de uma execução de verificação, você chamará um auxiliar com o nome `create_check_run`. Vamos escrever esse método agora.
|
||||
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.
|
||||
|
||||
## Etapa 1.3. Criar uma execução de verificação
|
||||
## Step 1.3. Creating a check run
|
||||
|
||||
Você adicionará esse novo método como [auxiliar do Sinatra](https://github.com/sinatra/sinatra#helpers) caso queira que outras rotas também o usem. Em `helpers do`, adicione 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
|
||||
```
|
||||
|
||||
Esse código chama o ponto de extremidade "[Criar uma execução de verificação](/rest/reference/checks#create-a-check-run)" usando o [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 criar uma execução de verificação, apenas dois parâmetros de entrada são necessários: `name` e `head_sha`. Usaremos o [RuboCop](https://rubocop.readthedocs.io/en/latest/) para implementar o teste de CI mais adiante neste início rápido e é por isso que o nome "Octo RuboCop" é usado aqui, mas você pode escolher qualquer nome que desejar para a execução de verificação.
|
||||
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.
|
||||
|
||||
Você só está fornecendo os parâmetros necessários agora para que a funcionalidade básica funcione, mas você irá atualizar a verificação de execução posteriormente enquanto coleta mais informações sobre a verificação de execução. Por padrão, o GitHub define `status` como `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`.
|
||||
|
||||
O GitHub cria uma execução de verificação para uma SHA de commit específica e é por isso que `head_sha` é um parâmetro necessário. Você pode encontrar commit SHA na carga do webhook. Embora você esteja apenas criando uma execução de verificação para o evento `check_suite` no momento, é bom saber que o `head_sha` está incluído nos objetos `check_suite` e `check_run` na carga do evento.
|
||||
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.
|
||||
|
||||
No código acima, você está usando o [operador ternário](https://ruby-doc.org/core-2.3.0/doc/syntax/control_expressions_rdoc.html#label-Ternary+if), que funciona como uma instrução `if/else`, para verificar se o conteúdo contém um objeto `check_run`. Se isso acontecer, você lerá o `head_sha` do objeto `check_run`, caso contrário, você o lerá do 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 testar esse código, reinicie o servidor a partir do seu 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 %}
|
||||
|
||||
Agora abra um pull request no repositório em que você instalou seu aplicativo. Seu aplicativo deve responder, criando uma verificação executada em seu pull request. Clique na guia **Verificações** e você verá algo assim:
|
||||
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:
|
||||
|
||||
![Execução de verificação enfileirada](/assets/images/github-apps/github_apps_queued_check_run.png)
|
||||
![Queued check run](/assets/images/github-apps/github_apps_queued_check_run.png)
|
||||
|
||||
Se você vir outros aplicativos na guia Verificações, significa que você tem outros aplicativos instalados em seu repositório que têm acesso de **Leitura e gravação** às verificações e que estão inscritos nos eventos **Verificar conjunto** e **Verificar execução**.
|
||||
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.
|
||||
|
||||
Ótimo! Você disse ao GitHub para criar uma execução de verificação. Veja que o status de execução de verificação está definido como `queued` ao lado de um ícone amarelo. Em seguida, você irá aguardar que o GitHub crie a execução de verificação e atualize seu status.
|
||||
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.
|
||||
|
||||
## Etapa 1.4. Atualizar a execução de verificação
|
||||
## Step 1.4. Updating a check run
|
||||
|
||||
Quando o método `create_check_run` é executado, ele solicita que GitHub crie uma execução de verificação. Quando o GitHub terminar de criar a execução de verificação, você receberá o evento de webhook `check_run` com a ação `created`. Esse evento é o sinal para começar a executar a verificação.
|
||||
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.
|
||||
|
||||
É interessante atualizar o manipulador de eventos para procurar a ação `created`. Enquanto estiver atualizando o manipulador de eventos, você pode adicionar uma condição para a ação `rerequested`. Quando alguém executa novamente um único teste no GitHub clicando no botão "Executar novamente", o GitHub envia o evento de execução de verificação `rerequested` para seu aplicativo. Quando uma execução de verificação for `rerequested`, você reiniciará o processo e criará uma execução de verificação.
|
||||
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 uma condição para o evento `check_run` na rota `post '/event_handler'`, adicione o seguinte código em `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
|
||||
```
|
||||
|
||||
O GitHub envia todos os eventos para execuções de verificação `created` para cada aplicativo instalado em um repositório que tenha as permissões de verificação necessárias. Isso significa que seu aplicativo receberá uma verificação que será executada por outros aplicativos. Uma execução de verificação `created` é um pouco diferente de um conjunto de verificação `requested` ou `rerequested`, que o GitHub envia apenas para aplicativos que estão sendo solicitados a executar uma verificação. O código acima procura o ID do aplicativo da execução de verificação. Isto filtra todas as execuções de verificação de outros aplicativos no repositório.
|
||||
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.
|
||||
|
||||
Em seguida, você escreverá o método `initiate_check_run`, que é o local em que você atualizará o status da execução de verificação e se preparará para iniciar o teste 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.
|
||||
|
||||
Nesta seção, você ainda não iniciará o teste de CI, mas examinará como atualizar o status da execução de verificação de `queued` para `pending` e depois de `pending` para `completed` para ver o fluxo geral de uma execução de verificação. Na "[Parte 2: Criando o teste de CI do Octo RuboCop](#part-2-creating-the-octo-rubocop-ci-test)", você adicionará o código que realmente executará o teste 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 criar o método `initiate_check_run` e atualizar o status da execução de verificação. Adicione o seguinte código à seção auxiliar:
|
||||
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
|
||||
```
|
||||
|
||||
O código acima chama o ponto de extremidade da API "[Atualizar uma execução de verificação](/rest/reference/checks#update-a-check-run)" usando o [método Octokit `update_check_run`](https://rdoc.info/gems/octokit/Octokit%2FClient%2FChecks:update_check_run) para atualizar a execução de verificação que você já criou.
|
||||
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.
|
||||
|
||||
Veja o que este código está fazendo. Primeiro, ele atualiza o status da execução de verificação para `in_progress` e define implicitamente a hora `started_at` com a hora atual. Na [Parte 2](#part-2-creating-the-octo-rubocop-ci-test) deste início rápido, você adicionará um código que inicia um teste de CI real em `***** RUN A CI TEST *****`. Por enquanto, você sairá da seção como um espaço reservado, para que o código que o segue apenas simule que o processo de CI seja bem-sucedido e todos os testes sejam aprovados. Por fim, o código atualiza o status da execução da verificação novamente para `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`.
|
||||
|
||||
Você observará nos documentos de "[Atualizar uma execução de verificação](/rest/reference/checks#update-a-check-run)" que, quando você fornece um status `completed`, os parâmetros `conclusion` e `completed_at` são necessários. O `conclusion` resume o resultado de uma execução de verificação e pode ser `success`, `failure`, `neutral`, `cancelled`, `timed_out` ou `action_required`. Você definirá a conclusão como `success`, a hora `completed_at` com a hora atual, e o status como `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`.
|
||||
|
||||
Você também pode fornecer mais informações sobre o que a sua verificação está fazendo, mas você poderá fazer isso na próxima seção. Vamos testar esse código executando `template_server.rb`novamente:
|
||||
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
|
||||
```
|
||||
|
||||
Vá até sua solicitação de pull aberta e clique na guia **Verificações**. Clique no botão "Executar tudo novamente" no canto superior esquerdo. Você verá a execução de verificação passar de `pending` para `in_progress` e terminar com `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`:
|
||||
|
||||
![Execução de verificação concluída](/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. Criar o teste de CI do Octo RuboCop
|
||||
## Part 2. Creating the Octo RuboCop CI test
|
||||
|
||||
O [RuboCop](https://rubocop.readthedocs.io/en/latest/) é um formatador e um linter de código Ruby. Ele verifica o código Ruby para garantir que ele esteja em conformidade com o "[Guia de Estilo do Ruby](https://github.com/rubocop-hq/ruby-style-guide)". O RuboCop tem três funções principais:
|
||||
[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:
|
||||
|
||||
* Linting para verificação do estilo do código
|
||||
* Formatação de código
|
||||
* Substitui os recursos nativos de linting do Ruby usando `ruby -w`
|
||||
* Linting to check code style
|
||||
* Code formatting
|
||||
* Replaces the native Ruby linting capabilities using `ruby -w`
|
||||
|
||||
Agora que a interface foi criada para receber eventos da API de verificações e criar execuções de verificação, você pode criar uma execução de verificação que implemente um teste de 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.
|
||||
|
||||
Seu aplicativo irá executar o RuboCop no servidor de CI e irá criar uma execuções de verificação (neste caso, testes de CI), que relatarão os resultados que o RuboCop relata para o 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.
|
||||
|
||||
A API de verificações permite que você relate informações valiosas sobre cada execução de verificação, incluindo status, imagens, resumos, anotações e ações solicitadas.
|
||||
The Checks API allows you to report rich details about each check run, including statuses, images, summaries, annotations, and requested actions.
|
||||
|
||||
As anotações são informações sobre linhas específicas de código em um repositório. Uma anotação permite que você identifique e visualize as partes exatas do código para as quais você gostaria de mostrar informações adicionais. Essas informações podem ser qualquer coisa: por exemplo, um comentário, um erro ou um aviso. Este início rápido usa anotações para visualizar erros no 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 aproveitar as ações solicitadas, os desenvolvedores de aplicativos podem criar botões na guia **Verificações** das solicitações de pull. Quando alguém clica em um desses botões, o clique envia um evento `requested_action` `check_run` para o Aplicativo do GitHub. A ação tomada pelo aplicativo é completamente configurável pelo desenvolvedor do aplicativo. Este início rápido irá orientá-lo no processo de adição de um botão que permite aos usuários solicitar que o RuboCop corrija os erros que encontrar. O RuboCop dá suporte à correção automática de erros usando uma opção de linha de comando e você configurará a opção `requested_action` para aproveitar essa opção.
|
||||
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.
|
||||
|
||||
Vamos começar! Estas são as etapas que você concluirá nesta seção:
|
||||
Let's get started! These are the steps you'll complete in this section:
|
||||
|
||||
1. [Adicionar um arquivo do Ruby](#step-21-adding-a-ruby-file)
|
||||
1. [Clonagem de repositório](#step-22-cloning-the-repository)
|
||||
1. [Executar o RuboCop](#step-23-running-rubocop)
|
||||
1. [Coletar erros do RuboCop](#step-24-collecting-rubocop-errors)
|
||||
1. [Atualizar a execução de verificação com resultados dos testes de CI](#step-25-updating-the-check-run-with-ci-test-results)
|
||||
1. [Corrigir erros do RuboCop automaticamente](#step-26-automatically-fixing-rubocop-errors)
|
||||
1. [Dicas de segurança](#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)
|
||||
|
||||
## Etapa 2.1. Adicionar um arquivo do Ruby
|
||||
## Step 2.1. Adding a Ruby file
|
||||
|
||||
Você pode passar arquivos específicos ou diretórios inteiros para o RuboCop verificar. Nesse início rápido, você irá executar o RuboCop em um diretório inteiro. Como RuboCop verifica apenas códigos Ruby, será necessário pelo menos um arquivo Ruby no seu repositório que contém erros. O arquivo de exemplo fornecido abaixo contém alguns erros. Adicione este arquivo do Ruby de exemplo ao repositório em que seu aplicativo está instalado (nomeie o arquivo com uma extensão `.rb`, como em `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
|
||||
```
|
||||
|
||||
## Etapa 2.2. Clonagem de repositório
|
||||
## Step 2.2. Cloning the repository
|
||||
|
||||
O RuboCop está disponível como um utilitário da linha de comando. Isso significa que o seu aplicativo GitHub deverá clonar uma cópia local do repositório no servidor da CI para que RuboCop possa analisar os arquivos. Para executar operações Git em seu aplicativo Ruby, use a gem [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.
|
||||
|
||||
O `Gemfile` no repositório `building-a-checks-api-ci-server` já inclui a gem ruby-git e você a instalou quando executou `bundle install` nas [etapas de pré-requisito](#prerequisites). Para usar a gem, adicione este código à parte superior do arquivo `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'
|
||||
```
|
||||
|
||||
Seu aplicativo deve permissão de leitura para "Conteúdo do repositório" para clonar um repositório. Mais adiante neste início rápido, você deverá fazer push de conteúdo para o GitHub, o que exige permissão de gravação. Defina a permissão "Conteúdo do repositório" do seu aplicativo como **Leitura e gravação** agora para que você não precise atualizá-lo novamente mais tarde. Para atualizar as permissões do aplicativo:
|
||||
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. Selecione seu aplicativo na [página de configurações do aplicativo](https://github.com/settings/apps) e clique em **Permissões e Webhooks** na barra lateral.
|
||||
1. Na seção "Permissões", localize "Conteúdo do repositório" e selecione **Leitura e gravação** na lista suspensa "Acesso" ao lado.
|
||||
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 um repositório usando as permissões do Aplicativo do GitHub, você pode usar o token de instalação do aplicativo (`x-access-token:<token>`) mostrado no exemplo abaixo:
|
||||
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
|
||||
```
|
||||
|
||||
O código acima clone um repositório por HTTP. Isto exige o nome completo do repositório, que inclui o proprietário do repositório (usuário ou organização) e o nome do repositório. Por exemplo, o repositório [octocat Hello-World](https://github.com/octocat/Hello-World) tem o nome completo `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`.
|
||||
|
||||
Depois que seu aplicativo clonar o repositório, ele precisará efetuar pull das alterações de código mais recentes e fazer check-out de um ref do Git específico. O código para fazer tudo isso se ajustará perfeitamente ao seu próprio método. Para realizar essas operações, o método precisa do nome e nome completo do repositório e que o ref faça checkout. O ref pode ser um commit SHA, branch ou tag. Adicione o seguinte novo método à seção de método auxiliar em `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
|
||||
```
|
||||
|
||||
O código acima usa a gem `ruby-git` para clonar o repositório usando o token de instalação do aplicativo. Esse código clona o código no mesmo diretório que `template_server.rb`. Para executar comandos Git no repositório, o código deve alterar para o diretório do repositório. Antes de alterar os diretórios, o código armazena o diretório de trabalho atual em uma variável (`pwd`) para lembrar o local para retornar antes de sair do 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.
|
||||
|
||||
No diretório do repositório, esse código busca e mescla as alterações mais recentes (`@git.pull`), faz check-out do ref (`@git.checkout(ref)`) e altera o diretório de volta para o diretório de trabalho 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`).
|
||||
|
||||
Agora você tem um método que clona um repositório e faz check-out de um ref. Em seguida, você precisa adicionar código para obter os parâmetros de entrada necessários e chamar o novo método `clone_repository`. Adicione o seguinte código sob o comentário `***** RUN A CI TEST *****` em seu método auxiliar `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)
|
||||
```
|
||||
|
||||
O código acima obtém o nome completo do repositório e o SHA principal do commit do conteúdo do webhook `check_run`.
|
||||
The code above gets the full repository name and the head SHA of the commit from the `check_run` webhook payload.
|
||||
|
||||
## Etapa 2.3. Executar o RuboCop
|
||||
## Step 2.3. Running RuboCop
|
||||
|
||||
Ótimo! Você está clonando o repositório e criando execuções de verificação usando seu servidor de CI. Agora você entrará no âmago dos detalhes do [linter do RuboCop](https://docs.rubocop.org/rubocop/usage/basic_usage.html#code-style-checker) e das [anotações da API de Verificações](/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).
|
||||
|
||||
O código a seguir executa RuboCop e salva os erros do código de estilo no formato JSON. Adicione este código abaixo da chamada ao `clone_repository` que você adicionou na [etapa anterior](#step-22-cloning-the-repository) e acima do código que atualiza a execução de verificação para concluir.
|
||||
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
|
||||
```
|
||||
|
||||
O código acima executa o RuboCop em todos os arquivos no diretório do repositório. A opção `--format json` é uma forma útil de salvar uma cópia dos resultados do linting em um formato que possa ser analisado pelo computador. Confira os [documentos do RuboCop](https://docs.rubocop.org/rubocop/formatters.html#json-formatter) para obter detalhes e um exemplo do 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.
|
||||
|
||||
Como esse código armazena os resultados do RuboCop em uma variável `@report`, ele pode remover com segurança o check-out do repositório. Esse código também analisa o JSON para que você possa acessar facilmente as chaves e os valores em seu Aplicativo do GitHub usando a variável `@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 %}
|
||||
|
||||
**Observação:** o comando usado para remover o repositório (`rm -rf`) não pode ser desfeito. Confira [Etapa 2.7. Dicas de segurança](#step-27-security-tips) para saber como verificar webhooks de comandos maliciosos injetados que podem ser usados para remover um diretório diferente do que era pretendido pelo seu aplicativo. Por exemplo, se um ator malicioso enviasse um webhook com o nome de repositório `./`, seu aplicativo removeria o diretório raiz. 😱 Se por algum motivo você _não_ estiver usando o método `verify_webhook_signature` (que está incluído no `template_server.rb`) para validar o remetente do webhook, verifique se o nome do repositório é 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 %}
|
||||
|
||||
Você pode testar se este código funciona e ver os erros relatados pelo RuboCop na saída de depuração do seu servidor. Reinicie o servidor `template_server.rb` e crie uma solicitação de pull no repositório em que você está testando seu aplicativo:
|
||||
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
|
||||
```
|
||||
|
||||
Você deve ver os erros de linting na saída de depuração, embora não sejam impressos com a formatação. Você pode usar uma ferramenta da Web como o [formatador JSON](https://jsonformatter.org/) para formatar a saída JSON como esta saída de erro do linting formatada:
|
||||
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 @@ Você deve ver os erros de linting na saída de depuração, embora não sejam i
|
|||
}
|
||||
```
|
||||
|
||||
## Etapa 2.4. Coletar erros do RuboCop
|
||||
## Step 2.4. Collecting RuboCop errors
|
||||
|
||||
A variável `@output` contém os resultados JSON analisados do relatório do RuboCop. Conforme mostrado acima, os resultados contêm uma seção `summary` que seu código pode usar para determinar rapidamente se há erros. O código a seguir definirá a conclusão da execução de verificação como `success` quando não houver erros relatados. O RuboCop relata erros para cada arquivo na matriz `files`, portanto, se houver erros, você precisará extrair alguns dados do objeto de arquivo.
|
||||
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.
|
||||
|
||||
A API de verificação permite que você crie anotações para linhas específicas do código. Ao criar ou atualizar uma execução de verificação, você pode adicionar anotações. Neste início rápido, você está [atualizando a execução de verificação](/rest/reference/checks#update-a-check-run) com anotações.
|
||||
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.
|
||||
|
||||
A API de verificação limita o número de anotações a um máximo de 50 por solicitação de API. Para criar mais de 50 anotações, você precisa fazer várias solicitações para o ponto de extremidade [Atualizar uma execução de verificação](/rest/reference/checks#update-a-check-run). Por exemplo, para criar 105 anotações, você precisará chamar o ponto de extremidade [Atualizar uma execução de verificação](/rest/reference/checks#update-a-check-run) três vezes. Cada uma das duas primeiras solicitações teria 50 anotações e a terceira solicitação incluiria as cinco anotações restantes. Cada vez que você atualizar a execução de verificação, as anotações são anexadas à lista de anotações que já existem para a execução de verificação.
|
||||
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.
|
||||
|
||||
Uma execução de verificação espera anotações como um array de objetos. Cada objeto de anotação deve incluir o `path`, `start_line`, `end_line`, `annotation_level` e `message`. O RuboCop também fornece o `start_column`e `end_column`, portanto, você pode incluir esses parâmetros opcionais na anotação. As anotações só dão suporte a `start_column` e `end_column` na mesma linha. Confira a documentação de referência do [objeto `annotations`](/rest/reference/checks#annotations-object-1) para obter detalhes.
|
||||
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.
|
||||
|
||||
Você irá extrair as informações necessárias do RuboCop para criar cada anotação. Acrescente o seguinte código ao código adicionado na [seção 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 o número total de anotações a 50. Mas você pode modificar este código para atualizar a verificação de execução para cada lote de 50 anotações. O código acima inclui a variável `max_annotations` que define o limite como 50, que é usado no loop que itera nas ofensas.
|
||||
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.
|
||||
|
||||
Quando a `offense_count` é zero, o teste de CI é um `success`. Se houver erros, esse código definirá a conclusão como `neutral` para evitar a imposição estrita de erros de linters de código. Mas você pode alterar a conclusão para `failure` se quiser garantir que o conjunto de verificação falhe quando houver erros 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.
|
||||
|
||||
Quando erros são relatados, o código acima itera na matriz `files` no relatório do RuboCop. Para cada arquivo, ele extrai o caminho do arquivo e define o nível de anotação como `notice`. Você pode ir ainda mais adiante e definir níveis de aviso específicos para cada tipo de [RuboCop Cop](https://docs.rubocop.org/rubocop/cops.html), mas para manter as coisas mais simples neste início rápido, todos os erros são definidos como um nível de `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`.
|
||||
|
||||
Esse código também itera em cada erro na matriz de `offenses` e coleta o local da mensagem de erro e ofensa. Depois de extrair as informações necessárias, o código cria uma anotação para cada erro e as armazena na matriz `annotations`. Como as anotações só dão suporte a colunas de início e fim na mesma linha, `start_column`e `end_column` só são adicionadas ao objeto `annotation` se os valores de linha inicial e final forem os mesmos.
|
||||
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.
|
||||
|
||||
Esse código ainda não cria uma anotação para a execução de verificação. Você irá adicionar esse código na próxima seção.
|
||||
This code doesn't yet create an annotation for the check run. You'll add that code in the next section.
|
||||
|
||||
## Etapa 2.5. Atualizar a execução de verificação com resultados dos testes de CI
|
||||
## Step 2.5. Updating the check run with CI test results
|
||||
|
||||
Cada execução de verificação do GitHub contém um objeto `output` que inclui um `title`, `summary`, `text`, `annotations` e `images`. Os parâmetros `summary` e `title` são os únicos necessários para o `output`, mas estes sozinhos não oferecem muitos detalhes, portanto, este início rápido também adiciona o `text` e `annotations`. Aqui, o código não adiciona uma imagem, mas sinta-se à vontade para adicionar uma, se desejar!
|
||||
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!
|
||||
|
||||
Para o `summary`, este exemplo usa as informações de resumo do RuboCop e adiciona algumas linhas novas (`\n`) para formatar a saída. Você pode personalizar o que adicionar ao parâmetro `text`, mas este exemplo define o parâmetro `text` com a versão do RuboCop. Para definir `summary` e `text`, acrescente esse código ao código que você adicionou na [seção 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']}"
|
||||
```
|
||||
|
||||
Agora você tem todas as informações de que precisa para atualizar sua execução de verificação. Na [primeira metade deste início rápido](#step-14-updating-a-check-run), você adicionou este código para definir o status da execução de verificação como `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 @@ Agora você tem todas as informações de que precisa para atualizar sua execuç
|
|||
)
|
||||
```
|
||||
|
||||
Você precisará atualizar esse código para usar a variável `conclusion` definida com base nos resultados do RuboCop (para `success` ou `neutral`). Você pode atualizar o código com o seguinte:
|
||||
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 @@ Você precisará atualizar esse código para usar a variável `conclusion` defin
|
|||
)
|
||||
```
|
||||
|
||||
Agora que você está definindo uma conclusão com base no status do teste CI e que você adicionou a saída dos resultados do RuboCop, você criou um teste de CI! Parabéns. 🙌
|
||||
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. 🙌
|
||||
|
||||
O código acima também adiciona um recurso ao servidor de CI chamado [ações solicitadas](https://developer.github.com/changes/2018-05-23-request-actions-on-checks/) por meio do objeto `actions`. {% ifversion fpt or ghec %}(Observe que isso não está relacionado ao [GitHub Actions](/actions)). {% endif %} As ações solicitadas adicionam um botão na guia **Verificações** no GitHub, que permite que alguém solicite que a execução de verificação realize uma ação adicional. A ação adicional é completamente configurável pelo seu aplicativo. Por exemplo, uma vez que o RuboCop tem um recurso para corrigir automaticamente os erros que encontra no código Ruby, seu servidor de CI pode usar um botão de ações solicitadas para permitir que as pessoas solicitem correções automáticas de erros. Quando alguém clica no botão, o aplicativo recebe o evento `check_run` com uma ação `requested_action`. Cada ação solicitada tem um `identifier` que o aplicativo usa para determinar qual botão foi clicado.
|
||||
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.
|
||||
|
||||
O código acima ainda não exige que o RuboCop corrija erros automaticamente. Você irá adicionar isso na próxima seção. Mas primeiro, dê uma olhada no teste de CI que você acabou de criar reiniciando o servidor `template_server.rb` e criando uma solicitação de pull:
|
||||
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
|
||||
```
|
||||
|
||||
As anotações aparecerão na guia **Verificações**.
|
||||
The annotations will show up in the **Checks** tab.
|
||||
|
||||
![Anotações da execução de verificação na aba verificações](/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)
|
||||
|
||||
Observe o botão "Corrija isso" que você criou ao adicionar uma ação solicitada.
|
||||
Notice the "Fix this" button that you created by adding a requested action.
|
||||
|
||||
![Botão de ação solicitada de execução de verificação](/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)
|
||||
|
||||
Se as anotações estiverem relacionadas a um arquivo já incluído na PR, as anotações também aparecerão na guia **Arquivos alterados**.
|
||||
If the annotations are related to a file already included in the PR, the annotations will also show up in the **Files changed** tab.
|
||||
|
||||
![Anotações da execução de verificação na aba Arquivos alterados](/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)
|
||||
|
||||
## Etapa 2.6. Corrigir erros do RuboCop automaticamente
|
||||
## Step 2.6. Automatically fixing RuboCop errors
|
||||
|
||||
Se você chegou até aqui, parabéns! 👏 Você já criou um teste de CI. Nesta seção, você irá adicionar mais um recurso que usa RuboCop para corrigir automaticamente os erros que encontra. Você já adicionou o botão "Corrigir isso" na [seção anterior](#step-25-updating-the-check-run-with-ci-test-results). Agora você adicionará o código para manipular o evento de execução de verificação `requested_action` que é disparado quando alguém clicar no botão "Corrigir isso".
|
||||
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.
|
||||
|
||||
A ferramenta RuboCop [oferece](https://docs.rubocop.org/rubocop/usage/basic_usage.html#auto-correcting-offenses) a opção `--auto-correct` de linha de comando para corrigir automaticamente os erros encontrados. Quando você usa o recurso `--auto-correct`, as atualizações são aplicadas aos arquivos locais no servidor. Você deverá fazer push das alterações no GitHub depois que o RuboCop fizer sua mágica.
|
||||
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 fazer push para um repositório, seu aplicativo deve ter permissões de "conteúdo do repositório". Você define essa permissão de volta na [Etapa 2.2. Clonando o repositório](#step-22-cloning-the-repository) para **Leitura e gravação**, para deixar tudo pronto.
|
||||
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 fazer commit dos arquivos, o Git deve saber qual [nome de usuário](/github/getting-started-with-github/setting-your-username-in-git/) e [email](/articles/setting-your-commit-email-address-in-git/) associar ao commit. Adicione mais duas variáveis de ambiente em seu arquivo `.env` para armazenar as configurações de nome (`GITHUB_APP_USER_NAME`) e email (`GITHUB_APP_USER_EMAIL`). Seu nome pode ser o nome do seu aplicativo e o e-mail pode ser qualquer e-mail que desejar para este exemplo. Por exemplo:
|
||||
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
|
||||
```
|
||||
|
||||
Depois de atualizar o arquivo `.env` com o nome e o email do autor e do committer, você estará pronto para adicionar código para ler as variáveis de ambiente e definir a configuração do Git. Você irá adicionar esse código em breve.
|
||||
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.
|
||||
|
||||
Quando alguém clica no botão "Corrigir isso", seu aplicativo recebe o [webhook de execução de verificação](/webhooks/event-payloads/#check_run) com o tipo de ação `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.
|
||||
|
||||
Na [Etapa 1.4. Atualizando uma execução de verificação](#step-14-updating-a-check-run), você atualizou seu `event_handler` para lidar com a procura de ações no evento `check_run`. Você já tem uma instrução case para lidar com os tipos de ação `created` e `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
|
||||
```
|
||||
|
||||
Adicione outra instrução `when` após o caso `rerequested` para manipular o evento `rerequested_action`:
|
||||
Add another `when` statement after the `rerequested` case to handle the `rerequested_action` event:
|
||||
|
||||
``` ruby
|
||||
when 'requested_action'
|
||||
take_requested_action
|
||||
```
|
||||
|
||||
Esse código chama um novo método que manipulará todos os eventos `requested_action` para seu aplicativo. Adicione o seguinte método à seção de métodos auxiliares do seu 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
|
||||
```
|
||||
|
||||
O código acima clona um repositório, assim como o código que você adicionou na [Etapa 2.2. Clonando o repositório](#step-22-cloning-the-repository). Uma instrução `if` verifica se o identificador da ação solicitada corresponde ao identificador do botão do RuboCop (`fix_rubocop_notices`). Quando eles correspondem, o código clona o repositório, define o nome de usuário e o email do Git e executa o RuboCop com a opção `--auto-correct`. A opção `--auto-correct` aplica as alterações aos arquivos do servidor de CI local automaticamente.
|
||||
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.
|
||||
|
||||
Os arquivos são alterados localmente, mas você ainda deverá enviá-los para o GitHub. Você usará a gem útil `ruby-git` novamente para fazer commit de todos os arquivos. O Git tem um único comando que prepara todos os arquivos modificados ou excluídos e faz o commit deles: `git commit -a`. Para fazer a mesma coisa usando `ruby-git`, o código acima usa o método `commit_all`. Em seguida, o código envia por push os arquivos do commit para o GitHub usando o token de instalação, usando o mesmo método de autenticação que o comando do Git `clone`. Por fim, ele remove o diretório do repositório para garantir que o diretório de trabalho seja preparado para o próximo 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.
|
||||
|
||||
É isso! O código que você escreveu agora conclui o servidor de CI da API de verificação. 💪 Reinicie o servidor `template_server.rb` e crie uma solicitação de pull:
|
||||
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 %}
|
||||
|
||||
Desta vez, clique no botão "Corrigir isso" para corrigir automaticamente os erros que o RuboCop encontrou na guia **Verificações**.
|
||||
This time, click the "Fix this" button to automatically fix the errors RuboCop found from the **Checks** tab.
|
||||
|
||||
Na guia **Commits**, você verá um commit novinho feito pelo nome de usuário definido na configuração do Git. Talvez seja necessário atualizar seu navegador para ver a atualização.
|
||||
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.
|
||||
|
||||
![Um novo commit para corrigir as notificações do Octo RuboCop automaticamente](/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)
|
||||
|
||||
Como um novo commit foi enviado por push para o repositório, você verá um novo conjunto de verificação para o Octo RuboCop na guia **Verificações**. Mas, desta vez, não há erros porque o RuboCop corrigiu todos eles. 🎉
|
||||
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. 🎉
|
||||
|
||||
![Nenhum erro de conjunto de verificação ou de execução de verificação](/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)
|
||||
|
||||
Encontre o código concluído para o aplicativo que acabou de criar no arquivo `server.rb` do repositório [Criar testes de CI com a API de Verificações](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.
|
||||
|
||||
## Etapa 2.7. Dicas de segurança
|
||||
## Step 2.7. Security tips
|
||||
|
||||
O modelo de código do aplicativo GitHub já possui um método para verificar as cargas do webhook de entrada para garantir que sejam de uma fonte confiável. Se você não estiver validando as cargas do webhook, você deverá garantir que, quando nomes do repositório estiverem incluídos na carga do webhook, este não conterá comandos arbitrários que possam ser usados maliciosamente. O código abaixo valida que o nome do repositório contém apenas caracteres alfabéticos latinos, hifens e sublinhados. Para fornecer um exemplo completo, o código completo `server.rb` disponível no [repositório complementar](https://github.com/github-developer/creating-ci-tests-with-the-checks-api) deste início rápido inclui o método de validação de conteúdo de webhook de entrada e essa verificação para verificar o nome do repositório.
|
||||
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
|
||||
```
|
||||
|
||||
## Solução de problemas
|
||||
## Troubleshooting
|
||||
|
||||
Aqui estão alguns problemas comuns e algumas soluções sugeridas. Se você tiver qualquer outro problema, poderá pedir ajuda ou orientação em {% 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:** Meu aplicativo não está enviando código por push para o GitHub. Eu não vejo as correções que o RuboCop faz automaticamente!
|
||||
* **Q:** My app isn't pushing code to GitHub. I don't see the fixes that RuboCop automatically makes!
|
||||
|
||||
**R:** Verifique se você tem permissões de **Leitura e gravação** para "Conteúdo do repositório" e se está clonando o repositório com o token de instalação. Confira a [Etapa 2.2. Clonando o repositório](#step-22-cloning-the-repository) para obter detalhes.
|
||||
**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:** Vejo um erro na saída de depuração `template_server.rb` relacionado à clonagem do meu repositório.
|
||||
* **Q:** I see an error in the `template_server.rb` debug output related to cloning my repository.
|
||||
|
||||
**R:** Se você vir o seguinte erro, significa que você não excluiu o check-out do repositório de um ou ambos os métodos `initiate_check_run`e `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.:
|
||||
```
|
||||
|
||||
Compare seu código com o arquivo `server.rb` para ter o mesmo código nos métodos `initiate_check_run` e `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:** Novas execuções de verificação não aparecem na guia "Verificações" no GitHub.
|
||||
* **Q:** New check runs are not showing up in the "Checks" tab on GitHub.
|
||||
|
||||
**R:** Reinicie o Smee e execute novamente o `template_server.rb` servidor.
|
||||
**A:** Restart Smee and re-run your `template_server.rb` server.
|
||||
|
||||
* **P:** Não vejo o botão "Executar tudo novamente" na guia "Verificações" no GitHub.
|
||||
* **Q:** I do not see the "Re-run all" button in the "Checks" tab on GitHub.
|
||||
|
||||
**R:** Reinicie o Smee e execute novamente o `template_server.rb` servidor.
|
||||
**A:** Restart Smee and re-run your `template_server.rb` server.
|
||||
|
||||
## Conclusão
|
||||
## Conclusion
|
||||
|
||||
Depois ler este guia, você aprendeu os princípios básicos para usar a API de verificação para criar um servidor de CI! Para resumir, você:
|
||||
After walking through this guide, you've learned the basics of using the Checks API to create a CI server! To review, you:
|
||||
|
||||
* Configurou seu servidor para receber eventos de API de verificação e criar execuções de verificação.
|
||||
* Usou o RuboCop para verificar códigos nos repositórios e criar anotações para os erros.
|
||||
* Implementou uma ação solicitada que corrige os erros do linter automaticamente.
|
||||
* 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.
|
||||
|
||||
## Próximas etapas
|
||||
## Next steps
|
||||
|
||||
Aqui estão algumas ideias do que você pode fazer a seguir:
|
||||
Here are some ideas for what you can do next:
|
||||
|
||||
* Atualmente, o botão "Corrija isso" sempre é exibido. Atualize o código que você escreveu para exibir o botão "Corrija isso" somente quando o RuboCop encontrar erros.
|
||||
* Se preferir que o RuboCop não faça commit dos arquivos diretamente no branch principal, atualize o código para [criar uma solicitação de pull](/rest/reference/pulls#create-a-pull-request) com um novo branch com base no branch 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.
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
title: Usar a API do GitHub no seu aplicativo
|
||||
intro: Aprenda como configurar seu aplicativo para ouvir eventos e usar a biblioteca do Octokit para realizar operações da API 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: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
|
||||
ms.translationtype: HT
|
||||
ms.contentlocale: pt-BR
|
||||
ms.lasthandoff: 09/05/2022
|
||||
ms.locfileid: '145084001'
|
||||
---
|
||||
## Introdução
|
||||
## Introduction
|
||||
|
||||
Este guia irá ajudá-lo a criar um aplicativo GitHub e executá-lo em um servidor. O aplicativo que você criar adicionará uma etiqueta a todos os novos problemas abertos no repositório onde o aplicativo está instalado.
|
||||
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 projeto orientará você no seguinte:
|
||||
This project will walk you through the following:
|
||||
|
||||
* Programar seu aplicativo para ouvir eventos
|
||||
* Usar a biblioteca do Octokit.rb para realizar operações da API REST
|
||||
* Programming your app to listen for events
|
||||
* Using the Octokit.rb library to do REST API operations
|
||||
|
||||
{% data reusables.apps.app-ruby-guides %}
|
||||
|
||||
Uma concluídas as etapas, você estará pronto para desenvolver outros tipos de integrações usando o conjunto completo das APIS do GitHub. {% ifversion fpt or ghec %}Confira exemplos bem-sucedidos de aplicativos no [GitHub Marketplace](https://github.com/marketplace) e [Compatível com o 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 %}
|
||||
|
||||
## Pré-requisitos
|
||||
## Prerequisites
|
||||
|
||||
Você pode achar útil ter um entendimento básico do seguinte:
|
||||
You may find it helpful to have a basic understanding of the following:
|
||||
|
||||
* [Aplicativos GitHub](/apps/about-apps)
|
||||
* [GitHub Apps](/apps/about-apps)
|
||||
* [Webhooks](/webhooks)
|
||||
* [A linguagem de programação Ruby](https://www.ruby-lang.org/en/)
|
||||
* [APIs REST](/rest)
|
||||
* [The Ruby programming language](https://www.ruby-lang.org/en/)
|
||||
* [REST APIs](/rest)
|
||||
* [Sinatra](http://sinatrarb.com/)
|
||||
|
||||
Mas é possível acompanhar o processo em qualquer nível de experiência. Nós vamos nos conectar a informações de que você precisa ao longo do caminho!
|
||||
But you can follow along at any experience level. We'll link out to information you need along the way!
|
||||
|
||||
Antes de começar, você precisará fazer o seguinte:
|
||||
Before you begin, you'll need to do the following:
|
||||
|
||||
1. Clone o repositório [Como usar a API do GitHub no seu aplicativo](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
|
||||
```
|
||||
|
||||
Dentro do diretório, você encontrará um arquivo `template_server.rb` com o código de modelo que será usado neste guia de início rápido e um arquivo `server.rb` com o código do projeto concluído.
|
||||
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 as etapas descritas no guia de início rápido [Como configurar seu ambiente de desenvolvimento](/apps/quickstart-guides/setting-up-your-development-environment/) para configurar e executar o servidor de aplicativos `template_server.rb`. Se você já concluiu um guia de início rápido do Aplicativo do GitHub além do guia [Como configurar seu ambiente de desenvolvimento](/apps/quickstart-guides/setting-up-your-development-environment/), registre um _novo_ Aplicativo do GitHub e inicie um novo canal do Smee para usá-lo com este guia de início 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 guia de início rápido inclui o mesmo código `template_server.rb` do guia de início rápido [Como configurar seu ambiente de desenvolvimento](/apps/quickstart-guides/setting-up-your-development-environment/). **Observação:** ao acompanhar o guia de início rápido [Como configurar seu ambiente de desenvolvimento](/apps/quickstart-guides/setting-up-your-development-environment/), use os arquivos de projeto incluídos no repositório [Como usar a API do GitHub no seu aplicativo](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.
|
||||
|
||||
Confira a seção [Solução de problemas](/apps/quickstart-guides/setting-up-your-development-environment/#troubleshooting) se você estiver tendo problemas ao configurar seu modelo de Aplicativo do 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.
|
||||
|
||||
## Criar o aplicativo
|
||||
## Building the app
|
||||
|
||||
Agora que você está familiarizado com o código `template_server.rb`, crie um código que adiciona automaticamente o rótulo `needs-response` a todos os problemas em aberto no repositório no qual o aplicativo está instalado.
|
||||
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.
|
||||
|
||||
O arquivo `template_server.rb` contém o código do modelo de aplicativo que ainda não foi personalizado. Neste arquivo, você verá um espaço reservado para manipular eventos de webhook e outro código para inicializar um cliente 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 %}
|
||||
|
||||
**Observação:** `template_server.rb` contém muitos comentários sobre o código que complementam este guia e explicam detalhes técnicos adicionais. Você pode considerar útil ler os comentários do arquivo antes de seguir com esta seção, para obter uma visão geral de como o código funciona.
|
||||
**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.
|
||||
|
||||
O código personalizado final que você criará até o final deste guia é fornecido em [`server.rb`](https://github.com/github-developer/using-the-github-api-in-your-app/blob/master/server.rb). Mas espere até o final para olhar isso!
|
||||
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 %}
|
||||
|
||||
Estas são as etapas que você concluirá para criar seu primeiro aplicativo GitHub:
|
||||
These are the steps you'll complete to create your first GitHub App:
|
||||
|
||||
1. [Atualizar as permissões do aplicativo](#step-1-update-app-permissions)
|
||||
2. [Adicionar um tratamento de evento](#step-2-add-event-handling)
|
||||
3. [Criar um novo rótulo](#step-3-create-a-new-label)
|
||||
4. [Adicionar um tratamento de rótulo](#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)
|
||||
|
||||
## Etapa 1. Atualizar as permissões do aplicativo
|
||||
## Step 1. Update app permissions
|
||||
|
||||
Quando você [registrou seu aplicativo pela primeira vez](/apps/quickstart-guides/setting-up-your-development-environment/#step-2-register-a-new-github-app), aceitou as permissões padrão, o que significa que o aplicativo não tem acesso à maioria dos recursos. Para este exemplo, seu aplicativo precisará de permissão para ler problemas e escrever 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 atualizar as permissões do aplicativo:
|
||||
To update your app's permissions:
|
||||
|
||||
1. Selecione seu aplicativo na [página de configurações do aplicativo](https://github.com/settings/apps) e clique em **Permissões e Webhooks** na barra lateral.
|
||||
1. Na seção "Permissões", encontre "Problemas" e selecione **Leitura e Gravação** na lista suspensa "Acesso" ao lado. A descrição diz que esta opção concede acesso a problemas e etiquetas, o que é exatamente o que você precisa.
|
||||
1. Na seção "Inscrever-se em eventos", selecione **Problemas** para se inscrever no 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 %}
|
||||
|
||||
Ótimo! Seu aplicativo tem permissão para realizar as tarefas que você deseja que ele realize. Agora você pode adicionar o código para que ele 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.
|
||||
|
||||
## Etapa 2. Adicionar gerenciamento de evento
|
||||
## Step 2. Add event handling
|
||||
|
||||
A primeira coisa que seu aplicativo precisa fazer é ouvir novos problemas que estão abertos. Agora que você se inscreveu no evento **Problemas**, começará a receber o webhook [`issues`](/webhooks/event-payloads/#issues), que é disparado quando determinadas ações relacionadas a problemas ocorrem. Você pode filtrar este tipo de evento para a ação específica que você deseja no seu 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.
|
||||
|
||||
O GitHub envia as cargas de webhook como solicitações `POST`. Como você encaminhou as cargas do webhook do Smee para o `http://localhost/event_handler:3000`, o servidor receberá as cargas da solicitação `POST` na rota `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.
|
||||
|
||||
Uma rota `post '/event_handler'` vazia já está incluída no arquivo `template_server.rb`, que você baixou na seção [Pré-requisitos](#prerequisites). O encaminhamento vazio tem a seguinte forma:
|
||||
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 @@ Uma rota `post '/event_handler'` vazia já está incluída no arquivo `template_
|
|||
end
|
||||
```
|
||||
|
||||
Use essa rota para tratar o evento `issues` adicionando o seguinte código:
|
||||
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 enviado pelo GitHub inclui um cabeçalho de solicitação chamado `HTTP_X_GITHUB_EVENT`, que indica o tipo de evento na solicitação `POST`. Por enquanto, você só está interessado nos tipos de eventos `issues`. Cada evento tem um campo `action` adicional que indica o tipo de ação que disparou os eventos. Para `issues`, o campo `action` pode ser `assigned`, `unassigned`, `labeled`, `unlabeled`, `opened`, `edited`, `milestoned`, `demilestoned`, `closed` ou `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 testar seu gerenciador de eventos, tente adicionar um método auxiliar temporário. Você atualizará isso mais tarde quando [Adicionar um tratamento de rótulo](#step-4-add-label-handling). Por enquanto, adicione o código a seguir na seção `helpers do` do código. Você pode colocar o novo método acima ou abaixo de qualquer outro método de ajuda. A ordem não 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 recebe uma carga de eventos formatada em JSON como argumento. Isso significa que você pode analisar a carga no método e detalhar os dados específicos de que você precisa. Você pode achar útil inspecionar a carga completa em algum momento: experimente alterar `logger.debug 'An issue was opened!` para `logger.debug payload`. A estrutura da carga observada deve corresponder ao que é [mostrado na documentação do 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).
|
||||
|
||||
Ótimo! É hora de testar as alterações.
|
||||
Great! It's time to test the changes.
|
||||
|
||||
{% data reusables.apps.sinatra_restart_instructions %}
|
||||
|
||||
No seu navegador, acesse o repositório onde você instalou seu aplicativo. Abra um novo problema neste repositório. O problema pode dizer o que você quiser. É apenas para teste.
|
||||
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.
|
||||
|
||||
Ao olhar novamente para o terminal, na saída, você verá a mensagem "`An issue was opened!` Parabéns! Você adicionou um gerenciador de eventos ao seu aplicativo. 💪
|
||||
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. 💪
|
||||
|
||||
## Etapa 3. Criar um novo rótulo
|
||||
## Step 3. Create a new label
|
||||
|
||||
Ok, seu aplicativo pode dizer quando os problemas estão abertos. Agora você deseja que ele adicione o rótulo `needs-response` a qualquer problema recém-aberto em um repositório no qual o aplicativo está instalado.
|
||||
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 que o rótulo seja _adicionado_ em qualquer lugar, você precisará _criar_ o rótulo personalizado no seu repositório. Você só terá de fazer isso uma vez. Para fins deste guia, crie a etiqueta manualmente no GitHub. No repositório, clique em **Problemas**, em **Rótulos** e clique em **Novo rótulo**. Dê ao novo rótulo o nome `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 %}
|
||||
|
||||
**Dica**: não seria ótimo se o aplicativo pudesse criar o rótulo por meio de programação? [Ele pode](/rest/reference/issues#create-a-label)! Adicione o código para fazer isso por conta própria depois de concluir as etapas deste guia.
|
||||
**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 %}
|
||||
|
||||
Agora que o rótulo existe, você pode programar seu aplicativo para usar a API REST a fim de [adicionar o rótulo a qualquer problema recém-aberto](/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).
|
||||
|
||||
## Etapa 4. Adicionar gerenciamento de etiqueta
|
||||
## Step 4. Add label handling
|
||||
|
||||
Parabéns! Você chegou à etapa final: adicionando o gerenciamento de etiquetas ao seu aplicativo. Para essa tarefa, o ideal será usar a [biblioteca Octokit.rb do 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/).
|
||||
|
||||
Na documentação do Octokit.rb, encontre a lista de [métodos de rótulos](http://octokit.github.io/octokit.rb/Octokit/Client/Labels.html). O método que recomendamos usar é o [`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 volta a `template_server.rb`, localize o método que você definiu 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
|
||||
```
|
||||
|
||||
A documentação de [`add_labels_to_an_issue`](http://octokit.github.io/octokit.rb/Octokit/Client/Labels.html#add_labels_to_an_issue-instance_method) mostra que você precisará transmitir três argumentos para 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:
|
||||
|
||||
* Repositório (cadeia de caracteres no formato `"owner/name"`)
|
||||
* Número do problema (inteiro)
|
||||
* Etiquetas (array)
|
||||
* Repo (string in `"owner/name"` format)
|
||||
* Issue number (integer)
|
||||
* Labels (array)
|
||||
|
||||
Você pode analisar a carga para obter o repositório e o número do problema. Como o nome do rótulo será sempre o mesmo (`needs-response`) você pode transmiti-lo como uma cadeia de caracteres embutida em código na matriz de rótulos. Ao juntar essas peças, seu método atualizado pode parecer com isto:
|
||||
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
|
||||
```
|
||||
|
||||
Tente abrir um novo problema no seu repositório de teste e veja o que acontece! Se nada acontecer imediatamente, tente atualizar.
|
||||
Try opening a new issue in your test repository and see what happens! If nothing happens right away, try refreshing.
|
||||
|
||||
Você não verá muitas coisas no terminal, _mas_ verá que um usuário bot adicionou um rótulo ao problema.
|
||||
You won't see much in the Terminal, _but_ you should see that a bot user has added a label to the issue.
|
||||
|
||||
{% note %}
|
||||
|
||||
**Observação:** quando os Aplicativos do GitHub executam ações pela API, como adicionar rótulos, o GitHub mostra essas ações como sendo realizadas pelas contas do _bot_. Para obter mais informações, confira "[Comparação entre contas de computador e contas 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 %}
|
||||
|
||||
Se for assim, parabéns! Você construiu um aplicativo funcional com sucesso! 🎉
|
||||
If so, congrats! You've successfully built a working app! 🎉
|
||||
|
||||
Você poderá ver o código final em `server.rb` no [repositório de modelo de aplicativo](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).
|
||||
|
||||
Confira "[Próximas etapas](#next-steps)" para descobrir ideias sobre o que você pode fazer em seguida.
|
||||
See "[Next steps](#next-steps)" for ideas about where you can go from here.
|
||||
|
||||
## Solução de problemas
|
||||
## Troubleshooting
|
||||
|
||||
Aqui estão alguns problemas comuns e algumas soluções sugeridas. Se você tiver qualquer outro problema, poderá pedir ajuda ou orientação em {% 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:** Meu servidor não está ouvindo eventos. O cliente da Smee está sendo executado em uma janela de Terminal, e eu estou enviando eventos para o github.com. abrindo novos problemas, mas não vejo nenhuma saída na janela do Terminal onde estou executando o 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:** Talvez você não tenha o domínio correto do Smee nas configurações do aplicativo. Acesse a [página de configurações do aplicativo](https://github.com/settings/apps) e verifique os campos mostrados em "[Registrar um novo aplicativo no GitHub](/apps/quickstart-guides/setting-up-your-development-environment/#step-2-register-a-new-github-app)". Verifique se o domínio nesses campos corresponde ao domínio usado no comando `smee -u <unique_channel>` em "[Iniciar um novo canal do 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:** Meu aplicativo não funciona. Eu abri um novo problema, mas mesmo depois de atualizado, nenhuma etiqueta foi adicionado a ele.
|
||||
* **Q:** My app doesn't work! I opened a new issue, but even after refreshing, no label has been added to it.
|
||||
|
||||
**R:** Verifique se todos os seguintes itens são verdadeiros:
|
||||
**A:** Make sure all of the following are true:
|
||||
|
||||
* Você [instalou o aplicativo](/apps/quickstart-guides/setting-up-your-development-environment/#step-7-install-the-app-on-your-account) no repositório em que está abrindo o problema.
|
||||
* O [cliente do Smee está em execução](/apps/quickstart-guides/setting-up-your-development-environment/#step-1-start-a-new-smee-channel) em uma janela do terminal.
|
||||
* O [servidor Web está em execução](/apps/quickstart-guides/setting-up-your-development-environment/#step-6-start-the-server) sem erros em outra janela do terminal.
|
||||
* Seu aplicativo tem [permissões de leitura e gravação em problemas e está inscrito para emitir eventos](/apps/quickstart-guides/setting-up-your-development-environment/#step-1-start-a-new-smee-channel).
|
||||
* Você [verificou seu email](#step-1-update-app-permissions) depois de atualizar as permissões e aceitou as novas permissões.
|
||||
* 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.
|
||||
|
||||
## Conclusão
|
||||
## Conclusion
|
||||
|
||||
Depois de analisar este guia, você aprendeu os componentes básicos para o desenvolvimento dos aplicativos GitHub! Para resumir, você:
|
||||
After walking through this guide, you've learned the basic building blocks for developing GitHub Apps! To review, you:
|
||||
|
||||
* Programou seu aplicativo para ouvir eventos
|
||||
* Usou a biblioteca do Octokit.rb para fazer operações da API REST
|
||||
* Programmed your app to listen for events
|
||||
* Used the Octokit.rb library to do REST API operations
|
||||
|
||||
## Próximas etapas
|
||||
## Next steps
|
||||
|
||||
Aqui estão algumas ideias do que você pode fazer a seguir:
|
||||
Here are some ideas for what you can do next:
|
||||
|
||||
* [Reescreva seu aplicativo usando o GraphQL](https://developer.github.com/changes/2018-04-30-graphql-supports-github-apps/).
|
||||
* Reescreva seu aplicativo em Node.js usando [o Probot](https://github.com/probot/probot).
|
||||
* Faça o aplicativo verificar se o rótulo `needs-response` já existe no problema e, em caso negativo, adicione-o.
|
||||
* Quando o bot adiciona a etiqueta com sucesso, é exibida uma mensagem no Terminal. (Dica: compare a ID do rótulo `needs-response` com a ID do rótulo na carga como uma condição para a mensagem, de modo que ela só seja exibida quando o rótulo relevante for adicionado e não qualquer outro rótulo).
|
||||
* Adicione uma página de aterrissagem ao aplicativo e conecte uma [rota do Sinatra](https://github.com/sinatra/sinatra#routes) a ele.
|
||||
* Mova o seu código para um servidor hospedado (como o Heroku). Não se esqueça de atualizar as configurações do seu aplicativo com o novo domínio.
|
||||
* Compartilhe seu projeto ou receba orientações no {% data variables.product.prodname_support_forum_with_url %}{% ifversion fpt or ghec %}
|
||||
* Você construiu um aplicativo novo brilhante que você considera que outras pessoas podem achar útil? [Adicione-o ao 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 %}
|
||||
|
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -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 %}
|
||||
|
|
|
@ -1,13 +1,5 @@
|
|||
---
|
||||
ms.openlocfilehash: a9edfbc5b5f3c0f50ae1e476d393e658751a5079
|
||||
ms.sourcegitcommit: fb047f9450b41b24afc43d9512a5db2a2b750a2a
|
||||
ms.translationtype: HT
|
||||
ms.contentlocale: pt-BR
|
||||
ms.lasthandoff: 09/11/2022
|
||||
ms.locfileid: "145094302"
|
||||
---
|
||||
{% data variables.product.company_short %} contas para {% data variables.product.prodname_advanced_security %} com base no committer. {% ifversion fpt or ghec %}Para obter mais informações, confira "[Como gerenciar o licenciamento do {% data variables.product.prodname_GH_advanced_security %}](/billing/managing-licensing-for-github-advanced-security)".{% elsif ghes %}Para obter mais informações, confira "[Como gerenciar o {% data variables.product.prodname_GH_advanced_security %} para sua empresa](/admin/advanced-security)".{% endif %}
|
||||
{% ifversion fpt or ghec or ghes %}{% data variables.product.company_short %} bills for {% data variables.product.prodname_advanced_security %} on a per-committer basis. For more information, see "[Managing licensing for {% data variables.product.prodname_GH_advanced_security %}](/billing/managing-licensing-for-github-advanced-security)."{% elsif ghes %}For more information, see "[Managing {% data variables.product.prodname_GH_advanced_security %} for your Enterprise](/admin/advanced-security)."{% endif %}
|
||||
|
||||
Você pode aplicar uma política que controla se os administradores de repositórios têm permissão para habilitar funcionalidades para {% data variables.product.prodname_advanced_security %} nos repositórios de uma organização. É possível configurar uma política para todas as organizações pertencentes à conta corporativa ou para organizações individuais escolhidas.
|
||||
You can enforce a policy that controls whether repository administrators are allowed to enable features for {% data variables.product.prodname_advanced_security %} in an organization's repositories. You can configure a policy for all organizations owned by your enterprise account, or for individual organizations that you choose.
|
||||
|
||||
Cancelar a permissão de {% data variables.product.prodname_advanced_security %} para uma organização impede que os administradores de repositórios habilitem funcionalidades de {% data variables.product.prodname_advanced_security %} para repositórios adicionais, mas não desabilita as funcionalidades nos repositórios onde já estão habilitadas. Para obter mais informações sobre a configuração de recursos do {% data variables.product.prodname_advanced_security %}, confira "[Como gerenciar as configurações de segurança e análise para sua organização](/organizations/keeping-your-organization-secure/managing-security-and-analysis-settings-for-your-organization)" ou "[Como gerenciar as configurações de segurança e análise para seu repositório](/github/administering-a-repository/managing-security-and-analysis-settings-for-your-repository)".
|
||||
Disallowing {% data variables.product.prodname_advanced_security %} for an organization prevents repository administrators from enabling {% data variables.product.prodname_advanced_security %} features for additional repositories, but does not disable the features for repositories where the features are already enabled. For more information about configuration of {% data variables.product.prodname_advanced_security %} features, see "[Managing security and analysis settings for your organization](/organizations/keeping-your-organization-secure/managing-security-and-analysis-settings-for-your-organization)" or "[Managing security and analysis settings for your repository](/github/administering-a-repository/managing-security-and-analysis-settings-for-your-repository)."
|
||||
|
|
|
@ -1,16 +1,10 @@
|
|||
---
|
||||
ms.openlocfilehash: cd30225961136524faf23bf1fc353c0c400cdc2b
|
||||
ms.sourcegitcommit: fcf3546b7cc208155fb8acdf68b81be28afc3d2d
|
||||
ms.translationtype: HT
|
||||
ms.contentlocale: pt-BR
|
||||
ms.lasthandoff: 09/10/2022
|
||||
ms.locfileid: "145094681"
|
||||
---
|
||||
{% ifversion ghes %}
|
||||
|
||||
{% note %}
|
||||
|
||||
**Observação:** o administrador do site precisa habilitar a {% data variables.product.prodname_code_scanning %} para o {% data variables.product.product_location %} para que você possa usar esse recurso. Para obter mais informações, confira "[Como configurar a {% data variables.product.prodname_code_scanning %} para seu dispositivo](/enterprise/admin/configuration/configuring-code-scanning-for-your-appliance)".1
|
||||
**Note:** Your site administrator must enable {% data variables.product.prodname_code_scanning %} for {% data variables.product.product_location %} before you can use this feature. For more information, see "[Configuring {% data variables.product.prodname_code_scanning %} for your appliance](/enterprise/admin/configuration/configuring-code-scanning-for-your-appliance)."
|
||||
|
||||
{% ifversion security-feature-enablement-policies %} You may not be able to enable or disable {% data variables.product.prodname_code_scanning %} if an enterprise owner has set a policy at the enterprise level. For more information, see "[Enforcing policies for code security and analysis for your enterprise](/admin/policies/enforcing-policies-for-your-enterprise/enforcing-policies-for-code-security-and-analysis-for-your-enterprise)."{% endif %}
|
||||
|
||||
{% endnote %}
|
||||
|
||||
|
|
|
@ -1,16 +1,10 @@
|
|||
---
|
||||
ms.openlocfilehash: 173ad67b9b54108c16978dc5f1a8f01768c7bb37
|
||||
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
|
||||
ms.translationtype: HT
|
||||
ms.contentlocale: pt-BR
|
||||
ms.lasthandoff: 09/05/2022
|
||||
ms.locfileid: "145127841"
|
||||
---
|
||||
{% ifversion ghes > 3.2 %}
|
||||
|
||||
{% note %}
|
||||
|
||||
**Observação:** o administrador do site precisa configurar as {% data variables.product.prodname_dependabot_updates %} para o {% data variables.product.product_location %} para que você possa usar esse recurso. Para obter mais informações, confira "[Como habilitar o {% data variables.product.prodname_dependabot %} para sua empresa](/admin/configuration/configuring-github-connect/enabling-dependabot-for-your-enterprise)".
|
||||
**Note:** Your site administrator must set up {% data variables.product.prodname_dependabot_updates %} for {% data variables.product.product_location %} before you can use this feature. For more information, see "[Enabling {% data variables.product.prodname_dependabot %} for your enterprise](/admin/configuration/configuring-github-connect/enabling-dependabot-for-your-enterprise)."
|
||||
|
||||
{% ifversion security-feature-enablement-policies %} You may not be able to enable or disable {% data variables.product.prodname_dependabot_updates %} if an enterprise owner has set a policy at the enterprise level. For more information, see "[Enforcing policies for code security and analysis for your enterprise](/admin/policies/enforcing-policies-for-your-enterprise/enforcing-policies-for-code-security-and-analysis-for-your-enterprise)."{% endif %}
|
||||
|
||||
{% endnote %}
|
||||
|
||||
|
|
|
@ -1,9 +1 @@
|
|||
---
|
||||
ms.openlocfilehash: 3c79982a7666f43d8e490dd4a7111a456f61f38a
|
||||
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
|
||||
ms.translationtype: HT
|
||||
ms.contentlocale: pt-BR
|
||||
ms.lasthandoff: 09/05/2022
|
||||
ms.locfileid: "145093426"
|
||||
---
|
||||
Se você tiver uma licença do GitHub Advanced Security para sua conta corporativa, poderá impor políticas para gerenciar os recursos do {% data variables.product.prodname_dotcom %} Advanced Security para organizações pertencentes a uma conta corporativa. Para obter mais informações, confira "[Como impor políticas do Advanced Security à sua conta corporativa](/enterprise-cloud@latest/admin/policies/enforcing-policies-for-your-enterprise/enforcing-policies-for-advanced-security-in-your-enterprise)".
|
||||
If you have a GitHub Advanced Security license for your enterprise account, you can enforce policies to manage {% data variables.product.prodname_GH_advanced_security %} features for organizations owned by an enterprise account. For more information, see "[Enforcing policies for code security and analysis for your enterprise](/enterprise-cloud@latest/admin/policies/enforcing-policies-for-your-enterprise/enforcing-policies-for-advanced-security-in-your-enterprise)."
|
||||
|
|
|
@ -1,13 +1,7 @@
|
|||
---
|
||||
ms.openlocfilehash: 0d3766d1ee339285978cb9b14f22fb1773561325
|
||||
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
|
||||
ms.translationtype: HT
|
||||
ms.contentlocale: pt-BR
|
||||
ms.lasthandoff: 09/05/2022
|
||||
ms.locfileid: "145093270"
|
||||
---
|
||||
{% ifversion ghes < 3.7 %}
|
||||
{% note %}
|
||||
|
||||
**Nota:** o modo vigilante está atualmente na versão beta e está sujeito a alterações.
|
||||
**Note:** Vigilant mode is currently in beta and subject to change.
|
||||
|
||||
{% endnote %}
|
||||
{% endif %}
|
|
@ -1,16 +1,9 @@
|
|||
---
|
||||
ms.openlocfilehash: bd43779cdfde11268b296b12ad5f328d3fdbc291
|
||||
ms.sourcegitcommit: fcf3546b7cc208155fb8acdf68b81be28afc3d2d
|
||||
ms.translationtype: HT
|
||||
ms.contentlocale: pt-BR
|
||||
ms.lasthandoff: 09/10/2022
|
||||
ms.locfileid: "147875613"
|
||||
---
|
||||
{% ifversion ghes %}
|
||||
|
||||
{% note %}
|
||||
|
||||
**Observação:** o administrador do site precisa habilitar a {% data variables.product.prodname_secret_scanning %} para o {% data variables.product.product_location %} para que você possa usar esse recurso. Para obter mais informações, confira "[Como configurar a {% data variables.product.prodname_secret_scanning %} para seu dispositivo](/enterprise/admin/configuration/configuring-secret-scanning-for-your-appliance)".
|
||||
**Note:** Your site administrator must enable {% data variables.product.prodname_secret_scanning %} for {% data variables.product.product_location %} before you can use this feature. For more information, see "[Configuring {% data variables.product.prodname_secret_scanning %} for your appliance](/enterprise/admin/configuration/configuring-secret-scanning-for-your-appliance)."
|
||||
{% ifversion security-feature-enablement-policies %} You may not be able to enable or disable {% data variables.product.prodname_secret_scanning %}, if an enterprise owner has set a policy at the enterprise level. For more information, see "[Enforcing policies for code security and analysis for your enterprise](/admin/policies/enforcing-policies-for-your-enterprise/enforcing-policies-for-code-security-and-analysis-for-your-enterprise)."{% endif %}
|
||||
|
||||
{% endnote %}
|
||||
|
||||
|
|
|
@ -1,15 +1,7 @@
|
|||
---
|
||||
ms.openlocfilehash: 01490f812c6a7b54293806a24023f25af2831d8e
|
||||
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
|
||||
ms.translationtype: HT
|
||||
ms.contentlocale: pt-BR
|
||||
ms.lasthandoff: 09/05/2022
|
||||
ms.locfileid: "147432077"
|
||||
---
|
||||
Em caso de dúvidas, relatórios de bug e discussões sobre os {% data variables.product.prodname_github_apps %}, os {% data variables.product.prodname_oauth_apps %} e o desenvolvimento de API, explore o {% data variables.product.prodname_support_forum_with_url %}. As discussões são moderadas e mantidas pela equipe do {% data variables.product.company_short %}, mas não é garantido que as perguntas publicadas no fórum recebam uma resposta da equipe do {% 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.
|
||||
|
||||
Considere a possibilidade de entrar em contato diretamente com o [Suporte do GitHub](https://support.github.com/) usando o formulário de contato para:
|
||||
- resposta garantida dos funcionários de {% data variables.product.product_name %}
|
||||
- solicitações de suporte que envolvem dados confidenciais ou questões privadas
|
||||
- solicitações de recursos
|
||||
- feedback sobre produtos 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
|
||||
|
|
|
@ -1,9 +1,7 @@
|
|||
---
|
||||
ms.openlocfilehash: 004cf3f20495daaec9413026c03e5514211c906d
|
||||
ms.sourcegitcommit: 76b840f45ba85fb79a7f0c1eb43bc663b3eadf2b
|
||||
ms.translationtype: HT
|
||||
ms.contentlocale: pt-BR
|
||||
ms.lasthandoff: 09/12/2022
|
||||
ms.locfileid: "145066112"
|
||||
---
|
||||
Atividade relacionada a alertas de vulnerabilidade de segurança em um repositório. {% data reusables.webhooks.action_type_desc %} Para obter mais informações, confira "[Sobre {% 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/)".
|
||||
|
|
Загрузка…
Ссылка в новой задаче