Skip to main content

poly_mcp/modules/
git.rs

1use serde_json::{json, Value};
2use anyhow::{Result, Context as _};
3use git2::{Repository, StatusOptions, DiffOptions, BranchType, ObjectType};
4use std::path::Path;
5
6pub struct GitModule;
7
8impl GitModule {
9    pub fn new() -> Self {
10        Self
11    }
12
13    pub fn get_tools(&self) -> Vec<Value> {
14        vec![
15            json!({
16                "name": "git_status",
17                "description": "Get git repository status",
18                "inputSchema": {
19                    "type": "object",
20                    "properties": {
21                        "path": {
22                            "type": "string",
23                            "description": "Path to git repository (default: current directory)"
24                        }
25                    }
26                }
27            }),
28            json!({
29                "name": "git_diff",
30                "description": "Get diff of changes in repository",
31                "inputSchema": {
32                    "type": "object",
33                    "properties": {
34                        "path": {
35                            "type": "string",
36                            "description": "Path to git repository (default: current directory)"
37                        },
38                        "staged": {
39                            "type": "boolean",
40                            "description": "Show staged changes only (default: false)"
41                        },
42                        "file": {
43                            "type": "string",
44                            "description": "Specific file to diff"
45                        }
46                    }
47                }
48            }),
49            json!({
50                "name": "git_commit",
51                "description": "Create a git commit",
52                "inputSchema": {
53                    "type": "object",
54                    "properties": {
55                        "path": {
56                            "type": "string",
57                            "description": "Path to git repository (default: current directory)"
58                        },
59                        "message": {
60                            "type": "string",
61                            "description": "Commit message"
62                        },
63                        "author_name": {
64                            "type": "string",
65                            "description": "Author name"
66                        },
67                        "author_email": {
68                            "type": "string",
69                            "description": "Author email"
70                        }
71                    },
72                    "required": ["message"]
73                }
74            }),
75            json!({
76                "name": "git_branch",
77                "description": "List, create, or delete branches",
78                "inputSchema": {
79                    "type": "object",
80                    "properties": {
81                        "path": {
82                            "type": "string",
83                            "description": "Path to git repository (default: current directory)"
84                        },
85                        "action": {
86                            "type": "string",
87                            "enum": ["list", "create", "delete"],
88                            "description": "Action to perform (default: list)"
89                        },
90                        "name": {
91                            "type": "string",
92                            "description": "Branch name (for create/delete)"
93                        }
94                    }
95                }
96            }),
97            json!({
98                "name": "git_checkout",
99                "description": "Checkout a branch or commit",
100                "inputSchema": {
101                    "type": "object",
102                    "properties": {
103                        "path": {
104                            "type": "string",
105                            "description": "Path to git repository (default: current directory)"
106                        },
107                        "target": {
108                            "type": "string",
109                            "description": "Branch name or commit hash to checkout"
110                        },
111                        "create": {
112                            "type": "boolean",
113                            "description": "Create branch if it doesn't exist (default: false)"
114                        }
115                    },
116                    "required": ["target"]
117                }
118            }),
119            json!({
120                "name": "git_blame",
121                "description": "Show what revision and author last modified each line of a file",
122                "inputSchema": {
123                    "type": "object",
124                    "properties": {
125                        "path": {
126                            "type": "string",
127                            "description": "Path to git repository (default: current directory)"
128                        },
129                        "file": {
130                            "type": "string",
131                            "description": "File to blame"
132                        }
133                    },
134                    "required": ["file"]
135                }
136            }),
137            json!({
138                "name": "git_log",
139                "description": "Show commit logs",
140                "inputSchema": {
141                    "type": "object",
142                    "properties": {
143                        "path": {
144                            "type": "string",
145                            "description": "Path to git repository (default: current directory)"
146                        },
147                        "limit": {
148                            "type": "number",
149                            "description": "Number of commits to show (default: 10)"
150                        },
151                        "file": {
152                            "type": "string",
153                            "description": "Show commits for specific file"
154                        }
155                    }
156                }
157            }),
158            json!({
159                "name": "git_tag",
160                "description": "List, create, or delete tags",
161                "inputSchema": {
162                    "type": "object",
163                    "properties": {
164                        "path": {
165                            "type": "string",
166                            "description": "Path to git repository (default: current directory)"
167                        },
168                        "action": {
169                            "type": "string",
170                            "enum": ["list", "create", "delete"],
171                            "description": "Action to perform (default: list)"
172                        },
173                        "name": {
174                            "type": "string",
175                            "description": "Tag name (for create/delete)"
176                        },
177                        "message": {
178                            "type": "string",
179                            "description": "Tag message (for annotated tags)"
180                        }
181                    }
182                }
183            }),
184        ]
185    }
186
187    pub async fn status(&self, args: Value) -> Result<Value> {
188        let path = args["path"].as_str().unwrap_or(".");
189        let repo = Repository::open(path)?;
190
191        let mut opts = StatusOptions::new();
192        opts.include_untracked(true);
193        let statuses = repo.statuses(Some(&mut opts))?;
194
195        let mut result = json!({
196            "staged": [],
197            "unstaged": [],
198            "untracked": []
199        });
200
201        for entry in statuses.iter() {
202            let path = entry.path().unwrap_or("");
203            let status = entry.status();
204
205            if status.is_index_new() || status.is_index_modified() || status.is_index_deleted() {
206                result["staged"].as_array_mut().unwrap().push(json!({
207                    "path": path,
208                    "status": format!("{:?}", status)
209                }));
210            }
211
212            if status.is_wt_modified() || status.is_wt_deleted() {
213                result["unstaged"].as_array_mut().unwrap().push(json!({
214                    "path": path,
215                    "status": format!("{:?}", status)
216                }));
217            }
218
219            if status.is_wt_new() {
220                result["untracked"].as_array_mut().unwrap().push(json!({
221                    "path": path
222                }));
223            }
224        }
225
226        // Get current branch
227        let head = repo.head()?;
228        let branch_name = head.shorthand().unwrap_or("HEAD");
229
230        result["branch"] = json!(branch_name);
231        result["is_detached"] = json!(!head.is_branch());
232
233        Ok(result)
234    }
235
236    pub async fn diff(&self, args: Value) -> Result<Value> {
237        let path = args["path"].as_str().unwrap_or(".");
238        let staged = args["staged"].as_bool().unwrap_or(false);
239        let file_filter = args["file"].as_str();
240
241        let repo = Repository::open(path)?;
242
243        let mut diff_opts = DiffOptions::new();
244        if let Some(file) = file_filter {
245            diff_opts.pathspec(file);
246        }
247
248        let diff = if staged {
249            // Diff between HEAD and index (staged changes)
250            let head = repo.head()?.peel_to_tree()?;
251            let _index = repo.index()?;
252            let index_tree = repo.find_tree(repo.index()?.write_tree()?)?;
253            repo.diff_tree_to_tree(Some(&head), Some(&index_tree), Some(&mut diff_opts))?
254        } else {
255            // Diff between index and working directory (unstaged changes)
256            repo.diff_index_to_workdir(None, Some(&mut diff_opts))?
257        };
258
259        let mut patches = Vec::new();
260
261        diff.print(git2::DiffFormat::Patch, |_delta, _hunk, line| {
262            patches.push(json!({
263                "origin": format!("{}", line.origin()),
264                "content": String::from_utf8_lossy(line.content())
265            }));
266            true
267        })?;
268
269        let stats = diff.stats()?;
270
271        Ok(json!({
272            "staged": staged,
273            "files_changed": stats.files_changed(),
274            "insertions": stats.insertions(),
275            "deletions": stats.deletions(),
276            "patches": patches
277        }))
278    }
279
280    pub async fn commit(&self, args: Value) -> Result<Value> {
281        let path = args["path"].as_str().unwrap_or(".");
282        let message = args["message"].as_str().context("Missing 'message' parameter")?;
283
284        let repo = Repository::open(path)?;
285
286        // Get signature
287        let signature = if let (Some(name), Some(email)) = (args["author_name"].as_str(), args["author_email"].as_str()) {
288            git2::Signature::now(name, email)?
289        } else {
290            repo.signature()?
291        };
292
293        // Get current index
294        let mut index = repo.index()?;
295        let tree_id = index.write_tree()?;
296        let tree = repo.find_tree(tree_id)?;
297
298        // Get parent commit
299        let parent_commit = repo.head()?.peel_to_commit()?;
300
301        // Create commit
302        let commit_id = repo.commit(
303            Some("HEAD"),
304            &signature,
305            &signature,
306            message,
307            &tree,
308            &[&parent_commit],
309        )?;
310
311        Ok(json!({
312            "success": true,
313            "commit_id": commit_id.to_string(),
314            "message": message,
315            "author": signature.name().unwrap_or(""),
316            "email": signature.email().unwrap_or("")
317        }))
318    }
319
320    pub async fn branch(&self, args: Value) -> Result<Value> {
321        let path = args["path"].as_str().unwrap_or(".");
322        let action = args["action"].as_str().unwrap_or("list");
323
324        let repo = Repository::open(path)?;
325
326        match action {
327            "list" => {
328                let mut branches = Vec::new();
329
330                for branch in repo.branches(None)? {
331                    let (branch, _) = branch?;
332                    let name = branch.name()?.unwrap_or("");
333                    let is_head = branch.is_head();
334
335                    branches.push(json!({
336                        "name": name,
337                        "is_current": is_head
338                    }));
339                }
340
341                Ok(json!({
342                    "branches": branches,
343                    "count": branches.len()
344                }))
345            }
346            "create" => {
347                let name = args["name"].as_str().context("Missing 'name' parameter")?;
348                let head = repo.head()?;
349                let commit = head.peel_to_commit()?;
350
351                repo.branch(name, &commit, false)?;
352
353                Ok(json!({
354                    "success": true,
355                    "branch": name,
356                    "action": "created"
357                }))
358            }
359            "delete" => {
360                let name = args["name"].as_str().context("Missing 'name' parameter")?;
361                let mut branch = repo.find_branch(name, BranchType::Local)?;
362
363                branch.delete()?;
364
365                Ok(json!({
366                    "success": true,
367                    "branch": name,
368                    "action": "deleted"
369                }))
370            }
371            _ => Err(anyhow::anyhow!("Unknown action: {}", action)),
372        }
373    }
374
375    pub async fn checkout(&self, args: Value) -> Result<Value> {
376        let path = args["path"].as_str().unwrap_or(".");
377        let target = args["target"].as_str().context("Missing 'target' parameter")?;
378        let create = args["create"].as_bool().unwrap_or(false);
379
380        let repo = Repository::open(path)?;
381
382        // Try to find existing branch
383        let branch_exists = repo.find_branch(target, BranchType::Local).is_ok();
384
385        if !branch_exists && create {
386            // Create new branch
387            let head = repo.head()?;
388            let commit = head.peel_to_commit()?;
389            repo.branch(target, &commit, false)?;
390        }
391
392        // Checkout the branch
393        let obj = repo.revparse_single(target)?;
394
395        repo.checkout_tree(&obj, None)?;
396        repo.set_head(&format!("refs/heads/{}", target))?;
397
398        Ok(json!({
399            "success": true,
400            "target": target,
401            "created": !branch_exists && create
402        }))
403    }
404
405    pub async fn blame(&self, args: Value) -> Result<Value> {
406        let path = args["path"].as_str().unwrap_or(".");
407        let file = args["file"].as_str().context("Missing 'file' parameter")?;
408
409        let repo = Repository::open(path)?;
410        let blame = repo.blame_file(Path::new(file), None)?;
411
412        let mut lines = Vec::new();
413
414        for hunk in blame.iter() {
415            let commit = repo.find_commit(hunk.final_commit_id())?;
416
417            lines.push(json!({
418                "line_start": hunk.final_start_line(),
419                "line_count": hunk.lines_in_hunk(),
420                "commit": hunk.final_commit_id().to_string(),
421                "author": commit.author().name().unwrap_or(""),
422                "email": commit.author().email().unwrap_or(""),
423                "timestamp": commit.time().seconds(),
424                "message": commit.summary().unwrap_or("")
425            }));
426        }
427
428        Ok(json!({
429            "file": file,
430            "lines": lines,
431            "total_hunks": lines.len()
432        }))
433    }
434
435    pub async fn log(&self, args: Value) -> Result<Value> {
436        let path = args["path"].as_str().unwrap_or(".");
437        let limit = args["limit"].as_u64().unwrap_or(10) as usize;
438        let file_filter = args["file"].as_str();
439
440        let repo = Repository::open(path)?;
441
442        let mut revwalk = repo.revwalk()?;
443        revwalk.push_head()?;
444
445        let mut commits = Vec::new();
446
447        for (idx, oid) in revwalk.enumerate() {
448            if idx >= limit {
449                break;
450            }
451
452            let oid = oid?;
453            let commit = repo.find_commit(oid)?;
454
455            // If file filter is specified, check if commit affects the file
456            if let Some(file) = file_filter {
457                let tree = commit.tree()?;
458                if tree.get_path(Path::new(file)).is_err() {
459                    continue;
460                }
461            }
462
463            commits.push(json!({
464                "id": oid.to_string(),
465                "short_id": format!("{:.7}", oid),
466                "author": commit.author().name().unwrap_or(""),
467                "email": commit.author().email().unwrap_or(""),
468                "timestamp": commit.time().seconds(),
469                "message": commit.message().unwrap_or(""),
470                "summary": commit.summary().unwrap_or("")
471            }));
472        }
473
474        Ok(json!({
475            "commits": commits,
476            "count": commits.len(),
477            "limit": limit
478        }))
479    }
480
481    pub async fn tag(&self, args: Value) -> Result<Value> {
482        let path = args["path"].as_str().unwrap_or(".");
483        let action = args["action"].as_str().unwrap_or("list");
484
485        let repo = Repository::open(path)?;
486
487        match action {
488            "list" => {
489                let mut tags = Vec::new();
490
491                for name in repo.tag_names(None)?.iter() {
492                    if let Some(tag_name) = name {
493                        tags.push(json!({
494                            "name": tag_name
495                        }));
496                    }
497                }
498
499                Ok(json!({
500                    "tags": tags,
501                    "count": tags.len()
502                }))
503            }
504            "create" => {
505                let name = args["name"].as_str().context("Missing 'name' parameter")?;
506                let message = args["message"].as_str();
507
508                let head = repo.head()?;
509                let target = head.peel(ObjectType::Commit)?;
510
511                if let Some(msg) = message {
512                    // Create annotated tag
513                    let sig = repo.signature()?;
514                    repo.tag(name, &target, &sig, msg, false)?;
515                } else {
516                    // Create lightweight tag
517                    repo.tag_lightweight(name, &target, false)?;
518                }
519
520                Ok(json!({
521                    "success": true,
522                    "tag": name,
523                    "action": "created",
524                    "annotated": message.is_some()
525                }))
526            }
527            "delete" => {
528                let name = args["name"].as_str().context("Missing 'name' parameter")?;
529                repo.tag_delete(name)?;
530
531                Ok(json!({
532                    "success": true,
533                    "tag": name,
534                    "action": "deleted"
535                }))
536            }
537            _ => Err(anyhow::anyhow!("Unknown action: {}", action)),
538        }
539    }
540}