# Clean-Go CLI (cg)

A powerful CLI tool to generate Go Clean Architecture projects with gRPC. Scaffold complete Go applications following clean architecture principles.

[![npm version](https://img.shields.io/npm/v/clean-go-cli.svg)](https://www.npmjs.com/package/clean-go-cli)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Features

- 🚀 **Project Scaffolding** - Generate complete Go projects with clean architecture
- 📦 **Resource Generator** - Create gRPC CRUD resources with all layers (domain, infrastructure, usecases)
- ⚡ **Service Generator** - Add custom services to existing resources
- 🔐 **Authentication** - Generate JWT authentication module
- 🔑 **Add Auth to Resource** - Add authentication guards to existing resources
- �️ **Module Removal** - Clean removal of resources
- 📋 **List Resources** - View all generated resources

## Tech Stack

Generated projects use:

| Category | Technology |
|----------|------------|
| **gRPC** | [gRPC-Go](https://grpc.io/docs/languages/go/) - High-performance RPC framework |
| **ORM** | [GORM](https://gorm.io/) - Fantastic ORM library for Go |
| **Database** | PostgreSQL |
| **Validation** | [go-playground/validator](https://github.com/go-playground/validator) |
| **Config** | [godotenv](https://github.com/joho/godotenv) |
| **Logging** | [Zap](https://github.com/uber-go/zap) - Blazing fast structured logger |
| **UUID** | [google/uuid](https://github.com/google/uuid) |
| **JWT** | [golang-jwt](https://github.com/golang-jwt/jwt) |

## Installation

### npm (Recommended)

```bash
npm install -g clean-go-cli
```

### npx (No Installation)

```bash
npx clean-go-cli <command>
```

### From Source

```bash
git clone https://github.com/yourusername/clean-go.git
cd clean-go
npm install -g .
```

## Commands

### Create New Project

```bash
cg new
# or
cg n
```

Creates a complete Go project with:
- Clean architecture structure
- gRPC API setup with Protocol Buffers
- Database configuration (PostgreSQL + GORM)
- Docker support
- Makefile with common commands

### Generate Resource (CRUD)

```bash
cg g res
# or
cg generate resource
```

Generates a complete gRPC CRUD resource with:
- Domain layer (DTOs, Models, Repository Interface)
- Infrastructure layer (Entity, Repository, gRPC Service)
- Use cases layer (Business logic)
- Proto definitions (.proto files)

### Generate Service

```bash
cg g s
# or
cg generate service
```

Adds a custom gRPC service method to an existing resource:
1. Select an existing module
2. Enter service name (e.g., `getByEmail`, `activate`)
3. Generates action and validation files
4. Updates repository, usecase, gRPC service, and proto

### Generate Authentication Module

```bash
cg g au
# or
cg generate auth
```

Generates a complete JWT authentication system:
- gRPC auth service (Login/Register)
- JWT token generation and validation
- gRPC interceptors for authentication
- Auth guards for protecting services
- Password hashing utilities

### Add Authentication to Resource

```bash
cg g au
# Select existing resource
```

Adds authentication guards to an existing resource's gRPC service.

### Remove Resource

```bash
cg rm res
# or
cg remove resource
```

Removes a resource and all its associated files.

### List Resources

```bash
cg ls
# or
cg list
```

Lists all generated resources in the project.

### Help & Version

```bash
cg --help    # Show help
cg -h        # Show help
cg --version # Show version
cg -v        # Show version
```

## Project Structure

```
project-name/
├── src/
│   ├── domain/                          # Domain layer
│   │   ├── dtos/                        # Data transfer objects
│   │   ├── logger/                      # Logger interface
│   │   ├── models/                      # Domain models
│   │   └── repositories/                # Repository interfaces
│   │
│   ├── infrastructure/                  # Infrastructure layer
│   │   ├── common/
│   │   │   ├── auth/                    # Authentication utilities
│   │   │   ├── filter/                  # Exception filters
│   │   │   ├── guards/                  # Auth guards
│   │   │   └── interceptors/            # gRPC interceptors
│   │   ├── config/
│   │   │   ├── database/                # Database configuration
│   │   │   └── environment/             # Environment configuration
│   │   ├── entities/                    # Database entities (GORM)
│   │   ├── grpc/
│   │   │   ├── interceptors/            # gRPC interceptors
│   │   │   └── services/                # gRPC service implementations
│   │   ├── logger/                      # Logger implementation
│   │   ├── repositories/                # Repository implementations
│   │   └── usecases-proxy/              # Usecases proxy (DI)
│   │
│   ├── usecases/                        # Application usecases
│   ├── _proto/                          # Protocol buffer definitions
│   ├── main.go                          # Application entry point
│   └── app.go                           # Application module
│
├── .env.example                         # Environment template
├── .gitignore
├── Dockerfile
├── docker-compose.yml
├── Makefile
├── go.mod
└── README.md
```

## Generated Resource Files

When you generate a resource (e.g., `user`):

```
src/
├── domain/
│   ├── dtos/user.dto.go                 # User DTOs
│   ├── models/user.model.go             # User domain model
│   └── repositories/user.interface.go   # Repository interface
│
├── infrastructure/
│   ├── entities/user.entity.go          # GORM entity
│   ├── grpc/services/user/user.go       # gRPC service implementation
│   ├── repositories/user/user.go        # Repository implementation
│   └── usecases-proxy/user.proxy.go     # Usecase proxy
│
├── usecases/user.usecase.go             # Business logic
└── _proto/user.proto                    # Protocol buffer definitions
```

## Quick Start

```bash
# 1. Create a new project
cg new
# Enter: my-api
# Enter: github.com/myuser/my-api

# 2. Navigate to project
cd my-api

# 3. Install dependencies
go mod tidy

# 4. Set up environment
cp .env.example .env
# Edit .env with your database credentials

# 5. Generate proto files
make proto

# 6. Run the application
make run

# 7. Generate a resource
cg g res
# Enter: user

# 8. Regenerate proto and restart
make proto
make run
```

## gRPC Services

Each resource generates a gRPC service with the following RPC methods:

| Method | Description |
|--------|-------------|
| `Create` | Create new record |
| `Update` | Update existing record |
| `Delete` | Delete record by ID |
| `LoadAll` | Get all records (paginated) |
| `LoadById` | Get single record by ID |

### Pagination Parameters

| Parameter | Description | Default |
|-----------|-------------|---------|
| `page` | Page number | 1 |
| `page_size` | Items per page | 10 |
| `search` | Search term | - |
| `sort_by` | Sort field | created_at |
| `sort_order` | Sort direction (asc/desc) | desc |

## Makefile Commands

```bash
make build          # Build the application
make run            # Run the application
make dev            # Run with hot reload (air)
make test           # Run tests
make test-coverage  # Run tests with coverage
make proto          # Generate protobuf files
make clean          # Clean build files
make fmt            # Format code
make lint           # Run linter
make tidy           # Tidy dependencies
make docker-build   # Build Docker image
make docker-up      # Start with Docker Compose
make docker-down    # Stop Docker containers
make migrate-up     # Run migrations
make migrate-down   # Rollback migrations
```

## Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `APP_NAME` | Application name | my-app |
| `APP_ENV` | Environment | development |
| `APP_DEBUG` | Debug mode | true |
| `GRPC_HOST` | gRPC server host | 0.0.0.0 |
| `GRPC_PORT` | gRPC server port | 50051 |
| `DB_HOST` | Database host | localhost |
| `DB_PORT` | Database port | 5432 |
| `DB_USER` | Database user | postgres |
| `DB_PASSWORD` | Database password | - |
| `DB_NAME` | Database name | - |
| `DB_SSL_MODE` | SSL mode | disable |
| `JWT_SECRET` | JWT signing secret | - |
| `JWT_EXPIRY` | JWT expiry duration | 24h |

## Authentication

After generating the auth module (`cg g au`), you can:

### Get Authenticated User

```go
// In gRPC service method
user, err := s.getAuthUser(ctx)
if err != nil {
    return nil, err
}
// Use user.ID, user.Email, user.Role
```

### Require Role

```go
// Check if user has required role
if err := s.requireRole(ctx, "admin"); err != nil {
    return nil, err
}
```

### gRPC Interceptor

Authentication is handled via gRPC interceptors:

```go
// Server setup with auth interceptor
server := grpc.NewServer(
    grpc.UnaryInterceptor(interceptors.AuthInterceptor()),
)
```

## Docker Support

```bash
# Build and run with Docker Compose
docker-compose up -d

# View logs
docker-compose logs -f

# Stop containers
docker-compose down
```

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

MIT License - see the [LICENSE](LICENSE) file for details.

## Support

- 📖 [Documentation](https://github.com/yourusername/clean-go#readme)
- 🐛 [Issue Tracker](https://github.com/yourusername/clean-go/issues)
- 💬 [Discussions](https://github.com/yourusername/clean-go/discussions)
