go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/logdog/client/butlerlib/streamproto/streamName.go (about) 1 // Copyright 2015 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 streamproto 16 17 import ( 18 "encoding/json" 19 "flag" 20 21 "go.chromium.org/luci/logdog/common/types" 22 ) 23 24 // StreamNameFlag is a flag and JSON-compatible type that converts to/from a 25 // types.StreamName. StreamName validation is part of the conversion. 26 type StreamNameFlag types.StreamName 27 28 var _ interface { 29 flag.Value 30 json.Marshaler 31 json.Unmarshaler 32 } = (*StreamNameFlag)(nil) 33 34 // Set implements flag.Value. 35 func (f *StreamNameFlag) Set(v string) error { 36 if err := types.StreamName(v).Validate(); err != nil { 37 return err 38 } 39 *f = StreamNameFlag(v) 40 return nil 41 } 42 43 // String implements flag.Value. 44 func (f *StreamNameFlag) String() string { 45 if f == nil { 46 return "" 47 } 48 return string(*f) 49 } 50 51 // UnmarshalJSON implements json.Unmarshaler. 52 func (f *StreamNameFlag) UnmarshalJSON(data []byte) error { 53 s := "" 54 if err := json.Unmarshal(data, &s); err != nil { 55 return err 56 } 57 if err := types.StreamName(s).Validate(); err != nil { 58 return err 59 } 60 *f = StreamNameFlag(s) 61 return nil 62 } 63 64 // MarshalJSON implements json.Marshaler. 65 func (f StreamNameFlag) MarshalJSON() ([]byte, error) { 66 s := string(f) 67 return json.Marshal(&s) 68 }