...

Source file src/github.com/bazelbuild/buildtools/buildifier/utils/tempfile.go

Documentation: github.com/bazelbuild/buildtools/buildifier/utils

     1  /*
     2  Copyright 2020 Google LLC
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      https://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package utils
    18  
    19  import (
    20  	"fmt"
    21  	"io/ioutil"
    22  	"os"
    23  )
    24  
    25  // TempFile keeps track of temporary files and cleans them up in the end
    26  type TempFile struct {
    27  	filenames []string
    28  }
    29  
    30  // WriteTemp writes data to a temporary file and returns the name of the file.
    31  func (tf *TempFile) WriteTemp(data []byte) (file string, err error) {
    32  	f, err := ioutil.TempFile("", "buildifier-tmp-")
    33  	if err != nil {
    34  		return "", fmt.Errorf("creating temporary file: %v", err)
    35  	}
    36  	defer func() {
    37  		e := f.Close()
    38  		if e != nil {
    39  			err = e
    40  		}
    41  	}()
    42  
    43  	name := f.Name()
    44  	if _, err := f.Write(data); err != nil {
    45  		return "", fmt.Errorf("writing temporary file: %v", err)
    46  	}
    47  	tf.filenames = append(tf.filenames, name)
    48  	return name, nil
    49  }
    50  
    51  // Clean removes all created temporary files
    52  func (tf *TempFile) Clean() error {
    53  	for _, file := range tf.filenames {
    54  		if err := os.Remove(file); err != nil {
    55  			return err
    56  		}
    57  	}
    58  	tf.filenames = []string{}
    59  	return nil
    60  }
    61  

View as plain text