From 4c44814df6561a936a5fb591a8ea37dffa35efef Mon Sep 17 00:00:00 2001 From: Mordechai Gerstley Date: Wed, 3 Nov 2021 07:25:00 +0100 Subject: [PATCH] feat(land): avoid landing on the wrong default branch (#586) Fail if the user is trying to land a commit on "master" or "main", and the default branch name doesn't match. --- components/git/land.js | 14 ++++++++++---- lib/landing_session.js | 16 ++++++++++++++++ lib/queries/DefaultBranchRef.gql | 8 ++++++++ 3 files changed, 34 insertions(+), 4 deletions(-) create mode 100644 lib/queries/DefaultBranchRef.gql diff --git a/components/git/land.js b/components/git/land.js index dff93c2..5dc2d14 100644 --- a/components/git/land.js +++ b/components/git/land.js @@ -1,5 +1,6 @@ 'use strict'; +const auth = require('../../lib/auth'); const { parsePRFromURL } = require('../../lib/links'); const { getMetadata } = require('../metadata'); const CLI = require('../../lib/cli'); @@ -144,10 +145,9 @@ function land(state, argv) { if (argv.yes) { cli.setAssumeYes(); } - const req = new Request(); const dir = process.cwd(); - return runPromise(main(state, argv, cli, req, dir)).catch((err) => { + return runPromise(main(state, argv, cli, dir)).catch((err) => { if (cli.spinner.enabled) { cli.spinner.fail(); } @@ -163,10 +163,16 @@ module.exports = { handler }; -async function main(state, argv, cli, req, dir) { +async function main(state, argv, cli, dir) { + const credentials = await auth({ + github: true + }); + const req = new Request(credentials); let session = new LandingSession(cli, req, dir); - if (state !== AMEND && state !== CONTINUE && session.warnForWrongBranch()) { + if (state !== AMEND && + state !== CONTINUE && + await session.warnForWrongBranch()) { return; } diff --git a/lib/landing_session.js b/lib/landing_session.js index 8d4ba03..c5ca053 100644 --- a/lib/landing_session.js +++ b/lib/landing_session.js @@ -456,6 +456,22 @@ class LandingSession extends Session { async status() { // TODO } + + async warnForWrongBranch() { + if (super.warnForWrongBranch()) { + return true; + } + const rev = this.getCurrentBranch(); + const { repository: { defaultBranchRef } } = await this.req.gql( + 'DefaultBranchRef', + { owner: this.owner, repo: this.repo }); + if ((rev === 'master' || rev === 'main') && defaultBranchRef.name !== rev) { + this.cli.warn(`You are running git-node-land on \`${rev}\`,` + + ` but the default branch is \`${defaultBranchRef.name}\`.`); + this.cli.setExitCode(1); + return true; + } + } } module.exports = LandingSession; diff --git a/lib/queries/DefaultBranchRef.gql b/lib/queries/DefaultBranchRef.gql new file mode 100644 index 0000000..3f27684 --- /dev/null +++ b/lib/queries/DefaultBranchRef.gql @@ -0,0 +1,8 @@ +query DefaultBranchRef($owner: String!, $repo: String!) { + repository(owner: $owner, name: $repo) { + defaultBranchRef { + name + } + } +} +