Skip to content

Commit 3f6e609

Browse files
committed
close opened and created files
1 parent 3787ebf commit 3f6e609

File tree

2 files changed

+21
-43
lines changed

2 files changed

+21
-43
lines changed

lib.go

+21-28
Original file line numberDiff line numberDiff line change
@@ -45,44 +45,37 @@ func New(probabilistic bool, limit uint32, fpRatio float64) DejaVu {
4545
// PROCESS TEXT (for dejavu bin) //
4646
///////////////////////////////////
4747

48-
func getReaders(paths []string) ([]io.Reader, error) {
49-
readers := make([]io.Reader, len(paths))
50-
for i, path := range paths {
48+
// ProcessPaths is equivalent to Process, only that file paths are given.
49+
// If - in inputs to use stdin and empty out to use stdout.
50+
func ProcessPaths(d DejaVu, filter bool, out string, inputs ...string) error {
51+
52+
// get output writer
53+
var writer *os.File
54+
if out == "" {
55+
writer = os.Stdout
56+
} else {
57+
writer, err := os.Create(out)
58+
if err != nil {
59+
return err
60+
}
61+
defer writer.Close()
62+
}
63+
64+
// get input readers
65+
readers := make([]io.Reader, len(inputs))
66+
for i, path := range inputs {
5167
if path == "-" { // read from stdin
5268
readers[i] = os.Stdin
5369
} else { // read from file path
5470
file, err := os.Open(path)
5571
if err != nil {
56-
return nil, err
72+
return err
5773
}
74+
defer file.Close()
5875
readers[i] = file
5976
}
6077
}
61-
return readers, nil
62-
}
6378

64-
func getWriter(path string) (io.Writer, error) {
65-
if path == "" {
66-
return os.Stdout, nil
67-
}
68-
file, err := os.Create(path)
69-
if err != nil {
70-
return nil, err
71-
}
72-
return file, nil
73-
}
74-
75-
// ProcessPaths is equivalent to Process, only that file paths are given.
76-
// If - in inputs to use stdin and empty out to use stdout.
77-
func ProcessPaths(d DejaVu, filter bool, out string, inputs ...string) error {
78-
writer, err := getWriter(out)
79-
if err != nil {
80-
return err
81-
}
82-
readers, err := getReaders(inputs)
83-
if err != nil {
84-
return err
85-
}
8679
Process(d, filter, writer, readers...)
8780
return nil
8881
}

lib_test.go

-15
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package dejavu
22

33
import (
44
"crypto/rand"
5-
"os"
65
"testing"
76
)
87

@@ -86,17 +85,3 @@ func TestProcess(t *testing.T) {
8685
d := NewProbabilistic(65536, 0.00000001)
8786
ProcessPaths(d, true, "/dev/null", "LICENSE", "README.md")
8887
}
89-
90-
func TestGetWriterStdout(t *testing.T) {
91-
w, _ := getWriter("")
92-
if w != os.Stdout {
93-
t.Errorf("Expected stdout writer!")
94-
}
95-
}
96-
97-
func TestGetReadersStdin(t *testing.T) {
98-
r, _ := getReaders([]string{"-"})
99-
if len(r) != 1 && r[0] != os.Stdin {
100-
t.Errorf("Expected stdin reader!")
101-
}
102-
}

0 commit comments

Comments
 (0)