(dbPath: string, projectRoot: string)
| 1740 | |
| 1741 | /** The include directories the compilation database at `dbPath` names; null when it can't be read. */ |
| 1742 | export function readCompileDbIncludeDirs(dbPath: string, projectRoot: string): string[] | null { |
| 1743 | try { |
| 1744 | const content = fs.readFileSync(dbPath, 'utf-8'); |
| 1745 | const entries = JSON.parse(content) as Array<{ |
| 1746 | directory: string; |
| 1747 | command?: string; |
| 1748 | arguments?: string[]; |
| 1749 | }>; |
| 1750 | if (!Array.isArray(entries)) return null; |
| 1751 | |
| 1752 | const dirSet = new Set<string>(); |
| 1753 | for (const entry of entries) { |
| 1754 | const dir = entry.directory || projectRoot; |
| 1755 | const args = entry.arguments || (entry.command ? shlexSplit(entry.command) : []); |
| 1756 | for (let i = 0; i < args.length; i++) { |
| 1757 | const arg = args[i]!; |
| 1758 | let includeDir: string | undefined; |
| 1759 | // -I<dir> (no space) |
| 1760 | if (arg.startsWith('-I') && arg.length > 2) { |
| 1761 | includeDir = arg.substring(2); |
| 1762 | } |
| 1763 | // -isystem <dir> (space-separated) |
| 1764 | else if ((arg === '-isystem' || arg === '-I') && i + 1 < args.length) { |
| 1765 | includeDir = args[i + 1]; |
| 1766 | i++; // skip next arg |
| 1767 | } |
| 1768 | if (includeDir) { |
| 1769 | // Normalize: resolve relative to the compilation directory |
| 1770 | const absPath = path.isAbsolute(includeDir) |
| 1771 | ? includeDir |
| 1772 | : path.resolve(dir, includeDir); |
| 1773 | const relPath = path.relative(projectRoot, absPath).replace(/\\/g, '/'); |
| 1774 | // Skip system directories and paths outside the project |
| 1775 | // (relative paths starting with .. or absolute paths like |
| 1776 | // /usr/include or C:\usr on Windows) |
| 1777 | if (!relPath.startsWith('..') && relPath.length > 0 && !path.isAbsolute(relPath)) { |
| 1778 | dirSet.add(relPath); |
| 1779 | } |
| 1780 | } |
| 1781 | } |
| 1782 | } |
| 1783 | return Array.from(dirSet); |
| 1784 | } catch { |
| 1785 | return null; |
| 1786 | } |
| 1787 | } |
| 1788 | |
| 1789 | /** |
| 1790 | * Minimal shlex-style split for compiler command strings. |
no test coverage detected