Struct git_odb::loose::Store

source ·
pub struct Store { /* private fields */ }
Expand description

A database for reading and writing objects to disk, one file per object.

Implementations§

Object lookup

Returns true if the given id is contained in our repository.

Examples found in repository?
src/store_impls/dynamic/header.rs (line 162)
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
    fn try_header_inner<'b>(
        &'b self,
        mut id: &'b git_hash::oid,
        snapshot: &mut load_index::Snapshot,
        recursion: Option<DeltaBaseRecursion<'_>>,
    ) -> Result<Option<Header>, Error> {
        if let Some(r) = recursion {
            if r.depth >= self.max_recursion_depth {
                return Err(Error::DeltaBaseRecursionLimit {
                    max_depth: self.max_recursion_depth,
                    id: r.original_id.to_owned(),
                });
            }
        } else if !self.ignore_replacements {
            if let Ok(pos) = self
                .store
                .replacements
                .binary_search_by(|(map_this, _)| map_this.as_ref().cmp(id))
            {
                id = self.store.replacements[pos].1.as_ref();
            }
        }

        'outer: loop {
            {
                let marker = snapshot.marker;
                for (idx, index) in snapshot.indices.iter_mut().enumerate() {
                    if let Some(handle::index_lookup::Outcome {
                        object_index: handle::IndexForObjectInPack { pack_id, pack_offset },
                        index_file,
                        pack: possibly_pack,
                    }) = index.lookup(id)
                    {
                        let pack = match possibly_pack {
                            Some(pack) => pack,
                            None => match self.store.load_pack(pack_id, marker)? {
                                Some(pack) => {
                                    *possibly_pack = Some(pack);
                                    possibly_pack.as_deref().expect("just put it in")
                                }
                                None => {
                                    // The pack wasn't available anymore so we are supposed to try another round with a fresh index
                                    match self.store.load_one_index(self.refresh, snapshot.marker)? {
                                        Some(new_snapshot) => {
                                            *snapshot = new_snapshot;
                                            self.clear_cache();
                                            continue 'outer;
                                        }
                                        None => {
                                            // nothing new in the index, kind of unexpected to not have a pack but to also
                                            // to have no new index yet. We set the new index before removing any slots, so
                                            // this should be observable.
                                            return Ok(None);
                                        }
                                    }
                                }
                            },
                        };
                        let entry = pack.entry(pack_offset);
                        let res = match pack.decode_header(entry, |id| {
                            index_file.pack_offset_by_id(id).map(|pack_offset| {
                                git_pack::data::decode::header::ResolvedBase::InPack(pack.entry(pack_offset))
                            })
                        }) {
                            Ok(header) => Ok(header.into()),
                            Err(git_pack::data::decode::Error::DeltaBaseUnresolved(base_id)) => {
                                // Only with multi-pack indices it's allowed to jump to refer to other packs within this
                                // multi-pack. Otherwise this would constitute a thin pack which is only allowed in transit.
                                // However, if we somehow end up with that, we will resolve it safely, even though we could
                                // avoid handling this case and error instead.
                                let hdr = self
                                    .try_header_inner(
                                        &base_id,
                                        snapshot,
                                        recursion
                                            .map(|r| r.inc_depth())
                                            .or_else(|| DeltaBaseRecursion::new(id).into()),
                                    )
                                    .map_err(|err| Error::DeltaBaseLookup {
                                        err: Box::new(err),
                                        base_id,
                                        id: id.to_owned(),
                                    })?
                                    .ok_or_else(|| Error::DeltaBaseMissing {
                                        base_id,
                                        id: id.to_owned(),
                                    })?;
                                let handle::index_lookup::Outcome {
                                    object_index:
                                        handle::IndexForObjectInPack {
                                            pack_id: _,
                                            pack_offset,
                                        },
                                    index_file,
                                    pack: possibly_pack,
                                } = match snapshot.indices[idx].lookup(id) {
                                    Some(res) => res,
                                    None => {
                                        let mut out = None;
                                        for index in snapshot.indices.iter_mut() {
                                            out = index.lookup(id);
                                            if out.is_some() {
                                                break;
                                            }
                                        }

                                        out.unwrap_or_else(|| {
                                            panic!("could not find object {} in any index after looking up one of its base objects {}", id, base_id)
                                        })
                                    }
                                };
                                let pack = possibly_pack
                                    .as_ref()
                                    .expect("pack to still be available like just now");
                                let entry = pack.entry(pack_offset);
                                pack.decode_header(entry, |id| {
                                    index_file
                                        .pack_offset_by_id(id)
                                        .map(|pack_offset| {
                                            git_pack::data::decode::header::ResolvedBase::InPack(
                                                pack.entry(pack_offset),
                                            )
                                        })
                                        .or_else(|| {
                                            (id == base_id).then(|| {
                                                git_pack::data::decode::header::ResolvedBase::OutOfPack {
                                                    kind: hdr.kind(),
                                                    num_deltas: hdr.num_deltas(),
                                                }
                                            })
                                        })
                                })
                                .map(Into::into)
                            }
                            Err(err) => Err(err),
                        }?;

                        if idx != 0 {
                            snapshot.indices.swap(0, idx);
                        }
                        return Ok(Some(res));
                    }
                }
            }

            for lodb in snapshot.loose_dbs.iter() {
                // TODO: remove this double-lookup once the borrow checker allows it.
                if lodb.contains(id) {
                    return lodb.try_header(id).map(|opt| opt.map(Into::into)).map_err(Into::into);
                }
            }

            match self.store.load_one_index(self.refresh, snapshot.marker)? {
                Some(new_snapshot) => {
                    *snapshot = new_snapshot;
                    self.clear_cache();
                }
                None => return Ok(None),
            }
        }
    }
