sigs.k8s.io/kubebuilder/v3@v3.14.0/pkg/plugins/golang/v4/scaffolds/edit.go (about)

     1  /*
     2  Copyright 2022 The Kubernetes 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 scaffolds
    18  
    19  import (
    20  	"github.com/spf13/afero"
    21  
    22  	"sigs.k8s.io/kubebuilder/v3/pkg/config"
    23  	"sigs.k8s.io/kubebuilder/v3/pkg/machinery"
    24  	"sigs.k8s.io/kubebuilder/v3/pkg/plugins"
    25  )
    26  
    27  var _ plugins.Scaffolder = &editScaffolder{}
    28  
    29  type editScaffolder struct {
    30  	config     config.Config
    31  	multigroup bool
    32  
    33  	// fs is the filesystem that will be used by the scaffolder
    34  	fs machinery.Filesystem
    35  }
    36  
    37  // NewEditScaffolder returns a new Scaffolder for configuration edit operations
    38  func NewEditScaffolder(config config.Config, multigroup bool) plugins.Scaffolder {
    39  	return &editScaffolder{
    40  		config:     config,
    41  		multigroup: multigroup,
    42  	}
    43  }
    44  
    45  // InjectFS implements cmdutil.Scaffolder
    46  func (s *editScaffolder) InjectFS(fs machinery.Filesystem) {
    47  	s.fs = fs
    48  }
    49  
    50  // Scaffold implements cmdutil.Scaffolder
    51  func (s *editScaffolder) Scaffold() error {
    52  	filename := "Dockerfile"
    53  	bs, err := afero.ReadFile(s.fs.FS, filename)
    54  	if err != nil {
    55  		return err
    56  	}
    57  	str := string(bs)
    58  
    59  	// Ignore the error encountered, if the file is already in desired format.
    60  	if err != nil && s.multigroup != s.config.IsMultiGroup() {
    61  		return err
    62  	}
    63  
    64  	if s.multigroup {
    65  		_ = s.config.SetMultiGroup()
    66  	} else {
    67  		_ = s.config.ClearMultiGroup()
    68  	}
    69  
    70  	// Check if the str is not empty, because when the file is already in desired format it will return empty string
    71  	// because there is nothing to replace.
    72  	if str != "" {
    73  		// TODO: instead of writing it directly, we should use the scaffolding machinery for consistency
    74  		return afero.WriteFile(s.fs.FS, filename, []byte(str), 0644)
    75  	}
    76  
    77  	return nil
    78  }