Vida de Ação do GitHub

Pareceu-me que seria divertido cortar um post chamado "Life of GitHub Action". No treinamento introdutório do Google, você é conduzido pela "Vida da solicitação" e eu tive um dos meus elementos favoritos. Portanto, eu uso uma abordagem semelhante para a Ação GitHub.


Para quem está no tanque, o Actions é um recurso do GitHub lançado no Universe no ano passado. Quer testadores beta? Vá aqui .


A ideia geral é um GitHub com suporte a scripts, mas não sofro com o lixo e transbordo em explicações. Melhor orientá-lo nos eventos que ocorrem quando a ação é iniciada.


O problema


Aqui está um fluxo de trabalho típico :


  • Eu crio uma solicitação pull para o repositório.
  • A solicitação de recebimento é absorvida.
  • O ramo é preservado até o fim dos tempos, me devorando a parte do cérebro que adora limpeza e ordem.


Os galhos restantes são a minha dor, concentre-se nela. Embora o problema seja geral, vamos criar uma ação para remover ramificações após absorver a solicitação de recebimento.


Mnogabukaf? Todo o código da ação está aqui .


Arquivo de fluxo de trabalho


Se desejar - crie ações através da interface do usuário, mas se desejar - escreva um arquivo de fluxo de trabalho com canetas. Neste artigo, eu apenas uso um arquivo.


