summaryrefslogtreecommitdiffstats
path: root/dom/webgpu/tests/cts/checkout/src/common/tools/gen_cache.ts
blob: e7e6d8514f1a22cfcdeb1498f2086ea2ba45be05 (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
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
import * as fs from 'fs';
import * as path from 'path';
import * as process from 'process';

import { Cacheable, dataCache, setIsBuildingDataCache } from '../framework/data_cache.js';

function usage(rc: number): void {
  console.error(`Usage: tools/gen_cache [options] [OUT_DIR] [SUITE_DIRS...]

For each suite in SUITE_DIRS, pre-compute data that is expensive to generate
at runtime and store it under OUT_DIR. If the data file is found then the
DataCache will load this instead of building the expensive data at CTS runtime.

Options:
  --help          Print this message and exit.
  --list          Print the list of output files without writing them.
`);
  process.exit(rc);
}

let mode: 'emit' | 'list' = 'emit';

const nonFlagsArgs: string[] = [];
for (const a of process.argv) {
  if (a.startsWith('-')) {
    if (a === '--list') {
      mode = 'list';
    } else if (a === '--help') {
      usage(0);
    } else {
      console.log('unrecognized flag: ', a);
      usage(1);
    }
  } else {
    nonFlagsArgs.push(a);
  }
}

if (nonFlagsArgs.length < 4) {
  usage(0);
}

const outRootDir = nonFlagsArgs[2];

dataCache.setStore({
  load: (path: string) => {
    return new Promise<string>((resolve, reject) => {
      fs.readFile(`data/${path}`, 'utf8', (err, data) => {
        if (err !== null) {
          reject(err.message);
        } else {
          resolve(data);
        }
      });
    });
  },
});
setIsBuildingDataCache();

void (async () => {
  for (const suiteDir of nonFlagsArgs.slice(3)) {
    await build(suiteDir);
  }
})();

const specFileSuffix = __filename.endsWith('.ts') ? '.spec.ts' : '.spec.js';

async function crawlFilesRecursively(dir: string): Promise<string[]> {
  const subpathInfo = await Promise.all(
    (await fs.promises.readdir(dir)).map(async d => {
      const p = path.join(dir, d);
      const stats = await fs.promises.stat(p);
      return {
        path: p,
        isDirectory: stats.isDirectory(),
        isFile: stats.isFile(),
      };
    })
  );

  const files = subpathInfo
    .filter(i => i.isFile && i.path.endsWith(specFileSuffix))
    .map(i => i.path);

  return files.concat(
    await subpathInfo
      .filter(i => i.isDirectory)
      .map(i => crawlFilesRecursively(i.path))
      .reduce(async (a, b) => (await a).concat(await b), Promise.resolve([]))
  );
}

async function build(suiteDir: string) {
  if (!fs.existsSync(suiteDir)) {
    console.error(`Could not find ${suiteDir}`);
    process.exit(1);
  }

  // Crawl files and convert paths to be POSIX-style, relative to suiteDir.
  const filesToEnumerate = (await crawlFilesRecursively(suiteDir)).sort();

  const cacheablePathToTS = new Map<string, string>();

  for (const file of filesToEnumerate) {
    if (file.endsWith(specFileSuffix)) {
      const pathWithoutExtension = file.substring(0, file.length - specFileSuffix.length);
      const mod = await import(`../../../${pathWithoutExtension}.spec.js`);
      if (mod.d?.serialize !== undefined) {
        const cacheable = mod.d as Cacheable<unknown>;

        {
          // Check for collisions
          const existing = cacheablePathToTS.get(cacheable.path);
          if (existing !== undefined) {
            console.error(
              `error: Cacheable '${cacheable.path}' is emitted by both:
    '${existing}'
and
    '${file}'`
            );
            process.exit(1);
          }
          cacheablePathToTS.set(cacheable.path, file);
        }

        const outPath = `${outRootDir}/data/${cacheable.path}`;

        switch (mode) {
          case 'emit': {
            const data = await cacheable.build();
            const serialized = cacheable.serialize(data);
            fs.mkdirSync(path.dirname(outPath), { recursive: true });
            fs.writeFileSync(outPath, serialized);
            break;
          }
          case 'list': {
            console.log(outPath);
            break;
          }
        }
      }
    }
  }
}