Skip to content

Commit 44f9c57

Browse files
Ricardo Lüderstremes
Ricardo Lüders
authored andcommitted
Replacing deprecated ioutil (openshift#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 2fdb142 commit 44f9c57

File tree

11 files changed

+50
-40
lines changed

11 files changed

+50
-40
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"
@@ -77,8 +77,8 @@ func createPullRequestLink(id string) string {
7777
func main() {
7878
log.SetFlags(0)
7979
if len(os.Args) != 1 && len(os.Args) != 3 {
80-
log.Fatalf(`Either specify two date arguments, AFTER and UNTIL,
81-
to create a brand new CHANGELOG, or call it without arguments to
80+
log.Fatalf(`Either specify two date arguments, AFTER and UNTIL,
81+
to create a brand new CHANGELOG, or call it without arguments to
8282
update the current one with new changes.`)
8383
}
8484
gitHubToken = os.Getenv("GITHUB_TOKEN")
@@ -120,7 +120,7 @@ type MarkdownReleaseBlock struct {
120120

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

234-
req, err := http.NewRequestWithContext(context.Background(), "GET", fmt.Sprintf(gitHubAPIFormat, gitHubRepoOwner, gitHubRepo, id), nil)
234+
req, err := http.NewRequestWithContext(
235+
context.Background(),
236+
"GET",
237+
fmt.Sprintf(gitHubAPIFormat, gitHubRepoOwner, gitHubRepo, id),
238+
http.NoBody)
235239
if err != nil {
236240
log.Fatalf(err.Error())
237241
}
@@ -242,7 +246,7 @@ func getPullRequestFromGitHub(id string) *Change {
242246
log.Fatalf(err.Error())
243247
}
244248
defer resp.Body.Close()
245-
body, err := ioutil.ReadAll(resp.Body)
249+
body, err := io.ReadAll(resp.Body)
246250
if err != nil {
247251
defer log.Fatalf(err.Error())
248252
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"
@@ -218,7 +217,7 @@ func findGoMod(pkgFilePath string) (goModPath, relPkgPath string, err error) {
218217

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

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"
@@ -83,7 +82,7 @@ func runGather(operator *controller.GatherJob, cfg *controllercmd.ControllerComm
8382

8483
var clientConfig *rest.Config
8584
if kubeConfigPath := cmd.Flags().Lookup("kubeconfig").Value.String(); len(kubeConfigPath) > 0 {
86-
kubeConfigBytes, err := ioutil.ReadFile(kubeConfigPath) //nolint: govet
85+
kubeConfigBytes, err := os.ReadFile(kubeConfigPath) //nolint: govet
8786
if err != nil {
8887
klog.Fatal(err)
8988
}
@@ -139,7 +138,7 @@ func runOperator(operator *controller.Operator, cfg *controllercmd.ControllerCom
139138
}
140139

141140
// if the service CA is rotated, we want to restart
142-
if data, err := ioutil.ReadFile(serviceCACertPath); err == nil {
141+
if data, err := os.ReadFile(serviceCACertPath); err == nil {
143142
startingFileContent[serviceCACertPath] = data
144143
} else {
145144
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

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

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"
@@ -68,7 +67,7 @@ func gatherMostRecentMetrics(ctx context.Context, metricsClient rest.Interface)
6867
return nil, []error{err}
6968
}
7069
r := utils.NewLineLimitReader(rsp, metricsAlertsLinesLimit)
71-
alerts, err := ioutil.ReadAll(r)
70+
alerts, err := io.ReadAll(r)
7271
if err != nil && err != io.EOF {
7372
klog.Errorf("Unable to read most recent alerts from metrics: %v", err)
7473
return nil, []error{err}

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

+6-7
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"errors"
88
"fmt"
99
"io"
10-
"io/ioutil"
1110
"mime/multipart"
1211
"net"
1312
"net/http"
@@ -98,7 +97,7 @@ func New(client *http.Client, maxBytes int64, metricsName string, authorizer Aut
9897
}
9998

10099
func getTrustedCABundle() (*x509.CertPool, error) {
101-
caBytes, err := ioutil.ReadFile("/var/run/configmaps/trusted-ca-bundle/ca-bundle.crt")
100+
caBytes, err := os.ReadFile("/var/run/configmaps/trusted-ca-bundle/ca-bundle.crt")
102101
if err != nil {
103102
if os.IsNotExist(err) {
104103
return nil, nil
@@ -247,7 +246,7 @@ func (c *Client) Send(ctx context.Context, endpoint string, source Source) error
247246
requestID := resp.Header.Get("x-rh-insights-request-id")
248247

249248
defer func() {
250-
if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil {
249+
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
251250
klog.Warningf("error copying body: %v", err)
252251
}
253252
if err := resp.Body.Close(); err != nil {
@@ -327,14 +326,14 @@ func (c Client) RecvReport(ctx context.Context, endpoint string) (*io.ReadCloser
327326
}
328327

329328
if resp.StatusCode == http.StatusBadRequest {
330-
body, _ := ioutil.ReadAll(resp.Body)
329+
body, _ := io.ReadAll(resp.Body)
331330
if len(body) > 1024 {
332331
body = body[:1024]
333332
}
334333
return nil, fmt.Errorf("gateway server bad request: %s (request=%s): %s", resp.Request.URL, requestID, string(body))
335334
}
336335
if resp.StatusCode == http.StatusNotFound {
337-
body, _ := ioutil.ReadAll(resp.Body)
336+
body, _ := io.ReadAll(resp.Body)
338337
if len(body) > 1024 {
339338
body = body[:1024]
340339
}
@@ -346,7 +345,7 @@ func (c Client) RecvReport(ctx context.Context, endpoint string) (*io.ReadCloser
346345
}
347346

348347
if resp.StatusCode >= 300 || resp.StatusCode < 200 {
349-
body, _ := ioutil.ReadAll(resp.Body)
348+
body, _ := io.ReadAll(resp.Body)
350349
if len(body) > 1024 {
351350
body = body[:1024]
352351
}
@@ -365,7 +364,7 @@ func responseBody(r *http.Response) string {
365364
if r == nil {
366365
return ""
367366
}
368-
body, _ := ioutil.ReadAll(r.Body)
367+
body, _ := io.ReadAll(r.Body)
369368
if len(body) > responseBodyLogLen {
370369
body = body[:responseBodyLogLen]
371370
}

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"
@@ -89,17 +89,21 @@ func (d *DiskRecorder) Save(records record.MemoryRecords) (record.MemoryRecords,
8989

9090
// Prune the archives older than given time
9191
func (d *DiskRecorder) Prune(olderThan time.Time) error {
92-
files, err := ioutil.ReadDir(d.basePath)
92+
files, err := os.ReadDir(d.basePath)
9393
if err != nil {
9494
return err
9595
}
9696
count := 0
9797
var errors []string
9898
for _, file := range files {
99-
if isNotArchiveFile(file) {
99+
fileInfo, err := file.Info()
100+
if err != nil {
100101
continue
101102
}
102-
if file.ModTime().After(olderThan) {
103+
if isNotArchiveFile(fileInfo) {
104+
continue
105+
}
106+
if fileInfo.ModTime().After(olderThan) {
103107
continue
104108
}
105109
if err := os.Remove(filepath.Join(d.basePath, file.Name())); err != nil {
@@ -122,19 +126,25 @@ func (d *DiskRecorder) Prune(olderThan time.Time) error {
122126

123127
// Summary implements summarizer interface to insights uploader
124128
func (d *DiskRecorder) Summary(_ context.Context, since time.Time) (io.ReadCloser, bool, error) {
125-
files, err := ioutil.ReadDir(d.basePath)
129+
files, err := os.ReadDir(d.basePath)
126130
if err != nil {
127131
return nil, false, err
128132
}
129133
if len(files) == 0 {
130134
return nil, false, nil
131135
}
132136
recentFiles := make([]string, 0, len(files))
137+
138+
var fileInfo fs.FileInfo
133139
for _, file := range files {
134-
if isNotArchiveFile(file) {
140+
fileInfo, err = file.Info()
141+
if err != nil {
142+
return nil, false, err
143+
}
144+
if isNotArchiveFile(fileInfo) {
135145
continue
136146
}
137-
if !file.ModTime().After(since) {
147+
if !fileInfo.ModTime().After(since) {
138148
continue
139149
}
140150
recentFiles = append(recentFiles, file.Name())

0 commit comments

Comments
 (0)