npm package: @jorlex/ghgen
Description: GitHub Workflow Generator - CLI tool for automating GitHub Actions workflow creation and secrets management for Kubernetes deployments
Author: Alex Veros
Latest version: 2.1.0

# GHGen - GitHub Workflow Generator

[![npm version](https://badge.fury.io/js/@jorlex%2Fghgen.svg)](https://badge.fury.io/js/@jorlex%2Fghgen)
[![Tests](https://img.shields.io/badge/tests-56%20passed-brightgreen)](https://github.com/alexveros/ghgen)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Automate GitHub Actions workflow creation and secrets management for Kubernetes deployments.

## Features

- **Interactive Wizard** - Step-by-step workflow generation
- **Secrets Management** - Upload secrets directly to GitHub
- **Multiple Templates** - Basic and advanced workflow types
- **Auto-configuration** - Smart detection of app settings
- **GitHub Integration** - Seamless GitHub CLI integration

## Installation

### From NPM (Recommended)

```bash
npm install -g @jorlex/ghgen
```

**Note:** Binary name is still `ghgen`, so you run commands with just `ghgen`.

### From Source

```bash
# Clone repository
git clone https://github.com/alexveros/ghgen.git
cd ghgen

# Install dependencies
npm install

# Link globally (for development)
npm link

# Or install system-wide
./install.sh
```

## Requirements

- **Node.js 14+**
- **Git**
- **GitHub CLI** (optional, but recommended for secrets upload)

Install GitHub CLI:
```bash
# macOS
brew install gh

# Ubuntu/Debian
sudo apt install gh

# Authenticate
gh auth login
```

## Usage

### Interactive Wizard

```bash
ghgen wizard
```

The wizard will guide you through:
1. **Application configuration** - name, port, replicas, health endpoint
2. **Workflow type** - K3s deployment with Traefik + cert-manager (with Discord notifications)
3. **Discord notifications** - Optional webhook for deployment status
4. **Environment variables** - Auto-detects and reads from `.env` file
5. **Resource limits** - Optional CPU & Memory limits
6. **Repository detection** - Auto-detects from git remote
7. **KUBECONFIG upload** - Optional auto-upload from `~/.kube/config`
8. **Automatic secrets upload** - Uploads all secrets to GitHub environment `production`

**Features:**
- ✅ Auto-read `.env` file
- ✅ Auto-categorize sensitive vs non-sensitive variables
- ✅ Auto-detect GitHub repository from git remote
- ✅ Generate K3s-ready workflow with Ingress + SSL
- ✅ Upload secrets to GitHub environment
- ✅ Automatic rollback on deployment failure

### Secrets Management

All secrets commands support **auto-detection** of the repository from your git remote. When inside a git repository with a GitHub remote, you can omit the `owner/repo` parameter.

#### Upload Secrets

**Upload to Environment (recommended):**
```bash
# Auto-detect repository, upload to production environment
ghgen secrets upload .env -e production

# Upload to staging environment
ghgen secrets upload .env -e staging

# Or specify repository manually
ghgen secrets upload owner/repo .env -e production
```

**Upload to Repository Secrets:**
```bash
# Auto-detect repository, upload to repository-level secrets
ghgen secrets upload .env

# Or specify repository manually
ghgen secrets upload owner/repo .env
```

**Note:**
- With `-e` flag: Secrets go to **Environment secrets** (production, staging, etc.)
- Without `-e` flag: Secrets go to **Repository secrets**
- Environments are auto-created if they don't exist

#### Add Single Secret

```bash
# Add to repository secrets
ghgen secrets add MY_SECRET "secret-value"

# Add to environment secrets
ghgen secrets add MY_SECRET "secret-value" -e production

# Or specify repository manually
ghgen secrets add owner/repo MY_SECRET "secret-value"
```

#### List Secrets

```bash
# List repository secrets
ghgen secrets list

# List environment secrets
ghgen secrets list -e production

# Or specify repository manually
ghgen secrets list owner/repo
```

#### Delete Secrets

**Delete Single Secret:**
```bash
# Delete from repository secrets
ghgen secrets delete MY_SECRET

# Delete from environment secrets
ghgen secrets delete MY_SECRET -e production

# Or specify repository manually
ghgen secrets delete owner/repo MY_SECRET
```

**Delete All Secrets:**
```bash
# Delete all repository secrets
ghgen secrets delete -a

# Delete all secrets from production environment
ghgen secrets delete -a -e production

# Or specify repository manually
ghgen secrets delete owner/repo -a
```

### Workflow Commands

**Create workflow from template:**
```bash
ghgen workflow create my-app

# With options
ghgen workflow create my-app \
  --template advanced \
  --namespace production \
  --port 8080
```

**List available templates:**
```bash
ghgen workflow list
```

**Validate workflow syntax:**
```bash
ghgen workflow validate .github/workflows/deploy.yml
```

### System Diagnostics

```bash
ghgen doctor
```

Checks:
- Node.js version
- Required tools (git, gh)
- GitHub CLI authentication
- Git repository status
- Workflow templates availability

## Workflow Template

### K3s Production Template
Production-ready deployment workflow for K3s clusters with Traefik and cert-manager.

**Features:**
- ✅ Build & Push to GitHub Container Registry (GHCR)
- ✅ Deploy to K3s with rolling updates (zero downtime)
- ✅ ClusterIP Service + Ingress (Traefik)
- ✅ Automatic SSL certificate via Let's Encrypt (cert-manager)
- ✅ ConfigMap for non-sensitive config
- ✅ Secrets for sensitive data
- ✅ Health checks (liveness & readiness probes)
- ✅ Automatic rollback on deployment failure
- ✅ Discord notifications (optional)
- ✅ Infrastructure prerequisites checking
- ✅ Resource limits (optional)

**Prerequisites:**
- K3s cluster running on VPS
- Traefik ingress controller installed
- cert-manager installed
- Let's Encrypt ClusterIssuer configured

## Examples

### Quick Start

```bash
# 1. Create .env file with your app secrets
cat > .env << EOF
DB_HOST=your-db-host
DB_PORT=5432
DB_USERNAME=dbuser
DB_PASSWORD=secretpassword
JWT_SECRET=your-jwt-secret
DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/xxx/yyy
EOF

# 2. Run wizard
ghgen wizard

# 3. Answer prompts
#    - App name: my-app
#    - Namespace: my-app
#    - Port: 3000
#    - Domain: app.example.com
#    - Use .env file: Yes
#    - Repository: auto-detected from git
#    - Upload KUBECONFIG: Yes
#    ...

# 4. Wizard will:
#    ✓ Generate workflow at .github/workflows/deploy.yml
#    ✓ Categorize env vars (ConfigMap vs Secrets)
#    ✓ Upload all secrets to GitHub environment 'production'
#    ✓ Upload KUBECONFIG

# 5. Manually add GHCR_PAT token (one-time setup)
#    Create token at: https://github.com/settings/tokens
#    Scopes: write:packages, read:packages
gh secret set GHCR_PAT -R owner/repo
# Note: GHCR_PAT goes to REPOSITORY secrets, not environment

# 6. Commit and push
git add .github/workflows/deploy.yml
git commit -m "feat: add K3s deployment workflow"
git push origin main

# 7. Watch deployment
gh run watch
```

### Upload Secrets Manually (without wizard)

Create `.env` file:
```bash
DB_HOST=localhost
DB_PORT=5432
DB_PASSWORD=secret
JWT_SECRET=your-secret
KUBECONFIG="$(cat ~/.kube/config)"
DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...
```

Upload to GitHub environment:
```bash
ghgen secrets upload your-username/your-repo .env -e production
```

## Configuration

### GitHub Secrets Setup

The workflow uses **two types of secrets** for better security:

#### 1. Repository Secrets (Infrastructure-level)

These are stored at: **Repository → Settings → Secrets and variables → Actions → Repository secrets**

**Required:**

1. **`KUBECONFIG`** - Kubernetes configuration file
   - **How to get:**
     - SSH to your VPS: `ssh user@your-vps-ip`
     - Get kubeconfig: `cat ~/.kube/config`
     - Or for K3s: `sudo cat /etc/rancher/k3s/k3s.yaml`
     - Copy the entire YAML content
   - **Add to GitHub:**
     ```bash
     # Via CLI
     gh secret set KUBECONFIG < ~/.kube/config

     # Or manually via Web UI:
     # Repository → Settings → Secrets → New repository secret
     # Name: KUBECONFIG
     # Value: [paste YAML content]
     ```
   - **Note:** Wizard can auto-upload this for you

2. **`GHCR_PAT`** - GitHub Personal Access Token for Container Registry
   - Required for pushing Docker images to GitHub Container Registry
   - **How to create:**
     1. Go to: https://github.com/settings/tokens
     2. Click **"Generate new token (classic)"**
     3. Give it a name: e.g., "GHCR Deploy Token"
     4. Set expiration (recommended: No expiration for production)
     5. Select scopes:
        - ✅ **`write:packages`** - Upload packages to GitHub Package Registry
        - ✅ **`read:packages`** - Download packages from GitHub Package Registry
        - ✅ **`delete:packages`** - Delete packages (optional)
     6. Click **"Generate token"**
     7. **Copy the token immediately** (format: `ghp_xxxxxxxxxxxxxxxxxxxx`)
     8. Add to repository:
        ```bash
        # Via CLI
        gh secret set GHCR_PAT
        # Paste token when prompted

        # Or manually:
        # Repository → Settings → Secrets → New repository secret
        # Name: GHCR_PAT
        # Value: ghp_your_token_here
        ```

#### 2. Environment Secrets (Application-level)

These are stored at: **Repository → Settings → Environments → production → Environment secrets**

The wizard automatically uploads your `.env` variables here and categorizes them:

**Uploaded from your `.env` file:**
- `DB_HOST`, `DB_PORT`, `DB_USERNAME`, `DB_PASSWORD`, `DB_DATABASE` - Database credentials
- `JWT_ACCESS_SECRET`, `JWT_REFRESH_SECRET` - JWT secrets
- `SENDGRID_API_KEY` - Email service
- `CLOUDINARY_*` - Image/media service credentials
- `DISCORD_WEBHOOK_URL` - Discord notifications
- Any other environment variables your app needs

**Auto-categorization by wizard:**
- **ConfigMap** (non-sensitive): `DB_HOST`, `DB_PORT`, `DB_USERNAME`, `NODE_ENV`, etc.
- **Secrets** (sensitive): Anything with `PASSWORD`, `SECRET`, `KEY`, `TOKEN`, `PRIVATE`, etc.

**Why separate?**
- Repository secrets = Infrastructure access (cluster, registry)
- Environment secrets = Application config (database, APIs)
- Better security and easier to manage per environment (production/staging)

## Development

```bash
# Install dependencies
npm install

# Run locally
npm start

# Or use directly
node src/index.js wizard
```

## Testing

GHGen has comprehensive test coverage using Jest.

```bash
# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Generate coverage report
npm run test:coverage

# Run with verbose output
npm run test:verbose
```

**Test Coverage:**
- 56 tests passing
- 64%+ code coverage
- Unit, integration, and CLI tests
- All test suites: 7 passed

See [TESTING.md](TESTING.md) for detailed testing documentation.

## Troubleshooting

**Error: GitHub CLI not authenticated**
```bash
gh auth login
```

**Error: Cannot find workflow templates**
- Make sure you're in the project root directory
- Templates should be in `../workflows/` directory

**Secrets upload fails**
- Check GitHub CLI authentication: `gh auth status`
- Verify repository permissions
- Ensure repository name is correct (owner/repo format)

## License

MIT