Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

alankars/auto-java-doc

Open more actions menu

Repository files navigation

JavaDoc + Swagger Auto-Documentation Setup

flow-illustration

Quick Start

# Set your API key
export ANTHROPIC_API_KEY='your-key'  # For Claude (default)
# OR
export GEMINI_API_KEY='your-key'     # For Gemini

# Run the tool
node javadoc-swagger-cli.js YourController.java

# Or specify provider explicitly
node javadoc-swagger-cli.js YourController.java --provider gemini

CLI Usage

node javadoc-swagger-cli.js <input-file.java> [options]

Options:
  -o, --output <file>    Output file path (default: adds _documented suffix)
  -p, --provider <name>  LLM provider: claude or gemini (default: claude)
  -s, --swagger-only     Generate only Swagger annotations
  -j, --javadoc-only     Generate only JavaDoc comments
  -i, --interactive      Review changes before writing
  --dry-run              Show output without writing file
  -h, --help             Show help message

Prerequisites

  1. GitHub repository with Java code
  2. AI API key from one of the supported providers:
    • Anthropic Claude (get from console.anthropic.com)
    • Google Gemini (get from ai.google.dev)
  3. Repository admin access for GitHub Actions

Supported LLM Providers

This tool supports multiple AI providers:

  • Anthropic Claude (default) - Uses Claude Sonnet 4
  • Google Gemini - Uses Gemini 1.5 Pro

You can switch between providers using the --provider option.

Setup Steps

Step 1: Add CLI Script to Repository

Create a scripts directory in your repository root:

mkdir -p scripts

Copy the javadoc-swagger-cli.js file to scripts/javadoc-swagger-cli.js

Step 2: Configure GitHub Secrets

  1. Go to your GitHub repository

  2. Navigate to Settings > Secrets and variables > Actions

  3. Click "New repository secret"

  4. Add secret(s) based on your chosen provider:

    For Claude (default):

    • Name: ANTHROPIC_API_KEY
    • Value: Your Anthropic API key

    For Gemini:

    Note: You can add both keys to switch between providers as needed. For Gemini: Ensure your API key has access to Gemini models. If you get "model not found" errors, regenerate your key.

Step 3: Add GitHub Action Workflow

Create .github/workflows/auto-javadoc.yml in your repository with the provided workflow configuration.

Step 4: Configure Repository Permissions

  1. Go to Settings > Actions > General
  2. Under "Workflow permissions", select:
    • "Read and write permissions"
    • Check "Allow GitHub Actions to create and approve pull requests"
  3. Save changes

How It Works

Trigger Conditions

The action triggers when:

  • Code is pushed to main or develop branches
  • Pull requests are opened/updated targeting main or develop
  • Only when .java files are modified

Workflow Process

  1. Detect Changes: Identifies which Java files were modified
  2. Process Files: Runs CLI tool on each changed file
  3. Generate Documentation: AI analyzes code and adds:
    • JavaDoc comments
    • Swagger annotations
    • HTTP status codes
    • Parameter descriptions
  4. Create Branch: Creates new branch docs/auto-javadoc-TIMESTAMP
  5. Commit Changes: Commits all documentation changes
  6. Open PR: Automatically creates pull request for review

Pull Request Contents

Each PR includes:

  • All documented files
  • List of changed files
  • Description of added documentation
  • Review checklist
  • Assignment to original committer

Customization Options

Modify Trigger Branches

Edit the workflow file to change which branches trigger the action:

on:
  push:
    branches:
      - main
      - staging  # Add your branches here

Change File Patterns

Process only specific directories:

paths:
  - 'src/main/java/**/*.java'
  - '!src/test/**'  # Exclude test files

Adjust CLI Options

Modify the CLI command in the workflow:

# Use Gemini instead of Claude
node javadoc-swagger-cli.js "$file" -o "$file" --provider gemini

# JavaDoc only
node javadoc-swagger-cli.js "$file" -o "$file" --javadoc-only

# Swagger only
node javadoc-swagger-cli.js "$file" -o "$file" --swagger-only

# With preview
node javadoc-swagger-cli.js "$file" -o "$file" --dry-run

# Combine provider with options
node javadoc-swagger-cli.js "$file" -o "$file" --provider gemini --swagger-only

Custom Bot Identity

Change the commit author:

git config user.name "Your Bot Name"
git config user.email "bot@yourdomain.com"

Add Auto-Merge

Add this step after PR creation for trusted environments:

- name: Auto-merge PR
  if: steps.check-changes.outputs.changes == 'true'
  run: |
    gh pr merge ${{ steps.create-branch.outputs.branch_name }} --auto --squash
  env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Local Testing (Before GitHub Integration)

Prerequisites for Local Testing

  1. Node.js installed (version 18 or higher)
  2. API key from your chosen provider (Anthropic or Google)

Setup Local Environment

# Clone the repository
git clone https://github.com/your-username/javadoc-swagger-ai.git
cd javadoc-swagger-ai

# Set your API key as environment variable
# For Claude (default):
# On Linux/Mac:
export ANTHROPIC_API_KEY='your-api-key-here'
# On Windows (PowerShell):
$env:ANTHROPIC_API_KEY='your-api-key-here'
# On Windows (Command Prompt):
set ANTHROPIC_API_KEY=your-api-key-here

# For Gemini:
# On Linux/Mac:
export GEMINI_API_KEY='your-api-key-here'
# On Windows (PowerShell):
$env:GEMINI_API_KEY='your-api-key-here'
# On Windows (Command Prompt):
set GEMINI_API_KEY=your-api-key-here

Test with Sample Files

Option 1: Use provided sample file (Claude - default)

# Basic test with Claude
node javadoc-swagger-cli.js samples/SampleController.java

