aboutsummaryrefslogtreecommitdiffhomepage
path: root/tools/utils/index.ts
blob: e0808bd11b86f14eeec92ed2afd87354113ab15e (plain)
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
import fs from 'fs-extra';
import { SemVer } from 'semver';
import { logger } from '../../lib/logger';

export const newFiles = new Set();

/**
 * Get environment variable or empty string.
 * Used for easy mocking.
 * @param {string} key variable name
 * @returns {string}
 */
export function getEnv(key: string): string {
  return process.env[key] ?? '';
}

/**
 * Find all module directories.
 * @param {string} dirname dir to search in
 * @returns {string[]}
 */
export function findModules(dirname: string): string[] {
  return fs
    .readdirSync(dirname, { withFileTypes: true })
    .filter((dirent) => dirent.isDirectory())
    .map((dirent) => dirent.name)
    .filter((name) => !name.startsWith('__'))
    .sort();
}

/**
 * @param {string} input
 * @returns {string}
 */
export function camelCase(input: string): string {
  return input
    .replace(/(?:^\w|[A-Z]|\b\w)/g, (char, index) =>
      index === 0 ? char.toLowerCase() : char.toUpperCase(),
    )
    .replace(/-/g, '');
}

/**
 * @param {string } file
 * @param {string} code
 * @returns {Promise<void>}
 */
export async function updateFile(file: string, code: string): Promise<void> {
  const oldCode = fs.existsSync(file) ? await fs.readFile(file, 'utf8') : null;
  if (code !== oldCode) {
    if (!code) {
      logger.error({ file }, 'Missing content');
    }
    await fs.outputFile(file, code ?? '', { encoding: 'utf8' });
  }
  newFiles.add(file);
}

/**
 * @param {string } file
 * @returns {Promise<string | null>}
 */
export function readFile(file: string): Promise<string> {
  if (fs.existsSync(file)) {
    return fs.readFile(file, 'utf8');
  }
  return Promise.resolve('');
}

/**
 *
 * @param  val
 */
export function parsePositiveInt(val: string | undefined): number {
  if (!val) {
    return 0;
  }
  const r = Number.parseInt(val, 10);
  if (!Number.isFinite(r) || r < 0) {
    throw new Error(`Invalid number: ${val}`);
  }

  return r;
}

/**
 *
 * @param val
 */
export function parseVersion(val: string | undefined): SemVer | undefined {
  if (!val) {
    return undefined;
  }
  // can throw
  return new SemVer(val);
}