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
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
// Copyright Kitware, Inc.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::path::PathBuf;

use crates::git_checks_core::impl_prelude::*;
use crates::thiserror::Error;

#[derive(Debug, Error)]
enum SubmoduleAvailableError {
    #[error("failed to get the merge-base for {} against the tracking branch {} in {}: {}", commit, branch, submodule.display(), output)]
    MergeBase {
        submodule: PathBuf,
        commit: CommitId,
        branch: String,
        output: String,
    },
    #[error("failed to list refs from {} to {} in {}: {}", branch, commit, submodule.display(), output)]
    RevList {
        submodule: PathBuf,
        commit: CommitId,
        branch: String,
        output: String,
    },
}

impl SubmoduleAvailableError {
    fn merge_base(submodule: &FileName, commit: CommitId, branch: String, output: &[u8]) -> Self {
        SubmoduleAvailableError::MergeBase {
            submodule: submodule.as_path().into(),
            commit,
            branch,
            output: String::from_utf8_lossy(output).into(),
        }
    }

    fn rev_list(submodule: &FileName, commit: CommitId, branch: String, output: &[u8]) -> Self {
        SubmoduleAvailableError::RevList {
            submodule: submodule.as_path().into(),
            commit,
            branch,
            output: String::from_utf8_lossy(output).into(),
        }
    }
}

/// Check that submodules are reachable from a given branch and available.
#[derive(Builder, Debug, Clone, Copy)]
#[builder(field(private))]
pub struct SubmoduleAvailable {
    /// Whether the first-parent history is required to contain commits or not.
    ///
    /// If the merge commit of the submodule into the tracked branch should be required, set this
    /// flag.
    ///
    /// Configuration: Optional
    /// Default: `false`
    #[builder(default = "false")]
    require_first_parent: bool,
}

impl SubmoduleAvailable {
    /// Create a new builder.
    pub fn builder() -> SubmoduleAvailableBuilder {
        SubmoduleAvailableBuilder::default()
    }
}

impl Default for SubmoduleAvailable {
    fn default() -> Self {
        SubmoduleAvailable {
            require_first_parent: false,
        }
    }
}

impl Check for SubmoduleAvailable {
    fn name(&self) -> &str {
        "submodule-available"
    }

    fn check(&self, ctx: &CheckGitContext, commit: &Commit) -> Result<CheckResult, Box<dyn Error>> {
        let mut result = CheckResult::new();

        for diff in &commit.diffs {
            // Ignore diffs which are not submodules on the new side.
            if diff.new_mode != "160000" {
                continue;
            }

            // Ignore deleted submodules.
            if let StatusChange::Deleted = diff.status {
                continue;
            }

            let submodule_ctx = if let Some(ctx) = SubmoduleContext::new(ctx, diff.name.as_ref()) {
                ctx
            } else {
                result.add_alert(
                    format!("submodule at `{}` is not configured.", diff.name),
                    false,
                );

                continue;
            };

            let submodule_commit = &diff.new_blob;

            let cat_file = submodule_ctx
                .context
                .git()
                .arg("cat-file")
                .arg("-t")
                .arg(submodule_commit.as_str())
                .output()
                .map_err(|err| GitError::subcommand("cat-file -t", err))?;
            let object_type = String::from_utf8_lossy(&cat_file.stdout);
            if !cat_file.status.success() || object_type.trim() != "commit" {
                result
                    .add_error(format!(
                        "commit {} references an unreachable commit {} at `{}`; please make the \
                         commit available in the {} repository on the `{}` branch first.",
                        commit.sha1,
                        submodule_commit,
                        submodule_ctx.path,
                        submodule_ctx.url,
                        submodule_ctx.branch,
                    ))
                    .make_temporary();
                continue;
            }

            let merge_base = submodule_ctx
                .context
                .git()
                .arg("merge-base")
                .arg(submodule_commit.as_str())
                .arg(submodule_ctx.branch)
                .output()
                .map_err(|err| GitError::subcommand("merge-base", err))?;
            if !merge_base.status.success() {
                return Err(SubmoduleAvailableError::merge_base(
                    &diff.name,
                    submodule_commit.clone(),
                    submodule_ctx.branch.into(),
                    &merge_base.stderr,
                )
                .into());
            }
            let base = String::from_utf8_lossy(&merge_base.stdout);

            if base.trim() != submodule_commit.as_str() {
                result
                    .add_error(format!(
                        "commit {} references the commit {} at `{}`, but it is not available on \
                         the tracked branch `{}`; please make the commit available from the `{}` \
                         branch first.",
                        commit.sha1,
                        submodule_commit,
                        submodule_ctx.path,
                        submodule_ctx.branch,
                        submodule_ctx.branch,
                    ))
                    .make_temporary();
                continue;
            }

            if self.require_first_parent {
                let refs = submodule_ctx
                    .context
                    .git()
                    .arg("rev-list")
                    .arg("--first-parent") // only look at first-parent history
                    .arg("--reverse") // start with oldest commits
                    .arg(submodule_ctx.branch)
                    .arg(format!("^{}~", submodule_commit))
                    .output()
                    .map_err(|err| GitError::subcommand("rev-list", err))?;
                if !refs.status.success() {
                    return Err(SubmoduleAvailableError::rev_list(
                        &diff.name,
                        submodule_commit.clone(),
                        submodule_ctx.branch.into(),
                        &refs.stderr,
                    )
                    .into());
                }
                let refs = String::from_utf8_lossy(&refs.stdout);

                if !refs.lines().any(|rev| rev == submodule_commit.as_str()) {
                    // This is not temporary because we've already determined above that it is in
                    // the history of the target branch in the first place; it not being in the
                    // first-parent isn't going to change.
                    result.add_error(format!(
                        "commit {} references the commit {} at `{}`, but it is not available as a \
                         first-parent of the tracked branch `{}`; please choose the commit where \
                         it was merged into the `{}` branch.",
                        commit.sha1,
                        submodule_commit,
                        submodule_ctx.path,
                        submodule_ctx.branch,
                        submodule_ctx.branch,
                    ));
                    continue;
                }
            }
        }

        Ok(result)
    }
}

