-
Notifications
You must be signed in to change notification settings - Fork 18k
/
Copy pathcover.go
100 lines (87 loc) · 2.42 KB
/
cover.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package test
import (
"cmd/go/internal/base"
"cmd/go/internal/cfg"
"fmt"
"io"
"os"
"path/filepath"
"sync"
)
var coverMerge struct {
f *os.File
fsize int64 // size of valid data written to f
sync.Mutex // for f.Write
}
// initCoverProfile initializes the test coverage profile.
// It must be run before any calls to mergeCoverProfile or closeCoverProfile.
// Using this function clears the profile in case it existed from a previous run,
// or in case it doesn't exist and the test is going to fail to create it (or not run).
func initCoverProfile() {
if testCoverProfile == "" || testC {
return
}
if !filepath.IsAbs(testCoverProfile) {
testCoverProfile = filepath.Join(testOutputDir.getAbs(), testCoverProfile)
}
// No mutex - caller's responsibility to call with no racing goroutines.
f, err := os.Create(testCoverProfile)
if err != nil {
base.Fatalf("%v", err)
}
s, err := fmt.Fprintf(f, "mode: %s\n", cfg.BuildCoverMode)
if err != nil {
base.Fatalf("%v", err)
}
coverMerge.f = f
coverMerge.fsize += int64(s)
}
// mergeCoverProfile merges file into the profile stored in testCoverProfile.
// It prints any errors it encounters to ew.
func mergeCoverProfile(file string) error {
if coverMerge.f == nil {
return nil
}
coverMerge.Lock()
defer coverMerge.Unlock()
expect := fmt.Sprintf("mode: %s\n", cfg.BuildCoverMode)
buf := make([]byte, len(expect))
r, err := os.Open(file)
if err != nil {
// Test did not create profile, which is OK.
return nil
}
defer r.Close()
n, err := io.ReadFull(r, buf)
if n == 0 {
return nil
}
if err != nil || string(buf) != expect {
return fmt.Errorf("test wrote malformed coverage profile %s", file)
}
m, err := io.Copy(coverMerge.f, r)
if err != nil {
if m > 0 {
// Attempt to rollback partial write.
coverMerge.f.Seek(coverMerge.fsize, 0)
}
return fmt.Errorf("saving coverage profile: %w", err)
}
coverMerge.fsize += m
return nil
}
func closeCoverProfile() {
if coverMerge.f == nil {
return
}
// Discard any partially written data from a failed merge.
if err := coverMerge.f.Truncate(coverMerge.fsize); err != nil {
base.Errorf("closing coverage profile: %v", err)
}
if err := coverMerge.f.Close(); err != nil {
base.Errorf("closing coverage profile: %v", err)
}
}