๐Ÿ“ฆ ionic-team / capacitor

๐Ÿ“„ sysconfig.ts ยท 60 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
60import Debug from 'debug';
import { readJSON, writeJSON, mkdirp } from 'fs-extra';
import { dirname, resolve } from 'path';

import { ENV_PATHS } from './util/cli';
import { uuidv4 } from './util/uuid';

const debug = Debug('capacitor:sysconfig');

const SYSCONFIG_FILE = 'sysconfig.json';
const SYSCONFIG_PATH = resolve(ENV_PATHS.config, SYSCONFIG_FILE);

export interface SystemConfig {
  /**
   * A UUID that anonymously identifies this computer.
   */
  readonly machine: string;

  /**
   * Whether telemetry is enabled or not.
   *
   * If undefined, a choice has not yet been made.
   */
  readonly telemetry?: boolean;

  /**
   * Wheter the user choose to signup or not.
   *
   * If undefined, the prompt has not been shown.
   */
  readonly signup?: boolean;
}

export async function readConfig(): Promise<SystemConfig> {
  debug('Reading from %O', SYSCONFIG_PATH);

  try {
    return await readJSON(SYSCONFIG_PATH);
  } catch (e: any) {
    if (e.code !== 'ENOENT') {
      throw e;
    }

    const sysconfig: SystemConfig = {
      machine: uuidv4(),
    };

    await writeConfig(sysconfig);

    return sysconfig;
  }
}

export async function writeConfig(sysconfig: SystemConfig): Promise<void> {
  debug('Writing to %O', SYSCONFIG_PATH);

  await mkdirp(dirname(SYSCONFIG_PATH));
  await writeJSON(SYSCONFIG_PATH, sysconfig, { spaces: '\t' });
}