github.com/GoogleContainerTools/skaffold@v1.39.18/pkg/skaffold/initializer/config.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 initializer 18 19 import ( 20 "context" 21 "os" 22 "path/filepath" 23 "regexp" 24 "strings" 25 26 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/initializer/build" 27 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/initializer/deploy" 28 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" 29 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest" 30 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/warnings" 31 ) 32 33 var ( 34 // for testing 35 getWd = os.Getwd 36 ) 37 38 func generateSkaffoldConfig(b build.Initializer, d deploy.Initializer) *latest.SkaffoldConfig { 39 // if we're here, the user has no skaffold yaml so we need to generate one 40 // if the user doesn't have any k8s yamls, generate one for each dockerfile 41 log.Entry(context.TODO()).Info("generating skaffold config") 42 43 name, err := suggestConfigName() 44 if err != nil { 45 warnings.Printf("Couldn't generate default config name: %s", err.Error()) 46 } 47 48 deploy, profiles := d.DeployConfig() 49 build, portForward := b.BuildConfig() 50 51 return &latest.SkaffoldConfig{ 52 APIVersion: latest.Version, 53 Kind: "Config", 54 Metadata: latest.Metadata{ 55 Name: name, 56 }, 57 Pipeline: latest.Pipeline{ 58 Build: build, 59 Deploy: deploy, 60 PortForward: portForward, 61 }, 62 Profiles: profiles, 63 } 64 } 65 66 func suggestConfigName() (string, error) { 67 cwd, err := getWd() 68 if err != nil { 69 return "", err 70 } 71 72 base := filepath.Base(cwd) 73 74 // give up for edge cases 75 if base == "." || base == string(filepath.Separator) { 76 return "", nil 77 } 78 79 return canonicalizeName(base), nil 80 } 81 82 // canonicalizeName converts a given string to a valid k8s name string. 83 // See https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names for details 84 func canonicalizeName(name string) string { 85 forbidden := regexp.MustCompile(`[^-.a-z]+`) 86 canonicalized := forbidden.ReplaceAllString(strings.ToLower(name), "-") 87 if len(canonicalized) <= 253 { 88 return canonicalized 89 } 90 return canonicalized[:253] 91 }