Debian Codegraph @

zip/internal/obscuretestdata/obscuretestdata.go

raw
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 //go:build go1.16
6
7 // Package obscuretestdata contains functionality used by tests to more easily
8 // work with testdata that must be obscured primarily due to
9 // golang.org/issue/34986.
10 package obscuretestdata
11
12 import (
13 "encoding/base64"
14 "io"
15 "os"
16 )
17
18 // DecodeToTempFile decodes the named file to a temporary location.
19 // If successful, it returns the path of the decoded file.
20 // The caller is responsible for ensuring that the temporary file is removed.
21 func DecodeToTempFile(name string) (path string, err error) {
22 f, err := os.Open(name)
23 if err != nil {
24 return "", err
25 }
26 defer f.Close()
27
28 tmp, err := os.CreateTemp("", "obscuretestdata-decoded-")
29 if err != nil {
30 return "", err
31 }
32 if _, err := io.Copy(tmp, base64.NewDecoder(base64.StdEncoding, f)); err != nil {
33 tmp.Close()
34 os.Remove(tmp.Name())
35 return "", err
36 }
37 if err := tmp.Close(); err != nil {
38 os.Remove(tmp.Name())
39 return "", err
40 }
41 return tmp.Name(), nil
42 }
43
44 // ReadFile reads the named file and returns its decoded contents.
45 func ReadFile(name string) ([]byte, error) {
46 f, err := os.Open(name)
47 if err != nil {
48 return nil, err
49 }
50 defer f.Close()
51 return io.ReadAll(base64.NewDecoder(base64.StdEncoding, f))
52 }