๐Ÿ“ฆ hyoban / release-it-pnpm

๐Ÿ“„ index.js ยท 333 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333import fs from 'node:fs'
import { EOL } from 'node:os'

import { versionBump } from 'bumpp'
import { generate, hasTagOnGitHub, isRepoShallow, sendRelease } from 'changelogithub'
import { Bumper } from 'conventional-recommended-bump'
import { blue, bold, cyan, dim, red, yellow } from 'kolorist'
import { Plugin } from 'release-it'
import semver from 'semver'

const prompts = {
  publish: {
    type: 'confirm',
    message: () => 'Are you sure you want to publish package?',
  },
  release: {
    type: 'confirm',
    message: () => 'Are you sure you want to create a new release on GitHub?',
  },
}

const defaultPublishCommand = 'pnpm -r publish --access public --no-git-checks --tag $tag'

class ReleaseItPnpmPlugin extends Plugin {
  static disablePlugin() {
    return ['npm', 'version']
  }

  constructor(...args) {
    super(...args)
    this.registerPrompts(prompts)
  }

  getInitialOptions(options, pluginName) {
    return Object.assign(
      {},
      options[pluginName],
      {
        'dry-run': options['dry-run'],
        'ci': options.ci,
        'preRelease': options.preRelease,
        'verbose': options.verbose,
      },
    )
  }

  getIncrement(options) {
    return options.increment
  }

  getIncrementedVersionCI(options) {
    return this.getRecommendedVersion(options)
  }

  getIncrementedVersion(options) {
    return this.getRecommendedVersion(options)
  }

  async getRecommendedVersion({
    latestVersion,
    increment,
    isPreRelease,
    preReleaseId,
  }) {
    this.debug(
      'release-it-pnpm:getRecommendedVersion',
      {
        increment,
        latestVersion,
        isPreRelease,
        preReleaseId,
      },
    )
    const { options } = this
    this.debug(
      'release-it-pnpm:getRecommendedVersion',
      { options },
    )

    if (!options.ci) {
      const result = await versionBump({
        commit: false,
        tag: false,
        push: false,
        confirm: true,
        preid: preReleaseId,
        files: ['this-is-a-non-existing-file-i-believe-you-do-not-have-it.txt'],
      })
      return semver.valid(result.newVersion)
    }

    try {
      const bumper = new Bumper(process.cwd()).loadPreset(
        {
          name: 'conventionalcommits',
          preMajor: semver.lt(latestVersion, '1.0.0'),
        },
      )
      const result = await bumper.bump()
      this.debug(
        'release-it-pnpm:getRecommendedVersion',
        { result },
      )
      let { releaseType } = result
      if (increment) {
        this.log.warn(`The recommended bump is "${releaseType}", but is overridden with "${increment}".`)
        releaseType = increment
      }
      if (increment && semver.valid(increment)) {
        return increment
      }
      else if (isPreRelease) {
        const type = releaseType && !semver.prerelease(latestVersion)
          ? `pre${releaseType}`
          : 'prerelease'
        return semver.inc(latestVersion, type, preReleaseId)
      }
      else if (!releaseType) {
        return null
      }
      return semver.inc(latestVersion, releaseType, preReleaseId)
    }
    catch (err) {
      this.debug(
        'release-it-pnpm:getRecommendedVersion',
        { err },
      )
      throw err
    }
  }

  async bump(newVersion) {
    this.setContext({ newVersion })

    const { publishCommand = defaultPublishCommand } = this.options
    let needPublish = false

    if (!this.options['dry-run']) {
      const { updatedFiles } = await versionBump({
        commit: false,
        tag: false,
        push: false,
        confirm: false,
        recursive: true,
        release: newVersion,
      })
      if (updatedFiles.length === 0)
        return

      // Only publish when some packages is not private
      for (const file of updatedFiles) {
        const { private: isPrivate } = JSON.parse(fs.readFileSync(file, 'utf8'))
        if (!isPrivate) {
          needPublish = true
          break
        }
      }

      // Using custom publish command
      if (publishCommand !== defaultPublishCommand)
        needPublish = true
    }

    const { prerelease } = semver.parse(newVersion)
    const includePrerelease = prerelease.length > 0
    const tag = prerelease[0] ?? 'latest'

    this.debug(
      'release-it-pnpm:bump',
      {
        needPublish,
        publishCommand,
        includePrerelease,
        prerelease,
        tag,
        newVersion,
        parsedNewVersion: semver.parse(newVersion),
      },
    )

    if (needPublish) {
      await this.step({
        task: () => this.exec(publishCommand.replace('$tag', tag)),
        label: 'Publishing packages(s)',
        prompt: 'publish',
      })
    }
  }

