/
workspace.go
211 lines (176 loc) 路 5.44 KB
/
workspace.go
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
// Copyright 2016-2021, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package workspace
import (
// nolint: gosec
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
// W offers functionality for interacting with Pulumi workspaces.
type W interface {
Settings() *Settings // returns a mutable pointer to the optional workspace settings info.
Save() error // saves any modifications to the workspace.
}
type projectWorkspace struct {
name tokens.PackageName // the package this workspace is associated with.
project string // the path to the Pulumi.[yaml|json] file for this project.
settings *Settings // settings for this workspace.
}
var cache = make(map[string]W)
var cacheMutex sync.RWMutex
func loadFromCache(key string) (W, bool) {
cacheMutex.RLock()
defer cacheMutex.RUnlock()
w, ok := cache[key]
return w, ok
}
func upsertIntoCache(key string, w W) {
contract.Require(w != nil, "w")
cacheMutex.Lock()
defer cacheMutex.Unlock()
cache[key] = w
}
// New creates a new workspace using the current working directory.
func New() (W, error) {
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
return NewFrom(cwd)
}
// NewFrom creates a new Pulumi workspace in the given directory. Requires a Pulumi.yaml file be present in the
// folder hierarchy between dir and the .pulumi folder.
func NewFrom(dir string) (W, error) {
absDir, err := filepath.Abs(dir)
if err != nil {
return nil, err
}
dir = absDir
if w, ok := loadFromCache(dir); ok {
return w, nil
}
path, err := DetectProjectPathFrom(dir)
if err != nil {
return nil, err
} else if path == "" {
return nil, errors.Errorf("no Pulumi.yaml project file found (searching upwards from %s). If you have not "+
"created a project yet, use `pulumi new` to do so", dir)
}
proj, err := LoadProject(path)
if err != nil {
return nil, err
}
w := &projectWorkspace{
name: proj.Name,
project: path,
}
err = w.readSettings()
if err != nil {
return nil, fmt.Errorf("unable to read workspace settings: %w", err)
}
upsertIntoCache(dir, w)
return w, nil
}
func (pw *projectWorkspace) Settings() *Settings {
return pw.settings
}
func (pw *projectWorkspace) Save() error {
settingsFile := pw.settingsPath()
// If the settings file is empty, don't write an new one, and delete the old one if present. Since we put workspaces
// under ~/.pulumi/workspaces, cleaning them out when possible prevents us from littering a bunch of files in the
// home directory.
if pw.settings.IsEmpty() {
err := os.Remove(settingsFile)
if err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
err := os.MkdirAll(filepath.Dir(settingsFile), 0700)
if err != nil {
return err
}
b, err := json.MarshalIndent(pw.settings, "", " ")
if err != nil {
return err
}
return atomicWriteFile(settingsFile, b)
}
// atomicWriteFile provides a rename based atomic write through a temporary file.
func atomicWriteFile(path string, b []byte) error {
tmp, err := ioutil.TempFile(filepath.Dir(path), filepath.Base(path))
if err != nil {
return errors.Wrapf(err, "failed to create temporary file %s", path)
}
defer func() { contract.Ignore(os.Remove(tmp.Name())) }()
if err = tmp.Chmod(0600); err != nil {
return errors.Wrap(err, "failed to set temporary file permission")
}
if _, err = tmp.Write(b); err != nil {
return errors.Wrap(err, "failed to write to temporary file")
}
if err = tmp.Sync(); err != nil {
return err
}
if err = tmp.Close(); err != nil {
return err
}
return os.Rename(tmp.Name(), path)
}
func (pw *projectWorkspace) readSettings() error {
settingsPath := pw.settingsPath()
b, err := ioutil.ReadFile(settingsPath)
if err != nil && os.IsNotExist(err) {
// not an error to not have an existing settings file.
pw.settings = &Settings{}
return nil
} else if err != nil {
return err
}
var settings Settings
err = json.Unmarshal(b, &settings)
if err != nil {
return errors.Wrapf(err, "could not parse file %s", settingsPath)
}
pw.settings = &settings
return nil
}
func (pw *projectWorkspace) settingsPath() string {
uniqueFileName := string(pw.name) + "-" + sha1HexString(pw.project) + "-" + WorkspaceFile
path, err := GetPulumiPath(WorkspaceDir, uniqueFileName)
contract.AssertNoErrorf(err, "could not get workspace path")
return path
}
// sha1HexString returns a hex string of the sha1 hash of value.
func sha1HexString(value string) string {
// nolint: gosec
h := sha1.New()
_, err := h.Write([]byte(value))
contract.AssertNoError(err)
return hex.EncodeToString(h.Sum(nil))
}
// qnameFileName takes a qname and cleans it for use as a filename (by replacing tokens.QNameDelimter with a dash)
func qnameFileName(nm tokens.QName) string {
return strings.Replace(string(nm), tokens.QNameDelimiter, "-", -1)
}