UNPKG

3.02 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 });
19var fs = require("fs");
20var path = require("path");
21var utils_1 = require("./utils");
22var CORE_FORMATTERS_DIRECTORY = path.resolve(__dirname, "formatters");
23function findFormatter(name, formattersDirectory) {
24 if (typeof name === "function") {
25 return name;
26 }
27 else if (typeof name === "string") {
28 name = name.trim();
29 var camelizedName = utils_1.camelize(name + "Formatter");
30 // first check for core formatters
31 var Formatter = loadFormatter(CORE_FORMATTERS_DIRECTORY, camelizedName, true);
32 if (Formatter !== undefined) {
33 return Formatter;
34 }
35 // then check for rules within the first level of rulesDirectory
36 if (formattersDirectory !== undefined) {
37 Formatter = loadFormatter(formattersDirectory, camelizedName);
38 if (Formatter !== undefined) {
39 return Formatter;
40 }
41 }
42 // else try to resolve as module
43 return loadFormatterModule(name);
44 }
45 else {
46 // If an something else is passed as a name (e.g. object)
47 throw new Error("Name of type " + typeof name + " is not supported.");
48 }
49}
50exports.findFormatter = findFormatter;
51function loadFormatter(directory, name, isCore) {
52 var formatterPath = path.resolve(path.join(directory, name));
53 var fullPath;
54 if (isCore) {
55 fullPath = formatterPath + ".js";
56 if (!fs.existsSync(fullPath)) {
57 return undefined;
58 }
59 }
60 else {
61 // Resolve using node's path resolution to allow developers to write custom formatters in TypeScript which can be loaded by TS-Node
62 try {
63 fullPath = require.resolve(formatterPath);
64 }
65 catch (_a) {
66 return undefined;
67 }
68 }
69 return require(fullPath).Formatter;
70}
71function loadFormatterModule(name) {
72 var src;
73 try {
74 // first try to find a module in the dependencies of the currently linted project
75 src = utils_1.tryResolvePackage(name, process.cwd());
76 if (src === undefined) {
77 // if there is no local module, try relative to the installation of TSLint (might be global)
78 src = require.resolve(name);
79 }
80 }
81 catch (_a) {
82 return undefined;
83 }
84 return require(src).Formatter;
85}