More examples
Hide additional examples
src/store_impls/dynamic/find.rs (line 282)
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
    fn try_find_cached_inner<'a, 'b>(
        &'b self,
        mut id: &'b git_hash::oid,
        buffer: &'a mut Vec<u8>,
        pack_cache: &mut impl DecodeEntry,
        snapshot: &mut load_index::Snapshot,
        recursion: Option<error::DeltaBaseRecursion<'_>>,
    ) -> Result<Option<(git_object::Data<'a>, Option<git_pack::data::entry::Location>)>, Error> {
        if let Some(r) = recursion {
            if r.depth >= self.max_recursion_depth {
                return Err(Error::DeltaBaseRecursionLimit {
                    max_depth: self.max_recursion_depth,
                    id: r.original_id.to_owned(),
                });
            }
        } else if !self.ignore_replacements {
            if let Ok(pos) = self
                .store
                .replacements
                .binary_search_by(|(map_this, _)| map_this.as_ref().cmp(id))
            {
                id = self.store.replacements[pos].1.as_ref();
            }
        }

        'outer: loop {
            {
                let marker = snapshot.marker;
                for (idx, index) in snapshot.indices.iter_mut().enumerate() {
                    if let Some(handle::index_lookup::Outcome {
                        object_index: handle::IndexForObjectInPack { pack_id, pack_offset },
                        index_file,
                        pack: possibly_pack,
                    }) = index.lookup(id)
                    {
                        let pack = match possibly_pack {
                            Some(pack) => pack,
                            None => match self.store.load_pack(pack_id, marker)? {
                                Some(pack) => {
                                    *possibly_pack = Some(pack);
                                    possibly_pack.as_deref().expect("just put it in")
                                }
                                None => {
                                    // The pack wasn't available anymore so we are supposed to try another round with a fresh index
                                    match self.store.load_one_index(self.refresh, snapshot.marker)? {
                                        Some(new_snapshot) => {
                                            *snapshot = new_snapshot;
                                            self.clear_cache();
                                            continue 'outer;
                                        }
                                        None => {
                                            // nothing new in the index, kind of unexpected to not have a pack but to also
                                            // to have no new index yet. We set the new index before removing any slots, so
                                            // this should be observable.
                                            return Ok(None);
                                        }
                                    }
                                }
                            },
                        };
                        let entry = pack.entry(pack_offset);
                        let header_size = entry.header_size();
                        let res = match pack.decode_entry(
                            entry,
                            buffer,
                            |id, _out| {
                                index_file.pack_offset_by_id(id).map(|pack_offset| {
                                    git_pack::data::decode::entry::ResolvedBase::InPack(pack.entry(pack_offset))
                                })
                            },
                            pack_cache,
                        ) {
                            Ok(r) => Ok((
                                git_object::Data {
                                    kind: r.kind,
                                    data: buffer.as_slice(),
                                },
                                Some(git_pack::data::entry::Location {
                                    pack_id: pack.id,
                                    pack_offset,
                                    entry_size: r.compressed_size + header_size,
                                }),
                            )),
                            Err(git_pack::data::decode::Error::DeltaBaseUnresolved(base_id)) => {
                                // Only with multi-pack indices it's allowed to jump to refer to other packs within this
                                // multi-pack. Otherwise this would constitute a thin pack which is only allowed in transit.
                                // However, if we somehow end up with that, we will resolve it safely, even though we could
                                // avoid handling this case and error instead.

                                // Since this is a special case, we just allocate here to make it work. It's an actual delta-ref object
                                // which is sent by some servers that points to an object outside of the pack we are looking
                                // at right now. With the complexities of loading packs, we go into recursion here. Git itself
                                // doesn't do a cycle check, and we won't either but limit the recursive depth.
                                // The whole ordeal isn't as efficient as it could be due to memory allocation and
                                // later mem-copying when trying again.
                                let mut buf = Vec::new();
                                let obj_kind = self
                                    .try_find_cached_inner(
                                        &base_id,
                                        &mut buf,
                                        pack_cache,
                                        snapshot,
                                        recursion
                                            .map(|r| r.inc_depth())
                                            .or_else(|| error::DeltaBaseRecursion::new(id).into()),
                                    )
                                    .map_err(|err| Error::DeltaBaseLookup {
                                        err: Box::new(err),
                                        base_id,
                                        id: id.to_owned(),
                                    })?
                                    .ok_or_else(|| Error::DeltaBaseMissing {
                                        base_id,
                                        id: id.to_owned(),
                                    })?
                                    .0
                                    .kind;
                                let handle::index_lookup::Outcome {
                                    object_index:
                                        handle::IndexForObjectInPack {
                                            pack_id: _,
                                            pack_offset,
                                        },
                                    index_file,
                                    pack: possibly_pack,
                                } = match snapshot.indices[idx].lookup(id) {
                                    Some(res) => res,
                                    None => {
                                        let mut out = None;
                                        for index in snapshot.indices.iter_mut() {
                                            out = index.lookup(id);
                                            if out.is_some() {
                                                break;
                                            }
                                        }

                                        out.unwrap_or_else(|| {
                                           panic!("could not find object {} in any index after looking up one of its base objects {}", id, base_id)
                                       })
                                    }
                                };
                                let pack = possibly_pack
                                    .as_ref()
                                    .expect("pack to still be available like just now");
                                let entry = pack.entry(pack_offset);
                                let header_size = entry.header_size();
                                pack.decode_entry(
                                    entry,
                                    buffer,
                                    |id, out| {
                                        index_file
                                            .pack_offset_by_id(id)
                                            .map(|pack_offset| {
                                                git_pack::data::decode::entry::ResolvedBase::InPack(
                                                    pack.entry(pack_offset),
                                                )
                                            })
                                            .or_else(|| {
                                                (id == base_id).then(|| {
                                                    out.resize(buf.len(), 0);
                                                    out.copy_from_slice(buf.as_slice());
                                                    git_pack::data::decode::entry::ResolvedBase::OutOfPack {
                                                        kind: obj_kind,
                                                        end: out.len(),
                                                    }
                                                })
                                            })
                                    },
                                    pack_cache,
                                )
                                .map(move |r| {
                                    (
                                        git_object::Data {
                                            kind: r.kind,
                                            data: buffer.as_slice(),
                                        },
                                        Some(git_pack::data::entry::Location {
                                            pack_id: pack.id,
                                            pack_offset,
                                            entry_size: r.compressed_size + header_size,
                                        }),
                                    )
                                })
                            }
                            Err(err) => Err(err),
                        }?;

                        if idx != 0 {
                            snapshot.indices.swap(0, idx);
                        }
                        return Ok(Some(res));
                    }
                }
            }

            for lodb in snapshot.loose_dbs.iter() {
                // TODO: remove this double-lookup once the borrow checker allows it.
                if lodb.contains(id) {
                    return lodb
                        .try_find(id, buffer)
                        .map(|obj| obj.map(|obj| (obj, None)))
                        .map_err(Into::into);
                }
            }

            match self.store.load_one_index(self.refresh, snapshot.marker)? {
                Some(new_snapshot) => {
                    *snapshot = new_snapshot;
                    self.clear_cache();
                }
                None => return Ok(None),
            }
        }
    }

    pub(crate) fn clear_cache(&self) {
        self.packed_object_count.borrow_mut().take();
    }
}