É assim que parece, e vou explicar o que tudo isso significa nos comentários no arquivo. Está localizado em .github/main.workflow no seu repositório.


 workflow "on pull request merge, delete the branch" { ## On pull_request defines that whenever a pull request event is fired this ## workflow will be run. on = "pull_request" ## What is the ending action (or set of actions) that we are running. ## Since we can set what actions "need" in our definition of an action, ## we only care about the last actions run here. resolves = ["branch cleanup"] } ## This is our action, you can have more than one but we just have this one for ## our example. ## I named it branch cleanup, and since it is our last action run it matches ## the name in the resolves section above. action "branch cleanup" { ## Uses defines what we are running, you can point to a repository like below ## OR you can define a docker image. uses = "jessfraz/branch-cleanup-action@master" ## We need a github token so that when we call the github api from our ## scripts in the above repository we can authenticate and have permission ## to delete a branch. secrets = ["GITHUB_TOKEN"] } 

Evento


Assim, como o artigo se chama "A vida da ação", começamos com o que está acontecendo com o obscurantismo. Todas as ações são acionadas através do evento GitHub. A lista de eventos suportados está aqui .


Acima, selecionamos o evento pull_request . Inicia quando uma solicitação pull é atribuída, não atribuída, marcada, desmarcada, aberta, editada, fechada, reaberta, sincronizada, solicitada para solicitar uma solicitação pull ou excluir uma solicitação pull.


Ok, nós começamos este evento, e ...


Há algo errado com a solicitação de recebimento ...

E aqui está o GitHub: "Droga de panqueca, algo está errado com a solicitação de recebimento! Estou com todas as ferramentas para problemas!


Observando o arquivo do fluxo de trabalho (veja acima), o GitHub diz: "Agora, iniciarei o fluxo de trabalho para absorver a solicitação de recebimento e excluirei a ramificação".


O que isso leva a? Ah, "limpando o galho". Permitam-me simplificar as etapas necessárias para limpar a ramificação (neste caso, não há nenhuma) e executá-las em ordem / em paralelo para chegar à "ramificação limpa".


Acção


Aqui o GitHub declara: “Pessoal, tenho que iniciar a“ limpeza da filial ”aqui. Deixe-me descobrir.


Isso nos leva de volta à seção de uses do nosso arquivo. jessfraz/branch-cleanup-action@master para o repositório: jessfraz/branch-cleanup-action@master .


Este repositório contém o Dockerfile. Ele define o ambiente em que nossa ação será executada.


Dockerfile


Dê uma olhada e tentarei explicar tudo nos comentários.


 ## FROM defines what Docker image we are starting at. A docker image is a bunch ## of files combined in a tarball. ## This image is all the files we need for an Alpine OS environment. FROM alpine:latest ## This label defines our action name, we could have named it butts but ## I decided to be an adult. LABEL "com.github.actions.name"="Branch Cleanup" ## This label defines the description for our action. LABEL "com.github.actions.description"="Delete the branch after a pull request has been merged" ## We can pick from a variety of icons for our action. ## The list of icons is here: https://developer.github.com/actions/creating-github-actions/creating-a-docker-container/#supported-feather-icons LABEL "com.github.actions.icon"="activity" ## This is the color for the action icon that shows up in the UI when it's run. LABEL "com.github.actions.color"="red" ## These are the packages we are installing. Since I just wrote a shitty bash ## script for our Action we don't really need all that much. We need bash, ## CA certificates and curl so we can send a request to the GitHub API ## and jq so I can easily muck with JSON from bash. RUN apk add --no-cache \ bash \ ca-certificates \ curl \ jq ## Now I am going to copy my shitty bash script into the image. COPY cleanup-pr-branch /usr/bin/cleanup-pr-branch ## The cmd for the container defines what arguments should be executed when ## it is run. ## We are just going to call back to my shitty script. CMD ["cleanup-pr-branch"] 

O script


Abaixo está o conteúdo do script de avaliação que estou executando.


 #!/bin/bash set -e set -o pipefail # This is populated by our secret from the Workflow file. if [[ -z "$GITHUB_TOKEN" ]]; then echo "Set the GITHUB_TOKEN env variable." exit 1 fi # This one is populated by GitHub for free :) if [[ -z "$GITHUB_REPOSITORY" ]]; then echo "Set the GITHUB_REPOSITORY env variable." exit 1 fi URI=https://api.github.com API_VERSION=v3 API_HEADER="Accept: application/vnd.github.${API_VERSION}+json" AUTH_HEADER="Authorization: token ${GITHUB_TOKEN}" main(){ # In every runtime environment for an Action you have the GITHUB_EVENT_PATH # populated. This file holds the JSON data for the event that was triggered. # From that we can get the status of the pull request and if it was merged. # In this case we only care if it was closed and it was merged. action=$(jq --raw-output .action "$GITHUB_EVENT_PATH") merged=$(jq --raw-output .pull_request.merged "$GITHUB_EVENT_PATH") echo "DEBUG -> action: $action merged: $merged" if [[ "$action" == "closed" ]] && [[ "$merged" == "true" ]]; then # We only care about the closed event and if it was merged. # If so, delete the branch. ref=$(jq --raw-output .pull_request.head.ref "$GITHUB_EVENT_PATH") owner=$(jq --raw-output .pull_request.head.repo.owner.login "$GITHUB_EVENT_PATH") repo=$(jq --raw-output .pull_request.head.repo.name "$GITHUB_EVENT_PATH") default_branch=$( curl -XGET -sSL \ -H "${AUTH_HEADER}" \ -H "${API_HEADER}" \ "${URI}/repos/${owner}/${repo}" | jq .default_branch ) if [[ "$ref" == "$default_branch" ]]; then # Never delete the default branch. echo "Will not delete default branch (${default_branch}) for ${owner}/${repo}, exiting." exit 0 fi echo "Deleting branch ref $ref for owner ${owner}/${repo}..." curl -XDELETE -sSL \ -H "${AUTH_HEADER}" \ -H "${API_HEADER}" \ "${URI}/repos/${owner}/${repo}/git/refs/heads/${ref}" echo "Branch delete success!" fi } main "$@" 

Então, por enquanto, o GitHub executou nosso script em nosso tempo de execução.
O GitHub reportará o status da ação para a interface do usuário, e você pode vê-lo na guia "Ações".


Espero que isso traga alguma clareza sobre como os processos são implementados nas Ações do GitHub. Mal posso esperar para ver o que acontece com você.

Source: https://habr.com/ru/post/pt438248/


All Articles