Skip to content

Commit 0d7a8ab

Browse files
committed
build: add more methods to invoke cpp
Add an environment variable and CLI flag to force the use of the C Preprocessor (cpp) instead of only relying on the Containerfile suffix. Closes #6744 Signed-off-by: James Harmison <jharmison@gmail.com>
1 parent 5713383 commit 0d7a8ab

8 files changed

Lines changed: 81 additions & 4 deletions

File tree

define/build.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,8 @@ type BuildOptions struct {
274274
CommonBuildOpts *CommonBuildOptions
275275
// CPPFlags are additional arguments to pass to the C Preprocessor (cpp).
276276
CPPFlags []string
277+
// Preprocess tells the builder to run the C Preprocessor (cpp) regardless of the file extension.
278+
Preprocess types.OptionalBool
277279
// DefaultMountsFilePath is the file path holding the mounts to be mounted for RUN
278280
// instructions in "host-path:container-path" format
279281
DefaultMountsFilePath string

docs/buildah-build.1.md

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ The build context directory can be specified as the http(s) URL of an archive, g
1818

1919
If no context directory is specified, then Buildah will assume the current working directory as build context, which should contain a Containerfile.
2020

21-
Containerfiles ending with a ".in" suffix will be preprocessed via cpp(1). This can be useful to decompose Containerfiles into several reusable parts that can be used via CPP's **#include** directive. Notice, a Containerfile.in file can still be used by other tools when manually preprocessing them via `cpp -E`. Any comments ( Lines beginning with `#` ) in included Containerfile(s) that are not preprocess commands, will be printed as warnings during builds.
21+
Containerfiles ending with a ".in" suffix will be automatically preprocessed via cpp(1). This can be useful to decompose Containerfiles into several reusable parts that can be used via CPP's **#include** directive. Notice, a Containerfile.in file can still be used by other tools when manually preprocessing them via `cpp -E`. Any comments ( Lines beginning with `#` ) in included Containerfile(s) that are not preprocess commands, will be printed as warnings during builds.
2222

2323
When the URL is an archive, the contents of the URL is downloaded to a temporary location and extracted before execution.
2424

@@ -829,6 +829,13 @@ The `buildah build` command allows building images for all Linux architectures,
829829

830830
**NOTE:** The `--platform` option may not be used in combination with the `--arch`, `--os`, or `--variant` options.
831831

832+
**--preprocess**
833+
834+
If specified, will always attempt to use the C Preprocessor cpp(1),
835+
even if the Containerfile doesn't end with the ".in" suffix.
836+
Note: You can also configure this behavior by setting the BUILDAH\_PREPROCESS
837+
environment variable to `1`, `true`, or `yes`.
838+
832839
**--pull**
833840

834841
Pull image policy. If not specified, the default is **missing**. If an explicit

imagebuildah/build.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,8 +162,10 @@ func BuildDockerfiles(ctx context.Context, store storage.Store, options define.B
162162
data = contents
163163
}
164164

165-
// pre-process Dockerfiles with ".in" suffix
166-
if strings.HasSuffix(dfile, ".in") {
165+
// pre-process Dockerfiles with ".in" suffix, if --preprocess is specified, or if BUILDAH_PREPROCESS is set
166+
preprocessSpecified := options.Preprocess == types.OptionalBoolTrue
167+
preprocessInferred := (options.Preprocess == types.OptionalBoolUndefined) && strings.HasSuffix(dfile, ".in")
168+
if preprocessSpecified || preprocessInferred {
167169
pData, err := preprocessContainerfileContents(logger, dfile, data, options.ContextDirectory, options.CPPFlags)
168170
if err != nil {
169171
return "", nil, err

pkg/cli/build.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,7 @@ func GenBuildOptions(c *cobra.Command, inputArgs []string, iopts BuildOptions) (
399399
sbomScanOptions = append(sbomScanOptions, *sbomScanOption)
400400
}
401401

402-
var compatVolumes, createdAnnotation, inheritAnnotations, inheritLabels, skipUnusedStages types.OptionalBool
402+
var compatVolumes, createdAnnotation, inheritAnnotations, inheritLabels, skipUnusedStages, preprocess types.OptionalBool
403403
if c.Flag("compat-volumes").Changed {
404404
compatVolumes = types.NewOptionalBool(iopts.CompatVolumes)
405405
}
@@ -415,6 +415,9 @@ func GenBuildOptions(c *cobra.Command, inputArgs []string, iopts BuildOptions) (
415415
if c.Flag("skip-unused-stages").Changed {
416416
skipUnusedStages = types.NewOptionalBool(iopts.SkipUnusedStages)
417417
}
418+
if c.Flag("preprocess").Changed || DefaultPreprocess() {
419+
preprocess = types.NewOptionalBool(iopts.Preprocess)
420+
}
418421

419422
options = define.BuildOptions{
420423
AddCapabilities: iopts.CapAdd,
@@ -433,6 +436,7 @@ func GenBuildOptions(c *cobra.Command, inputArgs []string, iopts BuildOptions) (
433436
CompatVolumes: compatVolumes,
434437
ConfidentialWorkload: confidentialWorkloadOptions,
435438
CPPFlags: iopts.CPPFlags,
439+
Preprocess: preprocess,
436440
CommonBuildOpts: commonOpts,
437441
Compression: compression,
438442
CompressionFormat: compressionFormat,

pkg/cli/common.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ type BudResults struct {
9595
Timestamp int64
9696
OmitHistory bool
9797
OCIHooksDir []string
98+
Preprocess bool
9899
Pull string
99100
PullAlways bool
100101
PullNever bool
@@ -250,6 +251,7 @@ func GetBudFlags(flags *BudResults) pflag.FlagSet {
250251
fs.BoolVar(&flags.InheritLabels, "inherit-labels", true, "inherit the labels from the base image or base stages.")
251252
fs.BoolVar(&flags.InheritAnnotations, "inherit-annotations", true, "inherit the annotations from the base image or base stages.")
252253
fs.StringArrayVar(&flags.CPPFlags, "cpp-flag", []string{}, "set additional flag to pass to C preprocessor (cpp)")
254+
fs.BoolVar(&flags.Preprocess, "preprocess", DefaultPreprocess(), "use the C preprocessor (cpp) on a Dockerfile, regardless of the file suffix. Use BUILDAH_PREPROCESS environment variable to change default.")
253255
fs.BoolVar(&flags.CreatedAnnotation, "created-annotation", true, `set an "org.opencontainers.image.created" annotation in the image`)
254256
fs.StringVar(&flags.Creds, "creds", "", "use `[username[:password]]` for accessing the registry")
255257
fs.StringVarP(&flags.CWOptions, "cw", "", "", "confidential workload `options`")
@@ -544,6 +546,16 @@ func DefaultHistory() bool {
544546
return false
545547
}
546548

549+
// DefaultPreprocess returns true if BUILDAH_PREPROCESS is set to "1" or "true"
550+
// otherwise it returns false
551+
func DefaultPreprocess() bool {
552+
preprocess := os.Getenv("BUILDAH_PREPROCESS")
553+
if strings.ToLower(preprocess) == "true" || preprocess == "1" {
554+
return true
555+
}
556+
return false
557+
}
558+
547559
func VerifyFlagsArgsOrder(args []string) error {
548560
for _, arg := range args {
549561
if strings.HasPrefix(arg, "-") {

tests/bud.bats

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4126,6 +4126,46 @@ _EOF
41264126
expect_output --substring "Ignoring <stdin>:5:2: error: #error"
41274127
}
41284128

4129+
@test "bud with preprocessor, via --preprocess" {
4130+
_prefetch busybox
4131+
target=alpine-image
4132+
run_buildah build $WITH_POLICY_JSON -t ${target} --preprocess -f Decomposed.tpl $BUDFILES/preprocess
4133+
}
4134+
4135+
@test "bud with preprocessor-requiring containerfile, without --preprocess" {
4136+
_prefetch busybox
4137+
target=alpine-image
4138+
run_buildah 125 build $WITH_POLICY_JSON -t ${target} -f Decomposed.tpl $BUDFILES/preprocess
4139+
expect_output --substring 'Build error: Unknown instruction: "RUNHELLO"'
4140+
}
4141+
4142+
@test "bud with preprocessor error, via --preprocess" {
4143+
_prefetch busybox
4144+
target=alpine-image
4145+
run_buildah bud $WITH_POLICY_JSON -t ${target} --preprocess -f Error.tpl $BUDFILES/preprocess
4146+
expect_output --substring "Ignoring <stdin>:5:2: error: #error"
4147+
}
4148+
4149+
@test "bud with preprocessor, via env var" {
4150+
_prefetch busybox
4151+
target=alpine-image
4152+
BUILDAH_PREPROCESS=1 run_buildah build $WITH_POLICY_JSON -t ${target} -f Decomposed.tpl $BUDFILES/preprocess
4153+
}
4154+
4155+
@test "bud with preprocessor error, via env var" {
4156+
_prefetch busybox
4157+
target=alpine-image
4158+
BUILDAH_PREPROCESS=1 run_buildah bud $WITH_POLICY_JSON -t ${target} -f Error.tpl $BUDFILES/preprocess
4159+
expect_output --substring "Ignoring <stdin>:5:2: error: #error"
4160+
}
4161+
4162+
@test "bud with preprocessor-implied containerfile, with preprocess force disabled" {
4163+
_prefetch busybox
4164+
target=alpine-image
4165+
run_buildah 125 build $WITH_POLICY_JSON -t ${target} --preprocess=false -f Decomposed.in $BUDFILES/preprocess
4166+
expect_output --substring 'Build error: Unknown instruction: "RUNHELLO"'
4167+
}
4168+
41294169
@test "bud-with-rejected-name" {
41304170
target=ThisNameShouldBeRejected
41314171
run_buildah 125 build -q $WITH_POLICY_JSON -t ${target} $BUDFILES/from-scratch
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
FROM busybox
2+
3+
#include "common"
4+
5+
RUNHELLO

tests/bud/preprocess/Error.tpl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
FROM busybox
2+
3+
#include "common"
4+
5+
#error THISERROR

0 commit comments

Comments
 (0)