go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/system/filesystem/tempdir.go (about)

     1  // Copyright 2017 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 filesystem
    16  
    17  import (
    18  	"io/ioutil"
    19  )
    20  
    21  // TempDir configures a temporary directory.
    22  type TempDir struct {
    23  	// Dir is the base diectory. If empty, the default will be used (see
    24  	// ioutil.TempDir)
    25  	Dir string
    26  
    27  	// Prefix is the prefix to apply to the temporary directory. If empty, a
    28  	// default will be used (see ioutil.TempDir).
    29  	Prefix string
    30  
    31  	// OnCleanupErr, if not nil, will be called if TempDir cleanup fails.
    32  	//
    33  	// If nil, cleanup errors will be silently discarded.
    34  	CleanupErrFunc func(tdir string, err error)
    35  }
    36  
    37  // With creates a temporary directory and passes it to fn. After fn  exits, the
    38  // directory and all of its contents is deleted.
    39  //
    40  // Any error that happens during setup or execution of the callback is returned.
    41  // If an error occurs during cleanup, the optional CleanupErrFunc will be
    42  // called.
    43  func (td *TempDir) With(fn func(string) error) error {
    44  	tdir, err := ioutil.TempDir(td.Dir, td.Prefix)
    45  	if err != nil {
    46  		return err
    47  	}
    48  	defer func() {
    49  		if rmErr := RemoveAll(tdir); rmErr != nil {
    50  			if cef := td.CleanupErrFunc; cef != nil {
    51  				cef(tdir, rmErr)
    52  			}
    53  		}
    54  	}()
    55  	return fn(tdir)
    56  }