ship-release 5.0.0 → 6.0.1

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.
package/LICENSE CHANGED
File without changes
package/README.md CHANGED
@@ -1,74 +1,106 @@
1
+ <!-- Please do not edit this file. Edit the `blah` field in the `package.json` instead. If in doubt, open an issue. -->
1
2
 
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
- ![ship-release](http://i.imgur.com/gOm6qum.png)
16
-
17
-
18
-
3
+ [![ship-release](http://i.imgur.com/gOm6qum.png)](#)
19
4
 
20
5
  # `$ ship-release`
21
6
 
22
- Publish new versions on GitHub and npm with ease.
7
+ [![Support me on Patreon][badge_patreon]][patreon] [![Buy me a book][badge_amazon]][amazon] [![PayPal][badge_paypal_donate]][paypal-donations] [![Ask me anything](https://img.shields.io/badge/ask%20me-anything-1abc9c.svg)](https://github.com/IonicaBizau/ama) [![Version](https://img.shields.io/npm/v/ship-release.svg)](https://www.npmjs.com/package/ship-release) [![Downloads](https://img.shields.io/npm/dt/ship-release.svg)](https://www.npmjs.com/package/ship-release) [![Get help on Codementor](https://cdn.codementor.io/badges/get_help_github.svg)](https://www.codementor.io/@johnnyb?utm_source=github&utm_medium=button&utm_term=johnnyb&utm_campaign=github)
23
8
 
9
+ <a href="https://www.buymeacoffee.com/H96WwChMy" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/yellow_img.png" alt="Buy Me A Coffee"></a>
24
10
 
11
+ > Publish new versions on GitHub and npm with ease.
25
12
 
13
+ ## :cloud: Installation
26
14
 
27
- ## Installation
15
+ You can install the package globally and use it as a command line tool:
28
16
 
29
17
  ```sh
30
- $ npm i ship-release
31
- ```
32
-
18
+ # Using npm
19
+ npm install --global ship-release
33
20
 
21
+ # Using yarn
22
+ yarn global add ship-release
23
+ ```
34
24
 
35
- ### CLI Usage
36
- You can install the package globally and use it as command line tool:
25
+ Then, run `ship-release --help` to see what the CLI tool can do.
37
26
 
38
- ```sh
39
- $ npm i -g ship-release
40
27
  ```
28
+ $ ship-release --help
29
+ Usage: ship-release <command> [options]
41
30
 
42
- Then, run `ship-release --help` and see what the CLI tool can do.
31
+ Publish new versions on GitHub and npm with ease.
43
32
 
33
+ Commands:
34
+ branch Creates a new branch and commits the changes.
35
+ bump Bumps the version and creates a new branch.
36
+ publish Creates a pull request with the changes, merges it
37
+ in the main branch, publishes it on npm and creates
38
+ a GitHub release.
44
39
 
40
+ Options:
41
+ -h, --help Displays this help.
42
+ -v, --version Displays version information.
45
43
 
44
+ Examples:
45
+ $ ship-release branch -m 'Fix the parser'
46
+ $ ship-release bump -V minor
47
+ $ ship-release publish -d 'Fixed the parser.'
46
48
 
49
+ The GitHub token is read from --token, GITHUB_TOKEN/GH_TOKEN or
50
+ ~/.github-config.json ({ "token": "..." }).
47
51
 
52
+ Documentation can be found at https://github.com/IonicaBizau/ship-release#readme.
53
+ ```
48
54
 
55
+ ## :memo: Documentation
49
56
 
57
+ For the full API reference, see the [DOCUMENTATION.md][docs] file.
50
58
 
59
+ ## :question: Get Help
51
60
 
52
- ## Documentation
61
+ There are a few ways to get help:
53
62
 
63
+ 1. Please [post questions on Stack Overflow](https://stackoverflow.com/questions/ask). You can open issues with questions, as long as you add a link to your Stack Overflow question.
64
+ 2. For bug reports and feature requests, open issues. :bug:
65
+ 3. For direct and quick help, you can [use Codementor](https://www.codementor.io/johnnyb). :rocket:
54
66
 
67
+ ## :yum: How to Contribute
55
68
 
69
+ Have an idea? Found a bug? See [how to contribute][contributing].
56
70
 
57
- For full API reference, see the [DOCUMENTATION.md][docs] file.
71
+ ## :sparkling_heart: Support My Projects
58
72
 
73
+ I open-source almost everything I can, and I try to reply to everyone needing help using these projects. Obviously, this takes time. You can integrate and use these projects in your applications *for free*! You can even change the source code and redistribute it (even resell it).
59
74
 
75
+ However, if you get some profit from this or just want to encourage me to continue creating stuff, there are a few ways you can do it:
60
76
 
77
+ - Starring and sharing the projects you like :rocket:
78
+ - [![Buy me a book][badge_amazon]][amazon]—I love books! I will remember you for years if you buy me one. :grin: :book:
79
+ - [![PayPal][badge_paypal]][paypal-donations]—You can make one-time donations via PayPal. I'll probably buy a ~~coffee~~ tea. :tea:
80
+ - [![Support me on Patreon][badge_patreon]][patreon]—Set up a recurring monthly donation and you will get interesting news about what I'm doing (things that I don't share with everyone).
81
+ - **Bitcoin**—You can send me bitcoins at this address (or by scanning the code below): `1P9BRsmazNQcuyTxEqveUsnf5CERdq35V6`
61
82
 
83
+ ![Bitcoin QR code](https://i.imgur.com/z6OQI95.png)
62
84
 
63
- ## How to contribute
64
- Have an idea? Found a bug? See [how to contribute][contributing].
85
+ Thanks! :heart:
65
86
 
87
+ ## :sparkles: Related
66
88
 
89
+ - [`babel-it`](https://github.com/IonicaBizau/babel-it#readme)—Babelify your code before `npm publish`.
90
+ - [`dist-it`](https://github.com/IonicaBizau/dist-it)—Generate minified bundles from modular inputs using Browserify.
67
91
 
68
- ## License
69
- See the [LICENSE][license] file.
92
+ ## :scroll: License
70
93
 
94
+ [MIT][license] © [Ionică Bizău][website]
71
95
 
72
96
  [license]: /LICENSE
97
+ [website]: https://ionicabizau.net
73
98
  [contributing]: /CONTRIBUTING.md
74
99
  [docs]: /DOCUMENTATION.md
100
+ [badge_patreon]: https://ionicabizau.github.io/badges/patreon.svg
101
+ [badge_amazon]: https://ionicabizau.github.io/badges/amazon.svg
102
+ [badge_paypal]: https://ionicabizau.github.io/badges/paypal.svg
103
+ [badge_paypal_donate]: https://ionicabizau.github.io/badges/paypal_donate.svg
104
+ [patreon]: https://www.patreon.com/ionicabizau
105
+ [amazon]: https://amzn.eu/hRo9sIZ
106
+ [paypal-donations]: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=RVXDDLKKLQRJW
@@ -1,68 +1,44 @@
1
1
  #!/usr/bin/env node
2
-
3
-
4
2
  "use strict";
5
3
 
6
- const rJson = require("r-json");
7
- const Logger = require("bug-killer");
8
- const wJson = require("w-json");
9
- const PackageJson = require("pkg.json");
10
- const Semver = require("semver");
11
- const spawno = require("spawno").promise;
4
+ const path = require("path");
12
5
  const Tilda = require("tilda");
13
6
  const pp = require("package-json-path");
14
- const abs = require("abs");
15
- const GitHub = require("gh.js");
16
- const gitUrlParse = require("git-url-parse");
17
- const findValue = require("find-value");
18
- const barbe = require("barbe");
19
- const ul = require("ul");
20
- const mapO = require("map-o");
21
- const BLAH_PATH = require.resolve("blah/bin/blah");
22
- const spawn = require("child_process").spawn;
23
-
24
- const packageJsonPromise = name => new Promise((resolve, reject) => {
25
- PackageJson(name, "latest", function (err, json) {
26
- if (err) {
27
- return reject(err);
28
- }
29
- resolve(json);
30
- });
31
- });
32
-
33
- const done = err => {
34
- if (err) {
35
- return Logger.log(err);
7
+ const shipRelease = require("../lib");
8
+ const ui = require("../lib/ui");
9
+
10
+ /**
11
+ * Wraps a command: prints the header, runs it, then prints a summary built
12
+ * from the result (or the error, setting a non-zero exit code).
13
+ */
14
+ const projectLabel = () => {
15
+ try {
16
+ const pack = require(pp(process.cwd()));
17
+ return `${pack.name}@${pack.version}`;
18
+ } catch (e) {
19
+ return path.basename(process.cwd());
36
20
  }
37
- Logger.log("✅ Done.");
38
21
  };
39
22
 
40
- const commitAll = async msg => {
41
- Logger.log("📦 Adding the modified files.");
42
- await spawno("git", ["add", ".", "-A"], { output: true });
43
-
44
- Logger.log("📝 Committing the changes.");
45
- await spawno("git", ["commit", "-m", msg], { output: true });
46
-
47
- Logger.log("🚀 Pushing the new branch.");
48
- await spawno("git", ["push", "--all"], { output: true });
49
- };
50
-
51
- const npmInstall = async () => {
52
- await spawno("npm", ["install", "--production"], { output: true });
53
- };
54
-
55
- const generateDocs = async () => {
56
- Logger.log("📚 Generating documentation.");
57
- await spawno(BLAH_PATH, ["-f"], { output: true });
58
- };
59
-
60
- const currentBranch = async () => {
61
- const { stdout, stderr } = await spawno("git", ["rev-parse", "--abbrev-ref", "HEAD"], { output: true });
62
- return (stdout || stderr || "").trim();
23
+ const command = (name, fn, summary) => async action => {
24
+ ui.header(name, projectLabel());
25
+ try {
26
+ const res = await fn(action.options);
27
+ ui.done(summary(res));
28
+ } catch (err) {
29
+ ui.error(err);
30
+ process.exitCode = 1;
31
+ }
63
32
  };
64
33
 
65
- const app = new Tilda(pp(__dirname + "/..")).action([{
34
+ const app = new Tilda(`${__dirname}/../package.json`, {
35
+ examples: [
36
+ "ship-release branch -m 'Fix the parser'",
37
+ "ship-release bump -V minor",
38
+ "ship-release publish -d 'Fixed the parser.'"
39
+ ],
40
+ notes: "The GitHub token is read from --token, GITHUB_TOKEN/GH_TOKEN or ~/.github-config.json ({ \"token\": \"...\" })."
41
+ }).action([{
66
42
  name: "branch",
67
43
  desc: "Creates a new branch and commits the changes.",
68
44
  options: [{
@@ -72,8 +48,8 @@ const app = new Tilda(pp(__dirname + "/..")).action([{
72
48
  type: String,
73
49
  default: "Working on the new version."
74
50
  }, {
75
- opts: ["n", "name"],
76
51
  name: "name",
52
+ opts: ["n", "name"],
77
53
  desc: "The branch name.",
78
54
  type: String,
79
55
  default: "new-version"
@@ -82,16 +58,17 @@ const app = new Tilda(pp(__dirname + "/..")).action([{
82
58
  name: "bump",
83
59
  desc: "Bumps the version and creates a new branch.",
84
60
  options: [{
61
+ name: "version",
85
62
  opts: ["V", "bump-version"],
86
- desc: "The semver tag to bump (major|minor|patch)",
63
+ desc: "The semver part to bump (major|minor|patch).",
87
64
  type: String,
88
65
  default: "patch"
89
66
  }, {
90
67
  opts: ["c", "current-branch"],
91
- desc: "If provided, an additional branch will not be created.",
92
- type: Boolean,
93
- default: false
68
+ desc: "Commit on the current branch instead of creating a new one (default: true unless on the default branch).",
69
+ type: Boolean
94
70
  }, {
71
+ name: "branch",
95
72
  opts: ["b", "branch"],
96
73
  desc: "The branch name to switch to.",
97
74
  type: String,
@@ -99,240 +76,55 @@ const app = new Tilda(pp(__dirname + "/..")).action([{
99
76
  }]
100
77
  }, {
101
78
  name: "publish",
102
- desc: "Creates a pull request with the changes, merge it in the main branch, publish it on npm and create a GitHub release.",
79
+ desc: "Creates a pull request with the changes, merges it in the main branch, publishes it on npm and creates a GitHub release.",
103
80
  options: [{
81
+ name: "token",
104
82
  opts: ["T", "token"],
105
83
  desc: "The GitHub token.",
106
84
  type: String
107
85
  }, {
86
+ name: "title",
108
87
  opts: ["t", "title"],
109
- desc: "The pull request title.",
88
+ desc: "The pull request title (default: \"<pack.name> <pack.version>\").",
110
89
  type: String
111
90
  }, {
91
+ name: "description",
112
92
  opts: ["d", "description"],
113
93
  desc: "The pull request/release description.",
114
94
  type: String
115
95
  }, {
96
+ name: "base",
116
97
  opts: ["b", "base-branch"],
117
98
  desc: "The base branch (defaults to the repository main branch).",
118
99
  type: String
119
100
  }, {
101
+ name: "config",
120
102
  opts: ["c", "config-path"],
121
- desc: "The path to a json/js file exporting ",
103
+ desc: "The path to a json/js file exporting the options (token, title, body, baseBranch).",
122
104
  type: String
123
105
  }]
124
- }]).on("branch", async a => {
125
- try {
126
- const branchName = a.options.name.value;
127
- Logger.log("🌿 Creating and switching to the " + branchName + " branch.");
128
- await spawno("git", ["checkout", "-B", branchName], { output: true });
129
- await commitAll(a.options.message.value);
130
- } catch (e) {
131
- done(e);
132
- }
133
- }).on("bump", async a => {
134
- try {
135
- const packPath = pp(process.cwd());
136
- let newVersion = null;
137
-
138
- const pack = rJson(packPath);
139
- try {
140
- const json = await packageJsonPromise(pack.name);
141
- if (Semver.major(json.version) === 0) {
142
- Logger.log("ℹ️ Since there is no 1.x.x release yet, setting 1.0.0.");
143
- pack.version = "1.0.0";
144
- } else {
145
- pack.version = Semver.inc(json.version, a.options.V.value);
146
- if (!pack.version) {
147
- return Logger.log(new Error("Invalid version bump option value."));
148
- }
149
- }
150
- if (json) {
151
- Logger.log("⬅️ Old version was: " + json.version);
152
- }
153
- Logger.log("➡️ New version is: " + pack.version);
154
- } catch (e) {
155
- Logger.log(e);
156
- Logger.log("⚙️ Setting version to 1.0.0.");
157
- pack.version = "1.0.0";
158
- }
159
- newVersion = pack.version;
160
- Logger.log("🧩 Updating package.json (version: " + newVersion + ")");
161
- wJson(packPath, pack);
162
- const cBranch = await currentBranch();
163
- const branchName = a.options.branch.value;
164
-
165
- if (!a.options.c.is_provided) {
166
- // TODO Check if default branch. Too lazy right now to do that.
167
- a.options.c.value = cBranch !== "master" && cBranch !== "gh-pages";
168
- }
169
-
170
- if (a.options.c.value) {
171
- Logger.log("📍 Using the current branch.");
172
- } else {
173
- Logger.log("🔀 Switching to the " + branchName + " branch.");
174
- await spawno("git", ["checkout", "-B", branchName], { output: true });
175
- }
176
-
177
- await commitAll(":arrow_up: " + newVersion + " :tada:");
178
- } catch (e) {
179
- done(e);
180
- }
181
- }).on("publish", async a => {
182
- let config = {};
183
-
184
- if (a.options.c.value) {
185
- try {
186
- config = require(abs(a.options.c.value));
187
- } catch (e) {
188
- Logger.log(e);
189
- return Logger.log(new Error("Cannot require the configuration file."));
190
- }
191
- }
192
-
193
- const readGhToken = () => {
194
- try {
195
- return require(abs("~/.github-config.json")).token;
196
- } catch (e) { };
197
- };
198
-
199
- const getRepoInfo = async (fullName) => {
200
- return new Promise((resolve, reject) => {
201
- gh.get("repos/" + fullName, function (err, repo) {
202
- if (err) {
203
- return reject(err);
204
- }
205
- resolve(repo);
206
- });
207
- });
208
- }
209
-
210
- const createPullRequest = async (fullName, data) => {
211
- return new Promise((resolve, reject) => {
212
- gh.get("repos/" + fullName + "/pulls", {
213
- data: data,
214
- headers: {
215
- Accept: "application/vnd.github.sailor-v-preview+json, application/vnd.github.v3+json"
216
- }
217
- }, function (err, pr) {
218
- if (err) {
219
- return reject(err);
220
- }
221
- resolve(pr);
222
- });
223
- });
224
- }
225
-
226
- const createRelease = async (fullName, data) => {
227
- return new Promise((resolve, reject) => {
228
- gh.get("repos/" + fullName + "/releases", {
229
- data: data,
230
- headers: {
231
- Accept: "application/vnd.github.sailor-v-preview+json, application/vnd.github.v3+json"
232
- }
233
- }, function (err, release) {
234
- if (err) {
235
- return reject(err);
236
- }
237
- resolve(release);
238
- });
239
- });
240
- }
241
-
242
- config.token = config.token || a.options.T.value || readGhToken();
243
- if (!config.token) {
244
- return Logger.log(new Error("A GitHub token is required."));
245
- }
246
-
247
- config = ul.merge({
248
- title: a.options.title.value || "<pack.name> <pack.version>",
249
- body: a.options.description.value,
250
- baseBranch: a.options.b.value
251
- }, config);
252
-
253
- if (!config.body) {
254
- return Logger.log(new Error("The pull request description is required."));
255
- }
256
-
257
- const gh = new GitHub(config.token);
258
- const packPath = pp(process.cwd());
259
-
260
- try {
261
- const pack = rJson(packPath);
262
- const repoUrl = findValue(pack, "repository.url");
263
- if (!repoUrl) {
264
- return done("Cannot find the repository URL in package.json.");
265
- }
266
- const url = gitUrlParse(repoUrl);
267
- if (url.source !== "github.com") {
268
- return done("The repository is not hosted on GitHub.");
269
- }
270
-
271
- Logger.log("🔎 Getting repository info.");
272
- config.version = pack.version;
273
- const fullName = url.full_name;
274
-
275
- const repo = await getRepoInfo(fullName);
276
- await npmInstall();
277
- await generateDocs();
278
- await commitAll("Updated docs")
279
- const cBranch = await currentBranch();
280
-
281
- config.headBranch = cBranch;
282
-
283
- Logger.log("📬 Creating a pull request.");
284
-
285
- config.baseBranch = config.baseBranch || repo.default_branch;
286
-
287
- mapO(config, function (v) {
288
- return v && barbe(v, ["<", ">"], { pack: pack, repo: repo });
289
- });
290
-
291
- await createPullRequest(fullName, {
292
- title: config.title,
293
- body: config.body,
294
- head: config.headBranch,
295
- base: config.baseBranch
296
- });
297
-
298
- Logger.log("✅ Created the pull request.");
299
-
300
- Logger.log("🔀 Switching to " + config.baseBranch);
301
- await spawno("git", ["checkout", config.baseBranch], { output: true });
302
-
303
- Logger.log("⬇️ Updating from GitHub.");
304
- await spawno("git", ["pull", "origin", config.baseBranch], { output: true });
305
-
306
- Logger.log("🔁 Merging " + config.headBranch + " -> " + config.baseBranch);
307
- await spawno("git", ["merge", config.headBranch], { output: true });
308
-
309
- Logger.log("🚀 Pushing everything to GitHub.");
310
- await spawno("git", ["push", "--all"], { output: true });
311
-
312
- Logger.log("📦 Publishing to npm.");
313
- await new Promise(
314
- (res, rej) => spawn("npm", ["publish"], {
315
- stdio: "inherit"
316
- }).on("exit", c => c === 0 ? res() : rej(new Error(`exit ${c}`)))
317
- );
318
-
319
- Logger.log("🏷️ Creating a new GitHub release.");
320
- await createRelease(fullName, {
321
- tag_name: config.version,
322
- name: config.version,
323
- body: config.body
324
- });
325
-
326
- Logger.log("✅ Created a new release.");
327
-
328
- Logger.log("🧹 Deleting the " + config.headBranch + " branch locally.");
329
- await spawno("git", ["branch", "-d", config.headBranch], { output: true });
330
-
331
- Logger.log("🧹 Deleting the " + config.headBranch + " branch on GitHub.");
332
- await spawno("git", ["push", "origin", "--delete", config.headBranch], { output: true });
333
- } catch (e) {
334
- Logger.log(e);
335
- }
336
- }).main(() => {
106
+ }]).on("branch", command("branch", o => shipRelease.branch({
107
+ name: o.name.value,
108
+ message: o.message.value
109
+ }), r => [["Branch", r.branch]])).on("bump", command("bump", o => shipRelease.bump({
110
+ type: o.bumpVersion.value,
111
+ currentBranch: o.currentBranch.is_provided ? o.currentBranch.value : undefined,
112
+ branch: o.branch.value
113
+ }), r => [
114
+ ["Version", `${r.previous || "unpublished"} → ${ui.c.green(ui.c.bold(r.version))}`],
115
+ ["Branch", r.branch],
116
+ ["Next", ui.c.dim("ship-release publish -d \"<what changed>\"")]
117
+ ])).on("publish", command("publish", o => shipRelease.publish({
118
+ token: o.token.value,
119
+ title: o.title.value,
120
+ body: o.description.value,
121
+ baseBranch: o.baseBranch.value,
122
+ configPath: o.configPath.value
123
+ }), r => [
124
+ ["Package", ui.c.green(ui.c.bold(`${r.pack.name}@${r.pack.version}`))],
125
+ ["npm", `https://www.npmjs.com/package/${r.pack.name}`],
126
+ ["Pull request", r.pullRequest && r.pullRequest.html_url],
127
+ ["Release", r.release.html_url]
128
+ ])).main(() => {
337
129
  app.displayHelp();
338
- })
130
+ });
package/lib/exec.js ADDED
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+
3
+ const spawno = require("spawno").default;
4
+ const { spawn } = require("child_process");
5
+ const ui = require("./ui");
6
+
7
+ const format = (cmd, args) => [cmd, ...args].join(" ");
8
+
9
+ /**
10
+ * Runs a command and rejects if it exits with a non-zero code (`spawno` on
11
+ * its own resolves no matter the exit code). The output is streamed
12
+ * indented and dimmed, unless `quiet` is set.
13
+ *
14
+ * @param {String} cmd The command.
15
+ * @param {Array} args The command arguments.
16
+ * @param {Object} opts Options: `quiet` (Boolean) to not print anything,
17
+ * `allowFail` (Boolean) to resolve even when the command fails.
18
+ * @returns {Promise<Object>} `{ code, stdout, stderr }`
19
+ */
20
+ const run = (cmd, args = [], opts = {}) => new Promise((resolve, reject) => {
21
+ const writer = opts.quiet ? null : ui.outputWriter();
22
+ if (!opts.quiet) { ui.command(cmd, args); }
23
+
24
+ const proc = spawno(cmd, args, {}, (err, stdout = "", stderr = "", code) => {
25
+ writer && writer.end();
26
+ if (err) { return reject(err); }
27
+ const res = { code, stdout: stdout.trim(), stderr: stderr.trim() };
28
+ if (code !== 0 && !opts.allowFail) {
29
+ const error = new Error(`\`${format(cmd, args)}\` exited with code ${code}.` + (opts.quiet && res.stderr ? `\n${res.stderr}` : ""));
30
+ error.code = code;
31
+ error.result = res;
32
+ return reject(error);
33
+ }
34
+ resolve(res);
35
+ });
36
+
37
+ if (writer) {
38
+ proc.stdout.on("data", d => writer.write(d));
39
+ proc.stderr.on("data", d => writer.write(d));
40
+ }
41
+ });
42
+
43
+ /**
44
+ * Runs a command attached to the current terminal (useful for commands which
45
+ * may prompt, such as `npm publish` asking for an OTP).
46
+ *
47
+ * @param {String} cmd The command.
48
+ * @param {Array} args The command arguments.
49
+ * @returns {Promise} Resolves when the command exits successfully.
50
+ */
51
+ const runInteractive = (cmd, args = []) => new Promise((resolve, reject) => {
52
+ ui.command(cmd, args);
53
+ spawn(cmd, args, { stdio: "inherit" })
54
+ .on("error", reject)
55
+ .on("exit", code => code === 0
56
+ ? resolve()
57
+ : reject(new Error(`\`${format(cmd, args)}\` exited with code ${code}.`))
58
+ );
59
+ });
60
+
61
+ module.exports = { run, runInteractive };
package/lib/git.js ADDED
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+
3
+ const ui = require("./ui");
4
+ const { run } = require("./exec");
5
+
6
+ const NEVER_WORK_ON = ["master", "main", "gh-pages"];
7
+
8
+ const git = (args, opts) => run("git", args, opts);
9
+
10
+ /**
11
+ * Returns the name of the currently checked out branch.
12
+ */
13
+ const currentBranch = async () => {
14
+ const { stdout } = await git(["rev-parse", "--abbrev-ref", "HEAD"], { quiet: true });
15
+ return stdout;
16
+ };
17
+
18
+ /**
19
+ * Returns the default branch of the `origin` remote, if git knows it.
20
+ */
21
+ const remoteDefaultBranch = async () => {
22
+ const { code, stdout } = await git(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], { quiet: true, allowFail: true });
23
+ return code === 0 ? stdout.replace(/^origin\//, "") : null;
24
+ };
25
+
26
+ /**
27
+ * Checks if the branch is one we should not commit work-in-progress to
28
+ * (the remote default branch, master, main or gh-pages).
29
+ */
30
+ const isProtectedBranch = async branch => {
31
+ const def = await remoteDefaultBranch();
32
+ return branch === def || NEVER_WORK_ON.includes(branch);
33
+ };
34
+
35
+ /**
36
+ * Switches to a branch, creating it if it does not exist yet. Uncommitted
37
+ * changes are carried over. An existing branch is never reset.
38
+ */
39
+ const checkoutNew = async branch => {
40
+ ui.step(`Switching to the ${ui.c.cyan(branch)} branch`);
41
+ const { code } = await git(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`], { quiet: true, allowFail: true });
42
+ await git(code === 0 ? ["checkout", branch] : ["checkout", "-b", branch]);
43
+ };
44
+
45
+ const hasChanges = async () => {
46
+ const { stdout } = await git(["status", "--porcelain"], { quiet: true });
47
+ return stdout.length > 0;
48
+ };
49
+
50
+ const push = async branch => {
51
+ ui.step(`Pushing ${ui.c.cyan(branch)} to GitHub`);
52
+ await git(["push", "-u", "origin", branch]);
53
+ };
54
+
55
+ /**
56
+ * Stages everything, commits (when there is something to commit) and pushes
57
+ * the current branch.
58
+ */
59
+ const commitAll = async message => {
60
+ ui.step(`Committing ${ui.c.dim(`"${message}"`)}`);
61
+ if (await hasChanges()) {
62
+ await git(["add", "-A", "."]);
63
+ await git(["commit", "-m", message]);
64
+ } else {
65
+ ui.info("Nothing to commit.");
66
+ }
67
+ await push(await currentBranch());
68
+ };
69
+
70
+ /**
71
+ * Merges `head` into `base`, after updating `base` from GitHub, and pushes it.
72
+ */
73
+ const mergeInto = async (head, base) => {
74
+ ui.step(`Merging ${ui.c.cyan(head)} → ${ui.c.cyan(base)}`);
75
+ await git(["checkout", base]);
76
+ await git(["pull", "origin", base]);
77
+ await git(["merge", head]);
78
+ await push(base);
79
+ };
80
+
81
+ /**
82
+ * Deletes a branch locally and on GitHub.
83
+ */
84
+ const deleteBranch = async branch => {
85
+ ui.step(`Cleaning up the ${ui.c.cyan(branch)} branch`);
86
+ await git(["branch", "-d", branch]);
87
+ const { code } = await git(["push", "origin", "--delete", branch], { allowFail: true });
88
+ if (code !== 0) { ui.warn(`Could not delete ${branch} on GitHub (already deleted?).`); }
89
+ };
90
+
91
+ module.exports = {
92
+ currentBranch,
93
+ isProtectedBranch,
94
+ checkoutNew,
95
+ commitAll,
96
+ mergeInto,
97
+ deleteBranch
98
+ };
package/lib/github.js ADDED
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+
3
+ const GitHub = require("gh.js");
4
+ const abs = require("abs").default;
5
+ const rJson = require("r-json");
6
+
7
+ /**
8
+ * Finds a GitHub token: the explicit one, then the `GITHUB_TOKEN`/`GH_TOKEN`
9
+ * environment variables, then `~/.github-config.json` (`{ "token": "..." }`).
10
+ */
11
+ const resolveToken = explicit => {
12
+ if (explicit) { return explicit; }
13
+ if (process.env.GITHUB_TOKEN || process.env.GH_TOKEN) {
14
+ return process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
15
+ }
16
+ try {
17
+ return rJson(abs("~/.github-config.json")).token || null;
18
+ } catch (e) {
19
+ return null;
20
+ }
21
+ };
22
+
23
+ /**
24
+ * Minimal promise-based wrapper around `gh.js`.
25
+ */
26
+ class GitHubClient {
27
+ constructor(token) {
28
+ this.gh = new GitHub(token);
29
+ }
30
+
31
+ request(path, data) {
32
+ return new Promise((resolve, reject) => {
33
+ this.gh.get(path, data ? { data } : {}, (err, res) => {
34
+ if (err) {
35
+ return reject(err instanceof Error ? err : new Error(`GitHub: ${err}`));
36
+ }
37
+ resolve(res);
38
+ });
39
+ });
40
+ }
41
+
42
+ repo(fullName) {
43
+ return this.request(`repos/${fullName}`);
44
+ }
45
+
46
+ createPullRequest(fullName, data) {
47
+ return this.request(`repos/${fullName}/pulls`, data);
48
+ }
49
+
50
+ createRelease(fullName, data) {
51
+ return this.request(`repos/${fullName}/releases`, data);
52
+ }
53
+ }
54
+
55
+ module.exports = { GitHubClient, resolveToken };
package/lib/index.js CHANGED
@@ -1 +1,246 @@
1
- "use strict";
1
+ "use strict";
2
+
3
+ const ui = require("./ui");
4
+ const rJson = require("r-json");
5
+ const wJson = require("w-json");
6
+ const pkgJson = require("pkg.json");
7
+ const packy = require("packy");
8
+ const Semver = require("semver");
9
+ const pp = require("package-json-path");
10
+ const abs = require("abs").default;
11
+ const findValue = require("find-value").default;
12
+ const gitUrlParse = require("git-url-parse");
13
+ const barbe = require("barbe");
14
+ const mapO = require("map-o");
15
+ const ul = require("ul").default;
16
+
17
+ const git = require("./git");
18
+ const { run, runInteractive } = require("./exec");
19
+ const { GitHubClient, resolveToken } = require("./github");
20
+
21
+ const BLAH_PATH = require.resolve("blah/bin/blah");
22
+ const BUMP_TYPES = ["major", "minor", "patch", "premajor", "preminor", "prepatch", "prerelease"];
23
+
24
+ // Fetches the latest published version of a package from npm.
25
+ // Resolves `null` if the package was never published.
26
+ const latestPublishedVersion = name => new Promise((resolve, reject) => {
27
+ pkgJson(name, "latest", (err, json) => {
28
+ if (err) {
29
+ return String(err.message).includes("doesn't exist") ? resolve(null) : reject(err);
30
+ }
31
+ resolve(json.version);
32
+ });
33
+ });
34
+
35
+ // Applies the `~/.packy.js(on)` defaults (if any) to the package.json file.
36
+ const applyPackyDefaults = packPath => {
37
+ let defaults = null;
38
+ try {
39
+ defaults = require(abs("~/.packy"));
40
+ } catch (e) {
41
+ if (e.code === "MODULE_NOT_FOUND") { return Promise.resolve(false); }
42
+ throw e;
43
+ }
44
+ ui.step("Applying the packy defaults to package.json");
45
+ return new Promise((resolve, reject) => {
46
+ packy(packPath, defaults, err => err ? reject(err) : resolve(true));
47
+ });
48
+ };
49
+
50
+ /**
51
+ * branch
52
+ * Creates (or resets) a branch, commits all the changes and pushes it.
53
+ *
54
+ * @name branch
55
+ * @function
56
+ * @param {Object} opts An object containing:
57
+ *
58
+ * - `name` (String): The branch name (default: `"new-version"`).
59
+ * - `message` (String): The commit message (default: `"Working on the new version."`).
60
+ *
61
+ * @returns {Promise<Object>} `{ branch }`
62
+ */
63
+ const branch = async (opts = {}) => {
64
+ const { name = "new-version", message = "Working on the new version." } = opts;
65
+ await git.checkoutNew(name);
66
+ await git.commitAll(message);
67
+ return { branch: name };
68
+ };
69
+
70
+ /**
71
+ * computeNextVersion
72
+ * Computes the next version of a package based on its latest npm release.
73
+ * Packages which were never published, or are still on `0.x.x`, get `1.0.0`.
74
+ *
75
+ * @name computeNextVersion
76
+ * @function
77
+ * @param {String} name The package name.
78
+ * @param {String} type The semver increment (`major`, `minor`, `patch`, ...).
79
+ * @returns {Promise<Object>} `{ previous, next }`
80
+ */
81
+ const computeNextVersion = async (name, type = "patch") => {
82
+ if (!BUMP_TYPES.includes(type)) {
83
+ throw new Error(`Invalid version bump: ${type}. Use one of: ${BUMP_TYPES.join(", ")}.`);
84
+ }
85
+ const previous = await latestPublishedVersion(name);
86
+ if (!previous) {
87
+ ui.info("The package is not published yet, using 1.0.0.");
88
+ return { previous, next: "1.0.0" };
89
+ }
90
+ if (Semver.major(previous) === 0) {
91
+ ui.info("There is no 1.x.x release yet, using 1.0.0.");
92
+ return { previous, next: "1.0.0" };
93
+ }
94
+ return { previous, next: Semver.inc(previous, type) };
95
+ };
96
+
97
+ /**
98
+ * bump
99
+ * Bumps the version in package.json (based on the latest npm release),
100
+ * commits and pushes the change.
101
+ *
102
+ * @name bump
103
+ * @function
104
+ * @param {Object} opts An object containing:
105
+ *
106
+ * - `type` (String): The semver increment: `major`, `minor` or `patch` (default: `"patch"`).
107
+ * - `currentBranch` (Boolean): Commit on the current branch instead of
108
+ * creating a new one. By default this is `true` unless the current branch
109
+ * is the default one (or `master`/`main`/`gh-pages`).
110
+ * - `branch` (String): The branch to create otherwise (default: `"new-version"`).
111
+ * - `cwd` (String): The project directory (default: `process.cwd()`).
112
+ *
113
+ * @returns {Promise<Object>} `{ previous, version, branch }`
114
+ */
115
+ const bump = async (opts = {}) => {
116
+ const packPath = pp(opts.cwd || process.cwd());
117
+ const pack = rJson(packPath);
118
+
119
+ ui.step("Computing the next version");
120
+ const { previous, next } = await computeNextVersion(pack.name, opts.type);
121
+ ui.success(`${ui.c.dim(previous || "unpublished")} → ${ui.c.green(ui.c.bold(next))}`);
122
+
123
+ pack.version = next;
124
+ wJson(packPath, pack);
125
+ ui.success("Updated package.json");
126
+
127
+ let useCurrent = opts.currentBranch;
128
+ if (typeof useCurrent !== "boolean") {
129
+ useCurrent = !(await git.isProtectedBranch(await git.currentBranch()));
130
+ }
131
+
132
+ if (useCurrent) {
133
+ ui.info(`Staying on the current branch.`);
134
+ } else {
135
+ await git.checkoutNew(opts.branch || "new-version");
136
+ }
137
+
138
+ await git.commitAll(`:arrow_up: ${next} :tada:`);
139
+ return { previous, version: next, branch: await git.currentBranch() };
140
+ };
141
+
142
+ /**
143
+ * publish
144
+ * Regenerates the docs (with blah), opens a pull request, merges it into the
145
+ * base branch, publishes the package on npm and creates a GitHub release.
146
+ *
147
+ * @name publish
148
+ * @function
149
+ * @param {Object} opts An object containing:
150
+ *
151
+ * - `token` (String): The GitHub token (defaults to `GITHUB_TOKEN`/`GH_TOKEN`, then `~/.github-config.json`).
152
+ * - `title` (String): The pull request title (default: `"<pack.name> <pack.version>"`).
153
+ * - `body` (String): The pull request/release description (required).
154
+ * - `baseBranch` (String): The base branch (default: the repository default branch).
155
+ * - `configPath` (String): Path to a json/js file exporting any of these fields.
156
+ * Values passed directly take precedence over the ones in the file.
157
+ * - `cwd` (String): The project directory (default: `process.cwd()`).
158
+ *
159
+ * The `title` and `body` are templates: `<pack.*>` and `<repo.*>` are replaced
160
+ * with fields from package.json and the GitHub repository.
161
+ *
162
+ * @returns {Promise<Object>} `{ pack, pullRequest, release }` (`pullRequest` is `null` when already on the base branch).
163
+ */
164
+ const publish = async (opts = {}) => {
165
+ let fileConfig = {};
166
+ if (opts.configPath) {
167
+ try {
168
+ fileConfig = require(abs(opts.configPath));
169
+ } catch (e) {
170
+ throw new Error(`Cannot require the configuration file (${opts.configPath}): ${e.message}`);
171
+ }
172
+ }
173
+
174
+ const config = ul.merge(mapO(opts, v => v === null ? undefined : v), fileConfig);
175
+ config.token = resolveToken(config.token);
176
+ if (!config.token) {
177
+ throw new Error("A GitHub token is required (--token, GITHUB_TOKEN or ~/.github-config.json).");
178
+ }
179
+ if (!config.body) {
180
+ throw new Error("The pull request description is required.");
181
+ }
182
+ config.title = config.title || "<pack.name> <pack.version>";
183
+
184
+ const packPath = pp(config.cwd || process.cwd());
185
+ const repoUrl = findValue(rJson(packPath), "repository.url");
186
+ if (!repoUrl) {
187
+ throw new Error("Cannot find the repository URL in package.json.");
188
+ }
189
+ const parsedUrl = gitUrlParse(repoUrl);
190
+ if (parsedUrl.source !== "github.com") {
191
+ throw new Error("The repository is not hosted on GitHub.");
192
+ }
193
+ const fullName = parsedUrl.full_name;
194
+ const gh = new GitHubClient(config.token);
195
+
196
+ ui.step(`Fetching ${ui.c.cyan(fullName)} from GitHub`);
197
+ const repo = await gh.repo(fullName);
198
+ ui.success(`Default branch: ${repo.default_branch}`);
199
+
200
+ ui.step("Installing the dependencies");
201
+ await run("npm", ["install", "--omit=dev"]);
202
+
203
+ await applyPackyDefaults(packPath);
204
+
205
+ ui.step("Generating the documentation (blah)");
206
+ await run(BLAH_PATH, ["-f"]);
207
+ await git.commitAll("Updated docs");
208
+
209
+ // Read package.json again: packy may have changed it
210
+ const pack = rJson(packPath);
211
+ const head = await git.currentBranch();
212
+ const base = config.baseBranch || repo.default_branch;
213
+ const fill = v => typeof v === "string" ? barbe(v, ["<", ">"], { pack, repo }) : v;
214
+ const title = fill(config.title);
215
+ const body = fill(config.body);
216
+
217
+ let pr = null;
218
+ if (head !== base) {
219
+ ui.step(`Opening a pull request ${ui.c.dim(`"${title}"`)}`);
220
+ pr = await gh.createPullRequest(fullName, { title, body, head, base });
221
+ ui.success(pr.html_url);
222
+ await git.mergeInto(head, base);
223
+ } else {
224
+ ui.info(`Already on ${base}, skipping the pull request.`);
225
+ }
226
+
227
+ ui.step(`Publishing ${ui.c.cyan(`${pack.name}@${pack.version}`)} to npm`);
228
+ await runInteractive("npm", ["publish"]);
229
+
230
+ ui.step(`Creating the ${ui.c.cyan(pack.version)} GitHub release`);
231
+ const release = await gh.createRelease(fullName, {
232
+ tag_name: pack.version,
233
+ target_commitish: base,
234
+ name: pack.version,
235
+ body
236
+ });
237
+ ui.success(release.html_url);
238
+
239
+ if (head !== base) {
240
+ await git.deleteBranch(head);
241
+ }
242
+
243
+ return { pack, pullRequest: pr, release };
244
+ };
245
+
246
+ module.exports = { branch, bump, publish, computeNextVersion };
package/lib/ui.js ADDED
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+
3
+ const Logger = require("bug-killer");
4
+
5
+ const useColor = !process.env.NO_COLOR && (process.env.FORCE_COLOR || process.stdout.isTTY);
6
+ const paint = (open, close) => s => useColor ? `\u001b[${open}m${s}\u001b[${close}m` : String(s);
7
+
8
+ const c = {
9
+ bold: paint(1, 22),
10
+ dim: paint(2, 22),
11
+ red: paint(31, 39),
12
+ green: paint(32, 39),
13
+ yellow: paint(33, 39),
14
+ cyan: paint(36, 39),
15
+ magenta: paint(35, 39)
16
+ };
17
+
18
+ const out = s => ui.silent || process.stdout.write(s + "\n");
19
+
20
+ let stepNo = 0;
21
+ let startedAt = Date.now();
22
+
23
+ const elapsed = () => {
24
+ const ms = Date.now() - startedAt;
25
+ return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`;
26
+ };
27
+
28
+ /**
29
+ * Small helpers for consistent terminal output.
30
+ */
31
+ const ui = {
32
+ c,
33
+
34
+ /** When `true`, nothing is printed (useful in tests). */
35
+ silent: false,
36
+
37
+ /** Prints the command header, e.g. `🚢 ship-release publish my-pkg@1.2.3`. */
38
+ header(command, subtitle) {
39
+ stepNo = 0;
40
+ startedAt = Date.now();
41
+ out("");
42
+ out(`${c.bold(c.magenta("🚢 ship-release"))} ${c.bold(command)}${subtitle ? " " + c.dim(subtitle) : ""}`);
43
+ out("");
44
+ },
45
+
46
+ /** Starts a new numbered step. */
47
+ step(msg) {
48
+ stepNo += 1;
49
+ out(`${c.cyan(c.bold(String(stepNo).padStart(2)))} ${c.dim("›")} ${c.bold(msg)}`);
50
+ },
51
+
52
+ info(msg) { out(` ${c.dim("ℹ " + msg)}`); },
53
+ success(msg) { out(` ${c.green("✔")} ${msg}`); },
54
+ warn(msg) { out(` ${c.yellow("⚠")} ${c.yellow(msg)}`); },
55
+
56
+ /** Prints a command that is about to run. */
57
+ command(cmd, args) {
58
+ const quote = a => /[\s"'$]/.test(a) ? JSON.stringify(a) : a;
59
+ out(` ${c.dim("$ " + [cmd, ...args].map(quote).join(" "))}`);
60
+ },
61
+
62
+ /** Returns a stream-like writer printing subprocess output indented and dimmed. */
63
+ outputWriter() {
64
+ let buffer = "";
65
+ const flush = line => out(` ${c.dim("│ " + line)}`);
66
+ return {
67
+ write(chunk) {
68
+ buffer += chunk.toString();
69
+ const lines = buffer.split(/\r?\n/);
70
+ buffer = lines.pop();
71
+ lines.filter(l => l.trim()).forEach(flush);
72
+ },
73
+ end() {
74
+ if (buffer.trim()) { flush(buffer); }
75
+ buffer = "";
76
+ }
77
+ };
78
+ },
79
+
80
+ /** Prints the final summary: a list of `[label, value]` pairs. */
81
+ done(rows = []) {
82
+ out("");
83
+ out(`${c.green(c.bold("✔ Done"))} ${c.dim("in " + elapsed())}`);
84
+ const width = Math.max(0, ...rows.map(([k]) => k.length));
85
+ rows.filter(([, v]) => v).forEach(([k, v]) => out(` ${c.dim(k.padEnd(width))} ${v}`));
86
+ out("");
87
+ },
88
+
89
+ /** Prints an error (with the stack trace when DEBUG is set). */
90
+ error(err) {
91
+ out("");
92
+ out(`${c.red(c.bold("✖ Failed"))} ${c.dim("after " + elapsed() + (stepNo ? `, at step ${stepNo}` : ""))}`);
93
+ if (process.env.DEBUG) {
94
+ Logger.log(err, "error");
95
+ } else {
96
+ out(` ${c.red(err && err.message || err)}`);
97
+ }
98
+ out("");
99
+ }
100
+ };
101
+
102
+ module.exports = ui;
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "ship-release",
3
3
  "description": "Publish new versions on GitHub and npm with ease.",
4
- "version": "5.0.0",
4
+ "version": "6.0.1",
5
5
  "bin": {
6
6
  "ship-release": "./bin/ship-release.js"
7
7
  },
8
8
  "main": "lib/index.js",
9
9
  "scripts": {
10
- "test": "echo \"Error: no test specified\" && exit 1"
10
+ "test": "node test"
11
11
  },
12
12
  "author": "Ionică Bizău <bizauionica@gmail.com> (https://ionicabizau.net)",
13
13
  "license": "MIT",
@@ -38,7 +38,6 @@
38
38
  "cli.js",
39
39
  "index.js",
40
40
  "index.d.ts",
41
- "package-lock.json",
42
41
  "bloggify.js",
43
42
  "bloggify.json",
44
43
  "bloggify/"
@@ -50,20 +49,28 @@
50
49
  "npm"
51
50
  ],
52
51
  "dependencies": {
53
- "abs": "^1.3.15",
54
- "barbe": "^3.0.17",
55
- "blah": "^5.4.2",
52
+ "abs": "^2.0.1",
53
+ "barbe": "^3.0.18",
54
+ "blah": "^6.1.4",
56
55
  "bug-killer": "^4.4.4",
57
- "find-value": "^1.0.13",
58
- "gh.js": "^3.2.1",
59
- "git-url-parse": "^16.1.0",
60
- "map-o": "^2.0.11",
61
- "package-json-path": "^1.0.10",
62
- "pkg.json": "^2.0.9",
63
- "r-json": "^1.3.1",
64
- "spawno": "^2.1.2",
56
+ "find-value": "^2.0.1",
57
+ "gh.js": "^3.2.2",
58
+ "git-url-parse": "^16.1.1",
59
+ "map-o": "^2.0.12",
60
+ "package-json-path": "^1.0.11",
61
+ "packy": "^1.2.12",
62
+ "pkg.json": "^2.0.10",
63
+ "r-json": "^1.3.2",
64
+ "semver": "^7.8.6",
65
+ "spawno": "^3.0.0",
65
66
  "tilda": "^4.4.17",
66
- "ul": "^5.2.16",
67
- "w-json": "^1.3.11"
67
+ "ul": "^7.0.1",
68
+ "w-json": "^1.3.12"
69
+ },
70
+ "engines": {
71
+ "node": "^20.19.0 || >=22.12.0"
72
+ },
73
+ "devDependencies": {
74
+ "tester": "^2.0.0"
68
75
  }
69
76
  }