Skip to content

Latest commit

 

History

History
831 lines (629 loc) · 21.3 KB

File metadata and controls

831 lines (629 loc) · 21.3 KB

Gemini CLI Training Labs

This document contains hands-on exercises for learning to use Gemini CLI for professional development workflows.

Table of Contents

  1. Lab 1: Getting Started and Project Creation
  2. Lab 2: Code Exploration
  3. Lab 3: GEMINI.md and Context Management
  4. Lab 4: Test Generation
  5. Lab 5: Configuration and Safety
  6. Lab 6: Advanced Features
  7. Lab 7: Optional Team Adoption Module

Prerequisites

  • Gemini CLI installed: npm install -g @google/gemini-cli (version 0.37.x or later)
  • API key set: export GEMINI_API_KEY="your-key"
  • Git installed and configured
  • Development environment for Python, JavaScript, or Java
  • Docker (optional, for sandbox mode)

Heads-up: Plan Mode is the default

As of Gemini CLI 0.34, plan is the default approval mode. When you launch gemini, it will draft a plan before executing any tool calls. For most of these labs you'll want to accept the plan (press Shift+Tab to cycle modes, or accept each step) before commands run. If a step feels "stuck," check whether Gemini is waiting for plan approval.

To skip plan mode entirely for a lab step:

gemini --approval-mode default       # per-tool approval
gemini --approval-mode auto_edit     # auto-approve edits

Also note the keyboard shortcut change in 0.37: Ctrl+G opens the external editor (it used to be Ctrl+X).


Lab 1: Getting Started and Project Creation

Duration: 25 minutes

Goal: Get comfortable with Gemini CLI while building a task manager application from scratch

Setup

  1. Create a new empty directory:

    mkdir my-task-manager && cd my-task-manager
  2. Initialize git:

    git init
  3. Start Gemini CLI:

    gemini

Exercises

  1. Explore the interface:

    What are your main capabilities for helping with development?
    

    Then explore the available commands:

    /help
    

    Review the slash commands before diving in.

  2. Project foundation:

    Create a Node.js task manager application with:
    - A Task class with id, title, description, status, and dueDate
    - Functions to add, remove, update, and list tasks
    - JSON file storage for persistence
    - A simple CLI interface using readline
    
  3. Check your work with shell integration:

    !ls -la
    

    Use shell commands to see what Gemini created. Observe how the output is displayed.

  4. Enhanced functionality (Stretch Goal - if time permits):

    Add these features to the task manager:
    - Filter tasks by status (pending, in-progress, completed)
    - Sort tasks by due date
    - Search tasks by title or description
    - Colored console output for different statuses
    
  5. Check context and memory:

    /memory show
    

    See what context Gemini has loaded about your project.

  6. Testing:

    Create comprehensive tests for the task manager using Jest:
    - Unit tests for all Task class methods
    - Integration tests for file persistence
    - Edge cases like empty lists, invalid inputs
    
  7. Documentation:

    Create a README.md with:
    - Project description and features
    - Installation instructions
    - Usage examples with sample output
    - API documentation for developers
    
  8. Keyboard shortcuts: Before moving to git, try these shortcuts:

    • Ctrl+L to clear the screen
    • Ctrl+Y to toggle YOLO mode (observe the indicator change)
    • Ctrl+Y again to toggle back to default mode
  9. Git workflow:

    Help me create a proper commit history:
    1. Commit the initial project structure
    2. Create a feature branch for "priority-levels"
    3. Add priority (low, medium, high) to tasks
    4. Create a commit message following conventional commits
    

Expected Outcomes

  • Understand Gemini CLI's conversational interface
  • Know essential slash commands and keyboard shortcuts
  • Build a functional application from scratch
  • Experience iterative development with AI assistance
  • Practice the full development cycle: concept → code → tests → docs
  • Be comfortable with shell integration

← Back to Table of Contents


Lab 2: Code Exploration

Duration: 15 minutes

Goal: Use Gemini CLI to understand complex codebases

Setup

Choose one of the provided exercise projects:

  • exercises/python/weather-app (Flask application)
  • exercises/javascript/task-manager (Node.js CLI app)
  • exercises/java/bookstore-api (Spring Boot REST API)

Navigate to the project directory and start Gemini CLI.

