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
//! Git index manipulation for staging files.
//!
//! This module handles the low-level git index operations required to stage
//! files for commit. The git index (also called the "staging area") is a binary
//! file that tracks which files should be included in the next commit.
//!
//! # Git Index Overview
//!
//! The git index serves as a staging area between the working directory and
//! the repository:
//!
//! ```text
//! Working Directory → Index (Staging) → Repository (Commits)
//! (files on disk) (.git/index) (.git/objects/)
//! ```
//!
//! # Index Structure
//!
//! The index file contains:
//! - **Entries**: One per file, containing:
//! - Path (stored in a shared string table for efficiency)
//! - Object ID (SHA-1 of the file content)
//! - Mode (file type: regular file, executable, symlink, etc.)
//! - Stat info (timestamps, size, etc. for change detection)
//! - **Path Backing**: Shared storage for all entry paths
//! - **Extensions**: Optional metadata (tree cache, resolve undo, etc.)
//!
//! # Path Storage
//!
//! Paths in the index are stored in a unique way:
//! - All paths are stored in a single contiguous byte array (`path_backing`)
//! - Each entry's `path` field is a `Range<usize>` into this array
//! - This saves memory and makes the index more cache-friendly
//!
//! Example:
//! ```text
//! path_backing: b"Cargo.tomlsrc/main.rssrc/lib.rs"
//! entry[0].path: 0..10 ("Cargo.toml")
//! entry[1].path: 10..21 ("src/main.rs")
//! entry[2].path: 21..31 ("src/lib.rs")
//! ```
//!
//! # Why gix Instead of git Commands?
//!
//! Using `gix` (gitoxide) provides:
//! - **Type Safety**: Compile-time guarantees about git operations
//! - **Performance**: No process spawning overhead
//! - **Consistency**: Same API for all git operations
//! - **Testability**: Easier to mock and test
//!
//! # Staging Process
//!
//! To stage a file using `gix`:
//!
//! 1. **Load Index**: Read current index state from `.git/index`
//! 2. **Write Blob**: Store file content in git object database
//! 3. **Create Entry**: Build index entry with file metadata
//! 4. **Update State**: Add/update entry in index state
//! 5. **Sort Entries**: Maintain index invariant (sorted by path)
//! 6. **Write Index**: Save modified index back to disk
//!
//! # Challenges
//!
//! The gix index API is low-level and requires careful handling:
//! - Path storage must be managed manually
//! - Entries must be kept sorted
//! - The State struct doesn't allow direct mutation of path_backing
//! - We must rebuild the entire state to add entries with new paths
use Path;
use ;
use BStr;
use ;
/// Stage a file in the git index.
///
/// This function adds or updates a file entry in the git index, making it
/// ready to be committed. It handles all the low-level details of:
/// - Loading the current index state
/// - Adding the file's path to the path backing storage
/// - Creating a properly formatted index entry
/// - Maintaining index invariants (sorted entries)
/// - Writing the updated index back to disk
///
/// # Arguments
///
/// * `index_path` - Path to the `.git/index` file
/// * `repo` - Reference to the git repository
/// * `relative_path` - Path to the file relative to repository root
/// * `blob_id` - Object ID of the file's content (already written to object db)
/// * `existing_state` - Current index state to modify
///
/// # Returns
///
/// Returns the new index state with the file staged.
///
/// # Errors
///
/// Returns an error if:
/// - The index file cannot be read or written
/// - The path contains invalid UTF-8
/// - Entries cannot be properly sorted
///
/// # Examples
///
/// ```rust,no_run
/// # use anyhow::Result;
/// # use gix::index::State;
/// # fn example(repo: &gix::Repository) -> Result<State> {
/// use cargo_version_info::commands::bump::index::stage_file;
///
/// let index_path = repo.path().join("index");
/// let relative_path = std::path::Path::new("Cargo.toml");
/// let blob_id = gix::ObjectId::null(repo.object_hash());
/// let existing_state = State::new(repo.object_hash());
///
/// let new_state = stage_file(&index_path, repo, relative_path, blob_id, existing_state)?;
/// # Ok(new_state)
/// # }
/// ```
///
/// # Implementation Details
///
/// ## Path Handling
///
/// Since the index stores paths in a shared backing array, we need to:
/// 1. Check if the path already exists (for updates)
/// 2. Create a new State to add the path properly
/// 3. Copy all existing entries (preserving their path references)
/// 4. Add the new entry with its path
///
/// ## Entry Creation
///
/// The `dangerously_push_entry` method is used because:
/// - It's the most efficient way to add entries
/// - The "dangerous" name indicates we must call `sort_entries()` afterward
/// - It handles path storage automatically
///
/// ## Sorting
///
/// Git requires index entries to be sorted by path. This is critical for:
/// - Binary search during status checks
/// - Merge operations
/// - Index format consistency
/// Load the current index state from disk.
///
/// This is a convenience wrapper around `gix::index::File::at()` that provides
/// better error messages and uses sensible defaults for the decode options.
///
/// # Arguments
///
/// * `index_path` - Path to the `.git/index` file
/// * `object_hash` - The hash algorithm used by the repository (sha1 or sha256)
///
/// # Returns
///
/// Returns the parsed index state.
///
/// # Errors
///
/// Returns an error if:
/// - The index file doesn't exist
/// - The index file is corrupted
/// - The index format is unsupported
///
/// # Examples
///
/// ```rust,no_run
/// # use anyhow::Result;
/// # fn example(repo: &gix::Repository) -> Result<()> {
/// use cargo_version_info::commands::bump::index::load_index_state;
///
/// let index_path = repo.path().join("index");
/// let state = load_index_state(&index_path, repo.object_hash())?;
///
/// println!("Index has {} entries", state.entries().len());
/// # Ok(())
/// # }
/// ```