aboutsummaryrefslogtreecommitdiff
path: root/internal/confyg/rule.go
blob: 6384935b38028b37425c39b9d5e4bd5f33d87791 (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
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package confyg

import (
	"bytes"
	"errors"
	"fmt"
	"strconv"
	"strings"
)

func Parse(file string, data []byte, r Reader, al Allower) (*FileSyntax, error) {
	fs, err := parse(file, data)
	if err != nil {
		return nil, err
	}

	var errs bytes.Buffer
	for _, x := range fs.Stmt {
		switch x := x.(type) {
		case *Line:
			ok := al.Allow(x.Token[0], false)
			if ok {
				r.Read(&errs, fs, x, x.Token[0], x.Token[1:])
				continue
			}

			fmt.Fprintf(&errs, "%s:%d: can't allow line verb %s", file, x.Start.Line, x.Token[0])

		case *LineBlock:
			if len(x.Token) > 1 {
				fmt.Fprintf(&errs, "%s:%d: unknown block type: %s\n", file, x.Start.Line, strings.Join(x.Token, " "))
				continue
			}
			ok := al.Allow(x.Token[0], true)
			if ok {
				for _, l := range x.Line {
					r.Read(&errs, fs, l, x.Token[0], l.Token)
				}
				continue
			}

			fmt.Fprintf(&errs, "%s:%d: can't allow line block verb %s", file, x.Start.Line, x.Token[0])
		}
	}

	if errs.Len() > 0 {
		return nil, errors.New(strings.TrimRight(errs.String(), "\n"))
	}
	return fs, nil
}

func isDirectoryPath(ns string) bool {
	// Because go.mod files can move from one system to another,
	// we check all known path syntaxes, both Unix and Windows.
	return strings.HasPrefix(ns, "./") || strings.HasPrefix(ns, "../") || strings.HasPrefix(ns, "/") ||
		strings.HasPrefix(ns, `.\`) || strings.HasPrefix(ns, `..\`) || strings.HasPrefix(ns, `\`) ||
		len(ns) >= 2 && ('A' <= ns[0] && ns[0] <= 'Z' || 'a' <= ns[0] && ns[0] <= 'z') && ns[1] == ':'
}

func isString(s string) bool {
	return s != "" && s[0] == '"'
}

func parseString(s *string) (string, error) {
	t, err := strconv.Unquote(*s)
	if err != nil {
		return "", err
	}
	*s = strconv.Quote(t)
	return t, nil
}