blob: 27c33e9fd0a6fdc76f2247e359d434651ad62f15 [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() {
67 line := scanner.Text()
68 cleanLine := strings.TrimSpace(line)
69 if strings.HasPrefix(cleanLine, "#") || cleanLine == "" {
70 // Pass through comments and empty lines
71 fmt.Fprintln(outFile, line)
72 } else {
73 // Line contains a configuration option
74 parts := strings.SplitN(line, "=", 2)
75 keyName := parts[0]
76 if overrideVal, ok := overrides[strings.TrimSpace(keyName)]; ok {
77 // Override it
78 if overrideVal == "" {
79 fmt.Fprintf(outFile, "# %v is not set\n", keyName)
80 } else {
81 fmt.Fprintf(outFile, "%v=%v\n", keyName, overrideVal)
82 }
83 delete(overrides, keyName)
84 } else {
85 // Pass through unchanged
86 fmt.Fprintln(outFile, line)
87 }
88 }
89 }
90 // Process left over overrides
91 for key, val := range overrides {
92 fmt.Fprintf(outFile, "%v=%v\n", key, val)
93 }
94 return nil
95}