blob: 1b5f24ff85785e3552a535daf279f0a93508ae82 [file] [log] [blame]
Lorenz Brun547b33f2020-04-23 15:27:06 +02001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17package main
18
19import (
20 "bufio"
21 "encoding/json"
22 "flag"
23 "fmt"
24 "io"
25 "os"
26 "strings"
27)
28
29var (
30 inPath = flag.String("in", "", "Path to input Kconfig")
31 outPath = flag.String("out", "", "Path to output Kconfig")
32)
33
34func main() {
35 flag.Parse()
36 if *inPath == "" || *outPath == "" {
37 flag.PrintDefaults()
38 os.Exit(2)
39 }
40 inFile, err := os.Open(*inPath)
41 if err != nil {
42 fmt.Fprintf(os.Stderr, "Failed to open input Kconfig: %v\n", err)
43 os.Exit(1)
44 }
45 outFile, err := os.Create(*outPath)
46 if err != nil {
47 fmt.Fprintf(os.Stderr, "Failed to create output Kconfig: %v\n", err)
48 os.Exit(1)
49 }
50 var config struct {
51 Overrides map[string]string `json:"overrides"`
52 }
53 if err := json.Unmarshal([]byte(flag.Arg(0)), &config); err != nil {
54 fmt.Fprintf(os.Stderr, "Failed to parse overrides: %v\n", err)
55 os.Exit(1)
56 }
57 err = patchKconfig(inFile, outFile, config.Overrides)
58 if err != nil {
59 fmt.Fprintf(os.Stderr, "Failed to patch: %v\n", err)
60 os.Exit(1)
61 }
62}
63
64func patchKconfig(inFile io.Reader, outFile io.Writer, overrides map[string]string) error {
65 scanner := bufio.NewScanner(inFile)
66 for scanner.Scan() {
Tim Windelschmidt783d0782024-04-17 17:38:32 +020067 if scanner.Err() != nil {
68 return scanner.Err()
69 }
Lorenz Brun547b33f2020-04-23 15:27:06 +020070 line := scanner.Text()
71 cleanLine := strings.TrimSpace(line)
72 if strings.HasPrefix(cleanLine, "#") || cleanLine == "" {
73 // Pass through comments and empty lines
74 fmt.Fprintln(outFile, line)
75 } else {
76 // Line contains a configuration option
77 parts := strings.SplitN(line, "=", 2)
78 keyName := parts[0]
79 if overrideVal, ok := overrides[strings.TrimSpace(keyName)]; ok {
80 // Override it
81 if overrideVal == "" {
82 fmt.Fprintf(outFile, "# %v is not set\n", keyName)
83 } else {
84 fmt.Fprintf(outFile, "%v=%v\n", keyName, overrideVal)
85 }
86 delete(overrides, keyName)
87 } else {
88 // Pass through unchanged
89 fmt.Fprintln(outFile, line)
90 }
91 }
92 }
93 // Process left over overrides
94 for key, val := range overrides {
95 fmt.Fprintf(outFile, "%v=%v\n", key, val)
96 }
97 return nil
98}