| 1 |
// Copyright 2025 The Jujutsu Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
//! Index of per-commit changed paths. |
| 16 |
|
| 17 |
use std::collections::HashMap; |
| 18 |
use std::fmt; |
| 19 |
use std::fmt::Debug; |
| 20 |
use std::fs::File; |
| 21 |
use std::io::Read; |
| 22 |
use std::io::Write as _; |
| 23 |
use std::path::Path; |
| 24 |
use std::sync::Arc; |
| 25 |
|
| 26 |
use blake2::Blake2b512; |
| 27 |
use digest::Digest as _; |
| 28 |
use either::Either; |
| 29 |
use futures::StreamExt as _; |
| 30 |
use futures::TryStreamExt as _; |
| 31 |
use itertools::Itertools as _; |
| 32 |
use tempfile::NamedTempFile; |
| 33 |
|
| 34 |
use super::entry::GlobalCommitPosition; |
| 35 |
use super::readonly::ReadonlyIndexLoadError; |
| 36 |
use crate::backend::BackendResult; |
| 37 |
use crate::commit::Commit; |
| 38 |
use crate::file_util::IoResultExt as _; |
| 39 |
use crate::file_util::PathError; |
| 40 |
use crate::file_util::persist_content_addressed_temp_file; |
| 41 |
use crate::index::Index; |
| 42 |
use crate::matchers::EverythingMatcher; |
| 43 |
use crate::object_id::ObjectId as _; |
| 44 |
use crate::object_id::id_type; |
| 45 |
use crate::repo_path::RepoPath; |
| 46 |
use crate::repo_path::RepoPathBuf; |
| 47 |
use crate::rewrite::merge_commit_trees_no_resolve_without_repo; |
| 48 |
use crate::tree_merge::resolve_file_values; |
| 49 |
|
| 50 |
/// Current format version of the changed-path index segment file. |
| 51 |
const FILE_FORMAT_VERSION: u32 = 0; |
| 52 |
|
| 53 |
id_type!(pub(super) ChangedPathIndexSegmentId { hex() }); |
| 54 |
|
| 55 |
/// Commit position within a changed-path index segment. |
| 56 |
/// |
| 57 |
/// This may be different from `LocalCommitPosition`, which is a position |
| 58 |
/// relative to the start of the commit index segment. |
| 59 |
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] |
| 60 |
struct CommitPosition(u32); |
| 61 |
|
| 62 |
/// Path position within a changed-path index segment. |
| 63 |
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] |
| 64 |
struct PathPosition(u32); |
| 65 |
|
| 66 |
/// Changed-path index segment backed by immutable file. |
| 67 |
/// |
| 68 |
/// File format: |
| 69 |
/// ```text |
| 70 |
/// u32: file format version |
| 71 |
/// |
| 72 |
/// u32: number of (local) commit entries |
| 73 |
/// u32: number of changed path entries |
| 74 |
/// u32: number of path entries |
| 75 |
/// u32: number of bytes of path entries |
| 76 |
/// |
| 77 |
/// for each commit, in commit-index order |
| 78 |
/// u32: position in changed-path table |
| 79 |
/// u32: number of changed-path entries (as sentinel) |
| 80 |
/// for each commit, in commit-index order |
| 81 |
/// for each changed path, sorted by path |
| 82 |
/// u32: lookup position of path |
| 83 |
/// |
| 84 |
/// for each path, sorted by path |
| 85 |
/// u32: byte offset in sorted paths table |
| 86 |
/// u32: number of bytes of path entries (as sentinel) |
| 87 |
/// for each path, sorted by path |
| 88 |
/// <arbitrary length of bytes>: path |
| 89 |
/// ``` |
| 90 |
/// |
| 91 |
/// * The parent segment id isn't stored in a segment file. This allows us to |
| 92 |
/// insert parents without rewriting the descendant segments. |
| 93 |
/// * Paths table isn't compacted across segments to keep the implementation |
| 94 |
/// simple. There isn't a strong reason to map paths to globally-unique |
| 95 |
/// integers. This also means changed-path positions are sorted by both path |
| 96 |
/// texts and integers. |
| 97 |
/// * Changed-path positions are sorted by paths so that we can binary-search |
| 98 |
/// entries by exact path or path prefix if needed. |
| 99 |
/// * Path components aren't split nor compressed so we can borrow `&RepoPath` |
| 100 |
/// from the index data. |
| 101 |
/// |
| 102 |
/// Ideas for future improvements: |
| 103 |
/// * Multi-level index based on the paths? Since indexing is slow, it might |
| 104 |
/// make sense to split index files based on path depths. |
| 105 |
/// * Shared paths table to save disk space? |
| 106 |
pub(super) struct ReadonlyChangedPathIndexSegment { |
| 107 |
id: ChangedPathIndexSegmentId, |
| 108 |
num_local_commits: u32, |
| 109 |
num_changed_paths: u32, |
| 110 |
num_paths: u32, |
| 111 |
// Base data offsets in bytes: |
| 112 |
commit_lookup_base: usize, |
| 113 |
changed_path_lookup_base: usize, |
| 114 |
path_lookup_base: usize, |
| 115 |
path_bytes_base: usize, |
| 116 |
data: Vec<u8>, |
| 117 |
} |
| 118 |
|
| 119 |
impl Debug for ReadonlyChangedPathIndexSegment { |
| 120 |
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { |
| 121 |
f.debug_struct("ReadonlyChangedPathIndexSegment") |
| 122 |
.field("id", &self.id) |
| 123 |
.finish_non_exhaustive() |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
impl ReadonlyChangedPathIndexSegment { |
| 128 |
pub(super) fn load( |
| 129 |
dir: &Path, |
| 130 |
id: ChangedPathIndexSegmentId, |
| 131 |
) -> Result<Arc<Self>, ReadonlyIndexLoadError> { |
| 132 |
let mut file = File::open(dir.join(id.hex())) |
| 133 |
.map_err(|err| ReadonlyIndexLoadError::from_io_err("changed-path", id.hex(), err))?; |
| 134 |
Self::load_from(&mut file, id) |
| 135 |
} |
| 136 |
|
| 137 |
pub(super) fn load_from( |
| 138 |
file: &mut dyn Read, |
| 139 |
id: ChangedPathIndexSegmentId, |
| 140 |
) -> Result<Arc<Self>, ReadonlyIndexLoadError> { |
| 141 |
let from_io_err = |err| ReadonlyIndexLoadError::from_io_err("changed-path", id.hex(), err); |
| 142 |
let read_u32 = |file: &mut dyn Read| { |
| 143 |
let mut buf = [0; 4]; |
| 144 |
file.read_exact(&mut buf).map_err(from_io_err)?; |
| 145 |
Ok(u32::from_le_bytes(buf)) |
| 146 |
}; |
| 147 |
|
| 148 |
let format_version = read_u32(file)?; |
| 149 |
if format_version != FILE_FORMAT_VERSION { |
| 150 |
return Err(ReadonlyIndexLoadError::UnexpectedVersion { |
| 151 |
kind: "changed-path", |
| 152 |
found_version: format_version, |
| 153 |
expected_version: FILE_FORMAT_VERSION, |
| 154 |
}); |
| 155 |
} |
| 156 |
|
| 157 |
let num_local_commits = read_u32(file)?; |
| 158 |
let num_changed_paths = read_u32(file)?; |
| 159 |
let num_paths = read_u32(file)?; |
| 160 |
let num_path_bytes = read_u32(file)?; |
| 161 |
let mut data = vec![]; |
| 162 |
file.read_to_end(&mut data).map_err(from_io_err)?; |
| 163 |
|
| 164 |
let commit_lookup_size = (num_local_commits as usize + 1) * 4; |
| 165 |
let changed_path_lookup_size = (num_changed_paths as usize) * 4; |
| 166 |
let path_lookup_size = (num_paths as usize + 1) * 4; |
| 167 |
|
| 168 |
let commit_lookup_base = 0; |
| 169 |
let changed_path_lookup_base = commit_lookup_base + commit_lookup_size; |
| 170 |
let path_lookup_base = changed_path_lookup_base + changed_path_lookup_size; |
| 171 |
let path_bytes_base = path_lookup_base + path_lookup_size; |
| 172 |
let expected_size = path_bytes_base + (num_path_bytes as usize); |
| 173 |
|
| 174 |
if data.len() != expected_size { |
| 175 |
return Err(ReadonlyIndexLoadError::invalid_data( |
| 176 |
"changed-path", |
| 177 |
id.hex(), |
| 178 |
"unexpected data length", |
| 179 |
)); |
| 180 |
} |
| 181 |
|
| 182 |
Ok(Arc::new(Self { |
| 183 |
id, |
| 184 |
num_local_commits, |
| 185 |
num_changed_paths, |
| 186 |
num_paths, |
| 187 |
commit_lookup_base, |
| 188 |
changed_path_lookup_base, |
| 189 |
path_lookup_base, |
| 190 |
path_bytes_base, |
| 191 |
data, |
| 192 |
})) |
| 193 |
} |
| 194 |
|
| 195 |
pub(super) fn id(&self) -> &ChangedPathIndexSegmentId { |
| 196 |
&self.id |
| 197 |
} |
| 198 |
|
| 199 |
pub(super) fn num_local_commits(&self) -> u32 { |
| 200 |
self.num_local_commits |
| 201 |
} |
| 202 |
|
| 203 |
pub(super) fn num_changed_paths(&self) -> u32 { |
| 204 |
self.num_changed_paths |
| 205 |
} |
| 206 |
|
| 207 |
pub(super) fn num_paths(&self) -> u32 { |
| 208 |
self.num_paths |
| 209 |
} |
| 210 |
|
| 211 |
fn changed_paths(&self, pos: CommitPosition) -> impl ExactSizeIterator<Item = &RepoPath> { |
| 212 |
let table = self.changed_paths_table(pos); |
| 213 |
let (chunks, _remainder) = table.as_chunks(); |
| 214 |
chunks |
| 215 |
.iter() |
| 216 |
.map(|&chunk: &[u8; 4]| PathPosition(u32::from_le_bytes(chunk))) |
| 217 |
.map(|pos| self.path(pos)) |
| 218 |
} |
| 219 |
|
| 220 |
fn changed_paths_table(&self, pos: CommitPosition) -> &[u8] { |
| 221 |
let table = &self.data[self.commit_lookup_base..self.changed_path_lookup_base]; |
| 222 |
let offset = pos.0 as usize * 4; |
| 223 |
let start = u32::from_le_bytes(table[offset..][0..4].try_into().unwrap()); |
| 224 |
let end = u32::from_le_bytes(table[offset..][4..8].try_into().unwrap()); |
| 225 |
|
| 226 |
let table = &self.data[self.changed_path_lookup_base..self.path_lookup_base]; |
| 227 |
&table[(start as usize) * 4..(end as usize) * 4] |
| 228 |
} |
| 229 |
|
| 230 |
fn path(&self, pos: PathPosition) -> &RepoPath { |
| 231 |
let bytes = self.path_bytes(pos); |
| 232 |
RepoPath::from_internal_string( |
| 233 |
str::from_utf8(bytes).expect("indexed path should be valid utf-8"), |
| 234 |
) |
| 235 |
.expect("indexed path should be valid") |
| 236 |
} |
| 237 |
|
| 238 |
fn path_bytes(&self, pos: PathPosition) -> &[u8] { |
| 239 |
let table = &self.data[self.path_lookup_base..self.path_bytes_base]; |
| 240 |
let offset = pos.0 as usize * 4; |
| 241 |
let start = u32::from_le_bytes(table[offset..][0..4].try_into().unwrap()); |
| 242 |
let end = u32::from_le_bytes(table[offset..][4..8].try_into().unwrap()); |
| 243 |
|
| 244 |
let bytes = &self.data[self.path_bytes_base..]; |
| 245 |
&bytes[start as usize..end as usize] |
| 246 |
} |
| 247 |
|
| 248 |
#[cfg(test)] |
| 249 |
fn paths(&self) -> impl ExactSizeIterator<Item = &RepoPath> { |
| 250 |
(0..self.num_paths).map(|pos| self.path(PathPosition(pos))) |
| 251 |
} |
| 252 |
} |
| 253 |
|
| 254 |
/// Changed-path index segment which is not serialized to file. |
| 255 |
#[derive(Clone)] |
| 256 |
pub(super) struct MutableChangedPathIndexSegment { |
| 257 |
entries: Vec<Vec<RepoPathBuf>>, |
| 258 |
} |
| 259 |
|
| 260 |
impl Debug for MutableChangedPathIndexSegment { |
| 261 |
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { |
| 262 |
f.debug_struct("MutableChangedPathIndexSegment") |
| 263 |
.finish_non_exhaustive() |
| 264 |
} |
| 265 |
} |
| 266 |
|
| 267 |
impl MutableChangedPathIndexSegment { |
| 268 |
pub(super) fn empty() -> Self { |
| 269 |
Self { entries: vec![] } |
| 270 |
} |
| 271 |
|
| 272 |
pub(super) fn is_empty(&self) -> bool { |
| 273 |
self.entries.is_empty() |
| 274 |
} |
| 275 |
|
| 276 |
pub(super) fn num_local_commits(&self) -> u32 { |
| 277 |
self.entries.len().try_into().unwrap() |
| 278 |
} |
| 279 |
|
| 280 |
fn changed_paths(&self, pos: CommitPosition) -> impl ExactSizeIterator<Item = &RepoPath> { |
| 281 |
self.entries[pos.0 as usize].iter().map(AsRef::as_ref) |
| 282 |
} |
| 283 |
|
| 284 |
fn add_changed_paths(&mut self, paths: Vec<RepoPathBuf>) { |
| 285 |
debug_assert!(paths.is_sorted_by(|a, b| a < b)); |
| 286 |
self.entries.push(paths); |
| 287 |
} |
| 288 |
|
| 289 |
fn extend_from_readonly_segment(&mut self, other_segment: &ReadonlyChangedPathIndexSegment) { |
| 290 |
self.entries |
| 291 |
.reserve(usize::try_from(other_segment.num_local_commits()).unwrap()); |
| 292 |
for pos in (0..other_segment.num_local_commits()).map(CommitPosition) { |
| 293 |
let paths = other_segment |
| 294 |
.changed_paths(pos) |
| 295 |
.map(|path| path.to_owned()) |
| 296 |
.collect(); |
| 297 |
self.add_changed_paths(paths); |
| 298 |
} |
| 299 |
} |
| 300 |
|
| 301 |
fn extend_from_mutable_segment(&mut self, other_segment: Self) { |
| 302 |
self.entries.extend(other_segment.entries); |
| 303 |
} |
| 304 |
|
| 305 |
fn serialize_into(&self, buf: &mut Vec<u8>) { |
| 306 |
let mut paths = self.entries.iter().flatten().unique().collect_vec(); |
| 307 |
paths.sort_unstable(); |
| 308 |
let path_pos_map: HashMap<_, _> = paths |
| 309 |
.iter() |
| 310 |
.enumerate() |
| 311 |
.map(|(i, &path)| (path, PathPosition(u32::try_from(i).unwrap()))) |
| 312 |
.collect(); |
| 313 |
|
| 314 |
buf.extend(FILE_FORMAT_VERSION.to_le_bytes()); |
| 315 |
let num_commits = u32::try_from(self.entries.len()).unwrap(); |
| 316 |
let num_paths = u32::try_from(paths.len()).unwrap(); |
| 317 |
buf.extend(num_commits.to_le_bytes()); |
| 318 |
let num_changed_paths_offset = buf.len(); |
| 319 |
buf.extend(0_u32.to_le_bytes()); |
| 320 |
buf.extend(num_paths.to_le_bytes()); |
| 321 |
let num_path_bytes_offset = buf.len(); |
| 322 |
buf.extend(0_u32.to_le_bytes()); |
| 323 |
|
| 324 |
let mut num_changed_paths: u32 = 0; |
| 325 |
for paths in &self.entries { |
| 326 |
buf.extend(num_changed_paths.to_le_bytes()); |
| 327 |
num_changed_paths += u32::try_from(paths.len()).unwrap(); |
| 328 |
} |
| 329 |
buf.extend(num_changed_paths.to_le_bytes()); // sentinel |
| 330 |
buf[num_changed_paths_offset..][..4].copy_from_slice(&num_changed_paths.to_le_bytes()); |
| 331 |
|
| 332 |
for path in self.entries.iter().flatten() { |
| 333 |
let PathPosition(pos) = path_pos_map[path]; |
| 334 |
buf.extend(pos.to_le_bytes()); |
| 335 |
} |
| 336 |
|
| 337 |
let mut num_path_bytes: u32 = 0; |
| 338 |
for &path in &paths { |
| 339 |
buf.extend(num_path_bytes.to_le_bytes()); |
| 340 |
num_path_bytes += u32::try_from(path.as_internal_file_string().len()).unwrap(); |
| 341 |
} |
| 342 |
buf.extend(num_path_bytes.to_le_bytes()); // sentinel |
| 343 |
buf[num_path_bytes_offset..][..4].copy_from_slice(&num_path_bytes.to_le_bytes()); |
| 344 |
|
| 345 |
for &path in &paths { |
| 346 |
buf.extend(path.as_internal_file_string().as_bytes()); |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
pub(super) fn save_in( |
| 351 |
&self, |
| 352 |
dir: &Path, |
| 353 |
) -> Result<Arc<ReadonlyChangedPathIndexSegment>, PathError> { |
| 354 |
let mut buf = Vec::new(); |
| 355 |
self.serialize_into(&mut buf); |
| 356 |
let mut hasher = Blake2b512::new(); |
| 357 |
hasher.update(&buf); |
| 358 |
|
| 359 |
let file_id = ChangedPathIndexSegmentId::from_bytes(&hasher.finalize()); |
| 360 |
let file_path = dir.join(file_id.hex()); |
| 361 |
let mut file = NamedTempFile::new_in(dir).context(dir)?; |
| 362 |
file.as_file_mut().write_all(&buf).context(file.path())?; |
| 363 |
persist_content_addressed_temp_file(file, &file_path).context(&file_path)?; |
| 364 |
|
| 365 |
let segment = ReadonlyChangedPathIndexSegment::load_from(&mut &buf[..], file_id) |
| 366 |
.expect("in-memory index data should be valid and readable"); |
| 367 |
Ok(segment) |
| 368 |
} |
| 369 |
} |
| 370 |
|
| 371 |
/// Index of per-commit changed paths. |
| 372 |
#[derive(Clone, Debug)] |
| 373 |
pub(super) struct CompositeChangedPathIndex { |
| 374 |
start_commit_pos: Option<GlobalCommitPosition>, |
| 375 |
num_commits: u32, // cache |
| 376 |
readonly_segments: Vec<Arc<ReadonlyChangedPathIndexSegment>>, |
| 377 |
mutable_segment: Option<Box<MutableChangedPathIndexSegment>>, |
| 378 |
} |
| 379 |
|
| 380 |
impl CompositeChangedPathIndex { |
| 381 |
/// Creates empty changed-path index which cannot store entries. In other |
| 382 |
/// words, the changed-path index is disabled. |
| 383 |
pub(super) fn null() -> Self { |
| 384 |
Self { |
| 385 |
start_commit_pos: None, |
| 386 |
num_commits: 0, |
| 387 |
readonly_segments: vec![], |
| 388 |
mutable_segment: None, |
| 389 |
} |
| 390 |
} |
| 391 |
|
| 392 |
/// Creates empty changed-path index which will store entries from |
| 393 |
/// `start_commit_pos`. |
| 394 |
pub(super) fn empty(start_commit_pos: GlobalCommitPosition) -> Self { |
| 395 |
Self { |
| 396 |
start_commit_pos: Some(start_commit_pos), |
| 397 |
num_commits: 0, |
| 398 |
readonly_segments: vec![], |
| 399 |
mutable_segment: None, |
| 400 |
} |
| 401 |
} |
| 402 |
|
| 403 |
pub(super) fn load( |
| 404 |
dir: &Path, |
| 405 |
start_commit_pos: GlobalCommitPosition, |
| 406 |
ids: &[ChangedPathIndexSegmentId], |
| 407 |
) -> Result<Self, ReadonlyIndexLoadError> { |
| 408 |
let readonly_segments: Vec<_> = ids |
| 409 |
.iter() |
| 410 |
.map(|id| ReadonlyChangedPathIndexSegment::load(dir, id.clone())) |
| 411 |
.try_collect()?; |
| 412 |
let num_commits = readonly_segments |
| 413 |
.iter() |
| 414 |
.map(|segment| segment.num_local_commits()) |
| 415 |
.sum(); |
| 416 |
Ok(Self { |
| 417 |
start_commit_pos: Some(start_commit_pos), |
| 418 |
num_commits, |
| 419 |
readonly_segments, |
| 420 |
mutable_segment: None, |
| 421 |
}) |
| 422 |
} |
| 423 |
|
| 424 |
/// Adds mutable segment if needed. |
| 425 |
pub(super) fn make_mutable(&mut self) { |
| 426 |
if self.start_commit_pos.is_none() || self.mutable_segment.is_some() { |
| 427 |
return; |
| 428 |
} |
| 429 |
self.mutable_segment = Some(Box::new(MutableChangedPathIndexSegment::empty())); |
| 430 |
} |
| 431 |
|
| 432 |
/// Position of the first indexed (or to-be-indexed) commit. |
| 433 |
pub(super) fn start_commit_pos(&self) -> Option<GlobalCommitPosition> { |
| 434 |
self.start_commit_pos |
| 435 |
} |
| 436 |
|
| 437 |
/// New commit index position which can be added to this index. |
| 438 |
pub(super) fn next_mutable_commit_pos(&self) -> Option<GlobalCommitPosition> { |
| 439 |
if self.mutable_segment.is_some() { |
| 440 |
self.start_commit_pos |
| 441 |
.map(|GlobalCommitPosition(start)| GlobalCommitPosition(start + self.num_commits)) |
| 442 |
} else { |
| 443 |
None |
| 444 |
} |
| 445 |
} |
| 446 |
|
| 447 |
pub(super) fn num_commits(&self) -> u32 { |
| 448 |
self.num_commits |
| 449 |
} |
| 450 |
|
| 451 |
pub(super) fn readonly_segments(&self) -> &[Arc<ReadonlyChangedPathIndexSegment>] { |
| 452 |
&self.readonly_segments |
| 453 |
} |
| 454 |
|
| 455 |
/// Appends segments from the `other` index. This and the other index should |
| 456 |
/// be contiguous. |
| 457 |
pub(super) fn append_segments(&mut self, other: &Self) { |
| 458 |
assert!(self.mutable_segment.is_none()); |
| 459 |
let GlobalCommitPosition(self_start_pos) = |
| 460 |
self.start_commit_pos.expect("should have start pos"); |
| 461 |
let Some(GlobalCommitPosition(other_start_pos)) = other.start_commit_pos else { |
| 462 |
return; |
| 463 |
}; |
| 464 |
assert_eq!(self_start_pos + self.num_commits, other_start_pos); |
| 465 |
self.readonly_segments |
| 466 |
.extend_from_slice(&other.readonly_segments); |
| 467 |
self.mutable_segment = other.mutable_segment.clone(); |
| 468 |
self.num_commits += other.num_commits; |
| 469 |
} |
| 470 |
|
| 471 |
/// Maps `global_pos` to segment and segment-local position. |
| 472 |
fn find_segment( |
| 473 |
&self, |
| 474 |
global_pos: GlobalCommitPosition, |
| 475 |
) -> Option<( |
| 476 |
CommitPosition, |
| 477 |
Either<&ReadonlyChangedPathIndexSegment, &MutableChangedPathIndexSegment>, |
| 478 |
)> { |
| 479 |
let mut local_pos = u32::checked_sub(global_pos.0, self.start_commit_pos?.0)?; |
| 480 |
for segment in &self.readonly_segments { |
| 481 |
local_pos = match u32::checked_sub(local_pos, segment.num_local_commits()) { |
| 482 |
Some(next_local_pos) => next_local_pos, |
| 483 |
None => return Some((CommitPosition(local_pos), Either::Left(segment))), |
| 484 |
}; |
| 485 |
} |
| 486 |
let segment = self.mutable_segment.as_deref()?; |
| 487 |
(local_pos < segment.num_local_commits()) |
| 488 |
.then_some((CommitPosition(local_pos), Either::Right(segment))) |
| 489 |
} |
| 490 |
|
| 491 |
/// Returns iterator over paths changed at the specified commit. The paths |
| 492 |
/// are sorted. Returns `None` if the commit wasn't indexed. |
| 493 |
pub(super) fn changed_paths( |
| 494 |
&self, |
| 495 |
global_pos: GlobalCommitPosition, |
| 496 |
) -> Option<impl ExactSizeIterator<Item = &RepoPath>> { |
| 497 |
let (local_pos, segment) = self.find_segment(global_pos)?; |
| 498 |
Some(segment.map_either( |
| 499 |
|x| x.changed_paths(local_pos), |
| 500 |
|x| x.changed_paths(local_pos), |
| 501 |
)) |
| 502 |
} |
| 503 |
|
| 504 |
/// Adds changed paths of the next commit. |
| 505 |
/// |
| 506 |
/// The input `paths` must be sorted. |
| 507 |
/// |
| 508 |
/// Caller must ensure that the commit matches `next_mutable_commit_pos()`. |
| 509 |
/// Panics if this index isn't mutable (i.e. `next_mutable_commit_pos()` is |
| 510 |
/// `None`.) |
| 511 |
pub(super) fn add_changed_paths(&mut self, paths: Vec<RepoPathBuf>) { |
| 512 |
let segment = self |
| 513 |
.mutable_segment |
| 514 |
.as_deref_mut() |
| 515 |
.expect("should have mutable"); |
| 516 |
segment.add_changed_paths(paths); |
| 517 |
self.num_commits += 1; |
| 518 |
} |
| 519 |
|
| 520 |
/// Squashes parent segments if the mutable segment has more than half the |
| 521 |
/// commits of its parent segment. This is done recursively, so the stack of |
| 522 |
/// index segments has O(log n) files. |
| 523 |
pub(super) fn maybe_squash_with_ancestors(&mut self) { |
| 524 |
let Some(mutable_segment) = self.mutable_segment.as_deref() else { |
| 525 |
return; |
| 526 |
}; |
| 527 |
let mut num_new_commits = mutable_segment.num_local_commits(); |
| 528 |
let mut squash_start = self.readonly_segments.len(); |
| 529 |
for segment in self.readonly_segments.iter().rev() { |
| 530 |
// TODO: We should probably also squash if the parent segment has |
| 531 |
// less than N commits, regardless of how many (few) are in |
| 532 |
// `mutable_segment`. |
| 533 |
if 2 * num_new_commits < segment.num_local_commits() { |
| 534 |
break; |
| 535 |
} |
| 536 |
num_new_commits += segment.num_local_commits(); |
| 537 |
squash_start -= 1; |
| 538 |
} |
| 539 |
if squash_start == self.readonly_segments.len() { |
| 540 |
return; |
| 541 |
} |
| 542 |
let mut squashed_segment = Box::new(MutableChangedPathIndexSegment::empty()); |
| 543 |
for segment in self.readonly_segments.drain(squash_start..) { |
| 544 |
squashed_segment.extend_from_readonly_segment(&segment); |
| 545 |
} |
| 546 |
squashed_segment.extend_from_mutable_segment(*self.mutable_segment.take().unwrap()); |
| 547 |
self.mutable_segment = Some(squashed_segment); |
| 548 |
} |
| 549 |
|
| 550 |
/// Writes mutable segment if exists, turns it into readonly segment. |
| 551 |
pub(super) fn save_in(&mut self, dir: &Path) -> Result<(), PathError> { |
| 552 |
let Some(segment) = self.mutable_segment.take() else { |
| 553 |
return Ok(()); |
| 554 |
}; |
| 555 |
if segment.is_empty() { |
| 556 |
return Ok(()); |
| 557 |
} |
| 558 |
let segment = segment.save_in(dir)?; |
| 559 |
self.readonly_segments.push(segment); |
| 560 |
Ok(()) |
| 561 |
} |
| 562 |
} |
| 563 |
|
| 564 |
/// Calculates the parent tree of the given `commit`, and builds a sorted list |
| 565 |
/// of changed paths compared to the parent tree. |
| 566 |
pub(super) async fn collect_changed_paths( |
| 567 |
index: &dyn Index, |
| 568 |
commit: &Commit, |
| 569 |
) -> BackendResult<Vec<RepoPathBuf>> { |
| 570 |
let parents = commit.parents().await?; |
| 571 |
if let [p] = parents.as_slice() |
| 572 |
&& commit.tree_ids() == p.tree_ids() |
| 573 |
{ |
| 574 |
return Ok(vec![]); |
| 575 |
} |
| 576 |
// Don't resolve the entire tree. It's cheaper to resolve each conflict file |
| 577 |
// even if we have to visit all files. |
| 578 |
tracing::trace!(?commit, parents_count = parents.len(), "calculating diffs"); |
| 579 |
let store = commit.store(); |
| 580 |
let from_tree = merge_commit_trees_no_resolve_without_repo(store, index, &parents).await?; |
| 581 |
let to_tree = commit.tree(); |
| 582 |
let tree_diff = from_tree.diff_stream(&to_tree, &EverythingMatcher); |
| 583 |
let paths = tree_diff |
| 584 |
.map(|entry| entry.values.map(|values| (entry.path, values))) |
| 585 |
.try_filter_map(async |(path, mut diff)| { |
| 586 |
diff.before = resolve_file_values(store, &path, diff.before).await?; |
| 587 |
Ok(diff.is_changed().then_some(path)) |
| 588 |
}) |
| 589 |
.try_collect() |
| 590 |
.await?; |
| 591 |
Ok(paths) |
| 592 |
} |
| 593 |
|
| 594 |
#[cfg(test)] |
| 595 |
mod tests { |
| 596 |
use test_case::test_case; |
| 597 |
|
| 598 |
use super::*; |
| 599 |
use crate::tests::TestResult; |
| 600 |
use crate::tests::new_temp_dir; |
| 601 |
|
| 602 |
fn repo_path(value: &str) -> &RepoPath { |
| 603 |
RepoPath::from_internal_string(value).unwrap() |
| 604 |
} |
| 605 |
|
| 606 |
fn repo_path_buf(value: impl Into<String>) -> RepoPathBuf { |
| 607 |
RepoPathBuf::from_internal_string(value).unwrap() |
| 608 |
} |
| 609 |
|
| 610 |
fn collect_changed_paths( |
| 611 |
index: &CompositeChangedPathIndex, |
| 612 |
pos: GlobalCommitPosition, |
| 613 |
) -> Option<Vec<&RepoPath>> { |
| 614 |
Some(index.changed_paths(pos)?.collect()) |
| 615 |
} |
| 616 |
|
| 617 |
#[test] |
| 618 |
fn test_composite_null() { |
| 619 |
let mut index = CompositeChangedPathIndex::null(); |
| 620 |
assert_eq!(index.start_commit_pos(), None); |
| 621 |
assert_eq!(index.next_mutable_commit_pos(), None); |
| 622 |
assert_eq!(collect_changed_paths(&index, GlobalCommitPosition(0)), None); |
| 623 |
|
| 624 |
// No entries can be added to "null" index |
| 625 |
index.make_mutable(); |
| 626 |
assert!(index.mutable_segment.is_none()); |
| 627 |
assert_eq!(index.num_commits(), 0); |
| 628 |
} |
| 629 |
|
| 630 |
#[test] |
| 631 |
fn test_composite_empty() -> TestResult { |
| 632 |
let temp_dir = new_temp_dir(); |
| 633 |
let mut index = CompositeChangedPathIndex::empty(GlobalCommitPosition(0)); |
| 634 |
assert_eq!(index.start_commit_pos(), Some(GlobalCommitPosition(0))); |
| 635 |
assert_eq!(index.next_mutable_commit_pos(), None); |
| 636 |
assert_eq!(collect_changed_paths(&index, GlobalCommitPosition(0)), None); |
| 637 |
|
| 638 |
index.make_mutable(); |
| 639 |
assert!(index.mutable_segment.is_some()); |
| 640 |
assert_eq!( |
| 641 |
index.next_mutable_commit_pos(), |
| 642 |
Some(GlobalCommitPosition(0)) |
| 643 |
); |
| 644 |
assert_eq!(collect_changed_paths(&index, GlobalCommitPosition(0)), None); |
| 645 |
|
| 646 |
// Empty segment shouldn't be saved on disk |
| 647 |
index.save_in(temp_dir.path())?; |
| 648 |
assert!(index.mutable_segment.is_none()); |
| 649 |
assert!(index.readonly_segments.is_empty()); |
| 650 |
assert_eq!(index.start_commit_pos(), Some(GlobalCommitPosition(0))); |
| 651 |
assert_eq!(index.next_mutable_commit_pos(), None); |
| 652 |
assert_eq!(index.num_commits(), 0); |
| 653 |
Ok(()) |
| 654 |
} |
| 655 |
|
| 656 |
#[test_case(false, false; "mutable")] |
| 657 |
#[test_case(true, false; "readonly")] |
| 658 |
#[test_case(true, true; "readonly, reloaded")] |
| 659 |
fn test_composite_some_commits(on_disk: bool, reload: bool) -> TestResult { |
| 660 |
let temp_dir = new_temp_dir(); |
| 661 |
let start_commit_pos = GlobalCommitPosition(1); |
| 662 |
let mut index = CompositeChangedPathIndex::empty(start_commit_pos); |
| 663 |
index.make_mutable(); |
| 664 |
index.add_changed_paths(vec![repo_path_buf("foo")]); |
| 665 |
index.add_changed_paths(vec![]); |
| 666 |
index.add_changed_paths(vec![repo_path_buf("bar/baz"), repo_path_buf("foo")]); |
| 667 |
index.add_changed_paths(vec![]); |
| 668 |
assert_eq!( |
| 669 |
index.next_mutable_commit_pos(), |
| 670 |
Some(GlobalCommitPosition(5)) |
| 671 |
); |
| 672 |
assert_eq!(index.num_commits(), 4); |
| 673 |
if on_disk { |
| 674 |
index.save_in(temp_dir.path())?; |
| 675 |
assert!(index.mutable_segment.is_none()); |
| 676 |
assert_eq!(index.readonly_segments.len(), 1); |
| 677 |
assert_eq!(index.next_mutable_commit_pos(), None); |
| 678 |
assert_eq!(index.num_commits(), 4); |
| 679 |
} |
| 680 |
if reload { |
| 681 |
let ids = index |
| 682 |
.readonly_segments() |
| 683 |
.iter() |
| 684 |
.map(|segment| segment.id().clone()) |
| 685 |
.collect_vec(); |
| 686 |
index = CompositeChangedPathIndex::load(temp_dir.path(), start_commit_pos, &ids)?; |
| 687 |
} |
| 688 |
if let [segment] = &*index.readonly_segments { |
| 689 |
assert_eq!(segment.num_local_commits(), 4); |
| 690 |
assert_eq!(segment.num_changed_paths(), 3); |
| 691 |
assert_eq!(segment.num_paths(), 2); |
| 692 |
assert_eq!( |
| 693 |
segment.paths().collect_vec(), |
| 694 |
[repo_path("bar/baz"), repo_path("foo")] |
| 695 |
); |
| 696 |
} |
| 697 |
|
| 698 |
assert_eq!(collect_changed_paths(&index, GlobalCommitPosition(0)), None); |
| 699 |
assert_eq!( |
| 700 |
collect_changed_paths(&index, GlobalCommitPosition(1)), |
| 701 |
Some(vec![repo_path("foo")]) |
| 702 |
); |
| 703 |
assert_eq!( |
| 704 |
collect_changed_paths(&index, GlobalCommitPosition(2)), |
| 705 |
Some(vec![]) |
| 706 |
); |
| 707 |
assert_eq!( |
| 708 |
collect_changed_paths(&index, GlobalCommitPosition(3)), |
| 709 |
Some(vec![repo_path("bar/baz"), repo_path("foo")]) |
| 710 |
); |
| 711 |
assert_eq!( |
| 712 |
collect_changed_paths(&index, GlobalCommitPosition(4)), |
| 713 |
Some(vec![]) |
| 714 |
); |
| 715 |
assert_eq!(collect_changed_paths(&index, GlobalCommitPosition(5)), None); |
| 716 |
Ok(()) |
| 717 |
} |
| 718 |
|
| 719 |
#[test] |
| 720 |
fn test_composite_empty_commits() -> TestResult { |
| 721 |
let temp_dir = new_temp_dir(); |
| 722 |
let mut index = CompositeChangedPathIndex::empty(GlobalCommitPosition(0)); |
| 723 |
index.make_mutable(); |
| 724 |
// An empty commits table can be serialized/deserialized if forced |
| 725 |
let segment = index.mutable_segment.take().unwrap(); |
| 726 |
let segment = segment.save_in(temp_dir.path())?; |
| 727 |
index.readonly_segments.push(segment); |
| 728 |
assert_eq!(collect_changed_paths(&index, GlobalCommitPosition(0)), None); |
| 729 |
Ok(()) |
| 730 |
} |
| 731 |
|
| 732 |
#[test] |
| 733 |
fn test_composite_empty_changed_paths() -> TestResult { |
| 734 |
let temp_dir = new_temp_dir(); |
| 735 |
let mut index = CompositeChangedPathIndex::empty(GlobalCommitPosition(0)); |
| 736 |
index.make_mutable(); |
| 737 |
index.add_changed_paths(vec![]); |
| 738 |
// An empty paths table can be serialized/deserialized |
| 739 |
assert_eq!(index.num_commits(), 1); |
| 740 |
index.save_in(temp_dir.path())?; |
| 741 |
assert_eq!( |
| 742 |
collect_changed_paths(&index, GlobalCommitPosition(0)), |
| 743 |
Some(vec![]) |
| 744 |
); |
| 745 |
Ok(()) |
| 746 |
} |
| 747 |
|
| 748 |
#[test_case(false; "with mutable")] |
| 749 |
#[test_case(true; "fully readonly")] |
| 750 |
fn test_composite_segmented(on_disk: bool) -> TestResult { |
| 751 |
let temp_dir = new_temp_dir(); |
| 752 |
let mut index = CompositeChangedPathIndex::empty(GlobalCommitPosition(1)); |
| 753 |
index.make_mutable(); |
| 754 |
index.add_changed_paths(vec![repo_path_buf("b")]); |
| 755 |
index.save_in(temp_dir.path())?; |
| 756 |
index.make_mutable(); |
| 757 |
index.add_changed_paths(vec![repo_path_buf("c")]); |
| 758 |
index.add_changed_paths(vec![repo_path_buf("a/b"), repo_path_buf("b")]); |
| 759 |
index.save_in(temp_dir.path())?; |
| 760 |
index.make_mutable(); |
| 761 |
index.add_changed_paths(vec![repo_path_buf("d")]); |
| 762 |
index.add_changed_paths(vec![repo_path_buf("a/c"), repo_path_buf("c")]); |
| 763 |
if on_disk { |
| 764 |
index.save_in(temp_dir.path())?; |
| 765 |
assert!(index.mutable_segment.is_none()); |
| 766 |
assert_eq!(index.readonly_segments.len(), 3); |
| 767 |
assert_eq!(index.next_mutable_commit_pos(), None); |
| 768 |
} else { |
| 769 |
assert_eq!(index.readonly_segments.len(), 2); |
| 770 |
assert!(index.mutable_segment.is_some()); |
| 771 |
} |
| 772 |
assert_eq!(index.num_commits(), 5); |
| 773 |
|
| 774 |
assert_eq!( |
| 775 |
index.readonly_segments[0].paths().collect_vec(), |
| 776 |
[repo_path("b")] |
| 777 |
); |
| 778 |
assert_eq!( |
| 779 |
index.readonly_segments[1].paths().collect_vec(), |
| 780 |
[repo_path("a/b"), repo_path("b"), repo_path("c")] |
| 781 |
); |
| 782 |
if on_disk { |
| 783 |
assert_eq!( |
| 784 |
index.readonly_segments[2].paths().collect_vec(), |
| 785 |
[repo_path("a/c"), repo_path("c"), repo_path("d")] |
| 786 |
); |
| 787 |
} |
| 788 |
|
| 789 |
assert_eq!(collect_changed_paths(&index, GlobalCommitPosition(0)), None); |
| 790 |
assert_eq!( |
| 791 |
collect_changed_paths(&index, GlobalCommitPosition(1)), |
| 792 |
Some(vec![repo_path("b")]) |
| 793 |
); |
| 794 |
assert_eq!( |
| 795 |
collect_changed_paths(&index, GlobalCommitPosition(2)), |
| 796 |
Some(vec![repo_path("c")]) |
| 797 |
); |
| 798 |
assert_eq!( |
| 799 |
collect_changed_paths(&index, GlobalCommitPosition(3)), |
| 800 |
Some(vec![repo_path("a/b"), repo_path("b")]) |
| 801 |
); |
| 802 |
assert_eq!( |
| 803 |
collect_changed_paths(&index, GlobalCommitPosition(4)), |
| 804 |
Some(vec![repo_path("d")]) |
| 805 |
); |
| 806 |
assert_eq!( |
| 807 |
collect_changed_paths(&index, GlobalCommitPosition(5)), |
| 808 |
Some(vec![repo_path("a/c"), repo_path("c")]) |
| 809 |
); |
| 810 |
assert_eq!(collect_changed_paths(&index, GlobalCommitPosition(6)), None); |
| 811 |
Ok(()) |
| 812 |
} |
| 813 |
|
| 814 |
#[test] |
| 815 |
fn test_composite_squash_segments() -> TestResult { |
| 816 |
let temp_dir = new_temp_dir(); |
| 817 |
let mut index = CompositeChangedPathIndex::empty(GlobalCommitPosition(0)); |
| 818 |
index.make_mutable(); |
| 819 |
index.add_changed_paths(vec![repo_path_buf("0")]); |
| 820 |
index.maybe_squash_with_ancestors(); |
| 821 |
index.save_in(temp_dir.path())?; |
| 822 |
assert_eq!(index.readonly_segments.len(), 1); |
| 823 |
assert_eq!(index.readonly_segments[0].num_local_commits(), 1); |
| 824 |
|
| 825 |
index.make_mutable(); |
| 826 |
index.add_changed_paths(vec![repo_path_buf("1")]); |
| 827 |
index.maybe_squash_with_ancestors(); |
| 828 |
index.save_in(temp_dir.path())?; |
| 829 |
assert_eq!(index.readonly_segments.len(), 1); |
| 830 |
assert_eq!(index.readonly_segments[0].num_local_commits(), 2); |
| 831 |
|
| 832 |
index.make_mutable(); |
| 833 |
index.add_changed_paths(vec![repo_path_buf("2")]); |
| 834 |
index.maybe_squash_with_ancestors(); |
| 835 |
index.save_in(temp_dir.path())?; |
| 836 |
assert_eq!(index.readonly_segments.len(), 1); |
| 837 |
assert_eq!(index.readonly_segments[0].num_local_commits(), 3); |
| 838 |
|
| 839 |
index.make_mutable(); |
| 840 |
index.add_changed_paths(vec![repo_path_buf("3")]); |
| 841 |
index.maybe_squash_with_ancestors(); |
| 842 |
index.save_in(temp_dir.path())?; |
| 843 |
assert_eq!(index.readonly_segments.len(), 2); |
| 844 |
assert_eq!(index.readonly_segments[0].num_local_commits(), 3); |
| 845 |
assert_eq!(index.readonly_segments[1].num_local_commits(), 1); |
| 846 |
|
| 847 |
index.make_mutable(); |
| 848 |
index.add_changed_paths(vec![repo_path_buf("4")]); |
| 849 |
index.add_changed_paths(vec![repo_path_buf("5")]); |
| 850 |
index.maybe_squash_with_ancestors(); |
| 851 |
index.save_in(temp_dir.path())?; |
| 852 |
assert_eq!(index.readonly_segments.len(), 1); |
| 853 |
assert_eq!(index.readonly_segments[0].num_local_commits(), 6); |
| 854 |
|
| 855 |
// Squashed segments should preserve the original entries. |
| 856 |
assert_eq!( |
| 857 |
collect_changed_paths(&index, GlobalCommitPosition(0)), |
| 858 |
Some(vec![repo_path("0")]) |
| 859 |
); |
| 860 |
assert_eq!( |
| 861 |
collect_changed_paths(&index, GlobalCommitPosition(1)), |
| 862 |
Some(vec![repo_path("1")]) |
| 863 |
); |
| 864 |
assert_eq!( |
| 865 |
collect_changed_paths(&index, GlobalCommitPosition(2)), |
| 866 |
Some(vec![repo_path("2")]) |
| 867 |
); |
| 868 |
assert_eq!( |
| 869 |
collect_changed_paths(&index, GlobalCommitPosition(3)), |
| 870 |
Some(vec![repo_path("3")]) |
| 871 |
); |
| 872 |
assert_eq!( |
| 873 |
collect_changed_paths(&index, GlobalCommitPosition(4)), |
| 874 |
Some(vec![repo_path("4")]) |
| 875 |
); |
| 876 |
assert_eq!( |
| 877 |
collect_changed_paths(&index, GlobalCommitPosition(5)), |
| 878 |
Some(vec![repo_path("5")]) |
| 879 |
); |
| 880 |
Ok(()) |
| 881 |
} |
| 882 |
} |