#[cfg(feature = "config")]
pub(crate) mod config {
    use crates::git_checks_config::{CommitCheckConfig, IntoCheck};
    use crates::inventory;
    #[cfg(test)]
    use crates::serde_json;

    use SubmoduleAvailable;

    /// Configuration for the `SubmoduleAvailable` check.
    ///
    /// The `require_first_parent` key is a boolean which defaults to `false`.
    ///
    /// This check is registered as a commit check with the name `"submodule_available"`.
    ///
    /// # Example
    ///
    /// ```json
    /// {
    ///     "require_first_parent": false
    /// }
    /// ```
    #[derive(Deserialize, Debug)]
    pub struct SubmoduleAvailableConfig {
        #[serde(default)]
        require_first_parent: Option<bool>,
    }

    impl IntoCheck for SubmoduleAvailableConfig {
        type Check = SubmoduleAvailable;

        fn into_check(self) -> Self::Check {
            let mut builder = SubmoduleAvailable::builder();

            if let Some(require_first_parent) = self.require_first_parent {
                builder.require_first_parent(require_first_parent);
            }

            builder
                .build()
                .expect("configuration mismatch for `SubmoduleAvailable`")
        }
    }

    register_checks! {
        SubmoduleAvailableConfig {
            "submodule_available" => CommitCheckConfig,
        },
    }

    #[test]
    fn test_submodule_available_config_empty() {
        let json = json!({});
        let check: SubmoduleAvailableConfig = serde_json::from_value(json).unwrap();

        assert_eq!(check.require_first_parent, None);
    }

    #[test]
    fn test_submodule_available_config_all_fields() {
        let json = json!({
            "require_first_parent": true,
        });
        let check: SubmoduleAvailableConfig = serde_json::from_value(json).unwrap();

        assert_eq!(check.require_first_parent, Some(true));
    }
}

#[cfg(test)]
mod tests {
    use test::*;
    use SubmoduleAvailable;

    const BASE_COMMIT: &str = "fe90ee22ae3ce4b4dc41f8d0876e59355ff1e21c";
    const MOVE_TOPIC: &str = "2088079e35503be3be41dbdca55080ced95614e1";
    const MOVE_NOT_FIRST_PARENT_TOPIC: &str = "eb4df16a8a38f6ca30b6e67cfbca0672156b54d2";
    const UNAVAILABLE_TOPIC: &str = "1b9275caca1557611df19d1dfea687c3ef302eef";
    const NOT_ANCESTOR_TOPIC: &str = "07fb2ca9c1c8c0ddfcf921e762688ffcd476bc09";

