-
Notifications
You must be signed in to change notification settings - Fork 264
/
internal.go
86 lines (78 loc) · 2.47 KB
/
internal.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright 2020-2023 Buf Technologies, Inc.
//
// 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
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package internal
import (
"fmt"
"sort"
"github.com/bufbuild/buf/private/pkg/normalpath"
)
// NormalizeAndCheckPaths verifies that:
//
// - No paths are empty.
// - All paths are normalized and validated if pathType is Relative.
// - All paths are normalized if pathType is Absolute.
//
// If sortAndCheckDuplicates is true:
// - All paths are unique.
// - No path contains another path.
//
// Normalizes the paths.
// Sorts the paths if sortAndCheckDuplicates is true.
// Makes the paths absolute if pathType is Absolute.
func NormalizeAndCheckPaths(
paths []string,
name string,
pathType normalpath.PathType,
sortAndCheckDuplicates bool,
) ([]string, error) {
if len(paths) == 0 {
return paths, nil
}
outputs := make([]string, len(paths))
for i, path := range paths {
if path == "" {
return nil, fmt.Errorf("%s contained an empty path", name)
}
output, err := normalpath.NormalizeAndTransformForPathType(path, pathType)
if err != nil {
// user error
return nil, err
}
outputs[i] = output
}
if sortAndCheckDuplicates {
return sortAndCheckDuplicatePaths(outputs, name, pathType)
}
return outputs, nil
}
// TODO: refactor this
func sortAndCheckDuplicatePaths(outputs []string, name string, pathType normalpath.PathType) ([]string, error) {
sort.Strings(outputs)
for i := 0; i < len(outputs); i++ {
for j := i + 1; j < len(outputs); j++ {
output1 := outputs[i]
output2 := outputs[j]
if output1 == output2 {
return nil, fmt.Errorf("duplicate %s %q", name, output1)
}
if normalpath.EqualsOrContainsPath(output2, output1, pathType) {
return nil, fmt.Errorf("%s %q is within %s %q which is not allowed", name, output1, name, output2)
}
if normalpath.EqualsOrContainsPath(output1, output2, pathType) {
return nil, fmt.Errorf("%s %q is within %s %q which is not allowed", name, output2, name, output1)
}
}
}
return outputs, nil
}