Chahuadev-smart-roadmap / src /analyzers /git-context-analyzer.js
chahuadev's picture
Upload 74 files
4fea3ee verified
/**
* Git Context Analyzer
* Zero-dependency Git integration using child_process
*
* Extracts business context and history from Git:
* - Task age from git blame
* - Commit messages and types (feat:, fix:, BREAKING CHANGE:)
* - Author information
* - Change frequency
*/
const { execSync } = require('child_process');
const path = require('path');
class GitContextAnalyzer {
constructor(projectRoot) {
this.projectRoot = projectRoot;
this.isGitRepo = this.checkGitRepository();
}
/**
* Check if project is a Git repository
*/
checkGitRepository() {
try {
execSync('git rev-parse --git-dir', {
cwd: this.projectRoot,
stdio: 'ignore'
});
return true;
} catch (error) {
return false;
}
}
/**
* Get blame information for specific line
* Returns actual date when TODO/FIXME was written
*/
getBlameForLine(filePath, lineNumber) {
if (!this.isGitRepo) return null;
try {
const relativePath = path.relative(this.projectRoot, filePath);
const output = execSync(
`git blame -L ${lineNumber},${lineNumber} --porcelain "${relativePath}"`,
{
cwd: this.projectRoot,
encoding: 'utf8',
timeout: 5000
}
);
return this.parseBlameOutput(output);
} catch (error) {
return null;
}
}
/**
* Parse git blame porcelain output
*/
parseBlameOutput(output) {
const lines = output.split('\n');
const result = {
commit: null,
author: null,
authorMail: null,
authorTime: null,
authorTz: null,
committer: null,
committerTime: null,
summary: null,
filename: null
};
for (const line of lines) {
if (line.startsWith('author ')) {
result.author = line.substring(7).trim();
} else if (line.startsWith('author-mail ')) {
result.authorMail = line.substring(12).trim().replace(/[<>]/g, '');
} else if (line.startsWith('author-time ')) {
const timestamp = parseInt(line.substring(12).trim());
result.authorTime = new Date(timestamp * 1000);
} else if (line.startsWith('author-tz ')) {
result.authorTz = line.substring(10).trim();
} else if (line.startsWith('committer ')) {
result.committer = line.substring(10).trim();
} else if (line.startsWith('committer-time ')) {
const timestamp = parseInt(line.substring(15).trim());
result.committerTime = new Date(timestamp * 1000);
} else if (line.startsWith('summary ')) {
result.summary = line.substring(8).trim();
} else if (line.startsWith('filename ')) {
result.filename = line.substring(9).trim();
} else if (/^[0-9a-f]{40}/.test(line)) {
result.commit = line.split(' ')[0];
}
}
return result;
}
/**
* Get commit history for file
*/
getFileHistory(filePath, limit = 50) {
if (!this.isGitRepo) return [];
try {
const relativePath = path.relative(this.projectRoot, filePath);
const output = execSync(
`git log --pretty=format:"%H|%an|%ae|%at|%s" -n ${limit} -- "${relativePath}"`,
{
cwd: this.projectRoot,
encoding: 'utf8',
timeout: 10000
}
);
return this.parseLogOutput(output);
} catch (error) {
return [];
}
}
/**
* Parse git log output
*/
parseLogOutput(output) {
if (!output) return [];
const lines = output.split('\n');
const commits = [];
for (const line of lines) {
if (!line) continue;
const [hash, author, email, timestamp, ...messageParts] = line.split('|');
const message = messageParts.join('|');
commits.push({
hash,
author,
email,
date: new Date(parseInt(timestamp) * 1000),
message,
type: this.detectCommitType(message),
isBreaking: this.isBreakingChange(message)
});
}
return commits;
}
/**
* Detect commit type from Conventional Commits
*/
detectCommitType(message) {
const lowerMessage = message.toLowerCase();
if (lowerMessage.startsWith('feat:') || lowerMessage.startsWith('feat(')) {
return 'feat';
} else if (lowerMessage.startsWith('fix:') || lowerMessage.startsWith('fix(')) {
return 'fix';
} else if (lowerMessage.startsWith('docs:') || lowerMessage.startsWith('docs(')) {
return 'docs';
} else if (lowerMessage.startsWith('style:') || lowerMessage.startsWith('style(')) {
return 'style';
} else if (lowerMessage.startsWith('refactor:') || lowerMessage.startsWith('refactor(')) {
return 'refactor';
} else if (lowerMessage.startsWith('perf:') || lowerMessage.startsWith('perf(')) {
return 'perf';
} else if (lowerMessage.startsWith('test:') || lowerMessage.startsWith('test(')) {
return 'test';
} else if (lowerMessage.startsWith('build:') || lowerMessage.startsWith('build(')) {
return 'build';
} else if (lowerMessage.startsWith('ci:') || lowerMessage.startsWith('ci(')) {
return 'ci';
} else if (lowerMessage.startsWith('chore:') || lowerMessage.startsWith('chore(')) {
return 'chore';
}
return 'other';
}
/**
* Check if commit is breaking change
*/
isBreakingChange(message) {
return message.toUpperCase().includes('BREAKING CHANGE:') ||
message.toUpperCase().includes('BREAKING-CHANGE:') ||
message.includes('!:');
}
/**
* Calculate actual age of annotation (TODO/FIXME)
*/
getAnnotationAge(filePath, lineNumber) {
const blame = this.getBlameForLine(filePath, lineNumber);
if (!blame || !blame.authorTime) return null;
const now = new Date();
const ageMs = now - blame.authorTime;
const ageDays = Math.floor(ageMs / (1000 * 60 * 60 * 24));
return {
days: ageDays,
author: blame.author,
authorMail: blame.authorMail,
date: blame.authorTime,
commit: blame.commit,
summary: blame.summary
};
}
/**
* Get change frequency for file (how often it's modified)
*/
getChangeFrequency(filePath) {
const history = this.getFileHistory(filePath);
if (history.length === 0) return null;
const firstCommit = history[history.length - 1].date;
const lastCommit = history[0].date;
const ageMs = lastCommit - firstCommit;
const ageDays = Math.max(1, ageMs / (1000 * 60 * 60 * 24));
return {
totalCommits: history.length,
changesPerWeek: (history.length / ageDays) * 7,
firstCommit,
lastCommit,
ageDays: Math.floor(ageDays),
isActive: ageDays < 90 // Active if modified in last 3 months
};
}
/**
* Enrich task with Git context
*/
enrichTask(task) {
if (!this.isGitRepo || !task.filePath || !task.line) {
return task;
}
const fullPath = path.join(this.projectRoot, task.filePath);
// Get annotation age
const age = this.getAnnotationAge(fullPath, task.line);
if (age) {
task.actualAge = age.days;
task.author = age.author;
task.authorMail = age.authorMail;
task.createdDate = age.date;
task.createdCommit = age.commit;
}
// Get file history
const frequency = this.getChangeFrequency(fullPath);
if (frequency) {
task.fileCommits = frequency.totalCommits;
task.fileChangesPerWeek = frequency.changesPerWeek;
task.fileIsActive = frequency.isActive;
task.fileAgeDays = frequency.ageDays;
}
// Get recent commits for context
const history = this.getFileHistory(fullPath, 10);
if (history.length > 0) {
task.recentCommits = history.slice(0, 5).map(c => ({
message: c.message,
type: c.type,
isBreaking: c.isBreaking,
author: c.author,
date: c.date
}));
// Check if file has breaking changes
task.hasBreakingChanges = history.some(c => c.isBreaking);
// Check if file is feature-heavy
const featureCommits = history.filter(c => c.type === 'feat').length;
task.isFeatureFile = featureCommits > history.length * 0.3;
}
return task;
}
/**
* Analyze entire project history
*/
analyzeProjectHistory() {
if (!this.isGitRepo) return null;
try {
// Get all commits
const output = execSync(
'git log --pretty=format:"%H|%an|%ae|%at|%s" --all',
{
cwd: this.projectRoot,
encoding: 'utf8',
timeout: 30000,
maxBuffer: 10 * 1024 * 1024 // 10MB buffer
}
);
const commits = this.parseLogOutput(output);
// Statistics
const typeCount = {};
let breakingChanges = 0;
const authors = new Set();
for (const commit of commits) {
typeCount[commit.type] = (typeCount[commit.type] || 0) + 1;
if (commit.isBreaking) breakingChanges++;
authors.add(commit.author);
}
return {
totalCommits: commits.length,
totalAuthors: authors.size,
breakingChanges,
typeDistribution: typeCount,
firstCommit: commits[commits.length - 1]?.date,
lastCommit: commits[0]?.date,
commits: commits.slice(0, 100) // Keep last 100
};
} catch (error) {
return null;
}
}
/**
* Get contributors statistics
*/
getContributors() {
if (!this.isGitRepo) return [];
try {
const output = execSync(
'git shortlog -sn --all --no-merges',
{
cwd: this.projectRoot,
encoding: 'utf8',
timeout: 10000
}
);
const lines = output.trim().split('\n');
return lines.map(line => {
const match = line.trim().match(/^(\d+)\s+(.+)$/);
if (match) {
return {
commits: parseInt(match[1]),
name: match[2]
};
}
return null;
}).filter(Boolean);
} catch (error) {
return [];
}
}
}
module.exports = GitContextAnalyzer;