-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathsearch.js
More file actions
84 lines (70 loc) · 3 KB
/
search.js
File metadata and controls
84 lines (70 loc) · 3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
'use strict';
const got = require('got');
const Table = require('cli-table3');
const chalk = require('chalk');
const moment = require('moment');
const truncate = require('truncate');
const handleError = require('./util/handleError');
exports.command = 'search <query...>';
exports.describe = 'Search npms.io for packages.';
exports.builder = (yargs) =>
yargs
.usage('Usage: $0 search <query...> [options]\n\nSearch npms.io for packages.\nFor advances filters and modifiers visit https://api-docs.npms.io/#api-search-query.')
.example('$0 search cross spawn', 'Search for "cross spawn"')
.example('$0 search cross spawn --output json', 'Search for "cross spawn" and print results as JSON')
.example('$0 search sass keywords:gulpplugin', 'Search for "sass" packages that contain the "gulpplugin" keywords')
.options({
from: {
alias: 'f',
describe: 'The offset in which to start searching from',
default: 0,
type: 'number',
},
size: {
alias: 's',
describe: 'The total number of results to return',
default: 10,
type: 'number',
},
output: {
alias: 'o',
describe: 'Format the results in a table or as JSON',
default: 'table',
choices: ['table', 'json'],
},
api: {
describe: 'The API url',
default: 'https://api.npms.io/v2',
},
});
exports.handler = (argv) => {
got(`${argv.api}/search?q=${argv.query.join(' ')}&from=${argv.from}&size=${argv.size}`, {
json: true,
})
.then((res) => {
if (argv.output === 'json') {
console.log(JSON.stringify(res.body.results, null, 2));
return;
}
if (!res.body.results.length) {
console.log(chalk.red(`No matches found for: ${chalk.white.bold(argv.query.join(' '))}`));
return;
}
const table = new Table({ head: ['Package', 'Quality', 'Popularity', 'Maintenance', 'Score'] });
table.push(...res.body.results.map((item) => {
const pkg = item.package;
const packageColumn = [
`${chalk.bold(pkg.name)} • ${chalk.dim(pkg.links.repository || pkg.links.npm)}`,
chalk.gray(truncate(pkg.description, 80, { ellipsis: '...' })),
pkg.date && pkg.publisher ? chalk.dim(`updated ${moment(pkg.date).fromNow()} by ${pkg.publisher.username}`) : '',
].join('\n');
const scoreColumns = ['quality', 'popularity', 'maintenance']
.map((score) => ({ hAlign: 'center', vAlign: 'center', content: Math.round(item.score.detail[score] * 100) }))
.concat([{ hAlign: 'center', vAlign: 'center', content: chalk.green(Math.round(item.score.final * 100)) }]);
return [packageColumn].concat(scoreColumns);
}));
console.log(table.toString());
})
.then(() => { process.exitCode = 0; })
.catch((err) => handleError(err));
};