代码示例
实用的代码示例和模板,帮助您充分利用 Gemini CLI。从基本用法到高级自动化和集成模式。
基础使用
开始使用 Gemini CLI 的简单示例
简单聊天
与 Gemini 开始基本对话
bash代码
# 启动交互式聊天
gemini chat
# 询问单个问题
gemini ask "什么是机器学习?"
# 使用特定模型询问
gemini ask "解释量子计算" --model gemini-pro
文件分析
使用 AI 辅助分析代码文件
bash代码
# 分析单个文件
gemini analyze src/main.js
# 分析多个文件
gemini analyze src/*.js --type code-review
# 获取代码建议
gemini analyze package.json --suggest-improvements
配置管理
基本配置管理
bash代码
# 查看当前配置
gemini config list
# 设置默认模型
gemini config set model gemini-pro
# 设置温度
gemini config set temperature 0.7
# 重置为默认值
gemini config reset
自动化脚本
自动化开发任务的脚本
代码审查脚本
自动化拉取请求的代码审查
bash代码
#!/bin/bash
# code-review.sh - 自动化代码审查脚本
# 获取更改的文件
CHANGED_FILES=\$(git diff --name-only HEAD~1)
echo "🔍 开始自动化代码审查..."
for file in $CHANGED_FILES; do
if [[ $file == *.js || $file == *.ts || $file == *.py ]]; then
echo "📝 审查中: $file"
# 分析文件
gemini analyze "$file" \
--type code-review \
--prompt "审查此代码的错误、性能问题和最佳实践" \
--output review-$file.md
fi
done
echo "✅ 代码审查完成!查看 review-*.md 文件"
文档生成器
从代码生成文档
bash代码
#!/bin/bash
# generate-docs.sh - 自动生成文档
echo "📚 生成文档中..."
# 生成 API 文档
gemini analyze src/api/*.js \
--prompt "生成包含示例的综合 API 文档" \
--output docs/api.md
# 生成 README
gemini ask "基于代码库为此项目创建 README.md" \
--context src/ \
--output README.md
# 生成更新日志
git log --oneline --since="1 month ago" | \
gemini ask "将这些 git 提交转换为更新日志" \
--output CHANGELOG.md
echo "✅ 文档生成完成!"
测试生成器
自动生成单元测试
bash代码
#!/bin/bash
# generate-tests.sh - 自动生成单元测试
SOURCE_DIR="src"
TEST_DIR="tests"
echo "🧪 生成单元测试中..."
find $SOURCE_DIR -name "*.js" -o -name "*.ts" | while read file; do
# 获取相对路径
rel_path=\$\{file#\$SOURCE_DIR/\}
test_file="\$TEST_DIR/\$\{rel_path%.*\}.test.\$\{file##*.\}"
echo "📝 为以下文件生成测试: $file"
gemini analyze "$file" \
--prompt "生成包含边界情况的综合单元测试" \
--template jest \
--output "$test_file"
done
echo "✅ 测试生成完成!"
集成示例
与其他工具和工作流的集成
GitHub Actions 工作流
CI/CD 与 GitHub Actions 集成
yaml代码
name: AI 代码审查
on:
pull_request:
types: [opened, synchronize]
jobs:
ai-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: 设置 Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: 安装 Gemini CLI
run: npm install -g @google/generative-ai-cli
- name: 配置 Gemini CLI
run: |
gemini config set api-key \$\{\{ secrets.GEMINI_API_KEY \}\}
gemini config set model gemini-pro
- name: 获取更改的文件
id: changed-files
run: |
echo "files=\$(git diff --name-only HEAD~1 | tr '\n' ' ')" >> $GITHUB_OUTPUT
- name: AI 代码审查
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: 评论 PR
uses: actions/github-script@v6
with:
script: |
const fs = require('fs');
const reviews = fs.readdirSync('.').filter(f => f.startsWith('review-'));
let comment = '## 🤖 AI 代码审查\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 扩展
自定义 VS Code 扩展集成
javascript代码
// extension.js - Gemini CLI 的 VS Code 扩展
const vscode = require('vscode');
const { exec } = require('child_process');
function activate(context) {
// 命令:解释代码
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('请选择要解释的代码');
return;
}
// 显示进度
vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: "使用 Gemini 解释代码中...",
cancellable: false
}, async () => {
return new Promise((resolve, reject) => {
exec(`echo "${text}" | gemini ask "解释这段代码"`,
(error, stdout, stderr) => {
if (error) {
vscode.window.showErrorMessage(`错误: ${error.message}`);
reject(error);
return;
}
// 在新文档中显示解释
vscode.workspace.openTextDocument({
content: stdout,
language: 'markdown'
}).then(doc => {
vscode.window.showTextDocument(doc);
resolve();
});
});
});
});
}
);
// 命令:生成测试
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 "生成单元测试" --output "${testPath}"`,
(error, stdout, stderr) => {
if (error) {
vscode.window.showErrorMessage(`错误: ${error.message}`);
return;
}
vscode.window.showInformationMessage(`测试已生成: ${testPath}`);
vscode.workspace.openTextDocument(testPath).then(doc => {
vscode.window.showTextDocument(doc);
});
});
}
);
context.subscriptions.push(explainCommand, testCommand);
}
function deactivate() {}
module.exports = { activate, deactivate };
Docker 集成
在容器中使用 Gemini CLI
dockerfile代码
# Dockerfile - Gemini CLI 容器
FROM node:18-alpine
# 安装 Gemini CLI
RUN npm install -g @google/generative-ai-cli
# 设置工作目录
WORKDIR /app
# 复制项目文件
COPY . .
# 设置环境变量
ENV GEMINI_API_KEY=""
# 创建分析脚本
RUN echo '#!/bin/sh' > /usr/local/bin/analyze-project && \
echo 'gemini analyze src/ --output analysis.md' >> /usr/local/bin/analyze-project && \
chmod +x /usr/local/bin/analyze-project
# 默认命令
CMD ["analyze-project"]
高级用法
复杂场景和高级功能
自定义工具开发
为特定任务创建自定义工具
javascript代码
// custom-tools.js - 自定义工具定义
const tools = {
// 数据库查询工具
database_query: {
name: 'database_query',
description: '在数据库上执行 SQL 查询',
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.message}`;
}
}
},
// API 测试工具
api_test: {
name: 'api_test',
description: '测试 API 端点',
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 `状态: ${response.status}\n响应: ${data}`;
} catch (error) {
return `错误: ${error.message}`;
}
}
},
// 代码格式化工具
format_code: {
name: 'format_code',
description: '使用 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.message}`;
}
}
}
};
// 向 Gemini CLI 注册工具
Object.values(tools).forEach(tool => {
process.env.GEMINI_TOOLS = JSON.stringify([
...(JSON.parse(process.env.GEMINI_TOOLS || '[]')),
tool
]);
});
module.exports = tools;
批量处理
批量处理多个文件或任务
bash代码
#!/bin/bash
# batch-process.sh - 使用 Gemini CLI 进行批量处理
BATCH_SIZE=5
CONCURRENT_JOBS=3
# 处理单个文件的函数
process_file() {
local file=$1
local task=$2
echo "🔄 处理中: $file"
case $task in
"translate")
gemini ask "将此代码注释翻译为英文" \
--file "$file" \
--output "${file%.js}.en.js"
;;
"optimize")
gemini analyze "$file" \
--prompt "优化此代码的性能" \
--output "${file%.js}.optimized.js"
;;
"document")
gemini analyze "$file" \
--prompt "添加综合的 JSDoc 注释" \
--output "${file%.js}.documented.js"
;;
esac
echo "✅ 完成: $file"
}
# 主批量处理函数
batch_process() {
local task=$1
shift
local files=("$@")
echo "🚀 开始批量处理: $task"
echo "📁 要处理的文件: ${#files[@]}"
# 分批处理文件
for ((i=0; i<${#files[@]}; i+=BATCH_SIZE)); do
batch=("${files[@]:i:BATCH_SIZE}")
echo "📦 处理批次 $((i/BATCH_SIZE + 1))"
# 限制并发处理批次
for file in "${batch[@]}"; do
(($(jobs -r | wc -l) >= CONCURRENT_JOBS)) && wait
process_file "$file" "$task" &
done
wait # 等待当前批次完成
done
echo "🎉 批量处理完成!"
}
# 使用示例
case $1 in
"translate")
batch_process "translate" src/**/*.js
;;
"optimize")
batch_process "optimize" src/**/*.js
;;
"document")
batch_process "document" src/**/*.js
;;
*)
echo "用法: $0 {translate|optimize|document}"
exit 1
;;
esac
插件系统
创建可扩展的插件架构
javascript代码
// plugin-system.js - 插件系统示例
const { GeminiCLI } = require('@google/generative-ai-cli');
class PluginManager {
constructor() {
this.cli = new GeminiCLI();
this.plugins = new Map();
}
// 注册插件
registerPlugin(plugin) {
if (!plugin.name || !plugin.version) {
throw new Error('插件必须有名称和版本');
}
this.plugins.set(plugin.name, plugin);
// 注册插件命令
if (plugin.commands) {
Object.entries(plugin.commands).forEach(([cmd, handler]) => {
this.cli.registerCommand(`${plugin.name}:${cmd}`, handler);
});
}
// 注册插件工具
if (plugin.tools) {
plugin.tools.forEach(tool => {
this.cli.registerTool(tool);
});
}
console.log(`✅ 插件 ${plugin.name} v${plugin.version} 已注册`);
}
// 获取插件信息
getPlugin(name) {
return this.plugins.get(name);
}
// 列出所有插件
listPlugins() {
return Array.from(this.plugins.values());
}
}
// 示例插件:代码质量检查器
const codeQualityPlugin = {
name: 'code-quality',
version: '1.0.0',
description: '代码质量检查插件',
commands: {
'check': async (args) => {
const files = args.files || ['src/'];
console.log(`🔍 检查代码质量: ${files.join(', ')}`);
// 实现代码质量检查逻辑
return '代码质量检查完成';
},
'metrics': async (args) => {
console.log('📊 生成代码指标...');
// 实现代码指标生成逻辑
return {
complexity: 'low',
maintainability: 'high',
coverage: '85%'
};
}
},
tools: [
{
name: 'complexity_analyzer',
description: '分析代码复杂度',
parameters: {
file: { type: 'string', required: true }
},
execute: async ({ file }) => {
// 实现复杂度分析
return `文件 ${file} 的复杂度: 中等`;
}
}
]
};
// 使用示例
async function main() {
const manager = new PluginManager();
// 注册插件
manager.registerPlugin(codeQualityPlugin);
// 使用插件命令
const result = await manager.cli.executeCommand('code-quality:check', {
files: ['src/main.js', 'src/utils.js']
});
console.log('检查结果:', result);
// 列出所有插件
console.log('已安装的插件:', manager.listPlugins());
}
main().catch(console.error);