npm package: @gringow/gringow-cli
Description: Command-line interface for Gringow AI-powered translation tool
Author: Renato Gaspar
Latest version: 0.4.0

# @gringow/gringow-cli

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

Command-line interface for Gringow AI-powered translation tool. Translate text and manage translation caches directly from your terminal using multiple LLM providers.

## Features

- 🌐 **Instant translations** from command line
- 💾 **Cache management** - list, show, rebuild, delete
- 🔀 **Cache merge** - combine two cache files with interactive conflict resolution (v0.3.0)
- ⚙️ **Configuration tools** - init, validate, show
- 🎨 **Colored output** using picocolors
- 🔄 **Smart caching** - reuses existing translations
- 🛠️ **Interactive prompts** for destructive operations

## Installation

### Global Installation (Recommended)

```bash
# Using pnpm
pnpm add -g @gringow/gringow-cli

# Using npm
npm install -g @gringow/gringow-cli

# Using yarn
yarn global add @gringow/gringow-cli
```

### Use Without Installing (npx)

```bash
npx @gringow/gringow-cli translate "Hello world"
```

### Install from Source

```bash
git clone https://github.com/rntgspr/gringow.git
cd gringow
pnpm install && pnpm run build
cd gringow-cli && pnpm link --global
```

## Quick Start

```bash
# Install globally
pnpm add -g @gringow/gringow-cli

# Initialize configuration (optional)
gringow config init

# Translate text
gringow translate "Hello world"

# View help
gringow --help
```

## Commands

### Translation

The `translate` command translates text using configured LLM providers. Translations are cached automatically.

#### Basic Usage

```bash
# Translate a phrase
gringow translate "Hello world"

# Output:
# ✓ Translation found in cache
# Original:
#   Hello world
# Translations:
#   pt-BR: Olá mundo
#   fr-CA: Bonjour le monde
```

#### Options

```bash
# Output specific language only
gringow translate "Hello world" --language pt-BR
# Output: Olá mundo

# JSON output (full cache payload)
gringow translate "Hello world" --json
# Output: { "original": "Hello world", "translation": {...} }

# Verbose mode (shows cache ID)
gringow translate "Hello world" --verbose
# Output includes: Cache ID: grw_abc123def456
```

#### Advanced Examples

```bash
# Translate with variables (use quotes)
gringow translate "Welcome back, {name}!"

# Translate longer text
gringow translate "The quick brown fox jumps over the lazy dog" -l es-ES

# Force new translation (clear cache first, then translate)
gringow cache delete grw_abc123 --force && gringow translate "Hello world"
```

### Cache Management

Manage your translation cache with comprehensive commands.

#### List Cache Entries

```bash
# List cached translations (default: first 10)
gringow cache list

# Output:
# Found 25 cached items
# Cached Translations (showing 10 of 25):
# ────────────────────────────────────────
# 1. ID: grw_abc123
#    Original: Hello world
#    Languages: pt-BR, fr-CA

# Show more items
gringow cache list --limit 50

# JSON output
gringow cache list --json
```

#### Show Specific Cache Item

```bash
# View details of a cached translation
gringow cache show grw_abc123

# Output:
# Cache item loaded
# ID: grw_abc123
# Original: Hello world
# Translations:
#   pt-BR: Olá mundo
#   fr-CA: Bonjour le monde

# JSON format
gringow cache show grw_abc123 --json
```

#### Rebuild Translation

Re-translate a cached entry using current LLM configuration.

```bash
# Rebuild specific cache entry
gringow cache rebuild grw_abc123

# Rebuild cache entry (text mode still prints all languages)
gringow cache rebuild grw_abc123 --language pt-BR

# Rebuild with JSON output
gringow cache rebuild grw_abc123 --json
```

**Use cases**:
- Updated LLM configuration (switched providers)
- Improved prompt engineering
- Language additions in config

#### Delete Cache Entry

```bash
# Delete single item (interactive confirmation)
gringow cache delete grw_abc123

# Force delete without confirmation
gringow cache delete grw_abc123 --force
```

