UNPKG

2.56 kBJavaScriptView Raw
1var component = require('component');
2var utils = component.utils;
3var cols = process.stdout.columns || 80;
4
5module.exports = function(options){
6
7 var query = options.terms.join(' ');
8
9 // search
10
11 component.search(query, function(err, pkgs){
12 if (err) utils.fatal(err.message);
13 if (!pkgs.length) return;
14 if (options.json) json(pkgs)
15 else verbose(pkgs);
16 });
17
18 /**
19 * Truncate the string if necessary.
20 */
21
22 function truncate(str, repo) {
23 var pad = 30 + repo.length;
24 if (str.length < cols - pad) return str;
25 return str.slice(0, cols - pad) + '…';
26 }
27
28 /**
29 * Wrap description `str`.
30 */
31
32 function description(str) {
33 if (!str) return '';
34 var space;
35 var width = cols - 20;
36 for (var i = 0; i < str.length; ++i) {
37 if (i && i % width == 0) {
38 space = str.indexOf(' ', i);
39 str = str.slice(0, space) + '\n ' + str.slice(space);
40 }
41 }
42 return str;
43 }
44
45 /**
46 * Filter blanks. TODO: remove... shouldn't be necessary
47 */
48
49 function blanks(pkg) {
50 return pkg;
51 }
52
53 /**
54 * Sort by stars descending.
55 */
56
57 function stars(a, b) {
58 return b.stars - a.stars;
59 }
60
61 /**
62 * Open `pkgs` in the default browser.
63 */
64
65 function open(pkgs) {
66 var max = 5;
67 pkgs.slice(0, max).forEach(function(pkg){
68 if (!pkg.repo) return console.warn('%s missing "repo"', pkg.name);
69 openSite('https://github.com/' + pkg.repo);
70 });
71 }
72
73 /**
74 * Verbose output.
75 */
76
77 function verbose(pkgs) {
78 console.log();
79 pkgs.filter(blanks).sort(stars).forEach(function(pkg){
80 console.log(' \033[36m%s\033[m', pkg.repo.toLowerCase() + "@" + pkg.version);
81 console.log(' url: \033[90mhttps://github.com/%s\033[m', pkg.repo);
82 console.log(' desc: \033[90m%s\033[m', description(pkg.description));
83 if (options.verbose) console.log(' demo: \033[90m%s\033[m', pkg.demo || 'none');
84 if (options.verbose) console.log(' license: \033[90m%s\033[m', pkg.license || 'none');
85 console.log(' ★ \033[90m%s\033[m', pkg.stars);
86 console.log();
87 });
88 console.log();
89 }
90
91 /**
92 * JSON output.
93 */
94
95 function json(pkgs) {
96 var len = pkgs.length;
97 console.log('[');
98 pkgs.filter(blanks).sort(stars).forEach(function(pkg, i){
99 process.stdout.write(JSON.stringify(pkg, null, 2));
100 if (i < len - 1) process.stdout.write(',\n');
101 });
102 console.log(']');
103 }
104
105 /**
106 * Handle EPIPE for pagers.
107 */
108
109 process.stdout.on('error', function(err){
110 if ('EPIPE' == err.code) return;
111 throw err;
112 });
113
114}