1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2024 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package clientutil
import (
"errors"
"fmt"
"strings"
"github.com/snapcore/snapd/i18n"
"github.com/snapcore/snapd/jsonutil"
)
// ParseConfigOptions controls how config values should be parsed.
type ParseConfigOptions struct {
// String is enabled when values should be stored as-is w/o parsing being parsed.
String bool
// Typed is enabled when values should be stored parsed as JSON. If String is
// enabled, this value is ignored.
Typed bool
}
// ParseConfigValues parses config values in the format of "foo=bar" or "!foo",
// optionally a strict strings or JSON values depending on passed options.
// By default, values are parsed if valid JSON and stored as-is if not.
// Returns a map of config keys to values to set and a slice of keys in the order
// they were passed in.
func ParseConfigValues(confValues []string, opts *ParseConfigOptions) (map[string]any, []string, error) {
if opts == nil {
opts = &ParseConfigOptions{}
}
patchValues := make(map[string]any, len(confValues))
keys := make([]string, 0, len(confValues))
for _, patchValue := range confValues {
parts := strings.SplitN(patchValue, "=", 2)
if len(parts) == 1 && strings.HasSuffix(patchValue, "!") {
key := strings.TrimSuffix(patchValue, "!")
if key == "" {
return nil, nil, errors.New(i18n.G("configuration keys cannot be empty (use key! to unset a key)"))
}
patchValues[key] = nil
keys = append(keys, key)
continue
}
if len(parts) != 2 {
return nil, nil, fmt.Errorf(i18n.G("invalid configuration: %q (want key=value)"), patchValue)
}
if parts[0] == "" {
return nil, nil, errors.New(i18n.G("configuration keys cannot be empty"))
}
if opts.String {
patchValues[parts[0]] = parts[1]
} else {
var value any
if err := jsonutil.DecodeWithNumber(strings.NewReader(parts[1]), &value); err != nil {
if opts.Typed {
return nil, nil, fmt.Errorf(i18n.G("failed to parse JSON: %w"), err)
}
// Not valid JSON-- just save the string as-is.
patchValues[parts[0]] = parts[1]
} else {
patchValues[parts[0]] = value
}
}
keys = append(keys, parts[0])
}
return patchValues, keys, nil
}
|