octocode 0.16.0

AI-powered code intelligence with semantic search, knowledge graphs, and built-in MCP server. Transform your codebase into a queryable knowledge graph for AI assistants.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// Copyright 2026 Muvon Un Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use anyhow::Result;
use std::path::Path;
use std::process::Command;

/// Git utilities for repository management
pub struct GitUtils;

impl GitUtils {
	/// Check if current directory is a git repository root
	pub fn is_git_repo_root(path: &Path) -> bool {
		path.join(".git").exists()
	}

	/// Find git repository root from current path
	pub fn find_git_root(start_path: &Path) -> Option<std::path::PathBuf> {
		let mut current = start_path;
		loop {
			if Self::is_git_repo_root(current) {
				return Some(current.to_path_buf());
			}
			match current.parent() {
				Some(parent) => current = parent,
				None => break,
			}
		}
		None
	}

	/// Get current git commit hash
	pub fn get_current_commit_hash(repo_path: &Path) -> Result<String> {
		let output = Command::new("git")
			.arg("rev-parse")
			.arg("HEAD")
			.current_dir(repo_path)
			.output()?;

		if !output.status.success() {
			return Err(anyhow::anyhow!("Failed to get git commit hash"));
		}

		Ok(String::from_utf8(output.stdout)?.trim().to_string())
	}

	/// Get files changed between two commits (committed changes only, no unstaged)
	pub fn get_changed_files_since_commit(
		repo_path: &Path,
		since_commit: &str,
	) -> Result<Vec<String>> {
		let mut changed_files = std::collections::HashSet::new();

		// Get files changed between commits (committed changes only)
		let output = Command::new("git")
			.args(["diff", "--name-only", since_commit, "HEAD"])
			.current_dir(repo_path)
			.output()?;

		if output.status.success() {
			let stdout = String::from_utf8(output.stdout)?;
			for line in stdout.lines() {
				if !line.trim().is_empty() {
					changed_files.insert(line.trim().to_string());
				}
			}
		}

		Ok(changed_files.into_iter().collect())
	}

	/// Get only staged files (files in git index)
	pub fn get_staged_files(repo_path: &Path) -> Result<Vec<String>> {
		let mut staged_files = Vec::new();

		// Get staged files
		let output = Command::new("git")
			.args(["diff", "--cached", "--name-only"])
			.current_dir(repo_path)
			.output()?;

		if output.status.success() {
			let stdout = String::from_utf8(output.stdout)?;
			for line in stdout.lines() {
				if !line.trim().is_empty() {
					staged_files.push(line.trim().to_string());
				}
			}
		}

		Ok(staged_files)
	}

	/// Note: This is used for non-git optimization scenarios only
	pub fn get_all_changed_files(repo_path: &Path) -> Result<Vec<String>> {
		let mut changed_files = std::collections::HashSet::new();

		// Get staged files
		let output = Command::new("git")
			.args(["diff", "--cached", "--name-only"])
			.current_dir(repo_path)
			.output()?;

		if output.status.success() {
			let stdout = String::from_utf8(output.stdout)?;
			for line in stdout.lines() {
				if !line.trim().is_empty() {
					changed_files.insert(line.trim().to_string());
				}
			}
		}

		// Get unstaged files
		let output = Command::new("git")
			.args(["diff", "--name-only"])
			.current_dir(repo_path)
			.output()?;

		if output.status.success() {
			let stdout = String::from_utf8(output.stdout)?;
			for line in stdout.lines() {
				if !line.trim().is_empty() {
					changed_files.insert(line.trim().to_string());
				}
			}
		}

		// Get untracked files
		let output = Command::new("git")
			.args(["ls-files", "--others", "--exclude-standard"])
			.current_dir(repo_path)
			.output()?;

		if output.status.success() {
			let stdout = String::from_utf8(output.stdout)?;
			for line in stdout.lines() {
				if !line.trim().is_empty() {
					changed_files.insert(line.trim().to_string());
				}
			}
		}

		Ok(changed_files.into_iter().collect())
	}

