๐Ÿ“ฆ ionic-team / capacitor

๐Ÿ“„ run.ts ยท 148 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148import { columnar } from '@ionic/utils-terminal';

import { runAndroid } from '../android/run';
import c from '../colors';
import {
  isValidPlatform,
  resolvePlatform,
  runPlatformHook,
  selectPlatforms,
  promptForPlatform,
  getPlatformTargetName,
} from '../common';
import { getCordovaPlugins, writeCordovaAndroidManifest } from '../cordova';
import type { Config } from '../definitions';
import { fatal, isFatal } from '../errors';
import { runIOS } from '../ios/run';
import { logger, output } from '../log';
import { CapLiveReloadHelper } from '../util/livereload';
import { getPlatformTargets } from '../util/native-run';

import { sync } from './sync';

export interface RunCommandOptions {
  scheme?: string;
  flavor?: string;
  list?: boolean;
  json?: boolean;
  target?: string;
  targetName?: string;
  targetNameSdkVersion?: string;
  sync?: boolean;
  forwardPorts?: string;
  liveReload?: boolean;
  host?: string;
  port?: string;
  configuration?: string;
}

export async function runCommand(
  config: Config,
  selectedPlatformName: string,
  options: RunCommandOptions,
): Promise<void> {
  options.host = options.host ?? CapLiveReloadHelper.getIpAddress() ?? 'localhost';
  options.port = options.port ?? '3000';
  if (selectedPlatformName && !(await isValidPlatform(selectedPlatformName))) {
    const platformDir = resolvePlatform(config, selectedPlatformName);
    if (platformDir) {
      await runPlatformHook(config, selectedPlatformName, platformDir, 'capacitor:run');
    } else {
      logger.error(`Platform ${c.input(selectedPlatformName)} not found.`);
    }
  } else {
    const platforms = await selectPlatforms(config, selectedPlatformName);
    let platformName: string;
    if (platforms.length === 1) {
      platformName = platforms[0];
    } else {
      platformName = await promptForPlatform(
        platforms.filter(createRunnablePlatformFilter(config)),
        `Please choose a platform to run:`,
      );
    }

    if (options.list) {
      const targets = await getPlatformTargets(platformName);
      const outputTargets = targets.map((t) => ({
        name: getPlatformTargetName(t),
        api: `${t.platform === 'ios' ? 'iOS' : 'API'} ${t.sdkVersion}`,
        id: t.id ?? '?',
      }));

      if (options.json) {
        process.stdout.write(`${JSON.stringify(outputTargets)}\n`);
      } else {
        const rows = outputTargets.map((t) => [t.name, t.api, t.id]);

        output.write(
          `${columnar(rows, {
            headers: ['Name', 'API', 'Target ID'],
            vsep: ' ',
          })}\n`,
        );
      }

      return;
    }

    try {
      if (options.sync) {
        await sync(config, platformName, false, true);
      }
      const cordovaPlugins = await getCordovaPlugins(config, platformName);
      if (options.liveReload) {
        await CapLiveReloadHelper.editCapConfigForLiveReload(config, platformName, options);
        if (platformName === config.android.name) {
          await await writeCordovaAndroidManifest(cordovaPlugins, config, platformName, true);
        }
      }
      await run(config, platformName, options);
      if (options.liveReload) {
        new Promise((resolve) => process.on('SIGINT', resolve))
          .then(async () => {
            await CapLiveReloadHelper.revertCapConfigForLiveReload();
            if (platformName === config.android.name) {
              await writeCordovaAndroidManifest(cordovaPlugins, config, platformName, false);
            }
          })
          .then(() => process.exit());
        logger.info(
          `App running with live reload listing for: http://${options.host}:${options.port}. Press Ctrl+C to quit.`,
        );
        await sleepForever();
      }
    } catch (e: any) {
      if (!isFatal(e)) {
        fatal(e.stack ?? e);
      }

      throw e;
    }
  }
}

export async function run(config: Config, platformName: string, options: RunCommandOptions): Promise<void> {
  if (platformName == config.ios.name) {
    await runIOS(config, options);
  } else if (platformName === config.android.name) {
    await runAndroid(config, options);
  } else if (platformName === config.web.name) {
    return;
  } else {
    throw `Platform ${platformName} is not valid.`;
  }
}

function createRunnablePlatformFilter(config: Config): (platform: string) => boolean {
  return (platform) => platform === config.ios.name || platform === config.android.name;
}

async function sleepForever(): Promise<never> {
  return new Promise<never>(() => {
    setInterval(() => {
      /* do nothing */
    }, 1000);
  });
}