Exercises

  1. Project overview:

    Analyze the architecture of this project and explain the main components.
    Reference @./src/ (or @. for a flat project like the Python weather app) to examine the source code.
    
  2. Technology identification:

    What frameworks, libraries, and tools does this project use?
    Check @./package.json or @./pom.xml for dependencies.
    
  3. Entry point discovery:

    Show me the main entry point of this application and trace the
    initialization flow.
    
  4. File reference practice:

    Explain how the main routing logic handles incoming requests.
    - Python: @app/routes/weather.py
    - Java: @src/main/java/com/example/bookstore/controller/BookController.java
    - JavaScript: @src/taskManager.js
    
  5. Architecture documentation:

    Create a Mermaid diagram showing the main components and their
    relationships in this project.
    
  6. Web search integration:

    Search the web for best practices for [Flask/Express/Spring Boot]
    application structure and compare with this project.
    

Expected Outcomes

  • Quickly understand unfamiliar codebases
  • Master file references with @ syntax
  • Leverage web search for current best practices
  • Generate visual documentation

← Back to Table of Contents


Lab 3: GEMINI.md and Context Management

Duration: 20 minutes

Goal: Set up effective project context using GEMINI.md files

Setup

Continue with the project from Lab 2, or start fresh in a new directory.

Exercises

  1. Generate initial GEMINI.md:

    /init
    

    Review the generated file and understand its structure.

  2. Customize the context:

    Update the GEMINI.md to include:
    - Our team's coding standards (PEP 8 for Python, or equivalent)
    - Preferred testing frameworks and patterns
    - Current sprint focus: implementing caching
    - Code review checklist items
    
  3. Test context loading:

    /memory show
    

    Verify your customizations are loaded.

  4. Create hierarchical context:

    # Create subdirectory-specific context
    mkdir -p src/api

    Then ask Gemini:

    Create a GEMINI.md file for the src/api/ directory that specifies:
    - All API endpoints should return JSON
    - Use consistent error response format
    - Include request validation
    - Document all endpoints with OpenAPI comments
    
  5. Global context setup:

    Help me create a global GEMINI.md at ~/.gemini/GEMINI.md with:
    - My preferred coding style (concise, well-documented)
    - Common libraries I use across projects
    - My Git commit message format preferences
    
  6. Modular imports:

    Break the project GEMINI.md into modular files:
    - Create docs/coding-standards.md
    - Create docs/api-guidelines.md
    - Update GEMINI.md to import these using @docs/coding-standards.md syntax
    
  7. Refresh and verify:

    /memory refresh
    /memory show
    

    Confirm all contexts are properly loaded.

Expected Outcomes

  • Create effective GEMINI.md files
  • Understand hierarchical context loading
  • Use modular imports for maintainability
  • Set up global and project-specific context

← Back to Table of Contents


Lab 4: Test Generation

Duration: 15 minutes

Goal: Generate comprehensive test suites with Gemini CLI

Setup

Use the project from previous labs or choose a new exercise project with existing source code.

Exercises

  1. Unit test generation:

    Create unit tests for a chosen file:
    - Java: @exercises/java/bookstore-api/src/main/java/com/example/bookstore/service/BookService.java using JUnit 5
    - JavaScript: @exercises/javascript/task-manager/src/taskManager.js using Jest
    - Python: @exercises/python/weather-app/app/services/weather_service.py using pytest
    
    Requirements:
    - Tests for all public methods
    - Edge cases (empty inputs, null values)
    - Mocking of external dependencies
    
  2. Test coverage analysis:

    Analyze @./src/models/ and identify which classes and methods
    are missing test coverage. Generate tests to fill the gaps.
    
  3. Edge case discovery:

    What edge cases should I test for the user authentication flow?
    List them and generate test cases for each.
    
  4. Integration tests:

    Create integration tests for the API endpoints in @./src/routes/
    that test the full request-response cycle with test fixtures.
    
  5. Test data generation:

    Generate realistic test fixtures for:
    - 10 sample users with varied data
    - 20 sample tasks with different statuses and dates
    - Edge cases like unicode characters, very long strings
    Save as JSON files in tests/fixtures/
    
  6. Run and verify:

    # Execute the generated tests
    !pytest -v
    # Or for Node.js:
    !npm test

    Then ask:

    Analyze the test results and fix any failing tests.
    

Expected Outcomes

  • Generate comprehensive test suites
  • Identify and test edge cases
  • Create realistic test fixtures
  • Iterate on failing tests

← Back to Table of Contents


Lab 5: Configuration and Safety

Duration: 20 minutes

Goal: Configure Gemini CLI for safe, efficient workflows

Setup

Create a test project for experimenting with configuration:

mkdir config-test && cd config-test
git init
echo "# Config Test" > README.md

