summaryrefslogtreecommitdiff
path: root/src/mongo/gotools/src/github.com/mongodb/mongo-tools/legacy/util/file.go
blob: ed7b6d758c085efc28604f2abdb9d91b2dc50181 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright (C) MongoDB, Inc. 2014-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

package util

import (
	"bufio"
	"io"
	"net/url"
	"os"
	"path/filepath"
)

// GetFieldsFromFile fetches the first line from the contents of the file
// at "path"
func GetFieldsFromFile(path string) ([]string, error) {
	fieldFileReader, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer fieldFileReader.Close()

	var fields []string
	fieldScanner := bufio.NewScanner(fieldFileReader)
	for fieldScanner.Scan() {
		fields = append(fields, fieldScanner.Text())
	}
	if err := fieldScanner.Err(); err != nil {
		return nil, err
	}
	return fields, nil
}

// ToUniversalPath returns the result of replacing each slash ('/') character
// in "path" with an OS-specific separator character. Multiple slashes are
// replaced by multiple separators
func ToUniversalPath(path string) string {
	return filepath.FromSlash(path)
}

func EscapeCollectionName(collName string) string {
	return url.PathEscape(collName)
}

func UnescapeCollectionName(escapedCollName string) (string, error) {
	return url.PathUnescape(escapedCollName)
}

type WrappedReadCloser struct {
	io.ReadCloser
	Inner io.ReadCloser
}

func (wrc *WrappedReadCloser) Close() error {
	outerErr := wrc.ReadCloser.Close()
	innerErr := wrc.Inner.Close()
	if outerErr != nil {
		return outerErr
	}
	return innerErr
}

type WrappedWriteCloser struct {
	io.WriteCloser
	Inner io.WriteCloser
}

func (wwc *WrappedWriteCloser) Close() error {
	outerErr := wwc.WriteCloser.Close()
	innerErr := wwc.Inner.Close()
	if outerErr != nil {
		return outerErr
	}
	return innerErr
}