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  // Rot13 returns the rot13 encoding or decoding of its input.
    17  func Rot13(data []byte) []byte {
    18  	out := make([]byte, len(data))
    19  	copy(out, data)
    20  	for i, c := range out {
    21  		switch {
    22  		case 'A' <= c && c <= 'M' || 'a' <= c && c <= 'm':
    23  			out[i] = c + 13
    24  		case 'N' <= c && c <= 'Z' || 'n' <= c && c <= 'z':
    25  			out[i] = c - 13
    26  		}
    27  	}
    28  	return out
    29  }
    30  
    31  // DecodeToTempFile decodes the named file to a temporary location.
    32  // If successful, it returns the path of the decoded file.
    33  // The caller is responsible for ensuring that the temporary file is removed.
    34  func DecodeToTempFile(name string) (path string, err error) {
    35  	f, err := os.Open(name)
    36  	if err != nil {
    37  		return "", err
    38  	}
    39  	defer f.Close()
    40  
    41  	tmp, err := os.CreateTemp("", "obscuretestdata-decoded-")
    42  	if err != nil {
    43  		return "", err
    44  	}
    45  	if _, err := io.Copy(tmp, base64.NewDecoder(base64.StdEncoding, f)); err != nil {
    46  		tmp.Close()
    47  		os.Remove(tmp.Name())
    48  		return "", err
    49  	}
    50  	if err := tmp.Close(); err != nil {
    51  		os.Remove(tmp.Name())
    52  		return "", err
    53  	}
    54  	return tmp.Name(), nil
    55  }
    56  
    57  // ReadFile reads the named file and returns its decoded contents.
    58  func ReadFile(name string) ([]byte, error) {
    59  	f, err := os.Open(name)
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  	defer f.Close()
    64  	return io.ReadAll(base64.NewDecoder(base64.StdEncoding, f))
    65  }
    66  

View as plain text