fork-version 1.4.13 → 1.4.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,821 @@
1
+ 'use strict';
2
+
3
+ var zod = require('zod');
4
+ var path = require('path');
5
+ var JoyCon = require('joycon');
6
+ var bundleRequire = require('bundle-require');
7
+ var meow = require('meow');
8
+ var conventionalChangelogConfigSpec = require('conventional-changelog-config-spec');
9
+ var semver3 = require('semver');
10
+ var conventionalRecommendedBump = require('conventional-recommended-bump');
11
+ var gitSemverTags = require('git-semver-tags');
12
+ var fs = require('fs');
13
+ var conventionalChangelog = require('conventional-changelog');
14
+ var child_process = require('child_process');
15
+ var detectIndent = require('detect-indent');
16
+ var detectNewline = require('detect-newline');
17
+
18
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
19
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
20
+
21
+ var JoyCon__default = /*#__PURE__*/_interopDefault(JoyCon);
22
+ var meow__default = /*#__PURE__*/_interopDefault(meow);
23
+ var conventionalChangelogConfigSpec__default = /*#__PURE__*/_interopDefault(conventionalChangelogConfigSpec);
24
+ var semver3__default = /*#__PURE__*/_interopDefault(semver3);
25
+ var conventionalRecommendedBump__default = /*#__PURE__*/_interopDefault(conventionalRecommendedBump);
26
+ var gitSemverTags__default = /*#__PURE__*/_interopDefault(gitSemverTags);
27
+ var conventionalChangelog__default = /*#__PURE__*/_interopDefault(conventionalChangelog);
28
+ var detectIndent__default = /*#__PURE__*/_interopDefault(detectIndent);
29
+
30
+ // src/config/schema.ts
31
+ var ChangelogPresetConfigSchema = zod.z.object({
32
+ /**
33
+ * An array of `type` objects representing the explicitly supported commit message types,
34
+ * and whether they should show up in generated `CHANGELOG`s.
35
+ */
36
+ types: zod.z.array(
37
+ zod.z.object({
38
+ type: zod.z.string(),
39
+ section: zod.z.string().optional(),
40
+ hidden: zod.z.boolean().optional()
41
+ })
42
+ ),
43
+ /**
44
+ * A URL representing a specific commit at a hash.
45
+ * @default "{{host}}/{{owner}}/{{repository}}/commit/{{hash}}"
46
+ */
47
+ commitUrlFormat: zod.z.string(),
48
+ /**
49
+ * A URL representing the comparison between two git SHAs.
50
+ * @default "{{host}}/{{owner}}/{{repository}}/compare/{{previousTag}}...{{currentTag}}"
51
+ */
52
+ compareUrlFormat: zod.z.string(),
53
+ /**
54
+ * A URL representing the issue format (allowing a different URL format to be swapped in
55
+ * for Gitlab, Bitbucket, etc).
56
+ * @default "{{host}}/{{owner}}/{{repository}}/issues/{{id}}"
57
+ */
58
+ issueUrlFormat: zod.z.string(),
59
+ /**
60
+ * A URL representing the a user's profile URL on GitHub, Gitlab, etc. This URL is used
61
+ * for substituting @bcoe with https://github.com/bcoe in commit messages.
62
+ * @default "{{host}}/{{user}}"
63
+ */
64
+ userUrlFormat: zod.z.string(),
65
+ /**
66
+ * A string to be used to format the auto-generated release commit message.
67
+ * @default "chore(release): {{currentTag}}"
68
+ */
69
+ releaseCommitMessageFormat: zod.z.string(),
70
+ /**
71
+ * An array of prefixes used to detect references to issues
72
+ * @default ["#"]
73
+ */
74
+ issuePrefixes: zod.z.array(zod.z.string())
75
+ });
76
+ var ForkConfigSchema = zod.z.object({
77
+ /**
78
+ * The path fork-version will run from.
79
+ * @default
80
+ * ```js
81
+ * process.cwd()
82
+ * ```
83
+ */
84
+ path: zod.z.string(),
85
+ /**
86
+ * Name of the changelog file.
87
+ * @default "CHANGELOG.md"
88
+ */
89
+ changelog: zod.z.string(),
90
+ /**
91
+ * The header to be used in the changelog.
92
+ * @default
93
+ * ```markdown
94
+ * # Changelog
95
+ *
96
+ * All notable changes to this project will be documented in this file. See [fork-version](https://github.com/eglavin/fork-version) for commit guidelines.
97
+ * ```
98
+ */
99
+ header: zod.z.string(),
100
+ /**
101
+ * Files to be updated.
102
+ * @default
103
+ * ```js
104
+ * ["bower.json", "manifest.json", "npm-shrinkwrap.json", "package-lock.json", "package.json"]
105
+ * ```
106
+ */
107
+ files: zod.z.array(zod.z.string()),
108
+ /**
109
+ * Specify a prefix for the git tag fork-version will create.
110
+ *
111
+ * For instance if your version tag is prefixed by "version/" instead of "v" you have to specify
112
+ * `tagPrefix: "version/"`.
113
+ *
114
+ * `tagPrefix` can also be used for a monorepo environment where you might want to deploy
115
+ * multiple package from the same repository. In this case you can specify a prefix for
116
+ * each package:
117
+ *
118
+ * | Value | Tag Created |
119
+ * |:-------------------------|:------------------------------|
120
+ * | "" | `1.2.3` |
121
+ * | "version/" | `version/1.2.3` |
122
+ * | "@eglavin/fork-version-" | `@eglavin/fork-version-1.2.3` |
123
+ *
124
+ * @example "", "version/", "@eglavin/fork-version-"
125
+ * @default "v"
126
+ */
127
+ tagPrefix: zod.z.string(),
128
+ /**
129
+ * Make a pre-release with optional label, if value is a string it will be used as the
130
+ * pre-release tag.
131
+ *
132
+ * | Value | Version |
133
+ * |:----------|:----------------|
134
+ * | true | "1.2.3-0" |
135
+ * | "alpha" | "1.2.3-alpha-0" |
136
+ * | "beta" | "1.2.3-beta-0" |
137
+ *
138
+ * @example true, "alpha", "beta", "rc"
139
+ * @default undefined
140
+ */
141
+ preReleaseTag: zod.z.string().or(zod.z.boolean()).optional(),
142
+ /**
143
+ * Commit all staged changes, not just files updated by fork-version.
144
+ * @default false
145
+ */
146
+ commitAll: zod.z.boolean(),
147
+ /**
148
+ * If set we'll log debug information.
149
+ * @default false
150
+ */
151
+ debug: zod.z.boolean(),
152
+ /**
153
+ * If true, no output will be written to disk or committed.
154
+ * @default false
155
+ */
156
+ dryRun: zod.z.boolean(),
157
+ /**
158
+ * If true and we cant find a version in the list of `files`, we'll fallback
159
+ * and attempt to use the latest git tag to get the current version.
160
+ * @default true
161
+ */
162
+ gitTagFallback: zod.z.boolean(),
163
+ /**
164
+ * If set, we'll gather information about the current version and exit.
165
+ * @default false
166
+ */
167
+ inspectVersion: zod.z.boolean(),
168
+ /**
169
+ * Should we sign the git commit using GPG?
170
+ * @see {@link https://git-scm.com/docs/git-commit#Documentation/git-commit.txt--Sltkeyidgt GPG Sign Commits}
171
+ * @default false
172
+ */
173
+ sign: zod.z.boolean(),
174
+ /**
175
+ * If true, no output will be written to stdout.
176
+ * @default false
177
+ */
178
+ silent: zod.z.boolean(),
179
+ /**
180
+ * If true, allow git to run git commit hooks.
181
+ * @default false
182
+ */
183
+ verify: zod.z.boolean(),
184
+ /**
185
+ * If set, we'll use this version number instead of trying to find a version from the list of `files`.
186
+ * @example "1.0.0"
187
+ * @default undefined
188
+ */
189
+ currentVersion: zod.z.string().optional(),
190
+ /**
191
+ * If set, we'll attempt to update the version number to this version, instead of incrementing
192
+ * using "conventional-commit".
193
+ * @example "2.0.0"
194
+ * @default undefined
195
+ */
196
+ nextVersion: zod.z.string().optional(),
197
+ /**
198
+ * Override the default conventional-changelog preset configuration.
199
+ */
200
+ changelogPresetConfig: ChangelogPresetConfigSchema.partial()
201
+ });
202
+ function defineConfig(config) {
203
+ return config;
204
+ }
205
+
206
+ // src/config/defaults.ts
207
+ var DEFAULT_CONFIG = {
208
+ path: process.cwd(),
209
+ changelog: "CHANGELOG.md",
210
+ files: [
211
+ "package.json",
212
+ "package-lock.json",
213
+ "npm-shrinkwrap.json",
214
+ "manifest.json",
215
+ // Chrome extensions
216
+ "bower.json"
217
+ ],
218
+ header: `# Changelog
219
+
220
+ All notable changes to this project will be documented in this file. See [fork-version](https://github.com/eglavin/fork-version) for commit guidelines.
221
+ `,
222
+ tagPrefix: "v",
223
+ commitAll: false,
224
+ debug: false,
225
+ dryRun: false,
226
+ gitTagFallback: true,
227
+ inspectVersion: false,
228
+ sign: false,
229
+ silent: false,
230
+ verify: false,
231
+ changelogPresetConfig: {}
232
+ };
233
+ function getCliArguments() {
234
+ return meow__default.default(
235
+ `
236
+ Usage:
237
+ $ fork-version [options]
238
+
239
+ Options:
240
+ --path [Default: process.cwd()]
241
+ The path fork-version will run from.
242
+ --changelog [Default: "CHANGELOG.md"]
243
+ Name of the changelog file.
244
+ --header, -H
245
+ The header to be used in the changelog.
246
+ --files, --file, -F [Default: ["bower.json", "manifest.json", "npm-shrinkwrap.json", "package-lock.json", "package.json"]]
247
+ Files to be updated.
248
+ --tag-prefix [Default: "v"]
249
+ Specify a prefix for the git tag "fork-version" will create.
250
+ --pre-release-tag [Default: undefined]
251
+ Make a pre-release with optional label, If value is a string it
252
+ will be used as the pre-release tag.
253
+
254
+ --commit-all
255
+ Commit all staged changes, not just files updated by fork-version.
256
+ --debug
257
+ If true, we'll output debug information.
258
+ --dry-run
259
+ If true, no output will be written to disk or committed.
260
+ --git-tag-fallback [Default: true]
261
+ If true and we cant find a version in the given files, we'll fallback
262
+ and attempt to use the latest git tag for the current version.
263
+ --inspect-version
264
+ If set, we'll gather information about the current version and exit.
265
+ --sign
266
+ Should we sign the git commit using GPG?
267
+ --silent
268
+ If true, no output will be written to stdout.
269
+ --verify
270
+ If true, allow git to run git commit hooks.
271
+
272
+ --current-version
273
+ If set, we'll use this version number instead of trying to find a
274
+ version in a "file".
275
+ --next-version
276
+ If set, we'll attempt to update the version number to this version,
277
+ instead of incrementing using "conventional-commit".
278
+ `,
279
+ {
280
+ importMeta: ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('out.js', document.baseURI).href)) }),
281
+ flags: {
282
+ path: { type: "string", default: process.cwd() },
283
+ changelog: { type: "string" },
284
+ header: { type: "string", shortFlag: "H" },
285
+ files: { type: "string", isMultiple: true, aliases: ["file"], shortFlag: "F" },
286
+ tagPrefix: { type: "string" },
287
+ preReleaseTag: { type: "string" },
288
+ commitAll: { type: "boolean" },
289
+ debug: { type: "boolean" },
290
+ dryRun: { type: "boolean" },
291
+ gitTagFallback: { type: "boolean" },
292
+ inspectVersion: { type: "boolean" },
293
+ sign: { type: "boolean" },
294
+ silent: { type: "boolean" },
295
+ verify: { type: "boolean" },
296
+ currentVersion: { type: "string" },
297
+ nextVersion: { type: "string" }
298
+ }
299
+ }
300
+ );
301
+ }
302
+ function getChangelogPresetConfig(usersChangelogPresetConfig) {
303
+ const preset = {
304
+ name: "conventionalcommits"
305
+ };
306
+ if (typeof conventionalChangelogConfigSpec__default.default.properties === "object") {
307
+ Object.entries(conventionalChangelogConfigSpec__default.default.properties).forEach(([key, value]) => {
308
+ if ("default" in value && value.default !== void 0) {
309
+ preset[key] = value.default;
310
+ }
311
+ });
312
+ }
313
+ if (usersChangelogPresetConfig && typeof usersChangelogPresetConfig === "object") {
314
+ Object.entries(usersChangelogPresetConfig).forEach(([key, value]) => {
315
+ if (value !== void 0) {
316
+ preset[key] = value;
317
+ }
318
+ });
319
+ }
320
+ return ChangelogPresetConfigSchema.passthrough().parse(preset);
321
+ }
322
+
323
+ // src/config/user-config.ts
324
+ async function getUserConfig() {
325
+ const cliArguments = getCliArguments();
326
+ const cwd = cliArguments.flags.path ? path.resolve(cliArguments.flags.path) : process.cwd();
327
+ const joycon = new JoyCon__default.default();
328
+ const configFilePath = await joycon.resolve({
329
+ files: ["fork.config.ts", "fork.config.js", "fork.config.cjs", "fork.config.mjs"],
330
+ cwd,
331
+ stopDir: path.parse(cwd).root
332
+ });
333
+ if (!configFilePath) {
334
+ return {
335
+ ...DEFAULT_CONFIG,
336
+ ...cliArguments.flags,
337
+ path: cwd,
338
+ changelogPresetConfig: getChangelogPresetConfig()
339
+ };
340
+ }
341
+ const foundConfig = await bundleRequire.bundleRequire({ filepath: configFilePath });
342
+ const parsedConfig = ForkConfigSchema.partial().safeParse(
343
+ foundConfig.mod.default || foundConfig.mod
344
+ );
345
+ if (!parsedConfig.success) {
346
+ throw parsedConfig.error;
347
+ }
348
+ const usersConfig = {
349
+ ...DEFAULT_CONFIG,
350
+ ...parsedConfig.data,
351
+ ...cliArguments.flags
352
+ };
353
+ const files = mergeFiles(parsedConfig.data?.files, cliArguments.flags?.files);
354
+ return {
355
+ ...usersConfig,
356
+ path: cwd,
357
+ files: files.length > 0 ? files : DEFAULT_CONFIG.files,
358
+ changelogPresetConfig: getChangelogPresetConfig(usersConfig?.changelogPresetConfig)
359
+ };
360
+ }
361
+ function mergeFiles(configFiles, cliFiles) {
362
+ return Array.from(
363
+ new Set(
364
+ [].concat(
365
+ Array.isArray(configFiles) ? configFiles : [],
366
+ Array.isArray(cliFiles) ? cliFiles : []
367
+ )
368
+ )
369
+ );
370
+ }
371
+ async function getLatestGitTagVersion(tagPrefix) {
372
+ const gitTags = await gitSemverTags__default.default({ tagPrefix });
373
+ if (!gitTags.length) {
374
+ return "1.0.0";
375
+ }
376
+ const cleanedTags = [];
377
+ for (const tag of gitTags) {
378
+ const cleanedTag = semver3__default.default.clean(tag.replace(new RegExp(`^${tagPrefix}`), ""));
379
+ if (cleanedTag) {
380
+ cleanedTags.push(cleanedTag);
381
+ }
382
+ }
383
+ return cleanedTags.sort(semver3__default.default.rcompare)[0];
384
+ }
385
+ function getPriority(type) {
386
+ return ["patch", "minor", "major"].indexOf(type ?? "");
387
+ }
388
+ function getVersionType(version) {
389
+ const parseVersion = semver3__default.default.parse(version);
390
+ if (parseVersion?.major) {
391
+ return "major";
392
+ } else if (parseVersion?.minor) {
393
+ return "minor";
394
+ } else if (parseVersion?.patch) {
395
+ return "patch";
396
+ }
397
+ return void 0;
398
+ }
399
+ function getReleaseType(releaseType, currentVersion, preReleaseTag) {
400
+ if (!preReleaseTag) {
401
+ return releaseType;
402
+ }
403
+ const currentVersionsIsPreRelease = Array.isArray(semver3__default.default.prerelease(currentVersion));
404
+ if (currentVersionsIsPreRelease) {
405
+ const currentReleaseType = getVersionType(currentVersion);
406
+ if (currentReleaseType === releaseType || getPriority(currentReleaseType) > getPriority(releaseType)) {
407
+ return "prerelease";
408
+ }
409
+ }
410
+ return `pre${releaseType}`;
411
+ }
412
+
413
+ // src/process/version.ts
414
+ async function getCurrentVersion(config, logger, fileManager) {
415
+ const files = [];
416
+ const versions = /* @__PURE__ */ new Set();
417
+ for (const file of config.files) {
418
+ const fileState = fileManager.read(file);
419
+ if (fileState) {
420
+ files.push(fileState);
421
+ if (config.currentVersion) {
422
+ continue;
423
+ }
424
+ versions.add(fileState.version);
425
+ }
426
+ }
427
+ if (config.currentVersion) {
428
+ versions.add(config.currentVersion);
429
+ }
430
+ if (versions.size === 0) {
431
+ if (config.gitTagFallback) {
432
+ const version = await getLatestGitTagVersion(config.tagPrefix);
433
+ if (version) {
434
+ return {
435
+ files: [],
436
+ version
437
+ };
438
+ }
439
+ }
440
+ throw new Error("Unable to find current version");
441
+ } else if (versions.size > 1) {
442
+ throw new Error("Found multiple versions");
443
+ }
444
+ const currentVersion = versions.entries().next().value[0];
445
+ if (config.inspectVersion) {
446
+ console.log(currentVersion);
447
+ process.exit(0);
448
+ }
449
+ logger.log(`Current version: ${currentVersion}`);
450
+ return {
451
+ files,
452
+ version: currentVersion
453
+ };
454
+ }
455
+ async function getNextVersion(config, logger, currentVersion) {
456
+ if (config.nextVersion && semver3__default.default.valid(config.nextVersion)) {
457
+ logger.log(`Next version: ${config.nextVersion}`);
458
+ return { version: config.nextVersion };
459
+ }
460
+ const isPreMajor = semver3__default.default.lt(currentVersion, "1.0.0");
461
+ let recommendedBump;
462
+ try {
463
+ recommendedBump = await conventionalRecommendedBump__default.default({
464
+ preset: {
465
+ name: "conventionalcommits",
466
+ ...config.changelogPresetConfig,
467
+ preMajor: isPreMajor
468
+ },
469
+ path: config.path,
470
+ tagPrefix: config.tagPrefix,
471
+ cwd: config.path
472
+ });
473
+ } catch (error) {
474
+ throw new Error(`[conventional-recommended-bump] Unable to determine next version`);
475
+ }
476
+ if (recommendedBump.releaseType) {
477
+ const releaseType = getReleaseType(
478
+ recommendedBump.releaseType,
479
+ currentVersion,
480
+ config.preReleaseTag
481
+ );
482
+ const state = {
483
+ ...recommendedBump,
484
+ preMajor: isPreMajor,
485
+ releaseType,
486
+ version: semver3__default.default.inc(
487
+ currentVersion,
488
+ releaseType,
489
+ typeof config.preReleaseTag === "string" ? config.preReleaseTag : void 0
490
+ ) ?? ""
491
+ };
492
+ logger.log(`Next version: ${state.version} (${state.releaseType})`);
493
+ return state;
494
+ }
495
+ throw new Error("Unable to find next version");
496
+ }
497
+ function fileExists(filePath) {
498
+ try {
499
+ return fs.lstatSync(filePath).isFile();
500
+ } catch (e) {
501
+ return false;
502
+ }
503
+ }
504
+
505
+ // src/process/changelog.ts
506
+ var RELEASE_PATTERN = /(^#+ \[?[0-9]+\.[0-9]+\.[0-9]+|<a name=)/m;
507
+ function getOldReleaseContent(filePath, exists) {
508
+ if (exists) {
509
+ const fileContents = fs.readFileSync(filePath, "utf-8");
510
+ const oldContentStart = fileContents.search(RELEASE_PATTERN);
511
+ if (oldContentStart !== -1) {
512
+ return fileContents.substring(oldContentStart);
513
+ }
514
+ }
515
+ return "";
516
+ }
517
+ function getNewReleaseContent(config, logger, nextVersion) {
518
+ return new Promise((onResolve) => {
519
+ let newContent = "";
520
+ conventionalChangelog__default.default(
521
+ {
522
+ preset: {
523
+ name: "conventionalcommits",
524
+ ...config.changelogPresetConfig
525
+ },
526
+ tagPrefix: config.tagPrefix,
527
+ warn: (...message) => logger.error("conventional-changelog: ", ...message),
528
+ cwd: config.path
529
+ },
530
+ {
531
+ version: nextVersion
532
+ },
533
+ {
534
+ merges: null,
535
+ path: config.path
536
+ }
537
+ ).on("error", (error) => {
538
+ logger.error("conventional-changelog: Unable to parse changes");
539
+ throw error;
540
+ }).on("data", (chunk) => {
541
+ newContent += chunk.toString();
542
+ }).on("end", () => {
543
+ onResolve(newContent);
544
+ });
545
+ });
546
+ }
547
+ async function updateChangelog(config, logger, nextVersion) {
548
+ if (config.header.search(RELEASE_PATTERN) !== -1) {
549
+ throw new Error("Header cannot contain release pattern");
550
+ }
551
+ const changelogPath = path.resolve(config.path, config.changelog);
552
+ if (!config.dryRun && !fileExists(changelogPath)) {
553
+ logger.log(`Creating Changelog file: ${changelogPath}`);
554
+ fs.writeFileSync(changelogPath, "\n", "utf8");
555
+ }
556
+ const oldContent = getOldReleaseContent(changelogPath, fileExists(changelogPath));
557
+ const newContent = await getNewReleaseContent(config, logger, nextVersion);
558
+ logger.log(`Updating Changelog: ${changelogPath}`);
559
+ if (!config.dryRun && newContent) {
560
+ fs.writeFileSync(
561
+ changelogPath,
562
+ `${config.header}
563
+ ${newContent}
564
+ ${oldContent}
565
+ `,
566
+ "utf8"
567
+ );
568
+ }
569
+ return {
570
+ changelogPath,
571
+ oldContent,
572
+ newContent
573
+ };
574
+ }
575
+ var Git = class {
576
+ constructor(config, logger) {
577
+ this.config = config;
578
+ this.logger = logger;
579
+ this.add = this.add.bind(this);
580
+ this.commit = this.commit.bind(this);
581
+ this.tag = this.tag.bind(this);
582
+ this.revParse = this.revParse.bind(this);
583
+ }
584
+ add(...args) {
585
+ return this.execGit("add", args.filter(Boolean));
586
+ }
587
+ commit(...args) {
588
+ return this.execGit("commit", args.filter(Boolean));
589
+ }
590
+ tag(...args) {
591
+ return this.execGit("tag", args.filter(Boolean));
592
+ }
593
+ revParse(...args) {
594
+ return this.execGit("rev-parse", args.filter(Boolean));
595
+ }
596
+ execGit(command, args) {
597
+ if (this.config.dryRun) {
598
+ return Promise.resolve("");
599
+ }
600
+ this.logger.debug(`Executing: git ${command} ${args.join(" ")}`);
601
+ return new Promise((onResolve, onReject) => {
602
+ child_process.execFile(
603
+ "git",
604
+ [command, ...args],
605
+ {
606
+ cwd: this.config.path
607
+ },
608
+ (error, stdout, stderr) => {
609
+ if (error) {
610
+ this.logger.error(`git ${command}:`);
611
+ onReject(error);
612
+ }
613
+ onResolve(stdout ? stdout : stderr);
614
+ }
615
+ );
616
+ });
617
+ }
618
+ };
619
+
620
+ // src/utils/format-commit-message.ts
621
+ function formatCommitMessage(message, version) {
622
+ if (!message) {
623
+ message = "chore(release): {{currentTag}}";
624
+ }
625
+ return message.replace(new RegExp("{{currentTag}}", "g"), version);
626
+ }
627
+
628
+ // src/process/commit.ts
629
+ async function commitChanges(config, logger, files, nextVersion) {
630
+ const git = new Git(config, logger);
631
+ logger.log("Committing changes");
632
+ const filesToCommit = [];
633
+ if (fileExists(path.resolve(config.path, config.changelog))) {
634
+ filesToCommit.push(path.resolve(config.path, config.changelog));
635
+ }
636
+ for (const file of files) {
637
+ filesToCommit.push(file.path);
638
+ }
639
+ if (filesToCommit.length === 0) {
640
+ return {
641
+ filesToCommit
642
+ };
643
+ }
644
+ const shouldVerify = config.verify ? void 0 : "--no-verify";
645
+ const shouldSign = config.sign ? "--gpg-sign" : void 0;
646
+ if (config.commitAll) {
647
+ return {
648
+ filesToCommit,
649
+ gitAddOutput: await git.add("--all"),
650
+ gitCommitOutput: await git.commit(
651
+ shouldVerify,
652
+ shouldSign,
653
+ "--message",
654
+ formatCommitMessage(config.changelogPresetConfig?.releaseCommitMessageFormat, nextVersion)
655
+ )
656
+ };
657
+ }
658
+ return {
659
+ filesToCommit,
660
+ gitAddOutput: await git.add(...filesToCommit),
661
+ gitCommitOutput: await git.commit(
662
+ shouldVerify,
663
+ shouldSign,
664
+ ...filesToCommit,
665
+ "--message",
666
+ formatCommitMessage(config.changelogPresetConfig?.releaseCommitMessageFormat, nextVersion)
667
+ )
668
+ };
669
+ }
670
+
671
+ // src/process/tag.ts
672
+ async function tagChanges(config, logger, nextVersion) {
673
+ const git = new Git(config, logger);
674
+ const tag = `${config.tagPrefix}${nextVersion}`;
675
+ logger.log(`Creating Tag: ${tag}`);
676
+ const gitTagOutput = await git.tag(
677
+ config.sign ? "--sign" : "--annotate",
678
+ tag,
679
+ "--message",
680
+ formatCommitMessage(config.changelogPresetConfig?.releaseCommitMessageFormat, nextVersion)
681
+ );
682
+ return {
683
+ gitTagOutput
684
+ };
685
+ }
686
+
687
+ // src/libs/stringify-package.ts
688
+ var DEFAULT_INDENT = 2;
689
+ var CRLF = "\r\n";
690
+ var LF = "\n";
691
+ function stringifyPackage(data, indent, newline) {
692
+ const stringified = JSON.stringify(data, null, indent ?? DEFAULT_INDENT);
693
+ if (newline === CRLF) {
694
+ return stringified.replace(new RegExp(LF, "g"), CRLF);
695
+ }
696
+ return stringified;
697
+ }
698
+
699
+ // src/strategies/json-package.ts
700
+ var JSONPackage = class {
701
+ constructor(config, logger) {
702
+ this.config = config;
703
+ this.logger = logger;
704
+ }
705
+ read(fileName) {
706
+ const filePath = path.resolve(this.config.path, fileName);
707
+ if (fileExists(filePath)) {
708
+ const fileContents = fs.readFileSync(filePath, "utf8");
709
+ const parsedJson = JSON.parse(fileContents);
710
+ if (parsedJson.version) {
711
+ return {
712
+ name: fileName,
713
+ path: filePath,
714
+ version: parsedJson.version,
715
+ isPrivate: typeof parsedJson?.private === "boolean" ? parsedJson.private : true
716
+ };
717
+ }
718
+ this.logger.warn(`Unable to determine json package file: ${fileName}`);
719
+ }
720
+ }
721
+ write(filePath, newVersion) {
722
+ const fileContents = fs.readFileSync(filePath, "utf8");
723
+ const parsedJson = JSON.parse(fileContents);
724
+ parsedJson.version = newVersion;
725
+ if (parsedJson.packages?.[""]) {
726
+ parsedJson.packages[""].version = newVersion;
727
+ }
728
+ fs.writeFileSync(
729
+ filePath,
730
+ stringifyPackage(parsedJson, detectIndent__default.default(fileContents).amount, detectNewline.detectNewline(fileContents)),
731
+ "utf8"
732
+ );
733
+ }
734
+ };
735
+ var PlainText = class {
736
+ constructor(config, logger) {
737
+ this.config = config;
738
+ this.logger = logger;
739
+ }
740
+ read(fileName) {
741
+ const filePath = path.resolve(this.config.path, fileName);
742
+ if (fileExists(filePath)) {
743
+ const fileContents = fs.readFileSync(filePath, "utf8");
744
+ return {
745
+ name: fileName,
746
+ path: filePath,
747
+ version: fileContents || ""
748
+ };
749
+ }
750
+ this.logger.warn(`Unable to determine plain text file: ${fileName}`);
751
+ }
752
+ write(filePath, newVersion) {
753
+ fs.writeFileSync(filePath, newVersion, "utf8");
754
+ }
755
+ };
756
+
757
+ // src/strategies/file-manager.ts
758
+ var FileManager = class {
759
+ constructor(config, logger) {
760
+ this.config = config;
761
+ this.logger = logger;
762
+ this.JSONPackage = new JSONPackage(config, logger);
763
+ this.PlainText = new PlainText(config, logger);
764
+ }
765
+ JSONPackage;
766
+ PlainText;
767
+ /**
768
+ * Get the state from the given file name.
769
+ *
770
+ * @example
771
+ * ```ts
772
+ * fileManager.read("package.json");
773
+ * ```
774
+ *
775
+ * @returns
776
+ * ```json
777
+ * { "name": "package.json", "path": "/path/to/package.json", "version": "1.2.3", "isPrivate": true }
778
+ * ```
779
+ */
780
+ read(fileName) {
781
+ if (fileName.toLowerCase().endsWith(".json")) {
782
+ return this.JSONPackage.read(fileName);
783
+ } else if (fileName.toLowerCase().endsWith("version.txt")) {
784
+ return this.PlainText.read(fileName);
785
+ }
786
+ this.logger.error(`Unsupported file type: ${fileName}`);
787
+ }
788
+ /**
789
+ * Write the new version to the given file path.
790
+ *
791
+ * @example
792
+ * ```ts
793
+ * fileManager.write("/path/to/package.json", "1.2.3");
794
+ * ```
795
+ */
796
+ write(filePath, newVersion) {
797
+ if (this.config.dryRun) {
798
+ this.logger.log(`[Dry run]: Not updating ${filePath}`);
799
+ return;
800
+ }
801
+ if (filePath.toLowerCase().endsWith(".json")) {
802
+ return this.JSONPackage.write(filePath, newVersion);
803
+ } else if (filePath.toLowerCase().endsWith("version.txt")) {
804
+ return this.PlainText.write(filePath, newVersion);
805
+ }
806
+ this.logger.error(`Unsupported file type: ${filePath}`);
807
+ }
808
+ };
809
+
810
+ exports.FileManager = FileManager;
811
+ exports.ForkConfigSchema = ForkConfigSchema;
812
+ exports.Git = Git;
813
+ exports.commitChanges = commitChanges;
814
+ exports.defineConfig = defineConfig;
815
+ exports.getCurrentVersion = getCurrentVersion;
816
+ exports.getNextVersion = getNextVersion;
817
+ exports.getUserConfig = getUserConfig;
818
+ exports.tagChanges = tagChanges;
819
+ exports.updateChangelog = updateChangelog;
820
+ //# sourceMappingURL=out.js.map
821
+ //# sourceMappingURL=chunk-UJKGEPR3.cjs.map