/
find-reporter.js
90 lines (72 loc) 路 2.25 KB
/
find-reporter.js
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
85
86
87
88
89
90
"use strict";
const JSReporters = require( "js-reporters" );
const path = require( "path" );
const findup = require( "findup-sync" );
const utils = require( "./utils" );
const pkg = require( "../../package.json" );
function findReporter( reporterName ) {
if ( !reporterName ) {
return JSReporters.TapReporter;
}
// First, check if the reporter is one of the standard js-reporters ones
const capitalizedName = utils.capitalize( reporterName );
const jsReporterName = `${capitalizedName}Reporter`;
if ( JSReporters[ jsReporterName ] ) {
return JSReporters[ jsReporterName ];
}
// Second, check if the reporter is an npm package
try {
return require( reporterName );
} catch ( e ) {
if ( e.code !== "MODULE_NOT_FOUND" ) {
throw e;
}
}
// If we didn't find a reporter, display the available reporters and exit
displayAvailableReporters( reporterName );
}
function displayAvailableReporters( inputReporterName ) {
const message = [];
if ( inputReporterName ) {
message.push( `No reporter found matching "${inputReporterName}".` );
}
const jsReporters = getReportersFromJSReporters();
message.push( `Available reporters from JS Reporters are: ${jsReporters.join( ", " )}` );
const npmReporters = getReportersFromDependencies();
if ( npmReporters.length ) {
message.push(
`Available custom reporters from dependencies are: ${npmReporters.join( ", " )}`
);
}
utils.error( message.join( "\n" ) );
}
function getReportersFromJSReporters() {
const jsReporterRegex = /(.*)Reporter$/;
return Object.keys( JSReporters )
.filter( key => jsReporterRegex.test( key ) )
.map( reporter => reporter.match( jsReporterRegex )[ 1 ].toLowerCase() )
.sort();
}
function getReportersFromDependencies() {
const dependencies = [].concat(
Object.keys( pkg.dependencies ),
Object.keys( pkg.devDependencies )
);
return dependencies.filter( dep => {
try {
const depPath = path.dirname( require.resolve( dep ) );
const pkgPath = findup( "package.json", { cwd: depPath } );
const pkg = require( pkgPath );
return !!pkg.keywords && pkg.keywords.indexOf( "js-reporter" ) !== -1;
} catch ( e ) {
if ( e.code !== "MODULE_NOT_FOUND" ) {
throw e;
}
}
return false;
} );
}
module.exports = {
findReporter,
displayAvailableReporters
};