UNPKG

3.05 kBJavaScriptView Raw
1"use strict";
2/**
3 * @license
4 * Copyright 2013 Palantir Technologies, Inc.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18Object.defineProperty(exports, "__esModule", { value: true });
19exports.findFormatter = void 0;
20var fs = require("fs");
21var path = require("path");
22var utils_1 = require("./utils");
23var CORE_FORMATTERS_DIRECTORY = path.resolve(__dirname, "formatters");
24function findFormatter(name, formattersDirectory) {
25 if (typeof name === "function") {
26 return name;
27 }
28 else if (typeof name === "string") {
29 name = name.trim();
30 var camelizedName = utils_1.camelize(name + "Formatter");
31 // first check for core formatters
32 var Formatter = loadFormatter(CORE_FORMATTERS_DIRECTORY, camelizedName, true);
33 if (Formatter !== undefined) {
34 return Formatter;
35 }
36 // then check for rules within the first level of rulesDirectory
37 if (formattersDirectory !== undefined) {
38 Formatter = loadFormatter(formattersDirectory, camelizedName);
39 if (Formatter !== undefined) {
40 return Formatter;
41 }
42 }
43 // else try to resolve as module
44 return loadFormatterModule(name);
45 }
46 else {
47 // If an something else is passed as a name (e.g. object)
48 throw new Error("Name of type " + typeof name + " is not supported.");
49 }
50}
51exports.findFormatter = findFormatter;
52function loadFormatter(directory, name, isCore) {
53 var formatterPath = path.resolve(path.join(directory, name));
54 var fullPath;
55 if (isCore) {
56 fullPath = formatterPath + ".js";
57 if (!fs.existsSync(fullPath)) {
58 return undefined;
59 }
60 }
61 else {
62 // Resolve using node's path resolution to allow developers to write custom formatters in TypeScript which can be loaded by TS-Node
63 try {
64 fullPath = require.resolve(formatterPath);
65 }
66 catch (_a) {
67 return undefined;
68 }
69 }
70 return require(fullPath).Formatter;
71}
72function loadFormatterModule(name) {
73 var src;
74 try {
75 // first try to find a module in the dependencies of the currently linted project
76 src = utils_1.tryResolvePackage(name, process.cwd());
77 if (src === undefined) {
78 // if there is no local module, try relative to the installation of TSLint (might be global)
79 src = require.resolve(name);
80 }
81 }
82 catch (_a) {
83 return undefined;
84 }
85 return require(src).Formatter;
86}