go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/flag/jsonmap.go (about) 1 // Copyright 2019 The LUCI Authors. 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 flag 16 17 import ( 18 "encoding/json" 19 "flag" 20 21 "go.chromium.org/luci/common/errors" 22 ) 23 24 type jsonMap map[string]string 25 26 // JSONMap returns a flag.Value that can be passed to flag.Var to 27 // parse a JSON string into a map. 28 func JSONMap(m *map[string]string) flag.Value { 29 return (*jsonMap)(m) 30 } 31 32 func (m *jsonMap) String() string { 33 if m == nil { 34 return "null" 35 } 36 d, err := json.Marshal(*m) 37 if err != nil { 38 // Marshaling a map[string]string shouldn't error. 39 panic(err) 40 } 41 return string(d) 42 } 43 44 func (m *jsonMap) Set(s string) error { 45 if m == nil { 46 return errors.Reason("JSONMap pointer is nil").Err() 47 } 48 d := []byte(s) 49 return json.Unmarshal(d, m) 50 }