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
// 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 derive_builder::Builder;
use git_checks_core::impl_prelude::*;
use thiserror::Error;

#[derive(Debug, Error)]
enum FastForwardError {
    #[error(
        "failed to get the merge-base for {} against a target branch {} ({:?}): {}",
        commit,
        base,
        code,
        output
    )]
    MergeBase {
        commit: CommitId,
        base: CommitId,
        code: Option<i32>,
        output: String,
    },
}

impl FastForwardError {
    fn merge_base(commit: CommitId, base: CommitId, code: Option<i32>, output: &[u8]) -> Self {
        Self::MergeBase {
            commit,
            base,
            code,
            output: String::from_utf8_lossy(output).into(),
        }
    }
}

/// A check which checks for fast-forward merge statuses.
///
/// Note that this check is fundamentally temporally bound because the state of the target ref can
/// change the state of this check.
///
/// By default, only warnings are produced.
#[derive(Builder, Debug, Clone)]
#[builder(field(private))]
pub struct FastForward {
    /// The branch name of the release being checked for.
    ///
    /// Configuration: Required
    #[builder(setter(into))]
    branch: CommitId,
    /// Whether the check should error or just warn.
    ///
    /// Configuration: Optional
    /// Default: `false`
    #[builder(default = "false")]
    required: bool,
}

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

impl BranchCheck for FastForward {
    fn name(&self) -> &str {
        "fast-forward"
    }

    fn check(
        &self,
        ctx: &CheckGitContext,
        commit: &CommitId,
    ) -> Result<CheckResult, Box<dyn Error>> {
        let merge_base = ctx
            .git()
            .arg("merge-base")
            .arg("--is-ancestor")
            .arg(self.branch.as_str())
            .arg(commit.as_str())
            .output()
            .map_err(|err| GitError::subcommand("merge-base", err))?;
        let ok = match merge_base.status.code() {
            Some(0) => true,
            Some(1) => false,
            code => {
                return Err(FastForwardError::merge_base(
                    commit.clone(),
                    self.branch.clone(),
                    code,
                    &merge_base.stderr,
                )
                .into());
            },
        };

        let mut result = CheckResult::new();

        // Indicate that the branch is eligible for fast-forward merges.
        if !ok {
            if self.required {
                result.add_error(format!(
                    "This branch is ineligible for the fast-forward merging into the `{}` branch; \
                     it needs to be rebased.",
                    self.branch,
                ));
            } else {
                result.add_warning(format!(
                    "Not eligible for fast-forward merging into `{}`.",
                    self.branch,
                ));
            }
        }

        Ok(result)
    }
}

#[cfg(feature = "config")]
pub(crate) mod config {
    use git_checks_config::{register_checks, BranchCheckConfig, IntoCheck};
    use git_workarea::CommitId;
    use serde::Deserialize;
    #[cfg(test)]
    use serde_json::json;

    #[cfg(test)]
    use crate::test;
    use crate::FastForward;

    /// Configuration for the `FastForward` check.
    ///
    /// The `branch` key is a string which is the name of the branch which is the target of
    /// merging. The `required` key is a boolean defaulting to `false` which indicates whether the
    /// check is a hard failure or not.
    ///
    /// This check is registered as a branch check with the name `"fast_forward"`.
    ///
    /// # Example
    ///
    /// ```json
    /// {
    ///     "branch": "master",
    ///     "required": true
    /// }
    /// ```
    #[derive(Deserialize, Debug)]
    pub struct FastForwardConfig {
        branch: String,
        #[serde(default)]
        required: Option<bool>,
    }

    impl IntoCheck for FastForwardConfig {
        type Check = FastForward;

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

            builder.branch(CommitId::new(self.branch));

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

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

    register_checks! {
        FastForwardConfig {
            "fast_forward" => BranchCheckConfig,
        },
    }

    #[test]
    fn test_fast_forward_config_empty() {
        let json = json!({});
        let err = serde_json::from_value::<FastForwardConfig>(json).unwrap_err();
        test::check_missing_json_field(err, "branch");
    }

