go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/lucictx/realm.go (about) 1 // Copyright 2020 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 lucictx 16 17 import ( 18 "context" 19 "fmt" 20 "strings" 21 ) 22 23 // GetRealm returns the current "realm" section from LUCI_CONTEXT if it was 24 // present or nil otherwise. 25 func GetRealm(ctx context.Context) *Realm { 26 ret := Realm{} 27 ok, err := Lookup(ctx, "realm", &ret) 28 if err != nil { 29 panic(err) 30 } 31 if !ok { 32 return nil 33 } 34 return &ret 35 } 36 37 // SetRealm sets the Realm in the LUCI_CONTEXT. 38 func SetRealm(ctx context.Context, r *Realm) context.Context { 39 return Set(ctx, "realm", r) 40 } 41 42 // CurrentRealm grab the result of GetRealm and parses it into parts. 43 // 44 // Returns empty strings if there's no "realm" section in the LUCI_CONTEXT. 45 func CurrentRealm(ctx context.Context) (project, realm string) { 46 r := GetRealm(ctx) 47 if r == nil || r.Name == "" { 48 return 49 } 50 idx := strings.IndexRune(r.Name, ':') 51 if idx == -1 { 52 panic(fmt.Sprintf("bad realm name %q in LUCI_CONTEXT - should be <project>:<realm>", r.Name)) 53 } 54 return r.Name[:idx], r.Name[idx+1:] 55 }