Claude
Skills
Sign in
Back

when-documenting-code-use-doc-generator

Included with Lifetime
$97 forever

Automated comprehensive code documentation generation with API docs, README files, inline comments, and architecture diagrams

Backend & APIsdocumentationapi-docsreadmecommentsdiagramsautomation

What this skill does


# When Documenting Code - Use Doc Generator

## Overview

This skill provides automated, comprehensive documentation generation for codebases. It analyzes code structure, generates API documentation, creates README files, adds inline comments, and produces architecture diagrams using evidence-based documentation patterns.

## Core Capabilities

1. **Code Analysis**: Extract APIs, functions, classes, types, and dependencies
2. **API Documentation**: Generate OpenAPI, JSDoc, TypeDoc, and Python docstrings
3. **README Generation**: Create comprehensive project documentation
4. **Inline Comments**: Add missing documentation with context-aware comments
5. **Diagram Generation**: Produce architecture and flow diagrams (Graphviz, Mermaid)

## SPARC Methodology: Documentation Generation

### Phase 1: SPECIFICATION - Analyze Documentation Requirements

**Objective**: Understand the codebase structure and documentation needs

**Actions**:
1. Scan project structure and identify file types
2. Detect programming languages and frameworks
3. Identify existing documentation (README, API docs, comments)
4. Analyze documentation gaps and missing coverage
5. Determine documentation standards (JSDoc, TSDoc, Python docstrings)

**Deliverables**:
- Project structure analysis
- Documentation gap report
- Recommended documentation strategy
- Style guide selection

**Agent**: `code-analyzer`

**Example Analysis**:
```
Project: express-api-server
Languages: JavaScript (TypeScript), 85% | JSON 10% | Markdown 5%
Frameworks: Express.js, Jest
Current Documentation:
  - README.md: Exists (outdated, 3 months old)
  - API Docs: None
  - Inline Comments: 12% coverage
  - Type Definitions: 45% coverage

Gaps Identified:
  - ❌ No API documentation (12 endpoints undocumented)
  - ❌ Missing installation instructions
  - ❌ No architecture diagrams
  - ⚠️  Low inline comment coverage
  - ✅ Package.json well-documented

Recommended Strategy:
  1. Generate OpenAPI 3.0 spec for REST API
  2. Add JSDoc comments to all public functions
  3. Create comprehensive README with badges
  4. Generate architecture diagram (system overview)
  5. Add usage examples for main features
```

### Phase 2: PSEUDOCODE - Design Documentation Structure

**Objective**: Plan documentation hierarchy and templates

**Actions**:
1. Design documentation structure (README, API, guides)
2. Define comment style and conventions
3. Create templates for each documentation type
4. Plan diagram types and structure
5. Define metadata and frontmatter standards

**Deliverables**:
- Documentation structure outline
- Template designs for each type
- Comment convention guide
- Diagram specifications

**Example Structure**:
```
Documentation Hierarchy:

docs/
├── README.md                 # Project overview
├── INSTALLATION.md          # Setup guide
├── API.md                   # API reference
├── ARCHITECTURE.md          # System design
├── CONTRIBUTING.md          # Contribution guide
├── diagrams/
│   ├── system-overview.svg  # High-level architecture
│   ├── data-flow.svg        # Data flow diagram
│   └── api-endpoints.svg    # API structure
└── examples/
    ├── basic-usage.md
    └── advanced-features.md

Comment Standards:
- JSDoc for all exported functions
- TypeDoc for TypeScript interfaces
- File header with purpose and author
- Inline comments for complex logic only

API Documentation:
- OpenAPI 3.0 specification
- Example requests/responses
- Error code documentation
- Authentication guide
```

### Phase 3: ARCHITECTURE - Define Generation Pipeline

**Objective**: Design the documentation generation workflow

**Actions**:
1. Define code parsing strategy (AST, regex, static analysis)
2. Design template engine for documentation generation
3. Plan diagram generation pipeline (Graphviz/Mermaid)
4. Define validation and quality checks
5. Create update and versioning strategy

