aboutsummaryrefslogtreecommitdiff
path: root/lib/std/build/check_file.zig
blob: 31966fad521af8d66c5fb65469a9540a5c632731 (plain)
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
// SPDX-License-Identifier: MIT
// Copyright (c) 2015-2021 Zig Contributors
// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("../std.zig");
const build = std.build;
const Step = build.Step;
const Builder = build.Builder;
const fs = std.fs;
const mem = std.mem;
const warn = std.debug.warn;

pub const CheckFileStep = struct {
    step: Step,
    builder: *Builder,
    expected_matches: []const []const u8,
    source: build.FileSource,
    max_bytes: usize = 20 * 1024 * 1024,

    pub fn create(
        builder: *Builder,
        source: build.FileSource,
        expected_matches: []const []const u8,
    ) *CheckFileStep {
        const self = builder.allocator.create(CheckFileStep) catch unreachable;
        self.* = CheckFileStep{
            .builder = builder,
            .step = Step.init(.CheckFile, "CheckFile", builder.allocator, make),
            .source = source,
            .expected_matches = expected_matches,
        };
        self.source.addStepDependencies(&self.step);
        return self;
    }

    fn make(step: *Step) !void {
        const self = @fieldParentPtr(CheckFileStep, "step", step);

        const src_path = self.source.getPath(self.builder);
        const contents = try fs.cwd().readFileAlloc(self.builder.allocator, src_path, self.max_bytes);

        for (self.expected_matches) |expected_match| {
            if (mem.indexOf(u8, contents, expected_match) == null) {
                warn(
                    \\
                    \\========= Expected to find: ===================
                    \\{s}
                    \\========= But file does not contain it: =======
                    \\{s}
                    \\
                , .{ expected_match, contents });
                return error.TestFailed;
            }
        }
    }
};