Exercises

  1. Explore settings:

    /settings
    

    Review the current settings interface.

  2. Create project settings:

    Create a .gemini/settings.json file with:
    - Use the current nested schema sections (general/ui/tools)
    - Vim mode enabled
    - Checkpointing enabled
    - Sandbox mode disabled
    - Hide tips set to true
    
  3. Tool restrictions:

    Update settings.json to:
    - Exclude the run_shell_command tool for safety
    - Use tools.allowed to only allow read_file, write_file, and glob tools
    
  4. Test sandbox mode:

    # Start in sandbox mode
    gemini --sandbox

    Then try:

    Create a file called test.txt with "Hello World"
    

    Observe how sandbox mode affects file operations.

  5. Checkpointing practice:

    Enable checkpointing in settings, then:

    Create a complex file structure:
    - src/index.js with a basic Express server
    - src/routes/api.js with sample routes
    - package.json with dependencies
    

    Then:

    /restore
    

    View available checkpoints.

  6. Approval modes:

    # Try different approval modes
    gemini --approval-mode auto_edit

    Request a file edit and observe auto-approval behavior.

    # Compare with YOLO mode
    gemini --approval-mode yolo

    Try creating files and observe the difference.

  7. Environment variables:

    Create a .gemini/.env file with:
    GEMINI_MODEL=gemini-2.5-flash
    
    Then restart Gemini and verify the model change.
    

Expected Outcomes

  • Configure project-specific settings
  • Understand sandbox and checkpointing
  • Practice different approval modes
  • Set up environment-based configuration

← Back to Table of Contents


Lab 6: Advanced Features

Duration: 30 minutes

Goal: Master MCP servers, extensions, custom commands, and session management

Part A: Session Management (5 minutes)

  1. Create a session: Start an interactive session and do some work:

    gemini
    > Create a simple Python calculator module with add, subtract, multiply, divide
    > Add error handling for division by zero
    > Create tests for the calculator
    

    Exit with Ctrl+D

  2. List sessions:

    gemini --list-sessions
  3. Resume session:

    gemini --resume

    Continue where you left off:

    Add a power function to the calculator and update the tests
    
  4. Session browser and rewind: In interactive mode, run:

    /resume
    /rewind
    

    Review what each workflow enables and when you'd prefer one over the other.

Part B: Custom Commands (10 minutes)

  1. Create a review command:

    mkdir -p ~/.gemini/commands

    Then create the file ~/.gemini/commands/review.toml with:

    description = "Review code for security, performance, and best practices"
    
    prompt = """
    Review the provided code for:
    - Security vulnerabilities (injection, credentials, validation)
    - Performance issues (inefficient algorithms, resource leaks)
    - Best practices and code quality
    
    Provide findings with severity levels:
    - CRITICAL: Must fix before deployment
    - WARNING: Should fix soon
    - INFO: Consider improving
    
    {{args}}
    """
  2. Test the custom command: In a new session, create a file to review:

    Create a file called sample.py with some intentionally problematic code:
    - SQL injection vulnerability
    - Hardcoded credentials
    - Inefficient loop
    

    Then use your command:

    /review @./sample.py
    
  3. Create a docs command: Create the file ~/.gemini/commands/docs.toml with:

    description = "Generate documentation for code"
    
    prompt = """
    Generate comprehensive documentation for the provided code:
    - Function signatures with parameters and return types
    - Usage examples
    - Markdown format suitable for a README
    
    {{args}}
    """

Part C: MCP Server Integration (10 minutes)

  1. List available MCP servers:

    gemini mcp list
  2. Configure Firecrawl MCP:

    
    Help me configure the Firecrawl MCP server in .gemini/settings.json:
    
    - Use the @modelcontextprotocol/server-firecrawl package
    
    - Set up my FIRECRAWL_API_KEY from environment
    
    - Ensure it allows scraping web content
    
    
  3. Test MCP integration:

If configured:

```

Use the Firecrawl MCP to search for "latest features of Gemini 3 Pro" and summarize the findings.

```
  1. Explore MCP tools:

    What MCP tools are available in this session?
    Show me an example of using one of them.
    
  2. Prompt quality booster:

    /prompt-suggest
    

    Ask Gemini for 3 stronger variants of your last MCP prompt and compare the results.

Part D: Output Formats (5 minutes)

  1. JSON output for scripting:

    gemini -o json "List the files in current directory and describe each"

    Observe the structured output format.

  2. Stream JSON:

    gemini -o stream-json "Explain the concept of microservices architecture"

    Watch the real-time streaming output.

  3. Piped workflows:

    echo "What are the top 5 Python web frameworks?" | gemini -o json