impl<S> git_pack::Find for super::Handle<S>
where
    S: Deref<Target = super::Store> + Clone,
{
    type Error = Error;

    // TODO: probably make this method fallible, but that would mean its own error type.
    fn contains(&self, id: impl AsRef<git_hash::oid>) -> bool {
        let id = id.as_ref();
        let mut snapshot = self.snapshot.borrow_mut();
        loop {
            for (idx, index) in snapshot.indices.iter().enumerate() {
                if index.contains(id) {
                    if idx != 0 {
                        snapshot.indices.swap(0, idx);
                    }
                    return true;
                }
            }

            for lodb in snapshot.loose_dbs.iter() {
                if lodb.contains(id) {
                    return true;
                }
            }

            match self.store.load_one_index(self.refresh, snapshot.marker) {
                Ok(Some(new_snapshot)) => {
                    *snapshot = new_snapshot;
                    self.clear_cache();
                }
                Ok(None) => return false, // nothing more to load, or our refresh mode doesn't allow disk refreshes
                Err(_) => return false, // something went wrong, nothing we can communicate here with this trait. TODO: Maybe that should change?
            }
        }
    }

Given a prefix, find an object that matches it uniquely within this loose object database as Ok(Some(Ok(<oid>))). If there is more than one object matching the object Ok(Some(Err(())) is returned.

Finally, if no object matches, the return value is Ok(None).

The outer Result is to indicate errors during file system traversal.

Pass candidates to obtain the set of all object ids matching prefix, with the same return value as one would have received if it remained None.

Examples found in repository?
src/store_impls/dynamic/prefix.rs (line 158)
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
    pub fn lookup_prefix(
        &self,
        prefix: git_hash::Prefix,
        mut candidates: Option<&mut HashSet<git_hash::ObjectId>>,
    ) -> Result<Option<lookup::Outcome>, lookup::Error> {
        let mut candidate: Option<git_hash::ObjectId> = None;
        loop {
            let snapshot = self.snapshot.borrow();
            for index in snapshot.indices.iter() {
                #[allow(clippy::needless_option_as_deref)] // needed as it's the equivalent of a reborrow.
                let lookup_result = index.lookup_prefix(prefix, candidates.as_deref_mut());
                if candidates.is_none() && !check_candidate(lookup_result, &mut candidate) {
                    return Ok(Some(Err(())));
                }
            }

            for lodb in snapshot.loose_dbs.iter() {
                #[allow(clippy::needless_option_as_deref)] // needed as it's the equivalent of a reborrow.
                let lookup_result = lodb.lookup_prefix(prefix, candidates.as_deref_mut())?;
                if candidates.is_none() && !check_candidate(lookup_result, &mut candidate) {
                    return Ok(Some(Err(())));
                }
            }

            match self.store.load_one_index(self.refresh, snapshot.marker)? {
                Some(new_snapshot) => {
                    drop(snapshot);
                    *self.snapshot.borrow_mut() = new_snapshot;
                }
                None => {
                    return match &candidates {
                        Some(candidates) => match candidates.len() {
                            0 => Ok(None),
                            1 => Ok(candidates.iter().cloned().next().map(Ok)),
                            _ => Ok(Some(Err(()))),
                        },
                        None => Ok(candidate.map(Ok)),
                    };
                }
            }
        }

        fn check_candidate(lookup_result: Option<lookup::Outcome>, candidate: &mut Option<git_hash::ObjectId>) -> bool {
            match (lookup_result, &*candidate) {
                (Some(Ok(oid)), Some(candidate)) if *candidate != oid => false,
                (Some(Ok(_)), Some(_)) | (None, None) | (None, Some(_)) => true,
                (Some(Err(())), _) => false,
                (Some(Ok(oid)), None) => {
                    *candidate = Some(oid);
                    true
                }
            }
        }
    }

Return the object identified by the given ObjectId if present in this database, writing its raw data into the given out buffer.

Returns Err if there was an error locating or reading the object. Returns Ok<None> if there was no such object.

Examples found in repository?
src/store_impls/loose/verify.rs (line 59)
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
    pub fn verify_integrity(
        &self,
        mut progress: impl Progress,
        should_interrupt: &AtomicBool,
    ) -> Result<integrity::Statistics, integrity::Error> {
        let mut buf = Vec::new();
        let sink = crate::sink(self.object_hash);

        let mut num_objects = 0;
        let start = Instant::now();
        let mut progress = progress.add_child_with_id("Validating", *b"VILO"); /* Verify Integrity Loose Objects */
        progress.init(None, git_features::progress::count("loose objects"));
        for id in self.iter().filter_map(Result::ok) {
            let object = self
                .try_find(id, &mut buf)
                .map_err(|_| integrity::Error::Retry)?
                .ok_or(integrity::Error::Retry)?;
            let actual_id = sink.write_buf(object.kind, object.data).expect("sink never fails");
            if actual_id != id {
                return Err(integrity::Error::ObjectHashMismatch {
                    kind: object.kind,
                    actual: actual_id,
                    expected: id,
                });
            }
            object.decode().map_err(|err| integrity::Error::ObjectDecode {
                source: err,
                kind: object.kind,
                id,
            })?;

            progress.inc();
            num_objects += 1;
            if should_interrupt.load(Ordering::SeqCst) {
                return Err(integrity::Error::Interrupted);
            }
        }
        progress.show_throughput(start);

        Ok(integrity::Statistics { num_objects })
    }
More examples
Hide additional examples
src/store_impls/dynamic/find.rs (line 284)
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
    fn try_find_cached_inner<'a, 'b>(
        &'b self,
        mut id: &'b git_hash::oid,
        buffer: &'a mut Vec<u8>,
        pack_cache: &mut impl DecodeEntry,
        snapshot: &mut load_index::Snapshot,
        recursion: Option<error::DeltaBaseRecursion<'_>>,
    ) -> Result<Option<(git_object::Data<'a>, Option<git_pack::data::entry::Location>)>, Error> {
        if let Some(r) = recursion {
            if r.depth >= self.max_recursion_depth {
                return Err(Error::DeltaBaseRecursionLimit {
                    max_depth: self.max_recursion_depth,
                    id: r.original_id.to_owned(),
                });
            }
        } else if !self.ignore_replacements {
            if let Ok(pos) = self
                .store
                .replacements
                .binary_search_by(|(map_this, _)| map_this.as_ref().cmp(id))
            {
                id = self.store.replacements[pos].1.as_ref();
            }
        }

        'outer: loop {
            {
                let marker = snapshot.marker;
                for (idx, index) in snapshot.indices.iter_mut().enumerate() {
                    if let Some(handle::index_lookup::Outcome {
                        object_index: handle::IndexForObjectInPack { pack_id, pack_offset },
                        index_file,
                        pack: possibly_pack,
                    }) = index.lookup(id)
                    {
                        let pack = match possibly_pack {
                            Some(pack) => pack,
                            None => match self.store.load_pack(pack_id, marker)? {
                                Some(pack) => {
                                    *possibly_pack = Some(pack);
                                    possibly_pack.as_deref().expect("just put it in")
                                }
                                None => {
                                    // The pack wasn't available anymore so we are supposed to try another round with a fresh index
                                    match self.store.load_one_index(self.refresh, snapshot.marker)? {
                                        Some(new_snapshot) => {
                                            *snapshot = new_snapshot;
                                            self.clear_cache();
                                            continue 'outer;
                                        }
                                        None => {
                                            // nothing new in the index, kind of unexpected to not have a pack but to also
                                            // to have no new index yet. We set the new index before removing any slots, so
                                            // this should be observable.
                                            return Ok(None);
                                        }
                                    }
                                }
                            },
                        };
                        let entry = pack.entry(pack_offset);
                        let header_size = entry.header_size();
                        let res = match pack.decode_entry(
                            entry,
                            buffer,
                            |id, _out| {
                                index_file.pack_offset_by_id(id).map(|pack_offset| {
                                    git_pack::data::decode::entry::ResolvedBase::InPack(pack.entry(pack_offset))
                                })
                            },
                            pack_cache,
                        ) {
                            Ok(r) => Ok((
                                git_object::Data {
                                    kind: r.kind,
                                    data: buffer.as_slice(),
                                },
                                Some(git_pack::data::entry::Location {
                                    pack_id: pack.id,
                                    pack_offset,
                                    entry_size: r.compressed_size + header_size,
                                }),
                            )),
                            Err(git_pack::data::decode::Error::DeltaBaseUnresolved(base_id)) => {
                                // Only with multi-pack indices it's allowed to jump to refer to other packs within this
                                // multi-pack. Otherwise this would constitute a thin pack which is only allowed in transit.
                                // However, if we somehow end up with that, we will resolve it safely, even though we could
                                // avoid handling this case and error instead.

                                // Since this is a special case, we just allocate here to make it work. It's an actual delta-ref object
                                // which is sent by some servers that points to an object outside of the pack we are looking
                                // at right now. With the complexities of loading packs, we go into recursion here. Git itself
                                // doesn't do a cycle check, and we won't either but limit the recursive depth.
                                // The whole ordeal isn't as efficient as it could be due to memory allocation and
                                // later mem-copying when trying again.
                                let mut buf = Vec::new();
                                let obj_kind = self
                                    .try_find_cached_inner(
                                        &base_id,
                                        &mut buf,
                                        pack_cache,
                                        snapshot,
                                        recursion
                                            .map(|r| r.inc_depth())
                                            .or_else(|| error::DeltaBaseRecursion::new(id).into()),
                                    )
                                    .map_err(|err| Error::DeltaBaseLookup {
                                        err: Box::new(err),
                                        base_id,
                                        id: id.to_owned(),
                                    })?
                                    .ok_or_else(|| Error::DeltaBaseMissing {
                                        base_id,
                                        id: id.to_owned(),
                                    })?
                                    .0
                                    .kind;
                                let handle::index_lookup::Outcome {
                                    object_index:
                                        handle::IndexForObjectInPack {
                                            pack_id: _,
                                            pack_offset,
                                        },
                                    index_file,
                                    pack: possibly_pack,
                                } = match snapshot.indices[idx].lookup(id) {
                                    Some(res) => res,
                                    None => {
                                        let mut out = None;
                                        for index in snapshot.indices.iter_mut() {
                                            out = index.lookup(id);
                                            if out.is_some() {
                                                break;
                                            }
                                        }

                                        out.unwrap_or_else(|| {
                                           panic!("could not find object {} in any index after looking up one of its base objects {}", id, base_id)
                                       })
                                    }
                                };
                                let pack = possibly_pack
                                    .as_ref()
                                    .expect("pack to still be available like just now");
                                let entry = pack.entry(pack_offset);
                                let header_size = entry.header_size();
                                pack.decode_entry(
                                    entry,
                                    buffer,
                                    |id, out| {
                                        index_file
                                            .pack_offset_by_id(id)
                                            .map(|pack_offset| {
                                                git_pack::data::decode::entry::ResolvedBase::InPack(
                                                    pack.entry(pack_offset),
                                                )
                                            })
                                            .or_else(|| {
                                                (id == base_id).then(|| {
                                                    out.resize(buf.len(), 0);
                                                    out.copy_from_slice(buf.as_slice());
                                                    git_pack::data::decode::entry::ResolvedBase::OutOfPack {
                                                        kind: obj_kind,
                                                        end: out.len(),
                                                    }
                                                })
                                            })
                                    },
                                    pack_cache,
                                )
                                .map(move |r| {
                                    (
                                        git_object::Data {
                                            kind: r.kind,
                                            data: buffer.as_slice(),
                                        },
                                        Some(git_pack::data::entry::Location {
                                            pack_id: pack.id,
                                            pack_offset,
                                            entry_size: r.compressed_size + header_size,
                                        }),
                                    )
                                })
                            }
                            Err(err) => Err(err),
                        }?;

                        if idx != 0 {
                            snapshot.indices.swap(0, idx);
                        }
                        return Ok(Some(res));
                    }
                }
            }

            for lodb in snapshot.loose_dbs.iter() {
                // TODO: remove this double-lookup once the borrow checker allows it.
                if lodb.contains(id) {
                    return lodb
                        .try_find(id, buffer)
                        .map(|obj| obj.map(|obj| (obj, None)))
                        .map_err(Into::into);
                }
            }

            match self.store.load_one_index(self.refresh, snapshot.marker)? {
                Some(new_snapshot) => {
                    *snapshot = new_snapshot;
                    self.clear_cache();
                }
                None => return Ok(None),
            }
        }
    }

Return only the decompressed size of the object and its kind without fully reading it into memory as tuple of (size, kind). Returns None if id does not exist in the database.

Examples found in repository?
src/store_impls/dynamic/header.rs (line 163)
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
    fn try_header_inner<'b>(
        &'b self,
        mut id: &'b git_hash::oid,
        snapshot: &mut load_index::Snapshot,
        recursion: Option<DeltaBaseRecursion<'_>>,
    ) -> Result<Option<Header>, Error> {
        if let Some(r) = recursion {
            if r.depth >= self.max_recursion_depth {
                return Err(Error::DeltaBaseRecursionLimit {
                    max_depth: self.max_recursion_depth,
                    id: r.original_id.to_owned(),
                });
            }
        } else if !self.ignore_replacements {
            if let Ok(pos) = self
                .store
                .replacements
                .binary_search_by(|(map_this, _)| map_this.as_ref().cmp(id))
            {
                id = self.store.replacements[pos].1.as_ref();
            }
        }

        'outer: loop {
            {
                let marker = snapshot.marker;
                for (idx, index) in snapshot.indices.iter_mut().enumerate() {
                    if let Some(handle::index_lookup::Outcome {
                        object_index: handle::IndexForObjectInPack { pack_id, pack_offset },
                        index_file,
                        pack: possibly_pack,
                    }) = index.lookup(id)
                    {
                        let pack = match possibly_pack {
                            Some(pack) => pack,
                            None => match self.store.load_pack(pack_id, marker)? {
                                Some(pack) => {
                                    *possibly_pack = Some(pack);
                                    possibly_pack.as_deref().expect("just put it in")
                                }
                                None => {
                                    // The pack wasn't available anymore so we are supposed to try another round with a fresh index
                                    match self.store.load_one_index(self.refresh, snapshot.marker)? {
                                        Some(new_snapshot) => {
                                            *snapshot = new_snapshot;
                                            self.clear_cache();
                                            continue 'outer;
                                        }
                                        None => {
                                            // nothing new in the index, kind of unexpected to not have a pack but to also
                                            // to have no new index yet. We set the new index before removing any slots, so
                                            // this should be observable.
                                            return Ok(None);
                                        }
                                    }
                                }
                            },
                        };
                        let entry = pack.entry(pack_offset);
                        let res = match pack.decode_header(entry, |id| {
                            index_file.pack_offset_by_id(id).map(|pack_offset| {
                                git_pack::data::decode::header::ResolvedBase::InPack(pack.entry(pack_offset))
                            })
                        }) {
                            Ok(header) => Ok(header.into()),
                            Err(git_pack::data::decode::Error::DeltaBaseUnresolved(base_id)) => {
                                // Only with multi-pack indices it's allowed to jump to refer to other packs within this
                                // multi-pack. Otherwise this would constitute a thin pack which is only allowed in transit.
                                // However, if we somehow end up with that, we will resolve it safely, even though we could
                                // avoid handling this case and error instead.
                                let hdr = self
                                    .try_header_inner(
                                        &base_id,
                                        snapshot,
                                        recursion
                                            .map(|r| r.inc_depth())
                                            .or_else(|| DeltaBaseRecursion::new(id).into()),
                                    )
                                    .map_err(|err| Error::DeltaBaseLookup {
                                        err: Box::new(err),
                                        base_id,
                                        id: id.to_owned(),
                                    })?
                                    .ok_or_else(|| Error::DeltaBaseMissing {
                                        base_id,
                                        id: id.to_owned(),
                                    })?;
                                let handle::index_lookup::Outcome {
                                    object_index:
                                        handle::IndexForObjectInPack {
                                            pack_id: _,
                                            pack_offset,
                                        },
                                    index_file,
                                    pack: possibly_pack,
                                } = match snapshot.indices[idx].lookup(id) {
                                    Some(res) => res,
                                    None => {
                                        let mut out = None;
                                        for index in snapshot.indices.iter_mut() {
                                            out = index.lookup(id);
                                            if out.is_some() {
                                                break;
                                            }
                                        }

                                        out.unwrap_or_else(|| {
                                            panic!("could not find object {} in any index after looking up one of its base objects {}", id, base_id)
                                        })
                                    }
                                };
                                let pack = possibly_pack
                                    .as_ref()
                                    .expect("pack to still be available like just now");
                                let entry = pack.entry(pack_offset);
                                pack.decode_header(entry, |id| {
                                    index_file
                                        .pack_offset_by_id(id)
                                        .map(|pack_offset| {
                                            git_pack::data::decode::header::ResolvedBase::InPack(
                                                pack.entry(pack_offset),
                                            )
                                        })
                                        .or_else(|| {
                                            (id == base_id).then(|| {
                                                git_pack::data::decode::header::ResolvedBase::OutOfPack {
                                                    kind: hdr.kind(),
                                                    num_deltas: hdr.num_deltas(),
                                                }
                                            })
                                        })
                                })
                                .map(Into::into)
                            }
                            Err(err) => Err(err),
                        }?;

                        if idx != 0 {
                            snapshot.indices.swap(0, idx);
                        }
                        return Ok(Some(res));
                    }
                }
            }

            for lodb in snapshot.loose_dbs.iter() {
                // TODO: remove this double-lookup once the borrow checker allows it.
                if lodb.contains(id) {
                    return lodb.try_header(id).map(|opt| opt.map(Into::into)).map_err(Into::into);
                }
            }

            match self.store.load_one_index(self.refresh, snapshot.marker)? {
                Some(new_snapshot) => {
                    *snapshot = new_snapshot;
                    self.clear_cache();
                }
                None => return Ok(None),
            }
        }
    }

