|
| 1 | +import { execSync } from 'node:child_process'; |
| 2 | + |
| 3 | +function isGlobPath(path: string) { |
| 4 | + const globPattern = /[*?{}\[\]()]/; |
| 5 | + return globPattern.test(path); |
| 6 | +} |
| 7 | + |
| 8 | +const filePathPattern = 'file://'; |
| 9 | + |
| 10 | +function parseSingleLocalFilePath(schemaPointer: string) { |
| 11 | + if (schemaPointer.includes('://') && !schemaPointer.startsWith(filePathPattern)) { |
| 12 | + return { |
| 13 | + status: 'error' as const, |
| 14 | + error: { |
| 15 | + type: 'path' as const, |
| 16 | + message: 'URL is not a local path.', |
| 17 | + }, |
| 18 | + }; |
| 19 | + } |
| 20 | + |
| 21 | + if (isGlobPath(schemaPointer)) { |
| 22 | + return { |
| 23 | + status: 'error' as const, |
| 24 | + error: { |
| 25 | + type: 'path' as const, |
| 26 | + message: 'Path is a glob pattern.', |
| 27 | + }, |
| 28 | + }; |
| 29 | + } |
| 30 | + |
| 31 | + return { |
| 32 | + status: 'ok' as const, |
| 33 | + path: schemaPointer.startsWith(filePathPattern) |
| 34 | + ? schemaPointer.substring(0, filePathPattern.length) |
| 35 | + : schemaPointer, |
| 36 | + }; |
| 37 | +} |
| 38 | + |
| 39 | +const buildShowGitFileCommand = (commit: string, path: string) => `git show ${commit}:${path}`; |
| 40 | + |
| 41 | +function loadGitFile(commit: string, path: string) { |
| 42 | + try { |
| 43 | + const sdl = execSync(buildShowGitFileCommand(commit, path), { cwd: process.cwd() }).toString(); |
| 44 | + return { |
| 45 | + status: 'ok' as const, |
| 46 | + sdl, |
| 47 | + }; |
| 48 | + } catch (error) { |
| 49 | + if (error instanceof Error) { |
| 50 | + return { |
| 51 | + status: 'error' as const, |
| 52 | + error: { |
| 53 | + type: 'git' as const, |
| 54 | + message: 'Failed to load schema SDL.\n' + error.message, |
| 55 | + path, |
| 56 | + }, |
| 57 | + }; |
| 58 | + } |
| 59 | + throw error; |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +export function loadSchemaFromGitHistory(schemaPointer: string, commit: string) { |
| 64 | + const pathResult = parseSingleLocalFilePath(schemaPointer); |
| 65 | + if (pathResult.error) { |
| 66 | + return pathResult; |
| 67 | + } |
| 68 | + const fileResult = loadGitFile(commit, pathResult.path); |
| 69 | + return fileResult; |
| 70 | +} |
0 commit comments