Code Examples

Practical code examples and templates to help you get the most out of Gemini CLI. From basic usage to advanced automation and integration patterns.

Basic Usage

Simple examples to get started with Gemini CLI

Simple Chat

Start a basic conversation with Gemini

bashCode
# Start interactive chat
gemini chat

# Ask a single question
gemini ask "What is machine learning?"

# Ask with specific model
gemini ask "Explain quantum computing" --model gemini-pro

File Analysis

Analyze code files with AI assistance

bashCode
# Analyze a single file
gemini analyze src/main.js

# Analyze multiple files
gemini analyze src/*.js --type code-review

# Get code suggestions
gemini analyze package.json --suggest-improvements

Configuration

Basic configuration management

bashCode
# View current configuration
gemini config list

# Set default model
gemini config set model gemini-pro

# Set temperature
gemini config set temperature 0.7

# Reset to defaults
gemini config reset

Automation Scripts

Scripts for automating development tasks

Code Review Script

Automated code review for pull requests

bashCode
#!/bin/bash
# code-review.sh - Automated code review script

# Get changed files
CHANGED_FILES=$(git diff --name-only HEAD~1)

echo "πŸ” Starting automated code review..."

for file in $CHANGED_FILES; do
  if [[ $file == *.js || $file == *.ts || $file == *.py ]]; then
    echo "πŸ“ Reviewing: $file"
    
    # Analyze the file
    gemini analyze "$file" \
      --type code-review \
      --prompt "Review this code for bugs, performance issues, and best practices" \
      --output review-$file.md
  fi
done

echo "βœ… Code review complete! Check review-*.md files"

Documentation Generator

Generate documentation from code

bashCode
#!/bin/bash
# generate-docs.sh - Auto-generate documentation

echo "πŸ“š Generating documentation..."

# Generate API docs
gemini analyze src/api/*.js \
  --prompt "Generate comprehensive API documentation with examples" \
  --output docs/api.md

# Generate README
gemini ask "Create a README.md for this project based on the codebase" \
  --context src/ \
  --output README.md

# Generate changelog
git log --oneline --since="1 month ago" | \
  gemini ask "Convert these git commits into a changelog" \
  --output CHANGELOG.md

echo "βœ… Documentation generated!"

Test Generator

Generate unit tests automatically

bashCode
#!/bin/bash
# generate-tests.sh - Auto-generate unit tests

SOURCE_DIR="src"
TEST_DIR="tests"

echo "πŸ§ͺ Generating unit tests..."

find $SOURCE_DIR -name "*.js" -o -name "*.ts" | while read file; do
  # Get relative path
  rel_path=${file#$SOURCE_DIR/}
  test_file="$TEST_DIR/${rel_path%.*}.test.${file##*.}"

  echo "πŸ“ Generating tests for: $file"

  gemini analyze "$file" \
    --prompt "Generate comprehensive unit tests with edge cases" \
    --template jest \
    --output "$test_file"
done

echo "βœ… Test generation complete!"

Integration Examples

Integrate Gemini CLI with other tools and workflows

GitHub Actions Workflow

CI/CD integration with GitHub Actions

yamlCode
name: AI Code Review
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  ai-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
      
      - name: Install Gemini CLI
        run: npm install -g @google/generative-ai-cli
      
      - name: Configure Gemini CLI
        run: |
          gemini config set api-key ${{ secrets.GEMINI_API_KEY }}
          gemini config set model gemini-pro
      
      - name: Get changed files
        id: changed-files
        run: |
          echo "files=$(git diff --name-only HEAD~1 | tr '\n' ' ')" >> $GITHUB_OUTPUT
      
      - name: AI Code Review
        run: |
          for file in ${{ steps.changed-files.outputs.files }}; do
            if [[ $file == *.js || $file == *.ts || $file == *.py ]]; then
              gemini analyze "$file" \
                --type code-review \
                --output "review-$file.md"
            fi
          done
      
      - name: Comment PR
        uses: actions/github-script@v6
        with:
          script: |
            const fs = require('fs');
            const reviews = fs.readdirSync('.').filter(f => f.startsWith('review-'));
            
            let comment = '## πŸ€– AI Code Review\n\n';
            reviews.forEach(file => {
              const content = fs.readFileSync(file, 'utf8');
              comment += `### ${file}\n${content}\n\n`;
            });
            
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: comment
            });

VS Code Extension

Custom VS Code extension integration

javascriptCode
// extension.js - VS Code extension for Gemini CLI
const vscode = require('vscode');
const { exec } = require('child_process');

function activate(context) {
  // Command: Explain Code
  let explainCommand = vscode.commands.registerCommand(
    'gemini.explainCode', 
    async () => {
      const editor = vscode.window.activeTextEditor;
      if (!editor) return;

      const selection = editor.selection;
      const text = editor.document.getText(selection);
      
      if (!text) {
        vscode.window.showErrorMessage('Please select code to explain');
        return;
      }

      // Show progress
      vscode.window.withProgress({
        location: vscode.ProgressLocation.Notification,
        title: "Explaining code with Gemini...",
        cancellable: false
      }, async () => {
        return new Promise((resolve, reject) => {
          exec(`echo "${text}" | gemini ask "Explain this code"`, 
            (error, stdout, stderr) => {
              if (error) {
                vscode.window.showErrorMessage(`Error: ${error.message}`);
                reject(error);
                return;
              }
              
              // Show explanation in new document
              vscode.workspace.openTextDocument({
                content: stdout,
                language: 'markdown'
              }).then(doc => {
                vscode.window.showTextDocument(doc);
                resolve();
              });
            });
        });
      });
    }
  );

  // Command: Generate Tests
  let testCommand = vscode.commands.registerCommand(
    'gemini.generateTests',
    async () => {
      const editor = vscode.window.activeTextEditor;
      if (!editor) return;

      const filePath = editor.document.fileName;
      const testPath = filePath.replace(/\.(js|ts)$/, '.test.$1');

      exec(`gemini analyze "${filePath}" --prompt "Generate unit tests" --output "${testPath}"`,
        (error, stdout, stderr) => {
          if (error) {
            vscode.window.showErrorMessage(`Error: ${error.message}`);
            return;
          }
          
          vscode.window.showInformationMessage(`Tests generated: ${testPath}`);
          vscode.workspace.openTextDocument(testPath).then(doc => {
            vscode.window.showTextDocument(doc);
          });
        });
    }
  );

  context.subscriptions.push(explainCommand, testCommand);
}

function deactivate() {}

module.exports = { activate, deactivate };

Advanced Usage

Complex scenarios and advanced features

Custom Tool Development

Create custom tools for specific tasks

javascriptCode
// custom-tools.js - Custom tool definitions
const tools = {
  // Database query tool
  database_query: {
    name: 'database_query',
    description: 'Execute SQL queries on the database',
    parameters: {
      query: { type: 'string', required: true },
      database: { type: 'string', default: 'main' }
    },
    execute: async ({ query, database }) => {
      const db = require('./db-connection');
      try {
        const result = await db.query(query, database);
        return JSON.stringify(result, null, 2);
      } catch (error) {
        return `Error: ${error.message}`;
      }
    }
  },

  // API testing tool
  api_test: {
    name: 'api_test',
    description: 'Test API endpoints',
    parameters: {
      url: { type: 'string', required: true },
      method: { type: 'string', default: 'GET' },
      headers: { type: 'object', default: {} },
      body: { type: 'object', default: null }
    },
    execute: async ({ url, method, headers, body }) => {
      const fetch = require('node-fetch');
      try {
        const response = await fetch(url, {
          method,
          headers,
          body: body ? JSON.stringify(body) : undefined
        });
        
        const data = await response.text();
        return `Status: ${response.status}\nResponse: ${data}`;
      } catch (error) {
        return `Error: ${error.message}`;
      }
    }
  },

  // Code formatter tool
  format_code: {
    name: 'format_code',
    description: 'Format code using prettier',
    parameters: {
      code: { type: 'string', required: true },
      language: { type: 'string', default: 'javascript' }
    },
    execute: async ({ code, language }) => {
      const prettier = require('prettier');
      try {
        const formatted = prettier.format(code, {
          parser: language === 'typescript' ? 'typescript' : 'babel',
          semi: true,
          singleQuote: true,
          tabWidth: 2
        });
        return formatted;
      } catch (error) {
        return `Error: ${error.message}`;
      }
    }
  }
};

// Register tools with Gemini CLI
Object.values(tools).forEach(tool => {
  process.env.GEMINI_TOOLS = JSON.stringify([
    ...(JSON.parse(process.env.GEMINI_TOOLS || '[]')),
    tool
  ]);
});

module.exports = tools;

Batch Processing

Process multiple files or tasks in batch

bashCode
#!/bin/bash
# batch-process.sh - Batch processing with Gemini CLI

BATCH_SIZE=5
CONCURRENT_JOBS=3

# Function to process a single file
process_file() {
  local file=$1
  local task=$2
  
  echo "πŸ”„ Processing: $file"
  
  case $task in
    "translate")
      gemini ask "Translate this code comments to English" \
        --file "$file" \
        --output "${file%.js}.en.js"
      ;;
    "optimize")
      gemini analyze "$file" \
        --prompt "Optimize this code for performance" \
        --output "${file%.js}.optimized.js"
      ;;
    "document")
      gemini analyze "$file" \
        --prompt "Add comprehensive JSDoc comments" \
        --output "${file%.js}.documented.js"
      ;;
  esac
  
  echo "βœ… Completed: $file"
}

# Main batch processing function
batch_process() {
  local task=$1
  shift
  local files=("$@")
  
  echo "πŸš€ Starting batch processing: $task"
  echo "πŸ“ Files to process: ${#files[@]}"

  # Process files in batches
  for ((i=0; i<${#files[@]}; i+=BATCH_SIZE)); do
    batch=("${files[@]:i:BATCH_SIZE}")
    
    echo "πŸ“¦ Processing batch $((i/BATCH_SIZE + 1))"
    
    # Process batch with limited concurrency
    for file in "${batch[@]}"; do
      (($(jobs -r | wc -l) >= CONCURRENT_JOBS)) && wait
      process_file "$file" "$task" &
    done
    
    wait # Wait for current batch to complete
  done
  
  echo "πŸŽ‰ Batch processing complete!"
}

# Usage examples
case $1 in
  "translate")
    batch_process "translate" src/**/*.js
    ;;
  "optimize")
    batch_process "optimize" src/**/*.js
    ;;
  "document")
    batch_process "document" src/**/*.js
    ;;
  *)
    echo "Usage: $0 {translate|optimize|document}"
    exit 1
    ;;
esac

Need More Help?

Explore additional resources and documentation