GitHub Action Life

Me pareció que sería divertido hacer una publicación llamada "Life of GitHub Action". En la capacitación introductoria de Google, lo guían a través de la "Vida de la solicitud", y tuve uno de mis elementos favoritos. Por lo tanto, uso un enfoque similar para GitHub Action.


Para aquellos en el tanque, Actions es una característica de GitHub lanzada en Universe el año pasado. ¿Quieres beta testers? Ve aqui


La idea general es un GitHub con soporte para secuencias de comandos, pero no sufriré basura y me derramaré en explicaciones. Es mejor guiarte a través de los eventos que ocurren cuando comienza la acción.


El problema


Aquí hay un flujo de trabajo típico :


  • Creo una solicitud de extracción en el repositorio.
  • La solicitud de extracción es absorbida.
  • La rama se conserva hasta el final de los tiempos, comiéndome esa parte del cerebro que ama la limpieza y el orden.


Las ramas restantes son mi dolor, concéntrate en ello. Aunque el problema es general, creemos una acción para eliminar ramas después de absorber la solicitud de extracción.


Mnogabukaf? Todo el código para la acción está aquí .


Archivo de flujo de trabajo


Si lo desea, cree acciones a través de la interfaz de usuario, pero si lo desea, escriba un archivo de flujo de trabajo con lápices. En este artículo, solo uso un archivo.


Así es como se ve, y explicaré lo que todo esto significa en los comentarios en el archivo. Se encuentra en .github/main.workflow en su repositorio.


 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"] } 

El evento


Entonces, dado que el artículo se llama "La vida de acción", comenzamos con lo que está sucediendo con el oscurantismo. Todas las acciones se desencadenan a través del evento GitHub. La lista de eventos compatibles está aquí .


Arriba, seleccionamos el evento pull_request . Comienza cuando se asigna una solicitud de extracción, sin asignar, marcada, sin marcar, abierta, editada, cerrada, reabierta, sincronizada, solicitada para solicitar una solicitud de extracción o eliminar una solicitud de extracción.


Bien, comenzamos este evento y ...


Hay algo mal con la solicitud de extracción ...

Y aquí está GitHub: "Maldita tortita, ¡algo está mal con la solicitud de extracción! ¡Estoy fuera de todas las herramientas para los problemas! "


Mirando el archivo de flujo de trabajo (ver arriba), GitHub dice: "Ahora comenzaré el flujo de trabajo para absorber la solicitud de extracción y eliminaré la rama".


¿A qué conduce esto? Oh, "limpiando la rama". Permítanme simplificar los pasos necesarios para limpiar la rama (en este caso, no hay ninguno) y ejecutarlos en orden / en paralelo para llegar a la "rama limpia".


Acción


Aquí GitHub declara: "Yo gente, tengo que comenzar la" limpieza de sucursales "aquí. Déjame resolverlo.


Esto nos lleva de vuelta a la sección de uses de nuestro archivo. jessfraz/branch-cleanup-action@master el repositorio: jessfraz/branch-cleanup-action@master .


Este repositorio contiene el Dockerfile. Define el entorno en el que se realizará nuestra acción.


Dockerfile


Échale un vistazo e intentaré explicar todo en los comentarios.


 ## 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"] 

El guión


A continuación se muestra el contenido del script de prueba que estoy ejecutando.


 #!/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 "$@" 

Entonces, por ahora, GitHub ha ejecutado nuestro script en nuestro tiempo de ejecución.
GitHub informará el estado de la acción a la interfaz de usuario, y puede verlo en la pestaña "Acciones".


Esperemos que esto traiga algo de claridad sobre cómo se implementan los procesos en las Acciones de GitHub. No puedo esperar para ver qué pasa contigo.

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


All Articles