Skip to content

Commit

Permalink
perf: defer windowWidth() to improve perf for non-help usage (#610)
Browse files Browse the repository at this point in the history
* defer windowWidth() to improve perf for non-help usage

* respond to @nexdrew's comments

* add 2nd arg to maxWidth() per @nexdrew
  • Loading branch information
nolanlawson authored and bcoe committed Aug 29, 2016
1 parent fdb3364 commit cbc3636
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions lib/usage.js
Expand Up @@ -96,11 +96,23 @@ module.exports = function (yargs, y18n) {
epilog = msg
}

var wrap = windowWidth()
var wrapSet = false
var wrap
self.wrap = function (cols) {
wrapSet = true
wrap = cols
}

function getWrap () {
// lazily call windowWidth() because it's very expensive,
// and only needs to be called if the user wants to show usage/help
if (!wrapSet) {
wrap = windowWidth()
wrapSet = true
}
return wrap
}

var deferY18nLookupPrefix = '__yargsString__:'
self.deferY18nLookup = function (str) {
return deferY18nLookupPrefix + str
Expand All @@ -122,9 +134,10 @@ module.exports = function (yargs, y18n) {
return acc
}, {})
)
var theWrap = getWrap()
var ui = require('cliui')({
width: wrap,
wrap: !!wrap
width: theWrap,
wrap: !!theWrap
})

// the usage string.
Expand All @@ -140,7 +153,7 @@ module.exports = function (yargs, y18n) {

commands.forEach(function (command) {
ui.div(
{text: command[0], padding: [0, 2, 0, 2], width: maxWidth(commands) + 4},
{text: command[0], padding: [0, 2, 0, 2], width: maxWidth(commands, theWrap) + 4},
{text: command[1]}
)
})
Expand Down Expand Up @@ -214,7 +227,7 @@ module.exports = function (yargs, y18n) {
].filter(Boolean).join(' ')

ui.span(
{text: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches) + 4},
{text: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches, theWrap) + 4},
desc
)

Expand All @@ -235,7 +248,7 @@ module.exports = function (yargs, y18n) {

examples.forEach(function (example) {
ui.div(
{text: example[0], padding: [0, 2, 0, 2], width: maxWidth(examples) + 4},
{text: example[0], padding: [0, 2, 0, 2], width: maxWidth(examples, theWrap) + 4},
example[1]
)
})
Expand All @@ -254,7 +267,7 @@ module.exports = function (yargs, y18n) {

// return the maximum width of a string
// in the left-hand column of a table.
function maxWidth (table) {
function maxWidth (table, theWrap) {
var width = 0

// table might be of the form [leftColumn],
Expand All @@ -271,7 +284,7 @@ module.exports = function (yargs, y18n) {

// if we've enabled 'wrap' we should limit
// the max-width of the left-column.
if (wrap) width = Math.min(width, parseInt(wrap * 0.5, 10))
if (theWrap) width = Math.min(width, parseInt(theWrap * 0.5, 10))

return width
}
Expand Down

0 comments on commit cbc3636

Please sign in to comment.