blob: 8150c383875d68051809614bd35b8e6b61d762b4 [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2015 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17// Package types contains go type information, packaged in a way that makes
18// auto-generation convenient, whether by template or straight go functions.
19package types
20
21import (
22 "fmt"
23 "strings"
24)
25
26// ExtractCommentTags parses comments for lines of the form:
27//
28// 'marker' + "key=value".
29//
30// Values are optional; "" is the default. A tag can be specified more than
31// one time and all values are returned. If the resulting map has an entry for
32// a key, the value (a slice) is guaranteed to have at least 1 element.
33//
34// Example: if you pass "+" for 'marker', and the following lines are in
35// the comments:
36// +foo=value1
37// +bar
38// +foo=value2
39// +baz="qux"
40// Then this function will return:
41// map[string][]string{"foo":{"value1, "value2"}, "bar": {""}, "baz": {"qux"}}
42func ExtractCommentTags(marker string, lines []string) map[string][]string {
43 out := map[string][]string{}
44 for _, line := range lines {
45 line = strings.Trim(line, " ")
46 if len(line) == 0 {
47 continue
48 }
49 if !strings.HasPrefix(line, marker) {
50 continue
51 }
52 // TODO: we could support multiple values per key if we split on spaces
53 kv := strings.SplitN(line[len(marker):], "=", 2)
54 if len(kv) == 2 {
55 out[kv[0]] = append(out[kv[0]], kv[1])
56 } else if len(kv) == 1 {
57 out[kv[0]] = append(out[kv[0]], "")
58 }
59 }
60 return out
61}
62
63// ExtractSingleBoolCommentTag parses comments for lines of the form:
64//
65// 'marker' + "key=value1"
66//
67// If the tag is not found, the default value is returned. Values are asserted
68// to be boolean ("true" or "false"), and any other value will cause an error
69// to be returned. If the key has multiple values, the first one will be used.
70func ExtractSingleBoolCommentTag(marker string, key string, defaultVal bool, lines []string) (bool, error) {
71 values := ExtractCommentTags(marker, lines)[key]
72 if values == nil {
73 return defaultVal, nil
74 }
75 if values[0] == "true" {
76 return true, nil
77 }
78 if values[0] == "false" {
79 return false, nil
80 }
81 return false, fmt.Errorf("tag value for %q is not boolean: %q", key, values[0])
82}