Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
lima-vm
GitHub Repository: lima-vm/lima
Path: blob/master/pkg/identifiers/validate.go
2610 views
1
// SPDX-FileCopyrightText: Copyright The Lima Authors
2
// SPDX-License-Identifier: Apache-2.0
3
4
// From https://github.com/containerd/containerd/blob/v2.1.1/pkg/identifiers/validate.go
5
// SPDX-FileCopyrightText: Copyright The containerd Authors
6
// LICENSE: https://github.com/containerd/containerd/blob/v2.1.1/LICENSE
7
// NOTICE: https://github.com/containerd/containerd/blob/v2.1.1/NOTICE
8
9
/*
10
Copyright The containerd Authors.
11
12
Licensed under the Apache License, Version 2.0 (the "License");
13
you may not use this file except in compliance with the License.
14
You may obtain a copy of the License at
15
16
http://www.apache.org/licenses/LICENSE-2.0
17
18
Unless required by applicable law or agreed to in writing, software
19
distributed under the License is distributed on an "AS IS" BASIS,
20
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
See the License for the specific language governing permissions and
22
limitations under the License.
23
*/
24
25
// Package identifiers provides common validation for identifiers and keys
26
// across Lima (originally from containerd).
27
//
28
// Identifiers in Lima must be a alphanumeric, allowing limited
29
// underscores, dashes and dots.
30
//
31
// While the character set may be expanded in the future, identifiers
32
// are guaranteed to be safely used as filesystem path components.
33
package identifiers
34
35
import (
36
"errors"
37
"fmt"
38
"regexp"
39
)
40
41
const (
42
maxLength = 76
43
alphanum = `[A-Za-z0-9]+`
44
separators = `[._-]`
45
)
46
47
// identifierRe defines the pattern for valid identifiers.
48
var identifierRe = regexp.MustCompile(reAnchor(alphanum + reGroup(separators+reGroup(alphanum)) + "*"))
49
50
// Validate returns nil if the string s is a valid identifier.
51
//
52
// Identifiers are similar to the domain name rules according to RFC 1035, section 2.3.1. However
53
// rules in this package are relaxed to allow numerals to follow period (".") and mixed case is
54
// allowed.
55
//
56
// In general identifiers that pass this validation should be safe for use as filesystem path components.
57
func Validate(s string) error {
58
if s == "" {
59
return errors.New("identifier must not be empty")
60
}
61
62
if len(s) > maxLength {
63
return fmt.Errorf("identifier %q greater than maximum length (%d characters)", s, maxLength)
64
}
65
66
if !identifierRe.MatchString(s) {
67
return fmt.Errorf("identifier %q must match %v", s, identifierRe)
68
}
69
return nil
70
}
71
72
func reGroup(s string) string {
73
return `(?:` + s + `)`
74
}
75
76
func reAnchor(s string) string {
77
return `^` + s + `$`
78
}
79
80