Hvad er Github-handlinger, og hvordan kan du automatisere test og slap notifikationer?

Automatisering er et kraftfuldt værktøj. Det sparer os både tid og kan hjælpe med at reducere menneskelige fejl.

Men automatisering kan være hård og kan undertiden vise sig at være dyr. Hvordan kan Github Actions hjælpe med at hærde vores kode og give os mere tid til at arbejde på funktioner i stedet for bugs?

  • Hvad er Github-handlinger?
  • Hvad er CI / CD?
  • Hvad skal vi bygge?
  • Del 0: Opsætning af et projekt
  • Del 1: Automatisering af tests
  • Del 2: Send nye pullanmodninger til Slack

Hvad er Github-handlinger?

Handlinger er en relativt ny funktion til Github, der giver dig mulighed for at konfigurere CI / CD-arbejdsgange ved hjælp af en konfigurationsfil lige i din Github-repo.

Tidligere, hvis du ville oprette enhver form for automatisering med tests, builds eller implementeringer, skulle du se på tjenester som Circle CI og Travis eller skrive dine egne scripts. Men med Handlinger har du førsteklasses support til kraftfuld værktøj til at automatisere din arbejdsgang.

Hvad er CI / CD?

CD / CD står for kontinuerlig integration og kontinuerlig implementering (eller kan være kontinuerlig levering). De er begge praksis inden for softwareudvikling, der giver hold mulighed for at opbygge projekter sammen hurtigt, effektivt og ideelt med mindre fejl.

Kontinuerlig integration er ideen om, at da forskellige medlemmer af teamet arbejder på kode på forskellige git-grene, flettes koden til en enkelt arbejdsgruppe, som derefter bygges og testes med automatiserede arbejdsgange. Dette hjælper med til konstant at sikre, at alles kode fungerer korrekt sammen og er velprøvet.

Kontinuerlig implementering tager dette et skridt videre og fører denne automatisering til implementeringsniveauet. Hvor du med CI-processen automatiserer testen og bygningen, vil kontinuerlig implementering automatisere implementeringen af ​​projektet i et miljø.

Ideen er, at koden, en gang gennem en hvilken som helst bygge- og testproces, er i en implementerbar tilstand, så den skal kunne implementeres.

Hvad skal vi bygge?

Vi skal tackle to forskellige arbejdsgange.

Den første vil være at køre nogle automatiske tests, der forhindrer, at en pull-anmodning flettes, hvis den fejler. Vi går ikke igennem opbygningen af ​​testene, men vi gennemgår løbende tests, der allerede findes.

I anden del opretter vi en arbejdsgang, der sender en besked til slap med et link til en pull-anmodning, hver gang en ny oprettes. Dette kan være super nyttigt, når du arbejder på open source-projekter med et team, og du har brug for en måde at holde styr på anmodninger på.

Del 0: Opsætning af et projekt

I denne vejledning kan du virkelig arbejde igennem ethvert node-baseret projekt, så længe det har tests, du kan køre til del 1.

Hvis du gerne vil følge med et enklere eksempel, som jeg bruger, har jeg oprettet et nyt projekt, som du kan klone med en enkelt funktion, der har to tests, der er i stand til at køre og bestå.

Hvis du vil tjekke denne kode for at komme i gang, kan du køre:

git clone --single-branch --branch start [email protected]:colbyfayock/my-github-actions.git 

Når du har klonet lokalt og har installeret afhængighederne, skal du kunne køre testene og se dem bestå!

Det skal også bemærkes, at du bliver forpligtet til at få dette projekt tilføjet som et nyt lager på Github for at følge med.

Følg med på forpligtelsen!

Del 1: Automatisering af tests

Test er en vigtig del af ethvert projekt, der giver os mulighed for at sikre, at vi ikke bryder eksisterende kode, mens vi arbejder. Mens de er vigtige, er de også lette at glemme.

Vi kan fjerne den menneskelige natur ud af ligningen og automatisere kørsel af vores tests for at sikre, at vi ikke kan fortsætte uden at rette det, vi brød.

Trin 1: Oprettelse af en ny handling

Den gode nyhed er, at Github faktisk gør det virkelig nemt at komme i gang med denne arbejdsgang, da den kommer som en af ​​deres forbagte muligheder.

