File tree 1 file changed +33
-0
lines changed
1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -182,6 +182,39 @@ func (ms *State) WritePath(fp string, p []byte) error {
182
182
return os .WriteFile (fp , p , 0644 )
183
183
}
184
184
185
+ func (ms * State ) AtomicWritePath (fp string , p []byte ) error {
186
+ if fp == "-" {
187
+ return ms .WritePath (fp , p )
188
+ }
189
+
190
+ dir := filepath .Dir (fp )
191
+ base := filepath .Base (fp )
192
+ tempFile , err := os .CreateTemp (dir , "tmp-" + base + "-" )
193
+ if err != nil {
194
+ return err
195
+ }
196
+ defer func () {
197
+ // Clean up temporary file if it still exists and there's an error
198
+ if err != nil {
199
+ os .Remove (tempFile .Name ())
200
+ }
201
+ }()
202
+
203
+ if _ , err = tempFile .Write (p ); err != nil {
204
+ return err
205
+ }
206
+
207
+ if err = tempFile .Close (); err != nil {
208
+ return err
209
+ }
210
+
211
+ if err = os .Rename (tempFile .Name (), fp ); err != nil {
212
+ return err
213
+ }
214
+
215
+ return nil
216
+ }
217
+
185
218
// AbsPath joins the PWD with fp to give the absolute path to fp.
186
219
func (ms * State ) AbsPath (fp string ) string {
187
220
if fp == "-" || filepath .IsAbs (fp ) {
You can’t perform that action at this time.
0 commit comments