Iteration and traversal

Return an iterator over all objects contained in the database.

The Ids returned by the iterator can typically be used in the locate(…) method. Note that the result is not sorted or stable, thus ordering can change between runs.

Notes

loose::Iter is used instead of impl Iterator<…> to allow using this iterator in struct fields, as is currently needed if iterators need to be implemented by hand in the absence of generators.

Examples found in repository?
src/store_impls/dynamic/iter.rs (line 101)
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
    pub fn new(db: &dynamic::Store) -> Result<Self, crate::store::load_index::Error> {
        let snapshot = db.load_all_indices()?;

        let packed_objects = snapshot
            .indices
            .iter()
            .fold(0usize, |dbc, index| dbc.saturating_add(index.num_objects() as usize));
        let mut index_iter = snapshot.indices.into_iter();
        let loose_dbs = snapshot.loose_dbs;
        let order = Default::default();
        let state = match index_iter.next() {
            Some(index) => {
                let num_objects = index.num_objects();
                State::Pack {
                    index_iter,
                    ordered_entries: maybe_sort_entries(&index, order),
                    index,
                    entry_index: 0,
                    num_objects,
                }
            }
            None => {
                let index = 0;
                State::Loose {
                    iter: loose_dbs.get(index).expect("at least one loose db").iter(),
                    index,
                }
            }
        };
        Ok(AllObjects {
            state,
            loose_dbs,
            num_objects: packed_objects,
            order,
        })
    }
}