#### Clear All Cache

```bash
# Clear entire cache (interactive confirmation)
gringow cache clear

# Force clear without confirmation
gringow cache clear --force
```

> ⚠️ **Warning**: Cache operations are destructive. Use `--force` carefully.

#### Merge Cache Files

Merge two translation cache files into one, with interactive conflict resolution. Available since **v0.3.0**.

```bash
# Merge source into target and save to output.json
gringow cache merge source.json target.json -o merged.json

# Load source from a remote URL
gringow cache merge https://cdn.example.com/i18n.json target.json -o merged.json

# Preview merge without saving
gringow cache merge source.json target.json -o merged.json --dry-run

# Show detailed conflict table
gringow cache merge source.json target.json -o merged.json --verbose

# Output result as JSON (implies --dry-run)
gringow cache merge source.json target.json -o merged.json --json
```

**Conflict resolution** – when the same cache ID exists in both files with different translations, the CLI prompts you interactively for each conflict:

| Option | Description |
|---|---|
| `S` Use Source | Overwrite with source file entry |
| `T` Use Target | Keep the target file entry |
| `M` Merge languages | Combine translation keys from both (only when languages differ) |
| `P` Skip | Exclude the entry from the result |
| `SA/TA/MA` | Apply that choice to **all** remaining conflicts |

Identical entries (same original and translations) are auto-resolved without prompting.
An automatic backup (`.bak`) of the output file is created if it already exists.

### Configuration

Manage Gringow configuration files and settings.

#### Initialize Config

```bash
# Create gringow.config.js in current directory
gringow config init

# Overwrite existing config
gringow config init --force
```

**Generated file example**:
```js
// gringow.config.js
export default {
  defaultLanguage: 'pt-BR',
  llm: {
    provider: 'openai',
    apiKey: process.env.OPENAI_API_KEY,
    model: 'gpt-4o-mini',
  },
  languages: ['pt-BR', 'fr-CA'],
  sourceLanguage: 'en-US',
}
```

#### Show Configuration

```bash
# Display merged configuration (defaults + local overrides)
gringow config show

# JSON output
gringow config show --json
```

#### Validate Configuration

```bash
# Check config validity (Zod schema validation)
gringow config validate

# Validates:
# - Required API keys for anthropic/gemini
# - Language codes format
# - LLM provider options
# - Cache paths
```

## Usage Workflows

### Basic Translation Workflow

```bash
# 1. Initialize config (optional, uses defaults otherwise)
gringow config init

# 2. Translate text
gringow translate "Welcome to Gringow"

# 3. View cache
gringow cache list
```

### Multi-Provider Setup

```bash
# 1. Create config with Gemini
echo 'export default {
  llm: { provider: "gemini", apiKey: process.env.GEMINI_API_KEY, model: "gemini-2.0-flash" },
  languages: ["es-ES", "ja-JP", "de-DE"]
}' > gringow.config.js

# 2. Validate configuration
gringow config validate

# 3. Translate
gringow translate "Good morning"
```

### Cache Maintenance

```bash
# Check cache size
gringow cache list | head -1

# Review translations for specific language
gringow cache list --json | jq '.[] | select(.translation["pt-BR"])'

# Rebuild outdated translations
gringow cache rebuild grw_old_entry_id

# Clean up unused cache entries
gringow cache delete grw_unused_id --force
```

## Configuration

