-
Notifications
You must be signed in to change notification settings - Fork 1
/
misc.go
68 lines (63 loc) · 1.3 KB
/
misc.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
package libbusyna
import (
"bufio"
"log"
"os"
"regexp"
)
// TmpEnd finishes a temporary file by closing its file descriptor and deleting
// it in the filesystem.
func TmpEnd(f *os.File) {
if f == nil {
return
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
if err := os.Remove(f.Name()); err != nil {
log.Fatal(err)
}
f = nil
}
// ReFindMap returns a map with the matched substrings of a regexp.
func ReFindMap(re *regexp.Regexp, l string) map[string]string {
m := re.FindAllStringSubmatch(l, -1)[0]
names := re.SubexpNames()
r := make(map[string]string)
for i := 0; i < len(names); i++ {
r[names[i]] = m[i]
}
return r
}
// ChanFromFile returns a channel that receives the provided file,
// line-by-line.
func ChanFromFile(filename string) <-chan string {
fd, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
c := make(chan string)
go func() {
defer close(c)
defer fd.Close()
scanner := bufio.NewScanner(fd)
for scanner.Scan() {
c <- scanner.Text()
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}()
return c
}
// ChanFromList returns a channel that receives the elements of the list.
func ChanFromList(list []string) <-chan string {
c := make(chan string)
go func() {
defer close(c)
for _, l := range list {
c <- l
}
}()
return c
}