Skip to content

Instantly share code, notes, and snippets.

@dmikusa
Created March 18, 2024 03:42
Show Gist options
  • Save dmikusa/b9ec718c6c6c9af399ad8f3ae4b817f2 to your computer and use it in GitHub Desktop.
Save dmikusa/b9ec718c6c6c9af399ad8f3ae4b817f2 to your computer and use it in GitHub Desktop.
Update a buildpack.toml file. For automating changes across many buildpacks.
package main
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/BurntSushi/toml"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("USAGE:")
fmt.Println(" update-buildpack-toml <bp-path>")
os.Exit(1)
}
buildpackRoot := os.Args[1]
file := filepath.Join(buildpackRoot, "buildpack.toml")
c, err := os.ReadFile(file)
if err != nil && !os.IsNotExist(err) {
panic(fmt.Errorf("unable to read %s\n%w", file, err))
}
comments := []byte{}
for i, line := range bytes.SplitAfter(c, []byte("\n")) {
if bytes.HasPrefix(line, []byte("#")) || (i > 0 && len(bytes.TrimSpace(line)) == 0) {
comments = append(comments, line...)
} else {
break // stop on first comment
}
}
md := make(map[string]interface{})
if err := toml.Unmarshal(c, &md); err != nil {
panic(fmt.Errorf("unable to decode buildpack\n%w", err))
}
md["targets"] = []map[string]string{
{
"os": "linux",
"arch": "amd64",
},
{
"os": "linux",
"arch": "arm64",
},
}
metadata, ok := md["metadata"].(map[string]interface{})
if !ok {
panic(fmt.Errorf("unable to find metadata key"))
}
include_files_raw, ok := metadata["include-files"]
if !ok {
panic(fmt.Errorf("unable to find include-files key"))
}
include_files, ok := include_files_raw.([]interface{})
if !ok {
panic(fmt.Errorf("unable to cast include-files to []string: %v", include_files_raw))
}
alreadyUpdated := false
new_include_files := []string{}
for _, f := range include_files {
if strings.HasPrefix(f.(string), "linux/") {
alreadyUpdated = true
break
}
if strings.HasPrefix(f.(string), "bin/") {
continue
}
new_include_files = append(new_include_files, f.(string))
}
if !alreadyUpdated {
new_include_files = append(new_include_files, []string{
"linux/amd64/bin/build",
"linux/amd64/bin/detect",
"linux/amd64/bin/main",
"linux/arm64/bin/build",
"linux/arm64/bin/detect",
"linux/arm64/bin/main",
}...)
}
metadata["include-files"] = new_include_files
buf := &bytes.Buffer{}
encoder := toml.NewEncoder(buf)
if err := encoder.Encode(md); err != nil {
panic(fmt.Errorf("unable to encode buildpack\n%w", err))
}
if err := os.WriteFile(file, append(comments, buf.Bytes()...), 0644); err != nil {
panic(fmt.Errorf("unable to write out %s\n%w", file, err))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment