github.com/GoogleContainerTools/skaffold@v1.39.18/pkg/skaffold/build/logfile.go (about)

     1  /*
     2  Copyright 2020 The Skaffold Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package build
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"io"
    23  
    24  	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/logfile"
    25  	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/platform"
    26  	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest"
    27  )
    28  
    29  type Muted interface {
    30  	MuteBuild() bool
    31  }
    32  
    33  // WithLogFile wraps an `artifactBuilder` so that it optionally outputs its logs to a file.
    34  func WithLogFile(builder ArtifactBuilder, muted Muted) ArtifactBuilder {
    35  	if !muted.MuteBuild() {
    36  		return builder
    37  	}
    38  
    39  	return func(ctx context.Context, out io.Writer, artifact *latest.Artifact, tag string, platforms platform.Matcher) (string, error) {
    40  		file, err := logfile.Create("build", artifact.ImageName+".log")
    41  		if err != nil {
    42  			return "", fmt.Errorf("unable to create log file for %s: %w", artifact.ImageName, err)
    43  		}
    44  		fmt.Fprintln(out, " - writing logs to", file.Name())
    45  
    46  		// Run the build.
    47  		digest, err := builder(ctx, file, artifact, tag, platforms)
    48  
    49  		// After the build finishes, close the log file.
    50  		file.Close()
    51  
    52  		return digest, err
    53  	}
    54  }