    #[test]
    fn test_fast_forward_config_branch_is_required() {
        let json = json!({});
        let err = serde_json::from_value::<FastForwardConfig>(json).unwrap_err();
        test::check_missing_json_field(err, "branch");
    }

    #[test]
    fn test_fast_forward_config_minimum_fields() {
        let exp_branch = CommitId::new("v1.x");
        let json = json!({
            "branch": exp_branch.as_str(),
        });
        let check: FastForwardConfig = serde_json::from_value(json).unwrap();

        assert_eq!(check.branch, exp_branch.as_str());
        assert_eq!(check.required, None);

        let check = check.into_check();

        assert_eq!(check.branch, exp_branch);
        assert!(!check.required);
    }

    #[test]
    fn test_fast_forward_config_all_fields() {
        let exp_branch = CommitId::new("v1.x");
        let json = json!({
            "branch": exp_branch.as_str(),
            "required": true,
        });
        let check: FastForwardConfig = serde_json::from_value(json).unwrap();

        assert_eq!(check.branch, exp_branch.as_str());
        assert_eq!(check.required, Some(true));

        let check = check.into_check();

        assert_eq!(check.branch, exp_branch);
        assert!(check.required);
    }
}

#[cfg(test)]
mod tests {
    use git_checks_core::BranchCheck;
    use git_workarea::CommitId;

    use crate::builders::FastForwardBuilder;
    use crate::test::*;
    use crate::FastForward;

    const RELEASE_BRANCH: &str = "3a22ca19fda09183da2faab60819ff6807568acd";
    const NON_FF_TOPIC: &str = "a61fd3759b61a4a1f740f3fe656bc42151cefbdd";
    const FF_TOPIC: &str = "969b794ea82ce51d1555852de33bfcb63dfec969";

    #[test]
    fn test_fast_forward_builder_default() {
        assert!(FastForward::builder().build().is_err());
    }

    #[test]
    fn test_fast_forward_builder_branch_is_required() {
        assert!(FastForward::builder().build().is_err());
    }

    #[test]
    fn test_fast_forward_builder_minimum_fields() {
        assert!(FastForward::builder()
            .branch(CommitId::new("release"))
            .build()
            .is_ok());
    }

    #[test]
    fn test_fast_forward_name_branch() {
        let check = FastForward::builder()
            .branch(CommitId::new("release"))
            .build()
            .unwrap();
        assert_eq!(BranchCheck::name(&check), "fast-forward");
    }

    fn make_fast_forward_check() -> FastForwardBuilder {
        let mut builder = FastForward::builder();
        builder.branch(CommitId::new(RELEASE_BRANCH));
        builder
    }

    #[test]
    fn test_fast_forward_ok() {
        let check = make_fast_forward_check().build().unwrap();
        run_branch_check_ok("test_fast_forward_ok", FF_TOPIC, check);
    }

    #[test]
    fn test_fast_forward_ok_required() {
        let check = make_fast_forward_check().required(true).build().unwrap();
        run_branch_check_ok("test_fast_forward_ok_required", FF_TOPIC, check);
    }

    #[test]
    fn test_fast_forward_bad() {
        let check = make_fast_forward_check().build().unwrap();
        let result = run_branch_check("test_fast_forward_bad", NON_FF_TOPIC, check);
        test_result_warnings(
            result,
            &["Not eligible for fast-forward merging into \
               `3a22ca19fda09183da2faab60819ff6807568acd`."],
        );
    }

    #[test]
    fn test_fast_forward_bad_required() {
        let check = make_fast_forward_check().required(true).build().unwrap();
        let result = run_branch_check("test_fast_forward_bad_required", NON_FF_TOPIC, check);
        test_result_errors(
            result,
            &[
                "This branch is ineligible for the fast-forward merging into the \
                 `3a22ca19fda09183da2faab60819ff6807568acd` branch; it needs to be rebased.",
            ],
        );
    }
}