Vi starter med at navigere til fanen Handlinger på vores arkivside.

Når vi er der, ser vi straks nogle starter-arbejdsgange, som Github giver os mulighed for at dykke ind i. Da vi bruger et node-projekt, kan vi gå videre og klikke på Opsæt denne arbejdsgang under Node.js- arbejdsgangen.

Når siden er indlæst, lander Github dig på en ny fileditor, der allerede har en masse konfigurationsindstillinger tilføjet.

Vi vil faktisk lade dette være "som det er" til vores første skridt. Eventuelt kan du ændre navnet på filen til tests.ymleller noget, du vil huske.

Du kan gå videre og klikke på Start forpligte derefter enten forpligte det bibliotek til mastergrenen eller føje ændringen til en ny gren. Til denne gennemgang forpligter jeg mig direkte til master.

For at se vores nye handlingskørsel kan vi igen klikke på fanen Handlinger , der navigerer os tilbage til vores nye Handlingsdashboard.

Derfra kan du klikke på Node.js CI og vælge den forpligtelse, du lige har lavet ovenfor, og du lander på vores nye handlingsdashboard. Du kan derefter klikke på en af nodeversionerne i sidebjælken via build (# .x) , klikke på rullemenuen Kør npm-test , og vi kan se resultatet af vores tests, der køres (som hvis du følger med med mig, skulle passere!).

Følg med på forpligtelsen!

Trin 2: Konfiguration af vores nye handling

Så hvad gjorde vi lige ovenfor? Vi går gennem konfigurationsfilen, og hvad vi kan tilpasse.

Fra toppen angiver vi vores navn:

name: Node.js CI 

This can really be whatever you want. Whatever you pick should help you remember what it is. I'm going to customize this to "Tests" so I know exactly what's going on.

on: push: branches: [ master ] pull_request: branches: [ master ] 

The on key is how we specify what events trigger our action. This can be a variety of things like based on time with cron. But here, we're saying that we want this action to run any time someone pushes commits to  master or someone creates a pull request targeting the master branch. We're not going to make a change here.

jobs: build: runs-on: ubuntu-latest 

This next bit creates a new job called build. Here we're saying that we want to use the latest version of Ubuntu to run our tests on. Ubuntu is common, so you'll only want to customize this if you want to run it on a specific environment.

 strategy: matrix: node-version: [10.x, 12.x, 14.x] 

Inside of our job we specify a strategy matrix. This allows us to run the same tests on a few different variations.

In this instance, we're running the tests on 3 different versions of node to make sure it works on all of them. This is definitely helpful to make sure your code is flexible and future proof, but if you're building and running your code on a specific node version, you're safe to change this to only that version.

 steps: - uses: actions/[email protected] - name: Use Node.js ${{ matrix.node-version }} uses: actions/[email protected] with: node-version: ${{ matrix.node-version }} - run: npm ci - run: npm run build --if-present - run: npm test 

Finally, we specify the steps we want our job to run. Breaking this down:

  • uses: actions/[email protected]: In order for us to run our code, we need to have it available. This checks out our code on our job environment so we can use it to run tests.
  • uses: actions/[email protected]: Since we're using node with our project, we'll need it set up on our environment. We're using this action to do that setup  for us for each version we've specified in the matrix we configured above.
  • run: npm ci: If you're not familiar with npm ci, it's similar to running npm install but uses the package-lock.json file without performing any patch upgrades. So essentially, this installs our dependencies.
  • run: npm run build --if-present: npm run build runs the build script in our project. The --if-present flag performs what it sounds like and only runs this command if the build script is present. It doesn't hurt anything to leave this in as it won't run without the script, but feel free to remove this as we're not building the project here.
  • run: npm test: Finally, we run npm test to run our tests. This uses the test npm script set up in our package.json file.

And with that, we've made a few tweaks, but our tests should run after we've committed those changes and pass like before!

Follow along with the commit!

Step 3: Testing that our tests fail and prevent merges

Now that our tests are set up to automatically run, let's try to break it to see it work.

At this point, you can really do whatever you want to intentionally break the tests, but here's what I did:

I'm intentionally returning different expected output so that my tests will fail. And they do!

In my new pull request, my new branch breaks the tests, so it tells me my checks have failed. If you noticed though, it's still green to merge, so how can we prevent merges?

We can prevent pull requests from being merged by setting up a Protected Branch in our project settings.

First, navigate to Settings, then Branches, and click Add rule.

We'll then want to set the branch name pattern to *, which means all branches, check the Require status checks to pass before merging option, then select all of our different status checks that we'd like to require to pass before merging.

Finally, hit Create at the bottom of the page.

And once you navigate back to the pull request, you'll notice that the messaging is a bit different and states that we need our statuses to pass before we can merge.

Note: as an administrator of a repository, you'll still be able to merge, so this technically only prevents non-administrators from merging. But will give you increased messaging if the tests fail.

And with that, we have a new Github Action that runs our tests and prevents pull requests from merging if they fail.

Follow along with the pull request!

Note: we won't be merging that pull request before continuing to Part 2.

Part 2: Post new pull requests to Slack

Now that we're preventing merge requests if they're failing, we want to post a message to our Slack workspace whenever a new pull request is opened up. This will help us keep tabs on our repos right in Slack.

For this part of the guide, you'll need a Slack workspace that you have permissions to create a new developer app with and the ability to create a new channel for the bot user that will be associated with that app.

Step 1: Setting up Slack

There are a few things we're going to walk through as we set up Slack for our workflow:

  • Create a new app for our workspace
  • Assign our bot permissions
  • Install our bot to our workspace
  • Invite our new bot to our channel

To get started, we'll create a new app. Head over to the Slack API Apps dashboard. If you already haven't, log in to your Slack account with the Workspace you'd like to set this up with.

Now, click Create New App where you'll be prompted to put in a name and select a workspace you want this app to be created for. I'm going to call my app "Gitbot" as the name, but you can choose whatever makes sense for you. Then click Create App.

Once created, navigate to the App Home link in the left sidebar. In order to use our bot, we need to assign it OAuth scopes so it has permissions to work in our channel, so select Review Scopes to Add on that page.

Scroll own and you'll see a Scopes section and under that a Bot Token section. Here, click Add an OAuth Scope. For our bot, we don't need a ton of permissions, so add the channels:join and chat:write scopes and we should be good to go.

Now that we have our scopes, let's add our bot to our workspace. Scroll up on that same page to the top and you'll see a button that says Install App to Workspace.

Once you click this, you'll be redirected to an authorization page. Here, you can see the scopes we selected for our bot. Next, click Allow.

At this point, our Slack bot is ready to go. At the top of the OAuth & Permissions page, you'll see a Bot User OAuth Access Token. This is what we'll use when setting up our workflow, so either copy and save this token or remember this location so you know how to find it later.

Note: this token is private - don't give this out, show it in a screencast, or let anyone see it!

Finally, we need to invite our Slack bot to our channel. If you open up your workspace, you can either use an existing channel or create a new channel for these notifications, but you'll want to enter the command /invite @[botname] which will invite our bot to our channel.

And once added, we're done with setting up Slack!

Create a Github Action to notify Slack

Our next step will be somewhat similar to when we created our first Github Action. We'll create a workflow file which we'll configure to send our notifications.

While we can use our code editors to do this by creating a file in the .github directory, I'm going to use the Github UI.

First, let's navigate back to our Actions tab in our repository. Once there, select New workflow.

This time, we're going to start the workflow manually instead of using a pre-made Action. Select set up a workflow yourself at the top.

Once the new page loads, you'll be dropped in to a new template where we can start working. Here's what our new workflow will look like:

name: Slack Notifications on: pull_request: branches: [ master ] jobs: notifySlack: runs-on: ubuntu-latest steps: - name: Notify slack env: SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }} uses: abinoda/[email protected] with: args: '{\"channel\":\"[Channel ID]\",\"blocks\":[{\"type\":\"section\",\"text\":{\"type\":\"mrkdwn\",\"text\":\"*Pull Request:* ${{ github.event.pull_request.title }}\"}},{\"type\":\"section\",\"text\":{\"type\":\"mrkdwn\",\"text\":\"*Who?:* ${{ github.event.pull_request.user.login }}\n*Request State:* ${{ github.event.pull_request.state }}\"}},{\"type\":\"section\",\"text\":{\"type\":\"mrkdwn\",\"text\":\"\"}}]}' 

