Skip to content
This repository has been archived by the owner on Nov 4, 2022. It is now read-only.

Commit

Permalink
refactor(options): make options immutable with immer
Browse files Browse the repository at this point in the history
  • Loading branch information
Ryan Garant committed Sep 25, 2019
1 parent 951cf04 commit e378e4f
Show file tree
Hide file tree
Showing 9 changed files with 77 additions and 60 deletions.
4 changes: 2 additions & 2 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"type": "node",
"request": "launch",
"runtimeArgs": ["-r", "ts-node/register"],
"args": ["${workspaceFolder}/src/debug.ts", "user", "--user=zeno"],
"args": ["${workspaceFolder}/src/debug.ts", "us", "--whoami"],
// "args": ["${workspaceFolder}/src/debug.ts", "ji", "LWM-117", "--status"],
"console": "integratedTerminal"
},
Expand All @@ -19,7 +19,7 @@
"request": "launch",
"env": { "NODE_ENV": "testing", "GH_USER": "protoEvangelion", "GH_TOKEN": "0001" },
"runtimeArgs": ["-r", "ts-node/register"],
"args": ["${workspaceFolder}/src/debug.ts", "pr", "659", "--browser"],
"args": ["${workspaceFolder}/src/debug.ts", "re", "--new", "foo", "--init"],
"console": "integratedTerminal"
}
]
Expand Down
7 changes: 6 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"cli-table3": "0.5.1",
"colors": "1.3.3",
"handlebars": "^4.2.0",
"immer": "^4.0.0",
"inquirer": "6.2.1",
"lodash": "^4.17.15",
"marked": "^0.7.0",
Expand Down
12 changes: 0 additions & 12 deletions src/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,6 @@ export function clone(o) {

export function load() {}

/**
* Checks if there are aliases in your .gh.json file.
* If there are aliases in your .gh.json file, we will attempt to resolve the user, PR forwarder or PR submitter to your alias.
*/
export function expandAliases(options) {
if (config.alias) {
options.fwd = config.alias[options.fwd] || options.fwd
options.submit = config.alias[options.submit] || options.submit
options.user = config.alias[options.user] || options.user
}
}

export function find(filepath, opt_pattern) {
return fs.readdirSync(filepath).filter(file => {
return (opt_pattern || /.*/).test(file)
Expand Down
95 changes: 56 additions & 39 deletions src/cmd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import * as fs from 'fs'
import * as nopt from 'nopt'
import * as path from 'path'
import * as updateNotifier from 'update-notifier'
import { find, getUser, expandAliases } from './base'
import { find, getUser } from './base'
import * as configs from './configs'
import * as git from './git'
import * as logger from './logger'
import { produce, setAutoFreeze } from 'immer'

const config = configs.getConfig()

Expand Down Expand Up @@ -93,25 +93,27 @@ function notifyVersion() {
}
}

export async function setUp() {
let Command
let options
const parsed = nopt(process.argv)
let remain = parsed.argv.remain
let cooked = parsed.argv.cooked

async function getCommand(args) {
/**
* nopt function returns:
*
* remain: The remaining args after all the parsing has occurred.
* original: The args as they originally appeared.
* cooked: The args after flags and shorthands are expanded.
*/
const parsed = nopt(args)
const remain = parsed.argv.remain
const cooked = parsed.argv.cooked
let module = remain[0]

notifyVersion()

if (cooked[0] === '--version' || cooked[0] === '-v') {
module = 'version'
} else if (!remain.length || cooked.indexOf('-h') >= 0 || cooked.indexOf('--help') >= 0) {
module = 'help'
}

try {
Command = await loadCommand(module)
var Command = await loadCommand(module)
} catch (err) {
throw new Error(`Cannot find module ${module}\n${err}`)
}
Expand All @@ -120,41 +122,56 @@ export async function setUp() {
throw new Error(`No cmd or plugin found.`)
}

options = nopt(Command.DETAILS.options, Command.DETAILS.shorthands, process.argv, 2)

cooked = options.argv.cooked
remain = options.argv.remain

options.number = options.number || [remain[1]]
options.remote = options.remote || config.default_remote

const remoteUrl = git.getRemoteUrl(options.remote)
return Command
}

options.isTTY = {}
options.isTTY.in = Boolean(process.stdin.isTTY)
options.isTTY.out = Boolean(process.stdout.isTTY)
options.loggedUser = getUser()
options.remoteUser = git.getUserFromRemoteUrl(remoteUrl)
export async function setUp() {
notifyVersion()

if (!options.user) {
if (options.repo || options.all) {
options.user = options.loggedUser
} else {
options.user = process.env.GH_USER || options.remoteUser || options.loggedUser
const Command = await getCommand(process.argv)

const args = nopt(Command.DETAILS.options, Command.DETAILS.shorthands, process.argv, 2)

setAutoFreeze(false)

const options = produce(args, draft => {
// Gets 2nd positional arg (`gh pr 1` will return 1)
const secondArg = [draft.argv.remain[1]]
const remote = draft.remote || config.default_remote
const remoteUrl = git.getRemoteUrl(remote)

draft.remote = remote
draft.number = draft.number || secondArg
draft.loggedUser = getUser()
draft.remoteUser = git.getUserFromRemoteUrl(remoteUrl)
draft.repo = draft.repo || git.getRepoFromRemoteURL(remoteUrl)
draft.currentBranch = git.getCurrentBranch()
draft.github_host = config.github_host
draft.github_gist_host = config.github_gist_host

if (!draft.user) {
if (draft.repo || draft.all) {
draft.user = draft.loggedUser
} else {
draft.user = process.env.GH_USER || draft.remoteUser || draft.loggedUser
}
}
}

expandAliases(options)

options.repo = options.repo || git.getRepoFromRemoteURL(remoteUrl)
options.currentBranch = testing ? 'master' : git.getCurrentBranch()
options.github_host = config.github_host
options.github_gist_host = config.github_gist_host
/**
* Checks if there are aliases in your .gh.json file.
* If there are aliases in your .gh.json file, we will attempt to resolve the user, PR forwarder or PR submitter to your alias.
*/
if (config.alias) {
draft.fwd = config.alias[draft.fwd] || draft.fwd
draft.submit = config.alias[draft.submit] || draft.submit
draft.user = config.alias[draft.user] || draft.user
}
})

if (testing) {
const { prepareTestFixtures } = await import('./utils')

await new Command(options).run(prepareTestFixtures(Command.name, cooked))
await new Command(options).run(prepareTestFixtures(Command.name, args.argv.cooked))
} else {
await new Command(options).run()
}
Expand Down
3 changes: 1 addition & 2 deletions src/cmds/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,7 @@ Help.prototype.listFlags_ = function(command) {
}

Help.prototype.listCommands_ = function(commands) {
let content =
'usage: gh <command> [payload] [--flags] [--verbose] [--no-color] [--no-hooks]\n\n'
let content = 'usage: gh <command> [--flags] [--verbose] [--no-color] [--no-hooks]\n\n'

content += 'List of available commands:\n'

Expand Down
6 changes: 4 additions & 2 deletions src/cmds/repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,9 @@ Repo.prototype.run = async function(done) {
options.type = options.type || Repo.TYPE_OWNER
}

if (options.isTTY.out) {
// Add a isTTY value on the options to determine whether or not the command is executed in a TTY context or not.
// Will be false if cmd is piped like: gh re --list | cat
if (Boolean(process.stdout.isTTY)) {
logger.log(
`Listing ${logger.colors.green(options.type)} repos for ${logger.colors.green(
user
Expand Down Expand Up @@ -474,7 +476,7 @@ Repo.prototype.listCallback_ = function(repos): void {
logger.log(`last update ${logger.getDuration(repo.updated_at, options.date)}`)
}

if (options.isTTY.out) {
if (Boolean(process.stdout.isTTY)) {
logger.log(
`${logger.colors.green(
`forks: ${repo.forks}, stars: ${repo.watchers}, issues: ${
Expand Down
5 changes: 3 additions & 2 deletions src/cmds/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,13 @@ User.DETAILS = {
User.prototype.run = async function(done) {
const instance = this
const options = instance.options
let login

if (!hasCmdInOptions(User.DETAILS.commands, options)) {
options.login = true
login = true
}

if (options.login) {
if (login) {
if (tokenExists()) {
logger.log(`You're logged in as ${logger.colors.green(options.user)}`)
} else {
Expand Down
4 changes: 4 additions & 0 deletions src/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,10 @@ export function getConfig(key) {
}

export function getCurrentBranch() {
if (testing) {
return 'master'
}

var git = exec.spawnSync(git_command, ['symbolic-ref', '--short', 'HEAD'])

if (git.status !== 0) {
Expand Down

0 comments on commit e378e4f

Please sign in to comment.