	/// Resolve a ref to a commit hash. Returns `None` if the ref doesn't exist
	/// (e.g. `origin/main` in a repo without a remote, or before `git fetch`).
	/// Distinguishes "ref doesn't exist" from "git command failed" — both map
	/// to None here because the caller cares about "is there a commit we can
	/// compare against", not why.
	pub fn resolve_ref(repo_path: &Path, refname: &str) -> Option<String> {
		let output = Command::new("git")
			.args(["rev-parse", "--verify", "--quiet", refname])
			.current_dir(repo_path)
			.output()
			.ok()?;
		if !output.status.success() {
			return None;
		}
		let s = String::from_utf8(output.stdout).ok()?.trim().to_string();
		if s.is_empty() {
			None
		} else {
			Some(s)
		}
	}

	/// Compute the merge-base (common ancestor) between two refs. This is the
	/// real fork point for branch-delta computation — diffing against the
	/// default-branch tip directly includes commits the branch is "missing",
	/// which would pollute the branch delta with files that belong in main.
	pub fn merge_base(repo_path: &Path, a: &str, b: &str) -> Result<String> {
		let output = Command::new("git")
			.args(["merge-base", a, b])
			.current_dir(repo_path)
			.output()?;
		if !output.status.success() {
			let stderr = String::from_utf8_lossy(&output.stderr);
			return Err(anyhow::anyhow!(
				"git merge-base {} {} failed: {}",
				a,
				b,
				stderr.trim()
			));
		}
		Ok(String::from_utf8(output.stdout)?.trim().to_string())
	}

	/// Count commits that `head_ref` is ahead of `base_ref` (i.e. commits in
	/// head_ref that aren't in base_ref). Used to surface "local main is N
	/// commits behind origin/main" warnings.
	pub fn commits_ahead(repo_path: &Path, base_ref: &str, head_ref: &str) -> Result<usize> {
		let range = format!("{}..{}", base_ref, head_ref);
		let output = Command::new("git")
			.args(["rev-list", "--count", &range])
			.current_dir(repo_path)
			.output()?;
		if !output.status.success() {
			let stderr = String::from_utf8_lossy(&output.stderr);
			return Err(anyhow::anyhow!(
				"git rev-list --count {} failed: {}",
				range,
				stderr.trim()
			));
		}
		let n: usize = String::from_utf8(output.stdout)?.trim().parse()?;
		Ok(n)
	}

	/// Detect the default branch name
	pub fn get_default_branch(repo_path: &Path) -> Result<String> {
		// Try remote HEAD first
		let output = Command::new("git")
			.args(["symbolic-ref", "refs/remotes/origin/HEAD"])
			.current_dir(repo_path)
			.output()?;

		if output.status.success() {
			let refname = String::from_utf8(output.stdout)?.trim().to_string();
			if let Some(branch) = refname.strip_prefix("refs/remotes/origin/") {
				return Ok(branch.to_string());
			}
		}

		// Fallback: check if main or master exists
		for branch in &["main", "master"] {
			let output = Command::new("git")
				.args(["rev-parse", "--verify", branch])
				.current_dir(repo_path)
				.output()?;
			if output.status.success() {
				return Ok(branch.to_string());
			}
		}

		// Last resort: current branch
		let output = Command::new("git")
			.args(["rev-parse", "--abbrev-ref", "HEAD"])
			.current_dir(repo_path)
			.output()?;

		if output.status.success() {
			return Ok(String::from_utf8(output.stdout)?.trim().to_string());
		}

		Err(anyhow::anyhow!("Could not determine default branch"))
	}

	/// Get commit log entries. If `since_commit` is Some, only returns commits after that hash.
	pub fn get_commit_log(
		repo_path: &Path,
		branch: &str,
		since_commit: Option<&str>,
	) -> Result<Vec<CommitEntry>> {
		let range = match since_commit {
			Some(hash) => format!("{}..{}", hash, branch),
			None => branch.to_string(),
		};

		let output = Command::new("git")
			.args(["log", "--format=%H|%an|%at|%B%x00", "--reverse", &range])
			.current_dir(repo_path)
			.output()?;

		if !output.status.success() {
			return Err(anyhow::anyhow!("Failed to get commit log"));
		}

		let stdout = String::from_utf8(output.stdout)?;
		let mut entries = Vec::new();

		// Records are separated by null bytes (%x00).
		// Each record: HASH|AUTHOR|TIMESTAMP|FULL_MESSAGE (may contain newlines)
		for record in stdout.split('\0') {
			let record = record.trim();
			if record.is_empty() {
				continue;
			}

			let parts: Vec<&str> = record.splitn(4, '|').collect();
			if parts.len() < 4 {
				continue;
			}

			entries.push(CommitEntry {
				hash: parts[0].to_string(),
				author: parts[1].to_string(),
				date: parts[2].parse::<i64>().unwrap_or(0),
				message: parts[3].trim().to_string(),
			});
		}

		Ok(entries)
	}

