• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import { Logger } from '../lib/Logger';
17import { logTscDiagnostic } from '../lib/utils/functions/LogTscDiagnostic';
18import type { CommandLineOptions } from '../lib/CommandLineOptions';
19import { Command, Option } from 'commander';
20import * as ts from 'typescript';
21import * as fs from 'node:fs';
22import * as path from 'node:path';
23
24const TS_EXT = '.ts';
25const TSX_EXT = '.tsx';
26const ETS_EXT = '.ets';
27
28let inputFiles: string[];
29let responseFile = '';
30function addSrcFile(value: string): void {
31  if (value.startsWith('@')) {
32    responseFile = value;
33  } else {
34    inputFiles.push(value);
35  }
36}
37
38const getFiles = (dir: string): string[] => {
39  const resultFiles: string[] = [];
40
41  const files = fs.readdirSync(dir);
42  for (let i = 0; i < files.length; ++i) {
43    const name = path.join(dir, files[i]);
44    if (fs.statSync(name).isDirectory()) {
45      resultFiles.push(...getFiles(name));
46    } else {
47      const extension = path.extname(name);
48      if (extension === TS_EXT || extension === TSX_EXT || extension === ETS_EXT) {
49        resultFiles.push(name);
50      }
51    }
52  }
53
54  return resultFiles;
55};
56
57function addProjectFolder(projectFolder: string, previous: string[]): string[] {
58  return previous.concat([projectFolder]);
59}
60
61function formCommandLineOptions(program: Command): CommandLineOptions {
62  const opts: CommandLineOptions = { inputFiles: inputFiles, warningsAsErrors: false, enableAutofix: false };
63  const options = program.opts();
64  if (options.TSC_Errors) {
65    opts.logTscErrors = true;
66  }
67  if (options.devecoPluginMode) {
68    opts.ideMode = true;
69  }
70  if (options.testMode) {
71    opts.testMode = true;
72  }
73  if (options.projectFolder) {
74    doProjectFolderArg(options.projectFolder, opts);
75  }
76  if (options.project) {
77    doProjectArg(options.project, opts);
78  }
79  if (options.autofix) {
80    opts.enableAutofix = true;
81  }
82  if (options.warningsAsErrors) {
83    opts.warningsAsErrors = true;
84  }
85  return opts;
86}
87
88export function parseCommandLine(commandLineArgs: string[]): CommandLineOptions {
89  const program = new Command();
90  program.name('tslinter').description('Linter for TypeScript sources').
91    version('0.0.1');
92  program.
93    option('-E, --TSC_Errors', 'show error messages from Tsc').
94    option('--test-mode', 'run linter as if running TS test files').
95    option('--deveco-plugin-mode', 'run as IDE plugin').
96    option('-p, --project <project_file>', 'path to TS project config file').
97    option('--project-folder <project_folder>', 'path to folder containig TS files to verify', addProjectFolder, []).
98    option('--autofix', 'automatically fix problems found by linter').
99    addOption(new Option('--warnings-as-errors', 'treat warnings as errors').hideHelp(true));
100  program.argument('[srcFile...]', 'files to be verified', addSrcFile);
101
102  inputFiles = [];
103  // method parse() eats two first args, so make them dummy
104  let cmdArgs: string[] = ['dummy', 'dummy'];
105  cmdArgs.push(...commandLineArgs);
106  program.parse(cmdArgs);
107  if (responseFile !== '') {
108    try {
109      // eslint-disable-next-line no-param-reassign
110      commandLineArgs = fs.
111        readFileSync(responseFile.slice(1)).
112        toString().
113        split('\n').
114        filter((e) => {
115          return e.trimEnd();
116        });
117      cmdArgs = ['dummy', 'dummy'];
118      cmdArgs.push(...commandLineArgs);
119      program.parse(cmdArgs);
120    } catch (error) {
121      Logger.error('Failed to read response file: ' + error);
122      process.exit(-1);
123    }
124  }
125
126  return formCommandLineOptions(program);
127}
128
129function doProjectFolderArg(prjFolders: string[], opts: CommandLineOptions): void {
130  for (let i = 0; i < prjFolders.length; i++) {
131    const prjFolderPath = prjFolders[i];
132    try {
133      opts.inputFiles.push(...getFiles(prjFolderPath));
134    } catch (error) {
135      Logger.error('Failed to read folder: ' + error);
136      process.exit(-1);
137    }
138  }
139}
140
141function doProjectArg(cfgPath: string, opts: CommandLineOptions): void {
142  // Process project file (tsconfig.json) and retrieve config arguments.
143  const configFile = cfgPath;
144
145  const host: ts.ParseConfigFileHost = ts.sys as ts.System & ts.ParseConfigFileHost;
146
147  const diagnostics: ts.Diagnostic[] = [];
148
149  try {
150    const oldUnrecoverableDiagnostic = host.onUnRecoverableConfigFileDiagnostic;
151    host.onUnRecoverableConfigFileDiagnostic = (diagnostic: ts.Diagnostic): void => {
152      diagnostics.push(diagnostic);
153    };
154    opts.parsedConfigFile = ts.getParsedCommandLineOfConfigFile(configFile, {}, host);
155    host.onUnRecoverableConfigFileDiagnostic = oldUnrecoverableDiagnostic;
156
157    if (opts.parsedConfigFile) {
158      diagnostics.push(...ts.getConfigFileParsingDiagnostics(opts.parsedConfigFile));
159    }
160
161    if (diagnostics.length > 0) {
162      // Log all diagnostic messages and exit program.
163      Logger.error('Failed to read config file.');
164      logTscDiagnostic(diagnostics, Logger.info);
165      process.exit(-1);
166    }
167  } catch (error) {
168    Logger.error('Failed to read config file: ' + error);
169    process.exit(-1);
170  }
171}
172