Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Write your own GitHub JavaScript Action and automate customized tasks unique to your workflow.

License

NotificationsYou must be signed in to change notification settings

skills/write-javascript-actions

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

54 Commits
 
 
 
 
 
 
 
 

Welcome

Write your own GitHub JavaScript Action and automate customized tasks unique to your workflow.

  • Who is this for: Developers, GitHub users, users new to Git, students, managers, and for teams.
  • What you'll learn: How to consume actions within a workflow file, create custom JavaScript based actions and publish your newly created action to the marketplace.
  • Prerequisites: Before you start, you should be familiar with GitHub, GitHub Actions, and Continuous Integration with GitHub Actions.
  • How long: This course is 6 steps long and takes about 1 to 2 hours to be completed.

How to start this course

  1. Right-clickStart course and open the link in a new tab.
    start-course
  2. In the new tab, follow the prompts to create a new repository.
    • For owner, choose your personal account or an organization to host the repository.
    • We recommend creating a public repository—private repositories willuse Actions minutes.Create a new repository
  3. After your new repository is created, wait about 20 seconds, then refresh the page. Follow the step-by-step instructions in the new repository's README.

Step 1: Initialize a new JavaScript project

Welcome to the course 🎉

Configuring a workflow

Actions are enabled on your repository by default, but we still have to tell our repository to use them. We do this by creating a workflow file in our repository.

Aworkflow file can be thought of as the recipe for automating a task. They house the start to finish instructions, in the form ofjobs andsteps, for what should happen based on specific triggers.

Your repository can contain multipleworkflow files that carry out a wide variety of tasks. It is important to consider this when deciding on a name for yourworkflow. The name you choose should reflect the tasks being performed.

In our case, we will use this oneworkflow file for many things, which leads us to break this convention for teaching purposes.

Read more aboutworkflows

On to your development environment

Our JavaScript actions are going to leverage theGitHub ToolKit for developing GitHub Actions.

This is an external library that we will install usingnpm which means that you will needNode.js installed.

We find writing actions to be easier from a local environment vs trying to do everything right here in the repository. Doing these steps locally allows you to use the editor of your choice so that you have all the extensions and snippets you are used to when writing code.

If you do not have a preferred environment then we suggest following along exactly as you see on the screen, which means you'll need to installVisual Studio Code.

Don't forget to set up your workstation

Most of your work going forward will take place away from your Skills repository, so before continuing with the course ensure you have the following installed on yourlocal machine.

  1. Node.js
  2. Visual Studio Code or your editor of choice
  3. Git

⌨️ Activity 1: Initialize a new JavaScript project

