1import { CommanderStatic } from 'commander';
2import * as tempy from 'tempy';
3
4import { Config } from './Config';
5import ConfigReader from './ConfigReader';
6import { Platform } from './Platform';
7
8export interface DefaultOptions {
9  configFile: string;
10  platform: Platform;
11  path: string;
12  shouldBeCleaned: boolean;
13}
14
15function mapPlatform(platform: string): Platform {
16  if (platform === 'android') {
17    return Platform.Android;
18  } else if (platform === 'ios') {
19    return Platform.iOS;
20  } else if (platform === 'both') {
21    return Platform.Both;
22  }
23
24  throw new Error(`Unknown platform: ${platform}`);
25}
26
27export function registerCommand<OptionsType extends DefaultOptions>(
28  commander: CommanderStatic,
29  commandName: string,
30  fn: (config: Config, options: OptionsType) => Promise<any>
31) {
32  return commander
33    .command(commandName)
34    .option('-c, --config <path>', 'Path to the config file.')
35    .option(
36      '--platform <platform>',
37      'Platform for which the project should be created. Available options: `ios`, `android`, `both`.'
38    )
39    .option('-p, --path <string>', 'Location where the test app will be created.')
40    .action(async (providedOptions) => {
41      if (providedOptions.platform) {
42        providedOptions.platform = mapPlatform(providedOptions.platform);
43      } else {
44        providedOptions.platform = Platform.Both;
45      }
46
47      // clean temp folder if the path wasn't provided.
48      providedOptions.shouldBeCleaned = !providedOptions.path;
49      providedOptions.path = providedOptions.path ?? tempy.directory();
50
51      providedOptions.configFile = ConfigReader.getFilePath(providedOptions.configFile);
52
53      const options = providedOptions as OptionsType;
54      const configReader = new ConfigReader(options.configFile);
55
56      try {
57        await fn(configReader.readConfigFile(), options);
58      } catch (e) {
59        console.error(e);
60        process.exit(1);
61      }
62    });
63}
64