xref: /aosp_15_r20/external/bazelbuild-rules_android/src/common/golang/ini.go (revision 9e965d6fece27a77de5377433c2f7e6999b8cc0b)
1// Copyright 2018 The Bazel Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//    http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Package ini provides utility functions to read and write ini files.
16package ini
17
18import (
19	"fmt"
20	"io"
21	"io/ioutil"
22	"log"
23	"os"
24	"sort"
25	"strings"
26)
27
28func parse(in string) map[string]string {
29	m := make(map[string]string)
30	lines := strings.Split(in, "\n")
31	for i, l := range lines {
32		l = strings.TrimSpace(l)
33		if len(l) == 0 {
34			// Skip empty line
35			continue
36		}
37		if strings.HasPrefix(l, ";") || strings.HasPrefix(l, "#") {
38			// Skip comment
39			continue
40		}
41		kv := strings.SplitN(l, "=", 2)
42		if len(kv) < 2 {
43			log.Printf("Invalid line in ini file at line:%v %q\n", i, l)
44			// Skip invalid line
45			continue
46		}
47		k := strings.TrimSpace(kv[0])
48		v := strings.TrimSpace(kv[1])
49		if ov, ok := m[k]; ok {
50			log.Printf("Overwrite \"%s=%s\", duplicate found at line:%v %q\n", k, ov, i, l)
51		}
52		m[k] = v
53	}
54	return m
55}
56
57func write(f io.Writer, m map[string]string) {
58	var keys []string
59	for k := range m {
60		keys = append(keys, k)
61	}
62	sort.Strings(keys)
63	for _, k := range keys {
64		fmt.Fprintf(f, "%s=%s\n", k, m[k])
65	}
66}
67
68// Read reads an ini file.
69func Read(n string) (map[string]string, error) {
70	c, err := ioutil.ReadFile(n)
71	if err != nil {
72		return nil, err
73	}
74	return parse(string(c)), nil
75}
76
77// Write writes an ini file.
78func Write(n string, m map[string]string) error {
79	f, err := os.Create(n)
80	if err != nil {
81		return err
82	}
83	defer f.Close()
84	write(f, m)
85	return nil
86}
87