backstage

Форк
0
92 строки · 2.5 Кб
1
/*
2
 * Copyright 2020 The Backstage Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
import { relative as relativePath } from 'path';
18
import { spawn } from 'child_process';
19
import { OptionValues } from 'commander';
20
import { findPaths } from '@backstage/cli-common';
21
import { platform } from 'os';
22
import { ExitCodeError } from './errors';
23

24
// eslint-disable-next-line no-restricted-syntax
25
const paths = findPaths(__dirname);
26

27
export function createCodemodAction(name: string) {
28
  return async (dirs: string[], opts: OptionValues) => {
29
    const transformPath = relativePath(
30
      process.cwd(),
31
      paths.resolveOwn('transforms', `${name}.js`),
32
    );
33

34
    const args = [
35
      '--parser=tsx',
36
      '--extensions=tsx,js,ts,tsx',
37
      '--transform',
38
      transformPath,
39
      '--ignore-pattern=**/node_modules/**',
40
    ];
41

42
    if (opts.dry) {
43
      args.push('--dry');
44
    }
45

46
    if (dirs.length) {
47
      args.push(...dirs);
48
    } else {
49
      args.push('.');
50
    }
51

52
    console.log(`Running jscodeshift with these arguments: ${args.join(' ')}`);
53

54
    let command;
55
    if (platform() === 'win32') {
56
      command = 'jscodeshift';
57
    } else {
58
      // jscodeshift ships a slightly broken bin script with windows
59
      // line endings so we need to execute it using node rather than
60
      // letting the `#!/usr/bin/env node` take care of it
61
      command = process.argv0;
62
      args.unshift(require.resolve('.bin/jscodeshift'));
63
    }
64

65
    const child = spawn(command, args, {
66
      stdio: 'inherit',
67
      shell: true,
68
      env: {
69
        ...process.env,
70
        FORCE_COLOR: 'true',
71
      },
72
    });
73

74
    if (typeof child.exitCode === 'number') {
75
      if (child.exitCode) {
76
        throw new ExitCodeError(child.exitCode, name);
77
      }
78
      return;
79
    }
80

81
    await new Promise<void>((resolve, reject) => {
82
      child.once('error', error => reject(error));
83
      child.once('exit', code => {
84
        if (code) {
85
          reject(new ExitCodeError(code, name));
86
        } else {
87
          resolve();
88
        }
89
      });
90
    });
91
  };
92
}
93

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.