正在学习
6.3 Working with Git and Version Control
Requires: pip install anthropic gitpython
Usage: python git_claude_commit.py
import os
from git import Repo
from anthropic import Anthropic
Load the repository and Anthropic client
REPO_PATH = os.getcwd() # assumes script runs inside a Git repo
repo = Repo(REPO_PATH)
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
def get_staged_diff():
"""Return a unified diff of staged changes."""
diff = repo.git.diff('--cached')
return diff.strip() if diff else None
def summarize_changes(diff_text):
"""Ask Claude to summarize the diff in plain English."""
if not diff_text:
return "No staged changes detected."
prompt = (
"You are Claude Code. Summarize the following git diff clearly, "
"explaining what was added, modified, or deleted. "
"Focus on intent and functionality, not syntax.\n\n"
f"{diff_text}"
)
response = client.messages.create(
model="claude-3-5-sonnet-20240620",
max_tokens=250,
messages=[{"role": "user", "content": prompt}],
)
return response.content[0].text
if name == "main":
diff_text = get_staged_diff()
summary = summarize_changes(diff_text)
print("\nClaude Summary of Staged Changes:\n")
print(summary)
How it works:
1. The script checks your current Git repository for staged changes.
2. It sends the diff content to Claude Code for summarization.
3. Claude analyzes the diff and returns a natural-language explanation of what’s being changed and why.
Example output:
Claude Summary of Staged Changes:
The commit adds input validation to the user registration API by checking for
duplicate emails before database insertion. It also introduces a new helper
function is_valid_email in utils.py and refactors the test suite to cover
edge cases for invalid domains.
You can now paste that summary directly into your commit message:
git commit -m "feat(auth): add email validation and improve test coverage"
Handling Merge Conflicts
Claude can also help you reason through merge conflicts, rather than just patching code mechanically.
Suppose you have a conflict in `app/routes.py`. You can feed the conflict section to Claude in the terminal:
git diff --merge | claude ask "Resolve this merge conflict by preserving both new routes and maintaining existing middleware."
Claude will return the unified, logically consistent version of the file, explaining what it merged and why. This is especially helpful when two developers modify related parts of the same logic.
Clarification Table
| Task | Claude’s Role | Example Command or Use | Outcome |
| --- | --- | --- | --- |
| Summarizing staged changes | Generate concise summaries | `python git_claude_commit.py` | Clear explanation of what changed |
| Commit message generation | Suggest context-aware commit messages | “Claude, create a commit message for this diff.” | Semantic, readable commit logs |
| Merge conflict resolution | Logical merging based on intent | `claude ask "resolve this conflict logically"` | Merged file consistent with both branches |
| Reviewing PRs | Analyze diffs between branches | “Claude, review all changes from feature/api-auth.” | Readable review report |
| Explaining historical commits | Translate git logs into natural language | “Claude, summarize commits from last week.” | Simplified project history overview |
Integrating Claude Code with Git enhances both speed and understanding in your development lifecycle. Instead of treating version control as a mechanical record, it becomes a living conversation between you, your codebase, and your AI collaborator. Claude translates diffs into intent, highlights risks, and produces human-readable insights that streamline collaboration and onboarding.
As you move forward, the next section will show how to automate these tasks, allowing Claude to assist automatically during pre-commit, post-merge, or CI validation phases for a smoother, more intelligent workflow.
## 6.4 Managing Cost and Token Usage
Every interaction with Claude Code has a measurable cost — not just in currency, but also in tokens, which represent the computational units used to process and generate text. As projects scale, understanding how Claude consumes tokens becomes crucial for managing both performance and budget. Developers who treat token usage as part of their engineering discipline achieve faster iterations, lower costs, and more predictable results. This section explains how to measure, monitor, and optimize token consumption while maintaining response quality across different workflows.
Concept Development
A token is a fragment of text (often a few characters or part of a word) that Claude uses to interpret and generate responses. Both your prompt (input) and response (output) contribute to total token usage. Larger prompts and verbose outputs cost more, so efficiency is about providing the right amount of context and asking for the right level of detail.
Claude Code provides several levers to control cost:
1. Model selection: Smaller models (like Claude 3 Haiku) handle lightweight tasks cheaply, while larger models (Claude 3.5 Sonnet or Claude 3 Opus) excel at complex reasoning.
2. Prompt length management: Trimming unnecessary history, redundant explanations, or repeated code blocks lowers input tokens without losing context.
3. Output constraints: Explicitly instructing Claude to limit the length of its answer reduces output tokens.
4. Session caching: Reusing concise summaries or reference snippets instead of re-pasting the same content helps maintain continuity at minimal cost.
By tracking token usage programmatically, you can strike a balance between cost and completeness while maintaining code accuracy and reasoning depth.
Hands-On Example: Tracking and Optimizing Tokens
Let’s create a short Python script that sends a prompt to Claude Code and reports exactly how many tokens were consumed. This will help you understand how different prompts affect cost.
# token_tracker.py
练习题
What is the primary purpose of the script in the given source material?
Which function in the script is responsible for obtaining the staged diff?
What model is used by the script to summarize the git diff?
What are the key steps involved in summarizing changes with Claude Code according to the script?
The script can automatically resolve merge conflicts in Git.
The script uses environment variables to securely store the Anthropic API key.
The function that asks Claude to summarize the diff is called ___.
The script uses the ___ method to send the prompt to Claude Code.
Explain how the script handles the case when there are no staged changes.
What is the purpose of the max_tokens parameter in the client.messages.create call?
When using the script to summarize Git changes with Claude, which of the following is a critical step to ensure secure API key handling?
summarize_changes functionWhich of the following are benefits of using Claude Code with Git in a collaborative environment? (Select all that apply)
The script can directly resolve merge conflicts by merging text without understanding the underlying logic.
To avoid exceeding rate limits when using Claude Code with Git, the script should implement ___ logic that waits before resending requests after hitting a rate limit.
登录后解锁笔记、知识点解析、AI 问答
立即登录