**Deliverables**:
- Documentation generation pipeline
- Parser and extractor design
- Template rendering engine
- Validation rules

**Pipeline Architecture**:
```
┌─────────────────┐
│  Source Code    │
│  Repository     │
└────────┬────────┘
         │
         ▼
┌─────────────────────────┐
│  Code Analyzer          │
│  - AST Parsing          │
│  - Extract Functions    │
│  - Extract Types        │
│  - Detect Patterns      │
└────────┬────────────────┘
         │
         ▼
┌─────────────────────────┐
│  Documentation Engine   │
│  ├─ API Generator       │
│  ├─ README Generator    │
│  ├─ Comment Generator   │
│  └─ Diagram Generator   │
└────────┬────────────────┘
         │
         ▼
┌─────────────────────────┐
│  Template Renderer      │
│  - Mustache/Handlebars  │
│  - Markdown Formatting  │
│  - Syntax Highlighting  │
└────────┬────────────────┘
         │
         ▼
┌─────────────────────────┐
│  Validator              │
│  - Link Checking        │
│  - Spelling             │
│  - Completeness         │
└────────┬────────────────┘
         │
         ▼
┌─────────────────────────┐
│  Output                 │
│  - docs/                │
│  - Inline Comments      │
│  - Generated Diagrams   │
└─────────────────────────┘
```

### Phase 4: REFINEMENT - Generate and Validate Documentation

**Objective**: Execute documentation generation with quality checks

**Actions**:
1. Parse source code and extract documentation targets
2. Generate API documentation from code signatures
3. Create README from templates and project metadata
4. Add inline comments to undocumented code
5. Generate architecture and flow diagrams
6. Validate completeness and accuracy
7. Check links and references
8. Format and style according to standards

**Deliverables**:
- Complete API documentation
- Comprehensive README
- Inline code comments
- Architecture diagrams
- Validation report

**Generation Examples**:

**Before (Undocumented Function)**:
```javascript
function calculateDiscount(price, customerType, quantity) {
  const baseDiscount = customerType === 'premium' ? 0.15 : 0.05;
  const volumeDiscount = quantity > 100 ? 0.1 : quantity > 50 ? 0.05 : 0;
  return price * (1 - baseDiscount - volumeDiscount);
}
```

**After (With JSDoc)**:
```javascript
/**
 * Calculates the final price after applying customer and volume discounts
 *
 * @param {number} price - The original price before discounts
 * @param {('standard'|'premium')} customerType - Customer tier level
 * @param {number} quantity - Number of items purchased
 * @returns {number} The discounted price
 *
 * @example
 * // Premium customer buying 60 items at $100 each
 * calculateDiscount(100, 'premium', 60);
 * // Returns: 80 (15% customer + 5% volume discount)
 *
 * @see {@link https://docs.example.com/pricing|Pricing Documentation}
 */
function calculateDiscount(price, customerType, quantity) {
  // Premium customers receive 15% base discount, standard customers 5%
  const baseDiscount = customerType === 'premium' ? 0.15 : 0.05;

  // Volume discounts: 10% for 100+, 5% for 50+, 0% otherwise
  const volumeDiscount = quantity > 100 ? 0.1 : quantity > 50 ? 0.05 : 0;

  return price * (1 - baseDiscount - volumeDiscount);
}
```

**API Documentation Generation**:
```yaml
# Generated OpenAPI 3.0 Specification
openapi: 3.0.0
info:
  title: E-commerce API
  version: 1.0.0
  description: REST API for e-commerce platform with pricing and inventory

paths:
  /api/v1/products/{id}/price:
    get:
      summary: Calculate product price with discounts
      description: Returns the final price after applying customer tier and volume discounts
      operationId: calculateProductPrice
      tags:
        - Pricing
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Product ID
        - name: quantity
          in: query
          required: true
          schema:
            type: integer
            minimum: 1
          description: Quantity to purchase
        - name: customerType
          in: query
          required: false
          s

Related in Backend & APIs