UNPKG

2.82 kBJavaScriptView Raw
1const meta = require('github-action-meta')
2const actionStatus = require('action-status')
3const getContext = require('./get-context')
4const runDry = require('./run-dry')
5
6module.exports = function publish(options = {}, npmArgs = []) {
7 if (!process.env.NPM_AUTH_TOKEN) {
8 throw new Error(`You must set the NPM_AUTH_TOKEN environment variable`)
9 }
10
11 const context = getContext(options)
12 const {name, version, tag, packageJson} = context
13 const isLatest = packageJson.version === version
14 const {branch, sha} = meta.git
15
16 const run = options.dryRun ? runDry : require('execa')
17 const execOpts = {stdio: 'inherit'}
18
19 return Promise.resolve()
20 .then(() => {
21 if (isLatest) {
22 console.warn(`[publish] skipping "npm version" because "${version}" matches package.json`)
23 return checkPublished().then(published => {
24 if (published) {
25 console.warn(`[publish] ${version} is already published; exiting with neutral status`)
26 // see: <https://developer.github.com/actions/creating-github-actions/accessing-the-runtime-environment/#exit-codes-and-statuses>
27 process.exit(78)
28 }
29 })
30 } else {
31 return publishStatus({
32 state: 'pending',
33 description: `npm version ${version}`
34 }).then(() => run('npm', [...npmArgs, 'version', version], execOpts))
35 }
36 })
37 .then(() =>
38 publishStatus({
39 state: 'pending',
40 description: `npm publish --tag ${tag}`
41 })
42 )
43 .then(() => run('npm', [...npmArgs, 'publish', '--tag', tag, '--access', 'public'], execOpts))
44 .then(() =>
45 publishStatus({
46 state: 'success',
47 description: version,
48 url: `https://unpkg.com/${name}@${version}/`
49 })
50 )
51 .then(() => {
52 if (isLatest) {
53 const context = 'git push'
54 return publishStatus({
55 context,
56 state: 'pending',
57 description: 'Pushing HEAD + tags...'
58 })
59 .then(() => run('git', ['push', '--tags', 'HEAD'], execOpts))
60 .then(() =>
61 publishStatus({
62 context,
63 state: 'success',
64 description: `Pushed ${branch} to ${sha.substr(0, 7)}`
65 })
66 )
67 }
68 })
69 .then(() => context)
70
71 function checkPublished() {
72 return run('npm', ['view', `${name}@${version}`, 'version'], {stderr: 'inherit'}).then(({stdout}) => {
73 return stdout === version
74 })
75 }
76
77 function publishStatus(props = {}) {
78 return actionStatus(
79 Object.assign(
80 {
81 context: `publish ${name}`,
82 // note: these need to be empty so that action-status
83 // doesn't throw an error w/o "required" env vars
84 description: '',
85 url: ''
86 },
87 props
88 )
89 )
90 }
91}