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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
// 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 crates::git_workarea::{GitContext, GitWorkArea};
use crates::itertools::Itertools;
use crates::rayon::prelude::*;
use crates::wait_timeout::ChildExt;

use impl_prelude::*;

use std::fmt;
use std::iter;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::Duration;

#[derive(Debug, Clone)]
/// Run a formatter in the repository to check commits for formatting.
///
/// The formatter is passed a single argument: the path to the file which should be checked.
///
/// The formatter is expected to exit with success whether the path passed to it has a valid format
/// in it or not. A failure exit status is considered a failure of the formatter itself. If any
/// changes (including untracked files) are left inside of the worktree, it is considered to have
/// failed the checks.
///
/// The formatter is run with its current working directory being the top-level of the work tree,
/// but not the proper `GIT_` context. This is because the setup for the workarea is not completely
/// isolated and `git` commands may not behave as expected. The worktree it is working from is only
/// guaranteed to have the files which have changed in the commit being checked on disk, so
/// additional files which should be available for the command to run must be specified with
/// `Formatting::add_config_files`.
pub struct Formatting {
    /// The "name" of the formatter.
    ///
    /// This defaults to the `kind` of the formatter.
    name: Option<String>,
    /// The "kind" of formatting being performed.
    ///
    /// This is used in the name of the attribute which uses this check.
    kind: String,
    /// The path to the formatter.
    formatter: PathBuf,
    /// Configuration files within the repository the formatter
    config_files: Vec<String>,
    /// A message to add when failures occur.
    ///
    /// Projects which check formatting may have a way to fix it automatically. This is here so
    /// that those projects can mention their specific instructions.
    fix_message: Option<String>,
    /// A timeout for running the formatter.
    ///
    /// If the formatter exceeds this timeout, it is considered to have failed.
    timeout: Option<Duration>,
}

/// This is the maximum number of files to list in the error message. Beyond this, the number of
/// other files with formatting issues in them are handled by a "and so many other files" note.
const MAX_EXPLICIT_FILE_LIST: usize = 5;

lazy_static! {
    /// How long to wait for a timed-out formatter to respond to `SIGKILL` before leaving it as a
    /// zombie process.
    static ref ZOMBIE_TIMEOUT: Duration = Duration::from_secs(1);
}

impl Formatting {
    /// Create a new formatting check.
    pub fn new<K, F>(kind: K, formatter: F) -> Self
        where K: ToString,
              F: AsRef<Path>,
    {
        Self {
            name: None,
            kind: kind.to_string(),
            formatter: formatter.as_ref().to_path_buf(),
            config_files: Vec::new(),
            fix_message: None,
            timeout: None,
        }
    }

    /// Set the name of the formatter.
    pub fn named<N>(&mut self, name: N) -> &mut Self
        where N: ToString,
    {
        self.name = Some(name.to_string());
        self
    }

    /// Add configuration files within the repository which should be checked out.
    pub fn add_config_files<I, F>(&mut self, files: I) -> &mut Self
        where I: IntoIterator<Item = F>,
              F: ToString,
    {
        self.config_files.extend(files.into_iter().map(|file| file.to_string()));
        self
    }

    /// Add a message for how to fix issues with this formatter.
    pub fn with_fix_message<F>(&mut self, fix_message: F) -> &mut Self
        where F: ToString,
    {
        self.fix_message = Some(fix_message.to_string());
        self
    }

    /// Add a timeout to the formatter.
    pub fn with_timeout(&mut self, timeout: Duration) -> &mut Self {
        self.timeout = Some(timeout);
        self
    }

