# Gitea Integration Guide

Complete guide to using Gitea integration for workspace management, extension distribution, and collaboration.

**Version:** 1.0.0
**Last Updated:** 2025-10-06

---

## Table of Contents

1. [Overview](#overview)
2. [Setup](#setup)
3. [Workspace Git Integration](#workspace-git-integration)
4. [Workspace Locking](#workspace-locking)
5. [Extension Publishing](#extension-publishing)
6. [Service Management](#service-management)
7. [API Reference](#api-reference)
8. [Troubleshooting](#troubleshooting)

---

## Overview

The Gitea integration provides:

- **Workspace Git Integration**: Version control for workspaces
- **Distributed Locking**: Prevent concurrent workspace modifications
- **Extension Distribution**: Publish and download extensions via releases
- **Collaboration**: Share workspaces and extensions across teams
- **Service Management**: Deploy and manage local Gitea instance

### Architecture

```plaintext
┌─────────────────────────────────────────────────────────┐
│                 Provisioning System                      │
├─────────────────────────────────────────────────────────┤
│                                                          │
│  ┌────────────┐  ┌──────────────┐  ┌─────────────────┐ │
│  │ Workspace  │  │   Extension  │  │    Locking      │ │
│  │   Git      │  │  Publishing  │  │   (Issues)      │ │
│  └─────┬──────┘  └──────┬───────┘  └────────┬────────┘ │
│        │                │                     │          │
│        └────────────────┼─────────────────────┘          │
│                         │                                │
│                  ┌──────▼──────┐                         │
│                  │  Gitea API  │                         │
│                  │   Client    │                         │
│                  └──────┬──────┘                         │
│                         │                                │
└─────────────────────────┼────────────────────────────────┘
                          │
                  ┌───────▼────────┐
                  │  Gitea Service │
                  │  (Local/Remote)│
                  └────────────────┘
```plaintext

---

## Setup

### Prerequisites

- **Nushell 0.107.1+**
- **Git** installed and configured
- **Docker** (for local Gitea deployment) or access to remote Gitea instance
- **SOPS** (for encrypted token storage)

### Configuration

#### 1. Add Gitea Configuration to Nickel

Edit your `provisioning/schemas/modes.ncl` or workspace config:

```kcl
import provisioning.gitea as gitea

# Local Docker deployment
_gitea_config = gitea.GiteaConfig {
    mode = "local"
    local = gitea.LocalGitea {
        enabled = True
        deployment = "docker"
        port = 3000
        auto_start = True
        docker = gitea.DockerGitea {
            image = "gitea/gitea:1.21"
            container_name = "provisioning-gitea"
        }
    }
    auth = gitea.GiteaAuth {
        token_path = "~/.provisioning/secrets/gitea-token.enc"
        username = "provisioning"
    }
}

# Or remote Gitea instance
_gitea_remote = gitea.GiteaConfig {
    mode = "remote"
    remote = gitea.RemoteGitea {
        enabled = True
        url = "https://gitea.example.com"
        api_url = "https://gitea.example.com/api/v1"
    }
    auth = gitea.GiteaAuth {
        token_path = "~/.provisioning/secrets/gitea-token.enc"
        username = "myuser"
    }
}
```plaintext

#### 2. Create Gitea Access Token

For local Gitea:

1. Start Gitea: `provisioning gitea start`
2. Open <http://localhost:3000>
3. Register admin account
4. Go to Settings → Applications → Generate New Token
5. Save token to encrypted file:

```bash
# Create encrypted token file
echo "your-gitea-token" | sops --encrypt /dev/stdin > ~/.provisioning/secrets/gitea-token.enc
```plaintext

For remote Gitea:

1. Login to your Gitea instance
2. Generate personal access token
3. Save encrypted as above

#### 3. Verify Setup

```bash
# Check Gitea status
provisioning gitea status

# Validate token
provisioning gitea auth validate

# Show current user
provisioning gitea user
```plaintext

---

## Workspace Git Integration

### Initialize Workspace with Git

When creating a new workspace, enable git integration:

```bash
# Initialize new workspace with Gitea
provisioning workspace init my-workspace --git --remote gitea

# Or initialize existing workspace
cd workspace_my-workspace
provisioning gitea workspace init . my-workspace --remote gitea
```plaintext

This will:

1. Initialize git repository in workspace
2. Create repository on Gitea (`workspaces/my-workspace`)
3. Add remote origin
4. Push initial commit

### Clone Existing Workspace

```bash
# Clone from Gitea
provisioning workspace clone workspaces/my-workspace ./workspace_my-workspace

# Or using full identifier
provisioning workspace clone my-workspace ./workspace_my-workspace
```plaintext

### Push/Pull Changes

```bash
# Push workspace changes
cd workspace_my-workspace
provisioning workspace push --message "Updated infrastructure configs"

# Pull latest changes
provisioning workspace pull

# Sync (pull + push)
provisioning workspace sync
```plaintext

### Branch Management

```bash
# Create branch
provisioning workspace branch create feature-new-cluster

# Switch branch
provisioning workspace branch switch feature-new-cluster

# List branches
provisioning workspace branch list

# Delete branch
provisioning workspace branch delete feature-new-cluster
```plaintext

### Git Status

```bash
# Get workspace git status
provisioning workspace git status

# Show uncommitted changes
provisioning workspace git diff

# Show staged changes
provisioning workspace git diff --staged
```plaintext

---

## Workspace Locking

Distributed locking prevents concurrent modifications to workspaces using Gitea issues.

### Lock Types

- **read**: Multiple readers allowed, blocks writers
- **write**: Exclusive access, blocks all other locks
- **deploy**: Exclusive access for deployments

### Acquire Lock

```bash
# Acquire write lock
provisioning gitea lock acquire my-workspace write \
    --operation "Deploying servers" \
    --expiry "2025-10-06T14:00:00Z"

# Output:
# ✓ Lock acquired for workspace: my-workspace
#   Lock ID: 42
#   Type: write
#   User: provisioning
```plaintext

### Check Lock Status

```bash
# List locks for workspace
provisioning gitea lock list my-workspace

# List all active locks
provisioning gitea lock list

# Get lock details
provisioning gitea lock info my-workspace 42
```plaintext

### Release Lock

```bash
# Release lock
provisioning gitea lock release my-workspace 42
```plaintext

### Force Release Lock (Admin)

```bash
# Force release stuck lock
provisioning gitea lock force-release my-workspace 42 \
    --reason "Deployment failed, releasing lock"
```plaintext

### Automatic Locking

Use `with-workspace-lock` for automatic lock management:

```nushell
use lib_provisioning/gitea/locking.nu *

with-workspace-lock "my-workspace" "deploy" "Server deployment" {
    # Your deployment code here
    # Lock automatically released on completion or error
}
```plaintext

### Lock Cleanup

```bash
# Cleanup expired locks
provisioning gitea lock cleanup
```plaintext

---

## Extension Publishing

Publish taskservs, providers, and clusters as versioned releases on Gitea.

### Publish Extension

```bash
# Publish taskserv
provisioning gitea extension publish \
    ./extensions/taskservs/database/postgres \
    1.2.0 \
    --release-notes "Added connection pooling support"

# Publish provider
provisioning gitea extension publish \
    ./extensions/providers/aws_prov \
    2.0.0 \
    --prerelease

# Publish cluster
provisioning gitea extension publish \
    ./extensions/clusters/buildkit \
    1.0.0
```plaintext

This will:

1. Validate extension structure
2. Create git tag (if workspace is git repo)
3. Package extension as `.tar.gz`
4. Create Gitea release
5. Upload package as release asset

### List Published Extensions

```bash
# List all extensions
provisioning gitea extension list

# Filter by type
provisioning gitea extension list --type taskserv
provisioning gitea extension list --type provider
provisioning gitea extension list --type cluster
```plaintext

### Download Extension

```bash
# Download specific version
provisioning gitea extension download postgres 1.2.0 \
    --destination ./extensions/taskservs/database

# Extension is downloaded and extracted automatically
```plaintext

### Extension Metadata

```bash
# Get extension information
provisioning gitea extension info postgres 1.2.0
```plaintext

### Publishing Workflow

```bash
# 1. Make changes to extension
cd extensions/taskservs/database/postgres

# 2. Update version in kcl/kcl.mod
# 3. Update CHANGELOG.md

# 4. Commit changes
git add .
git commit -m "Release v1.2.0"

# 5. Publish to Gitea
provisioning gitea extension publish . 1.2.0
```plaintext

---

## Service Management

### Start/Stop Gitea

```bash
# Start Gitea (local mode)
provisioning gitea start

# Stop Gitea
provisioning gitea stop

# Restart Gitea
provisioning gitea restart
```plaintext

### Check Status

```bash
# Get service status
provisioning gitea status

# Output:
# Gitea Status:
#   Mode: local
#   Deployment: docker
#   Running: true
#   Port: 3000
#   URL: http://localhost:3000
#   Container: provisioning-gitea
#   Health: ✓ OK
```plaintext

### View Logs

```bash
# View recent logs
provisioning gitea logs

# Follow logs
provisioning gitea logs --follow

# Show specific number of lines
provisioning gitea logs --lines 200
```plaintext

### Install Gitea Binary

```bash
# Install latest version
provisioning gitea install

# Install specific version
provisioning gitea install 1.21.0

# Custom install directory
provisioning gitea install --install-dir ~/bin
```plaintext

---

## API Reference

### Repository Operations

```nushell
use lib_provisioning/gitea/api_client.nu *

# Create repository
create-repository "my-org" "my-repo" "Description" true

# Get repository
get-repository "my-org" "my-repo"

# Delete repository
delete-repository "my-org" "my-repo" --force

# List repositories
list-repositories "my-org"
```plaintext

### Release Operations

```nushell
# Create release
create-release "my-org" "my-repo" "v1.0.0" "Release Name" "Notes"

# Upload asset
upload-release-asset "my-org" "my-repo" 123 "./file.tar.gz"

# Get release
get-release-by-tag "my-org" "my-repo" "v1.0.0"

# List releases
list-releases "my-org" "my-repo"
```plaintext

### Workspace Operations

```nushell
use lib_provisioning/gitea/workspace_git.nu *

# Initialize workspace git
init-workspace-git "./workspace_test" "test" --remote "gitea"

# Clone workspace
clone-workspace "workspaces/my-workspace" "./workspace_my-workspace"

# Push changes
push-workspace "./workspace_my-workspace" "Updated configs"

# Pull changes
pull-workspace "./workspace_my-workspace"
```plaintext

### Locking Operations

```nushell
use lib_provisioning/gitea/locking.nu *

# Acquire lock
let lock = acquire-workspace-lock "my-workspace" "write" "Deployment"

# Release lock
release-workspace-lock "my-workspace" $lock.lock_id

# Check if locked
is-workspace-locked "my-workspace" "write"

# List locks
list-workspace-locks "my-workspace"
```plaintext

---

## Troubleshooting

### Gitea Not Starting

**Problem**: `provisioning gitea start` fails

**Solutions**:

```bash
# Check Docker status
docker ps

# Check if port is in use
lsof -i :3000

# Check Gitea logs
provisioning gitea logs

# Remove old container
docker rm -f provisioning-gitea
provisioning gitea start
```plaintext

### Token Authentication Failed

**Problem**: `provisioning gitea auth validate` returns false

**Solutions**:

```bash
# Verify token file exists
ls ~/.provisioning/secrets/gitea-token.enc

# Test decryption
sops --decrypt ~/.provisioning/secrets/gitea-token.enc

# Regenerate token in Gitea UI
# Save new token
echo "new-token" | sops --encrypt /dev/stdin > ~/.provisioning/secrets/gitea-token.enc
```plaintext

### Cannot Push to Repository

**Problem**: Git push fails with authentication error

**Solutions**:

```bash
# Check remote URL
cd workspace_my-workspace
git remote -v

# Reconfigure remote with token
git remote set-url origin http://username:token@localhost:3000/org/repo.git

# Or use SSH
git remote set-url origin git@localhost:workspaces/my-workspace.git
```plaintext

### Lock Already Exists

**Problem**: Cannot acquire lock, workspace already locked

**Solutions**:

```bash
# Check active locks
provisioning gitea lock list my-workspace

# Get lock details
provisioning gitea lock info my-workspace 42

# If lock is stale, force release
provisioning gitea lock force-release my-workspace 42 --reason "Stale lock"
```plaintext

### Extension Validation Failed

**Problem**: Extension publishing fails validation

**Solutions**:

```bash
# Check extension structure
ls -la extensions/taskservs/myservice/
# Required:
# - schemas/manifest.toml
# - schemas/*.ncl (main schema file)

# Verify manifest.toml format
cat extensions/taskservs/myservice/schemas/manifest.toml

# Should have:
# [package]
# name = "myservice"
# version = "1.0.0"
```plaintext

### Docker Volume Permissions

**Problem**: Gitea Docker container has permission errors

**Solutions**:

```bash
# Fix data directory permissions
sudo chown -R 1000:1000 ~/.provisioning/gitea

# Or recreate with correct permissions
provisioning gitea stop --remove
rm -rf ~/.provisioning/gitea
provisioning gitea start
```plaintext

---

## Best Practices

### Workspace Management

1. **Always use locking** for concurrent operations
2. **Commit frequently** with descriptive messages
3. **Use branches** for experimental changes
4. **Sync before operations** to get latest changes

### Extension Publishing

1. **Follow semantic versioning** (MAJOR.MINOR.PATCH)
2. **Update CHANGELOG.md** for each release
3. **Test extensions** before publishing
4. **Use prerelease flag** for beta versions

### Security

1. **Encrypt tokens** with SOPS
2. **Use private repositories** for sensitive workspaces
3. **Rotate tokens** regularly
4. **Audit lock history** via Gitea issues

### Performance

1. **Cleanup expired locks** periodically
2. **Use shallow clones** for large workspaces
3. **Archive old releases** to reduce storage
4. **Monitor Gitea resources** for local deployments

---

## Advanced Usage

### Custom Gitea Deployment

Edit `docker-compose.yml`:

```yaml
services:
  gitea:
    image: gitea/gitea:1.21
    environment:
      - GITEA__server__DOMAIN=gitea.example.com
      - GITEA__server__ROOT_URL=https://gitea.example.com
      # Add custom settings
    volumes:
      - /custom/path/gitea:/data
```plaintext

### Webhooks Integration

Configure webhooks for automated workflows:

```kcl
import provisioning.gitea as gitea

_webhook = gitea.GiteaWebhook {
    url = "https://provisioning.example.com/api/webhooks/gitea"
    events = ["push", "pull_request", "release"]
    secret = "webhook-secret"
}
```plaintext

### Batch Extension Publishing

```bash
# Publish all taskservs with same version
provisioning gitea extension publish-batch \
    ./extensions/taskservs \
    1.0.0 \
    --extension-type taskserv
```plaintext

---

## References

- **Gitea API Documentation**: <https://docs.gitea.com/api/>
- **Nickel Schema**: `/Users/Akasha/project-provisioning/provisioning/schemas/gitea.ncl`
- **API Client**: `/Users/Akasha/project-provisioning/provisioning/core/nulib/lib_provisioning/gitea/api_client.nu`
- **Workspace Git**: `/Users/Akasha/project-provisioning/provisioning/core/nulib/lib_provisioning/gitea/workspace_git.nu`
- **Locking**: `/Users/Akasha/project-provisioning/provisioning/core/nulib/lib_provisioning/gitea/locking.nu`

---

**Version:** 1.0.0
**Maintained By:** Provisioning Team
**Last Updated:** 2025-10-06
