|
| 1 | +import { execFile } from 'child_process'; |
| 2 | +import { writeFileSync } from 'fs'; |
| 3 | +import { promisify } from 'util'; |
| 4 | + |
| 5 | +const execFileAsync = promisify(execFile); |
| 6 | + |
| 7 | +type AnyObject = Record<string, any>; |
| 8 | + |
| 9 | +function parseArgs(argv: string[]) { |
| 10 | + const args: Record<string, string | boolean> = {}; |
| 11 | + for (let i = 2; i < argv.length; i++) { |
| 12 | + const a = argv[i]; |
| 13 | + if (a.startsWith('--')) { |
| 14 | + const [k, v] = a.split('='); |
| 15 | + const key = k.replace(/^--/, ''); |
| 16 | + if (typeof v === 'string') args[key] = v; |
| 17 | + else if (i + 1 < argv.length && !argv[i + 1].startsWith('-')) args[key] = argv[++i]; |
| 18 | + else args[key] = true; |
| 19 | + } |
| 20 | + } |
| 21 | + return args; |
| 22 | +} |
| 23 | + |
| 24 | +async function kubectlRaw(path: string): Promise<AnyObject> { |
| 25 | + const { stdout } = await execFileAsync('kubectl', ['get', '--raw', path], { maxBuffer: 1024 * 1024 * 200 }); |
| 26 | + return JSON.parse(stdout.toString()); |
| 27 | +} |
| 28 | + |
| 29 | +async function main() { |
| 30 | + const args = parseArgs(process.argv); |
| 31 | + const outPath = (args.out as string) || __dirname + '/swagger.v2.json'; |
| 32 | + const endpoint = (args.index as string) || '/openapi/v2'; |
| 33 | + |
| 34 | + console.log(`[info] fetching OpenAPI v2: ${endpoint}`); |
| 35 | + const doc = await kubectlRaw(endpoint); |
| 36 | + |
| 37 | + if (doc.openapi) { |
| 38 | + console.warn('[warn] Received OpenAPI v3 document at /openapi/v2?'); |
| 39 | + } |
| 40 | + if (doc.swagger !== '2.0') { |
| 41 | + console.warn(`[warn] Expected swagger "2.0", got: ${doc.swagger || 'unknown'}`); |
| 42 | + } |
| 43 | + |
| 44 | + const pathsCount = doc.paths ? Object.keys(doc.paths).length : 0; |
| 45 | + const defsCount = doc.definitions ? Object.keys(doc.definitions).length : 0; |
| 46 | + console.log(`[info] fetched: ${pathsCount} paths, ${defsCount} definitions`); |
| 47 | + |
| 48 | + writeFileSync(outPath, JSON.stringify(doc, null, 2)); |
| 49 | + console.log(`[info] wrote ${outPath}`); |
| 50 | +} |
| 51 | + |
| 52 | +main().catch(err => { |
| 53 | + console.error('[error] ' + (err?.stack || err?.message || String(err))); |
| 54 | + process.exit(1); |
| 55 | +}); |
0 commit comments