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
// Copyright 2016 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 impl_prelude::*;

#[derive(Debug, Default, Clone, Copy)]
/// Check that submodules are reachable from a given branch and available.
pub struct SubmoduleAvailable {
    /// Whether the first-parent history is required to contain commits or not.
    require_first_parent: bool,
}

impl SubmoduleAvailable {
    /// Checks that submodules in the project are available.
    pub fn new() -> Self {
        Self {
            require_first_parent: false,
        }
    }

    /// Sets whether a first parent history is required to reach the commit.
    ///
    /// If the merge commit of the submodule into the tracked branch should be required, set this
    /// flag.
    pub fn require_first_parent(&mut self, require: bool) -> &mut Self {
        self.require_first_parent = require;
        self
    }
}

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

    fn check(&self, ctx: &CheckGitContext, commit: &Commit) -> Result<CheckResult> {
        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()
                .chain_err(|| "failed to construct cat-file command")?;
            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()
                .chain_err(|| "failed to construct merge-base command")?;
            if !merge_base.status.success() {
                bail!(ErrorKind::Git(format!("failed to get the merge base for the {} \
                                              submodule: {}",
                                             diff.name,
                                             String::from_utf8_lossy(&merge_base.stderr))));
            }
            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()
                    .chain_err(|| "failed to construct rev-list command")?;
                if !refs.status.success() {
                    bail!(ErrorKind::Git(format!("failed to get list the first parent history \
                                                  for the {} submodule: {}",
                                                 diff.name,
                                                 String::from_utf8_lossy(&refs.stderr))));
                }
                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(test)]
mod tests {
    use checks::SubmoduleAvailable;
    use checks::test::*;

    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_unconfigured() {
        let check = SubmoduleAvailable::new();
        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::new();
        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::new();
        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 mut check = SubmoduleAvailable::new();
        check.require_first_parent(true);
        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::new();
        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::new();
        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);
    }
}