|
1 | | -// ast-grep CLI path (homebrew installed) |
2 | | -export const SG_CLI_PATH = "sg" |
| 1 | +import { createRequire } from "module" |
| 2 | +import { dirname, join } from "path" |
| 3 | +import { existsSync } from "fs" |
| 4 | + |
| 5 | +type Platform = "darwin" | "linux" | "win32" | "unsupported" |
| 6 | + |
| 7 | +function getPlatformPackageName(): string | null { |
| 8 | + const platform = process.platform as Platform |
| 9 | + const arch = process.arch |
| 10 | + |
| 11 | + const platformMap: Record<string, string> = { |
| 12 | + "darwin-arm64": "@ast-grep/cli-darwin-arm64", |
| 13 | + "darwin-x64": "@ast-grep/cli-darwin-x64", |
| 14 | + "linux-arm64": "@ast-grep/cli-linux-arm64-gnu", |
| 15 | + "linux-x64": "@ast-grep/cli-linux-x64-gnu", |
| 16 | + "win32-x64": "@ast-grep/cli-win32-x64-msvc", |
| 17 | + "win32-arm64": "@ast-grep/cli-win32-arm64-msvc", |
| 18 | + "win32-ia32": "@ast-grep/cli-win32-ia32-msvc", |
| 19 | + } |
| 20 | + |
| 21 | + return platformMap[`${platform}-${arch}`] ?? null |
| 22 | +} |
| 23 | + |
| 24 | +function findSgCliPath(): string { |
| 25 | + // 1. Try to find from @ast-grep/cli package (installed via npm) |
| 26 | + try { |
| 27 | + const require = createRequire(import.meta.url) |
| 28 | + const cliPkgPath = require.resolve("@ast-grep/cli/package.json") |
| 29 | + const cliDir = dirname(cliPkgPath) |
| 30 | + const sgPath = join(cliDir, process.platform === "win32" ? "sg.exe" : "sg") |
| 31 | + |
| 32 | + if (existsSync(sgPath)) { |
| 33 | + return sgPath |
| 34 | + } |
| 35 | + } catch { |
| 36 | + // @ast-grep/cli not installed, try platform-specific package |
| 37 | + } |
| 38 | + |
| 39 | + // 2. Try platform-specific package directly |
| 40 | + const platformPkg = getPlatformPackageName() |
| 41 | + if (platformPkg) { |
| 42 | + try { |
| 43 | + const require = createRequire(import.meta.url) |
| 44 | + const pkgPath = require.resolve(`${platformPkg}/package.json`) |
| 45 | + const pkgDir = dirname(pkgPath) |
| 46 | + const binaryName = process.platform === "win32" ? "ast-grep.exe" : "ast-grep" |
| 47 | + const binaryPath = join(pkgDir, binaryName) |
| 48 | + |
| 49 | + if (existsSync(binaryPath)) { |
| 50 | + return binaryPath |
| 51 | + } |
| 52 | + } catch { |
| 53 | + // Platform-specific package not installed |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + // 3. Fallback to system PATH |
| 58 | + return "sg" |
| 59 | +} |
| 60 | + |
| 61 | +// ast-grep CLI path (auto-detected from node_modules or system PATH) |
| 62 | +export const SG_CLI_PATH = findSgCliPath() |
3 | 63 |
|
4 | 64 | // CLI supported languages (25 total) |
5 | 65 | export const CLI_LANGUAGES = [ |
|
0 commit comments