1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
//! What:
//! Which candidates hold content that a parent commit's tree already holds,
//! found by exact blob object name.
//! Why:
//! A pure rename or a copy re-lists a file as an addition,
//! and a merge lists every file one parent lacks as an addition,
//! although the bytes are already in history.
//! Scanning them again refuses moves of
//! files that were accepted when they entered history,
//! while an object name is the hash of the bytes,
//! so a
//! candidate whose object a parent holds carries no byte that is new.
//! The comparison is by object
//! name only:
//! never by pathname,
//! never by similarity,
//! so one changed byte makes the content new.
//!
//! In TS you'd write (pseudocode):
//! ```ts
//! // const known = await findKnownContent(store, version, ContentBasis.of(request), rulesPath, corrected);
//! // known.entry(candidate.identity.index)?.parent
//! ```
/// Import the layer's failure type.
use super::candidate_error::CandidateError;
/// Import the candidate modes and the validated object name.
use super::candidate_object::{CandidateMode, ObjectId};
/// Import what a lifecycle asks for.
use super::candidate_prediction::CandidateRequest;
/// Import the store that lists commits and trees.
use super::candidate_store::CandidateStore;
/// Import the candidate and the immutable version type.
use super::candidate_version::{Candidate, CandidateVersion};
/// Import the change a converged fix installs,
/// which marks a candidate whose bytes are no longer its object's.
use super::direct_fix_install::InstallChange;
/// Import which candidates a scan reads at all.
use super::scanner_selection::is_scannable;
/// What:
/// `BTreeMap<K, V>` is a map kept sorted by key (sibling `HashMap` is unordered);
/// `HashSet<T>` is an
/// unordered set with constant-time membership tests.
/// Why:
/// Known candidates are listed in candidate order,
/// and each parent's blobs are looked up by name.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// // Map<number, KnownEntry> iterated in key order; Set<ObjectId>.
/// ```
use std::collections::{BTreeMap, HashSet};
/// What:
/// The commits whose trees count as already holding content for one lifecycle.
/// `#[derive(...)]` generates cloning,
/// debug printing and `==`.
/// Why:
/// Each lifecycle compares with a different history:
/// the commit being made with its base,
/// a landed
/// commit with each of its parents,
/// a push with the parents that were published before it.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// type ContentBasis = { kind: 'nothing' } | { kind: 'baseline' } | { kind: 'parents-outside'; commits: ObjectId[] };
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ContentBasis {
/// No tree counts:
/// a direct check reads the selected files for what they hold now,
/// and a push with a tip whose published history is unknown has no commit to vouch for anything.
Nothing,
/// The commit the candidates are compared with:
/// the recorded base of a commit,
/// else the commit `HEAD` names;
/// an unborn branch has none.
Baseline,
/// Every parent of these commits that is not one of them:
/// a landed commit's parents,
/// or a push's already published parents.
ParentsOutside(
/// The commits whose parents are listed.
Vec<ObjectId>,
),
}
/// What:
/// `impl ContentBasis { ... }` attaches the choice for a request.
/// Why:
/// The choice follows the request's kind alone,
/// so no policy decides it separately.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// class ContentBasis { static of(request: CandidateRequest): ContentBasis }
/// ```
impl ContentBasis {
/// What:
/// The basis of one request.
/// `&CandidateRequest` borrows what the lifecycle asked for.
/// Why:
/// A parent commit of a pushed commit that is itself pushed is new to the remote,
/// so a push counts only the parents outside the pushed commits.
/// A pushed tip tree has no published
/// base to compare with,
/// and its candidates share one version with the commits' candidates,
/// so a push with such a tip skips nothing.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// static of(request: CandidateRequest): ContentBasis
/// ```
pub fn of(request: &CandidateRequest) -> ContentBasis {
match request {
CandidateRequest::Direct(_) => return ContentBasis::Nothing,
CandidateRequest::Add(_)
| CandidateRequest::Staged(_)
| CandidateRequest::StagedAtBase { .. } => return ContentBasis::Baseline,
CandidateRequest::Landed(commit) => {
return ContentBasis::ParentsOutside(vec![commit.clone()]);
}
CandidateRequest::Pushed(scope) => {
if !scope.trees.is_empty() {
return ContentBasis::Nothing;
}
return ContentBasis::ParentsOutside(scope.commits.clone());
}
}
}
}
/// What:
/// One candidate whose content a parent already holds:
/// the object and the first parent that holds it.
/// `#[derive(...)]` generates cloning,
/// debug printing and `==`.
/// Why:
/// The skip is a decision,
/// and a decision is only checkable when its inputs are kept.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// type KnownEntry = { object: ObjectId; parent: ObjectId };
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct KnownEntry {
/// The candidate's blob.
pub object: ObjectId,
/// The commit whose tree holds the blob.
pub parent: ObjectId,
}
/// What:
/// `impl KnownEntry { ... }` attaches the record of the decision.
/// Why:
/// One wording for the decision,
/// so a log line always carries the same inputs.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// class KnownEntry { describe(displayPath: string): string }
/// ```
impl KnownEntry {
/// What:
/// The decision as one line of text.
/// `&str` is the pathname as the scanner masks it.
/// Why:
/// The pathname is shown masked because a pathname may hold a secret;
/// the blob and the parent are
/// object names.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// describe(displayPath: string): string
/// ```
pub fn describe(&self, display_path: &str) -> String {
return format!(
"skipped the content of {display_path}: blob {} is already in the tree of commit {}; only the pathname was checked.",
self.object.as_str(),
self.parent.as_str()
);
}
}
/// What:
/// The known candidates of one version,
/// by the candidate's position in the version.
/// `#[derive(...)]` generates cloning,
/// debug printing and `==`;
/// `Default` is the empty value.
/// Why:
/// The scan pass asks by position,
/// and the log lists them in candidate order.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// class KnownContent { entry(index: number): KnownEntry | undefined }
/// ```
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct KnownContent {
/// The known candidates,
/// sorted by position.
entries: BTreeMap<usize, KnownEntry>,
}
/// What:
/// `impl KnownContent { ... }` attaches the read-only accessors.
/// Why:
/// A scan can read the decision and cannot change it.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// class KnownContent { entry(index) {} len() {} }
/// ```
impl KnownContent {
/// What:
/// The entry of the candidate at `index`,
/// if its content is known.
/// Why:
/// The scan pass asks once per candidate.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// entry(index: number): KnownEntry | undefined
/// ```
pub fn entry(&self, index: usize) -> Option<&KnownEntry> {
return self.entries.get(&index);
}
/// What:
/// How many candidates are known.
/// Why:
/// A pass with none reads exactly the bytes it read before the rule existed.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// get length(): number
/// ```
pub fn len(&self) -> usize {
return self.entries.len();
}
/// What:
/// Whether no candidate is known.
/// Why:
/// Clippy asks a type with a `len()` to provide `is_empty()` too.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// get isEmpty(): boolean
/// ```
pub fn is_empty(&self) -> bool {
return self.entries.is_empty();
}
}
/// What:
/// Whether a candidate's content can be known from a parent's tree at all.
/// `Option<&[u8]>` is the rules file's own pathname.
/// Why:
/// Only a scanned blob has bytes that a parent could already hold.
/// A submodule entry is a commit name,
/// and a file a fix corrected no longer holds its object's bytes.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// const comparable = (candidate, rulesPath, corrected) => isScannable(candidate, rulesPath) && candidate.object !== undefined && candidate.mode !== 'gitlink' && !corrected.has(candidate.path);
/// ```
fn is_comparable(
candidate: &Candidate,
rules_path: Option<&[u8]>,
corrected: &BTreeMap<Vec<u8>, InstallChange>,
) -> bool {
return is_scannable(candidate, rules_path)
&& candidate.object.is_some()
&& candidate.mode != CandidateMode::Gitlink
&& !corrected.contains_key(&candidate.path);
}
/// What:
/// Find every comparable candidate whose blob a parent's tree holds.
/// `&mut CandidateStore` lends the listing;
/// `Option<&[u8]>` is the rules file's pathname;
/// `&BTreeMap<..>` are the files a fix corrected.
/// Why:
/// Parents are listed one after another and listing stops when every candidate is placed,
/// so a
/// version that is all known costs one listing.
/// No candidate to compare and no parent to compare with
/// each cost no Git process beyond the basis question.
/// The first parent that holds a blob is the one reported.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// async function findKnownContent(store, version, basis, rulesPath, corrected): Promise<KnownContent>;
/// ```
pub fn find_known_content(
store: &mut CandidateStore,
version: &CandidateVersion,
basis: &ContentBasis,
rules_path: Option<&[u8]>,
corrected: &BTreeMap<Vec<u8>, InstallChange>,
) -> Result<KnownContent, CandidateError> {
let mut pending: Vec<&Candidate> = Vec::new();
for candidate in version.candidates() {
if is_comparable(candidate, rules_path, corrected) {
pending.push(candidate);
}
}
let mut entries: BTreeMap<usize, KnownEntry> = BTreeMap::new();
if pending.is_empty() {
return Ok(KnownContent { entries });
}
let parents: Vec<ObjectId> = match basis {
ContentBasis::Nothing => Vec::new(),
// `.into_iter().collect()` turns "a commit or nothing" into a list of zero or one.
ContentBasis::Baseline => store.baseline_reference()?.into_iter().collect(),
ContentBasis::ParentsOutside(commits) => store.parents_outside(commits.as_slice())?,
};
for parent in parents {
if pending.is_empty() {
break;
}
let mut blobs: HashSet<ObjectId> = HashSet::new();
for record in store.commit_tree_records(&parent)? {
if record.mode != CandidateMode::Gitlink {
blobs.insert(record.object);
}
}
let mut unplaced: Vec<&Candidate> = Vec::new();
for candidate in pending {
match candidate.object.as_ref() {
Some(object) if blobs.contains(object) => {
entries.insert(
candidate.identity.index,
KnownEntry {
object: object.clone(),
parent: parent.clone(),
},
);
}
Some(_) | None => unplaced.push(candidate),
}
}
pending = unplaced;
}
return Ok(KnownContent { entries });
}
/// Basis choice,
/// lookup by object name and the stop once every candidate is placed stay out of the release executable.
#[cfg(test)]
#[path = "candidate_known_content_tests.rs"]
mod tests;