	/// Get changed file paths for a specific commit
	pub fn get_changed_files_for_commit(repo_path: &Path, hash: &str) -> Result<Vec<String>> {
		let output = Command::new("git")
			.args([
				"diff-tree",
				"--no-commit-id",
				"--name-only",
				"-r",
				"--root",
				hash,
			])
			.current_dir(repo_path)
			.output()?;

		if !output.status.success() {
			return Ok(vec![]);
		}

		let stdout = String::from_utf8(output.stdout)?;
		Ok(stdout
			.lines()
			.filter(|l| !l.trim().is_empty())
			.map(|l| l.trim().to_string())
			.collect())
	}

	/// Get diff for a specific commit (truncated to max_chars)
	pub fn get_commit_diff(repo_path: &Path, hash: &str, max_chars: usize) -> Result<String> {
		// Check if this is the root commit (no parent)
		let parent_check = Command::new("git")
			.args(["rev-parse", &format!("{}^", hash)])
			.current_dir(repo_path)
			.output()?;

		let output = if parent_check.status.success() {
			Command::new("git")
				.args(["diff", &format!("{}^..{}", hash, hash), "--stat", "-p"])
				.current_dir(repo_path)
				.output()?
		} else {
			// Root commit
			Command::new("git")
				.args(["diff", "--root", hash, "--stat", "-p"])
				.current_dir(repo_path)
				.output()?
		};

		if !output.status.success() {
			return Ok(String::new());
		}

		let diff = String::from_utf8_lossy(&output.stdout).to_string();
		if diff.len() > max_chars {
			Ok(diff[..max_chars].to_string())
		} else {
			Ok(diff)
		}
	}
}

/// Parsed commit entry from git log
#[derive(Debug, Clone)]
pub struct CommitEntry {
	pub hash: String,
	pub author: String,
	pub date: i64,
	pub message: String,
}

#[cfg(test)]
mod tests {
	use super::*;
	use std::path::Path;

	#[test]
	fn test_is_git_repo_root() {
		// Current project should be a git repo
		let path = Path::new(env!("CARGO_MANIFEST_DIR"));
		assert!(GitUtils::is_git_repo_root(path));
	}

	#[test]
	fn test_find_git_root_from_subdir() {
		let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
		let src = manifest.join("src");
		let result = GitUtils::find_git_root(&src);
		assert!(result.is_some());
		assert_eq!(result.unwrap(), manifest);
	}

	#[test]
	fn test_get_default_branch() {
		let path = Path::new(env!("CARGO_MANIFEST_DIR"));
		let result = GitUtils::get_default_branch(path);
		// Should succeed — returns some branch name
		assert!(result.is_ok());
		let branch = result.unwrap();
		assert!(!branch.is_empty());
	}

	#[test]
	fn test_get_commit_log() {
		let path = Path::new(env!("CARGO_MANIFEST_DIR"));
		let branch = GitUtils::get_default_branch(path).unwrap();
		let commits = GitUtils::get_commit_log(path, &branch, None).unwrap();
		// The project has commits
		assert!(!commits.is_empty());
		// Each entry should have non-empty fields
		let first = &commits[0];
		assert!(!first.hash.is_empty());
		assert!(!first.author.is_empty());
		assert!(first.date > 0);
		assert!(!first.message.is_empty());
	}

	#[test]
	fn test_get_changed_files_for_commit() {
		let path = Path::new(env!("CARGO_MANIFEST_DIR"));

		// Test with root commit (the bug case: diff-tree without --root returns empty)
		let output = std::process::Command::new("git")
			.args(["rev-list", "--max-parents=0", "HEAD"])
			.current_dir(path)
			.output()
			.unwrap();
		let root_hash = String::from_utf8(output.stdout).unwrap().trim().to_string();
		let files = GitUtils::get_changed_files_for_commit(path, &root_hash).unwrap();
		assert!(!files.is_empty(), "root commit should have changed files");

		// Test with HEAD (non-root commit)
		let hash = GitUtils::get_current_commit_hash(path).unwrap();
		let files = GitUtils::get_changed_files_for_commit(path, &hash).unwrap();
		assert!(!files.is_empty(), "HEAD commit should have changed files");
	}
}