go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/lucictx/exported.go (about) 1 // Copyright 2016 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 "io" 19 "os" 20 "os/exec" 21 "strings" 22 23 "go.chromium.org/luci/common/system/environ" 24 ) 25 26 // Exported represents an exported on-disk LUCI_CONTEXT file. 27 type Exported interface { 28 io.Closer 29 30 // SetInCmd sets/replaces the LUCI_CONTEXT environment variable in an 31 // exec.Cmd. 32 SetInCmd(c *exec.Cmd) 33 34 // SetInEnviron sets/replaces the LUCI_CONTEXT in an environ.Env object. 35 SetInEnviron(env environ.Env) 36 } 37 38 type baseExport struct { 39 closed bool 40 } 41 42 func (e baseExport) assertOpen() { 43 if e.closed { 44 panic("Using closed lucictx.Exported object") 45 } 46 } 47 48 func (e *baseExport) Close() error { 49 e.assertOpen() 50 e.closed = true 51 return nil 52 } 53 54 type liveExport struct { 55 baseExport 56 path string 57 closer func() 58 } 59 60 func (e *liveExport) SetInCmd(c *exec.Cmd) { 61 e.assertOpen() 62 pfx := EnvKey + "=" 63 newVal := pfx + e.path 64 if c.Env == nil { 65 c.Env = os.Environ() 66 } 67 for i, l := range c.Env { 68 if strings.HasPrefix(strings.ToUpper(l), pfx) { 69 c.Env[i] = newVal 70 return 71 } 72 } 73 c.Env = append(c.Env, newVal) 74 } 75 76 func (e *liveExport) SetInEnviron(env environ.Env) { 77 e.assertOpen() 78 env.Set(EnvKey, e.path) 79 } 80 81 func (e *liveExport) Close() error { 82 e.baseExport.Close() 83 e.closer() 84 return nil 85 } 86 87 type nullExport struct { 88 baseExport 89 } 90 91 func (n *nullExport) SetInCmd(c *exec.Cmd) { 92 n.assertOpen() 93 pfx := EnvKey + "=" 94 if c.Env == nil { 95 c.Env = os.Environ() 96 } 97 filtered := make([]string, 0, len(c.Env)) 98 for _, l := range c.Env { 99 if !strings.HasPrefix(strings.ToUpper(l), pfx) { 100 filtered = append(filtered, l) 101 } 102 } 103 c.Env = filtered 104 } 105 106 func (n *nullExport) SetInEnviron(env environ.Env) { 107 n.assertOpen() 108 env.Remove(EnvKey) 109 }