Skip to content

Commit e702e09

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 341785a commit e702e09

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
@@ -265,6 +265,8 @@ type BuildOptions struct {
265265
CommonBuildOpts *CommonBuildOptions
266266
// CPPFlags are additional arguments to pass to the C Preprocessor (cpp).
267267
CPPFlags []string
268+
// Preprocess tells the builder to run the C Preprocessor (cpp) regardless of the file extension.
269+
Preprocess types.OptionalBool
268270
// DefaultMountsFilePath is the file path holding the mounts to be mounted for RUN
269271
// instructions in "host-path:container-path" format
270272
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

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

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

823+
**--preprocess**
824+
825+
If specified, will always attempt to use the C Preprocessor cpp(1),
826+
even if the Containerfile doesn't end with the ".in" suffix.
827+
Note: You can also configure this behavior by setting the BUILDAH\_PREPROCESS
828+
environment variable to `1`, `true`, or `yes`.
829+
823830
**--pull**
824831

825832
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
@@ -363,7 +363,7 @@ func GenBuildOptions(c *cobra.Command, inputArgs []string, iopts BuildOptions) (
363363
sbomScanOptions = append(sbomScanOptions, *sbomScanOption)
364364
}
365365

366-
var compatVolumes, createdAnnotation, inheritAnnotations, inheritLabels, skipUnusedStages types.OptionalBool
366+
var compatVolumes, createdAnnotation, inheritAnnotations, inheritLabels, skipUnusedStages, preprocess types.OptionalBool
367367
if c.Flag("compat-volumes").Changed {
368368
compatVolumes = types.NewOptionalBool(iopts.CompatVolumes)
369369
}
@@ -379,6 +379,9 @@ func GenBuildOptions(c *cobra.Command, inputArgs []string, iopts BuildOptions) (
379379
if c.Flag("skip-unused-stages").Changed {
380380
skipUnusedStages = types.NewOptionalBool(iopts.SkipUnusedStages)
381381
}
382+
if c.Flag("preprocess").Changed || DefaultPreprocess() {
383+
preprocess = types.NewOptionalBool(iopts.Preprocess)
384+
}
382385

383386
options = define.BuildOptions{
384387
AddCapabilities: iopts.CapAdd,
@@ -397,6 +400,7 @@ func GenBuildOptions(c *cobra.Command, inputArgs []string, iopts BuildOptions) (
397400
CompatVolumes: compatVolumes,
398401
ConfidentialWorkload: confidentialWorkloadOptions,
399402
CPPFlags: iopts.CPPFlags,
403+
Preprocess: preprocess,
400404
CommonBuildOpts: commonOpts,
401405
Compression: compression,
402406
ConfigureNetwork: networkPolicy,

pkg/cli/common.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ type BudResults struct {
7070
Compress bool
7171
Creds string
7272
CPPFlags []string
73+
Preprocess bool
7374
DisableCompression bool
7475
DisableContentTrust bool
7576
IgnoreFile string
@@ -247,6 +248,7 @@ func GetBudFlags(flags *BudResults) pflag.FlagSet {
247248
fs.BoolVar(&flags.InheritLabels, "inherit-labels", true, "inherit the labels from the base image or base stages.")
248249
fs.BoolVar(&flags.InheritAnnotations, "inherit-annotations", true, "inherit the annotations from the base image or base stages.")
249250
fs.StringArrayVar(&flags.CPPFlags, "cpp-flag", []string{}, "set additional flag to pass to C preprocessor (cpp)")
251+
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.")
250252
fs.BoolVar(&flags.CreatedAnnotation, "created-annotation", true, `set an "org.opencontainers.image.created" annotation in the image`)
251253
fs.StringVar(&flags.Creds, "creds", "", "use `[username[:password]]` for accessing the registry")
252254
fs.StringVarP(&flags.CWOptions, "cw", "", "", "confidential workload `options`")
@@ -536,6 +538,16 @@ func DefaultHistory() bool {
536538
return false
537539
}
538540

541+
// DefaultPreprocess returns true if BUILDAH_PREPROCESS is set to "1" or "true"
542+
// otherwise it returns false
543+
func DefaultPreprocess() bool {
544+
preprocess := os.Getenv("BUILDAH_PREPROCESS")
545+
if strings.ToLower(preprocess) == "true" || preprocess == "1" {
546+
return true
547+
}
548+
return false
549+
}
550+
539551
func VerifyFlagsArgsOrder(args []string) error {
540552
for _, arg := range args {
541553
if strings.HasPrefix(arg, "-") {

tests/bud.bats

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

4104+
@test "bud with preprocessor, via --preprocess" {
4105+
_prefetch busybox
4106+
target=alpine-image
4107+
run_buildah build $WITH_POLICY_JSON -t ${target} --preprocess -f Decomposed.tpl $BUDFILES/preprocess
4108+
}
4109+
4110+
@test "bud with preprocessor-requiring containerfile, without --preprocess" {
4111+
_prefetch busybox
4112+
target=alpine-image
4113+
run_buildah 125 build $WITH_POLICY_JSON -t ${target} -f Decomposed.tpl $BUDFILES/preprocess
4114+
expect_output --substring 'Build error: Unknown instruction: "RUNHELLO"'
4115+
}
4116+
4117+
@test "bud with preprocessor error, via --preprocess" {
4118+
_prefetch busybox
4119+
target=alpine-image
4120+
run_buildah bud $WITH_POLICY_JSON -t ${target} --preprocess -f Error.tpl $BUDFILES/preprocess
4121+
expect_output --substring "Ignoring <stdin>:5:2: error: #error"
4122+
}
4123+
4124+
@test "bud with preprocessor, via env var" {
4125+
_prefetch busybox
4126+
target=alpine-image
4127+
BUILDAH_PREPROCESS=1 run_buildah build $WITH_POLICY_JSON -t ${target} -f Decomposed.tpl $BUDFILES/preprocess
4128+
}
4129+
4130+
@test "bud with preprocessor error, via env var" {
4131+
_prefetch busybox
4132+
target=alpine-image
4133+
BUILDAH_PREPROCESS=1 run_buildah bud $WITH_POLICY_JSON -t ${target} -f Error.tpl $BUDFILES/preprocess
4134+
expect_output --substring "Ignoring <stdin>:5:2: error: #error"
4135+
}
4136+
4137+
@test "bud with preprocessor-implied containerfile, with preprocess force disabled" {
4138+
_prefetch busybox
4139+
target=alpine-image
4140+
run_buildah 125 build $WITH_POLICY_JSON -t ${target} --preprocess=false -f Decomposed.in $BUDFILES/preprocess
4141+
expect_output --substring 'Build error: Unknown instruction: "RUNHELLO"'
4142+
}
4143+
41044144
@test "bud-with-rejected-name" {
41054145
target=ThisNameShouldBeRejected
41064146
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)