ic_host_process/provenance/
mod.rs1#[cfg(test)]
8mod tests;
9
10use crate::tool::{AdmittedTool, ExecutionContext, ExecutionEvidence, OutputLimits, ToolError};
11use ic_host_artifacts::artifact::{ArtifactIdentity, Sha256Digest};
12use std::{ffi::OsString, fmt};
13
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
16pub enum UntrackedFiles {
17 No,
19 Normal,
21 All,
23}
24
25#[derive(Clone, Copy, Debug, Eq, PartialEq)]
27pub enum IgnoreSubmodules {
28 None,
30 Untracked,
32 Dirty,
34 All,
36}
37
38#[derive(Clone, Copy, Debug, Eq, PartialEq)]
40pub struct StatusOptions {
41 pub untracked: UntrackedFiles,
43 pub ignore_submodules: IgnoreSubmodules,
45}
46
47#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub enum GitQuery {
50 Revision,
52 Tree,
54 Status,
56}
57
58#[derive(Debug)]
60pub enum GitFailure {
61 Tool(Box<ToolError>),
63 InvalidObjectId,
65 UnterminatedStatus,
67}
68
69#[derive(Debug)]
71pub struct GitError {
72 pub query: GitQuery,
74 pub failure: GitFailure,
76 pub completed: Box<[Option<ExecutionEvidence>; 3]>,
79}
80
81impl fmt::Display for GitError {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 write!(f, "Git {:?} observation failed", self.query)
84 }
85}
86
87impl std::error::Error for GitError {
88 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
89 match &self.failure {
90 GitFailure::Tool(source) => Some(source.as_ref()),
91 GitFailure::InvalidObjectId | GitFailure::UnterminatedStatus => None,
92 }
93 }
94}
95
96#[derive(Debug)]
98pub struct GitObservations {
99 pub revision: String,
101 pub tree: String,
103 pub options: StatusOptions,
105 pub status_identity: ArtifactIdentity,
107 pub tool_identity: ArtifactIdentity,
109 pub revision_evidence: ExecutionEvidence,
111 pub tree_evidence: ExecutionEvidence,
113 pub status_evidence: ExecutionEvidence,
115}
116
117impl GitObservations {
118 #[must_use]
121 pub const fn is_dirty(&self) -> bool {
122 self.status_identity.bytes != 0
123 }
124}
125
126pub fn capture_git(
138 git: &AdmittedTool,
139 context: &ExecutionContext<'_>,
140 options: StatusOptions,
141 limits: OutputLimits,
142) -> Result<GitObservations, GitError> {
143 let revision = observe(git, context, options, limits, GitQuery::Revision)?;
144 let tree = match observe(git, context, options, limits, GitQuery::Tree) {
145 Ok(evidence) => evidence,
146 Err(mut error) => {
147 error.completed[0] = Some(revision);
148 return Err(error);
149 }
150 };
151 let status = match observe(git, context, options, limits, GitQuery::Status) {
152 Ok(evidence) => evidence,
153 Err(mut error) => {
154 error.completed[0] = Some(revision);
155 error.completed[1] = Some(tree);
156 return Err(error);
157 }
158 };
159 let status_identity = ArtifactIdentity {
160 bytes: status.stdout.len() as u64,
161 sha256: Sha256Digest::compute(&status.stdout),
162 };
163 let revision_id = object_id(&revision.stdout);
165 let tree_id = object_id(&tree.stdout);
166 Ok(GitObservations {
167 revision: revision_id,
168 tree: tree_id,
169 options,
170 status_identity,
171 tool_identity: git.identity(),
172 revision_evidence: revision,
173 tree_evidence: tree,
174 status_evidence: status,
175 })
176}
177
178fn observe(
179 git: &AdmittedTool,
180 context: &ExecutionContext<'_>,
181 options: StatusOptions,
182 limits: OutputLimits,
183 query: GitQuery,
184) -> Result<ExecutionEvidence, GitError> {
185 let mut completed = [None, None, None];
186 let index = match query {
187 GitQuery::Revision => 0,
188 GitQuery::Tree => 1,
189 GitQuery::Status => 2,
190 };
191 let evidence = match git
192 .run(&arguments(query, options), context, limits)
193 .and_then(ExecutionEvidence::require_complete)
194 {
195 Ok(evidence) => evidence,
196 Err(source) => {
197 return Err(GitError {
198 query,
199 failure: GitFailure::Tool(Box::new(source)),
200 completed: Box::new(completed),
201 });
202 }
203 };
204 let failure = match query {
205 GitQuery::Revision | GitQuery::Tree if !valid_object_id(&evidence.stdout) => {
206 Some(GitFailure::InvalidObjectId)
207 }
208 GitQuery::Status if !evidence.stdout.is_empty() && evidence.stdout.last() != Some(&0) => {
209 Some(GitFailure::UnterminatedStatus)
210 }
211 _ => None,
212 };
213 if let Some(failure) = failure {
214 completed[index] = Some(evidence);
215 return Err(GitError {
216 query,
217 failure,
218 completed: Box::new(completed),
219 });
220 }
221 Ok(evidence)
222}
223
224fn valid_object_id(bytes: &[u8]) -> bool {
225 matches!(bytes.len(), 41 | 65)
226 && bytes.last() == Some(&b'\n')
227 && bytes[..bytes.len() - 1]
228 .iter()
229 .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
230}
231
232fn object_id(bytes: &[u8]) -> String {
233 bytes[..bytes.len() - 1]
234 .iter()
235 .map(|&byte| char::from(byte))
236 .collect()
237}
238
239fn arguments(query: GitQuery, options: StatusOptions) -> Vec<OsString> {
240 let mut arguments = vec![
241 "--no-optional-locks".into(),
242 "-c".into(),
243 "core.fsmonitor=false".into(),
244 ];
245 match query {
246 GitQuery::Revision => {
247 arguments.extend(["rev-parse".into(), "--verify".into(), "HEAD".into()]);
248 }
249 GitQuery::Tree => {
250 arguments.extend(["rev-parse".into(), "--verify".into(), "HEAD^{tree}".into()]);
251 }
252 GitQuery::Status => {
253 let untracked = match options.untracked {
254 UntrackedFiles::No => "no",
255 UntrackedFiles::Normal => "normal",
256 UntrackedFiles::All => "all",
257 };
258 let submodules = match options.ignore_submodules {
259 IgnoreSubmodules::None => "none",
260 IgnoreSubmodules::Untracked => "untracked",
261 IgnoreSubmodules::Dirty => "dirty",
262 IgnoreSubmodules::All => "all",
263 };
264 arguments.extend([
265 "status".into(),
266 "--porcelain=v1".into(),
267 "-z".into(),
268 format!("--untracked-files={untracked}").into(),
269 format!("--ignore-submodules={submodules}").into(),
270 ]);
271 }
272 }
273 arguments
274}