Once you have the necessary tools installed locally, follow these steps to begin creating your first action.

  1. Open theTerminal (Mac and Linux) orCommand Prompt (Windows) on your local machine
  2. Clone your Skills repo to your local machine:
    git clone<this repository URL>.git
  3. Navigate to the folder you just cloned:
    cd<local folder with cloned repo>
  4. We are using branch calledmain.
    git switch main
  5. Create a new folder for our actions files:
    mkdir -p .github/actions/joke-action
  6. Navigate to thejoke-action folder you just created:
    cd .github/actions/joke-action
  7. Initialize a new project:
    npm init -y
  8. Install therequest,request-promise and@actions/core dependencies usingnpm from the [GitHub ToolKit] (https://github.com/actions/toolkit):
    npm install --save request request-promise @actions/core
  9. Commit those newly added files,we will remove the need to uploadnode_modules in a later step:
    git add.git commit -m'add project dependencies'
  10. Push your changes to your repository:
    git push
  11. Wait about 20 seconds then refresh this page for the next step.

Step 2: Configure Your Action

Let's keep going! 🚲

Excellent!

Now that we have the custom action pre-requisites, let us createjoke-action action.

⌨️ Activity 1: Configure Your Action

All of the following steps take place inside of the.github/actions/joke-action directory.

We will start with using the parameters that arerequired and later implement some optional parameters as our action evolves.

  1. Create a new file in:.github/actions/joke-action/action.yml
  2. Add the following contents to the.github/actions/joke-action/action.yml file:
    name:"my joke action"description:"use an external API to retrieve and display a joke"runs:using:"node16"main:"main.js"
  3. Save theaction.yml file
  4. Commit the changes and push them to themain branch:
    git add action.ymlgit commit -m'create action.yml'git pullgit push
  5. Wait about 20 seconds then refresh this page for the next step.

Step 3: Create the metadata file

Nice working configuring your action 😄

Action metadata

Every GitHub Action that we write needs to be accompanied by a metadata file. This file has a few rules to it, as are indicated below:

  • Filenamemust beaction.yml.
  • Required for both Docker container and JavaScript actions.
  • Written in YAML syntax.

This file defines the following information about your action:

ParameterDescriptionRequired
NameThe name of your action. Helps visually identify the actions in a job.
DescriptionA summary of what your action does.
InputsInput parameters allow you to specify data that the action expects to use during runtime. These parameters become environment variables in the runner.
OutputsSpecifies the data that subsequent actions can use later in the workflow after the action that defines these outputs has run.
RunsThe command to run when the action executes.
BrandingYou can use a color and Feather icon to create a badge to personalize and distinguish your action in GitHub Marketplace.

Read more aboutAction metadata

⌨️ Activity 1: Create the metadata file

All of the following steps take place inside of the.github/actions/joke-action directory.

Our action does not require much metadata for it to run correctly. We will not be accepting any inputs, we will however be setting a single output this time.

  1. Update the action metadata file.github/actions/joke-action/action.yml with the following content:
    name:"my joke action"description:"use an external API to retrieve and display a joke"outputs:joke-output:description:The resulting joke from the icanhazdadjokes APIruns:using:"node16"main:"main.js"
  2. Save theaction.yml file
  3. Commit the changes and push them to GitHub:
    git add action.ymlgit commit -m'add metadata for the joke action'git pullgit push
  4. Wait about 20 seconds then refresh this page for the next step.

Step 4: Create the JavaScript files for your action

Good job adding the metadata file! 💃

Files

As you probably know, in JavaScript and other programming languages it is common to break your code into modules so that it is easier to read and maintain going forward. Since JavaScript actions are just programs written in JavaScript that run based on a specific trigger we are able to make our action code modular as well.

To do so we will create two files. One of them will contain the logic to reach out to an external API and retrieve a joke for us, the other will call that module and print the joke to the actions console for us. We will be extending this functionality in our third and final action.

Fetching a joke

Joke API

The first file will bejoke.js and it will fetch our joke for us. We will be using theicanhazdadjoke API for our action. This API does not require any authentication, but it does however that we set a few parameters in theHTTP headers. We need to point out what those are when we get to the code, however it is outside of the scope of this course to cover HTTP in any depth.

When we make our request to this API we will get back a JSON Object in the response. That Object looks like this:

{  id: '0LuXvkq4Muc',  joke: "I knew I shouldn't steal a mixer from work, but it was a whisk I was willing to take.",  status: 200}

It contains 3 key/value pairs of data that we can use in our own program or service. In our case, we are only interested in thejoke field.

Joke Module

We will create a file namedjoke.js and it will reside in the.github/action/joke-action directory.

The joke module will look like this:

constrequest=require("request-promise");constoptions={method:"GET",uri:"https://icanhazdadjoke.com/",headers:{Accept:"application/json","User-Agent":"Writing JavaScript action GitHub Skills course."},json:true};asyncfunctiongetJoke(){constres=awaitrequest(options);returnres.joke;}module.exports=getJoke;
Need an advanced description of thejoke.js source code?We first bring in the `request-promise` library that we installed earlier using `npm`.

Next we define a set ofoptions that therequest-promise library will use when it makes the request.

Read more aboutrequest-promise

Inside of theoptions block we add a key namedheaders. This defines the HTTP headers that theicanhazdadjoke API expects in each request that comes it's way.

icanhazdadjoke cares the most about the keys,Accept andUser-Agent, so we need to make sure we fill them in.

Next we define anasynchronous JavaScript function to make the request for us, storing the JSON Object that is returned in a variable namedres.

Lastly, wereturn theres.joke which is only the value associated with thejoke key of the JSON Object. This value will be random every time our action runs because of how we are interacting with theicanhazdadjoke API.

This file finishes up by exporting the newly created function so that we can use it in ourmain.js file.

Creating the main entry point for your action

Main Module

We will also create a file namedmain.js that resides inside of the.github/actions/joke-action directory.

That file will look like this:

constgetJoke=require("./joke");constcore=require("@actions/core");asyncfunctionrun(){constjoke=awaitgetJoke();console.log(joke);core.setOutput("joke-output",joke);}run();
Need an advanced description of themain.js source code?Like we did in the `joke.js` file, we are first going to bring in our dependencies. Only this time, our dependencies include something we wrote! To do that we simply use `require()` to point to the location of the file we wish to bring in.

We also bring in@actions/core so that we can set the output of our action.

Next we write anotherasynchronous JavaScript function that stores the return value ofgetJoke() in a variable calledjoke.

Then we log the joke to the console.

Finally we finish the function with by setting the contents of the joke as the value of thejoke-output output parameter. We will use this output later in the course.Don't forget to call therun() function.

⌨️ Activity 1: Creating the JavaScript files for your new action.

  1. Create and add the following contents to the.github/actions/joke-action/joke.js file:

    constrequest=require("request-promise");constoptions={method:"GET",uri:"https://icanhazdadjoke.com/",headers:{Accept:"application/json","User-Agent":"Writing JavaScript action GitHub Skills course."},json:true};asyncfunctiongetJoke(){constres=awaitrequest(options);returnres.joke;}module.exports=getJoke;
  2. Save thejoke.js file.

  3. Create and add the following contents to the.github/actions/joke-action/main.js file:

    constgetJoke=require("./joke");constcore=require("@actions/core");asyncfunctionrun(){constjoke=awaitgetJoke();console.log(joke);core.setOutput("joke-output",joke);}run();
  4. Save themain.js file.

  5. Commit the changes to this branch and push them to GitHub:

    git add joke.js main.jsgit commit -m'creating joke.js and main.js'git pullgit push

Step 5: Add your action to the workflow file

Great job! 🎉

All of the following steps will add the action to the workflow file that’s already in the repomy-workflow.yml file

⌨️ Activity 1: Edit the custom action at the bottom of the workflow file.

      -name:ha-hauses:./.github/actions/joke-action

Here is what the full file should look like (we’re using issues instead of the pull request event and removing the reference to the hello world action.)

name:JS Actionson:issues:types:[labeled]jobs:action:if:${{ !github.event.repository.is_template }}runs-on:ubuntu-lateststeps:      -uses:actions/checkout@v3      -name:ha-hauses:./.github/actions/joke-action

You can make these changes in your repository by openingmy-workflow.yml in another browser tab andediting the file directly. Make sure to select theCommit directly to the main branch option.

Step 6: Trigger the joke action

Great job! ❤️

Everything is all set up and now we are ready to start laughing. You will find you have some joke related labels available to you in this repository. You don't have to use them, any label will trigger our workflow, but the easiest way to follow along would be to use suggested labels.

Trigger a joke

  1. Open issue #1 in the "Issues tab"
  2. Apply thefirst-joke label to the issue
  3. Wait a few seconds and then apply thesecond-joke label to the issue
  4. Check theJS Actions workflow results on the "Actions tab"

Finish

celebrate

Congratulations, you've completed this course!

In this course, you've learned a lot about developing custom actions using JavaScript and Actions Toolkit.

Publishing your actions

Publishing your actions is a great way to help others in your team and across the GitHub community. Although actions do not need to be published to be consumed, by adding them to the marketplace you make them easier to find.

Some notable actions you will find on the marketplace are:

And that just scratches the surface of the 1600+ and counting actions you will find on the marketplace

Followthis guide to learn how to publish your actions to the GitHub Marketplace

What's next?


Get help:Post in our discussion boardReview the GitHub status page

© 2022 GitHub •Code of ConductCC-BY-4.0 License

About

Write your own GitHub JavaScript Action and automate customized tasks unique to your workflow.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Contributors20


[8]ページ先頭

©2009-2025 Movatter.jp