fn maybe_sort_entries(index: &handle::IndexLookup, order: Ordering) -> Option<Vec<EntryForOrdering>> {
    let mut order: Vec<_> = match order {
        Ordering::PackLexicographicalThenLooseLexicographical => return None,
        Ordering::PackAscendingOffsetThenLooseLexicographical => match &index.file {
            // We know that we cannot have more than u32 entry indices per pack.
            SingleOrMultiIndex::Single { index, .. } => index
                .iter()
                .enumerate()
                .map(|(idx, e)| EntryForOrdering {
                    pack_offset: e.pack_offset,
                    entry_index: idx as u32,
                    pack_index: 0,
                })
                .collect(),
            SingleOrMultiIndex::Multi { index, .. } => index
                .iter()
                .enumerate()
                .map(|(idx, e)| EntryForOrdering {
                    pack_offset: e.pack_offset,
                    entry_index: idx as u32,
                    pack_index: {
                        debug_assert!(
                            e.pack_index < PackId::max_packs_in_multi_index(),
                            "this shows the relation between u16 and pack_index (u32) and why this is OK"
                        );
                        e.pack_index as u16
                    },
                })
                .collect(),
        },
    };
    order.sort_by(|a, b| {
        a.pack_index
            .cmp(&b.pack_index)
            .then_with(|| a.pack_offset.cmp(&b.pack_offset))
    });
    Some(order)
}

impl Iterator for AllObjects {
    type Item = Result<ObjectId, loose::iter::Error>;

    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.state {
            State::Depleted => None,
            State::Pack {
                index_iter,
                ordered_entries,
                index,
                entry_index,
                num_objects,
            } => {
                if *entry_index < *num_objects {
                    let oid = match ordered_entries {
                        Some(entries) => index.oid_at_index(entries[*entry_index as usize].entry_index),
                        None => index.oid_at_index(*entry_index),
                    }
                    .to_owned();
                    *entry_index += 1;
                    Some(Ok(oid))
                } else {
                    match index_iter.next() {
                        Some(new_index) => {
                            *ordered_entries = maybe_sort_entries(&new_index, self.order);
                            *index = new_index;
                            *entry_index = 0;
                            *num_objects = index.num_objects();
                        }
                        None => {
                            let index = 0;
                            self.state = State::Loose {
                                iter: self.loose_dbs.get(index).expect("at least one loose odb").iter(),
                                index,
                            }
                        }
                    }
                    self.next()
                }
            }
            State::Loose { iter, index } => match iter.next() {
                Some(id) => Some(id),
                None => {
                    *index += 1;
                    match self.loose_dbs.get(*index).map(|ldb| ldb.iter()) {
                        Some(new_iter) => {
                            *iter = new_iter;
                            self.next()
                        }
                        None => {
                            self.state = State::Depleted;
                            None
                        }
                    }
                }
            },
        }
    }