The CLI uses [cosmiconfig](https://github.com/cosmiconfig/cosmiconfig) to load `gringow.config.{js,mjs,json}` from your project root. Initialize with:

```bash
gringow config init
```

### Configuration Options

All options from [@gringow/gringow](https://www.npmjs.com/package/@gringow/gringow) are supported:

- **`llm.provider`**: provider ID (e.g., `'openai'`, `'anthropic'`, `'gemini'`, `'ollama'`)
- **`llm.apiKey`**: API key for providers that require authentication
- **`llm.model`**: Model name/ID for selected provider
- **`languages`**: Array of target language codes (e.g., `['pt-BR', 'fr-CA']`)
- **`sourceLanguage`**: Source language code (default: `'en-US'`)
- **`defaultLanguage`**: Runtime fallback language
- **`cache.dir`**: Cache directory path (default: `'./gringow'`)
- **`cache.file`**: Cache filename (default: `'gringow.json'`)

See the [core package README](https://github.com/rntgspr/gringow/tree/main/gringow#configuration) for complete options.

## How It Works

1. **Input Processing**: Text is hashed using content-based hashing
2. **Cache Lookup**: Checks `./gringow/gringow.json` for existing translation
3. **LLM Query**: If not cached, calls configured LLM provider
4. **Cache Write**: Stores translation (even if `cache.write` is `false` in config)
5. **Output**: Displays colored, formatted results

The CLI always writes to cache regardless of `cache.write` config to ensure translations persist for other tools.

## Command Reference

```bash
gringow translate <text>              # Translate text
  -l, --language <code>               # Output specific language
  -j, --json                          # JSON output
  -v, --verbose                       # Show cache ID

gringow cache list                    # List cached translations
  -l, --limit <number>                # Number of items (default: 10)
  -j, --json                          # JSON output

gringow cache show <id>               # Show cache item details
  -j, --json                          # JSON output

gringow cache rebuild <id>            # Re-translate cached entry
  -l, --language <code>               # Accepted option (does not filter text output)
  -j, --json                          # JSON output

gringow cache delete <id>             # Delete cache entry
  --force                             # Skip confirmation

gringow cache clear                   # Clear entire cache
  --force                             # Skip confirmation

gringow cache merge <source> <target> # Merge two cache files (v0.3.0)
  -o, --output <path>                 # Output file path (required)
  -d, --dry-run                       # Preview without saving
  -v, --verbose                       # Detailed conflict table
  -j, --json                          # Output result as JSON (implies --dry-run)

gringow config init                   # Create config file
  --force                             # Overwrite existing

gringow config show                   # Display configuration
  -j, --json                          # JSON output

gringow config validate               # Validate configuration

gringow --help                        # Show help
gringow --version                     # Show version
```

## Dependencies

- **[Commander.js](https://github.com/tj/commander.js)** - CLI framework
- **[picocolors](https://github.com/alexeyraspopov/picocolors)** - Terminal colors (used by Vite)
- **[inquirer](https://github.com/SBoudrias/Inquirer.js)** - Interactive prompts
- **[@gringow/gringow](https://www.npmjs.com/package/@gringow/gringow)** - Core translation library

## Development

```bash
# Install dependencies
pnpm install

# Build the CLI
pnpm run build

# Development mode (with tsx)
pnpm run dev

# Watch mode
pnpm run watch
```

## Testing

See [TESTING.md](./TESTING.md) for comprehensive testing instructions.

## Related Packages

Gringow provides a complete ecosystem for AI-powered translation:

- **[@gringow/gringow](https://www.npmjs.com/package/@gringow/gringow)** - Core translation library
- **[@gringow/gringow-vite](https://www.npmjs.com/package/@gringow/gringow-vite)** - Vite plugin for build-time extraction
- **[@gringow/gringow-react](https://www.npmjs.com/package/@gringow/gringow-react)** - React hooks and components
- **[@gringow/gringow-shadow](https://www.npmjs.com/package/@gringow/gringow-shadow)** - Web Component layer
- **[@gringow/gringow-nextjs](https://www.npmjs.com/package/@gringow/gringow-nextjs)** - Next.js plugin (experimental)

## Resources

- [Documentation](https://gringow.dev)
- [GitHub Repository](https://github.com/rntgspr/gringow)
- [Core Package README](https://github.com/rntgspr/gringow/tree/main/gringow)

## License

MIT © [Renato Gaspar](https://github.com/rntgspr)

---

**Need Help?** Open an issue on [GitHub](https://github.com/rntgspr/gringow/issues)