Part E: Extensions (optional, 5 minutes)

  1. List extensions:

    gemini --list-extensions
  2. Create a simple extension:

    Help me create a basic extension at ~/.gemini/extensions/my-tools/
    that adds a custom tool for formatting code.
    Include the gemini-extension.json configuration.
    
  3. Enable specific extensions:

    gemini -e my-tools "Format the code in @./src/"

Expected Outcomes

After completing this lab:

  • Manage and resume sessions effectively
  • Create reusable custom commands
  • Configure and use MCP servers
  • Use output formats for automation
  • Understand the extension system

← Back to Table of Contents


Lab 7: Optional Team Adoption Module

Duration: 30-45 minutes (optional / take-home)

Goal: Practice production-oriented workflows for authentication strategy, governance, skills/MCP controls, and CI automation.

Part A: Authentication Strategy (10 minutes)

  1. Compare auth options: Create a short matrix in AUTH_NOTES.md that compares:

    • Login with Google
    • GEMINI_API_KEY
    • Vertex AI with ADC
    • Service account credentials for CI

    Include when each is preferred and one drawback.

  2. Validate one non-default path: Choose one of these:

    • Vertex path (GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION)
    • API-key path (GEMINI_API_KEY)

    Then run:

    gemini --version
    gemini --list-sessions

    Confirm your environment is usable with the chosen auth setup.

Part B: Governance and Safety Controls (10-15 minutes)

  1. Create a team-safe project settings file: In .gemini/settings.json, configure:

    • general.defaultApprovalMode to auto_edit or plan
    • tools.sandbox enabled
    • general.checkpointing.enabled set to true

    Then create a policy.toml file alongside it with a deny rule for run_shell_command and launch Gemini with gemini --policy policy.toml. (The legacy tools.exclude key still works but is deprecated as of Gemini CLI 0.30 — the Policy Engine is the forward path.)

  2. Inspect hooks and policy behavior: In interactive mode, run:

    /hooks list
    /policies list
    

    Ask Gemini to explain what each active control does and which risks it reduces.

Part C: Skills + MCP Hardening (10-15 minutes)

  1. Skills lifecycle drill: In interactive mode:

    /skills list
    /skills disable <one-skill-name>
    /skills enable <one-skill-name>
    

    Observe how discoverable skills change.

  2. MCP scoping exercise: Update one MCP server in .gemini/settings.json to:

    • Add includeTools for only the tools you need
    • Add excludeTools for at least one sensitive tool

    Then run:

    gemini mcp list

    In interactive mode:

    /mcp list
    /mcp refresh
    
  3. MCP resource prompt practice: If your MCP server exposes resources, use one URI with @... in a prompt and summarize what changed versus a tool-only prompt.

Part D: CI/Automation Pattern (10 minutes)

  1. Create a repeatable automation check: Add a script snippet to automation_notes.md:

    gemini -o json "Review @./src/ for security issues" > review.json
    if gemini -o json "Summarize risk level in one sentence"; then
      echo "Gemini check completed"
    else
      echo "Gemini check failed" && exit 1
    fi
  2. Post-process output: Parse review.json with your preferred tool (jq, Node, Python) and extract one field for a simple pass/fail decision.

Expected Outcomes

After completing this optional lab:

  • Choose the right auth method for local, team, and CI contexts
  • Apply practical governance controls with settings, hooks, and policies
  • Restrict MCP/skills behavior to safer team defaults
  • Build a basic non-interactive Gemini CLI automation pattern

← Back to Table of Contents


Tips for Success

Effective Prompting

  • Be specific about what you want to achieve
  • Use file references (@path/to/file) for context
  • Iterate for complex tasks - don't try everything at once
  • Provide examples when the output format matters

Best Practices

  • Start with default approval mode, use YOLO after building trust
  • Enable checkpointing before risky operations
  • Keep GEMINI.md files updated with current project state
  • Commit regularly to have a safety net
  • Review all AI-generated code before accepting

Common Issues and Solutions

Issue: Gemini doesn't understand the project structure Solution: Create a comprehensive GEMINI.md with architecture details

Issue: Generated code doesn't match project style Solution: Add coding standards to your GEMINI.md

Issue: API rate limits Solution: Use Gemini 2.5 Flash for faster, cheaper operations

Issue: Context not loading Solution: Run /memory refresh and check file paths

Issue: MCP server not connecting Solution: Check server configuration in settings.json, then use gemini mcp list and /mcp refresh


Next Steps

After completing these labs:

  1. Practice daily: Use Gemini CLI for regular development tasks
  2. Customize: Build your personal GEMINI.md and command library
  3. Explore MCP: Set up servers for your common tools and services
  4. Share: Document workflows for your team
  5. Stay updated: Follow Gemini CLI releases for new features

Additional Resources