aboutsummaryrefslogtreecommitdiffstats
path: root/skate/xio/util.go
blob: 681f2604ecdcb7cdf18ac626f458db754a53a8c7 (plain)
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
package xio

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
)

// OpenTwo opens two files. The caller needs to check for a single error only.
func OpenTwo(f1, f2 string) (g1, g2 *os.File, err error) {
	if g1, err = os.Open(f1); err != nil {
		return nil, nil, err
	}
	if g2, err = os.Open(f2); err != nil {
		return nil, nil, err
	}
	return g1, g2, nil
}

// TabsToMap read from a reader and turns values from kCol, vCol columns into a
// mapping.
func TabsToMap(r io.Reader, sep string, kCol, vCol int) (map[string]string, error) {
	var (
		br = bufio.NewReader(r)
		m  = make(map[string]string)
	)
	for {
		line, err := br.ReadString('\n')
		if err == io.EOF {
			return m, nil
		}
		if err != nil {
			return nil, err
		}
		fields := strings.Split(line, sep)
		if len(fields) <= kCol && len(fields) <= vCol {
			k := strings.TrimSpace(fields[kCol-1])
			v := strings.TrimSpace(fields[vCol-1])
			m[k] = v
		} else {
			return nil, fmt.Errorf("invalid line: %v", line)
		}
	}
	return m, nil
}