    #[test]
    fn test_submodule_available_builder_default() {
        assert!(SubmoduleAvailable::builder().build().is_ok());
    }

    #[test]
    fn test_submodule_unconfigured() {
        let check = SubmoduleAvailable::default();
        let result = run_check("test_submodule_unconfigured", BASE_COMMIT, check);

        assert_eq!(result.warnings().len(), 0);
        assert_eq!(result.alerts().len(), 1);
        assert_eq!(
            result.alerts()[0],
            "submodule at `submodule` is not configured.",
        );
        assert_eq!(result.errors().len(), 0);
        assert_eq!(result.temporary(), false);
        assert_eq!(result.allowed(), false);
        assert_eq!(result.pass(), true);
    }

    #[test]
    fn test_submodule_move() {
        let check = SubmoduleAvailable::default();
        let conf = make_check_conf(&check);

        let result = test_check_submodule("test_submodule_move", MOVE_TOPIC, &conf);
        test_result_ok(result);
    }

    #[test]
    fn test_submodule_move_not_first_parent() {
        let check = SubmoduleAvailable::default();
        let conf = make_check_conf(&check);

        let result = test_check_submodule(
            "test_submodule_move_not_first_parent",
            MOVE_NOT_FIRST_PARENT_TOPIC,
            &conf,
        );
        test_result_ok(result);
    }

    #[test]
    fn test_submodule_move_not_first_parent_reject() {
        let check = SubmoduleAvailable::builder()
            .require_first_parent(true)
            .build()
            .unwrap();
        let conf = make_check_conf(&check);

        let result = test_check_submodule(
            "test_submodule_move_not_first_parent_reject",
            MOVE_NOT_FIRST_PARENT_TOPIC,
            &conf,
        );
        test_result_errors(result, &[
            "commit eb4df16a8a38f6ca30b6e67cfbca0672156b54d2 references the commit \
             c2bd427807b40b1715b8d1441fe92f50e8ad1769 at `submodule`, but it is not available as a \
             first-parent of the tracked branch `master`; please choose the commit where it was \
             merged into the `master` branch.",
        ]);
    }

    #[test]
    fn test_submodule_unavailable() {
        let check = SubmoduleAvailable::default();
        let conf = make_check_conf(&check);

        let result = test_check_submodule("test_submodule_unavailable", UNAVAILABLE_TOPIC, &conf);

        assert_eq!(result.warnings().len(), 0);
        assert_eq!(result.alerts().len(), 0);
        assert_eq!(result.errors().len(), 1);
        assert_eq!(
            result.errors()[0],
            "commit 1b9275caca1557611df19d1dfea687c3ef302eef references an unreachable commit \
             4b029c2e0f186d681caa071fa4dd7eb1f0f033f6 at `submodule`; please make the commit \
             available in the https://gitlab.kitware.com/utils/test-repo.git repository on the \
             `master` branch first.",
        );
        assert_eq!(result.temporary(), true);
        assert_eq!(result.allowed(), false);
        assert_eq!(result.pass(), false);
    }

    #[test]
    fn test_submodule_not_ancestor() {
        let check = SubmoduleAvailable::default();
        let conf = make_check_conf(&check);

        let result = test_check_submodule("test_submodule_not_ancestor", NOT_ANCESTOR_TOPIC, &conf);

        assert_eq!(result.warnings().len(), 0);
        assert_eq!(result.alerts().len(), 0);
        assert_eq!(result.errors().len(), 1);
        assert_eq!(
            result.errors()[0],
            "commit 07fb2ca9c1c8c0ddfcf921e762688ffcd476bc09 references the commit \
             bd89a556b6ab6f378a776713439abbc1c1f15b6d at `submodule`, but it is not available on \
             the tracked branch `master`; please make the commit available from the `master` \
             branch first."
        );
        assert_eq!(result.temporary(), true);
        assert_eq!(result.allowed(), false);
        assert_eq!(result.pass(), false);
    }
}