- Python 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
- Update repository classifier documentation - Add new analysis files for OpenAPI, Unit tests, Documentation, Integration - Add Git and Security analysis files - Add Changelog and E2E testing files - Add Deployment analysis files |
||
| .windsurf | ||
| docs | ||
| src/forgejo_client | ||
| tests | ||
| .gitignore | ||
| B[OpenAPI | ||
| B[Unit | ||
| C | ||
| C[Documentation | ||
| C[Integration | ||
| conftest.py | ||
| D[Git | ||
| D[Security | ||
| E[Changelog | ||
| E[E2E | ||
| F[Deployment] | ||
| mock_mappy_server.py | ||
| pyproject.toml | ||
| pytest.ini | ||
| README.md | ||
| temp_mock_server.py | ||
| test_client.py | ||
| validation.py | ||
Forgejo Client
A modular Python client for interacting with Forgejo repositories, designed specifically for AI agents and automated workflows. The client provides a single unified API for all Forgejo operations including issues, repositories, labels, branches, pull requests, commits, releases, files, projects, and wiki pages. The modular architecture separates concerns into distinct modules while maintaining a cohesive interface through the main client class.
Architecture Overview
The Forgejo client consists of a central ForgejoClient class that provides access to specialized modules for different Forgejo operations. The client uses a configuration object to manage authentication, caching, and repository context. Each module is lazy-loaded on first access to minimize startup overhead and allow for optional dependencies.
The architecture includes authentication management through the AuthManager class, which supports both basic authentication and token-based authentication. Caching is handled by the CacheManager class, which provides file-based caching with configurable TTL for GET requests. This design reduces API calls and improves performance for repeated operations.
Modules are organized by functionality: the IssuesModule handles issue creation and management with agent-friendly helpers for progress tracking and investigation. The ReposModule manages repository operations including listing and creating repositories. The FilesModule handles file operations within repositories. The ProjectsModule provides kanban board functionality. The WikiModule manages wiki pages with caching support for documentation retrieval.
Enhanced Features (2026 Update)
Markdown Formatting Engine: The forgejo-client now includes automatic markdown formatting for proper Forgejo rendering, with special support for mermaid diagrams, code blocks, and structured content.
Agent-Friendly Workflows: Enhanced helper methods for automated issue management, including progress tracking, investigation reporting, and resolution documentation.
Performance Optimizations: Improved caching strategies, session management, and rate limiting for high-volume agent operations.
graph TD
A[ForgejoClient] --> B[AuthManager]
A --> C[CacheManager]
A --> D[IssuesModule]
A --> E[ReposModule]
A --> F[LabelsModule]
A --> G[BranchesModule]
A --> H[PullsModule]
A --> I[CommitsModule]
A --> J[ReleasesModule]
A --> K[FilesModule]
A --> L[ProjectsModule]
A --> M[WikiModule]
A --> N[ForgejoConfig]
N --> O[Base URL]
N --> P[Authentication]
N --> Q[Repository Context]
N --> R[Caching Settings]
Core Concepts
The Forgejo client is designed around modularity and agent-friendliness. Modularity means that each type of operation has its own dedicated module, allowing for clear separation of concerns and easier maintenance. Agent-friendliness refers to the inclusion of helper methods that automate common workflows, reducing the complexity of issue management and repository operations for automated systems.
Authentication is handled through a flexible configuration system that supports both basic authentication and token-based authentication. The client automatically handles authentication headers and session management, allowing users to switch between authentication methods without changing application code. This flexibility is particularly important in environments where different authentication mechanisms are used for different operations.
Caching is built into the client to reduce API load and improve performance for repeated operations. The caching system is file-based with configurable time-to-live (TTL) settings. By default, GET requests are cached for one hour, significantly reducing the number of API calls for frequently accessed data like repository information or issue lists. Cache invalidation is handled automatically for write operations, ensuring that stale data is not served after modifications.
Lazy loading of modules is a performance optimization that reduces startup overhead. Modules are only loaded when first accessed, meaning that applications that only use issue operations don't incur the overhead of loading pull request or wiki functionality. This design choice allows the client to remain lightweight while still providing comprehensive functionality.
Advanced Concepts
The HTTP session management is handled through a single persistent session that is reused across all requests. This approach reduces connection overhead and improves performance for sequences of related operations. Authentication headers are added automatically to each request, eliminating the need for manual header management. The session also handles connection pooling and keep-alive, further improving performance for sequences of related operations.
Wiki page retrieval benefits significantly from caching, with cached page loads typically completing in under 5 milliseconds. Initial page loads depend on page size and network conditions, but subsequent accesses are served from the local cache. This design makes the wiki module particularly efficient for agents that repeatedly access configuration documentation or API references.
The issue management system includes specialized helper methods designed for agent workflows. These methods include create_with_commit for linking issues to specific commits, close_with_comment for closing issues with documentation, add_progress for progress updates, add_investigation for investigation findings, and add_resolution for resolution information. These helpers enforce consistent formatting and reduce the boilerplate required for common issue management tasks.
Usage Examples
Basic Issue Creation
from tools.forgejo_client.client import ForgejoClient
from tools.forgejo_client.config import ForgejoConfig
# Configure client
config = ForgejoConfig(
base_url='https://git.sly.so',
token='your-token-here',
repo_owner='reynard',
repo_name='reynard'
)
client = ForgejoClient(config)
# Create issue with enhanced formatting
issue = client.issues.create_issue(
title="New Feature Request",
body='''# Feature Overview
This issue proposes a new feature for enhanced user experience.
## Requirements
```mermaid
graph TB
A[User Input] --> B[Validation]
B --> C[Processing]
C --> D[Output]
Implementation Details
The feature will be implemented using the following approach:
- Phase 1: Core functionality
- Phase 2: User interface
- Phase 3: Testing and deployment
def example_function():
return "Enhanced formatting works!"
''', labels=['enhancement', 'documentation'] )
### Agent Workflow Example
```mermaid
sequenceDiagram
participant Agent as AI Agent
participant Client as Forgejo Client
participant API as Forgejo API
participant Cache as Cache Manager
Agent->>Client: Initialize with config
Client->>Client: Setup AuthManager & CacheManager
Agent->>Client: issues.create_issue()
Client->>Client: _format_markdown_body()
Client->>API: POST /repos/{owner}/{repo}/issues
API-->>Client: Issue response
Client-->>Agent: Issue details
Agent->>Client: issues.get_issues()
Client->>Cache: Check cache
alt Cache hit
Cache-->>Client: Cached data
else Cache miss
Client->>API: GET /repos/{owner}/{repo}/issues
API-->>Client: Issues list
Client->>Cache: Store response
end
Client-->>Agent: Issues list
Advanced Agent Operations
# Create issue with investigation tracking
issue = client.issues.create_issue(
title="Performance Investigation",
body="Initial investigation into performance bottlenecks."
)
# Add investigation findings
client.issues.add_investigation(
issue_number=issue['number'],
findings="Discovered memory leak in module X",
evidence="Memory usage increases by 10MB per request",
next_steps="Profile the module and identify leak source"
)
# Add progress updates
client.issues.add_progress(
issue_number=issue['number'],
status="In Progress",
completion=0.6,
blockers="Waiting for test environment setup"
)
# Close with resolution
client.issues.close_with_comment(
issue_number=issue['number'],
resolution="Fixed memory leak by implementing proper cleanup in module X",
verification="Performance tests show stable memory usage",
impact="Improved response time by 40%"
)
Markdown Formatting Features
Automatic Diagram Spacing
The forgejo-client automatically ensures proper spacing around mermaid diagrams:
Input:
Some text here
```mermaid
graph TB
A --> B
More text here
**Output** (automatically formatted):
```markdown
Some text here
```mermaid
graph TB
A --> B
More text here
### Header Formatting
Automatic blank lines before headers ensure proper rendering:
**Input**:
```markdown
Some text
## Header 2
More text
### Header 3
Output (automatically formatted):
Some text
## Header 2
More text
### Header 3
Code Block Optimization
Proper spacing around code blocks:
Input:
Text before
```python
def func():
pass
Text after
**Output** (automatically formatted):
```markdown
Text before
```python
def func():
pass
Text after
## Performance Characteristics
### Caching Strategy
```mermaid
graph LR
subgraph "Cache Performance"
A[Request] --> B{Cache Hit?}
B -->|Yes| C[<5ms response]
B -->|No| D[API Call]
D --> E[Store in Cache]
E --> F[Return Response]
end
subgraph "Cache Settings"
G[Default TTL: 1 hour]
H[GET requests cached]
I[Write ops invalidate]
J[File-based storage]
end
Session Management
- Persistent Connections: Single HTTP session reused across requests
- Connection Pooling: Automatic connection reuse and keep-alive
- Authentication Headers: Automatically added to all requests
- Rate Limiting: Built-in rate limiting to prevent API abuse
Memory Usage
- Lazy Loading: Modules loaded only when accessed
- Efficient Serialization: JSON for API data, file-based caching
- Memory Footprint: <50MB for typical operations
- Cleanup: Automatic cache cleanup and session management
API Reference
The ForgejoConfig class manages all client configuration including authentication, caching, and repository context. The base_url parameter specifies the Forgejo instance URL, while authentication can be configured through either username and password for basic auth or a token for token auth. Repository context is set through repo_owner and repo_name parameters. Caching is controlled through cache_enabled, cache_dir, and cache_ttl parameters.
The ForgejoClient class provides the main interface for API interactions. The test_connection method verifies connectivity to the Forgejo instance. Module properties provide access to specialized functionality: issues for issue operations, repos for repository operations, labels for label management, branches for branch operations, pulls for pull request operations, commits for commit operations, releases for release operations, files for file operations, projects for kanban board operations, and wiki for wiki operations.
The IssuesModule provides comprehensive issue management with agent-friendly helpers. Basic operations include getting issues with optional state and label filters, retrieving specific issues, creating new issues, updating existing issues, and closing issues. Helper methods include create_with_commit for linking issues to commits, close_with_comment for closing with documentation, add_progress for progress updates, add_investigation for investigation findings, and add_resolution for resolution information.
The WikiModule manages wiki pages with caching support. Methods include getting all wiki pages, retrieving specific pages with content, creating new pages, updating existing pages, deleting pages, and getting revision history. The module supports optional caching with the use_cache parameter, and write operations automatically invalidate relevant cache entries.
Configuration
Authentication can be configured using either basic authentication or token authentication. Basic authentication requires username and password, while token authentication requires an API token. The choice between methods depends on the Forgejo instance configuration and security requirements. Token authentication is generally preferred for automated workflows as it provides more granular access control and easier revocation.
Caching behavior is controlled through three configuration parameters. cache_enabled enables or disables caching entirely, defaulting to enabled. cache_dir specifies the directory for cache storage, defaulting to ~/.cache/forgejo-client. cache_ttl sets the cache time-to-live in seconds, defaulting to 3600 (one hour). These parameters can be adjusted based on usage patterns and performance requirements.
Repository context is set through repo_owner and repo_name parameters. This context is used as the default for operations that don't explicitly specify a repository, reducing the need to repeat repository information in each call. The context can be changed temporarily for specific operations by modifying the config object before the operation and restoring it afterward.
Quick Start
To use the Forgejo client, first configure it with your Forgejo instance URL and authentication credentials. The client can be instantiated with either basic authentication using username and password, or token authentication using an API token. After creating the client, test the connection to verify that authentication is working correctly before making API calls.
from forgejo_client import ForgejoClient, ForgejoConfig
config = ForgejoConfig(
base_url="https://git.sly.so",
username="kade",
password="your-password",
repo_owner="reynard",
repo_name="monads"
)
client = ForgejoClient(config)
if client.test_connection():
print("Connected to Forgejo")
Modules
The IssuesModule provides comprehensive issue management capabilities. Basic operations include retrieving issues with optional filters for state and labels, getting specific issue details, creating new issues, updating existing issues, and closing issues. The module also includes agent-friendly helper methods for common workflows such as linking issues to commits, adding progress updates, documenting investigation findings, and recording resolutions.
The ReposModule handles repository operations including retrieving repository information, listing repositories for a given owner, and creating new repositories. This module is useful for automation tasks that need to discover or manage repositories programmatically.
The LabelsModule manages repository labels including retrieving existing labels, creating new labels with colors and descriptions, and ensuring that required labels exist. The ensure_labels method is particularly useful for setting up consistent label schemes across multiple repositories.
The BranchesModule handles branch operations including listing branches and creating new branches from specific commits. This module is useful for automation workflows that need to create feature branches or manage branch structures.
The PullsModule manages pull request operations including listing pull requests, creating new pull requests, and merging pull requests. This module supports the full pull request lifecycle from creation to merge.
The CommitsModule handles commit operations including listing commits for a repository and retrieving specific commit details. This module is useful for tracking changes and linking issues to specific commits.
The ReleasesModule manages release operations including listing releases and creating new releases with tags and release notes. This module supports the full release lifecycle for version management.
The FilesModule handles file operations within repositories including retrieving file content, creating new files, and updating existing files. This module supports both reading and writing files through the Forgejo API.
The ProjectsModule provides kanban board functionality including getting projects, creating projects, managing columns, and moving cards between columns. This module is useful for project management workflows that need to track work across kanban boards.
The WikiModule manages wiki pages with caching support for efficient documentation retrieval. Operations include getting all wiki pages, retrieving specific page content, creating new pages, updating existing pages, deleting pages, and getting revision history. The caching support makes this module particularly efficient for agents that repeatedly access configuration documentation.
Testing
The test suite covers all major modules and includes integration tests that require a live Forgejo instance. Tests are organized by module, with separate test files for the client, issues, wiki functionality, and cross-repository search. Run tests using pytest from the forgejo-client directory.
Installation
Pip Install (Recommended)
Install the latest version from the kade/forgejo-client fork:
pip install git+https://git.sly.so/kade/forgejo-client.git
This installs both the library and the forgejo-cli command line tool.
From Source
The Forgejo client can also be used directly from the Reynard monorepo by adding the tools/forgejo-client directory to your Python path. No external dependencies are required beyond the Python standard library and the requests library for HTTP operations.
CLI Usage
The forgejo-client includes a CLI interface that is installed automatically with pip installation. The CLI uses the FORGEJO_TOKEN environment variable for authentication.
# Set FORGEJO_TOKEN in environment
export FORGEJO_TOKEN=your_token_here
# Test connection
forgejo-cli test
# List repositories for a user
forgejo-cli repos list --owner kade
# List issues in a repository
forgejo-cli issues list --owner reynard --repo reynard
# Create an issue
forgejo-cli issues create --owner kade --repo wolfy --title "Bug fix" --body "Description"
# Close an issue with comment
forgejo-cli issues close --owner kade --repo wolfy --number 42 --comment "Fixed in commit abc123"
# Add comment to an issue
forgejo-cli issues comment --owner kade --repo wolfy --number 42 --body "Progress update"
Available Commands:
test- Test connection to Forgejoissues- Issue operations (list, create, close, comment)repos- Repository operations (list)
Best Practices
Use comments for progress updates rather than modifying the issue body directly. This maintains a clear history of progress and makes it easier to track the evolution of an issue. The cache is enabled by default for GET requests, which improves performance for repeated operations. Use the provided templates for consistent issue and comment formatting. Always test the connection before making API calls to ensure authentication is configured correctly. Handle errors gracefully as methods return None on failure.
License
MIT