sigs.k8s.io/kubebuilder/v3@v3.14.0/pkg/machinery/marker.go (about)

     1  /*
     2  Copyright 2019 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 machinery
    18  
    19  import (
    20  	"fmt"
    21  	"path/filepath"
    22  	"strings"
    23  )
    24  
    25  const prefix = "+kubebuilder:scaffold:"
    26  
    27  var commentsByExt = map[string]string{
    28  	".go":   "//",
    29  	".yaml": "#",
    30  	".yml":  "#",
    31  	// When adding additional file extensions, update also the NewMarkerFor documentation and error
    32  }
    33  
    34  // Marker represents a machine-readable comment that will be used for scaffolding purposes
    35  type Marker struct {
    36  	comment string
    37  	value   string
    38  }
    39  
    40  // NewMarkerFor creates a new marker customized for the specific file
    41  // Supported file extensions: .go, .yaml, .yml
    42  func NewMarkerFor(path string, value string) Marker {
    43  	ext := filepath.Ext(path)
    44  	if comment, found := commentsByExt[ext]; found {
    45  		return Marker{comment, value}
    46  	}
    47  
    48  	extensions := make([]string, 0, len(commentsByExt))
    49  	for extension := range commentsByExt {
    50  		extensions = append(extensions, fmt.Sprintf("%q", extension))
    51  	}
    52  	panic(fmt.Errorf("unknown file extension: '%s', expected one of: %s", ext, strings.Join(extensions, ", ")))
    53  }
    54  
    55  // String implements Stringer
    56  func (m Marker) String() string {
    57  	return m.comment + prefix + m.value
    58  }
    59  
    60  // EqualsLine compares a marker with a string representation to check if they are the same marker
    61  func (m Marker) EqualsLine(line string) bool {
    62  	line = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), m.comment))
    63  	return line == prefix+m.value
    64  }
    65  
    66  // CodeFragments represents a set of code fragments
    67  // A code fragment is a piece of code provided as a Go string, it may have multiple lines
    68  type CodeFragments []string
    69  
    70  // CodeFragmentsMap binds Markers and CodeFragments together
    71  type CodeFragmentsMap map[Marker]CodeFragments