context-creator 1.5.0

High-performance CLI tool to convert codebases to Markdown for LLM context
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
//! Git utilities for executing git commands and parsing output

use anyhow::{anyhow, Result};
use git2::{Repository, Sort};
use std::path::{Path, PathBuf};
use std::process::Command;
use tracing::{debug, trace, warn};

/// Statistics from a git diff operation
#[derive(Debug, Clone, PartialEq)]
pub struct DiffStats {
    pub files_changed: usize,
    pub insertions: usize,
    pub deletions: usize,
}

/// Information about a single commit
#[derive(Debug, Clone)]
pub struct CommitInfo {
    pub message: String,
    pub author: String,
}

/// Git context for a file containing recent commit history
#[derive(Debug, Clone)]
pub struct GitContext {
    pub recent_commits: Vec<CommitInfo>,
}

/// Validate that a git reference looks safe and reasonable
fn validate_git_reference(git_ref: &str) -> Result<()> {
    // Basic validation to prevent command injection
    if git_ref.is_empty() {
        return Err(anyhow!("Git reference cannot be empty"));
    }

    // Check for dangerous characters that could be used for command injection
    let dangerous_chars = [';', '&', '|', '`', '$', '(', ')', '\n', '\r'];
    for &ch in &dangerous_chars {
        if git_ref.contains(ch) {
            return Err(anyhow!("Invalid character in git reference: '{}'", ch));
        }
    }

    // Additional length check to prevent extremely long inputs
    if git_ref.len() > 256 {
        return Err(anyhow!("Git reference too long"));
    }

    Ok(())
}

/// Sanitize error messages to prevent information disclosure
fn sanitize_git_error(error_output: &str) -> String {
    // Remove potentially sensitive paths and information
    let sanitized = error_output
        .lines()
        .filter(|line| !line.contains("fatal:") || line.contains("unknown revision"))
        .collect::<Vec<_>>()
        .join("\n");

    if sanitized.is_empty() {
        "Invalid git reference".to_string()
    } else {
        format!("Git error: {sanitized}")
    }
}

/// Validate that a file path is safe (no directory traversal)
fn validate_file_path(path: &str) -> Result<PathBuf> {
    if path.contains("..") || path.starts_with('/') {
        return Err(anyhow!("Unsafe file path detected: {}", path));
    }
    Ok(PathBuf::from(path))
}

/// Check if a directory is a git repository
pub fn is_git_repository<P: AsRef<Path>>(path: P) -> bool {
    let git_dir = path.as_ref().join(".git");
    git_dir.exists()
}

/// Get the list of files changed between two git references
pub fn get_changed_files<P: AsRef<Path>>(
    repo_path: P,
    from: &str,
    to: &str,
) -> Result<Vec<PathBuf>> {
    // Validate git references to prevent command injection
    validate_git_reference(from)?;
    validate_git_reference(to)?;

    let output = Command::new("git")
        .args(["diff", "--name-only", from, to])
        .current_dir(repo_path.as_ref())
        .output()
        .map_err(|e| anyhow!("Failed to execute git command: {}", e))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(anyhow!("{}", sanitize_git_error(&stderr)));
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut files = Vec::new();

    for line in stdout.lines() {
        let line = line.trim();
        if !line.is_empty() {
            // Validate each file path to prevent path traversal
            let safe_path = validate_file_path(line)?;
            files.push(repo_path.as_ref().join(safe_path));
        }
    }

    Ok(files)
}

/// Get diff statistics between two git references
pub fn get_diff_stats<P: AsRef<Path>>(repo_path: P, from: &str, to: &str) -> Result<DiffStats> {
    // Validate git references to prevent command injection
    validate_git_reference(from)?;
    validate_git_reference(to)?;

    let output = Command::new("git")
        .args(["diff", "--numstat", from, to])
        .current_dir(repo_path.as_ref())
        .output()
        .map_err(|e| anyhow!("Failed to execute git command: {}", e))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(anyhow!("{}", sanitize_git_error(&stderr)));
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut stats = DiffStats {
        files_changed: 0,
        insertions: 0,
        deletions: 0,
    };

    for line in stdout.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }

        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() >= 2 {
            stats.files_changed += 1;

            // Parse insertions (first column)
            if let Ok(insertions) = parts[0].parse::<usize>() {
                stats.insertions += insertions;
            }

            // Parse deletions (second column)
            if let Ok(deletions) = parts[1].parse::<usize>() {
                stats.deletions += deletions;
            }
        }
    }

    Ok(stats)
}

/// Get the root directory of the git repository
pub fn get_repository_root<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
    let output = Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .current_dir(path.as_ref())
        .output()
        .map_err(|e| anyhow!("Failed to execute git command: {}", e))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(anyhow!("{}", sanitize_git_error(&stderr)));
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let root_path = stdout.trim();

    Ok(PathBuf::from(root_path))
}

/// Get git context (recent commits) for a specific file
pub fn get_file_git_context<P: AsRef<Path>>(repo_path: P, file_path: P) -> Option<GitContext> {
    get_file_git_context_with_depth(repo_path, file_path, 3)
}

