Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/npm/cli.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authordoug.wade <doug.wade@redfin.com>2016-03-08 09:25:51 +0300
committerRebecca Turner <me@re-becca.org>2016-03-10 22:55:11 +0300
commit24ab70a4ccfeaa005b80252da313bb589510668e (patch)
treecb87d28b38bc442673a2628dd2076fda7bc1d971 /lib/view.js
parent3db37a52b2b2e3193ef250ad2cf96dfd2def2777 (diff)
view: Make npm produce valid JSON when requested with --json
Previously it produced some sort of weird hybrid output, with multiple JSON docs. Credit: @doug-wade Reviewed-By: @iarna PR-URL: https://github.com/npm/npm/pull/11813 Fixes: #11808
Diffstat (limited to 'lib/view.js')
-rw-r--r--lib/view.js35
1 files changed, 27 insertions, 8 deletions
diff --git a/lib/view.js b/lib/view.js
index 9ca18d354..e6fa21655 100644
--- a/lib/view.js
+++ b/lib/view.js
@@ -239,29 +239,48 @@ function search (data, fields, version, title) {
function printData (data, name, cb) {
var versions = Object.keys(data)
var msg = ''
+ var msgJson = []
var includeVersions = versions.length > 1
var includeFields
versions.forEach(function (v) {
var fields = Object.keys(data[v])
includeFields = includeFields || (fields.length > 1)
+ msgJson.push({})
fields.forEach(function (f) {
var d = cleanup(data[v][f])
+ if (fields.length === 1 && npm.config.get('json')) {
+ msgJson[msgJson.length - 1][f] = d
+ }
if (includeVersions || includeFields || typeof d !== 'string') {
- d = cleanup(data[v][f])
- d = npm.config.get('json')
- ? JSON.stringify(d, null, 2)
- : util.inspect(d, false, 5, npm.color)
+ if (npm.config.get('json')) {
+ msgJson[msgJson.length - 1][f] = d
+ } else {
+ d = util.inspect(d, false, 5, npm.color)
+ }
} else if (typeof d === 'string' && npm.config.get('json')) {
d = JSON.stringify(d)
}
- if (f && includeFields) f += ' = '
- if (d.indexOf('\n') !== -1) d = ' \n' + d
- msg += (includeVersions ? name + '@' + v + ' ' : '') +
- (includeFields ? f : '') + d + '\n'
+ if (!npm.config.get('json')) {
+ if (f && includeFields) f += ' = '
+ if (d.indexOf('\n') !== -1) d = ' \n' + d
+ msg += (includeVersions ? name + '@' + v + ' ' : '') +
+ (includeFields ? f : '') + d + '\n'
+ }
})
})
+ if (msgJson.length && Object.keys(msgJson[0]).length === 1) {
+ var k = Object.keys(msgJson[0])[0]
+ msgJson = msgJson.map(function (m) { return m[k] })
+ }
+
+ if (!msg) {
+ msg = JSON.stringify(msgJson[0], null, 2) + '\n'
+ } else if (msgJson.length > 1) {
+ msg = JSON.stringify(msgJson, null, 2) + '\n'
+ }
+
// preserve output symmetry by adding a whitespace-only line at the end if
// there's one at the beginning
if (/^\s*\n/.test(msg)) msg += '\n'