  async writeChangelog(changelog, version) {
    const { inFile, header: _header = '# Changelog' } = this.options
    const header = _header.split(/\r\n|\r|\n/g).join(EOL)

    let hasInFile = false
    try {
      fs.accessSync(inFile)
      hasInFile = true
    }
    catch (err) {
      this.debug(err)
    }

    let previousChangelog = ''
    try {
      previousChangelog = await fs.promises.readFile(inFile, 'utf8')
      previousChangelog = previousChangelog.replace(header, '')
    }
    catch (err) {
      this.debug(err)
    }

    fs.writeFileSync(
      inFile,
      `${header + EOL + EOL}## ${version}${changelog ? EOL + EOL + changelog.trim() : ''}${previousChangelog ? EOL + EOL + previousChangelog.trim() : ''}${EOL}`,
    )

    if (!hasInFile)
      await this.exec(`git add ${inFile}`)
  }

  async beforeRelease() {
    const { newVersion } = this.getContext()
    const { inFile } = this.options
    const isDryRun = this.options['dry-run']

    this.log.exec(`Writing changelog to ${inFile}`, isDryRun)

    if (inFile && !isDryRun) {
      const { md } = await generate()
      await this.writeChangelog(md, newVersion)
    }
  }

  async release() {
    if (this.options?.disableRelease)
      return

    await this.step({
      task: async () => {
        let token = process.env.GITHUB_TOKEN
        if (!token) {
          try {
            token = await this.exec('gh auth token')
          }
          catch (e) {
            this.debug('release-it-pnpm:release', e)
          }
        }

        let webUrl = ''

        try {
          const { config, md, commits } = await generate({
            token,
            emoji: true,
            dry: this.options['dry-run'],
          })
          webUrl = `https://${config.baseUrl}/${config.repo}/releases/new?title=${encodeURIComponent(String(config.name || config.to))}&body=${encodeURIComponent(String(md))}&tag=${encodeURIComponent(String(config.to))}&prerelease=${config.prerelease}`

          this.debug('release-it-pnpm:release', { config, md, commits })

          if (this.options['verbose']) {
            this.log.log(
              cyan(config.from)
              + dim(' -> ')
              + blue(config.to)
              + dim(` (${commits.length} commits)`),
            )
            this.log.log(dim('--------------'))
            this.log.log()
            this.log.log(md.replaceAll(' ', ''))
            this.log.log()
            this.log.log(dim('--------------'))
          }

          const printWebUrl = () => {
            this.log.log()
            this.log.error(yellow('Using the following link to create it manually:'))
            this.log.error(yellow(webUrl))
            this.log.log()
          }

          if (config.dry) {
            this.log.log(yellow('Dry run. Release skipped.'))
            printWebUrl()
            return
          }

          if (!config.token) {
            this.log.error(red('No GitHub token found, specify it via GITHUB_TOKEN env. Release skipped.'))
            printWebUrl()
            return
          }

          if (!(await hasTagOnGitHub(config.to, config))) {
            this.log.error(yellow(`Current ref "${bold(config.to)}" is not available as tags on GitHub. Release skipped.`))
            process.exitCode = 1
            printWebUrl()
            return
          }

          if (commits.length === 0 && (await isRepoShallow())) {
            this.log.error(yellow('The repo seems to be clone shallowly, which make changelog failed to generate. You might want to specify `fetch-depth: 0` in your CI config.'))
            process.exitCode = 1
            printWebUrl()
            return
          }

          await sendRelease(config, md)
        }
        catch (e) {
          this.log.error(red(String(e)))
          if (e?.stack)
            this.log.error(dim(e.stack?.split('\n').slice(1).join('\n')))

          if (webUrl) {
            this.log.log()
            this.log.error(red('Failed to create the release. Using the following link to create it manually:'))
            this.log.error(yellow(webUrl))
            this.log.log()
          }
          // eslint-disable-next-line unicorn/no-process-exit
          process.exit(1)
        }
      },
      label: 'Creating release on GitHub',
      prompt: 'release',
    })
  }
}

export default ReleaseItPnpmPlugin