Documentation Generation: Building a Doc-Writing Skill
Create a Claude Code skill that generates comprehensive documentation. From API docs to READMEs, automate your documentation workflow.
Documentation Generation: Building a Doc-Writing Skill
Documentation is the part of software development everyone knows is important but nobody wants to do. It's tedious, time-consuming, and becomes outdated the moment code changes.
What if documentation wrote itself? What if every time you finished a feature, the docs were already there, accurate and comprehensive?
This tutorial shows you how to build documentation generation skills that keep your docs in sync with your code.
The Documentation Challenge
Why Documentation Is Hard
- Time investment: Writing docs takes as long as writing code
- Staleness: Docs become outdated as code evolves
- Context switching: Moving from coding to writing is jarring
- Multiple audiences: Different readers need different docs
What AI Does Well
- Pattern recognition: Understand code structure
- Natural language: Write clear explanations
- Consistency: Maintain style across docs
- Tirelessness: Document everything without fatigue
Building the Core Documentation Skill
Master Documentation Command
.claude/commands/doc.md:
---
description: Generate documentation for code
arguments:
- name: target
description: File, directory, or symbol to document
required: true
- name: type
description: Doc type (api, readme, guide, inline)
required: false
default: auto
- name: format
description: Output format (markdown, jsdoc, docstring)
required: false
default: markdown
---
# Documentation Generator
When the user runs /doc [target], generate comprehensive documentation.
## Analyze Target
First, understand what you're documenting:
### If target is a file:
1. Read the entire file
2. Identify language and framework
3. Map exports, classes, functions
4. Note dependencies and integrations
### If target is a directory:
1. List all source files
2. Build dependency graph
3. Identify entry points
4. Note architecture patterns
### If target is a symbol (function/class name):
1. Find the symbol in codebase
2. Read its implementation
3. Find all usages
4. Understand context
## Determine Documentation Type
If type is "auto", choose based on context:
- Single function → API documentation
- Single class → Class documentation
- Entire module → Module documentation
- Package root → README
- Complex workflow → Guide
## Generate Documentation
### For API Documentation:
```markdown
# API Reference: [Module/Class Name]
## Overview
[1-2 paragraph description of what this does and why]
## Installation
```bash
[installation command if applicable]
Quick Start
[minimal working example]
API
[Function/Method Name]
[Description of what it does]
Signature:
[function signature with types]
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
| param1 | string | Yes | Description |
| param2 | number | No | Description (default: 10) |
Returns:
ReturnType - Description of return value
Throws:
ErrorType- When this condition occurs
Example:
[usage example]
[Repeat for each function/method]
Types
[TypeName]
[type definition]
Description of the type and its fields.
Error Handling
[Description of error patterns]
See Also
- [Related functions/docs]
### For README:
```markdown
# [Project Name]
[One-line description]
## Features
- Feature 1
- Feature 2
- Feature 3
## Installation
```bash
[installation steps]
Quick Start
[minimal example to get started]
Usage
[Common use cases with examples]
Configuration
[Configuration options if applicable]
API Reference
[Link to full API docs or summary]
Contributing
[How to contribute]
License
[License info]
### For Inline Documentation:
Generate comments appropriate to the language:
**JavaScript/TypeScript (JSDoc):**
```javascript
/**
* Brief description of the function.
*
* Longer description if needed, explaining the purpose,
* behavior, and any important notes.
*
* @param {string} param1 - Description of param1
* @param {number} [param2=10] - Optional param with default
* @returns {Promise<Result>} Description of return value
* @throws {ValidationError} When input is invalid
* @example
* const result = await myFunction('test');
* console.log(result);
*/
Python (docstring):
def function_name(param1: str, param2: int = 10) -> Result:
"""Brief description of the function.
Longer description if needed, explaining the purpose,
behavior, and any important notes.
Args:
param1: Description of param1
param2: Optional param with default (default: 10)
Returns:
Result: Description of return value
Raises:
ValidationError: When input is invalid
Example:
>>> result = function_name('test')
>>> print(result)
"""
Quality Standards
Generated documentation must:
- Be accurate to the code
- Include working examples
- Cover error cases
- Be understandable to the target audience
- Follow project conventions
### README Generator
**.claude/commands/readme.md:**
```markdown
---
description: Generate or update project README
arguments:
- name: style
description: README style (minimal, standard, detailed)
required: false
default: standard
---
# README Generator
Generate a comprehensive README for the project.
## Gather Project Information
### From Files
1. `package.json` / `setup.py` / `Cargo.toml`:
- Project name
- Description
- Version
- Dependencies
- Scripts
2. `LICENSE`:
- License type
3. Source files:
- Main entry points
- Key exports
- Architecture patterns
4. Existing docs:
- Any existing README
- CHANGELOG
- CONTRIBUTING
### From Git
1. Repository URL
2. Recent commits for activity
3. Contributors
## Generate README
### Minimal Style
```markdown
# [Project Name]
[Description]
## Install
```bash
[command]
Usage
[example]
License
[License]
### Standard Style
```markdown
# [Project Name]
[Badge: version] [Badge: license] [Badge: build status]
[2-3 sentence description]
## Features
- [Key feature 1]
- [Key feature 2]
- [Key feature 3]
## Installation
```bash
[installation command]
Requirements
- [Requirement 1]
- [Requirement 2]
Quick Start
[minimal working example]
Documentation
[Link to full docs or brief API reference]
Contributing
[Brief contribution guidelines or link]
License
[License name] - see LICENSE
### Detailed Style
Include all sections from standard plus:
- Table of Contents
- Detailed installation options
- Full API reference or link
- Configuration options
- Troubleshooting section
- FAQ
- Roadmap
- Acknowledgments
## Update vs Replace
If README already exists:
1. Read existing content
2. Preserve custom sections
3. Update generated sections
4. Mark sections that might need manual review
API Documentation Generator
.claude/commands/api-docs.md:
---
description: Generate API documentation
arguments:
- name: target
description: Source file or directory
required: true
- name: output
description: Output directory for docs
required: false
default: docs/api
---
# API Documentation Generator
Generate comprehensive API documentation from source code.
## Analyze Source
1. Parse all source files
2. Extract:
- Classes and their methods
- Standalone functions
- Type definitions
- Constants and configuration
3. Build relationships:
- Inheritance hierarchies
- Dependencies between modules
- Usage patterns
## Generate Documentation Structure
docs/api/ ├── index.md # Overview and navigation ├── getting-started.md # Quick start guide ├── modules/ │ ├── module-a.md # Each module │ └── module-b.md ├── classes/ │ ├── ClassA.md # Each class │ └── ClassB.md ├── functions/ │ └── utilities.md # Grouped functions └── types/ └── types.md # Type definitions
## Documentation Format
### Module Page
```markdown
# [Module Name]
## Overview
[Module description and purpose]
## Exports
| Export | Type | Description |
|--------|------|-------------|
| funcA | Function | Brief description |
| ClassB | Class | Brief description |
## Dependencies
This module depends on:
- [Module X](./module-x.md)
- [External: lodash]
## Example
```[language]
[Complete usage example]
See Also
- [Related module]
### Class Page
```markdown
# Class: [ClassName]
[Brief description]
## Hierarchy
ParentClass └── ClassName ├── ChildClassA └── ChildClassB
## Constructor
```[language]
new ClassName(param1: Type, param2: Type)
Parameters:
param1(Type) - Descriptionparam2(Type) - Description
Properties
property1
property1: Type
Description of the property.
Methods
methodName()
methodName(param: Type): ReturnType
[Method description]
Parameters:
param(Type) - Description
Returns: ReturnType - Description
Example:
const instance = new ClassName();
const result = instance.methodName(value);
Static Methods
staticMethod()
[Similar format to instance methods]
Events
eventName
Fired when [condition].
Event data:
{ property: Type }
## Cross-Reference
Add links between related docs:
- Parent/child classes link to each other
- Function parameters link to type definitions
- Examples reference real use cases
Keeping Docs in Sync
Doc Sync Agent
.claude/agents/doc-sync.md:
---
description: Keep documentation in sync with code
trigger:
event: post-commit
files: ["src/**/*"]
---
# Documentation Sync Agent
Automatically update documentation when code changes.
## On Code Change
When source files change:
1. Identify what changed:
- New functions/classes
- Modified signatures
- Deleted exports
- Changed behavior
2. Find related documentation:
- API docs for modified functions
- README sections referencing changed code
- Inline comments that might be outdated
3. Update documentation:
- Regenerate affected API docs
- Update examples if behavior changed
- Flag potentially stale content
## Notification
After sync, report:
Documentation Sync Complete
Files changed: 3 Docs updated: 2 Docs needing review: 1
Updated:
- docs/api/UserService.md (new method: getUserByEmail)
- docs/api/types.md (updated User type)
Needs review:
- README.md (references removed function: oldHelper)
Run /doc-review to see details.
## Limitations
DO NOT automatically update:
- README sections with custom content
- Guides and tutorials (may need rewriting)
- Marketing copy
- Version-specific documentation
Doc Review Command
.claude/commands/doc-review.md:
---
description: Review documentation for accuracy
arguments:
- name: path
description: Path to documentation
required: false
default: docs/
---
# Documentation Review
Check documentation for accuracy against code.
## Analysis
For each documentation file:
1. **Extract code references:**
- Function names mentioned
- Class names mentioned
- Code examples
2. **Verify against source:**
- Do referenced functions exist?
- Are signatures correct?
- Do examples still work?
3. **Check for staleness:**
- References to deleted code
- Outdated examples
- Missing new features
## Report Format
Documentation Review Report
Files reviewed: 15 Issues found: 7
Critical (Code references don't exist)
-
docs/api/utils.md:42 References
formatDate()which no longer exists Suggested action: Remove or update toformatDateTime() -
docs/guide/auth.md:89 Example uses deprecated
login()method Suggested action: Update toauthenticate()
Warning (Potentially outdated)
- docs/api/UserService.md:23
Method signature outdated
Code:
createUser(name: string, email: string)Docs:createUser(name: string)
Info (Missing documentation)
- src/services/PaymentService.ts New file, no documentation exists Suggested action: Run /doc src/services/PaymentService.ts
Suggestions
- Add examples to docs/api/config.md
- Update changelog with recent changes
Specialized Documentation Skills
Changelog Generator
.claude/commands/changelog.md:
---
description: Generate or update CHANGELOG
arguments:
- name: version
description: New version number
required: true
- name: since
description: Git ref to compare from
required: false
---
# Changelog Generator
Generate a CHANGELOG entry from git history.
## Gather Changes
1. Get commits since last tag (or specified ref):
`git log [since]..HEAD --oneline`
2. Categorize commits:
- **Added**: New features (feat:)
- **Changed**: Changes to existing features (refactor:, change:)
- **Deprecated**: Soon-to-be removed features
- **Removed**: Removed features (remove:)
- **Fixed**: Bug fixes (fix:)
- **Security**: Security fixes (security:)
## Format
```markdown
## [version] - YYYY-MM-DD
### Added
- Add user authentication system (#42)
- New dashboard component
### Changed
- Improve database query performance
- Update dependencies
### Fixed
- Fix login redirect loop (#38)
- Correct date formatting in reports
### Security
- Patch XSS vulnerability in comments
Integration
If CHANGELOG.md exists:
- Read existing content
- Insert new version at top (after header)
- Preserve existing entries
If no CHANGELOG.md:
- Create with Keep a Changelog format
- Add new version entry
### Contributing Guide Generator
**.claude/commands/contributing.md:**
```markdown
---
description: Generate CONTRIBUTING.md
---
# Contributing Guide Generator
Generate a comprehensive contributing guide.
## Analyze Project
1. Check for:
- Test framework
- Linting rules
- Build process
- PR workflow
2. Detect conventions:
- Commit message format
- Branch naming
- Code style
## Generate Guide
```markdown
# Contributing to [Project Name]
Thank you for your interest in contributing!
## Getting Started
### Prerequisites
- [Requirement 1]
- [Requirement 2]
### Setup
```bash
# Clone the repository
git clone [repo-url]
cd [project-name]
# Install dependencies
[install command]
# Run tests to verify setup
[test command]
Development Workflow
Branch Naming
feature/description- New featuresfix/description- Bug fixesdocs/description- Documentation
Commit Messages
We use conventional commits:
type(scope): description
[optional body]
[optional footer]
Types: feat, fix, docs, style, refactor, test, chore
Before Submitting
- Run tests:
[test command] - Run linter:
[lint command] - Update documentation if needed
Pull Request Process
- Create a branch from
main - Make your changes
- Add tests if applicable
- Update documentation
- Submit PR with clear description
Code Style
[Code style guidelines or link to style guide]
Testing
[How to run tests, what to test]
Questions?
[How to get help - issues, discussions, etc.]
Best Practices
1. Document Early
Generate docs as you code, not after:
/docafter each new function/readmewhen starting a project/api-docsbefore code review
2. Use Templates
Create team templates for consistency:
## Function Documentation Template
- What it does (one sentence)
- Why it exists (context)
- How to use it (example)
- What can go wrong (errors)
3. Verify Examples
Every example should be tested:
## Example Verification
Before including an example:
1. Run the code
2. Verify output matches
3. Check for edge cases
4. Link Everything
Documentation should connect:
- Functions → Types they use
- Classes → Parent classes
- Modules → Dependencies
5. Update on Change
Use the doc-sync agent or remember to:
- Update docs when changing code
- Review docs in code review
- Run doc-review regularly
Summary
Documentation doesn't have to be painful. With the right skills, you can:
- Generate comprehensive docs from code
- Keep docs in sync automatically
- Review docs for accuracy
- Create consistent, professional documentation
Skills Created
| Skill | Purpose |
|---|---|
/doc | Generate documentation for any target |
/readme | Create or update README |
/api-docs | Generate full API documentation |
/changelog | Generate CHANGELOG entries |
/contributing | Generate contributing guide |
/doc-review | Check docs for accuracy |
Integration
- Pre-commit: Generate inline docs
- Post-commit: Sync API docs
- Pre-release: Update changelog
- Regularly: Review docs for staleness
Ready to integrate with GitHub? Check out GitHub Integration for automating GitHub workflows.