/// Get git context (recent commits) for a specific file with configurable depth
pub fn get_file_git_context_with_depth<P: AsRef<Path>>(
    repo_path: P,
    file_path: P,
    max_commits: usize,
) -> Option<GitContext> {
    let repo_path_str = repo_path.as_ref().display();
    let file_path_str = file_path.as_ref().display();

    trace!(
        "Getting git context for file: {} in repo: {}",
        file_path_str,
        repo_path_str
    );

    // First, try to discover the actual repository root
    let repo = match Repository::discover(repo_path.as_ref()) {
        Ok(r) => {
            debug!(
                "Successfully discovered git repository at: {}",
                repo_path_str
            );
            r
        }
        Err(e) => {
            debug!(
                "Failed to discover git repository at {}: {}",
                repo_path_str, e
            );
            return None;
        }
    };

    // Get the repository root path
    let repo_root = match repo.workdir() {
        Some(root) => {
            trace!("Repository workdir: {}", root.display());
            root
        }
        None => {
            warn!("Repository has no working directory (bare repository)");
            return None;
        }
    };

    // Get the relative path from repo root
    let file_canonical = match file_path.as_ref().canonicalize() {
        Ok(path) => path,
        Err(e) => {
            debug!("Failed to canonicalize file path {}: {}", file_path_str, e);
            return None;
        }
    };

    let repo_canonical = match repo_root.canonicalize() {
        Ok(path) => path,
        Err(e) => {
            warn!(
                "Failed to canonicalize repository path {}: {}",
                repo_root.display(),
                e
            );
            return None;
        }
    };

    let relative_path = match file_canonical.strip_prefix(repo_canonical) {
        Ok(path) => {
            trace!("Relative path in repository: {}", path.display());
            path
        }
        Err(e) => {
            debug!(
                "File {} is not within repository {}: {}",
                file_path_str,
                repo_root.display(),
                e
            );
            return None;
        }
    };

    // Create a revwalk starting from HEAD
    let mut revwalk = match repo.revwalk() {
        Ok(walk) => {
            trace!("Created revwalk for repository");
            walk
        }
        Err(e) => {
            warn!("Failed to create revwalk: {}", e);
            return None;
        }
    };

    // Configure sorting
    if let Err(e) = revwalk.set_sorting(Sort::TIME) {
        warn!("Failed to set revwalk sorting: {}", e);
        return None;
    }

    if let Err(e) = revwalk.push_head() {
        debug!(
            "Failed to push HEAD to revwalk (repository may be empty): {}",
            e
        );
        return None;
    }

    let mut commits = Vec::new();
    let mut commits_processed = 0;

    trace!(
        "Walking through commits to find those affecting file: {}",
        relative_path.display()
    );

    // Walk through commits
    for oid_result in revwalk {
        if commits.len() >= max_commits {
            trace!("Reached maximum commit limit of {}", max_commits);
            break;
        }

        let oid = match oid_result {
            Ok(o) => o,
            Err(e) => {
                debug!("Failed to get commit OID: {}", e);
                continue;
            }
        };

        let commit = match repo.find_commit(oid) {
            Ok(c) => c,
            Err(e) => {
                debug!("Failed to find commit {}: {}", oid, e);
                continue;
            }
        };

        commits_processed += 1;

        // Check if this commit touches our file
        let touches_file = if let Ok(parent) = commit.parent(0) {
            let parent_tree = match parent.tree() {
                Ok(tree) => tree,
                Err(e) => {
                    debug!("Failed to get parent tree: {}", e);
                    continue;
                }
            };
            let commit_tree = match commit.tree() {
                Ok(tree) => tree,
                Err(e) => {
                    debug!("Failed to get commit tree: {}", e);
                    continue;
                }
            };
            let diff = match repo.diff_tree_to_tree(Some(&parent_tree), Some(&commit_tree), None) {
                Ok(diff) => diff,
                Err(e) => {
                    debug!("Failed to create diff: {}", e);
                    continue;
                }
            };

            diff.deltas().any(|delta| {
                delta.old_file().path() == Some(relative_path)
                    || delta.new_file().path() == Some(relative_path)
            })
        } else {
            // First commit - check if file exists
            let tree = match commit.tree() {
                Ok(tree) => tree,
                Err(e) => {
                    debug!("Failed to get tree for root commit: {}", e);
                    continue;
                }
            };
            tree.get_path(relative_path).is_ok()
        };

        if touches_file {
            let message = commit
                .message()
                .unwrap_or("<no message>")
                .lines()
                .next()
                .unwrap_or("<no message>")
                .to_string();
            let author = commit.author().name().unwrap_or("Unknown").to_string();

            trace!("Found relevant commit: {} by {}", message, author);
            commits.push(CommitInfo { message, author });
        }
    }

    debug!(
        "Processed {} commits, found {} relevant commits for file {}",
        commits_processed,
        commits.len(),
        relative_path.display()
    );

    if commits.is_empty() {
        debug!("No git history found for file: {}", file_path_str);
        None
    } else {
        trace!("Returning git context with {} commits", commits.len());
        Some(GitContext {
            recent_commits: commits,
        })
    }
}

/// Format git context as markdown string
pub fn format_git_context_to_markdown(git_context: &GitContext) -> String {
    if git_context.recent_commits.is_empty() {
        return String::new();
    }

    let mut output = String::new();
    output.push('\n');
    output.push_str("Git history:\n");

    for (i, commit) in git_context.recent_commits.iter().enumerate().take(3) {
        if i > 0 {
            output.push('\n');
        }
        output.push_str(&format!(
            "  - {} by {}",
            commit.message.trim(),
            commit.author
        ));
    }
    output.push('\n');

    output
}