├── .eslintrc.js ├── .github └── workflows │ ├── publish.yml │ └── test.yml ├── .gitignore ├── .npmrc ├── CODE_OF_CONDUCT.md ├── Dockerfile ├── LICENSE ├── README.md ├── action.yml ├── cli.js ├── entrypoint.sh ├── index.js ├── jest.config.js ├── package-lock.json ├── package.json ├── prettier.config.js └── src ├── __tests__ ├── .eslintrc.json ├── __utils.js ├── context.js └── publish.js ├── context.js ├── publish.js ├── read-json.js └── run-dry.js /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | node: true 4 | }, 5 | extends: [ 6 | 'plugin:github/es6' 7 | ], 8 | rules: { 9 | 'no-console': 0 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | on: [push] 3 | 4 | jobs: 5 | 6 | publish: 7 | name: Publish 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v1 11 | 12 | - name: Install dependencies 13 | run: yarn 14 | 15 | - name: Publish to the npm registry 16 | uses: "./" 17 | with: 18 | npm_args: "--unsafe-perm --allow-same-version" 19 | default_branch: "main" 20 | env: 21 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 22 | NPM_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }} -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Lint & Test 2 | on: [push] 3 | 4 | jobs: 5 | test: 6 | name: Tests 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v1 10 | 11 | - name: Install dependencies 12 | run: npm ci 13 | 14 | - name: Lint 15 | run: npm run lint 16 | 17 | - name: Test 18 | run: npm test 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | git-tag-version=false 2 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at design-systems@github.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:10-slim 2 | 3 | LABEL com.github.actions.name="Primer publish" 4 | LABEL com.github.actions.icon="package" 5 | LABEL com.github.actions.color="blue" 6 | 7 | LABEL version="0.1.0" 8 | LABEL repository="http://github.com/primer/actions" 9 | LABEL homepage="http://github.com/primer/actions/tree/master/deploy" 10 | LABEL maintainer="GitHub Design Systems " 11 | 12 | RUN apt-get update && \ 13 | apt-get install -y --no-install-recommends git jq 14 | 15 | WORKDIR /primer-publish 16 | COPY . . 17 | RUN npm install --production 18 | 19 | ENTRYPOINT ["/primer-publish/entrypoint.sh"] 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Primer 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # primer/publish 2 | 3 | This [GitHub Action][github actions] publishes to npm with the following conventions: 4 | 5 | 1. If we're on the default branch, the `version` field is used as-is and we just run `npm publish --access public`. 6 | - After publishing a new version on the default branch, we tag the commit SHA with `v{version}` via the GitHub API. 7 | - If the version in `package.json` is already published, we exit with a `0` code. Previously, we exited with a `78` code, which was Actions v1-speak for "neutral", but this has been [removed from Actions v2](https://twitter.com/ethomson/status/1163899559279497217?s=20). 8 | 1. If we're on a `release-` branch, we publish a release candidate to the `next` npm dist-tag with the version in the form: `-rc.`. 9 | - A [status check][status checks] is created with the context `npm version` noting whether the `version` field in `package.json` matches the `` portion of the branch. If it doesn't, the check's status is marked as pending. 10 | 1. Otherwise, we publish a "canary" release, which has a version in the form: `0.0.0-`. 11 | 12 | ## Status checks 13 | 14 | Depending on the branch, a series of [statuses][status checks] will be created by this action in your checks: **publish** is the action's check, and **publish {package-name}** is a [commit status] created by the action that reports the version published and links to `unpkg.com` via "Details": 15 | 16 | ![image](https://user-images.githubusercontent.com/113896/52375286-23368980-2a14-11e9-8974-062a3e45a846.png) 17 | 18 | If you're on a release branch (`release-`) and the `` portion of the branch name doesn't match the `version` field in `package.json`, you'll get a pending status reminding you to update it: 19 | 20 | ![image](https://user-images.githubusercontent.com/113896/52388530-b63ae800-2a43-11e9-92ef-14ec9459c109.png) 21 | 22 | ## Usage 23 | 24 | **You will need to provide an npm access token with publish permissions via the `NPM_AUTH_TOKEN` secret in the Actions visual editor** if you haven't already. The `GITHUB_TOKEN` secret is also required to create tags after releasing on the master branch. 25 | 26 | We suggest that you place this action after any linting and/or testing actions to catch as many errors as possible before publishing. 27 | 28 | 29 | ### Actions 30 | To use this in an Actions workflow, add the following YAML to one or more of your steps: 31 | 32 | ```yaml 33 | - uses: primer/publish@v3 34 | env: 35 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 36 | NPM_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }} 37 | ``` 38 | 39 | You can pass additional [inputs](#inputs) via the `with` key: 40 | 41 | ```hcl 42 | - name: Publish to the npm registry 43 | uses: "primer/publish@3.0.0" 44 | with: 45 | npm-args: "--unsafe-perm --allow-same-version" 46 | default-branch: "main" 47 | ``` 48 | 49 | 50 | ## Inputs 51 | 52 | ### `dry_run` 53 | 54 | Does everything publish would do except actually publishing to the registry. Reports the details of what would have been published. 55 | 56 | Default: `false` 57 | 58 | #### Example 59 | 60 | ```hcl 61 | - name: Publish to the npm registry 62 | uses: "primer/publish@3.0.0" 63 | with: 64 | dry_run: true 65 | ``` 66 | 67 | ### `dir` 68 | 69 | Accepts a path to the directory that contains the `package.json` to publish. 70 | 71 | Default: `.` 72 | 73 | #### Example 74 | 75 | ```hcl 76 | - name: Publish to the npm registry 77 | uses: "primer/publish@3.0.0" 78 | with: 79 | dir: "packages/example" 80 | } 81 | ``` 82 | 83 | ### `npm_args` 84 | 85 | It's possible to pass additional arguments to `npm` via the `npm_args` input in your workflow action. 86 | 87 | ```hcl 88 | - name: Publish to the npm registry 89 | uses: "primer/publish@3.0.0" 90 | with: 91 | npm_args: "--unsafe-perm --allow-same-version" 92 | ``` 93 | 94 | ### `default_branch` 95 | 96 | The branch you'd like to use to trigger releases. Typically this is `main` or `master`. 97 | 98 | Default: `master` 99 | 100 | ```hcl 101 | - name: Publish to the npm registry 102 | uses: "primer/publish@3.0.0" 103 | with: 104 | default_branch: "main" 105 | ``` 106 | 107 | ### `release_tag` 108 | 109 | The `release_tag` input can be used to override the auto-generated release tag. 110 | 111 | Default: `latest` 112 | 113 | ```hcl 114 | - name: Publish to the npm registry 115 | uses: "primer/publish@3.0.0" 116 | with: 117 | release_tag: "1.0.0" 118 | ``` 119 | 120 | [github actions]: https://github.com/features/actions 121 | [commit status]: https://developer.github.com/v3/repos/statuses/ 122 | [status checks]: https://help.github.com/articles/about-status-checks/ 123 | -------------------------------------------------------------------------------- /action.yml: -------------------------------------------------------------------------------- 1 | name: '@primer/publish' 2 | description: 'Publish Primer projects to npm with GitHub Design Systems conventions' 3 | inputs: 4 | default_branch: 5 | description: 'Branch that releases should be cut from (usually your default branch)' 6 | required: false 7 | dir: 8 | description: "directory to find package.json in" 9 | required: false 10 | dry_run: 11 | description: "run action without publishing" 12 | required: false 13 | npm_args: 14 | description: "publish options & additional npm cli arguments" 15 | required: false 16 | release_tag: 17 | description: 'Override tag to release package with' 18 | required: false 19 | default: 'latest' 20 | runs: 21 | using: 'docker' 22 | image: 'Dockerfile' 23 | args: 24 | - ${{inputs.npm_args}} -------------------------------------------------------------------------------- /cli.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | const publish = require('./src/publish') 3 | 4 | const yargs = require('yargs') 5 | .option('dry-run', { 6 | describe: 'Print what will be done without doing it', 7 | default: process.env.INPUT_DRY_RUN || false, 8 | type: 'boolean' 9 | }) 10 | .option('dir', { 11 | describe: 'Path to the directory that contains the package.json to publish', 12 | type: 'string', 13 | default: process.env.INPUT_DIR || '.' 14 | }) 15 | .option('default-branch', { 16 | describe: 'Default branch to use for merge releases', 17 | type: 'string', 18 | default: process.env.INPUT_DEFAULT_BRANCH || 'master' 19 | }) 20 | .option('release-tag', { 21 | describe: 'Override tag to release package with', 22 | type: 'string', 23 | default: process.env.INPUT_RELEASE_TAG || 'latest' 24 | }) 25 | .alias('help', 'h') 26 | 27 | const options = yargs.argv 28 | 29 | if (options.help) { 30 | yargs.showHelp() 31 | process.exit(0) 32 | } 33 | 34 | const npmArgs = options._ 35 | delete options._ 36 | 37 | console.warn(`[publish] options: ${JSON.stringify(options, null, 2)}`) 38 | console.warn(`[publish] npm args: ${JSON.stringify(npmArgs, null, 2)}`) 39 | 40 | publish(options, npmArgs) 41 | .then(context => { 42 | console.warn(`published! ${JSON.stringify(context, null, 2)}`) 43 | }) 44 | .catch(error => { 45 | console.error(error) 46 | process.exitCode = 1 47 | }) 48 | -------------------------------------------------------------------------------- /entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | # Actions v1 reported a neutral status when a process exited with a 78 code. 5 | # Actions v2 removed support for this, so exit with a 0 code instead 6 | neutral_exit() { 7 | EXIT_CODE=$? 8 | [[ $EXIT_CODE == "78" ]] && exit 0 || exit $EXIT_CODE 9 | } 10 | trap neutral_exit EXIT 11 | 12 | # copied directly from: 13 | # https://github.com/actions/npm/blob/98e6dc1/entrypoint.sh#L5-L13 14 | if [ -n "$NPM_AUTH_TOKEN" ]; then 15 | # Respect NPM_CONFIG_USERCONFIG if it is provided, default to $HOME/.npmrc 16 | NPM_CONFIG_USERCONFIG="${NPM_CONFIG_USERCONFIG-"$HOME/.npmrc"}" 17 | NPM_REGISTRY_URL="${NPM_REGISTRY_URL-"registry.npmjs.org"}" 18 | 19 | # Allow registry.npmjs.org to be overridden with an environment variable 20 | printf "//%s/:_authToken=%s\\nregistry=%s" "$NPM_REGISTRY_URL" "$NPM_AUTH_TOKEN" "$NPM_REGISTRY_URL" > "$NPM_CONFIG_USERCONFIG" 21 | chmod 0600 "$NPM_CONFIG_USERCONFIG" 22 | fi 23 | 24 | # configure git with sensible defaults 25 | git config --global user.email "${GIT_USER_EMAIL:-$(jq -r .pusher.email $GITHUB_EVENT_PATH)}" 26 | git config --global user.name "${GIT_USER_NAME:-$(jq -r .pusher.name $GITHUB_EVENT_PATH)}" 27 | # then print out our config 28 | git config --list 29 | 30 | sh -c "/primer-publish/cli.js -- $*" 31 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | module.exports = require('./src/publish') 2 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | testPathIgnorePatterns: ['__utils.js$'] 3 | } 4 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@primer/publish", 3 | "version": "3.0.0", 4 | "description": "Publish Primer projects to npm with GitHub Design Systems conventions", 5 | "keywords": [ 6 | "primer", 7 | "publish", 8 | "github-actions", 9 | "npm" 10 | ], 11 | "author": "GitHub, Inc.", 12 | "license": "MIT", 13 | "main": "index.js", 14 | "bin": { 15 | "primer-publish": "cli.js" 16 | }, 17 | "scripts": { 18 | "lint": "eslint *.js src", 19 | "test": "jest" 20 | }, 21 | "dependencies": { 22 | "@octokit/rest": "^16.15.0", 23 | "action-status": "^0.1.1", 24 | "github-action-meta": "^0.1.2", 25 | "yargs": "^12.0.5" 26 | }, 27 | "devDependencies": { 28 | "eslint": "^5.13.0", 29 | "eslint-plugin-github": "^1.8.1", 30 | "jest": "^24.1.0", 31 | "mocked-env": "^1.2.4", 32 | "prettier": "^1.16.4" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | module.exports = require('eslint-plugin-github/prettier.config') 2 | -------------------------------------------------------------------------------- /src/__tests__/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "jest": true 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /src/__tests__/__utils.js: -------------------------------------------------------------------------------- 1 | const readJSON = require('../read-json') 2 | 3 | module.exports = { 4 | mockFiles 5 | } 6 | 7 | function mockFiles(files) { 8 | readJSON.mockImplementation(path => { 9 | if (path in files) { 10 | return files[path] 11 | } 12 | }) 13 | } 14 | -------------------------------------------------------------------------------- /src/__tests__/context.js: -------------------------------------------------------------------------------- 1 | const mockedEnv = require('mocked-env') 2 | const getContext = require('../context') 3 | const readJSON = require('../read-json') 4 | const {mockFiles} = require('./__utils') 5 | 6 | jest.mock('../read-json') 7 | 8 | describe('getContext()', () => { 9 | const defaultPackageJson = { 10 | name: 'default-package', 11 | version: '0.0.1' 12 | } 13 | 14 | let restoreEnv = () => {} 15 | 16 | beforeEach(() => { 17 | mockFiles({'package.json': defaultPackageJson}) 18 | }) 19 | 20 | afterEach(() => { 21 | restoreEnv() 22 | readJSON.mockReset() 23 | }) 24 | 25 | it('throws if it is unable to read package.json', () => { 26 | mockFiles({}) 27 | expect(() => getContext()).toThrow() 28 | }) 29 | 30 | it('throws if package.json does not exist in given directory', () => { 31 | expect(() => getContext({dir: 'foo/bar'})).toThrow() 32 | }) 33 | 34 | it('throws if "private": true in package.json', () => { 35 | mockFiles({'package.json': {private: true}}) 36 | expect(() => getContext()).toThrow() 37 | }) 38 | 39 | it('throws if there is no "name" field in package.json', () => { 40 | mockFiles({'package.json': {name: ''}}) 41 | expect(() => getContext()).toThrow() 42 | }) 43 | 44 | it('gets the canary version by default', () => { 45 | mockEnv({ 46 | GITHUB_REF: 'refs/heads/feat-x', 47 | GITHUB_SHA: '50faded' 48 | }) 49 | return getContext().then(context => { 50 | expect(context.version).toBe('0.0.0-50faded') 51 | expect(context.tag).toBe('canary') 52 | }) 53 | }) 54 | 55 | it('gets the release candidate version if the branch matches /^release-/', () => { 56 | mockEnv({ 57 | GITHUB_REF: 'refs/heads/release-1.0.0', 58 | GITHUB_SHA: 'deadfad' 59 | }) 60 | return getContext().then(context => { 61 | expect(context.version).toBe('1.0.0-rc.deadfad') 62 | expect(context.tag).toBe('next') 63 | }) 64 | }) 65 | 66 | it('generates a pending "npm version" status for release branches', () => { 67 | mockFiles({ 68 | 'package.json': {name: 'foo', version: '0.4.2'} 69 | }) 70 | mockEnv({ 71 | GITHUB_REF: 'refs/heads/release-1.0.0', 72 | GITHUB_REPOSITORY: 'primer/foo', 73 | GITHUB_SHA: 'deadfad' 74 | }) 75 | return getContext().then(context => { 76 | expect(context.status).toEqual({ 77 | context: 'npm version', 78 | state: 'pending', 79 | description: `Remember to set "version": "1.0.0" in package.json`, 80 | url: 'https://github.com/primer/foo/edit/release-1.0.0/package.json' 81 | }) 82 | }) 83 | }) 84 | 85 | it('generates a success "npm version" status for release branches', () => { 86 | mockFiles({ 87 | 'package.json': {name: 'foo', version: '1.0.0'} 88 | }) 89 | mockEnv({ 90 | GITHUB_REF: 'refs/heads/release-1.0.0', 91 | GITHUB_REPOSITORY: 'primer/foo', 92 | GITHUB_SHA: 'deadfad' 93 | }) 94 | return getContext().then(context => { 95 | expect(context.packageJson).toEqual({name: 'foo', version: '1.0.0'}) 96 | expect(context.status).toEqual({ 97 | context: 'npm version', 98 | state: 'success', 99 | description: '1.0.0' 100 | }) 101 | }) 102 | }) 103 | 104 | it('gets the version from package.json if the branch is "master"', () => { 105 | const version = '2.0.1' 106 | mockFiles({ 107 | 'package.json': {name: 'mooch', version} 108 | }) 109 | mockEnv({GITHUB_REF: 'refs/heads/master'}) 110 | return getContext().then(context => { 111 | expect(context.version).toBe(version) 112 | expect(context.tag).toBe('latest') 113 | }) 114 | }) 115 | 116 | it('respects "dir" option', () => { 117 | mockFiles({ 118 | 'foo/bar/package.json': {name: 'example', version: '1.0.0'} 119 | }) 120 | mockEnv({GITHUB_REF: 'refs/heads/master'}) 121 | return getContext({dir: 'foo/bar'}).then(context => { 122 | expect(context.name).toBe('example') 123 | expect(context.version).toBe('1.0.0') 124 | expect(context.tag).toBe('latest') 125 | }) 126 | }) 127 | 128 | function mockEnv(env) { 129 | restoreEnv = mockedEnv(env) 130 | } 131 | }) 132 | -------------------------------------------------------------------------------- /src/__tests__/publish.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | const actionStatus = require('action-status') 3 | const execa = require('execa') 4 | const mockedEnv = require('mocked-env') 5 | const publish = require('../publish') 6 | const readJSON = require('../read-json') 7 | const {mockFiles} = require('./__utils') 8 | 9 | jest.mock('action-status') 10 | jest.mock('execa') 11 | jest.mock('../read-json') 12 | 13 | describe('publish()', () => { 14 | let restoreEnv = () => {} 15 | 16 | const execOpts = {stdio: 'inherit'} 17 | 18 | beforeEach(() => { 19 | execa.mockImplementation(() => Promise.resolve({stdout: '', stderr: ''})) 20 | actionStatus.mockImplementation(() => Promise.resolve()) 21 | }) 22 | 23 | afterEach(() => { 24 | restoreEnv() 25 | execa.mockClear() 26 | readJSON.mockClear() 27 | }) 28 | 29 | it('throws if NPM_AUTH_TOKEN is falsy', () => { 30 | mockFiles({ 31 | 'package.json': {name: 'pkg', version: '1.0.0'} 32 | }) 33 | mockEnv({NPM_AUTH_TOKEN: undefined}) 34 | expect(() => publish()).toThrow() 35 | mockEnv({NPM_AUTH_TOKEN: ''}) 36 | expect(() => publish()).toThrow() 37 | }) 38 | 39 | it('does the right things on a feature branch', () => { 40 | mockEnv({ 41 | GITHUB_REF: 'refs/heads/feature-x', 42 | GITHUB_SHA: 'deadfad', 43 | NPM_AUTH_TOKEN: 'secret' 44 | }) 45 | mockFiles({ 46 | 'package.json': {name: 'pkg', version: '1.0.0'} 47 | }) 48 | const version = '0.0.0-deadfad' 49 | return publish().then(() => { 50 | expect(execa).toHaveBeenCalledTimes(2) 51 | expect(execa).toHaveBeenNthCalledWith( 52 | 1, 53 | 'npm', 54 | ['version', version], 55 | Object.assign({}, execOpts, {cwd: path.join(process.cwd(), '.')}) 56 | ) 57 | expect(execa).toHaveBeenNthCalledWith( 58 | 2, 59 | 'npm', 60 | ['publish', '.', '--tag', 'canary', '--access', 'public'], 61 | execOpts 62 | ) 63 | }) 64 | }) 65 | 66 | it('does the right things on a release branch', () => { 67 | mockEnv({ 68 | GITHUB_REF: 'refs/heads/release-2.0.0', 69 | GITHUB_SHA: 'deadfad', 70 | NPM_AUTH_TOKEN: 'secret' 71 | }) 72 | mockFiles({ 73 | 'package.json': {name: 'pkg', version: '1.0.0'} 74 | }) 75 | const version = '2.0.0-rc.deadfad' 76 | return publish().then(() => { 77 | expect(execa).toHaveBeenCalledTimes(2) 78 | expect(execa).toHaveBeenNthCalledWith( 79 | 1, 80 | 'npm', 81 | ['version', version], 82 | Object.assign({}, execOpts, {cwd: path.join(process.cwd(), '.')}) 83 | ) 84 | expect(execa).toHaveBeenNthCalledWith(2, 'npm', ['publish', '.', '--tag', 'next', '--access', 'public'], execOpts) 85 | }) 86 | }) 87 | 88 | it('does the right things on master', () => { 89 | const version = '1.1.0' 90 | mockEnv({ 91 | GITHUB_REF: 'refs/heads/master', 92 | GITHUB_SHA: 'deadfad', 93 | NPM_AUTH_TOKEN: 'secret' 94 | }) 95 | mockFiles({ 96 | 'package.json': {name: 'pkg', version} 97 | }) 98 | return publish().then(() => { 99 | expect(execa).toHaveBeenCalledTimes(2) 100 | expect(execa).toHaveBeenNthCalledWith(1, 'npm', ['view', `pkg@${version}`, 'version'], {stderr: 'inherit'}) 101 | expect(execa).toHaveBeenNthCalledWith( 102 | 2, 103 | 'npm', 104 | ['publish', '.', '--tag', 'latest', '--access', 'public'], 105 | execOpts 106 | ) 107 | // expect(execa).toHaveBeenNthCalledWith(3, 'git', ['tag', `v${version}`], execOpts) 108 | // expect(execa).toHaveBeenNthCalledWith(4, 'git', ['push', '--tags', 'origin'], execOpts) 109 | }) 110 | }) 111 | 112 | it('respects the "dryRun" option', () => { 113 | mockEnv({ 114 | GITHUB_REF: 'refs/heads/run-dry', 115 | GITHUB_SHA: 'bedface', 116 | NPM_AUTH_TOKEN: 'secret' 117 | }) 118 | mockFiles({ 119 | 'package.json': {name: 'pkg', version: '1.0.0'} 120 | }) 121 | return publish({dryRun: true, dir: '.'}).then(() => { 122 | expect(execa).toHaveBeenCalledTimes(0) 123 | }) 124 | }) 125 | 126 | it('respects "dir" option on master', () => { 127 | const version = '1.1.0' 128 | mockEnv({ 129 | GITHUB_REF: 'refs/heads/master', 130 | GITHUB_SHA: 'deadfad', 131 | NPM_AUTH_TOKEN: 'secret' 132 | }) 133 | mockFiles({ 134 | 'foo/bar/package.json': {name: 'pkg', version} 135 | }) 136 | return publish({dir: 'foo/bar'}).then(() => { 137 | expect(execa).toHaveBeenCalledTimes(2) 138 | expect(execa).toHaveBeenNthCalledWith(1, 'npm', ['view', `pkg@${version}`, 'version'], {stderr: 'inherit'}) 139 | expect(execa).toHaveBeenNthCalledWith( 140 | 2, 141 | 'npm', 142 | ['publish', 'foo/bar', '--tag', 'latest', '--access', 'public'], 143 | execOpts 144 | ) 145 | }) 146 | }) 147 | 148 | it('respects "dir" option on a release branch', () => { 149 | mockEnv({ 150 | GITHUB_REF: 'refs/heads/release-2.0.0', 151 | GITHUB_SHA: 'deadfad', 152 | NPM_AUTH_TOKEN: 'secret' 153 | }) 154 | mockFiles({ 155 | 'foo/bar/package.json': {name: 'pkg', version: '1.0.0'} 156 | }) 157 | const version = '2.0.0-rc.deadfad' 158 | return publish({dir: 'foo/bar'}).then(() => { 159 | expect(execa).toHaveBeenCalledTimes(2) 160 | expect(execa).toHaveBeenNthCalledWith( 161 | 1, 162 | 'npm', 163 | ['version', version], 164 | Object.assign({}, execOpts, {cwd: path.join(process.cwd(), 'foo/bar')}) 165 | ) 166 | expect(execa).toHaveBeenNthCalledWith( 167 | 2, 168 | 'npm', 169 | ['publish', 'foo/bar', '--tag', 'next', '--access', 'public'], 170 | execOpts 171 | ) 172 | }) 173 | }) 174 | 175 | function mockEnv(env) { 176 | restoreEnv = mockedEnv(env) 177 | } 178 | }) 179 | -------------------------------------------------------------------------------- /src/context.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | const meta = require('github-action-meta') 3 | const readJSON = require('./read-json') 4 | 5 | const RELEASE_BRANCH_PATTERN = /^release-(.+)$/ 6 | const RELEASE_CANDIDATE_PREID = 'rc' 7 | const RELEASE_CANDIDATE_TAG = 'next' 8 | 9 | const CANARY_VERSION = '0.0.0' 10 | const CANARY_TAG = 'canary' 11 | 12 | module.exports = function getContext({dir, defaultBranch, releaseTag} = {}) { 13 | const packageJson = readJSON(path.join(dir, 'package.json')) 14 | if (!packageJson) { 15 | throw new Error(`Unable to read package.json in ${path.join(process.cwd(), dir)}!`) 16 | } 17 | const {name} = packageJson 18 | 19 | // basic sanity checks 20 | if (packageJson.private === true) { 21 | throw new Error(`"private" is true in package.json; bailing`) 22 | } else if (!name) { 23 | throw new Error(`package.json is missing a "name" field`) 24 | } 25 | 26 | let version 27 | let status 28 | let tag = releaseTag 29 | 30 | const {sha, branch} = meta.git 31 | const repo = meta.repo.toString() 32 | 33 | if (branch === defaultBranch) { 34 | version = packageJson.version 35 | } else { 36 | let match 37 | const shortSha = sha.substr(0, 7) 38 | if ((match = branch.match(RELEASE_BRANCH_PATTERN))) { 39 | const v = match[1] 40 | status = Object.assign( 41 | { 42 | context: `npm version` 43 | }, 44 | v === packageJson.version 45 | ? { 46 | state: 'success', 47 | description: v 48 | } 49 | : { 50 | state: 'pending', 51 | description: `Remember to set "version": "${v}" in package.json`, 52 | url: `https://github.com/${repo}/edit/${branch}/package.json` 53 | } 54 | ) 55 | const preid = RELEASE_CANDIDATE_PREID 56 | version = `${v}-${preid}.${shortSha}` 57 | tag = RELEASE_CANDIDATE_TAG 58 | } else { 59 | const v = CANARY_VERSION 60 | version = `${v}-${shortSha}` 61 | tag = CANARY_TAG 62 | } 63 | } 64 | 65 | return Promise.resolve({name, version, tag, packageJson, status}) 66 | } 67 | -------------------------------------------------------------------------------- /src/publish.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | const meta = require('github-action-meta') 3 | const actionStatus = require('action-status') 4 | const getContext = require('./context') 5 | const runDry = require('./run-dry') 6 | 7 | module.exports = function publish(options = {dir: '.'}, npmArgs = []) { 8 | if (!process.env.NPM_AUTH_TOKEN) { 9 | throw new Error(`You must set the NPM_AUTH_TOKEN environment variable`) 10 | } 11 | 12 | const run = options.dryRun ? runDry : require('execa') 13 | const execOpts = {stdio: 'inherit'} 14 | 15 | return getContext(options).then(context => { 16 | const {name, version, tag, packageJson} = context 17 | const {sha} = meta.git 18 | 19 | // this is true if we think we're publishing the version that's in git 20 | const isLatest = packageJson.version === version 21 | 22 | return (context.status ? publishStatus(context, context.status) : Promise.resolve()) 23 | .then(() => { 24 | if (isLatest) { 25 | console.warn(`[publish] skipping "npm version" because "${version}" matches package.json`) 26 | // this is a fairly reliable way to determine whether the package@version is published 27 | return run('npm', ['view', `${name}@${version}`, 'version'], {stderr: 'inherit'}) 28 | .then(({stdout}) => stdout === version) 29 | .then(published => { 30 | if (published) { 31 | console.warn(`[publish] ${version} is already published`) 32 | process.exit(0) 33 | } 34 | }) 35 | } else { 36 | return publishStatus(context, { 37 | state: 'pending', 38 | description: `npm version ${version}` 39 | }).then(() => 40 | run( 41 | 'npm', 42 | [...npmArgs, 'version', version], 43 | Object.assign({}, execOpts, {cwd: path.join(process.cwd(), options.dir)}) 44 | ) 45 | ) 46 | } 47 | }) 48 | .then(() => 49 | publishStatus(context, { 50 | state: 'pending', 51 | description: `npm publish --tag ${tag}` 52 | }) 53 | ) 54 | .then(() => run('npm', [...npmArgs, 'publish', options.dir, '--tag', tag, '--access', 'public'], execOpts)) 55 | .then(() => 56 | publishStatus(context, { 57 | state: 'success', 58 | description: version, 59 | url: `https://unpkg.com/${name}@${version}/` 60 | }) 61 | ) 62 | .then(() => { 63 | if (isLatest) { 64 | const {GITHUB_TOKEN} = process.env 65 | if (!GITHUB_TOKEN) { 66 | console.warn(`[publish] GITHUB_TOKEN is not set; skipping tag`) 67 | return context 68 | } 69 | 70 | const tagContext = 'git tag' 71 | const tag = `v${version}` 72 | 73 | const Octokit = require('@octokit/rest') 74 | const github = new Octokit({auth: `token ${GITHUB_TOKEN}`}) 75 | const {repo} = meta 76 | 77 | return publishStatus(context, { 78 | context: tagContext, 79 | state: 'pending', 80 | description: `Tagging the release as "${tag}"...` 81 | }) 82 | .then(() => 83 | github.git.createRef({ 84 | owner: repo.owner, 85 | repo: repo.name, 86 | sha, 87 | ref: `refs/tags/${tag}` 88 | }) 89 | ) 90 | .then(() => 91 | publishStatus(context, { 92 | context: tagContext, 93 | state: 'success', 94 | description: `Tagged ${sha.substr(0, 7)} as "${tag}"`, 95 | url: `https://github.com/${repo}/releases/new?tag=${tag}` 96 | }) 97 | ) 98 | } 99 | }) 100 | .then(() => context) 101 | }) 102 | } 103 | 104 | function publishStatus(context, options = {}) { 105 | return actionStatus( 106 | Object.assign( 107 | { 108 | context: `publish ${context.name}`, 109 | // note: these need to be empty so that action-status 110 | // doesn't throw an error w/o "required" env vars 111 | description: '', 112 | url: '' 113 | }, 114 | options 115 | ) 116 | ) 117 | } 118 | -------------------------------------------------------------------------------- /src/read-json.js: -------------------------------------------------------------------------------- 1 | const {resolve} = require('path') 2 | const {existsSync} = require('fs') 3 | 4 | module.exports = function readJSON(path) { 5 | const resolved = resolve(process.cwd(), path) 6 | return existsSync(resolved) ? require(resolved) : undefined 7 | } 8 | -------------------------------------------------------------------------------- /src/run-dry.js: -------------------------------------------------------------------------------- 1 | module.exports = function runDry(cmd, args, execOpts = {}) { 2 | console.warn(`[dry-run] ${cmd} ${JSON.stringify(args)} (execOpts: ${JSON.stringify(execOpts)})`) 3 | return Promise.resolve({stdout: '', stderr: ''}) 4 | } 5 | --------------------------------------------------------------------------------