More examples
Hide additional examples
src/store_impls/loose/verify.rs (line 57)
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
    pub fn verify_integrity(
        &self,
        mut progress: impl Progress,
        should_interrupt: &AtomicBool,
    ) -> Result<integrity::Statistics, integrity::Error> {
        let mut buf = Vec::new();
        let sink = crate::sink(self.object_hash);

        let mut num_objects = 0;
        let start = Instant::now();
        let mut progress = progress.add_child_with_id("Validating", *b"VILO"); /* Verify Integrity Loose Objects */
        progress.init(None, git_features::progress::count("loose objects"));
        for id in self.iter().filter_map(Result::ok) {
            let object = self
                .try_find(id, &mut buf)
                .map_err(|_| integrity::Error::Retry)?
                .ok_or(integrity::Error::Retry)?;
            let actual_id = sink.write_buf(object.kind, object.data).expect("sink never fails");
            if actual_id != id {
                return Err(integrity::Error::ObjectHashMismatch {
                    kind: object.kind,
                    actual: actual_id,
                    expected: id,
                });
            }
            object.decode().map_err(|err| integrity::Error::ObjectDecode {
                source: err,
                kind: object.kind,
                id,
            })?;

            progress.inc();
            num_objects += 1;
            if should_interrupt.load(Ordering::SeqCst) {
                return Err(integrity::Error::Interrupted);
            }
        }
        progress.show_throughput(start);

        Ok(integrity::Statistics { num_objects })
    }
src/store_impls/dynamic/mod.rs (line 155)
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
        pub fn structure(&self) -> Result<Vec<Record>, load_index::Error> {
            let index = self.index.load();
            if !index.is_initialized() {
                self.consolidate_with_disk_state(true, false /*load one new index*/)?;
            }
            let index = self.index.load();
            let mut res: Vec<_> = index
                .loose_dbs
                .iter()
                .map(|db| Record::LooseObjectDatabase {
                    objects_directory: db.path.clone(),
                    num_objects: db.iter().count(),
                })
                .collect();

            for slot in index.slot_indices.iter().map(|idx| &self.files[*idx]) {
                let files = slot.files.load();
                let record = match &**files {
                    Some(index) => {
                        let state = if index.is_disposable() {
                            IndexState::Disposable
                        } else if index.index_is_loaded() {
                            IndexState::Loaded
                        } else {
                            IndexState::Unloaded
                        };
                        match index {
                            IndexAndPacks::Index(b) => Record::Index {
                                path: b.index.path().into(),
                                state,
                            },
                            IndexAndPacks::MultiIndex(b) => Record::MultiIndex {
                                path: b.multi_index.path().into(),
                                state,
                            },
                        }
                    }
                    None => Record::Empty,
                };
                res.push(record);
            }
            Ok(res)
        }

Check all loose objects for their integrity checking their hash matches the actual data and by decoding them fully.

Examples found in repository?
src/store_impls/dynamic/verify.rs (lines 218-221)
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
    pub fn verify_integrity<C, P, F>(
        &self,
        mut progress: P,
        should_interrupt: &AtomicBool,
        options: integrity::Options<F>,
    ) -> Result<integrity::Outcome<P>, integrity::Error>
    where
        P: Progress,
        C: pack::cache::DecodeEntry,
        F: Fn() -> C + Send + Clone,
    {
        let mut index = self.index.load();
        if !index.is_initialized() {
            self.consolidate_with_disk_state(true, false)?;
            index = self.index.load();
            assert!(
                index.is_initialized(),
                "BUG: after consolidating successfully, we have an initialized index"
            )
        }

        progress.init(
            Some(index.slot_indices.len()),
            git_features::progress::count("pack indices"),
        );
        let mut statistics = Vec::new();
        let index_check_message = |path: &std::path::Path| {
            format!(
                "Checking integrity: {}",
                path.file_name()
                    .map(|f| f.to_string_lossy())
                    .unwrap_or_else(std::borrow::Cow::default)
            )
        };
        for slot_index in &index.slot_indices {
            let slot = &self.files[*slot_index];
            if slot.generation.load(Ordering::SeqCst) != index.generation {
                return Err(integrity::Error::NeedsRetryDueToChangeOnDisk);
            }
            let files = slot.files.load();
            let files = Option::as_ref(&files).ok_or(integrity::Error::NeedsRetryDueToChangeOnDisk)?;

            let start = Instant::now();
            let (mut child_progress, num_objects, index_path) = match files {
                IndexAndPacks::Index(bundle) => {
                    let index;
                    let index = match bundle.index.loaded() {
                        Some(index) => index.deref(),
                        None => {
                            index = pack::index::File::at(bundle.index.path(), self.object_hash)?;
                            &index
                        }
                    };
                    let pack;
                    let data = match bundle.data.loaded() {
                        Some(pack) => pack.deref(),
                        None => {
                            pack = pack::data::File::at(bundle.data.path(), self.object_hash)?;
                            &pack
                        }
                    };
                    let outcome = index.verify_integrity(
                        Some(pack::index::verify::PackContext {
                            data,
                            options: options.clone(),
                        }),
                        progress.add_child_with_id("never shown", git_features::progress::UNKNOWN),
                        should_interrupt,
                    )?;
                    statistics.push(IndexStatistics {
                        path: bundle.index.path().to_owned(),
                        statistics: SingleOrMultiStatistics::Single(
                            outcome
                                .pack_traverse_statistics
                                .expect("pack provided so there are stats"),
                        ),
                    });
                    (outcome.progress, index.num_objects(), index.path().to_owned())
                }
                IndexAndPacks::MultiIndex(bundle) => {
                    let index;
                    let index = match bundle.multi_index.loaded() {
                        Some(index) => index.deref(),
                        None => {
                            index = pack::multi_index::File::at(bundle.multi_index.path())?;
                            &index
                        }
                    };
                    let outcome = index.verify_integrity(
                        progress.add_child_with_id("never shown", git_features::progress::UNKNOWN),
                        should_interrupt,
                        options.clone(),
                    )?;

                    let index_dir = bundle.multi_index.path().parent().expect("file in a directory");
                    statistics.push(IndexStatistics {
                        path: Default::default(),
                        statistics: SingleOrMultiStatistics::Multi(
                            outcome
                                .pack_traverse_statistics
                                .into_iter()
                                .zip(index.index_names())
                                .map(|(statistics, index_name)| (index_dir.join(index_name), statistics))
                                .collect(),
                        ),
                    });
                    (outcome.progress, index.num_objects(), index.path().to_owned())
                }
            };

            child_progress.set_name(index_check_message(&index_path));
            child_progress.show_throughput_with(
                start,
                num_objects as usize,
                git_features::progress::count("objects").expect("set"),
                MessageLevel::Success,
            );
            progress.inc();
        }

        progress.init(
            Some(index.loose_dbs.len()),
            git_features::progress::count("loose object stores"),
        );
        let mut loose_object_stores = Vec::new();
        for loose_db in &*index.loose_dbs {
            let out = loose_db
                .verify_integrity(
                    progress.add_child_with_id(loose_db.path().display().to_string(), *b"VISP"), /* Verify Integrity Store Path */
                    should_interrupt,
                )
                .map(|statistics| integrity::LooseObjectStatistics {
                    path: loose_db.path().to_owned(),
                    statistics,
                })?;
            loose_object_stores.push(out);
        }

        Ok(integrity::Outcome {
            loose_object_stores,
            index_statistics: statistics,
            progress,
        })
    }

Initialization

Initialize the Db with the objects_directory containing the hexadecimal first byte subdirectories, which in turn contain all loose objects.

In a git repository, this would be .git/objects.

The object_hash determines which hash to use when writing, finding or iterating objects.

