Source file src/internal/obscuretestdata/obscuretestdata.go

     1  // Copyright 2019 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package obscuretestdata contains functionality used by tests to more easily
     6  // work with testdata that must be obscured primarily due to
     7  // golang.org/issue/34986.
     8  package obscuretestdata
     9  
    10  import (
    11  	"encoding/base64"
    12  	"io"
    13  	"os"
    14  )
    15  
    16  // DecodeToTempFile decodes the named file to a temporary location.
    17  // If successful, it returns the path of the decoded file.
    18  // The caller is responsible for ensuring that the temporary file is removed.
    19  func DecodeToTempFile(name string) (path string, err error) {
    20  	f, err := os.Open(name)
    21  	if err != nil {
    22  		return "", err
    23  	}
    24  	defer f.Close()
    25  
    26  	tmp, err := os.CreateTemp("", "obscuretestdata-decoded-")
    27  	if err != nil {
    28  		return "", err
    29  	}
    30  	if _, err := io.Copy(tmp, base64.NewDecoder(base64.StdEncoding, f)); err != nil {
    31  		tmp.Close()
    32  		os.Remove(tmp.Name())
    33  		return "", err
    34  	}
    35  	if err := tmp.Close(); err != nil {
    36  		os.Remove(tmp.Name())
    37  		return "", err
    38  	}
    39  	return tmp.Name(), nil
    40  }
    41  
    42  // ReadFile reads the named file and returns its decoded contents.
    43  func ReadFile(name string) ([]byte, error) {
    44  	f, err := os.Open(name)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  	defer f.Close()
    49  	return io.ReadAll(base64.NewDecoder(base64.StdEncoding, f))
    50  }
    51  

View as plain text