Documentation
¶
Index ¶
- Variables
- func AESGCMDecrypt(key, ciphertext []byte) ([]byte, error)
- func AESGCMEncrypt(key, plaintext []byte) ([]byte, error)
- func ApplyUmask(f string, newMode os.FileMode) error
- func CallerFuncName(skip int) string
- func ContrastColor(backgroundColor string) string
- func CopyFile(src, dest string) error
- func CreatePublicKeyFingerprint(key crypto.PublicKey) ([]byte, error)
- func CryptoRandomBytes(length int64) ([]byte, error)
- func CryptoRandomInt(limit int64) (int64, error)
- func CryptoRandomString(length int64) (string, error)
- func Debounce(d time.Duration) func(f func())
- func EllipsisDisplayString(str string, limit int) string
- func EllipsisDisplayStringX(str string, limit int) (left, right string)
- func ErrorWrap(unwrap error, message string, args ...any) error
- func ErrorWrapLocale(err error, trKey string, trArgs ...any) error
- func FilePathJoinAbs(base string, sub ...string) string
- func FileURLToPath(u *url.URL) (string, error)
- func GenerateKeyPair(bits int) (string, string, error)
- func GetRelativeLuminance(color string) float64
- func HexToRBGColor(colorString string) (float64, float64, float64)
- func HomeDir() (home string, err error)
- func IfEmpty[T any](v, def []T) []T
- func IfZero[T comparable](v, def T) T
- func Iif[T any](condition bool, trueVal, falseVal T) T
- func IsCommonHiddenFileName(name string) bool
- func IsDir(dir string) (bool, error)
- func IsEmptyReader(r io.Reader) (err error)
- func IsEmptyString(s string) bool
- func IsExist(path string) (bool, error)
- func IsFile(filePath string) (bool, error)
- func IsLikelyEllipsisLeftPart(s string) bool
- func IsReadmeFileExtension(name string, ext ...string) (int, bool)
- func IsReadmeFileName(name string) bool
- func KeysOfMap[K comparable, V any](m map[K]V) []K
- func ListDirRecursively(rootDir string, opts *ListDirOptions) (res []string, err error)
- func NewAlreadyExistErrorf(message string, args ...any) error
- func NewInvalidArgumentErrorf(message string, args ...any) error
- func NewNotExistErrorf(message string, args ...any) error
- func NewPermissionDeniedErrorf(message string, args ...any) error
- func NormalizeEOL(input []byte) []byte
- func OptionalArg[T any](optArg []T, defaultValue ...T) (ret T)
- func PackData(data ...any) ([]byte, error)
- func PaginateSlice(list any, page, pageSize int) any
- func PathEscapeSegments(path string) string
- func PathJoinRel(elem ...string) string
- func PathJoinRelX(elem ...string) string
- func ReadAtMost(r io.Reader, buf []byte) (n int, err error)
- func ReadWithLimit(r io.Reader, n int) (buf []byte, err error)
- func Remove(name string) error
- func RemoveAll(name string) error
- func Rename(oldpath, newpath string) error
- func ReserveLineBreakForTextarea(input string) string
- func SanitizeCredentialURLs(s string) string
- func SanitizeErrorCredentialURLs(err error) error
- func SanitizeURL(s string) (string, error)
- func SecToHours(durationVal any) string
- func ShellEscape(toEscape string) string
- func SliceContainsString(slice []string, target string, insensitive ...bool) bool
- func SliceNilAsEmpty[T any](a []T) []T
- func SliceRemoveAll[T comparable](slice []T, target T) []T
- func SliceSortedEqual[T comparable](s1, s2 []T) bool
- func Sorted[S ~[]E, E cmp.Ordered](values S) S
- func SplitTrimSpace(input, sep string) []string
- func TimeEstimateParse(timeStr string) (int64, error)
- func TimeEstimateString(amount int64) string
- func ToFloat64(number any) (float64, error)
- func ToInt64(number any) (int64, error)
- func ToPointer[T any](val T) *T
- func ToSnakeCase(input string) string
- func ToTitleCase(s string) string
- func ToTitleCaseNoLower(s string) string
- func ToUpperASCII(s string) string
- func TruncateRunes(str string, limit int) string
- func URLJoin(base string, elems ...string) string
- func UnpackData(buf []byte, data ...any) error
- func UnsafeBytesToString(b []byte) string
- func UnsafeStringToBytes(s string) []byte
- func UseLightText(backgroundColor string) bool
- func ValuesOfMap[K comparable, V any](m map[K]V) []V
- type CountingReader
- type ListDirOptions
- type LocaleWrapper
- type NopCloser
Constants ¶
This section is empty.
Variables ¶
var ( ErrInvalidArgument = errors.New("invalid argument") // also implies HTTP 400 ErrPermissionDenied = errors.New("permission denied") // also implies HTTP 403 ErrNotExist = errors.New("resource does not exist") // also implies HTTP 404 ErrAlreadyExist = errors.New("resource already exists") // also implies HTTP 409 // ErrUnprocessableContent implies HTTP 422, syntax of the request content was correct, // but server was unable to process the contained instructions ErrUnprocessableContent = errors.New("unprocessable content") )
Common Errors forming the base of our error system
Many Errors returned by Gitea can be tested against these errors using "errors.Is".
var ErrNotEmpty = errors.New("not-empty")
ErrNotEmpty is an error reported when there is a non-empty reader
Functions ¶
func AESGCMDecrypt ¶ added in v1.17.0
AESGCMDecrypt (from legacy package): decrypts ciphertext with the given key using AES in GCM mode. should be replaced.
func AESGCMEncrypt ¶ added in v1.17.0
AESGCMEncrypt (from legacy package): encrypts plaintext with the given key using AES in GCM mode. should be replaced.
func CallerFuncName ¶
func ContrastColor ¶ added in v1.22.0
ContrastColor returns a black or white foreground color that the highest contrast ratio. In the future, the APCA contrast function, or CSS `contrast-color` will be better. https://github.com/color-js/color.js/blob/eb7b53f7a13bb716ec8b28c7a56f052cd599acd9/src/contrast/APCA.js#L42
func CreatePublicKeyFingerprint ¶ added in v1.20.0
CreatePublicKeyFingerprint creates a fingerprint of the given key. The fingerprint is the sha256 sum of the PKIX structure of the key.
func CryptoRandomBytes ¶ added in v1.17.0
CryptoRandomBytes generates `length` crypto bytes This differs from CryptoRandomString, as each byte in CryptoRandomString is generated by [0,61] range This function generates totally random bytes, each byte is generated by [0,255] range
func CryptoRandomInt ¶ added in v1.17.0
CryptoRandomInt returns a crypto random integer between 0 and limit, inclusive
func CryptoRandomString ¶ added in v1.17.0
CryptoRandomString generates a crypto random alphanumerical string, each byte is generated by [0,61] range
func EllipsisDisplayString ¶
EllipsisDisplayString returns a truncated short string for display purpose. The length is the approximate number of ASCII-width in the string (CJK/emoji are 2-ASCII width) It appends "…" or "..." at the end of truncated string. It guarantees the length of the returned runes doesn't exceed the limit.
func EllipsisDisplayStringX ¶
EllipsisDisplayStringX works like EllipsisDisplayString while it also returns the right part
func ErrorWrap ¶
ErrorWrap returns an error that formats as the given text but unwraps as the provided error
func ErrorWrapLocale ¶
ErrorWrapLocale wraps an err with a translation key and arguments
func FilePathJoinAbs ¶ added in v1.19.1
FilePathJoinAbs joins the path elements into a single file path, each element is cleaned by filepath.Clean separately. All slashes/backslashes are converted to path separators before cleaning, the result only contains path separators. The first element must be an absolute path, caller should prepare the base path. It's caller's duty to make every element not bypass its own directly level, to avoid security issues. Like PathJoinRel, any redundant part (empty, relative dots, slashes) is removed.
{`/foo`, ``, `bar`} => `/foo/bar` {`/foo`, `..`, `bar`} => `/foo/bar`
func FileURLToPath ¶ added in v1.15.0
FileURLToPath extracts the path information from a file://... url. It returns an error only if the URL is not a file URL.
func GenerateKeyPair ¶ added in v1.19.0
GenerateKeyPair generates a public and private keypair
func GetRelativeLuminance ¶ added in v1.22.0
GetRelativeLuminance returns relative luminance for a SRGB color - https://en.wikipedia.org/wiki/Relative_luminance Keep this in sync with web_src/js/utils/color.js
func HexToRBGColor ¶ added in v1.20.0
HexToRBGColor parses color as RGB values in 0..255 range from the hex color string (with or without #)
func HomeDir ¶ added in v1.17.0
HomeDir returns path of '~'(in Linux) on Windows, it returns error when the variable does not exist.
func IfZero ¶ added in v1.22.0
func IfZero[T comparable](v, def T) T
IfZero returns "def" if "v" is a zero value, otherwise "v"
func Iif ¶ added in v1.22.0
Iif is an "inline-if", it returns "trueVal" if "condition" is true, otherwise "falseVal"
func IsCommonHiddenFileName ¶
IsCommonHiddenFileName will check a provided name to see if it represents file or directory that should not be watched
func IsDir ¶ added in v1.14.0
IsDir returns true if given path is a directory, or returns false when it's a file or does not exist.
func IsEmptyReader ¶ added in v1.18.4
IsEmptyReader reads a reader and ensures it is empty
func IsEmptyString ¶ added in v1.7.0
IsEmptyString checks if the provided string is empty
func IsExist ¶ added in v1.14.0
IsExist checks whether a file or directory exists. It returns false when the file or directory does not exist.
func IsFile ¶ added in v1.14.0
IsFile returns true if given path is a file, or returns false when it's a directory or does not exist.
func IsReadmeFileExtension ¶ added in v1.19.0
IsReadmeFileExtension reports whether name looks like a README file based on its name. It will look through the provided extensions and check if the file matches one of the extensions and provide the index in the extension list. If the filename is `readme.` with an unmatched extension it will match with the index equaling the length of the provided extension list. Note that the '.' should be provided in ext, e.g ".md"
func IsReadmeFileName ¶ added in v1.19.0
IsReadmeFileName reports whether name looks like a README file based on its name.
func KeysOfMap ¶ added in v1.21.9
func KeysOfMap[K comparable, V any](m map[K]V) []K
TODO: Replace with "maps.Keys" once available, current it only in golang.org/x/exp/maps but not in standard library
func ListDirRecursively ¶
func ListDirRecursively(rootDir string, opts *ListDirOptions) (res []string, err error)
ListDirRecursively gathers information of given directory by depth-first. The paths are always in "dir/slash/file" format (not "\\" even in Windows) Slice does not include given path itself.
func NewAlreadyExistErrorf ¶ added in v1.19.0
NewAlreadyExistErrorf returns an error that formats as the given text but unwraps as an ErrAlreadyExist
func NewInvalidArgumentErrorf ¶ added in v1.19.0
NewInvalidArgumentErrorf returns an error that formats as the given text but unwraps as an ErrInvalidArgument
func NewNotExistErrorf ¶ added in v1.19.0
NewNotExistErrorf returns an error that formats as the given text but unwraps as an ErrNotExist
func NewPermissionDeniedErrorf ¶ added in v1.19.0
NewPermissionDeniedErrorf returns an error that formats as the given text but unwraps as an ErrPermissionDenied
func NormalizeEOL ¶ added in v1.11.0
NormalizeEOL will convert Windows (CRLF) and Mac (CR) EOLs to UNIX (LF)
func OptionalArg ¶ added in v1.23.0
func OptionalArg[T any](optArg []T, defaultValue ...T) (ret T)
OptionalArg helps the "optional argument" in Golang:
func foo(optArg ...int) { return OptionalArg(optArg) } calling `foo()` gets zero value 0, calling `foo(100)` gets 100 func bar(optArg ...int) { return OptionalArg(optArg, 42) } calling `bar()` gets default value 42, calling `bar(100)` gets 100
Passing more than 1 item to `optArg` or `defaultValue` is undefined behavior. At the moment only the first item is used.
func PaginateSlice ¶ added in v1.14.0
PaginateSlice cut a slice as per pagination options if page = 0 it do not paginate
func PathEscapeSegments ¶ added in v1.8.0
PathEscapeSegments escapes segments of a path while not escaping forward slash
func PathJoinRel ¶ added in v1.19.1
PathJoinRel joins the path elements into a single path, each element is cleaned by path.Clean separately. It only returns the following values (like path.Join), any redundant part (empty, relative dots, slashes) is removed. It's caller's duty to make every element not bypass its own directly level, to avoid security issues.
empty => `` `` => `` `..` => `.` `dir` => `dir` `/dir/` => `dir` `foo\..\bar` => `foo\..\bar` {`foo`, ``, `bar`} => `foo/bar` {`foo`, `..`, `bar`} => `foo/bar`
func PathJoinRelX ¶ added in v1.19.1
PathJoinRelX joins the path elements into a single path like PathJoinRel, and covert all backslashes to slashes. (X means "extended", also means the combination of `\` and `/`). It's caller's duty to make every element not bypass its own directly level, to avoid security issues. It returns similar results as PathJoinRel except:
`foo\..\bar` => `bar` (because it's processed as `foo/../bar`)
All backslashes are handled as slashes, the result only contains slashes.
func ReadAtMost ¶ added in v1.15.6
ReadAtMost reads at most len(buf) bytes from r into buf. It returns the number of bytes copied. n is only less than len(buf) if r provides fewer bytes. If EOF or ErrUnexpectedEOF occurs while reading, err will be nil.
func ReadWithLimit ¶ added in v1.20.0
ReadWithLimit reads at most "limit" bytes from r into buf. If EOF or ErrUnexpectedEOF occurs while reading, err will be nil.
func Remove ¶ added in v1.13.0
Remove removes the named file or (empty) directory with at most 5 attempts.
func RemoveAll ¶ added in v1.2.0
RemoveAll removes the named file or (empty) directory with at most 5 attempts.
func ReserveLineBreakForTextarea ¶ added in v1.22.0
func SanitizeCredentialURLs ¶ added in v1.17.0
SanitizeCredentialURLs remove all credentials in URLs (starting with "scheme://") for the input string: "https://user:[email protected]" => "https://[email protected]"
func SanitizeErrorCredentialURLs ¶ added in v1.17.0
SanitizeErrorCredentialURLs wraps the error and make sure the returned error message doesn't contain sensitive credentials in URLs
func SanitizeURL ¶ added in v1.21.0
func SecToHours ¶ added in v1.23.2
SecToHours converts an amount of seconds to a human-readable hours string. This is stable for planning and managing timesheets. Here it only supports hours and minutes, because a work day could contain 6 or 7 or 8 hours. If the duration is less than 1 minute, it will be shown as seconds.
func ShellEscape ¶ added in v1.13.0
ShellEscape will escape the provided string. We can't just use go-shellquote here because our preferences for escaping differ from those in that we want:
* If the string doesn't require any escaping just leave it as it is. * If the string requires any escaping prefer double quote escaping * If we have ! or newlines then we need to use single quote escaping
func SliceContainsString ¶ added in v1.19.0
SliceContainsString sequential searches if string exists in slice.
func SliceNilAsEmpty ¶ added in v1.23.4
func SliceNilAsEmpty[T any](a []T) []T
func SliceRemoveAll ¶ added in v1.19.0
func SliceRemoveAll[T comparable](slice []T, target T) []T
SliceRemoveAll removes all the target elements from the slice.
func SliceSortedEqual ¶ added in v1.19.0
func SliceSortedEqual[T comparable](s1, s2 []T) bool
SliceSortedEqual returns true if the two slices will be equal when they get sorted. It doesn't require that the slices have been sorted, and it doesn't sort them either.
func Sorted ¶ added in v1.22.0
Sorted returns the sorted slice Note: The parameter is sorted inline.
func SplitTrimSpace ¶ added in v1.20.0
SplitTrimSpace splits the string at given separator and trims leading and trailing space
func TimeEstimateParse ¶ added in v1.23.0
func TimeEstimateString ¶ added in v1.23.0
func ToPointer ¶ added in v1.21.0
func ToPointer[T any](val T) *T
ToPointer returns the pointer of a copy of any given value
func ToSnakeCase ¶ added in v1.17.0
ToSnakeCase convert the input string to snake_case format.
Some samples.
"FirstName" => "first_name" "HTTPServer" => "http_server" "NoHTTPS" => "no_https" "GO_PATH" => "go_path" "GO PATH" => "go_path" // space is converted to underscore. "GO-PATH" => "go_path" // hyphen is converted to underscore.
func ToTitleCase ¶ added in v1.17.0
ToTitleCase returns s with all english words capitalized
func ToTitleCaseNoLower ¶ added in v1.17.4
ToTitleCaseNoLower returns s with all english words capitalized without lower-casing
func ToUpperASCII ¶ added in v1.17.0
ToUpperASCII returns s with all ASCII letters mapped to their upper case.
func TruncateRunes ¶
TruncateRunes returns a truncated string with given rune limit, it returns input string if its rune length doesn't exceed the limit.
func URLJoin ¶ added in v1.4.3
URLJoin joins url components, like path.Join, but preserving contents
func UnpackData ¶ added in v1.19.0
UnpackData uses gob to decode the given data in sequence
func UnsafeBytesToString ¶ added in v1.21.3
UnsafeBytesToString uses Go's unsafe package to convert a byte slice to a string.
func UnsafeStringToBytes ¶ added in v1.21.3
UnsafeStringToBytes uses Go's unsafe package to convert a string to a byte slice.
func UseLightText ¶ added in v1.22.0
func ValuesOfMap ¶ added in v1.22.0
func ValuesOfMap[K comparable, V any](m map[K]V) []V
TODO: Replace with "maps.Values" once available, current it only in golang.org/x/exp/maps but not in standard library
Types ¶
type CountingReader ¶ added in v1.23.0
func NewCountingReader ¶ added in v1.23.0
func NewCountingReader(rd io.Reader) *CountingReader
func (*CountingReader) Count ¶ added in v1.23.0
func (w *CountingReader) Count() int
type ListDirOptions ¶
type LocaleWrapper ¶
func ErrorAsLocale ¶
func ErrorAsLocale(err error) *LocaleWrapper
func (LocaleWrapper) Unwrap ¶
func (w LocaleWrapper) Unwrap() error
Unwrap returns the underlying error