diff --git a/apps/mobile/package.json b/apps/mobile/package.json index b40a72211..934242515 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -6,6 +6,7 @@ "scripts": { "android": "expo run:android", "bump": "vv", + "changelog:generate": "tsx ../../packages/changelog-cli/index.ts", "dev": "npm run start", "eas-build-post-install": "rm -rf $TMPDIR/metro-cache", "eas-build-pre-install": "command -v pod >/dev/null 2>&1 && pod repo update || echo 'CocoaPods not found, skipping pod repo update'", diff --git a/apps/mobile/scripts/changelog-cli/config.json b/apps/mobile/scripts/changelog-cli/config.json new file mode 100644 index 000000000..57c8fea5d --- /dev/null +++ b/apps/mobile/scripts/changelog-cli/config.json @@ -0,0 +1,54 @@ +{ + "internalTeamMembers": [ + "Innei", + "DIYgod", + "hyoban", + "renovate[bot]", + "github-actions[bot]", + "dependabot[bot]", + "vercel[bot]", + "whitewater" + ], + "aiModel": { + "provider": "openai", + "model": "gpt-4o-mini", + "temperature": 0.3, + "maxTokens": 1000, + "apiKey": "", + "baseURL": "https://openrouter.ai/v1", + "customEndpoint": "" + }, + "commitAnalysis": { + "categories": { + "features": { + "keywords": ["feat", "feature", "add", "implement", "introduce"], + "section": "Shiny new things" + }, + "improvements": { + "keywords": ["improve", "enhance", "optimize", "refactor", "update", "perf"], + "section": "Improvements" + }, + "fixes": { + "keywords": ["fix", "bug", "patch", "resolve", "correct"], + "section": "No longer broken" + } + }, + "ignorePatterns": [ + "^chore:", + "^docs:", + "^test:", + "^ci:", + "^build:", + "Merge pull request", + "Merge branch", + "version bump", + "changelog", + "Update dependencies" + ] + }, + "changelog": { + "maxCommitsPerSection": 5, + "includeCommitHash": true, + "includePullRequestLinks": true + } +} diff --git a/packages/changelog-cli/README.md b/packages/changelog-cli/README.md new file mode 100644 index 000000000..24e2257e4 --- /dev/null +++ b/packages/changelog-cli/README.md @@ -0,0 +1,186 @@ +# @follow/changelog-cli + +AI-driven changelog generator for the Follow project. This package automatically analyzes git commits and generates user-friendly changelog entries using configurable AI models. + +## Features + +- šŸ¤– **AI-Powered Analysis**: Uses OpenAI GPT models to analyze commit messages +- šŸ“Š **Smart Categorization**: Automatically categorizes changes into sections +- šŸ‘„ **Contributor Recognition**: Identifies and thanks external contributors +- šŸ”§ **Configurable**: Supports custom AI endpoints and models +- šŸ”„ **Fallback Support**: Falls back to keyword-based analysis if AI is unavailable + +## Installation + +This package is part of the Follow monorepo and is not published to npm. It's designed to be used within the monorepo environment. + +## Usage + +### As a Workspace Script + +From the mobile app directory: + +```bash +npm run changelog:generate +``` + +### Direct Execution + +From the package directory: + +```bash +pnpm run generate +``` + +### CLI Command (after building) + +```bash +pnpm run build +./bin/cli.js +``` + +## Configuration + +Create or modify `config.json` in the package root: + +```json +{ + "internalTeamMembers": [ + "innei", + "DIYgod", + "hyoban", + "renovate[bot]", + "github-actions[bot]", + "dependabot[bot]", + "vercel[bot]" + ], + "aiModel": { + "provider": "openai", + "model": "gpt-4o-mini", + "temperature": 0.3, + "maxTokens": 1000, + "apiKey": "", + "baseURL": "https://api.openai.com/v1", + "customEndpoint": "" + }, + "commitAnalysis": { + "categories": { + "features": { + "keywords": ["feat", "feature", "add", "implement", "introduce"], + "section": "Shiny new things" + }, + "improvements": { + "keywords": ["improve", "enhance", "optimize", "refactor", "update", "perf"], + "section": "Improvements" + }, + "fixes": { + "keywords": ["fix", "bug", "patch", "resolve", "correct"], + "section": "No longer broken" + } + }, + "ignorePatterns": [ + "^chore:", + "^docs:", + "^test:", + "^ci:", + "^build:", + "Merge pull request", + "Merge branch", + "version bump", + "changelog", + "Update dependencies" + ] + }, + "changelog": { + "maxCommitsPerSection": 5, + "includeCommitHash": true, + "includePullRequestLinks": true + } +} +``` + +## Custom OpenAI Endpoints + +The tool supports custom OpenAI-compatible endpoints: + +### Environment Variables + +```bash +export OPENAI_API_KEY="your-api-key" +export OPENAI_BASE_URL="https://your-custom-endpoint.com/v1" +``` + +### Configuration File + +```json +{ + "aiModel": { + "apiKey": "your-api-key", + "customEndpoint": "https://your-custom-endpoint.com/v1" + } +} +``` + +### Supported Providers + +- OpenAI API +- Azure OpenAI +- Any OpenAI-compatible API (e.g., Claude via proxy, local models) + +## Requirements + +- Node.js >= 18.0.0 +- Git repository with proper tag structure (`mobile@x.y.z`) +- Must be run on a release branch (`release/mobile/*`) + +## How It Works + +1. **Branch Validation**: Ensures execution on a release branch +2. **Git Analysis**: Finds commits between latest mobile tag and current HEAD +3. **Commit Filtering**: Removes noise commits (merges, version bumps, etc.) +4. **AI Analysis**: Sends filtered commits to AI for categorization +5. **Contributor Detection**: Identifies external contributors from commit authors +6. **Changelog Generation**: Formats and writes changelog to target file + +## Files Structure + +- `index.ts` - Main entry point and orchestration logic +- `git-tools.ts` - Git command execution and analysis +- `ai-agent.ts` - AI-powered commit analysis and categorization +- `openai-client.ts` - OpenAI API client with custom endpoint support +- `config.json` - Configuration file +- `bin/cli.js` - CLI executable wrapper + +## Development + +```bash +# Install dependencies +pnpm install + +# Run in development mode +pnpm run dev + +# Type checking +pnpm run typecheck + +# Build for production +pnpm run build +``` + +## Integration + +This package is designed to integrate with the existing release workflow in the Follow monorepo. It can be called from other apps' package.json scripts or integrated into the bump configuration. + +Example integration in mobile app's `package.json`: + +```json +{ + "scripts": { + "changelog:generate": "tsx ../packages/changelog-cli/index.ts" + } +} +``` + +## License + +This package is part of the Follow project and follows the same license terms. diff --git a/packages/changelog-cli/USAGE.md b/packages/changelog-cli/USAGE.md new file mode 100644 index 000000000..248cd3271 --- /dev/null +++ b/packages/changelog-cli/USAGE.md @@ -0,0 +1,331 @@ +# Usage Examples + +This document provides practical examples of how to use the `@follow/changelog-cli` package in different scenarios. + +## Basic Usage + +### 1. Generate Changelog for Current Release + +Make sure you're on a release branch (e.g., `release/mobile/0.2.5`): + +```bash +# From mobile app directory +cd apps/mobile +npm run changelog:generate + +# Or from the package directory +cd packages/changelog-cli +pnpm run generate +``` + +### 2. Using with Custom OpenAI Endpoint + +If you're using a custom OpenAI-compatible endpoint (like Azure OpenAI or a local model): + +```bash +# Set environment variables +export OPENAI_API_KEY="your-api-key" +export OPENAI_BASE_URL="https://your-endpoint.openai.azure.com/v1" + +# Run the generator +npm run changelog:generate +``` + +### 3. Configuration for Different AI Providers + +#### Azure OpenAI + +```json +{ + "aiModel": { + "provider": "openai", + "model": "gpt-4", + "apiKey": "your-azure-key", + "customEndpoint": "https://your-resource.openai.azure.com/openai/deployments/gpt-4/chat/completions?api-version=2024-02-15-preview" + } +} +``` + +#### Local Model (Ollama) + +```json +{ + "aiModel": { + "provider": "openai", + "model": "llama2", + "apiKey": "not-needed", + "customEndpoint": "http://localhost:11434/v1" + } +} +``` + +#### Claude via Proxy + +```json +{ + "aiModel": { + "provider": "openai", + "model": "claude-3-sonnet-20240229", + "apiKey": "your-anthropic-key", + "customEndpoint": "https://api.anthropic.com/v1" + } +} +``` + +## Integration Examples + +### 1. Auto-generate during Release Process + +Add to `apps/mobile/bump.config.ts`: + +```typescript +export default defineConfig({ + leading: [ + "git pull --rebase", + "npm run changelog:generate", // Add this line + "tsx scripts/apply-changelog.ts ${NEW_VERSION}", + "git add changelog", + // ... rest of config + ], + // ... +}) +``` + +### 2. CI/CD Integration + +Example GitHub Actions workflow: + +```yaml +name: Generate Changelog +on: + push: + branches: + - "release/mobile/*" + +jobs: + changelog: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # Important: fetch full history + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: "18" + cache: "pnpm" + + - name: Install dependencies + run: pnpm install + + - name: Generate changelog + env: + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + run: | + cd apps/mobile + npm run changelog:generate + + - name: Commit changelog + run: | + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + git add apps/mobile/changelog/next.md + git commit -m "chore: auto-generate changelog" || exit 0 + git push +``` + +### 3. Custom Script Integration + +Create a custom script that uses the changelog CLI: + +```typescript +// scripts/release-workflow.ts +import { execSync } from "node:child_process" + +async function releaseWorkflow() { + console.log("šŸš€ Starting release workflow...") + + // 1. Generate changelog + console.log("šŸ“ Generating changelog...") + execSync("npm run changelog:generate", { + cwd: "apps/mobile", + stdio: "inherit", + }) + + // 2. Review and edit if needed + console.log("šŸ“‹ Changelog generated. Please review before continuing.") + + // 3. Continue with release process... +} + +releaseWorkflow() +``` + +## Configuration Examples + +### 1. Team-specific Configuration + +For different teams with different internal members: + +```json +{ + "internalTeamMembers": [ + "innei", + "DIYgod", + "hyoban", + "team-lead-1", + "team-lead-2", + "renovate[bot]", + "dependabot[bot]" + ] +} +``` + +### 2. Project-specific Keywords + +Customize keywords for different types of projects: + +```json +{ + "commitAnalysis": { + "categories": { + "features": { + "keywords": ["feat", "feature", "add", "implement", "new"], + "section": "šŸŽ‰ New Features" + }, + "improvements": { + "keywords": ["improve", "enhance", "optimize", "perf", "refactor"], + "section": "⚔ Improvements" + }, + "fixes": { + "keywords": ["fix", "bug", "patch", "resolve", "hotfix"], + "section": "šŸ› Bug Fixes" + } + } + } +} +``` + +### 3. Strict Filtering + +For projects with very specific changelog requirements: + +```json +{ + "commitAnalysis": { + "ignorePatterns": [ + "^chore:", + "^docs:", + "^test:", + "^ci:", + "^build:", + "^style:", + "^refactor:", + "Merge pull request", + "Merge branch", + "version bump", + "changelog", + "Update dependencies", + "^deps:", + "^devDeps:" + ] + }, + "changelog": { + "maxCommitsPerSection": 3, + "includeCommitHash": false, + "includePullRequestLinks": true + } +} +``` + +## Troubleshooting Examples + +### 1. API Rate Limiting + +If you hit OpenAI API rate limits: + +```json +{ + "aiModel": { + "temperature": 0.1, + "maxTokens": 500 + } +} +``` + +Or process commits in smaller batches by modifying the batch size in `ai-agent.ts`. + +### 2. Custom Git Tag Format + +If your project uses a different tag format, modify `git-tools.ts`: + +```typescript +// In git-tools.ts, modify getLatestMobileTag() +getLatestMobileTag(): GitTag | null { + try { + // Change this line to match your tag format + const tags = this.exec('git tag --sort=-version:refname | grep "^v" | head -1') + // ... rest of the method + } +} +``` + +### 3. Working with Monorepos + +For complex monorepo setups, you might need to adjust the working directory: + +```typescript +// Create a custom git tools instance +const git = new GitTools("/path/to/your/specific/repo") +``` + +## Best Practices + +### 1. Review Before Committing + +Always review the generated changelog before committing: + +```bash +# Generate changelog +npm run changelog:generate + +# Review the changes +cat apps/mobile/changelog/next.md + +# Edit if necessary +vim apps/mobile/changelog/next.md + +# Commit when satisfied +git add apps/mobile/changelog/next.md +git commit -m "chore: update changelog" +``` + +### 2. Backup Configuration + +Keep your configuration in version control but sensitive data in environment variables: + +```json +{ + "aiModel": { + "apiKey": "", // Leave empty in version control + "customEndpoint": "" // Can be committed if not sensitive + } +} +``` + +### 3. Testing Configuration + +Test your configuration with a small batch first: + +```json +{ + "changelog": { + "maxCommitsPerSection": 1, // Start small + "includeCommitHash": true, + "includePullRequestLinks": true + } +} +``` + +This way you can verify the output format before processing many commits. diff --git a/packages/changelog-cli/ai-agent.ts b/packages/changelog-cli/ai-agent.ts new file mode 100644 index 000000000..3f1750665 --- /dev/null +++ b/packages/changelog-cli/ai-agent.ts @@ -0,0 +1,250 @@ +import type { GitCommit } from "./git-tools" +import OpenAIClient from "./openai-client" + +export interface ChangelogEntry { + section: "Shiny new things" | "Improvements" | "No longer broken" + description: string + commitHash?: string + pullRequest?: string +} + +export interface AIConfig { + provider: string + model: string + temperature: number + maxTokens: number + apiKey?: string +} + +export interface CommitCategory { + keywords: string[] + section: "Shiny new things" | "Improvements" | "No longer broken" +} + +export class AIAgent { + private config: AIConfig + private categories: Record + private openaiClient: OpenAIClient + + constructor(config: AIConfig, categories: Record) { + this.config = config + this.categories = categories + this.openaiClient = new OpenAIClient(config) + } + + /** + * Analyze commits and generate changelog entries using AI + */ + async analyzeCommits(commits: GitCommit[]): Promise { + console.info(`Analyzing ${commits.length} commits with AI...`) + + const filteredCommits = this.filterImportantCommits(commits) + console.info(`Selected ${filteredCommits.length} important commits`) + + const changelogEntries: ChangelogEntry[] = [] + + // Process commits in batches to avoid API limits + const batchSize = 10 + for (let i = 0; i < filteredCommits.length; i += batchSize) { + const batch = filteredCommits.slice(i, i + batchSize) + const batchEntries = await this.processBatch(batch) + changelogEntries.push(...batchEntries) + } + + return changelogEntries + } + + /** + * Filter commits to identify important ones + */ + private filterImportantCommits(commits: GitCommit[]): GitCommit[] { + return commits.filter((commit) => { + const message = `${commit.subject} ${commit.body}`.toLowerCase() + + // Skip ignored patterns + const shouldIgnore = [ + /^chore:/, + /^docs:/, + /^test:/, + /^ci:/, + /^build:/, + /merge pull request/, + /merge branch/, + /version bump/, + /changelog/, + /update dependencies/, + /^\d+\.\d+\.\d+/, // version numbers + /^bump /, + /^release\(/, + ].some((pattern) => pattern.test(message)) + + if (shouldIgnore) return false + + // Include commits with significant changes + const hasSignificantChange = [ + /\bfeat\b/, + /\bfeature\b/, + /\badd\b/, + /\bimplement\b/, + /\bintroduce\b/, + /\bfix\b/, + /\bbug\b/, + /\bpatch\b/, + /\bresolve\b/, + /\bcorrect\b/, + /\bimprove\b/, + /\benhance\b/, + /\boptimize\b/, + /\brefactor\b/, + /\bupdate\b/, + /\bperf\b/, + /\bbreaking\b/, + /\bmajor\b/, + /\bminor\b/, + /\bui\b/, + /\bux\b/, + /\bdesign\b/, + ].some((pattern) => pattern.test(message)) + + return hasSignificantChange || commit.pullRequest + }) + } + + /** + * Process a batch of commits using AI + */ + private async processBatch(commits: GitCommit[]): Promise { + const prompt = this.buildAnalysisPrompt(commits) + + try { + const aiResponse = await this.callAI(prompt) + return this.parseAIResponse(aiResponse, commits) + } catch (error) { + console.warn("AI analysis failed, falling back to keyword-based categorization:", error) + return this.fallbackCategorization(commits) + } + } + + /** + * Build the analysis prompt for AI + */ + private buildAnalysisPrompt(commits: GitCommit[]): string { + const commitsText = commits + .map( + (commit, index) => + `${index + 1}. [${commit.shortHash}] ${commit.subject}\n ${commit.body || "No description"}\n ${commit.pullRequest ? `PR #${commit.pullRequest}` : ""}`, + ) + .join("\n\n") + + return `You are a technical writer creating a changelog for a React Native RSS reader app called "Follow". + +Analyze these git commits and categorize the most important user-facing changes into these sections: + +**Shiny new things**: New features, major additions that users can see/use +**Improvements**: Enhancements, optimizations, better UX/UI, performance improvements +**No longer broken**: Bug fixes, crash fixes, issues resolved + +For each relevant commit, provide: +1. A user-friendly description (not technical jargon) +2. Which section it belongs to +3. Reference the commit hash or PR number if significant + +Focus on changes that impact the user experience. Skip internal refactoring, dependency updates, or development-only changes unless they significantly affect users. + +Commits to analyze: +${commitsText} + +Respond in this JSON format: +{ + "entries": [ + { + "section": "Shiny new things", + "description": "User-friendly description of what changed", + "commitHash": "abc123", + "pullRequest": "1234" + } + ] +} + +Only include meaningful user-facing changes. Be selective and focus on quality over quantity.` + } + + /** + * Call AI API (mock implementation - you need to implement the actual API call) + */ + private async callAI(prompt: string): Promise { + // This is a mock implementation. You need to implement the actual AI API call + // based on your chosen provider (OpenAI, Anthropic, etc.) + + if (this.config.provider === "openai") { + return this.callOpenAI(prompt) + } + + throw new Error(`AI provider "${this.config.provider}" not implemented`) + } + + /** + * OpenAI API call implementation + */ + private async callOpenAI(prompt: string): Promise { + if (!this.openaiClient.isAvailable()) { + throw new Error("OpenAI API not available") + } + + console.info("šŸ¤– Calling OpenAI API...") + return await this.openaiClient.chat(prompt) + } + + /** + * Parse AI response into changelog entries + */ + private parseAIResponse(response: string, commits: GitCommit[]): ChangelogEntry[] { + try { + const parsed = JSON.parse(response) + return parsed.entries || [] + } catch { + console.warn("Failed to parse AI response, using fallback") + return this.fallbackCategorization(commits) + } + } + + /** + * Fallback categorization using keywords when AI fails + */ + private fallbackCategorization(commits: GitCommit[]): ChangelogEntry[] { + return commits.map((commit) => { + const message = `${commit.subject} ${commit.body}`.toLowerCase() + + // Determine category based on keywords + let section: ChangelogEntry["section"] = "Improvements" + + if (this.categories.features?.keywords.some((keyword) => message.includes(keyword))) { + section = "Shiny new things" + } else if (this.categories.fixes?.keywords.some((keyword) => message.includes(keyword))) { + section = "No longer broken" + } + + // Clean up the description + let description = commit.subject + if ( + description.startsWith("feat:") || + description.startsWith("fix:") || + description.startsWith("chore:") + ) { + description = description.slice(Math.max(0, description.indexOf(":") + 1)).trim() + } + + // Capitalize first letter + description = description.charAt(0).toUpperCase() + description.slice(1) + + return { + section, + description, + commitHash: commit.shortHash, + pullRequest: commit.pullRequest, + } + }) + } +} + +export default AIAgent diff --git a/packages/changelog-cli/bin/cli.js b/packages/changelog-cli/bin/cli.js new file mode 100644 index 000000000..ea3a32dbe --- /dev/null +++ b/packages/changelog-cli/bin/cli.js @@ -0,0 +1,18 @@ +#!/usr/bin/env node + +import { execSync } from "node:child_process" +import { fileURLToPath } from "node:url" + +import { dirname, join } from "pathe" + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const indexPath = join(__dirname, "..", "index.ts") + +try { + execSync(`tsx "${indexPath}"`, { + stdio: "inherit", + cwd: process.cwd(), + }) +} catch (error) { + process.exit(error.status || 1) +} diff --git a/packages/changelog-cli/config.json b/packages/changelog-cli/config.json new file mode 100644 index 000000000..35744beaf --- /dev/null +++ b/packages/changelog-cli/config.json @@ -0,0 +1,54 @@ +{ + "internalTeamMembers": [ + "Innei", + "DIYgod", + "hyoban", + "renovate[bot]", + "github-actions[bot]", + "dependabot[bot]", + "vercel[bot]", + "whitewater" + ], + "aiModel": { + "provider": "openai", + "model": "gpt-4o-mini", + "temperature": 0.3, + "maxTokens": 1000, + "apiKey": "", + "baseURL": "https://api.openai.com/v1", + "customEndpoint": "" + }, + "commitAnalysis": { + "categories": { + "features": { + "keywords": ["feat", "feature", "add", "implement", "introduce"], + "section": "Shiny new things" + }, + "improvements": { + "keywords": ["improve", "enhance", "optimize", "refactor", "update", "perf"], + "section": "Improvements" + }, + "fixes": { + "keywords": ["fix", "bug", "patch", "resolve", "correct"], + "section": "No longer broken" + } + }, + "ignorePatterns": [ + "^chore:", + "^docs:", + "^test:", + "^ci:", + "^build:", + "Merge pull request", + "Merge branch", + "version bump", + "changelog", + "Update dependencies" + ] + }, + "changelog": { + "maxCommitsPerSection": 5, + "includeCommitHash": true, + "includePullRequestLinks": true + } +} diff --git a/packages/changelog-cli/git-tools.ts b/packages/changelog-cli/git-tools.ts new file mode 100644 index 000000000..2d60efef8 --- /dev/null +++ b/packages/changelog-cli/git-tools.ts @@ -0,0 +1,179 @@ +import { execSync } from "node:child_process" +import { fileURLToPath } from "node:url" + +import { dirname, join } from "pathe" + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const projectRoot = join(__dirname, "..", "..") + +export interface GitCommit { + hash: string + shortHash: string + subject: string + body: string + author: string + email: string + date: string + pullRequest?: string +} + +export interface GitTag { + name: string + hash: string + date: string +} + +export class GitTools { + private workingDir: string + + constructor(workingDir = projectRoot) { + this.workingDir = workingDir + } + + /** + * Execute git command and return output + */ + private exec(command: string): string { + try { + return execSync(command, { + cwd: this.workingDir, + encoding: "utf-8", + }).trim() + } catch (error) { + console.error(`Git command failed: ${command}`) + throw error + } + } + + /** + * Get the latest tag for mobile releases + */ + getLatestMobileTag(): GitTag | null { + try { + const tags = this.exec('git tag --sort=-version:refname | grep "^mobile@" | head -1') + if (!tags) return null + + const tagName = tags.trim() + const hash = this.exec(`git rev-list -n 1 ${tagName}`) + const date = this.exec(`git log -1 --format=%ai ${hash}`) + + return { + name: tagName, + hash, + date, + } + } catch { + return null + } + } + + /** + * Get current branch name + */ + getCurrentBranch(): string { + return this.exec("git rev-parse --abbrev-ref HEAD") + } + + /** + * Get the latest commit hash on current branch + */ + getLatestCommitHash(): string { + return this.exec("git rev-parse HEAD") + } + + /** + * Get commits between two references + */ + getCommitsBetween(fromRef: string, toRef: string): GitCommit[] { + const format = [ + "%H", // full hash + "%h", // short hash + "%s", // subject + "%b", // body + "%an", // author name + "%ae", // author email + "%ai", // author date + ].join("%x1f") // use ASCII unit separator + + const command = `git log --format="${format}%x1e" ${fromRef}..${toRef}` + const output = this.exec(command) + + if (!output) return [] + + return output + .split("\x1e") + .filter(Boolean) + .map((entry) => { + const parts = entry.split("\x1f") + const [hash, shortHash, subject, body, author, email, date] = parts + + // Ensure all required fields exist + if (!hash || !shortHash || !subject || !author || !email || !date) { + throw new Error("Invalid git log entry format") + } + + // Check if commit is related to a pull request + const pullRequest = this.extractPullRequestNumber(subject, body || "") + + return { + hash: hash.trim(), + shortHash: shortHash.trim(), + subject: subject.trim(), + body: (body || "").trim(), + author: author.trim(), + email: email.trim(), + date: date.trim(), + pullRequest, + } + }) + } + + /** + * Extract pull request number from commit message + */ + private extractPullRequestNumber(subject: string, body: string): string | undefined { + const text = `${subject} ${body}` + const prMatch = text.match(/#(\d+)/) + return prMatch ? prMatch[1] : undefined + } + + /** + * Get all unique authors from commits, excluding bots and internal members + */ + getUniqueAuthors(commits: GitCommit[], internalMembers: string[]): string[] { + const authors = new Set() + + commits.forEach((commit) => { + const author = commit.author.toLowerCase() + const isBotOrInternal = + author.includes("[bot]") || + author.includes("bot") || + internalMembers.some((member) => author.includes(member.toLowerCase())) + + if (!isBotOrInternal) { + authors.add(commit.author) + } + }) + + return Array.from(authors).sort() + } + + /** + * Check if we're on a release branch + */ + isOnReleaseBranch(): boolean { + const currentBranch = this.getCurrentBranch() + return currentBranch.startsWith("release/") + } + + /** + * Get the version from release branch name + */ + getVersionFromBranch(): string | null { + const currentBranch = this.getCurrentBranch() + const match = currentBranch.match(/release\/mobile\/(.+)/) + return match?.[1] ?? null + } +} + +export default GitTools diff --git a/packages/changelog-cli/index.ts b/packages/changelog-cli/index.ts new file mode 100644 index 000000000..d5ad7fb60 --- /dev/null +++ b/packages/changelog-cli/index.ts @@ -0,0 +1,224 @@ +#!/usr/bin/env tsx + +import "dotenv/config" + +import { readFileSync, writeFileSync } from "node:fs" +import { fileURLToPath } from "node:url" + +import { dirname, join } from "pathe" + +import type { ChangelogEntry } from "./ai-agent" +import AIAgent from "./ai-agent" +import GitTools from "./git-tools" + +// Get current directory +const __dirname = dirname(fileURLToPath(import.meta.url)) +const changelogDir = join(__dirname, "..", "..", "apps", "mobile", "changelog") +const configPath = join(__dirname, "config.json") + +interface Config { + internalTeamMembers: string[] + aiModel: { + provider: string + model: string + temperature: number + maxTokens: number + baseURL?: string + customEndpoint?: string + } + commitAnalysis: { + categories: Record< + string, + { + keywords: string[] + section: string + } + > + ignorePatterns: string[] + } + changelog: { + maxCommitsPerSection: number + includeCommitHash: boolean + includePullRequestLinks: boolean + } +} + +/** + * Load configuration from file + */ +function loadConfig(): Config { + try { + const configContent = readFileSync(configPath, "utf-8") + return JSON.parse(configContent) + } catch (error) { + console.error("Failed to load config file:", error) + process.exit(1) + } +} + +/** + * Format changelog entry for output + */ +function formatChangelogEntry(entry: ChangelogEntry, config: Config): string { + let line = `- ${entry.description}` + + if (config.changelog.includePullRequestLinks && entry.pullRequest) { + line += `(#${entry.pullRequest})` + } else if (config.changelog.includeCommitHash && entry.commitHash) { + line += `(${entry.commitHash})` + } + + return line +} + +/** + * Group changelog entries by section + */ +function groupEntriesBySection(entries: ChangelogEntry[]): Record { + const grouped: Record = { + "Shiny new things": [], + Improvements: [], + "No longer broken": [], + } + + entries.forEach((entry) => { + if (grouped[entry.section]) { + grouped[entry.section]!.push(entry) + } + }) + + return grouped +} + +/** + * Generate the changelog content + */ +function generateChangelogContent( + version: string, + entries: ChangelogEntry[], + contributors: string[], + config: Config, +): string { + const groupedEntries = groupEntriesBySection(entries) + + let content = `# What's New in v${version}\n\n` + + // Add sections with entries + Object.entries(groupedEntries).forEach(([section, sectionEntries]) => { + content += `## ${section}\n\n` + + if (sectionEntries.length > 0) { + // Limit entries per section + const limitedEntries = sectionEntries.slice(0, config.changelog.maxCommitsPerSection) + limitedEntries.forEach((entry) => { + content += `${formatChangelogEntry(entry, config)}\n` + }) + } + + content += "\n" + }) + + // Add contributors section + content += "## Thanks\n\n" + if (contributors.length > 0) { + const contributorList = contributors.map((name) => `@${name}`).join(" ") + content += `Special thanks to volunteer contributors ${contributorList} for their valuable contributions\n` + } else { + content += "Special thanks to volunteer contributors @ for their valuable contributions\n" + } + + return content +} + +/** + * Main function to generate changelog + */ +async function main() { + try { + console.info("šŸ¤– Starting AI-driven changelog generation...") + + // Load configuration + const config = loadConfig() + console.info("āœ… Configuration loaded") + + // Initialize Git tools + const git = new GitTools() + + // Check if we're on a release branch + if (!git.isOnReleaseBranch()) { + console.error("āŒ This script should only be run on a release branch (release/mobile/*)") + process.exit(1) + } + + // Get version from branch name + const version = git.getVersionFromBranch() + if (!version) { + console.error("āŒ Could not extract version from branch name") + process.exit(1) + } + + console.info(`šŸ“ Generating changelog for version: ${version}`) + + // Get the latest mobile tag + const latestTag = git.getLatestMobileTag() + if (!latestTag) { + console.error("āŒ No previous mobile tags found") + process.exit(1) + } + + console.info(`šŸ“Œ Latest tag: ${latestTag.name}`) + + // Get commits between latest tag and current HEAD + const currentCommit = git.getLatestCommitHash() + const commits = git.getCommitsBetween(latestTag.hash, currentCommit) + + console.info(`šŸ” Found ${commits.length} commits since last release`) + + if (commits.length === 0) { + console.warn("āš ļø No new commits found since last release") + return + } + + // Initialize AI agent + const aiAgent = new AIAgent(config.aiModel, config.commitAnalysis.categories as any) + + // Analyze commits with AI + const changelogEntries = await aiAgent.analyzeCommits(commits) + console.info(`✨ Generated ${changelogEntries.length} changelog entries`) + + // Get contributors + const contributors = git.getUniqueAuthors(commits, config.internalTeamMembers) + console.info(`šŸ‘„ Found ${contributors.length} external contributors`) + + // Generate changelog content + const changelogContent = generateChangelogContent( + version, + changelogEntries, + contributors, + config, + ) + + // Write to next.md + const nextFilePath = join(changelogDir, "next.md") + writeFileSync(nextFilePath, changelogContent, "utf-8") + + console.info("āœ… Changelog generated successfully!") + console.info(`šŸ“„ Updated: ${nextFilePath}`) + + // Show preview + console.info("\nšŸ“‹ Preview:") + console.info("─".repeat(50)) + console.info(changelogContent) + console.info("─".repeat(50)) + } catch (error) { + console.error("āŒ Failed to generate changelog:", error) + process.exit(1) + } +} + +// Run the script if called directly +if (import.meta.url === `file://${process.argv[1]}`) { + main() +} + +export default main diff --git a/packages/changelog-cli/openai-client.ts b/packages/changelog-cli/openai-client.ts new file mode 100644 index 000000000..5e26b43e5 --- /dev/null +++ b/packages/changelog-cli/openai-client.ts @@ -0,0 +1,84 @@ +export interface OpenAIConfig { + apiKey?: string + model: string + temperature: number + maxTokens: number + baseURL?: string + customEndpoint?: string +} + +export class OpenAIClient { + private config: OpenAIConfig + private apiKey: string + private baseURL: string + + constructor(config: OpenAIConfig) { + this.config = config + this.apiKey = config.apiKey || process.env.OPENAI_API_KEY || "" + + // Support custom endpoints + if (config.customEndpoint) { + this.baseURL = config.customEndpoint + } else if (config.baseURL) { + this.baseURL = config.baseURL + } else { + this.baseURL = process.env.OPENAI_BASE_URL || "https://api.openai.com/v1" + } + + if (!this.apiKey) { + console.warn("āš ļø No OpenAI API key provided. Using fallback analysis.") + } + + if (config.customEndpoint) { + console.info(`šŸ”— Using custom OpenAI endpoint: ${this.baseURL}`) + } + } + + async chat(prompt: string): Promise { + if (!this.apiKey) { + throw new Error("OpenAI API key not provided") + } + + try { + const response = await fetch(`${this.baseURL}/chat/completions`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify({ + model: this.config.model, + messages: [ + { + role: "user", + content: prompt, + }, + ], + temperature: this.config.temperature, + max_tokens: this.config.maxTokens, + }), + }) + + if (!response.ok) { + throw new Error(`OpenAI API error: ${response.status} ${response.statusText}`) + } + + const data = await response.json() + + if (!data.choices || data.choices.length === 0) { + throw new Error("No response from OpenAI API") + } + + return data.choices[0].message.content + } catch (error) { + console.error("OpenAI API call failed:", error) + throw error + } + } + + isAvailable(): boolean { + return Boolean(this.apiKey) + } +} + +export default OpenAIClient diff --git a/packages/changelog-cli/package.json b/packages/changelog-cli/package.json new file mode 100644 index 000000000..3354c071c --- /dev/null +++ b/packages/changelog-cli/package.json @@ -0,0 +1,35 @@ +{ + "name": "@follow/changelog-cli", + "type": "module", + "version": "1.0.0", + "private": true, + "description": "AI-driven changelog generator for Follow project", + "keywords": [ + "changelog", + "git", + "ai", + "cli", + "automation" + ], + "main": "./index.ts", + "bin": { + "changelog-cli": "./bin/cli.js" + }, + "engines": { + "node": ">=18.0.0" + }, + "scripts": { + "build": "tsc", + "dev": "tsx index.ts", + "generate": "tsx index.ts", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "dotenv": "17.2.0", + "pathe": "2.0.3" + }, + "devDependencies": { + "tsx": "4.20.3", + "typescript": "catalog:" + } +} diff --git a/packages/changelog-cli/tsconfig.json b/packages/changelog-cli/tsconfig.json new file mode 100644 index 000000000..5fd15f48a --- /dev/null +++ b/packages/changelog-cli/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../configs/tsconfig.extend.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./", + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true, + "esModuleInterop": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true + }, + "include": ["**/*.ts"], + "exclude": ["node_modules", "dist", "**/*.test.ts"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7c10cdb3b..00a31c89a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1338,6 +1338,22 @@ importers: specifier: 0.3.0 version: 0.3.0 + packages/changelog-cli: + dependencies: + dotenv: + specifier: 17.2.0 + version: 17.2.0 + pathe: + specifier: 2.0.3 + version: 2.0.3 + devDependencies: + tsx: + specifier: 4.20.3 + version: 4.20.3 + typescript: + specifier: 'catalog:' + version: 5.8.3 + packages/configs: dependencies: '@egoist/tailwindcss-icons': @@ -8690,6 +8706,10 @@ packages: resolution: {integrity: sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg==} engines: {node: '>=12'} + dotenv@17.2.0: + resolution: {integrity: sha512-Q4sgBT60gzd0BB0lSyYD3xM4YxrXA9y4uBDof1JNYGzOXrQdQ6yX+7XIAqoFOGQFOTK1D3Hts5OllpxMDZFONQ==} + engines: {node: '>=12'} + dotenv@9.0.2: resolution: {integrity: sha512-I9OvvrHp4pIARv4+x9iuewrWycX6CcZtoAu1XrzPxc5UygMJXJZYmBsynku8IkrJwgypE5DGNjDPmPRhDCptUg==} engines: {node: '>=10'} @@ -24848,6 +24868,8 @@ snapshots: dotenv@16.5.0: {} + dotenv@17.2.0: {} + dotenv@9.0.2: {} drizzle-kit@0.31.4: