github.com/BarDweller/libpak@v0.0.0-20230630201634-8dd5cfc15ec9/carton/build_image_dependency.go (about) 1 /* 2 * Copyright 2018-2020 the original author or 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 * https://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 carton 18 19 import ( 20 "fmt" 21 "os" 22 "regexp" 23 24 "github.com/BarDweller/libpak/bard" 25 "github.com/BarDweller/libpak/internal" 26 ) 27 28 const ( 29 ImageDependencyPattern = `(?m)(.*build-image[\s]+=[\s]+"[^"]+:)[^"]+(".*)` 30 ImageDependencySubstitution = "${1}%s${2}" 31 ) 32 33 type BuildImageDependency struct { 34 BuilderPath string 35 Version string 36 } 37 38 func (i BuildImageDependency) Update(options ...Option) { 39 config := Config{ 40 exitHandler: internal.NewExitHandler(), 41 } 42 43 for _, option := range options { 44 config = option(config) 45 } 46 47 logger := bard.NewLogger(os.Stdout) 48 _, _ = fmt.Fprintf(logger.TitleWriter(), "\n%s\n", bard.FormatIdentity("Build Image", i.Version)) 49 50 c, err := os.ReadFile(i.BuilderPath) 51 if err != nil { 52 config.exitHandler.Error(fmt.Errorf("unable to read %s\n%w", i.BuilderPath, err)) 53 return 54 } 55 56 r := regexp.MustCompile(ImageDependencyPattern) 57 58 if !r.Match(c) { 59 config.exitHandler.Error(fmt.Errorf("unable to match '%s'", r.String())) 60 return 61 } 62 63 s := fmt.Sprintf(ImageDependencySubstitution, i.Version) 64 c = r.ReplaceAll(c, []byte(s)) 65 66 if err := os.WriteFile(i.BuilderPath, c, 0644); err != nil { 67 config.exitHandler.Error(fmt.Errorf("unable to write %s\n%w", i.BuilderPath, err)) 68 return 69 } 70 71 }