(workspaceRoot: string)
| 18 | * @returns Git repository information or empty object if not a git repository |
| 19 | */ |
| 20 | export async function getGitRepositoryInfo(workspaceRoot: string): Promise<GitRepositoryInfo> { |
| 21 | try { |
| 22 | const gitDir = path.join(workspaceRoot, ".git") |
| 23 | |
| 24 | // Check if .git directory exists |
| 25 | try { |
| 26 | await fs.access(gitDir) |
| 27 | } catch { |
| 28 | // Not a git repository |
| 29 | return {} |
| 30 | } |
| 31 | |
| 32 | const gitInfo: GitRepositoryInfo = {} |
| 33 | |
| 34 | // Try to read git config file |
| 35 | try { |
| 36 | const configPath = path.join(gitDir, "config") |
| 37 | const configContent = await fs.readFile(configPath, "utf8") |
| 38 | |
| 39 | // Very simple approach - just find any URL line |
| 40 | const urlMatch = configContent.match(/url\s*=\s*(.+?)(?:\r?\n|$)/m) |
| 41 | |
| 42 | if (urlMatch && urlMatch[1]) { |
| 43 | const url = urlMatch[1].trim() |
| 44 | // Sanitize the URL and convert to HTTPS format for telemetry |
| 45 | gitInfo.repositoryUrl = convertGitUrlToHttps(sanitizeGitUrl(url)) |
| 46 | const repositoryName = extractRepositoryName(url) |
| 47 | if (repositoryName) { |
| 48 | gitInfo.repositoryName = repositoryName |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | // Extract default branch (if available) |
| 53 | const branchMatch = configContent.match(/\[branch "([^"]+)"\]/i) |
| 54 | if (branchMatch && branchMatch[1]) { |
| 55 | gitInfo.defaultBranch = branchMatch[1] |
| 56 | } |
| 57 | } catch (error) { |
| 58 | // Ignore config reading errors |
| 59 | } |
| 60 | |
| 61 | // Try to read HEAD file to get current branch |
| 62 | if (!gitInfo.defaultBranch) { |
| 63 | try { |
| 64 | const headPath = path.join(gitDir, "HEAD") |
| 65 | const headContent = await fs.readFile(headPath, "utf8") |
| 66 | const branchMatch = headContent.match(/ref: refs\/heads\/(.+)/) |
| 67 | if (branchMatch && branchMatch[1]) { |
| 68 | gitInfo.defaultBranch = branchMatch[1].trim() |
| 69 | } |
| 70 | } catch (error) { |
| 71 | // Ignore HEAD reading errors |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | return gitInfo |
| 76 | } catch (error) { |
| 77 | // Return empty object on any error |
no test coverage detected