Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions MODULE.bazel.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion diff/defs.bzl
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
"Public API re-exports"

load("@bazel_skylib//lib:partial.bzl", "partial")
load("//diff/private:diff.bzl", "diff_rule")
load("//diff/private:diff.bzl", "diff_rule", _FilesToDiffInfo = "FilesToDiffInfo", _diff_multiple = "diff_multiple")

# Re-export the FilesToDiffInfo provider
FilesToDiffInfo = _FilesToDiffInfo

diff_multiple = _diff_multiple

def diff(name, file1, file2, patch = None, exit_code = None, **kwargs):
"""Runs a diff between two files and returns the exit code.
Expand Down
177 changes: 128 additions & 49 deletions diff/private/diff.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

load("//diff/private:options.bzl", "DiffOptionsInfo")

FilesToDiffInfo = provider(
doc = "Which files among the sources are meant to be diffed.",
fields = {
"src_subpaths": "The files to diff among the srcs. Names are expected to match relative to the workspace root.",
"dep_subpaths": "The files to diff among the deps. Names are expected to match relative to the workspace root.",
},
)

# We run diff in actions, so we want to use the execution platform toolchain.
DIFFUTILS_TOOLCHAIN_TYPE = "@diff.bzl//diff/toolchain:execution_type"

Expand All @@ -17,13 +25,31 @@ def _validate_no_diff(ctx, exit_code_file, error_message):
>&2 echo "{}"
exit 1
fi
""".format(exit_code_valid.path, ctx.outputs.exit_code.path, error_message),
""".format(exit_code_valid.path, exit_code_file.path, error_message),
)
return exit_code_valid

def _diff_rule_impl(ctx):
DIFF_BIN = ctx.toolchains[DIFFUTILS_TOOLCHAIN_TYPE].diffutilsinfo.diff_bin
def _maybe_validate_diff(ctx, exit_code_file, patch_file):
if ctx.attr.validate == 1:
validate = True
elif ctx.attr.validate == 0:
validate = False
else:
validate = ctx.attr._options[DiffOptionsInfo].validate_diffs

if not validate:
return []

# NB: the error message we print here allows the user to be in any working directory.
return [_validate_no_diff(ctx, exit_code_file, """\
ERROR: diff command exited with non-zero status.

To accept the diff, run:
( cd \\$(bazel info workspace); patch -p0 < {patch} )
""".format(patch = patch_file.path))]

def _diff_action(ctx, file1, file2, patch, exit_code):
diff_bin = ctx.toolchains[DIFFUTILS_TOOLCHAIN_TYPE].diffutilsinfo.diff_bin
command = """\
{} {} {} {} > {}
EXIT_CODE=$?
Expand All @@ -32,63 +58,130 @@ if [[ $EXIT_CODE == '2' ]]; then
fi
echo $EXIT_CODE > {}
""".format(
DIFF_BIN.path,
diff_bin.path,
" ".join(ctx.attr.args),
ctx.file.file1.path,
ctx.file.file2.path,
ctx.outputs.patch.path,
ctx.outputs.exit_code.path,
file1.path,
file2.path,
patch.path,
exit_code.path,
)

# If both inputs are generated, there's no writable file to patch.
is_copy_to_source = ctx.file.file1.is_source or ctx.file.file2.is_source
outputs = [ctx.outputs.patch, ctx.outputs.exit_code]
outputs = [patch, exit_code]
ctx.actions.run_shell(
inputs = [ctx.file.file1, ctx.file.file2],
inputs = [file1, file2],
outputs = outputs,
command = command,
mnemonic = "DiffutilsDiff",
progress_message = "Diffing %{input} to %{output}",
tools = [DIFF_BIN],
tools = [diff_bin],
toolchain = "@diff.bzl//diffutils/toolchain:execution_type",
)
return outputs

validation_outputs = []
copy_to_source_outputs = [ctx.outputs.patch] if is_copy_to_source else []
def _diff_rule_impl(ctx):
# If both inputs are generated, there's no writable file to patch.
is_copy_to_source = ctx.file.file1.is_source or ctx.file.file2.is_source
outputs = _diff_action(
ctx,
ctx.file.file1,
ctx.file.file2,
ctx.outputs.patch,
ctx.outputs.exit_code,
)

if ctx.attr.validate == 1:
validate = True
elif ctx.attr.validate == 0:
validate = False
else:
validate = ctx.attr._options[DiffOptionsInfo].validate_diffs
copy_to_source_outputs = [ctx.outputs.patch] if is_copy_to_source else []
validation_outputs = _maybe_validate_diff(ctx, ctx.outputs.exit_code, ctx.outputs.patch)
return [
DefaultInfo(files = depset(outputs)),
OutputGroupInfo(
_validation = depset(validation_outputs),
# By reading the Build Events, a Bazel wrapper can identify this diff output group and apply the patch.
diff_bzl__patch = depset(copy_to_source_outputs),
),
]

if validate:
validation_outputs.append(_validate_no_diff(ctx, ctx.outputs.exit_code, """\
ERROR: diff command exited with non-zero status.
# Borrowed from https://github.com/bazelbuild/bazel-skylib/blob/f7718b7b8e2003b9359248e9632c875cb48a6e48/rules/select_file.bzl
def _select_file(deps, subpath):
out = None
canonical = subpath.replace("\\", "/")
candidates = [f for d in deps for f in d[DefaultInfo].files.to_list()]
for file_ in candidates:
if file_.path.replace("\\", "/").endswith(canonical):
out = file_
break
if not out:
files_str = ",\n".join([
str(f.path)
for f in candidates
])
fail("Can not find specified file {} in {}".format(canonical, files_str))
return out

