코드 예제
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 "✅ 테스트 생성 완료!"
통합 예제
Gemini CLI를 다른 도구 및 워크플로와 통합
GitHub Actions 워크플로
GitHub Actions와의 CI/CD 통합
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);