So what's happening in the above?

  • name: we're setting a friendly name for our workflow
  • on: we want our workflow to trigger when there's a pull request is created that targets our master branch
  • jobs: we're creating a new job called notifySlack
  • jobs.notifySlack.runs-on: we want our job to run on a basic setup of the latest Unbuntu
  • jobs.notifySlack.steps: we really only have one step here - we're using a pre-existing Github Action called Slack Action and we're configuring it to publish a notification to our Slack

There are two points here we'll need to pay attention to, the env.SLACK_BOT_TOKEN and the with.args.

In order for Github to communicate with Slack, we'll need a token. This is what we're setting in env.SLACK_BOT_TOKEN. We generated this token in the first step. Now that we'll be using this in our workflow configuration, we'll need to add it as a Git Secret in our project.

The  with.args property is what we use to configure the payload to the Slack API that includes the channel ID (channel) and our actual message (blocks).

The payload in the arguments is stringified and escaped. For example, when expanded it looks like this:

{ "channel": "[Channel ID]", "blocks": [{ "type": "section", "text": { "type": "mrkdwn", "text": "*Pull Request:* ${{ github.event.pull_request.title }}" } }, { "type": "section", "text": { "type": "mrkdwn", "text": "*Who?:*n${{ github.event.pull_request.user.login }}n*State:*n${{ github.event.pull_request.state }}" } }, { "type": "section", "text": { "type": "mrkdwn", "text": "" } }] } 