To accept the diff, run:
patch -d \\$(bazel info workspace) -p0 < {patch}
""".format(patch = ctx.outputs.patch.path)))
def _diff_multiple_impl(ctx):
outputs = []
infos = [dep[FilesToDiffInfo] for dep in ctx.attr.deps]

patches = []
exit_codes = []
validation_outputs = []
for info in infos:
for src_subpath, dep_subpath in zip(info.src_subpaths, info.dep_subpaths):
patch = ctx.actions.declare_file(src_subpath + ".patch")
exit_code = ctx.actions.declare_file(src_subpath + ".exit_code")
outputs.extend(_diff_action(
ctx,
_select_file(ctx.attr.srcs, src_subpath),
_select_file(ctx.attr.deps, dep_subpath),
patch,
exit_code,
))
patches.append(patch)
exit_codes.append(exit_code)
validation_outputs.extend(_maybe_validate_diff(ctx, exit_code, patch))
return [
DefaultInfo(files = depset(outputs)),
OutputGroupInfo(
_validation = depset(validation_outputs),
# By reading the Build Events, a Bazel wrapper can identify this diff output group and apply the patch.
diff_bzl__patch = depset(copy_to_source_outputs),
#diff_bzl__patch = depset(copy_to_source_outputs),
),
]

common_attrs = {
"args": attr.string_list(
doc = """\
Additional arguments to pass to the diff command.
""",
default = [],
),
"validate": attr.int(
doc = """\
Whether to treat a non-empty diff (exit 1) as a build validation failure.

-1: default to the flag value --@diff.bzl//diff:validate_diffs
0: never validate
1: always validate

An individual Bazel invocation can run with --norun_validations to skip this behavior.
""",
default = -1,
values = [-1, 0, 1],
),
"_options": attr.label(default = "//diff:diff_options"),
}

diff_multiple = rule(
implementation = _diff_multiple_impl,
attrs = common_attrs | {
"srcs": attr.label_list(allow_files = True),
"deps": attr.label_list(providers = [FilesToDiffInfo]),
},
toolchains = [DIFFUTILS_TOOLCHAIN_TYPE],
)

diff_rule = rule(
implementation = _diff_rule_impl,
attrs = {
"args": attr.string_list(
doc = """\
Additional arguments to pass to the diff command.
""",
default = [],
),
attrs = common_attrs | {
"file1": attr.label(allow_single_file = True),
"file2": attr.label(allow_single_file = True),
"exit_code": attr.output(
Expand All @@ -107,20 +200,6 @@ diff_rule = rule(
""",
mandatory = True,
),
"validate": attr.int(
doc = """\
Whether to treat a non-empty diff (exit 1) as a build validation failure.

-1: default to the flag value --@diff.bzl//diff:validate_diffs
0: never validate
1: always validate

An individual Bazel invocation can run with --norun_validations to skip this behavior.
""",
default = -1,
values = [-1, 0, 1],
),
"_options": attr.label(default = "//diff:diff_options"),
},
toolchains = [DIFFUTILS_TOOLCHAIN_TYPE],
)
1 change: 1 addition & 0 deletions diff/tests/case.3.dir_a/file.txt.orig
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
hello
5 changes: 5 additions & 0 deletions diff/tests/case.3.dir_a/file.txt.rej
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
***************
*** 3
- > moo, moooooo!
--- 3 -----
+ > moo, moooeooo!
39 changes: 39 additions & 0 deletions examples/multiple-files/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
load("@bazel_skylib//rules:write_file.bzl", "write_file")
load("@diff.bzl//diff:defs.bzl", "diff_multiple")
load(":diff_files.bzl", "diff_files")

write_file(
name = "file1",
out = "file1.gen",
content = [
"file1_content",
"",
],
)

write_file(
name = "file2",
out = "file2.gen",
content = [
"file2_content",
"",
],
)

diff_files(
name = "diff_files",
srcs = [
":file1",
":file2",
],
)

diff_multiple(
name = "diff",
srcs = [
"file1.txt",
"file2.txt",
],
validate = 1,
deps = [":diff_files"],
)
21 changes: 21 additions & 0 deletions examples/multiple-files/diff_files.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"A specialization of filegroup that also provides FilesToDiffInfo instructions to diff"

load("@diff.bzl//diff:defs.bzl", "FilesToDiffInfo")

def _diff_files_impl(ctx):
# we expect file paths to appear in the same path under bazel-bin and the source tree
subpaths = [f.short_path for f in ctx.files.srcs]
return [
FilesToDiffInfo(
src_subpaths = [f.replace("gen", "txt") for f in subpaths],
dep_subpaths = subpaths,
),
DefaultInfo(files = depset(ctx.files.srcs)),
]

diff_files = rule(
implementation = _diff_files_impl,
attrs = {
"srcs": attr.label_list(allow_files = True),
},
)
Empty file.
Empty file.
Loading