Examples found in repository?
src/store_impls/dynamic/load_index.rs (line 222)
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
    pub(crate) fn consolidate_with_disk_state(
        &self,
        needs_init: bool,
        load_new_index: bool,
    ) -> Result<Option<Snapshot>, Error> {
        let index = self.index.load();
        let previous_index_state = Arc::as_ptr(&index) as usize;

        // IMPORTANT: get a lock after we recorded the previous state.
        let write = self.write.lock();
        let objects_directory = &self.path;

        // Now we know the index isn't going to change anymore, even though threads might still load indices in the meantime.
        let index = self.index.load();
        if previous_index_state != Arc::as_ptr(&index) as usize {
            // Someone else took the look before and changed the index. Return it without doing any additional work.
            return Ok(Some(self.collect_snapshot()));
        }

        let was_uninitialized = !index.is_initialized();

        // We might not be able to detect by pointer if the state changed, as this itself is racy. So we keep track of double-initialization
        // using a flag, which means that if `needs_init` was true we saw the index uninitialized once, but now that we are here it's
        // initialized meaning that somebody was faster and we couldn't detect it by comparisons to the index.
        // If so, make sure we collect the snapshot instead of returning None in case nothing actually changed, which is likely with a
        // race like this.
        if !was_uninitialized && needs_init {
            return Ok(Some(self.collect_snapshot()));
        }
        self.num_disk_state_consolidation.fetch_add(1, Ordering::Relaxed);

        let db_paths: Vec<_> = std::iter::once(objects_directory.to_owned())
            .chain(crate::alternate::resolve(objects_directory, &self.current_dir)?)
            .collect();

        // turn db paths into loose object databases. Reuse what's there, but only if it is in the right order.
        let loose_dbs = if was_uninitialized
            || db_paths.len() != index.loose_dbs.len()
            || db_paths
                .iter()
                .zip(index.loose_dbs.iter().map(|ldb| &ldb.path))
                .any(|(lhs, rhs)| lhs != rhs)
        {
            Arc::new(
                db_paths
                    .iter()
                    .map(|path| crate::loose::Store::at(path, self.object_hash))
                    .collect::<Vec<_>>(),
            )
        } else {
            Arc::clone(&index.loose_dbs)
        };

        let indices_by_modification_time = Self::collect_indices_and_mtime_sorted_by_size(
            db_paths,
            index.slot_indices.len().into(),
            self.use_multi_pack_index.then(|| self.object_hash),
        )?;
        let mut idx_by_index_path: BTreeMap<_, _> = index
            .slot_indices
            .iter()
            .filter_map(|&idx| {
                let f = &self.files[idx];
                Option::as_ref(&f.files.load()).map(|f| (f.index_path().to_owned(), idx))
            })
            .collect();

        let mut new_slot_map_indices = Vec::new(); // these indices into the slot map still exist there/didn't change
        let mut index_paths_to_add = was_uninitialized
            .then(|| VecDeque::with_capacity(indices_by_modification_time.len()))
            .unwrap_or_default();

        // Figure out this number based on what we see while handling the existing indices
        let mut num_loaded_indices = 0;
        for (index_info, mtime) in indices_by_modification_time.into_iter().map(|(a, b, _)| (a, b)) {
            match idx_by_index_path.remove(index_info.path()) {
                Some(slot_idx) => {
                    let slot = &self.files[slot_idx];
                    let files_guard = slot.files.load();
                    let files =
                        Option::as_ref(&files_guard).expect("slot is set or we wouldn't know it points to this file");
                    if index_info.is_multi_index() && files.mtime() != mtime {
                        // we have a changed multi-pack index. We can't just change the existing slot as it may alter slot indices
                        // that are currently available. Instead we have to move what's there into a new slot, along with the changes,
                        // and later free the slot or dispose of the index in the slot (like we do for removed/missing files).
                        index_paths_to_add.push_back((index_info, mtime, Some(slot_idx)));
                        // If the current slot is loaded, the soon-to-be copied multi-index path will be loaded as well.
                        if files.index_is_loaded() {
                            num_loaded_indices += 1;
                        }
                    } else {
                        // packs and indices are immutable, so no need to check modification times. Unchanged multi-pack indices also
                        // are handled like this just to be sure they are in the desired state. For these, the only way this could happen
                        // is if somebody deletes and then puts back
                        if Self::assure_slot_matches_index(&write, slot, index_info, mtime, index.generation) {
                            num_loaded_indices += 1;
                        }
                        new_slot_map_indices.push(slot_idx);
                    }
                }
                None => index_paths_to_add.push_back((index_info, mtime, None)),
            }
        }
        let needs_stable_indices = self.maintain_stable_indices(&write);

        let mut next_possibly_free_index = index
            .slot_indices
            .iter()
            .max()
            .map(|idx| (idx + 1) % self.files.len())
            .unwrap_or(0);
        let mut num_indices_checked = 0;
        let mut needs_generation_change = false;
        let mut slot_indices_to_remove: Vec<_> = idx_by_index_path.into_values().collect();
        while let Some((mut index_info, mtime, move_from_slot_idx)) = index_paths_to_add.pop_front() {
            'increment_slot_index: loop {
                if num_indices_checked == self.files.len() {
                    return Err(Error::InsufficientSlots {
                        current: self.files.len(),
                        needed: index_paths_to_add.len() + 1, /*the one currently popped off*/
                    });
                }
                let slot_index = next_possibly_free_index;
                let slot = &self.files[slot_index];
                next_possibly_free_index = (next_possibly_free_index + 1) % self.files.len();
                num_indices_checked += 1;
                match move_from_slot_idx {
                    Some(move_from_slot_idx) => {
                        debug_assert!(index_info.is_multi_index(), "only set for multi-pack indices");
                        if slot_index == move_from_slot_idx {
                            // don't try to move onto ourselves
                            continue 'increment_slot_index;
                        }
                        match Self::try_set_index_slot(
                            &write,
                            slot,
                            index_info,
                            mtime,
                            index.generation,
                            needs_stable_indices,
                        ) {
                            Ok(dest_was_empty) => {
                                slot_indices_to_remove.push(move_from_slot_idx);
                                new_slot_map_indices.push(slot_index);
                                // To avoid handling out the wrong pack (due to reassigned pack ids), declare this a new generation.
                                if !dest_was_empty {
                                    needs_generation_change = true;
                                }
                                break 'increment_slot_index;
                            }
                            Err(unused_index_info) => index_info = unused_index_info,
                        }
                    }
                    None => {
                        match Self::try_set_index_slot(
                            &write,
                            slot,
                            index_info,
                            mtime,
                            index.generation,
                            needs_stable_indices,
                        ) {
                            Ok(dest_was_empty) => {
                                new_slot_map_indices.push(slot_index);
                                if !dest_was_empty {
                                    needs_generation_change = true;
                                }
                                break 'increment_slot_index;
                            }
                            Err(unused_index_info) => index_info = unused_index_info,
                        }
                    }
                }
                // This isn't racy as it's only us who can change the Option::Some/None state of a slot.
            }
        }
        assert_eq!(
            index_paths_to_add.len(),
            0,
            "By this time we have assigned all new files to slots"
        );

        let generation = if needs_generation_change {
            index.generation.checked_add(1).ok_or(Error::GenerationOverflow)?
        } else {
            index.generation
        };
        let index_unchanged = index.slot_indices == new_slot_map_indices;
        if generation != index.generation {
            assert!(
                !index_unchanged,
                "if the generation changed, the slot index must have changed for sure"
            );
        }
        if !index_unchanged || loose_dbs != index.loose_dbs {
            let new_index = Arc::new(SlotMapIndex {
                slot_indices: new_slot_map_indices,
                loose_dbs,
                generation,
                // if there was a prior generation, some indices might already be loaded. But we deal with it by trying to load the next index then,
                // until we find one.
                next_index_to_load: index_unchanged
                    .then(|| Arc::clone(&index.next_index_to_load))
                    .unwrap_or_default(),
                loaded_indices: index_unchanged
                    .then(|| Arc::clone(&index.loaded_indices))
                    .unwrap_or_else(|| Arc::new(num_loaded_indices.into())),
                num_indices_currently_being_loaded: Default::default(),
            });
            self.index.store(new_index);
        }

        // deleted items - remove their slots AFTER we have set the new index if we may alter indices, otherwise we only declare them garbage.
        // removing slots may cause pack loading to fail, and they will then reload their indices.
        for slot in slot_indices_to_remove.into_iter().map(|idx| &self.files[idx]) {
            let _lock = slot.write.lock();
            let mut files = slot.files.load_full();
            let files_mut = Arc::make_mut(&mut files);
            if needs_stable_indices {
                if let Some(files) = files_mut.as_mut() {
                    files.trash();
                    // generation stays the same, as it's the same value still but scheduled for eventual removal.
                }
            } else {
                *files_mut = None;
            };
            slot.files.store(files);
            if !needs_stable_indices {
                // Not racy due to lock, generation must be set after unsetting the slot value AND storing it.
                slot.generation.store(generation, Ordering::SeqCst);
            }
        }

        let new_index = self.index.load();
        Ok(if index.state_id() == new_index.state_id() {
            // there was no change, and nothing was loaded in the meantime, reflect that in the return value to not get into loops
            None
        } else {
            if load_new_index {
                self.load_next_index(new_index);
            }
            Some(self.collect_snapshot())
        })
    }

