linsk/utils/validations.go

65 lines
1.7 KiB
Go
Raw Permalink Normal View History

2023-09-02 20:03:44 +01:00
// Linsk - A utility to access Linux-native file systems on non-Linux operating systems.
// Copyright (c) 2023 The Linsk Authors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
2023-08-25 15:12:19 +01:00
package utils
import (
"encoding/binary"
2023-08-25 16:54:58 +01:00
"regexp"
2023-08-25 15:12:19 +01:00
"strings"
"unicode"
2023-08-27 15:30:51 +01:00
"github.com/acarl005/stripansi"
2023-08-25 15:12:19 +01:00
)
2023-08-27 15:30:51 +01:00
func ClearUnprintableChars(s string, allowNewlines bool) string {
// This will remove ANSI color codes.
s = stripansi.Strip(s)
2023-08-25 15:12:19 +01:00
return strings.Map(func(r rune) rune {
2023-08-27 15:30:51 +01:00
if unicode.IsPrint(r) || (allowNewlines && r == '\n') {
2023-08-25 15:12:19 +01:00
return r
}
return -1
}, s)
}
2023-08-25 16:54:58 +01:00
2023-09-27 15:37:28 +01:00
var fsTypeRegex = regexp.MustCompile(`^[a-z0-9]+$`)
func ValidateFsType(s string) bool {
return fsTypeRegex.MatchString(s)
}
2023-08-29 14:24:18 +01:00
var devNameRegexp = regexp.MustCompile(`^[0-9a-z_-]+$`)
2023-08-25 16:54:58 +01:00
func ValidateDevName(s string) bool {
// Allow mapped devices.
s = strings.TrimPrefix(s, "mapper/")
return devNameRegexp.MatchString(s)
}
2023-08-29 14:24:18 +01:00
var unixUsernameRegexp = regexp.MustCompile(`^[a-z_]([a-z0-9_-]{0,31}|[a-z0-9_-]{0,30}\$)$`)
func ValidateUnixUsername(s string) bool {
return unixUsernameRegexp.MatchString(s)
}
func Uint16ToBytesBE(v uint16) []byte {
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, v)
return b
}