    /// Check a path using the formatter.
    fn check_path<'a>(&self, ctx: &GitWorkArea, path: &'a FileName)
                      -> Result<Option<&'a FileName>> {
        let mut cmd = Command::new(&self.formatter);
        ctx.cd_to_work_tree(&mut cmd);
        cmd.arg(path.as_path());

        let (success, output) = if let Some(timeout) = self.timeout {
            let mut child = cmd
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .spawn()
                .chain_err(|| "failed to construct formatter command")?;
            let check = child.wait_timeout(timeout)
                .chain_err(|| "failed to wait on the formatter command")?;

            if let Some(status) = check {
                (status.success(), format!("failed with exit code {:?}, signal {:?}",
                                           status.code(),
                                           status.unix_signal()))
            } else {
                child.kill().chain_err(|| "failed to kill a timed-out formatter")?;
                let timed_out_status = child.wait_timeout(*ZOMBIE_TIMEOUT)
                    .chain_err(|| "failed to wait on a timed-out formatter")?;
                if timed_out_status.is_none() {
                    warn!(target: "git-checks/formatting",
                          "leaving a zombie '{}' process; it did not respond to kill",
                          self.kind);
                }
                (false, "timeout reached".to_string())
            }
        } else {
            let check = cmd.output()
                .chain_err(|| "failed to construct formatter command")?;
            (check.status.success(), String::from_utf8_lossy(&check.stderr).into_owned())
        };

        Ok(if success {
            None
        } else {
            info!(target: "git-checks/formatting",
                  "failed to run the {} formatting command: {}",
                  self.kind,
                  output);
            Some(path)
        })
    }

    /// Create a message for the given paths.
    fn message_for_paths<P>(&self, results: &mut CheckResult, content: &Content,
                            paths: Vec<P>, description: &str)
        where P: fmt::Display,
    {
        if !paths.is_empty() {
            let mut all_paths = paths.into_iter();
            // List at least a certain number of files by name.
            let explicit_paths = all_paths.by_ref()
                .take(MAX_EXPLICIT_FILE_LIST)
                .map(|path| format!("`{}`", path))
                .collect::<Vec<_>>();
            // Eline the remaining files...
            let next_path = all_paths.next();
            let tail_paths = if let Some(next_path) = next_path {
                    let remaining_paths = all_paths.count();
                    if remaining_paths == 0 {
                        // ...but avoid saying `and 1 others`.
                        iter::once(format!("`{}`", next_path)).collect::<Vec<_>>()
                    } else {
                        iter::once(format!("and {} others", remaining_paths + 1))
                            .collect::<Vec<_>>()
                    }
                } else {
                    iter::empty().collect::<Vec<_>>()
                }
                .into_iter();
            let paths = explicit_paths.into_iter()
                .chain(tail_paths)
                .join(", ");
            let fix = self.fix_message
                .as_ref()
                .map_or_else(String::new, |fix_message| format!(" {}", fix_message));
            results.add_error(format!("{}the following files {} the '{}' check: {}.{}",
                                      commit_prefix_str(content, "is not allowed because"),
                                      description,
                                      self.name.as_ref().unwrap_or(&self.kind),
                                      paths,
                                      fix));
        }
    }
}

impl ContentCheck for Formatting {
    fn name(&self) -> &str {
        "formatting"
    }