Return the path to our objects directory.

Examples found in repository?
src/store_impls/dynamic/verify.rs (line 219)
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
    pub fn verify_integrity<C, P, F>(
        &self,
        mut progress: P,
        should_interrupt: &AtomicBool,
        options: integrity::Options<F>,
    ) -> Result<integrity::Outcome<P>, integrity::Error>
    where
        P: Progress,
        C: pack::cache::DecodeEntry,
        F: Fn() -> C + Send + Clone,
    {
        let mut index = self.index.load();
        if !index.is_initialized() {
            self.consolidate_with_disk_state(true, false)?;
            index = self.index.load();
            assert!(
                index.is_initialized(),
                "BUG: after consolidating successfully, we have an initialized index"
            )
        }

        progress.init(
            Some(index.slot_indices.len()),
            git_features::progress::count("pack indices"),
        );
        let mut statistics = Vec::new();
        let index_check_message = |path: &std::path::Path| {
            format!(
                "Checking integrity: {}",
                path.file_name()
                    .map(|f| f.to_string_lossy())
                    .unwrap_or_else(std::borrow::Cow::default)
            )
        };
        for slot_index in &index.slot_indices {
            let slot = &self.files[*slot_index];
            if slot.generation.load(Ordering::SeqCst) != index.generation {
                return Err(integrity::Error::NeedsRetryDueToChangeOnDisk);
            }
            let files = slot.files.load();
            let files = Option::as_ref(&files).ok_or(integrity::Error::NeedsRetryDueToChangeOnDisk)?;

            let start = Instant::now();
            let (mut child_progress, num_objects, index_path) = match files {
                IndexAndPacks::Index(bundle) => {
                    let index;
                    let index = match bundle.index.loaded() {
                        Some(index) => index.deref(),
                        None => {
                            index = pack::index::File::at(bundle.index.path(), self.object_hash)?;
                            &index
                        }
                    };
                    let pack;
                    let data = match bundle.data.loaded() {
                        Some(pack) => pack.deref(),
                        None => {
                            pack = pack::data::File::at(bundle.data.path(), self.object_hash)?;
                            &pack
                        }
                    };
                    let outcome = index.verify_integrity(
                        Some(pack::index::verify::PackContext {
                            data,
                            options: options.clone(),
                        }),
                        progress.add_child_with_id("never shown", git_features::progress::UNKNOWN),
                        should_interrupt,
                    )?;
                    statistics.push(IndexStatistics {
                        path: bundle.index.path().to_owned(),
                        statistics: SingleOrMultiStatistics::Single(
                            outcome
                                .pack_traverse_statistics
                                .expect("pack provided so there are stats"),
                        ),
                    });
                    (outcome.progress, index.num_objects(), index.path().to_owned())
                }
                IndexAndPacks::MultiIndex(bundle) => {
                    let index;
                    let index = match bundle.multi_index.loaded() {
                        Some(index) => index.deref(),
                        None => {
                            index = pack::multi_index::File::at(bundle.multi_index.path())?;
                            &index
                        }
                    };
                    let outcome = index.verify_integrity(
                        progress.add_child_with_id("never shown", git_features::progress::UNKNOWN),
                        should_interrupt,
                        options.clone(),
                    )?;

                    let index_dir = bundle.multi_index.path().parent().expect("file in a directory");
                    statistics.push(IndexStatistics {
                        path: Default::default(),
                        statistics: SingleOrMultiStatistics::Multi(
                            outcome
                                .pack_traverse_statistics
                                .into_iter()
                                .zip(index.index_names())
                                .map(|(statistics, index_name)| (index_dir.join(index_name), statistics))
                                .collect(),
                        ),
                    });
                    (outcome.progress, index.num_objects(), index.path().to_owned())
                }
            };

            child_progress.set_name(index_check_message(&index_path));
            child_progress.show_throughput_with(
                start,
                num_objects as usize,
                git_features::progress::count("objects").expect("set"),
                MessageLevel::Success,
            );
            progress.inc();
        }

        progress.init(
            Some(index.loose_dbs.len()),
            git_features::progress::count("loose object stores"),
        );
        let mut loose_object_stores = Vec::new();
        for loose_db in &*index.loose_dbs {
            let out = loose_db
                .verify_integrity(
                    progress.add_child_with_id(loose_db.path().display().to_string(), *b"VISP"), /* Verify Integrity Store Path */
                    should_interrupt,
                )
                .map(|statistics| integrity::LooseObjectStatistics {
                    path: loose_db.path().to_owned(),
                    statistics,
                })?;
            loose_object_stores.push(out);
        }

        Ok(integrity::Outcome {
            loose_object_stores,
            index_statistics: statistics,
            progress,
        })
    }

Return the kind of hash we would iterate and write.

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Write the given buffer in from to disk in one syscall at best.

This will cost at least 4 IO operations.

Write the given stream in from to disk with at least one syscall.

This will cost at least 4 IO operations.

The error type used for all trait methods. Read more
Write objects using the intrinsic kind of hash into the database, returning id to reference it in subsequent reads.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Checks if this value is equivalent to the given key. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.