# Test with Gemini
node javadoc-swagger-cli.js samples/SampleController.java --provider gemini

# Check the output
cat samples/SampleController_documented.java

Option 2: Test with your own file

# Copy your Java file to test directory
cp /path/to/your/Controller.java ./test/

# Run the tool with Claude (default)
node javadoc-swagger-cli.js test/Controller.java

# Or use Gemini
node javadoc-swagger-cli.js test/Controller.java --provider gemini

# Review the output
cat test/Controller_documented.java

Option 3: Dry run (preview without writing)

# See what would be generated without creating files
node javadoc-swagger-cli.js test/Controller.java --dry-run

Option 4: Interactive mode

# Review and approve before writing
node javadoc-swagger-cli.js test/Controller.java -i

Create Test Controller

If you don't have a test file, create one:

mkdir -p test
cat > test/UserController.java << 'EOF'
package com.example.api;

import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @GetMapping("/{id}")
    public ResponseEntity<User> getUser(@PathVariable Long id) {
        return ResponseEntity.ok(userService.findById(id));
    }
    
    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody UserRequest request) {
        User user = userService.create(request);
        return ResponseEntity.status(201).body(user);
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userService.delete(id);
        return ResponseEntity.noContent().build();
    }
}
EOF

# Run the tool
node javadoc-swagger-cli.js test/UserController.java

Validate Output

Check for JavaDoc:

# Should see /** comments above classes and methods
grep -A 3 "^/\*\*" test/UserController_documented.java

Check for Swagger annotations:

# Should see @Tag, @Operation, @ApiResponse
grep "@Tag\|@Operation\|@ApiResponse" test/UserController_documented.java

Test Different Options

Choose your provider:

# Use Claude (default)
node javadoc-swagger-cli.js test/UserController.java

# Use Gemini
node javadoc-swagger-cli.js test/UserController.java --provider gemini

Generate only JavaDoc:

node javadoc-swagger-cli.js test/UserController.java --javadoc-only -o test/UserController_javadoc.java

Generate only Swagger:

node javadoc-swagger-cli.js test/UserController.java --swagger-only -o test/UserController_swagger.java

Specify custom output:

node javadoc-swagger-cli.js test/UserController.java -o test/UserController_final.java

Combine options:

# Use Gemini with Swagger only
node javadoc-swagger-cli.js test/UserController.java --provider gemini --swagger-only

# Use Claude with interactive mode
node javadoc-swagger-cli.js test/UserController.java --provider claude -i

Compare Before and After

# Install diff tool (if not already installed)
# Linux: sudo apt-get install colordiff
# Mac: brew install colordiff

# Side-by-side comparison
diff -y test/UserController.java test/UserController_documented.java | less

# Or with colors
colordiff -u test/UserController.java test/UserController_documented.java

Batch Testing Multiple Files

# Process all Java files in a directory
for file in src/main/java/**/*.java; do
    echo "Processing: $file"
    node javadoc-swagger-cli.js "$file" --dry-run
done

Performance Testing

# Time the execution
time node javadoc-swagger-cli.js test/UserController.java

# Typical execution time: 2-5 seconds per file

Testing the GitHub Action Setup

Manual Test with GitHub Actions

  1. Create a test Java file without documentation:
@RestController
@RequestMapping("/api/test")
public class TestController {
    @GetMapping("/{id}")
    public String test(@PathVariable Long id) {
        return "test";
    }
}
  1. Commit and push to your branch
  2. Wait for GitHub Action to run
  3. Check for new PR with documentation

Test in a Separate Branch

# Create test branch
git checkout -b test/documentation-automation

# Add undocumented file
cat > src/main/java/TestController.java << 'EOF'
@RestController
@RequestMapping("/api/test")
public class TestController {
    @GetMapping
    public String test() {
        return "test";
    }
}
EOF

# Commit and push
git add .
git commit -m "test: add undocumented controller"
git push origin test/documentation-automation

# Check Actions tab in GitHub
# Should see workflow running
# Should get PR with documentation within 2-3 minutes

Verify Action Logs

  1. Go to Actions tab in GitHub
  2. Click on the latest workflow run
  3. Review logs for each step
  4. Check for errors or warnings

Troubleshooting

Action Not Triggering

Check:

  • Workflow file is in .github/workflows/
  • File changes include .java files
  • Branch matches trigger configuration

API Key Issues

Verify:

  • Secret name matches your provider:
    • For Claude: ANTHROPIC_API_KEY
    • For Gemini: GEMINI_API_KEY
  • API key is valid and active
  • Key has sufficient credits/quota
  • Correct provider is specified in command (--provider claude or --provider gemini)

Permission Errors

Ensure:

  • Workflow permissions are set to "Read and write"
  • "Allow GitHub Actions to create PRs" is enabled
  • Token has necessary scopes

CLI Tool Errors

Review:

  • Node.js version is 18 or higher
  • CLI script path is correct
  • Input files are valid Java code

Advanced Configuration

Multiple Environments

Create separate workflows for different environments:

.github/workflows/
  ├── auto-javadoc-dev.yml    # Development
  ├── auto-javadoc-staging.yml # Staging
  └── auto-javadoc-prod.yml    # Production

Custom Review Rules

Add required reviewers in workflow:

reviewers: |
  senior-dev-1
  senior-dev-2
team-reviewers: |
  backend-team

Scheduled Documentation Updates

Add cron trigger for periodic checks:

on:
  schedule:
    - cron: '0 2 * * 1'  # Weekly on Monday at 2 AM

Furute!! Integration with Other Tools

Chain with other actions:

  • Code quality checks (SonarQube)
  • Static analysis (Checkstyle)
  • Test coverage reports
  • Deploy documentation to wiki

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published
Morty Proxy This is a proxified and sanitized view of the page, visit original site.