    fn check(&self, ctx: &CheckGitContext, content: &Content) -> Result<CheckResult> {
        let changed_paths = content.modified_files();

        let gitctx = GitContext::new(ctx.gitdir());
        let workarea = content.workarea(&gitctx)?;

        // Create the files necessary on the disk.
        let files_to_checkout = changed_paths.iter()
            .map(|path| path.as_path())
            .chain(self.config_files.iter().map(AsRef::as_ref))
            .collect::<Vec<_>>();
        workarea.checkout(&files_to_checkout)?;

        let attr = format!("format.{}", self.kind);
        let failed_paths = changed_paths.par_iter()
            .map(|path| {
                if let AttributeState::Set = ctx.check_attr(&attr, path.as_path())? {
                    self.check_path(&workarea, path)
                } else {
                    Ok(None)
                }
            })
            .collect::<Vec<Result<_>>>()
            .into_iter()
            .collect::<Result<Vec<_>>>()?
            .into_iter()
            .filter_map(|path| path)
            .collect::<Vec<_>>();

        let ls_files_m = workarea.git()
            .arg("ls-files")
            .arg("-m")
            .output()
            .chain_err(|| "failed to construct ls-files command")?;
        if !ls_files_m.status.success() {
            bail!(ErrorKind::Git(format!("failed to list modified files in the work area: {}",
                                         String::from_utf8_lossy(&ls_files_m.stderr))));
        }
        let modified_paths = String::from_utf8_lossy(&ls_files_m.stdout);

        // It seems that the `HEAD` ref is used rather than the index for `ls-files -m`, so
        // basically every file is considered `deleted` and therefore listed here. Not sure if this
        // is a bug in Git or not.
        let modified_paths_in_commit = modified_paths.lines()
            .filter(|&path| changed_paths.iter().any(|diff_path| diff_path.as_str() == path))
            .collect();

        let ls_files_o = workarea.git()
            .arg("ls-files")
            .arg("-o")
            .output()
            .chain_err(|| "failed to construct ls-files command")?;
        if !ls_files_o.status.success() {
            bail!(ErrorKind::Git(format!("failed to list untracked files in the work area: {}",
                                         String::from_utf8_lossy(&ls_files_o.stderr))));
        }
        let untracked_paths = String::from_utf8_lossy(&ls_files_o.stdout);

        let mut results = CheckResult::new();

        self.message_for_paths(&mut results,
                               content,
                               failed_paths,
                               "could not be formatted by");
        self.message_for_paths(&mut results,
                               content,
                               modified_paths_in_commit,
                               "are not formatted according to");
        self.message_for_paths(&mut results,
                               content,
                               untracked_paths.lines().collect(),
                               "were created by");

        Ok(results)
    }
}

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

    use std::time::Duration;

    fn formatting_check(kind: &str) -> Formatting {
        let formatter = format!("{}/test/format.{}", env!("CARGO_MANIFEST_DIR"), kind);
        let mut check = Formatting::new(kind, formatter);
        check.add_config_files(&["format-config"]);
        check
    }

    const MISSING_CONFIG_COMMIT: &str = "220efbb4d0380fe932b70444fe15e787506080b0";
    const ADD_CONFIG_COMMIT: &str = "e08e9ac1c5b6a0a67e0b2715cb0dbf99935d9cbf";
    const BAD_FORMAT_COMMIT: &str = "e9a08d956553f94e9c8a0a02b11ca60f62de3c2b";
    const FIX_BAD_FORMAT_COMMIT: &str = "7fe590bdb883e195812cae7602ce9115cbd269ee";
    const OK_FORMAT_COMMIT: &str = "b77d2a5d63cd6afa599d0896dafff95f1ace50b6";
    const IGNORE_UNTRACKED_COMMIT: &str = "c0154d1087906d50c5551ff8f60e544e9a492a48";
    const DELETE_FORMAT_COMMIT: &str = "31446c81184df35498814d6aa3c7f933dddf91c2";
    const MANY_BAD_FORMAT_COMMIT: &str = "f0d10d9385ef697175c48fa72324c33d5e973f4b";
    const MANY_MORE_BAD_FORMAT_COMMIT: &str = "0e80ff6dd2495571b7d255e39fb3e7cc9f487fb7";
    const TIMEOUT_CONFIG_COMMIT: &str = "62f5eac20c5021cf323c757a4d24234c81c9c7ad";

    #[test]
    fn test_formatting_pass() {
        let check = formatting_check("simple");
        let conf = make_check_conf(&check);

        let result = test_check_base("test_formatting_pass",
                                     OK_FORMAT_COMMIT,
                                     BAD_FORMAT_COMMIT,
                                     &conf);
        test_result_ok(result);
    }

    #[test]
    fn test_formatting_formatter_fail() {
        let check = formatting_check("simple");
        let result = run_check("test_formatting_formatter_fail",
                               MISSING_CONFIG_COMMIT,
                               check);
        test_result_errors(result, &[
            "commit 220efbb4d0380fe932b70444fe15e787506080b0 is not allowed because the following \
             files could not be formatted by the 'simple' check: `empty.txt`.",
        ]);
    }

    #[test]
    fn test_formatting_formatter_fail_named() {
        let mut check = formatting_check("simple");
        check.named("renamed");
        let result = run_check("test_formatting_formatter_fail_named",
                               MISSING_CONFIG_COMMIT,
                               check);
        test_result_errors(result, &[
            "commit 220efbb4d0380fe932b70444fe15e787506080b0 is not allowed because the following \
             files could not be formatted by the 'renamed' check: `empty.txt`.",
        ]);
    }

    #[test]
    fn test_formatting_formatter_fail_fix_message() {
        let mut check = formatting_check("simple");
        check.with_fix_message("These may be fixed by magic.");
        let result = run_check("test_formatting_formatter_fail_fix_message",
                               MISSING_CONFIG_COMMIT,
                               check);
        test_result_errors(result, &[
            "commit 220efbb4d0380fe932b70444fe15e787506080b0 is not allowed because the following \
             files could not be formatted by the 'simple' check: `empty.txt`. These may be fixed \
             by magic.",
        ]);
    }

    #[test]
    fn test_formatting_formatter_untracked_files() {
        let check = formatting_check("untracked");
        let result = run_check("test_formatting_formatter_untracked_files",
                               MISSING_CONFIG_COMMIT,
                               check);
        test_result_errors(result, &[
            "commit 220efbb4d0380fe932b70444fe15e787506080b0 is not allowed because the following \
             files were created by the 'untracked' check: `untracked`.",
        ]);
    }

    #[test]
    fn test_formatting_formatter_timeout() {
        let mut check = formatting_check("timeout");
        check.with_timeout(Duration::from_secs(1));
        let result = run_check("test_formatting_formatter_timeout",
                               TIMEOUT_CONFIG_COMMIT,
                               check);
        test_result_errors(result, &[
            "commit 62f5eac20c5021cf323c757a4d24234c81c9c7ad is not allowed because the following \
             files could not be formatted by the 'timeout' check: `empty.txt`.",
        ]);
    }

    #[test]
    fn test_formatting_formatter_untracked_files_ignored() {
        let check = formatting_check("untracked");
        let conf = make_check_conf(&check);

        let result = test_check_base("test_formatting_formatter_untracked_files_ignored",
                                     IGNORE_UNTRACKED_COMMIT,
                                     OK_FORMAT_COMMIT,
                                     &conf);
        test_result_ok(result);
    }

    #[test]
    fn test_formatting_formatter_modified_files() {
        let check = formatting_check("simple");
        let conf = make_check_conf(&check);

        let result = test_check_base("test_formatting_formatter_modified_files",
                                     BAD_FORMAT_COMMIT,
                                     ADD_CONFIG_COMMIT,
                                     &conf);
        test_result_errors(result, &[
            "commit e9a08d956553f94e9c8a0a02b11ca60f62de3c2b is not allowed because the following \
             files are not formatted according to the 'simple' check: `bad.txt`.",
        ]);
    }

    #[test]
    fn test_formatting_formatter_modified_files_topic() {
        let check = formatting_check("simple");
        let conf = make_topic_check_conf(&check);

        let result = test_check_base("test_formatting_formatter_modified_files_topic",
                                     BAD_FORMAT_COMMIT,
                                     ADD_CONFIG_COMMIT,
                                     &conf);
        test_result_errors(result, &[
            "the following files are not formatted according to the 'simple' check: `bad.txt`.",
        ]);
    }

    #[test]
    fn test_formatting_formatter_modified_files_topic_fixed() {
        let check = formatting_check("simple");
        run_topic_check_ok("test_formatting_formatter_modified_files_topic_fixed",
                           FIX_BAD_FORMAT_COMMIT,
                           check);
    }

    #[test]
    fn test_formatting_formatter_many_modified_files() {
        let check = formatting_check("simple");
        let conf = make_check_conf(&check);

        let result = test_check_base("test_formatting_formatter_many_modified_files",
                                     MANY_BAD_FORMAT_COMMIT,
                                     ADD_CONFIG_COMMIT,
                                     &conf);
        test_result_errors(result, &[
            "commit f0d10d9385ef697175c48fa72324c33d5e973f4b is not allowed because the following \
             files are not formatted according to the 'simple' check: `1.bad.txt`, `2.bad.txt`, \
             `3.bad.txt`, `4.bad.txt`, `5.bad.txt`, `6.bad.txt`.",
        ]);
    }

    #[test]
    fn test_formatting_formatter_many_more_modified_files() {
        let check = formatting_check("simple");
        let conf = make_check_conf(&check);

        let result = test_check_base("test_formatting_formatter_many_more_modified_files",
                                     MANY_MORE_BAD_FORMAT_COMMIT,
                                     ADD_CONFIG_COMMIT,
                                     &conf);
        test_result_errors(result, &[
            "commit 0e80ff6dd2495571b7d255e39fb3e7cc9f487fb7 is not allowed because the following \
             files are not formatted according to the 'simple' check: `1.bad.txt`, `2.bad.txt`, \
             `3.bad.txt`, `4.bad.txt`, `5.bad.txt`, and 2 others.",
        ]);
    }

    #[test]
    fn test_formatting_script_deleted_files() {
        let check = formatting_check("delete");
        let result = run_check("test_formatting_script_deleted_files",
                               DELETE_FORMAT_COMMIT,
                               check);
        test_result_errors(result, &[
            "commit 31446c81184df35498814d6aa3c7f933dddf91c2 is not allowed because the following \
            files are not formatted according to the 'delete' check: `remove.txt`.",
        ]);
    }
}