Skip to content

Commit 771bed2

Browse files
author
Ricardo Lüders
authored
Bug 2020250: Replacing deprecated ioutil (#532)
* refactor: replacing deprecated ioutil * style: fixing lint issues * fix: lint and error handling * fix: govet err shadow declaration * fix: ignore fileInfo error on prune
1 parent 22ea9c9 commit 771bed2

File tree

13 files changed

+54
-45
lines changed

13 files changed

+54
-45
lines changed

cmd/changelog/main.go

+11-7
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import (
44
"context"
55
"encoding/json"
66
"fmt"
7-
"io/ioutil"
7+
"io"
88
"log"
99
"net/http"
1010
"os"
@@ -78,8 +78,8 @@ func createPullRequestLink(id string) string {
7878
func main() {
7979
log.SetFlags(0)
8080
if len(os.Args) != 1 && len(os.Args) != 3 {
81-
log.Fatalf(`Either specify two date arguments, AFTER and UNTIL,
82-
to create a brand new CHANGELOG, or call it without arguments to
81+
log.Fatalf(`Either specify two date arguments, AFTER and UNTIL,
82+
to create a brand new CHANGELOG, or call it without arguments to
8383
update the current one with new changes.`)
8484
}
8585
gitHubToken = os.Getenv("GITHUB_TOKEN")
@@ -121,7 +121,7 @@ type MarkdownReleaseBlock struct {
121121

122122
func readCHANGELOG() map[string]MarkdownReleaseBlock {
123123
releaseBlocks := make(map[string]MarkdownReleaseBlock)
124-
rawBytes, _ := ioutil.ReadFile("./CHANGELOG.md")
124+
rawBytes, _ := os.ReadFile("./CHANGELOG.md")
125125
rawString := string(rawBytes)
126126
if match := latestHashRegexp.FindStringSubmatch(rawString); len(match) > 0 {
127127
latestHash = match[1]
@@ -182,7 +182,7 @@ func updateToMarkdownReleaseBlock(releaseBlocks map[string]MarkdownReleaseBlock,
182182
func createCHANGELOG(releaseBlocks map[string]MarkdownReleaseBlock) {
183183
file, _ := os.Create("CHANGELOG.md")
184184
defer file.Close()
185-
_, _ = file.WriteString(`# Note: This CHANGELOG is only for the changes in insights operator.
185+
_, _ = file.WriteString(`# Note: This CHANGELOG is only for the changes in insights operator.
186186
Please see OpenShift release notes for official changes\n`)
187187
_, _ = file.WriteString(fmt.Sprintf("<!--Latest hash: %s-->\n", latestHash))
188188
var releases []string
@@ -232,7 +232,11 @@ func getPullRequestFromGitHub(id string) *Change {
232232
// There is a limit for the GitHub API, if you use auth then its 5000/hour
233233
var bearer = "token " + gitHubToken
234234

235-
req, err := http.NewRequestWithContext(context.Background(), "GET", fmt.Sprintf(gitHubAPIFormat, gitHubRepoOwner, gitHubRepo, id), nil)
235+
req, err := http.NewRequestWithContext(
236+
context.Background(),
237+
"GET",
238+
fmt.Sprintf(gitHubAPIFormat, gitHubRepoOwner, gitHubRepo, id),
239+
http.NoBody)
236240
if err != nil {
237241
log.Fatalf(err.Error())
238242
}
@@ -243,7 +247,7 @@ func getPullRequestFromGitHub(id string) *Change {
243247
log.Fatalf(err.Error())
244248
}
245249
defer resp.Body.Close()
246-
body, err := ioutil.ReadAll(resp.Body)
250+
body, err := io.ReadAll(resp.Body)
247251
if err != nil {
248252
defer log.Fatalf(err.Error())
249253
return nil

cmd/gendoc/main.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66
"go/ast"
77
"go/parser"
88
"go/token"
9-
"io/ioutil"
109
"log"
1110
"math/rand"
1211
"os"
@@ -219,7 +218,7 @@ func findGoMod(pkgFilePath string) (goModPath, relPkgPath string, err error) {
219218

220219
// getModuleNameFromGoMod parses the go.mod file and returns the name (URL) of the module.
221220
func getModuleNameFromGoMod(goModPath string) (string, error) {
222-
goModBytes, err := ioutil.ReadFile(goModPath)
221+
goModBytes, err := os.ReadFile(goModPath)
223222
if err != nil {
224223
return "", err
225224
}

cmd/obfuscate-archive/main.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66
"encoding/json"
77
"fmt"
88
"io"
9-
"io/ioutil"
109
"os"
1110
"strings"
1211

@@ -190,7 +189,7 @@ func readArchive(path string) (map[string]*record.MemoryRecord, error) {
190189
return nil, err
191190
}
192191

193-
content, err := ioutil.ReadAll(tarReader)
192+
content, err := io.ReadAll(tarReader)
194193
if err != nil {
195194
return nil, err
196195
}

pkg/cmd/start/start.go

+2-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package start
22

33
import (
44
"context"
5-
"io/ioutil"
65
"math/rand"
76
"os"
87
"time"
@@ -87,7 +86,7 @@ func runGather(operator *controller.GatherJob, cfg *controllercmd.ControllerComm
8786

8887
var clientConfig *rest.Config
8988
if kubeConfigPath := cmd.Flags().Lookup("kubeconfig").Value.String(); len(kubeConfigPath) > 0 {
90-
kubeConfigBytes, err := ioutil.ReadFile(kubeConfigPath) //nolint: govet
89+
kubeConfigBytes, err := os.ReadFile(kubeConfigPath) //nolint: govet
9190
if err != nil {
9291
klog.Exit(err)
9392
}
@@ -143,7 +142,7 @@ func runOperator(operator *controller.Operator, cfg *controllercmd.ControllerCom
143142
}
144143

145144
// if the service CA is rotated, we want to restart
146-
if data, err := ioutil.ReadFile(serviceCACertPath); err == nil {
145+
if data, err := os.ReadFile(serviceCACertPath); err == nil {
147146
startingFileContent[serviceCACertPath] = data
148147
} else {
149148
klog.V(4).Infof("Unable to read service ca bundle: %v", err)

pkg/gatherers/clusterconfig/certificate_signing_requests_test.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ package clusterconfig
33
import (
44
"encoding/json"
55
"fmt"
6-
"io/ioutil"
6+
"io"
77
"os"
88
"reflect"
99
"testing"
@@ -33,7 +33,7 @@ func Test_CSR(t *testing.T) {
3333
t.Fatal("test failed to unmarshal csr data", err)
3434
}
3535
defer f.Close()
36-
bts, err := ioutil.ReadAll(f)
36+
bts, err := io.ReadAll(f)
3737
if err != nil {
3838
t.Fatal("error reading test data file", err)
3939
}
@@ -48,7 +48,7 @@ func Test_CSR(t *testing.T) {
4848
t.Fatal("test failed to unmarshal csr anonymized data", err)
4949
}
5050
defer f.Close()
51-
bts, err = ioutil.ReadAll(f)
51+
bts, err = io.ReadAll(f)
5252
if err != nil {
5353
t.Fatal("error reading test data file", err)
5454
}

pkg/gatherers/clusterconfig/config_maps_test.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
package clusterconfig
22

33
import (
4+
"bytes"
45
"context"
56
"encoding/json"
67
"fmt"
7-
"io/ioutil"
8+
"io"
89
"os"
910
"strings"
1011
"testing"
@@ -86,7 +87,7 @@ func Test_ConfigMap_Anonymizer(t *testing.T) {
8687
mustNotFail(t, err, "unmarshaling of expected failed %+v")
8788
exp, err := json.Marshal(d)
8889
mustNotFail(t, err, "marshaling of expected failed %+v")
89-
if string(exp) != string(md) {
90+
if !bytes.Equal(exp, md) {
9091
t.Fatalf("The test %s result is unexpected. Result: \n%s \nExpected \n%s", tt.testName, string(md), string(exp))
9192
}
9293
})
@@ -119,7 +120,7 @@ func readConfigMapsTestData() (*corev1.ConfigMapList, error) {
119120

120121
defer f.Close()
121122

122-
bts, err := ioutil.ReadAll(f)
123+
bts, err := io.ReadAll(f)
123124
if err != nil {
124125
return nil, fmt.Errorf("error reading test data file %+v ", err)
125126
}

pkg/gatherers/clusterconfig/install_plans_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ package clusterconfig
22

33
import (
44
"context"
5-
"io/ioutil"
5+
"io"
66
"os"
77
"testing"
88

@@ -63,7 +63,7 @@ func Test_InstallPlans_Gather(t *testing.T) {
6363
t.Fatal("test failed to read installplan data", err)
6464
}
6565
defer f.Close()
66-
installplancontent, err := ioutil.ReadAll(f)
66+
installplancontent, err := io.ReadAll(f)
6767
if err != nil {
6868
t.Fatal("error reading test data file", err)
6969
}

pkg/gatherers/clusterconfig/olm_operators_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ package clusterconfig
33
import (
44
"context"
55
"fmt"
6-
"io/ioutil"
6+
"io"
77
"os"
88
"reflect"
99
"testing"
@@ -154,7 +154,7 @@ func readFromFile(filePath string) ([]byte, error) {
154154

155155
defer f.Close()
156156

157-
content, err := ioutil.ReadAll(f)
157+
content, err := io.ReadAll(f)
158158
if err != nil {
159159
return nil, err
160160
}

pkg/gatherers/clusterconfig/recent_metrics.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"context"
55
"fmt"
66
"io"
7-
"io/ioutil"
87

98
"k8s.io/client-go/rest"
109
"k8s.io/klog/v2"
@@ -76,7 +75,7 @@ func gatherMostRecentMetrics(ctx context.Context, metricsClient rest.Interface)
7675
return nil, []error{err}
7776
}
7877
r := utils.NewLineLimitReader(rsp, metricsAlertsLinesLimit)
79-
alerts, err := ioutil.ReadAll(r)
78+
alerts, err := io.ReadAll(r)
8079
if err != nil && err != io.EOF {
8180
klog.Errorf("Unable to read most recent alerts from metrics: %v", err)
8281
return nil, []error{err}

pkg/gatherers/conditional/conditional_gatherer_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ package conditional
33
import (
44
"context"
55
"encoding/json"
6-
"io/ioutil"
6+
"io"
77
"net/http"
88
"strings"
99
"testing"
@@ -175,7 +175,7 @@ func newFakeClientWithMetrics(metrics string) *fake.RESTClient {
175175
Client: fake.CreateHTTPClient(func(request *http.Request) (*http.Response, error) {
176176
resp := &http.Response{
177177
StatusCode: http.StatusOK,
178-
Body: ioutil.NopCloser(strings.NewReader(metrics + "\n")),
178+
Body: io.NopCloser(strings.NewReader(metrics + "\n")),
179179
}
180180
return resp, nil
181181
}),

pkg/gatherers/workloads/workloads_info_test.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"compress/gzip"
66
"context"
77
"encoding/json"
8-
"io/ioutil"
98
"os"
109
"testing"
1110
"time"
@@ -50,7 +49,7 @@ func Test_gatherWorkloadInfo(t *testing.T) {
5049
if err != nil {
5150
t.Fatal(err)
5251
}
53-
if err = ioutil.WriteFile("../../../docs/insights-archive-sample/config/workload_info.json", out, 0750); err != nil {
52+
if err = os.WriteFile("../../../docs/insights-archive-sample/config/workload_info.json", out, 0750); err != nil {
5453
t.Fatal(err)
5554
}
5655

pkg/insights/insightsclient/insightsclient.go

+7-8
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import (
88
"errors"
99
"fmt"
1010
"io"
11-
"io/ioutil"
1211
"mime/multipart"
1312
"net"
1413
"net/http"
@@ -102,7 +101,7 @@ func New(client *http.Client, maxBytes int64, metricsName string, authorizer Aut
102101
}
103102

104103
func getTrustedCABundle() (*x509.CertPool, error) {
105-
caBytes, err := ioutil.ReadFile("/var/run/configmaps/trusted-ca-bundle/ca-bundle.crt")
104+
caBytes, err := os.ReadFile("/var/run/configmaps/trusted-ca-bundle/ca-bundle.crt")
106105
if err != nil {
107106
if os.IsNotExist(err) {
108107
return nil, nil
@@ -251,7 +250,7 @@ func (c *Client) Send(ctx context.Context, endpoint string, source Source) error
251250
requestID := resp.Header.Get(insightsReqId)
252251

253252
defer func() {
254-
if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil {
253+
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
255254
klog.Warningf("error copying body: %v", err)
256255
}
257256
if err := resp.Body.Close(); err != nil {
@@ -332,15 +331,15 @@ func (c Client) RecvReport(ctx context.Context, endpoint string) (*http.Response
332331
}
333332

334333
if resp.StatusCode == http.StatusBadRequest {
335-
body, _ := ioutil.ReadAll(resp.Body)
334+
body, _ := io.ReadAll(resp.Body)
336335
if len(body) > 1024 {
337336
body = body[:1024]
338337
}
339338
c.IncrementRecvReportMetric(resp.StatusCode)
340339
return nil, fmt.Errorf("gateway server bad request: %s (request=%s): %s", resp.Request.URL, requestID, string(body))
341340
}
342341
if resp.StatusCode == http.StatusNotFound {
343-
body, _ := ioutil.ReadAll(resp.Body)
342+
body, _ := io.ReadAll(resp.Body)
344343
if len(body) > 1024 {
345344
body = body[:1024]
346345
}
@@ -353,7 +352,7 @@ func (c Client) RecvReport(ctx context.Context, endpoint string) (*http.Response
353352
}
354353

355354
if resp.StatusCode >= 300 || resp.StatusCode < 200 {
356-
body, _ := ioutil.ReadAll(resp.Body)
355+
body, _ := io.ReadAll(resp.Body)
357356
if len(body) > 1024 {
358357
body = body[:1024]
359358
}
@@ -404,14 +403,14 @@ func (c Client) RecvSCACerts(ctx context.Context, endpoint string) ([]byte, erro
404403
}
405404
}()
406405

407-
return ioutil.ReadAll(resp.Body)
406+
return io.ReadAll(resp.Body)
408407
}
409408

410409
func responseBody(r *http.Response) string {
411410
if r == nil {
412411
return ""
413412
}
414-
body, _ := ioutil.ReadAll(r.Body)
413+
body, _ := io.ReadAll(r.Body)
415414
if len(body) > responseBodyLogLen {
416415
body = body[:responseBodyLogLen]
417416
}

pkg/recorder/diskrecorder/diskrecorder.go

+17-7
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import (
66
"context"
77
"fmt"
88
"io"
9-
"io/ioutil"
9+
"io/fs"
1010
"os"
1111
"path/filepath"
1212
"strings"
@@ -102,17 +102,21 @@ func (d *DiskRecorder) SaveAtPath(records record.MemoryRecords, path string) (re
102102

103103
// Prune the archives older than given time
104104
func (d *DiskRecorder) Prune(olderThan time.Time) error {
105-
files, err := ioutil.ReadDir(d.basePath)
105+
files, err := os.ReadDir(d.basePath)
106106
if err != nil {
107107
return err
108108
}
109109
count := 0
110110
var errors []string
111111
for _, file := range files {
112-
if isNotArchiveFile(file) {
112+
fileInfo, err := file.Info()
113+
if err != nil {
113114
continue
114115
}
115-
if file.ModTime().After(olderThan) {
116+
if isNotArchiveFile(fileInfo) {
117+
continue
118+
}
119+
if fileInfo.ModTime().After(olderThan) {
116120
continue
117121
}
118122
if err := os.Remove(filepath.Join(d.basePath, file.Name())); err != nil {
@@ -135,19 +139,25 @@ func (d *DiskRecorder) Prune(olderThan time.Time) error {
135139

136140
// Summary implements summarizer interface to insights uploader
137141
func (d *DiskRecorder) Summary(_ context.Context, since time.Time) (io.ReadCloser, bool, error) {
138-
files, err := ioutil.ReadDir(d.basePath)
142+
files, err := os.ReadDir(d.basePath)
139143
if err != nil {
140144
return nil, false, err
141145
}
142146
if len(files) == 0 {
143147
return nil, false, nil
144148
}
145149
recentFiles := make([]string, 0, len(files))
150+
151+
var fileInfo fs.FileInfo
146152
for _, file := range files {
147-
if isNotArchiveFile(file) {
153+
fileInfo, err = file.Info()
154+
if err != nil {
155+
return nil, false, err
156+
}
157+
if isNotArchiveFile(fileInfo) {
148158
continue
149159
}
150-
if !file.ModTime().After(since) {
160+
if !fileInfo.ModTime().After(since) {
151161
continue
152162
}
153163
recentFiles = append(recentFiles, file.Name())

0 commit comments

Comments
 (0)