Note: this is just to show what the content looks like, we need to use the original file with the stringified and escaped argument.

Back to our configuration file, the first thing we set is our channel ID. To find our channel ID, you'll need to use the Slack web interface. Once you open Slack in your browser, you want to find your channel ID in the URL:

//app.slack.com/client/[workspace ID]/[channel ID] 

With that channel ID, you can modify our workflow configuration and replace [Channel ID] with that ID:

with: args: '{\"channel\":\"C014RMKG6H2\",... 

The rest of the arguments property is how we set up our message. It includes variables from the Github event that we use to customize our message.

We won't go into tweaking that here, as what we already have will send a basic pull request message, but you can test out and build your own payload with Slack's Block Kit Builder.

Follow along with the commit!

Test out our Slack workflow

So now we have our workflow configured with our Slack app, finally we're ready to use our bot!

For this part, all we need to do is create a new pull request with any change we want. To test this out, I simply created a new branch where I added a sentence to the README.md file.

Once you create that pull request, similar to our tests workflow, Github will run our Slack workflow! You can see this running in the Actions tab just like before.

As long as you set everything up correctly, once the workflow runs, you should now have a new message in Slack from your new bot.

Note: we won't be merging that pull request in.

What else can we do?

Customize your Slack notifications

The message I put together is simple. It tells us who created the pull request and gives us a link to it.

To customize the formatting and messaging, you can use the Github Block Kit Builder to create your own.

If you'd like to include additional details like the variables I used for the pull request, you can make use of Github's available contexts. This lets you pull information about the environment and the job to customize your message.

I couldn't seem to find any sample payloads, so here's an example of a sample github context payload you would expect in the event.

Sample github context

Flere Github-handlinger

Med vores evne til at oprette nye tilpassede arbejdsgange er det ikke meget, vi ikke kan automatisere. Github har endda en markedsplads, hvor du kan søge rundt efter en.

Hvis du har lyst til at tage det et skridt videre, kan du endda oprette din egen! Dette giver dig mulighed for at oprette scripts til at konfigurere en arbejdsgang til at udføre de opgaver, du har brug for til dit projekt.

Deltag i samtalen!

. @ github Handlinger er en fantastisk måde at automatisere din udviklingsworkflow på?

Du kan gøre ting som at automatisere kørende tests og sende underretninger til @slack! ?

Her leder jeg dig gennem, hvad Handlinger er, og hvordan du kan bruge dem til dit projekt

? // t.co/CNDIsNXbhm

- Colby Fayock (@colbyfayock) 3. juni 2020

Hvad bruger du Github-handlinger til?

Del med mig på Twitter!

Follow me for more Javascript, UX, and other interesting things!

  • ? Følg mig på Twitter
  • ? ️ Abonner på min Youtube
  • ✉️ Tilmeld dig mit nyhedsbrev