From a3026c2a4c287be3e9ea3602570462c864a56a72 Mon Sep 17 00:00:00 2001 From: Atomys Date: Thu, 5 Dec 2024 14:27:37 +0100 Subject: [PATCH] doc: replace all go template example by doc link (#97) --- docs/roadmap-to-sprout-v1.0.md | 2 +- registry/_example/_example.go | 15 +- registry/_example/functions.go | 8 + registry/backward/functions.go | 40 +-- registry/backward/helpers.go | 11 + registry/checksum/functions.go | 70 ++--- registry/checksum/helpers.go | 1 - registry/conversion/functions.go | 120 ++++---- registry/conversion/helpers.go | 1 - registry/crypto/functions.go | 60 ++-- registry/crypto/helpers.go | 91 ++++++ registry/encoding/functions.go | 121 ++++---- registry/env/functions.go | 14 +- registry/filesystem/functions.go | 100 +++---- registry/maps/functions.go | 57 ++-- registry/network/functions.go | 99 +++---- registry/numeric/functions.go | 158 +++++------ registry/numeric/helpers.go | 6 - registry/random/functions.go | 57 ++-- registry/random/helpers.go | 10 +- registry/reflect/functions.go | 121 ++++---- registry/reflect/functions_test.go | 8 +- registry/regexp/functions.go | 110 +++---- registry/semver/functions.go | 20 +- registry/slices/functions.go | 106 +++---- registry/slices/helpers.go | 53 +++- registry/std/functions.go | 92 +++--- registry/strings/functions.go | 441 ++++++++++++++--------------- registry/strings/helpers.go | 99 ++----- registry/time/functions.go | 58 ++-- registry/uniqueid/functions.go | 4 +- 31 files changed, 1110 insertions(+), 1043 deletions(-) delete mode 100644 registry/checksum/helpers.go delete mode 100644 registry/conversion/helpers.go diff --git a/docs/roadmap-to-sprout-v1.0.md b/docs/roadmap-to-sprout-v1.0.md index ca09c54..a56bab4 100644 --- a/docs/roadmap-to-sprout-v1.0.md +++ b/docs/roadmap-to-sprout-v1.0.md @@ -45,7 +45,7 @@ Aim to minimize memory allocations as much as possible to alleviate the burden o ### :white\_check\_mark: Native Error Handling - **DONE** -Follow default go template error handling mechanisms for all functions to ensure that errors are managed gracefully and efficiently. +Follow default Go template error handling mechanisms for all functions to ensure that errors are managed gracefully and efficiently. {% hint style="success" %} These features are implemented on v0.6.0, documentation can be found here: diff --git a/registry/_example/_example.go b/registry/_example/_example.go index 2017da5..582f7e5 100644 --- a/registry/_example/_example.go +++ b/registry/_example/_example.go @@ -1,3 +1,10 @@ +// This package is an example of how to create a new registry for Sprout. +// +// You can use this package as a template to create your own registry and +// replace all instances of `example` with your registry name following the +// conventions. You can see more on [Documentation] +// +// [Documentation]: https://docs.atom.codes/sprout/advanced/how-to-create-a-registry package example import ( @@ -31,11 +38,15 @@ func (or *ExampleRegistry) RegisterFunctions(funcsMap sprout.FunctionMap) error } func (or *ExampleRegistry) RegisterAliases(aliasMap sprout.FunctionAliasMap) error { - // Register your alias here if you have any or remove this method + // Register your alias here if you have any or remove this method if you don't have any + // You can see more on [Documentation] + // [Documentation]: https://docs.atom.codes/sprout/features/function-aliases return nil } func (or *ExampleRegistry) RegisterNotices(notices *[]sprout.FunctionNotice) error { - // Register your notices here if you have any or remove this method + // Register your notices here if you have any or remove this method if you don't have any + // You can see more on [Documentation] + // [Documentation]: https://docs.atom.codes/sprout/features/function-notices return nil } diff --git a/registry/_example/functions.go b/registry/_example/functions.go index 567a313..78d324a 100644 --- a/registry/_example/functions.go +++ b/registry/_example/functions.go @@ -1,6 +1,14 @@ package example // ExampleFunction is a function that does something. +// +// Parameters: +// +// Returns: +// +// For an example of this function in a Go template, refer to [Sprout Documentation: exampleFunction]. +// +// [Sprout Documentation: exampleFunction]: https://docs.atom.codes/sprout/registries/example#examplefunction func (or *ExampleRegistry) ExampleFunction() (string, error) { // Do something with helper or.helperFunction() diff --git a/registry/backward/functions.go b/registry/backward/functions.go index 57accd8..9327d69 100644 --- a/registry/backward/functions.go +++ b/registry/backward/functions.go @@ -23,9 +23,9 @@ import ( // *uint - always returns nil, indicating no value is associated with the failure. // error - the error object containing the provided message. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: sha256Sum]. // -// {{ "Operation failed" | fail }} // Output: nil, error with "Operation failed" +// [Sprout Documentation: sha256Sum]: https://docs.atom.codes/sprout/registries/backward#fail func (bcr *BackwardCompatibilityRegistry) Fail(message string) (*uint, error) { return nil, errors.New(message) } @@ -35,7 +35,7 @@ func (bcr *BackwardCompatibilityRegistry) Fail(message string) (*uint, error) { // // Parameters: // -// v string - the URL string to parse. +// value string - the URL string to parse. // // Returns: // @@ -43,12 +43,12 @@ func (bcr *BackwardCompatibilityRegistry) Fail(message string) (*uint, error) { // "hostname", "path", "query", "opaque", "fragment", and "userinfo". // error - an error object if the URL string is invalid. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: urlParse]. // -// {{ "https://example.com/path?query=1#fragment" | urlParse }} // Output: map[fragment:fragment host:example.com hostname:example.com path:path query:query scheme:https] -func (bcr *BackwardCompatibilityRegistry) UrlParse(v string) (map[string]any, error) { +// [Sprout Documentation: urlParse]: https://docs.atom.codes/sprout/registries/backward#urlparse +func (bcr *BackwardCompatibilityRegistry) UrlParse(value string) (map[string]any, error) { dict := map[string]any{} - parsedURL, err := url.Parse(v) + parsedURL, err := url.Parse(value) if err != nil { return dict, fmt.Errorf("unable to parse url: %w", err) } @@ -73,7 +73,7 @@ func (bcr *BackwardCompatibilityRegistry) UrlParse(v string) (map[string]any, er // // Parameters: // -// d map[string]any - a map containing the URL components: "scheme", "host", +// dataMap map[string]any - a map containing the URL components: "scheme", "host", // "path", "query", "opaque", "fragment", and "userinfo". // // Returns: @@ -81,19 +81,19 @@ func (bcr *BackwardCompatibilityRegistry) UrlParse(v string) (map[string]any, er // string - the constructed URL string. // error - an error object if the URL components are invalid. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: urlJoin]. // -// {{ dict scheme="https" host="example.com" path="/path" query="query=1" opaque="opaque" fragment="fragment" | urlJoin }} // Output: "https://example.com/path?query=1#fragment" -func (bcr *BackwardCompatibilityRegistry) UrlJoin(d map[string]any) (string, error) { +// [Sprout Documentation: urlJoin]: https://docs.atom.codes/sprout/registries/backward#urljoin +func (bcr *BackwardCompatibilityRegistry) UrlJoin(dataMap map[string]any) (string, error) { resURL := url.URL{ - Scheme: bcr.get(d, "scheme").(string), - Host: bcr.get(d, "host").(string), - Path: bcr.get(d, "path").(string), - RawQuery: bcr.get(d, "query").(string), - Opaque: bcr.get(d, "opaque").(string), - Fragment: bcr.get(d, "fragment").(string), + Scheme: bcr.get(dataMap, "scheme").(string), + Host: bcr.get(dataMap, "host").(string), + Path: bcr.get(dataMap, "path").(string), + RawQuery: bcr.get(dataMap, "query").(string), + Opaque: bcr.get(dataMap, "opaque").(string), + Fragment: bcr.get(dataMap, "fragment").(string), } - userinfo := bcr.get(d, "userinfo").(string) + userinfo := bcr.get(dataMap, "userinfo").(string) var user *url.Userinfo if userinfo != "" { tempURL, err := url.Parse(fmt.Sprintf("proto://%s@host", userinfo)) @@ -121,9 +121,9 @@ func (bcr *BackwardCompatibilityRegistry) UrlJoin(d map[string]any) (string, err // // Note: This function currently lacks error handling // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: getHostByName]. // -// {{ getHostByName "example.com" }} // Output: "237.84.2.178" +// [Sprout Documentation: getHostByName]: https://docs.atom.codes/sprout/registries/checksum#gethostbyname func (bcr *BackwardCompatibilityRegistry) GetHostByName(name string) (string, error) { addrs, err := net.LookupHost(name) if err != nil { diff --git a/registry/backward/helpers.go b/registry/backward/helpers.go index 7fc0969..5a1c2f4 100644 --- a/registry/backward/helpers.go +++ b/registry/backward/helpers.go @@ -1,5 +1,16 @@ package backward +// get retrieves the value associated with the specified key from the given dictionary. +// If the key exists, it returns the corresponding value; otherwise, it returns an empty string. +// +// Parameters: +// +// dict map[string]any - the dictionary to search for the key. +// key string - the key whose associated value is to be returned. +// +// Returns: +// +// any - the value associated with the specified key, or an empty string if the key does not exist. func (bcr *BackwardCompatibilityRegistry) get(dict map[string]any, key string) any { if value, ok := dict[key]; ok { return value diff --git a/registry/checksum/functions.go b/registry/checksum/functions.go index fc80472..6fc0f1b 100644 --- a/registry/checksum/functions.go +++ b/registry/checksum/functions.go @@ -10,87 +10,87 @@ import ( "hash/adler32" ) -// SHA1Sum calculates the SHA-1 hash of the input string and returns it as a +// SHA1Sum calculates the SHA-1 hash of the value string and returns it as a // hexadecimal encoded string. // // Parameters: -// - input: the string to be hashed. +// - value: the string to be hashed. // // Returns: -// - the SHA-1 hash of the input string as a hexadecimal encoded string. +// - the SHA-1 hash of the value string as a hexadecimal encoded string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: sha1Sum]. // -// {{ sha1Sum "Hello, World!" }} // Output: 0a0a9f2a6772942557ab5355d76af442f8f65e01 -func (cr *ChecksumRegistry) SHA1Sum(input string) string { - hash := sha1.Sum([]byte(input)) +// [Sprout Documentation: sha1Sum]: https://docs.atom.codes/sprout/registries/checksum#sha1sum +func (cr *ChecksumRegistry) SHA1Sum(value string) string { + hash := sha1.Sum([]byte(value)) return hex.EncodeToString(hash[:]) } -// SHA256Sum calculates the SHA-256 hash of the input string and returns it as a +// SHA256Sum calculates the SHA-256 hash of the value string and returns it as a // hexadecimal encoded string. // // Parameters: -// - input: the string to be hashed. +// - value: the string to be hashed. // // Returns: -// - the SHA-256 hash of the input string as a hexadecimal encoded string. +// - the SHA-256 hash of the value string as a hexadecimal encoded string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: sha256Sum]. // -// {{ sha256Sum "Hello, World!" }} // Output: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f -func (cr *ChecksumRegistry) SHA256Sum(input string) string { - hash := sha256.Sum256([]byte(input)) +// [Sprout Documentation: sha256Sum]: https://docs.atom.codes/sprout/registries/checksum#sha256sum +func (cr *ChecksumRegistry) SHA256Sum(value string) string { + hash := sha256.Sum256([]byte(value)) return hex.EncodeToString(hash[:]) } -// SHA512Sum calculates the SHA-512 hash of the input string and returns it as a +// SHA512Sum calculates the SHA-512 hash of the value string and returns it as a // hexadecimal encoded string. // // Parameters: -// - input: the string to be hashed. +// - value: the string to be hashed. // // Returns: -// - the SHA-512 hash of the input string as a hexadecimal encoded string. +// - the SHA-512 hash of the value string as a hexadecimal encoded string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: sha512Sum]. // -// {{ sha512Sum "Hello, World!" }} // Output: 374d794a95cdcfd8b35993185fef9ba368f160d8daf432d08ba9f1ed1e5abe6cc69291e0fa2fe0006a52570ef18c19def4e617c33ce52ef0a6e5fbe318cb0387 -func (cr *ChecksumRegistry) SHA512Sum(input string) string { - hash := sha512.Sum512([]byte(input)) +// [Sprout Documentation: sha512Sum]: https://docs.atom.codes/sprout/registries/checksum#sha512sum +func (cr *ChecksumRegistry) SHA512Sum(value string) string { + hash := sha512.Sum512([]byte(value)) return hex.EncodeToString(hash[:]) } -// Adler32Sum calculates the Adler-32 checksum of the input string and returns +// Adler32Sum calculates the Adler-32 checksum of the value string and returns // it as a hexadecimal encoded string. // // Parameters: -// - input: the string to be hashed. +// - value: the string to be hashed. // // Returns: -// - the Adler-32 checksum of the input string as a hexadecimal encoded string. +// - the Adler-32 checksum of the value string as a hexadecimal encoded string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: adler32Sum]. // -// {{ adler32Sum "Hello, World!" }} // Output: 1f9e046a -func (cr *ChecksumRegistry) Adler32Sum(input string) string { - hash := adler32.Checksum([]byte(input)) +// [Sprout Documentation: adler32Sum]: https://docs.atom.codes/sprout/registries/checksum#adler32sum +func (cr *ChecksumRegistry) Adler32Sum(value string) string { + hash := adler32.Checksum([]byte(value)) return fmt.Sprint(hash) } -// MD5Sum calculates the MD5 hash of the input string and returns it as a +// MD5Sum calculates the MD5 hash of the value string and returns it as a // hexadecimal encoded string. // // Parameters: -// - input: the string to be hashed. +// - value: the string to be hashed. // // Returns: -// - the MD5 hash of the input string as a hexadecimal encoded string. +// - the MD5 hash of the value string as a hexadecimal encoded string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: md5Sum]. // -// {{ md5Sum "Hello, World!" }} // Output: 65a8e27d8879283831b664bd8b7f0ad4 -func (cr *ChecksumRegistry) MD5Sum(input string) string { - hash := md5.Sum([]byte(input)) +// [Sprout Documentation: md5Sum]: https://docs.atom.codes/sprout/registries/checksum#md5sum +func (cr *ChecksumRegistry) MD5Sum(value string) string { + hash := md5.Sum([]byte(value)) return hex.EncodeToString(hash[:]) } diff --git a/registry/checksum/helpers.go b/registry/checksum/helpers.go deleted file mode 100644 index a47efa2..0000000 --- a/registry/checksum/helpers.go +++ /dev/null @@ -1 +0,0 @@ -package checksum diff --git a/registry/conversion/functions.go b/registry/conversion/functions.go index 17265fc..ffac425 100644 --- a/registry/conversion/functions.go +++ b/registry/conversion/functions.go @@ -12,126 +12,126 @@ import ( // // Parameters: // -// v any - the value to convert to a boolean. This can be any types reasonably be converted to true or false. +// value any - the value to convert to a boolean. This can be any types reasonably be converted to true or false. // // Returns: // // bool - the boolean representation of the value. // error - error if the value cannot be converted to a boolean. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toBool]. // -// {{ "true" | toBool }} // Output: true -func (cr *ConversionRegistry) ToBool(v any) (bool, error) { - return cast.ToBoolE(v) +// [Sprout Documentation: toBool]: https://docs.atom.codes/sprout/registries/conversion#tobool +func (cr *ConversionRegistry) ToBool(value any) (bool, error) { + return cast.ToBoolE(value) } // ToInt converts a value to an int using robust type casting. // // Parameters: // -// v any - the value to convert to an int. +// value any - the value to convert to an int. // // Returns: // // int - the integer representation of the value. // error - error if the value cannot be converted to an int. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toInt]. // -// {{ "123" | toInt }} // Output: 123 -func (cr *ConversionRegistry) ToInt(v any) (int, error) { - return cast.ToIntE(v) +// [Sprout Documentation: toInt]: https://docs.atom.codes/sprout/registries/conversion#toint +func (cr *ConversionRegistry) ToInt(value any) (int, error) { + return cast.ToIntE(value) } // ToInt64 converts a value to an int64, accommodating larger integer values. // // Parameters: // -// v any - the value to convert to an int64. +// value any - the value to convert to an int64. // // Returns: // // int64 - the int64 representation of the value. // error - error if the value cannot be converted to an int64. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toInt64]. // -// {{ "123456789012" | toInt64 }} // Output: 123456789012 -func (cr *ConversionRegistry) ToInt64(v any) (int64, error) { - return cast.ToInt64E(v) +// [Sprout Documentation: toInt64]: https://docs.atom.codes/sprout/registries/conversion#toint64 +func (cr *ConversionRegistry) ToInt64(value any) (int64, error) { + return cast.ToInt64E(value) } // ToUint converts a value to a uint. // // Parameters: // -// v any - the value to convert to uint. This value can be of any type that is numerically convertible. +// value any - the value to convert to uint. This value can be of any type that is numerically convertible. // // Returns: // // uint - the uint representation of the value. // error - error if the value cannot be converted to a uint. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toUint]. // -// {{ "123" | toUint }} // Output: 123 -func (cr *ConversionRegistry) ToUint(v any) (uint, error) { - return cast.ToUintE(v) +// [Sprout Documentation: toUint]: https://docs.atom.codes/sprout/registries/conversion#touint +func (cr *ConversionRegistry) ToUint(value any) (uint, error) { + return cast.ToUintE(value) } // ToUint64 converts a value to a uint64. // // Parameters: // -// v any - the value to convert to uint64. This value can be of any type that is numerically convertible. +// value any - the value to convert to uint64. This value can be of any type that is numerically convertible. // // Returns: // // uint64 - the uint64 representation of the value. // error - error if the value cannot be converted to a uint64. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toUint64]. // -// {{ "123456789012345" | toUint64 }} // Output: 123456789012345 -func (cr *ConversionRegistry) ToUint64(v any) (uint64, error) { - return cast.ToUint64E(v) +// [Sprout Documentation: toUint64]: https://docs.atom.codes/sprout/registries/conversion#touint64 +func (cr *ConversionRegistry) ToUint64(value any) (uint64, error) { + return cast.ToUint64E(value) } // ToFloat64 converts a value to a float64. // // Parameters: // -// v any - the value to convert to a float64. +// value any - the value to convert to a float64. // // Returns: // // float64 - the float64 representation of the value. // error - error if the value cannot be converted to a float64. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toFloat64]. // -// {{ "123.456" | toFloat64 }} // Output: 123.456 -func (cr *ConversionRegistry) ToFloat64(v any) (float64, error) { - return cast.ToFloat64E(v) +// [Sprout Documentation: toFloat64]: https://docs.atom.codes/sprout/registries/conversion#tofloat64 +func (cr *ConversionRegistry) ToFloat64(value any) (float64, error) { + return cast.ToFloat64E(value) } // ToOctal parses a string value as an octal (base 8) integer. // // Parameters: // -// v any - the string representing an octal number. +// value any - the string representing an octal number. // // Returns: // // int64 - the decimal (base 10) representation of the octal value. // error - error if the value cannot be converted to an octal number. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toOctal]. // -// {{ "123" | toOctal }} // Output: 83 (since "123" in octal is 83 in decimal) -func (cr *ConversionRegistry) ToOctal(v any) (int64, error) { - result, err := strconv.ParseInt(fmt.Sprint(v), 8, 64) +// [Sprout Documentation: toOctal]: https://docs.atom.codes/sprout/registries/conversion#tooctal +func (cr *ConversionRegistry) ToOctal(value any) (int64, error) { + result, err := strconv.ParseInt(fmt.Sprint(value), 8, 64) if err != nil { return 0, fmt.Errorf("failed to parse octal: %w", err) } @@ -142,27 +142,27 @@ func (cr *ConversionRegistry) ToOctal(v any) (int64, error) { // // Parameters: // -// v any - the value to convert to a string. +// value any - the value to convert to a string. // // Returns: // // string - the string representation of the value. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toString]. // -// {{ 123 | toString }} // Output: "123" -func (cr *ConversionRegistry) ToString(v any) string { - switch v := v.(type) { +// [Sprout Documentation: toString]: https://docs.atom.codes/sprout/registries/conversion#tostring +func (cr *ConversionRegistry) ToString(value any) string { + switch value := value.(type) { case string: - return v + return value case []byte: - return string(v) + return string(value) case error: - return v.Error() + return value.Error() case fmt.Stringer: - return v.String() + return value.String() default: - return fmt.Sprint(v) + return fmt.Sprint(value) } } @@ -171,18 +171,18 @@ func (cr *ConversionRegistry) ToString(v any) string { // Parameters: // // fmt string - the date format string. -// str string - the date string to parse. +// value string - the date string to parse. // // Returns: // // time.Time - the parsed date. // error - error if the date string does not conform to the format. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toDate]. // -// {{ "2023-05-04" | toDate "2006-01-02" }} // Output: 2023-05-04 00:00:00 +0000 UTC -func (cr *ConversionRegistry) ToDate(fmt, str string) (time.Time, error) { - return time.ParseInLocation(fmt, str, time.Local) +// [Sprout Documentation: toDate]: https://docs.atom.codes/sprout/registries/conversion#todate +func (cr *ConversionRegistry) ToDate(fmt, value string) (time.Time, error) { + return time.ParseInLocation(fmt, value, time.Local) } // ToLocalDate converts a string to a time.Time object based on a format specification @@ -191,39 +191,39 @@ func (cr *ConversionRegistry) ToDate(fmt, str string) (time.Time, error) { // Parameters: // // fmt string - the date format string. -// str string - the date string to parse. +// value string - the date string to parse. // // Returns: // // time.Time - the parsed date. // error - error if the date string does not conform to the format. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toLocalDate]. // -// {{ "2023-05-04" | toLocalDate "2006-01-02" "Europe/Paris" }} // Output: 2023-05-04 00:00:00 +0200 UTC -func (cr *ConversionRegistry) ToLocalDate(fmt, timezone, str string) (time.Time, error) { +// [Sprout Documentation: toLocalDate]: https://docs.atom.codes/sprout/registries/conversion#tolocaldate +func (cr *ConversionRegistry) ToLocalDate(fmt, timezone, value string) (time.Time, error) { location, err := time.LoadLocation(timezone) if err != nil { return time.Time{}, err } - return time.ParseInLocation(fmt, str, location) + return time.ParseInLocation(fmt, value, location) } // ToDuration converts a value to a time.Duration. // // Parameters: // -// v any - the value to convert to time.Duration. This value can be a string, int, or another compatible type. +// value any - the value to convert to time.Duration. This value can be a string, int, or another compatible type. // // Returns: // // time.Duration - the duration representation of the value. // error - error if the value cannot be converted to a duration. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toDuration]. // -// {{ (toDuration "1h30m").Seconds }} // Output: 5400 -func (cr *ConversionRegistry) ToDuration(v any) (time.Duration, error) { - return cast.ToDurationE(v) +// [Sprout Documentation: toDuration]: https://docs.atom.codes/sprout/registries/conversion#toduration +func (cr *ConversionRegistry) ToDuration(value any) (time.Duration, error) { + return cast.ToDurationE(value) } diff --git a/registry/conversion/helpers.go b/registry/conversion/helpers.go deleted file mode 100644 index 0eac6ac..0000000 --- a/registry/conversion/helpers.go +++ /dev/null @@ -1 +0,0 @@ -package conversion diff --git a/registry/crypto/functions.go b/registry/crypto/functions.go index 2eaafd9..cb3efec 100644 --- a/registry/crypto/functions.go +++ b/registry/crypto/functions.go @@ -25,16 +25,16 @@ import ( "golang.org/x/crypto/scrypt" ) -// Bcrypt generates a bcrypt hash from the given input string. +// Bcrypt generates a bcrypt hash from the given value string. // -// input - the string to be hashed. +// value - the string to be hashed. // Returns the bcrypt hash as a string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: bcrypt]. // -// {{ "Hello World" | bcrypt }} // Output: "$2a$12$C1qL8XVjIuGKzQXwC6g6tO" -func (ch *CryptoRegistry) Bcrypt(input string) (string, error) { - hash, err := bcrypt_lib.GenerateFromPassword([]byte(input), bcrypt_lib.DefaultCost) +// [Sprout Documentation: bcrypt]: https://docs.atom.codes/sprout/registries/crypto#bcrypt +func (ch *CryptoRegistry) Bcrypt(value string) (string, error) { + hash, err := bcrypt_lib.GenerateFromPassword([]byte(value), bcrypt_lib.DefaultCost) if err != nil { return "", fmt.Errorf("failed to encrypt string with bcrypt: %w", err) } @@ -48,9 +48,9 @@ func (ch *CryptoRegistry) Bcrypt(input string) (string, error) { // password - the password string for the Htpasswd hash. // Returns the generated Htpasswd hash as a string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: htpasswd]. // -// {{ htpasswd "username" "password" }} // Output: "$2a$12$C1qL8XVjIuGKzQXwC6g6tO" +// [Sprout Documentation: htpasswd]: https://docs.atom.codes/sprout/registries/crypto#htpasswd func (ch *CryptoRegistry) Htpasswd(username string, password string) (string, error) { if strings.Contains(username, ":") { return "", fmt.Errorf("invalid username: %s", username) @@ -71,9 +71,9 @@ func (ch *CryptoRegistry) Htpasswd(username string, password string) (string, er // site - the site string used in the derivation process. // Returns the derived password as a string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: derivePassword]. // -// {{ derivePassword 0 "bcrypt" "password" "user" "site" }} // Output: "$2a$12$C1qL8XVjIuGKzQXwC6g6tO" +// [Sprout Documentation: derivePassword]: https://docs.atom.codes/sprout/registries/crypto#derivepassword func (ch *CryptoRegistry) DerivePassword(counter uint32, passwordType, password, user, site string) (string, error) { templates := passwordTypeTemplates[passwordType] if templates == nil { @@ -116,9 +116,9 @@ func (ch *CryptoRegistry) DerivePassword(counter uint32, passwordType, password, // typ - the type of private key to generate (e.g., "rsa", "dsa", "ecdsa", "ed25519"). // Returns the generated private key as a string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: genPrivateKey]. // -// {{ generatePrivateKey "rsa" }} // Output: "-----BEGIN RSA PRIVATE KEY-----" +// [Sprout Documentation: genPrivateKey]: https://docs.atom.codes/sprout/registries/crypto#genprivatekey func (ch *CryptoRegistry) GeneratePrivateKey(typ string) (string, error) { var priv any var err error @@ -155,9 +155,9 @@ func (ch *CryptoRegistry) GeneratePrivateKey(typ string) (string, error) { // b64key - the base64 encoded private key. // Returns a certificate and an error. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: buildCustomCert]. // -// {{ buildCustomCertificate "b64cert" "b64key" }} // Output: {"Cert":"b64cert","Key":"b64key"} +// [Sprout Documentation: buildCustomCert]: https://docs.atom.codes/sprout/registries/crypto#buildcustomcert func (ch *CryptoRegistry) BuildCustomCertificate(b64cert string, b64key string) (Certificate, error) { crt := Certificate{} @@ -204,9 +204,9 @@ func (ch *CryptoRegistry) BuildCustomCertificate(b64cert string, b64key string) // - Certificate: the generated certificate authority // - error: an error if any occurred during the generation process // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: genCA]. // -// {{ generateCertificateAuthority "example.com" 365 }} // Output: {"Cert":"b64cert","Key":"b64key"} +// [Sprout Documentation: genCA]: https://docs.atom.codes/sprout/registries/crypto#genca func (ch *CryptoRegistry) GenerateCertificateAuthority( cn string, daysValid int, @@ -230,9 +230,9 @@ func (ch *CryptoRegistry) GenerateCertificateAuthority( // - Certificate: the generated certificate authority // - error: an error if any occurred during the generation process // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: genCAWithKey]. // -// {{ generateCertificateAuthorityWithPEMKey "example.com" 365 "privPEM" }} // Output: {"Cert":"b64cert","Key":"b64key"} +// [Sprout Documentation: genCAWithKey]: https://docs.atom.codes/sprout/registries/crypto#gencawithkey func (ch *CryptoRegistry) GenerateCertificateAuthorityWithPEMKey( cn string, daysValid int, @@ -257,9 +257,9 @@ func (ch *CryptoRegistry) GenerateCertificateAuthorityWithPEMKey( // - Certificate: the generated certificate // - error: an error if any occurred during the generation process // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: genSelfSignedCert]. // -// {{ generateSelfSignedCertificate "example.com" ["127.0.0.1"] ["localhost"] 365 }} // Output: {"Cert":"b64cert","Key":"b64key"} +// [Sprout Documentation: genSelfSignedCert]: https://docs.atom.codes/sprout/registries/crypto#genselfsignedcert func (ch *CryptoRegistry) GenerateSelfSignedCertificate( cn string, ips []any, @@ -286,9 +286,9 @@ func (ch *CryptoRegistry) GenerateSelfSignedCertificate( // - Certificate: the generated certificate // - error: an error if any occurred during the generation process // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: genSelfSignedCertWithKey]. // -// {{ generateSelfSignedCertificateWithPEMKey "example.com" ["127.0.0.1"] ["localhost"] 365 "privPEM" }} // Output: {"Cert":"b64cert","Key":"b64key"} +// [Sprout Documentation: genSelfSignedCertWithKey]: https://docs.atom.codes/sprout/registries/crypto#genselfsignedcertwithkey func (ch *CryptoRegistry) GenerateSelfSignedCertificateWithPEMKey( cn string, ips []any, @@ -316,9 +316,9 @@ func (ch *CryptoRegistry) GenerateSelfSignedCertificateWithPEMKey( // - Certificate: the generated certificate // - error: an error if any occurred during the generation process // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: genSignedCert]. // -// {{ generateSignedCertificate "example.com" ["127.0.0.1"] ["localhost"] 365 ca }} // Output: {"Cert":"b64cert","Key":"b64key"} +// [Sprout Documentation: genSignedCert]: https://docs.atom.codes/sprout/registries/crypto#gensignedcert func (ch *CryptoRegistry) GenerateSignedCertificate( cn string, ips []any, @@ -347,9 +347,9 @@ func (ch *CryptoRegistry) GenerateSignedCertificate( // - Certificate: the generated certificate // - error: an error if any occurred during the generation process // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: genSignedCertWithKey]. // -// {{ generateSignedCertificateWithPEMKey "example.com" ["127.0.0.1"] ["localhost"] 365 ca "privPEM" }} // Output: {"Cert":"b64cert","Key":"b64key"} +// [Sprout Documentation: genSignedCertWithKey]: https://docs.atom.codes/sprout/registries/crypto#gensignedcertwithkey func (ch *CryptoRegistry) GenerateSignedCertificateWithPEMKey( cn string, ips []any, @@ -375,9 +375,9 @@ func (ch *CryptoRegistry) GenerateSignedCertificateWithPEMKey( // - string: the encrypted text as a base64-encoded string // - error: an error if any occurred during the encryption process // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: encryptAES]. // -// {{ encryptAES "password" "plaintext" }} // Output: "b64encrypted" +// [Sprout Documentation: encryptAES]: https://docs.atom.codes/sprout/registries/crypto#encryptaes func (ch *CryptoRegistry) EncryptAES(password string, plaintext string) (string, error) { if plaintext == "" { return "", nil @@ -419,9 +419,9 @@ func (ch *CryptoRegistry) EncryptAES(password string, plaintext string) (string, // - string: the decrypted text // - error: an error if any occurred during the decryption process // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: decryptAES]. // -// {{ decryptAES "password" "b64encrypted" }} // Output: "plaintext" +// [Sprout Documentation: decryptAES]: https://docs.atom.codes/sprout/registries/crypto#decryptaes func (ch *CryptoRegistry) DecryptAES(password string, crypt64 string) (string, error) { if crypt64 == "" { return "", nil diff --git a/registry/crypto/helpers.go b/registry/crypto/helpers.go index 09a2482..3aed355 100644 --- a/registry/crypto/helpers.go +++ b/registry/crypto/helpers.go @@ -19,6 +19,12 @@ import ( "time" ) +// getNetIPs takes a slice of any, which should contain IP addresses as strings and +// returns a slice of [net.IP] and an error. +// +// If the input is empty or nil, it will return an empty slice of [net.IP]. +// +// It will also return an error if the input contains any non-string values. func (ch *CryptoRegistry) getNetIPs(ips []any) ([]net.IP, error) { if ips == nil { return []net.IP{}, nil @@ -41,6 +47,12 @@ func (ch *CryptoRegistry) getNetIPs(ips []any) ([]net.IP, error) { return netIPs, nil } +// getAlternateDNSStrs takes a slice of any, which should contain DNS names as +// strings and returns a slice of strings and an error. +// +// If the input is empty or nil, it will return an empty slice of strings. +// +// It will also return an error if the input contains any non-string values. func (ch *CryptoRegistry) getAlternateDNSStrs(alternateDNS []any) ([]string, error) { if alternateDNS == nil { return []string{}, nil @@ -61,6 +73,19 @@ func (ch *CryptoRegistry) getAlternateDNSStrs(alternateDNS []any) ([]string, err return alternateDNSStrs, nil } +// getBaseCertTemplate generates a base x509.Certificate template that can be +// used to create a self-signed certificate or a certificate signed by a +// certificate authority. +// +// Parameters: +// - cn: the common name for the certificate +// - ips: a list of IP addresses +// - alternateDNS: a list of alternate DNS names +// - daysValid: the number of days the certificate is valid for +// +// Returns: +// - *x509.Certificate: the generated certificate template +// - error: an error if any occurred during the generation process func (ch *CryptoRegistry) getBaseCertTemplate( cn string, ips []any, @@ -98,6 +123,19 @@ func (ch *CryptoRegistry) getBaseCertTemplate( }, nil } +// pemBlockForKey returns a PEM block for the given private key. +// +// The function handles different types of private keys, including RSA, DSA, +// and ECDSA, by marshalling them into their respective PEM formats. For keys +// that do not match these types, it attempts to marshal them using the PKCS#8 +// format. +// +// Parameters: +// - priv: the private key to be converted into a PEM block. +// +// Returns: +// - *pem.Block: the PEM block representation of the private key, or nil if +// the key type is unsupported or conversion fails. func (ch *CryptoRegistry) pemBlockForKey(priv any) *pem.Block { switch k := priv.(type) { case *rsa.PrivateKey: @@ -122,6 +160,19 @@ func (ch *CryptoRegistry) pemBlockForKey(priv any) *pem.Block { } } +// parsePrivateKeyPEM parses a PEM-encoded private key block into a crypto.PrivateKey. +// +// The function handles different types of private keys, including RSA, DSA, and ECDSA, +// by decoding them from their respective PEM formats. For keys that do not match these +// types, it returns an error. +// +// Parameters: +// - pemBlock: the PEM-encoded private key block to be parsed. +// +// Returns: +// - crypto.PrivateKey: the parsed private key, or nil if the key type is unsupported +// or parsing fails. +// - error: an error if parsing fails. func (ch *CryptoRegistry) parsePrivateKeyPEM(pemBlock string) (crypto.PrivateKey, error) { block, _ := pem.Decode([]byte(pemBlock)) if block == nil { @@ -172,6 +223,11 @@ func (ch *CryptoRegistry) parsePrivateKeyPEM(pemBlock string) (crypto.PrivateKey } } +// getPublicKey extracts the public key from a given private key. +// +// This function will return the public key associated with the given private key. +// If the private key is of a type that does not support public key extraction, +// an error will be returned instead. func (ch *CryptoRegistry) getPublicKey(priv crypto.PrivateKey) (crypto.PublicKey, error) { switch k := priv.(type) { case interface{ Public() crypto.PublicKey }: @@ -183,6 +239,16 @@ func (ch *CryptoRegistry) getPublicKey(priv crypto.PrivateKey) (crypto.PublicKey } } +// generateCertificateAuthorityWithKeyInternal generates a certificate authority using the provided common name, validity period, and private key. +// +// Parameters: +// - cn: the common name for the certificate authority +// - daysValid: the number of days the certificate authority is valid for +// - priv: the private key to use for signing the certificate authority +// +// Returns: +// - Certificate: the generated certificate authority +// - error: an error if any occurred during the generation process func (ch *CryptoRegistry) generateCertificateAuthorityWithKeyInternal( cn string, daysValid int, @@ -205,6 +271,18 @@ func (ch *CryptoRegistry) generateCertificateAuthorityWithKeyInternal( return ca, err } +// generateSelfSignedCertificateWithKeyInternal generates a self-signed certificate using a given private key. +// +// Parameters: +// - cn: the common name for the certificate +// - ips: a list of IP addresses +// - alternateDNS: a list of alternate DNS names +// - daysValid: the number of days the certificate is valid for +// - priv: the private key to use for signing the certificate +// +// Returns: +// - Certificate: the generated self-signed certificate +// - error: an error if any occurred during the generation process func (ch *CryptoRegistry) generateSelfSignedCertificateWithKeyInternal( cn string, ips []any, @@ -224,6 +302,19 @@ func (ch *CryptoRegistry) generateSelfSignedCertificateWithKeyInternal( return cert, err } +// generateSignedCertificateWithKeyInternal generates a signed certificate using a given certificate authority and private key. +// +// Parameters: +// - cn: the common name for the certificate +// - ips: a list of IP addresses +// - alternateDNS: a list of alternate DNS names +// - daysValid: the number of days the certificate is valid for +// - ca: the certificate authority to sign with +// - priv: the private key to use for signing the certificate +// +// Returns: +// - Certificate: the generated signed certificate +// - error: an error if any occurred during the generation process func (ch *CryptoRegistry) generateSignedCertificateWithKeyInternal( cn string, ips []any, diff --git a/registry/encoding/functions.go b/registry/encoding/functions.go index b131680..8406fc6 100644 --- a/registry/encoding/functions.go +++ b/registry/encoding/functions.go @@ -17,17 +17,17 @@ import ( // // Parameters: // -// str string - the string to encode. +// value string - the string to encode. // // Returns: // // string - the Base64 encoded string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: base64Encode]. // -// {{ "Hello World" | base64Encode }} // Output: "SGVsbG8gV29ybGQ=" -func (er *EncodingRegistry) Base64Encode(str string) string { - return base64.StdEncoding.EncodeToString([]byte(str)) +// [Sprout Documentation: base64Encode]: https://docs.atom.codes/sprout/registries/encoding#base64encode +func (er *EncodingRegistry) Base64Encode(value string) string { + return base64.StdEncoding.EncodeToString([]byte(value)) } // Base64Decode decodes a Base64 encoded string back to its original form. @@ -35,18 +35,18 @@ func (er *EncodingRegistry) Base64Encode(str string) string { // // Parameters: // -// str string - the Base64 encoded string to decode. +// value string - the Base64 encoded string to decode. // // Returns: // // string - the decoded string, or an error message if the decoding fails. // error - an error message if the decoding fails. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: base64Decode]. // -// {{ "SGVsbG8gV29ybGQ=" | base64Decode }} // Output: "Hello World" -func (er *EncodingRegistry) Base64Decode(str string) (string, error) { - bytes, err := base64.StdEncoding.DecodeString(str) +// [Sprout Documentation: base64Decode]: https://docs.atom.codes/sprout/registries/encoding#base64decode +func (er *EncodingRegistry) Base64Decode(value string) (string, error) { + bytes, err := base64.StdEncoding.DecodeString(value) if err != nil { return "", fmt.Errorf("base64 decode error: %w", err) } @@ -57,17 +57,17 @@ func (er *EncodingRegistry) Base64Decode(str string) (string, error) { // // Parameters: // -// str string - the string to encode. +// value string - the string to encode. // // Returns: // // string - the Base32 encoded string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: base32Encode]. // -// {{ "Hello World" | base32Encode }} // Output: "JBSWY3DPEBLW64TMMQQQ====" -func (er *EncodingRegistry) Base32Encode(str string) string { - return base32.StdEncoding.EncodeToString([]byte(str)) +// [Sprout Documentation: base32Encode]: https://docs.atom.codes/sprout/registries/encoding#base32encode +func (er *EncodingRegistry) Base32Encode(value string) string { + return base32.StdEncoding.EncodeToString([]byte(value)) } // Base32Decode decodes a Base32 encoded string back to its original form. @@ -75,18 +75,18 @@ func (er *EncodingRegistry) Base32Encode(str string) string { // // Parameters: // -// str string - the Base32 encoded string to decode. +// value string - the Base32 encoded string to decode. // // Returns: // // string - the decoded string, or an error message if the decoding fails. // error - an error message if the decoding fails. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: base32Decode]. // -// {{ "JBSWY3DPEBLW64TMMQQQ====" | base32Decode }} // Output: "Hello World" -func (er *EncodingRegistry) Base32Decode(str string) (string, error) { - bytes, err := base32.StdEncoding.DecodeString(str) +// [Sprout Documentation: base32Decode]: https://docs.atom.codes/sprout/registries/encoding#base32decode +func (er *EncodingRegistry) Base32Decode(value string) (string, error) { + bytes, err := base32.StdEncoding.DecodeString(value) if err != nil { return "", fmt.Errorf("base32 decode error: %w", err) } @@ -98,19 +98,19 @@ func (er *EncodingRegistry) Base32Decode(str string) (string, error) { // // Parameters: // -// v string - the JSON string to decode. +// value string - the JSON string to decode. // // Returns: // // any - the decoded Go data structure. // error - error encountered during decoding, if any. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: fromJson]. // -// {{ `{"name":"John", "age":30}` | fromJson }} // Output: map[name:John age:30], nil -func (er *EncodingRegistry) FromJson(v string) (any, error) { +// [Sprout Documentation: fromJson]: https://docs.atom.codes/sprout/registries/encoding#fromjson +func (er *EncodingRegistry) FromJson(value string) (any, error) { var output any - err := json.Unmarshal([]byte(v), &output) + err := json.Unmarshal([]byte(value), &output) if err != nil { return nil, fmt.Errorf("json decode error: %w", err) } @@ -122,18 +122,18 @@ func (er *EncodingRegistry) FromJson(v string) (any, error) { // // Parameters: // -// v any - the Go data structure to encode. +// value any - the Go data structure to encode. // // Returns: // // string - the JSON-encoded string. // error - error encountered during encoding, if any. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toJson]. // -// {{ {"name": "John", "age": 30} | toJson }} // Output: "{"age":30,"name":"John"}", nil -func (er *EncodingRegistry) ToJson(v any) (string, error) { - output, err := json.Marshal(v) +// [Sprout Documentation: toJson]: https://docs.atom.codes/sprout/registries/encoding#tojson +func (er *EncodingRegistry) ToJson(value any) (string, error) { + output, err := json.Marshal(value) if err != nil { return "", fmt.Errorf("json encode error: %w", err) } @@ -145,18 +145,18 @@ func (er *EncodingRegistry) ToJson(v any) (string, error) { // // Parameters: // -// v any - the Go data structure to encode. +// value any - the Go data structure to encode. // // Returns: // // string - the pretty-printed JSON string. // error - error encountered during encoding, if any. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toPrettyJson]. // -// {{ {"name": "John", "age": 30} | toPrettyJson }} // Output: "{\n \"age\": 30,\n \"name\": \"John\"\n}", nil -func (er *EncodingRegistry) ToPrettyJson(v any) (string, error) { - output, err := json.MarshalIndent(v, "", " ") +// [Sprout Documentation: toPrettyJson]: https://docs.atom.codes/sprout/registries/encoding#toprettyjson +func (er *EncodingRegistry) ToPrettyJson(value any) (string, error) { + output, err := json.MarshalIndent(value, "", " ") if err != nil { return "", fmt.Errorf("json encode error: %w", err) } @@ -168,21 +168,21 @@ func (er *EncodingRegistry) ToPrettyJson(v any) (string, error) { // // Parameters: // -// v any - the Go data structure to encode. +// value any - the Go data structure to encode. // // Returns: // // string - the raw JSON string. // error - error encountered during encoding, if any. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toRawJson]. // -// {{ {"content": "
Hello World!
"} | toRawJson }} // Output: "{\"content\":\"
Hello World!
\"}", nil -func (er *EncodingRegistry) ToRawJson(v any) (string, error) { +// [Sprout Documentation: toRawJson]: https://docs.atom.codes/sprout/registries/encoding#torawjson +func (er *EncodingRegistry) ToRawJson(value any) (string, error) { buf := new(bytes.Buffer) enc := json.NewEncoder(buf) enc.SetEscapeHTML(false) - err := enc.Encode(&v) + err := enc.Encode(&value) if err != nil { return "", fmt.Errorf("json encode error: %w", err) } @@ -193,20 +193,20 @@ func (er *EncodingRegistry) ToRawJson(v any) (string, error) { // // Parameters: // -// str string - the YAML string to deserialize. +// value string - the YAML string to deserialize. // // Returns: // // any - a map representing the YAML data. Returns nil if deserialization fails. // error - an error message if the YAML content cannot be deserialized. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: fromYaml]. // -// {{ "name: John Doe\nage: 30" | fromYaml }} // Output: map[name:John Doe age:30] -func (er *EncodingRegistry) FromYAML(str string) (any, error) { +// [Sprout Documentation: fromYaml]: https://docs.atom.codes/sprout/registries/encoding#fromyaml +func (er *EncodingRegistry) FromYAML(value string) (any, error) { m := make(map[string]any) - if err := yaml.Unmarshal([]byte(str), &m); err != nil { + if err := yaml.Unmarshal([]byte(value), &m); err != nil { return nil, fmt.Errorf("yaml decode error: %w", err) } @@ -218,19 +218,18 @@ func (er *EncodingRegistry) FromYAML(str string) (any, error) { // // Parameters: // -// v any - the data structure to serialize. +// value any - the data structure to serialize. // // Returns: // // string - the YAML string representation of the data structure. // error - error if the serialization fails. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toYaml]. // -// {{ $d := dict "name" "John Doe" "age" 30 }} -// {{ $d | toYaml }} // Output: name: John Doe\nage: 30 -func (er *EncodingRegistry) ToYAML(v any) (out string, err error) { - return er.ToIndentYAML(4, v) +// [Sprout Documentation: toYaml]: https://docs.atom.codes/sprout/registries/encoding#toyaml +func (er *EncodingRegistry) ToYAML(value any) (out string, err error) { + return er.ToIndentYAML(4, value) } // ToIndentYAML serializes a Go data structure to a YAML string and returns any error @@ -238,21 +237,19 @@ func (er *EncodingRegistry) ToYAML(v any) (out string, err error) { // // Parameters: // -// v any - the data structure to serialize. -// indent int - the indentation -// omitempty bool - omit empty fields (default: false) +// value any - the data structure to serialize. +// indent int - the indentation +// omitempty bool - omit empty fields (default: false) // // Returns: // -// string - the YAML string representation of the data structure. -// error - error if the serialization fails. +// string - the YAML string representation of the data structure. +// error - error if the serialization fails. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toIndentYaml]. // -// {{ $person := dict "name" "John Doe" "age" 30 "location" (dict "country" "US" "planet" "Earth") }} -// {{ $person | toIndentYaml 2 }} // Output: name: John Doe\nage: 30\nlocation:\n country: US\n planet: Earth - -func (er *EncodingRegistry) ToIndentYAML(indent int, v any) (out string, err error) { +// [Sprout Documentation: toIndentYaml]: https://docs.atom.codes/sprout/registries/encoding#toindentyaml +func (er *EncodingRegistry) ToIndentYAML(indent int, value any) (out string, err error) { // recover panic from yaml package defer sprout.ErrRecoverPanic(&err, "yaml encode error") @@ -260,7 +257,7 @@ func (er *EncodingRegistry) ToIndentYAML(indent int, v any) (out string, err err enc := yaml.NewEncoder(&buf) enc.SetIndent(indent) - if err = enc.Encode(&v); err != nil { + if err = enc.Encode(&value); err != nil { // code unreachable because yaml.Marshal always panic on error and never // returns an error, but we still need to handle the error for the sake of // consistency. The error message is set by ErrRecoverPanic. diff --git a/registry/env/functions.go b/registry/env/functions.go index d02ae40..513f764 100644 --- a/registry/env/functions.go +++ b/registry/env/functions.go @@ -14,9 +14,9 @@ import ( // // string - the value of the environment variable. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: env]. // -// {{ "PATH" | env }} // Output: "/usr/bin:/bin:/usr/sbin:/sbin" +// [Sprout Documentation: env]: https://docs.atom.codes/sprout/registries/env#env func (er *EnvironmentRegistry) Env(key string) string { return os.Getenv(key) } @@ -26,15 +26,15 @@ func (er *EnvironmentRegistry) Env(key string) string { // // Parameters: // -// str string - the string with environment variables to expand. +// value string - the string with environment variables to expand. // // Returns: // // string - the expanded string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: expandEnv]. // -// {{ "Path is $PATH" | expandEnv }} // Output: "Path is /usr/bin:/bin:/usr/sbin:/sbin" -func (er *EnvironmentRegistry) ExpandEnv(str string) string { - return os.ExpandEnv(str) +// [Sprout Documentation: expandEnv]: https://docs.atom.codes/sprout/registries/env#expandenv +func (er *EnvironmentRegistry) ExpandEnv(value string) string { + return os.ExpandEnv(value) } diff --git a/registry/filesystem/functions.go b/registry/filesystem/functions.go index 15ce811..52b7502 100644 --- a/registry/filesystem/functions.go +++ b/registry/filesystem/functions.go @@ -9,17 +9,17 @@ import ( // // Parameters: // -// str string - the path string. +// value string - the path string. // // Returns: // // string - the base element of the path. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: pathBase]. // -// {{ "/path/to/file.txt" | pathBase }} // Output: "file.txt" -func (fsr *FileSystemRegistry) PathBase(str string) string { - return path.Base(str) +// [Sprout Documentation: pathBase]: https://docs.atom.codes/sprout/registries/filesystem#pathbase +func (fsr *FileSystemRegistry) PathBase(value string) string { + return path.Base(value) } // PathDir returns all but the last element of the path, effectively the path's @@ -27,68 +27,68 @@ func (fsr *FileSystemRegistry) PathBase(str string) string { // // Parameters: // -// str string - the path string. +// value string - the path string. // // Returns: // // string - the directory part of the path. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: pathDir]. // -// {{ "/path/to/file.txt" | pathDir }} // Output: "/path/to" -func (fsr *FileSystemRegistry) PathDir(str string) string { - return path.Dir(str) +// [Sprout Documentation: pathDir]: https://docs.atom.codes/sprout/registries/filesystem#pathdir +func (fsr *FileSystemRegistry) PathDir(value string) string { + return path.Dir(value) } // PathExt returns the file extension of the path. // // Parameters: // -// str string - the path string. +// value string - the path string. // // Returns: // // string - the extension of the file in the path. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: pathExt]. // -// {{ "/path/to/file.txt" | pathExt }} // Output: ".txt" -func (fsr *FileSystemRegistry) PathExt(str string) string { - return path.Ext(str) +// [Sprout Documentation: pathExt]: https://docs.atom.codes/sprout/registries/filesystem#pathext +func (fsr *FileSystemRegistry) PathExt(value string) string { + return path.Ext(value) } // PathClean cleans up the path, simplifying any redundancies like double slashes. // // Parameters: // -// str string - the path string. +// value string - the path string. // // Returns: // // string - the cleaned path. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: pathClean]. // -// {{ "/path//to/file.txt" | pathClean }} // Output: "/path/to/file.txt" -func (fsr *FileSystemRegistry) PathClean(str string) string { - return path.Clean(str) +// [Sprout Documentation: pathClean]: https://docs.atom.codes/sprout/registries/filesystem#pathclean +func (fsr *FileSystemRegistry) PathClean(value string) string { + return path.Clean(value) } // PathIsAbs checks if the path is absolute. // // Parameters: // -// str string - the path string. +// value string - the path string. // // Returns: // // bool - true if the path is absolute, otherwise false. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: pathIsAbs]. // -// {{ "/path/to/file.txt" | pathIsAbs }} // Output: true -func (fsr *FileSystemRegistry) PathIsAbs(str string) bool { - return path.IsAbs(str) +// [Sprout Documentation: pathIsAbs]: https://docs.atom.codes/sprout/registries/filesystem#pathisabs +func (fsr *FileSystemRegistry) PathIsAbs(value string) bool { + return path.IsAbs(value) } // OsBase returns the last element of the path, using the OS-specific path @@ -96,17 +96,17 @@ func (fsr *FileSystemRegistry) PathIsAbs(str string) bool { // // Parameters: // -// str string - the path string. +// value string - the path string. // // Returns: // // string - the base element of the path. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: osBase]. // -// {{ "C:\\path\\to\\file.txt" | osBase }} // Output: "file.txt" -func (fsr *FileSystemRegistry) OsBase(str string) string { - return filepath.Base(str) +// [Sprout Documentation: osBase]: https://docs.atom.codes/sprout/registries/filesystem#osbase +func (fsr *FileSystemRegistry) OsBase(value string) string { + return filepath.Base(value) } // OsDir returns all but the last element of the path, using the OS-specific @@ -114,17 +114,17 @@ func (fsr *FileSystemRegistry) OsBase(str string) string { // // Parameters: // -// str string - the path string. +// value string - the path string. // // Returns: // // string - the directory part of the path. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: osDir]. // -// {{ "C:\\path\\to\\file.txt" | osDir }} // Output: "C:\\path\\to" -func (fsr *FileSystemRegistry) OsDir(str string) string { - return filepath.Dir(str) +// [Sprout Documentation: osDir]: https://docs.atom.codes/sprout/registries/filesystem#osdir +func (fsr *FileSystemRegistry) OsDir(value string) string { + return filepath.Dir(value) } // OsExt returns the file extension of the path, using the OS-specific path @@ -132,17 +132,17 @@ func (fsr *FileSystemRegistry) OsDir(str string) string { // // Parameters: // -// str string - the path string. +// value string - the path string. // // Returns: // // string - the extension of the file in the path. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: osExt]. // -// {{ "C:\\path\\to\\file.txt" | osExt }} // Output: ".txt" -func (fsr *FileSystemRegistry) OsExt(str string) string { - return filepath.Ext(str) +// [Sprout Documentation: osExt]: https://docs.atom.codes/sprout/registries/filesystem#osext +func (fsr *FileSystemRegistry) OsExt(value string) string { + return filepath.Ext(value) } // OsClean cleans up the path, using the OS-specific path separator and @@ -150,32 +150,32 @@ func (fsr *FileSystemRegistry) OsExt(str string) string { // // Parameters: // -// str string - the path string. +// value string - the path string. // // Returns: // // string - the cleaned path. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: osClean]. // -// {{ "C:\\path\\\\to\\file.txt" | osClean }} // Output: "C:\\path\\to\\file.txt" -func (fsr *FileSystemRegistry) OsClean(str string) string { - return filepath.Clean(str) +// [Sprout Documentation: osClean]: https://docs.atom.codes/sprout/registries/filesystem#osclean +func (fsr *FileSystemRegistry) OsClean(value string) string { + return filepath.Clean(value) } // OsIsAbs checks if the path is absolute, using the OS-specific path separator. // // Parameters: // -// str string - the path string. +// value string - the path string. // // Returns: // // bool - true if the path is absolute, otherwise false. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: osIsAbs]. // -// {{ "C:\\path\\to\\file.txt" | osIsAbs }} // Output: true -func (fsr *FileSystemRegistry) OsIsAbs(str string) bool { - return filepath.IsAbs(str) +// [Sprout Documentation: osIsAbs]: https://docs.atom.codes/sprout/registries/filesystem#osisabs +func (fsr *FileSystemRegistry) OsIsAbs(value string) bool { + return filepath.IsAbs(value) } diff --git a/registry/maps/functions.go b/registry/maps/functions.go index 049ed06..089cfec 100644 --- a/registry/maps/functions.go +++ b/registry/maps/functions.go @@ -20,9 +20,9 @@ import ( // // map[string]any - the created dictionary. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: dict]. // -// {{ dict "key1", "value1", "key2", "value2" }} // Output: {"key1": "value1", "key2": "value2"} +// [Sprout Documentation: dict]: https://docs.atom.codes/sprout/registries/maps#dict func (mr *MapsRegistry) Dict(values ...any) map[string]any { // Ensure even number of values for key-value pairs if len(values)%2 != 0 { @@ -52,9 +52,9 @@ func (mr *MapsRegistry) Dict(values ...any) map[string]any { // any - the value associated with the key, or an empty string if the key does not exist. // error - protect against undesired behavior due to migration to new signature. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: get]. // -// {{ {"key": "value"} | get "key" }} // Output: "value" +// [Sprout Documentation: get]: https://docs.atom.codes/sprout/registries/maps#get func (mr *MapsRegistry) Get(args ...any) (any, error) { // ! BACKWARDS COMPATIBILITY: deprecated in v1.0 and removed in v1.1 // ! Due to change in signature, this function still supports the old signature @@ -94,9 +94,9 @@ func (mr *MapsRegistry) Get(args ...any) (any, error) { // map[string]any - the updated dictionary. // error - protect against undesired behavior due to migration to new signature. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: set]. // -// {{ {"key": "oldValue"} | set "key", "newValue" }} // Output: {"key": "newValue"} +// [Sprout Documentation: set]: https://docs.atom.codes/sprout/registries/maps#set func (mr *MapsRegistry) Set(args ...any) (map[string]any, error) { // ! BACKWARDS COMPATIBILITY: deprecated in v1.0 and removed in v1.1 // ! Due to change in signature, this function still supports the old signature @@ -136,9 +136,9 @@ func (mr *MapsRegistry) Set(args ...any) (map[string]any, error) { // map[string]any - the dictionary after removing the key. // error - protect against undesired behavior due to migration to new signature. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: unset]. // -// {{ {"key": "value"} | unset "key" }} // Output: {} +// [Sprout Documentation: unset]: https://docs.atom.codes/sprout/registries/maps#unset func (mr *MapsRegistry) Unset(args ...any) (map[string]any, error) { // ! BACKWARDS COMPATIBILITY: deprecated in v1.0 and removed in v1.1 // ! Due to change in signature, this function still supports the old signature @@ -176,9 +176,9 @@ func (mr *MapsRegistry) Unset(args ...any) (map[string]any, error) { // // []string - a list of all keys from the dictionaries. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: keys]. // -// {{ keys {"key1": "value1", "key2": "value2"} }} // Output: ["key1", "key2"] +// [Sprout Documentation: keys]: https://docs.atom.codes/sprout/registries/maps#keys func (mr *MapsRegistry) Keys(dicts ...map[string]any) []string { var keyCount int for i := range dicts { @@ -206,9 +206,9 @@ func (mr *MapsRegistry) Keys(dicts ...map[string]any) []string { // // []any - a list of all values from the dictionary. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: values]. // -// {{ values {"key1": "value1", "key2": "value2"} }} // Output: ["value1", "value2"] +// [Sprout Documentation: values]: https://docs.atom.codes/sprout/registries/maps#values func (mr *MapsRegistry) Values(dicts ...map[string]any) []any { var keyCount int for i := range dicts { @@ -237,11 +237,9 @@ func (mr *MapsRegistry) Values(dicts ...map[string]any) []any { // // []any - a list of values associated with the key from each dictionary. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: pluck]. // -// {{ $d1 := dict "key" "value1"}} -// {{ $d2 := dict "key" "value2" }} -// {{ pluck "key" $d1 $d2 }} // Output: ["value1", "value2"] +// [Sprout Documentation: pluck]: https://docs.atom.codes/sprout/registries/maps#pluck func (mr *MapsRegistry) Pluck(key string, dicts ...map[string]any) []any { result := make([]any, 0, len(dicts)) @@ -266,10 +264,9 @@ func (mr *MapsRegistry) Pluck(key string, dicts ...map[string]any) []any { // map[string]any - a dictionary containing only the picked keys and their values. // error - protect against undesired behavior due to migration to new signature. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: pick]. // -// {{ $d := dict "key1" "value1" "key2" "value2" "key3" "value3" }} -// {{ $d | pick "key1" "key3" }} // Output: {"key1": "value1", "key3": "value3"} +// [Sprout Documentation: pick]: https://docs.atom.codes/sprout/registries/maps#pick func (mr *MapsRegistry) Pick(args ...any) (map[string]any, error) { // ! BACKWARDS COMPATIBILITY: deprecated in v1.0 and removed in v1.1 // ! Due to change in signature, this function still supports the old signature @@ -323,10 +320,9 @@ func (mr *MapsRegistry) Pick(args ...any) (map[string]any, error) { // map[string]any - a dictionary without the omitted keys. // error - protect against undesired behavior due to migration to new signature. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: omit]. // -// {{ $d := dict "key1" "value1" "key2" "value2" "key3" "value3" }} -// {{ omit $d "key1" "key3" }} // Output: {"key2": "value2"} +// [Sprout Documentation: omit]: https://docs.atom.codes/sprout/registries/maps#omit func (mr *MapsRegistry) Omit(args ...any) (map[string]any, error) { // ! BACKWARDS COMPATIBILITY: deprecated in v1.0 and removed in v1.1 // ! Due to change in signature, this function still supports the old signature @@ -384,10 +380,9 @@ func (mr *MapsRegistry) Omit(args ...any) (map[string]any, error) { // any - the value found at the nested key path or nil if any key in the path is not found. // error - an error if there are fewer than three arguments, if the last argument is not a dictionary, or if any key is not a string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: dig]. // -// {{ dig "user", "profile", "name", {"user": {"profile": {"name": "John Doe"}}} }} // Output: "John Doe", nil -// {{ dig "user.profile.age", {"user": {"profile": {"name": "John Doe"}}} }} // Output: nil, nil +// [Sprout Documentation: dig]: https://docs.atom.codes/sprout/registries/maps#dig func (mr *MapsRegistry) Dig(args ...any) (any, error) { if len(args) < 2 { return nil, errors.New("dig requires at least two arguments: a sequence of keys and a dictionary") @@ -418,9 +413,9 @@ func (mr *MapsRegistry) Dig(args ...any) (any, error) { // bool - true if the key exists, otherwise false. // error - protect against undesired behavior due to migration to new signature. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: hasKey]. // -// {{ {"key": "value"} | hasKey "key" }} // Output: true +// [Sprout Documentation: hasKey]: https://docs.atom.codes/sprout/registries/maps#haskey func (mr *MapsRegistry) HasKey(args ...any) (bool, error) { // ! BACKWARDS COMPATIBILITY: deprecated in v1.0 and removed in v1.1 // ! Due to change in signature, this function still supports the old signature @@ -459,9 +454,9 @@ func (mr *MapsRegistry) HasKey(args ...any) (bool, error) { // any - the merged destination map. // error - error if the merge fails. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: merge]. // -// {{ merge {}, {"a": 1, "b": 2}, {"b": 3, "c": 4} }} // Output: {"a": 1, "b": 2, "c": 4}, nil +// [Sprout Documentation: merge]: https://docs.atom.codes/sprout/registries/maps#merge func (mr *MapsRegistry) Merge(dest map[string]any, srcs ...map[string]any) (any, error) { for _, src := range srcs { if err := mergo.Merge(&dest, src, mergo.WithoutDereference); err != nil { @@ -487,9 +482,9 @@ func (mr *MapsRegistry) Merge(dest map[string]any, srcs ...map[string]any) (any, // any - the merged destination map with overwritten values where applicable. // error - error if the merge fails. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: mergeOverwrite]. // -// {{ mergeOverwrite {}, {"a": 1, "b": 2}, {"b": 3, "c": 4} }} // Output: {"a": 1, "b": 3, "c": 4}, nil +// [Sprout Documentation: mergeOverwrite]: https://docs.atom.codes/sprout/registries/maps#mergeoverwrite func (mr *MapsRegistry) MergeOverwrite(dest map[string]any, srcs ...map[string]any) (any, error) { for _, src := range srcs { if err := mergo.Merge(&dest, src, mergo.WithOverride, mergo.WithoutDereference); err != nil { diff --git a/registry/network/functions.go b/registry/network/functions.go index 5276841..06fa831 100644 --- a/registry/network/functions.go +++ b/registry/network/functions.go @@ -14,19 +14,18 @@ import ( // // Parameters: // -// str string - the string representation of the IP address. +// value string - the string representation of the IP address. // // Returns: // // net.IP - the parsed IP address in its net.IP format. // error - an error if the string cannot be parsed as a valid IP address. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: parseIP]. // -// {{ parseIP "10.42.0.1" }} // Output: net.IP{10, 42, 0, 1} -// {{ parseIP "2001:db8::" }} // Output: net.IP{32, 1, 13, 184, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} -func (nr *NetworkRegistry) ParseIP(str string) (net.IP, error) { - ip := net.ParseIP(str) +// [Sprout Documentation: parseIP]: https://docs.atom.codes/sprout/registries/network#parseip +func (nr *NetworkRegistry) ParseIP(value string) (net.IP, error) { + ip := net.ParseIP(value) if ip == nil { return nil, errors.New("invalid IP address") } @@ -41,18 +40,18 @@ func (nr *NetworkRegistry) ParseIP(str string) (net.IP, error) { // // Parameters: // -// str string - the string representation of the MAC address. +// value string - the string representation of the MAC address. // // Returns: // // net.HardwareAddr - the parsed MAC address in its net.HardwareAddr format. // error - an error if the string cannot be parsed as a valid MAC address. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: parseMAC]. // -// {{ parseMAC "01:23:45:67:89:ab" }} // Output: net.HardwareAddr{1, 35, 69, 103, 137, 171} -func (nr *NetworkRegistry) ParseMAC(str string) (net.HardwareAddr, error) { - mac, err := net.ParseMAC(str) +// [Sprout Documentation: parseMAC]: https://docs.atom.codes/sprout/registries/network#parsemac +func (nr *NetworkRegistry) ParseMAC(value string) (net.HardwareAddr, error) { + mac, err := net.ParseMAC(value) if err != nil { return nil, fmt.Errorf("cannot parse MAC address: %w", err) } @@ -68,19 +67,18 @@ func (nr *NetworkRegistry) ParseMAC(str string) (net.HardwareAddr, error) { // // Parameters: // -// str string - the string representation of the CIDR block. +// value string - the string representation of the CIDR block. // // Returns: // // *net.IPNet - the parsed IP network in its *net.IPNet format. // error - an error if the string cannot be parsed as valid CIDR notation. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: parseCIDR]. // -// {{ parseCIDR "192.168.0.0/24" }} // Output: &net.IPNet{IP: net.IP{192, 168, 0, 0}, Mask: net.CIDRMask(24, 32)} -// {{ parseCIDR "2001:db8::/32" }} // Output: &net.IPNet{IP: net.IP{32, 1, 13, 184, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Mask: net.CIDRMask(32, 128)} -func (nr *NetworkRegistry) ParseCIDR(str string) (*net.IPNet, error) { - _, cidr, err := net.ParseCIDR(str) +// [Sprout Documentation: parseCIDR]: https://docs.atom.codes/sprout/registries/network#parsecidr +func (nr *NetworkRegistry) ParseCIDR(value string) (*net.IPNet, error) { + _, cidr, err := net.ParseCIDR(value) if err != nil { return nil, fmt.Errorf("cannot parse CIDR: %w", err) } @@ -100,10 +98,9 @@ func (nr *NetworkRegistry) ParseCIDR(str string) (*net.IPNet, error) { // uint8 - the IP version, 4 for IPv4 or 16 for IPv6. // error - an error if the IP address is invalid or cannot be parsed. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: ipVersion]. // -// {{ ipVersion "192.168.0.1" }} // Output: 4 -// {{ ipVersion "2001:db8::" }} // Output: 6 +// [Sprout Documentation: ipVersion]: https://docs.atom.codes/sprout/registries/network#ipversion func (nr *NetworkRegistry) IPVersion(ipStr string) (uint8, error) { ip, err := nr.ParseIP(ipStr) if err != nil { @@ -127,10 +124,9 @@ func (nr *NetworkRegistry) IPVersion(ipStr string) (uint8, error) { // bool - true if the IP address is a loopback address. // error - an error if the IP address is invalid or cannot be parsed. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: ipisLoopback]. // -// {{ ipIsLoopback "127.0.0.1" }} // Output: true -// {{ ipIsLoopback "192.168.0.1" }} // Output: false +// [Sprout Documentation: ipisLoopback]: https://docs.atom.codes/sprout/registries/network#ipisloopback func (nr *NetworkRegistry) IPIsLoopback(ipStr string) (bool, error) { ip, err := nr.ParseIP(ipStr) if err != nil { @@ -155,10 +151,9 @@ func (nr *NetworkRegistry) IPIsLoopback(ipStr string) (bool, error) { // bool - true if the IP address is a global unicast address. // error - an error if the IP address is invalid or cannot be parsed. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: ipIsGlobalUnicast]. // -// {{ ipIsGlobalUnicast "8.8.8.8" }} // Output: true -// {{ ipIsGlobalUnicast "127.0.0.1" }} // Output: false +// [Sprout Documentation: ipIsGlobalUnicast]: https://docs.atom.codes/sprout/registries/network#ipisglobalunicast func (nr *NetworkRegistry) IPIsGlobalUnicast(ipStr string) (bool, error) { ip, err := nr.ParseIP(ipStr) if err != nil { @@ -182,10 +177,9 @@ func (nr *NetworkRegistry) IPIsGlobalUnicast(ipStr string) (bool, error) { // bool - true if the IP address is a multicast address. // error - an error if the IP address is invalid or cannot be parsed. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: ipIsMulticast]. // -// {{ ipIsMulticast "224.0.0.1" }} // Output: true -// {{ ipIsMulticast "192.168.0.1" }} // Output: false +// [Sprout Documentation: ipIsMulticast]: https://docs.atom.codes/sprout/registries/network#ipismulticast func (nr *NetworkRegistry) IPIsMulticast(ipStr string) (bool, error) { ip, err := nr.ParseIP(ipStr) if err != nil { @@ -210,10 +204,9 @@ func (nr *NetworkRegistry) IPIsMulticast(ipStr string) (bool, error) { // bool - true if the IP address is a private address. // error - an error if the IP address is invalid or cannot be parsed. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: ipIsPrivate]. // -// {{ ipIsPrivate "192.168.0.1" }} // Output: true -// {{ ipIsPrivate "8.8.8.8" }} // Output: false +// [Sprout Documentation: ipIsPrivate]: https://docs.atom.codes/sprout/registries/network#ipisprivate func (nr *NetworkRegistry) IPIsPrivate(ipStr string) (bool, error) { ip, err := nr.ParseIP(ipStr) if err != nil { @@ -239,10 +232,9 @@ func (nr *NetworkRegistry) IPIsPrivate(ipStr string) (bool, error) { // net.IP - the incremented IP address. // error - an error if the IP address overflows or if the IP version cannot be determined. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: ipIncrement]. // -// {{ parseIP "192.168.0.1" | ipIncrement }} // Output: 192.168.0.2 -// {{ parseIP "ffff::" | ipIncrement }} // Output: ffff::1 +// [Sprout Documentation: ipIncrement]: https://docs.atom.codes/sprout/registries/network#ipincrement func (nr *NetworkRegistry) IPIncrement(ip net.IP) (net.IP, error) { switch nr.determineIPVersion(ip) { case 4: @@ -284,10 +276,9 @@ func (nr *NetworkRegistry) IPIncrement(ip net.IP) (net.IP, error) { // net.IP - the decremented IP address. // error - an error if the IP address underflows or if the IP version cannot be determined. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: ipDecrement]. // -// {{ parseIP "192.168.0.2" | ipDecrement }} // Output: 192.168.0.1 -// {{ parseIP "ffff::1" | ipDecrement }} // Output: ffff:: +// [Sprout Documentation: ipDecrement]: https://docs.atom.codes/sprout/registries/network#ipdecrement func (nr *NetworkRegistry) IPDecrement(ip net.IP) (net.IP, error) { switch nr.determineIPVersion(ip) { case 4: @@ -329,10 +320,9 @@ func (nr *NetworkRegistry) IPDecrement(ip net.IP) (net.IP, error) { // bool - true if the IP address is within the CIDR block, false otherwise. // error - an error if the CIDR block or IP address cannot be parsed. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: cidrContains]. // -// {{ cidrContains "192.168.0.0/24" "192.168.0.1" }} // Output: true -// {{ cidrContains "192.168.0.0/24" "10.0.0.1" }} // Output: false +// [Sprout Documentation: cidrContains]: https://docs.atom.codes/sprout/registries/network#cidrcontains func (nr *NetworkRegistry) CIDRContains(cidrStr string, ip string) (bool, error) { parsedCIRDR, err := nr.ParseCIDR(cidrStr) if err != nil { @@ -362,10 +352,11 @@ func (nr *NetworkRegistry) CIDRContains(cidrStr string, ip string) (bool, error) // *big.Int - the total number of IP addresses in the CIDR block. // error - an error if the CIDR block cannot be parsed. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: cidrSize]. // -// {{ cidrSize "192.168.0.0/24" }} // Output: 256 // {{ cidrSize "2001:db8::/32" }} // Output: 79228162514264337593543950336 (IPv6 range) +// +// [Sprout Documentation: cidrSize]: https://docs.atom.codes/sprout/registries/network#cidrsize func (nr *NetworkRegistry) CIDRSize(cidrStr string) (*big.Int, error) { cidr, err := nr.ParseCIDR(cidrStr) if err != nil { @@ -396,10 +387,9 @@ func (nr *NetworkRegistry) CIDRSize(cidrStr string) (*big.Int, error) { // []net.IP - a slice containing all IP addresses within the CIDR block. // error - an error if the CIDR block cannot be parsed. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: cidrRangeList]. // -// {{ range cidrRangeList "10.42.1.1/32" }}{{ . }}{{ end }} // Output: 10.42.1.1 -// {{ range cidrRangeList "2001:db8::/128" }}{{ . }}{{ end }} // Output: 2001:db8:: +// [Sprout Documentation: cidrRangeList]: https://docs.atom.codes/sprout/registries/network#cidrrangelist func (nr *NetworkRegistry) CIDRRangeList(cidrStr string) ([]net.IP, error) { cidr, err := nr.ParseCIDR(cidrStr) if err != nil { @@ -446,10 +436,9 @@ func (nr *NetworkRegistry) CIDRRangeList(cidrStr string) ([]net.IP, error) { // string - the first IP address as a string. // error - an error if the CIDR block cannot be parsed. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: cidrFirst]. // -// {{ cidrFirst "10.42.0.0/24" }} // Output: 10.42.0.0 -// {{ cidrFirst "2001:db8::/32" }} // Output: 2001:db8:: +// [Sprout Documentation: cidrFirst]: https://docs.atom.codes/sprout/registries/network#cidrfirst func (nr *NetworkRegistry) CIDRFirst(cidrStr string) (string, error) { cidr, err := nr.ParseCIDR(cidrStr) if err != nil { @@ -470,10 +459,9 @@ func (nr *NetworkRegistry) CIDRFirst(cidrStr string) (string, error) { // string - the last IP address as a string. // error - an error if the CIDR block cannot be parsed. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: cidrLast]. // -// {{ cidrLast "10.42.0.0/24" }} // Output: 10.42.0.255 -// {{ cidrLast "2001:db8::/32" }} // Output: 2001:db8::ffff:ffff +// [Sprout Documentation: cidrLast]: https://docs.atom.codes/sprout/registries/network#cidrlast func (nr *NetworkRegistry) CIDRLast(cidrStr string) (string, error) { cidr, err := nr.ParseCIDR(cidrStr) if err != nil { @@ -496,12 +484,9 @@ func (nr *NetworkRegistry) CIDRLast(cidrStr string) (string, error) { // bool - true if the two CIDR blocks overlap, false otherwise. // error - an error if either of the CIDR blocks cannot be parsed. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: cidrOverlap]. // -// {{ cidrOverlap "10.42.0.0/24" "10.42.0.0/16" }} // Output: true -// {{ cidrOverlap "192.168.1.0/24" "192.168.2.0/24" }} // Output: false -// {{ cidrOverlap "2001:db8::/64" "2001:db8::/32" }} // Output: true -// {{ cidrOverlap "2001:db8::/64" "2001:db8:1::/64" }} // Output: false +// [Sprout Documentation: cidrOverlap]: https://docs.atom.codes/sprout/registries/network#cidroverlap func (nr *NetworkRegistry) CIDROverlap(cidrStrA, cidrStrB string) (bool, error) { cidrA, err := nr.ParseCIDR(cidrStrA) if err != nil { diff --git a/registry/numeric/functions.go b/registry/numeric/functions.go index b6292fa..95f6a54 100644 --- a/registry/numeric/functions.go +++ b/registry/numeric/functions.go @@ -13,20 +13,20 @@ import ( // // Parameters: // -// num any - the number to floor, expected to be numeric or convertible to float64. +// value any - the number to floor, expected to be numeric or convertible to float64. // // Returns: // // float64 - the floored value. // error - an error if the input cannot be converted to float64. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: floor]. // -// {{ 3.7 | floor }} // Output: 3 -func (nr *NumericRegistry) Floor(num any) (float64, error) { - float, err := cast.ToFloat64E(num) +// [Sprout Documentation: floor]: https://docs.atom.codes/sprout/registries/numeric#floor +func (nr *NumericRegistry) Floor(value any) (float64, error) { + float, err := cast.ToFloat64E(value) if err != nil { - return 0.0, sprout.NewErrConvertFailed("float64", num, err) + return 0.0, sprout.NewErrConvertFailed("float64", value, err) } return math.Floor(float), nil @@ -36,20 +36,20 @@ func (nr *NumericRegistry) Floor(num any) (float64, error) { // // Parameters: // -// num any - the number to ceil, expected to be numeric or convertible to float64. +// value any - the number to ceil, expected to be numeric or convertible to float64. // // Returns: // // float64 - the ceiled value. // error - an error if the input cannot be converted to float64. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: ceil]. // -// {{ 3.1 | ceil }} // Output: 4 -func (nr *NumericRegistry) Ceil(num any) (float64, error) { - float, err := cast.ToFloat64E(num) +// [Sprout Documentation: ceil]: https://docs.atom.codes/sprout/registries/numeric#ceil +func (nr *NumericRegistry) Ceil(value any) (float64, error) { + float, err := cast.ToFloat64E(value) if err != nil { - return 0.0, sprout.NewErrConvertFailed("float64", num, err) + return 0.0, sprout.NewErrConvertFailed("float64", value, err) } return math.Ceil(float), nil @@ -59,7 +59,7 @@ func (nr *NumericRegistry) Ceil(num any) (float64, error) { // // Parameters: // -// num any - the number to round. +// value any - the number to round. // poww int - the power of ten to which to round. // roundOpts ...float64 - optional threshold for rounding up (default is 0.5). // @@ -69,21 +69,20 @@ func (nr *NumericRegistry) Ceil(num any) (float64, error) { // // error - an error if the input cannot be converted to float64. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: round]. // -// {{ 3.746, 2, 0.5 | round }} // Output: 3.75 -// -// ! NEED TO CHANGE PARAMS ORDER -func (nr *NumericRegistry) Round(num any, poww int, roundOpts ...float64) (float64, error) { +// [Sprout Documentation: round]: https://docs.atom.codes/sprout/registries/numeric#round +func (nr *NumericRegistry) Round(value any, poww int, roundOpts ...float64) (float64, error) { + // ! NEED TO CHANGE PARAMS ORDER roundOn := 0.5 if len(roundOpts) > 0 { roundOn = roundOpts[0] } pow := math.Pow(10, float64(poww)) - float, err := cast.ToFloat64E(num) + float, err := cast.ToFloat64E(value) if err != nil { - return 0.0, sprout.NewErrConvertFailed("float64", num, err) + return 0.0, sprout.NewErrConvertFailed("float64", value, err) } digit := float * pow @@ -105,9 +104,9 @@ func (nr *NumericRegistry) Round(num any, poww int, roundOpts ...float64) (float // any - the sum of the values, converted to the type of the first value. // error - when a value cannot be converted. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: add]. // -// {{ 5, 3.5, 2 | add }} // Output: 10.5 +// [Sprout Documentation: add]: https://docs.atom.codes/sprout/registries/numeric#add-addf func (nr *NumericRegistry) Add(values ...any) (any, error) { return operateNumeric(values, func(a, b float64) float64 { return a + b }, 0.0) } @@ -116,19 +115,19 @@ func (nr *NumericRegistry) Add(values ...any) (any, error) { // // Parameters: // -// x any - the number to add. +// value any - the number to add. // // Returns: // // any - the sum of the value and 1, converted to the type of the input. // error - when a value cannot be converted. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: add1]. // -// {{ 5 | add1 }} // Output: 6 -func (nr *NumericRegistry) Add1(x any) (any, error) { - one := reflect.ValueOf(1).Convert(reflect.TypeOf(x)).Interface() - return nr.Add(x, one) +// [Sprout Documentation: add1]: https://docs.atom.codes/sprout/registries/numeric#add1-add1f +func (nr *NumericRegistry) Add1(value any) (any, error) { + one := reflect.ValueOf(1).Convert(reflect.TypeOf(value)).Interface() + return nr.Add(value, one) } // Sub performs subtraction on a slice of values, starting with the first value. @@ -142,9 +141,9 @@ func (nr *NumericRegistry) Add1(x any) (any, error) { // any - the result of the subtraction, converted to the type of the first value. // error - when a value cannot be converted. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: sub]. // -// {{ 10, 3, 2 | sub }} // Output: 5 +// [Sprout Documentation: sub]: https://docs.atom.codes/sprout/registries/numeric#sub-subf func (nr *NumericRegistry) Sub(values ...any) (any, error) { return operateNumeric(values, func(a, b float64) float64 { return a - b }, 0.0) } @@ -160,9 +159,9 @@ func (nr *NumericRegistry) Sub(values ...any) (any, error) { // int64 - the product of the values. // error - an error if the result cannot be converted to int64. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: mul]. // -// {{ 5, 3, 2 | mulInt }} // Output: 30 +// [Sprout Documentation: mul]: https://docs.atom.codes/sprout/registries/numeric#mul func (nr *NumericRegistry) MulInt(values ...any) (int64, error) { result, err := operateNumeric(values, func(a, b float64) float64 { return a * b }, 1) if err != nil { @@ -183,9 +182,9 @@ func (nr *NumericRegistry) MulInt(values ...any) (int64, error) { // any - the product of the values, converted to the type of the first value. // error - when a value cannot be converted. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: mulf]. // -// {{ 5.5, 2.0, 2.0 | mulf }} // Output: 22.0 +// [Sprout Documentation: mulf]: https://docs.atom.codes/sprout/registries/numeric#mulf func (nr *NumericRegistry) Mulf(values ...any) (any, error) { return operateNumeric(values, func(a, b float64) float64 { return a * b }, 1.0) } @@ -200,9 +199,9 @@ func (nr *NumericRegistry) Mulf(values ...any) (any, error) { // // int64 - the quotient of the division. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: div]. // -// {{ 30, 3, 2 | divInt }} // Output: 5 +// [Sprout Documentation: div]: https://docs.atom.codes/sprout/registries/numeric#div func (nr *NumericRegistry) DivInt(values ...any) (int64, error) { result, err := nr.Divf(values...) if err != nil { @@ -222,9 +221,9 @@ func (nr *NumericRegistry) DivInt(values ...any) (int64, error) { // // any - the quotient of the division, converted to the type of the first value. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: divf]. // -// {{ 30.0, 3.0, 2.0 | divf }} // Output: 5.0 +// [Sprout Documentation: divf]: https://docs.atom.codes/sprout/registries/numeric#divf func (nr *NumericRegistry) Divf(values ...any) (any, error) { // FIXME: Special manipulation to force float operation // This is a workaround to ensure that the result is a float to allow @@ -242,55 +241,56 @@ func (nr *NumericRegistry) Divf(values ...any) (any, error) { // // Parameters: // -// x any, y any - numbers to divide, expected to be numeric or convertible to float64. +// value any - the number to divide. +// divisor any - the number to divide by. // // Returns: // // any - the remainder, converted to the type of 'x'. // error - when a value cannot be converted. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: mod]. // -// {{ 10, 4 | mod }} // Output: 2 -func (nr *NumericRegistry) Mod(x, y any) (any, error) { - floatX, err := cast.ToFloat64E(x) +// [Sprout Documentation: mod]: https://docs.atom.codes/sprout/registries/numeric#mod +func (nr *NumericRegistry) Mod(value, divisor any) (any, error) { + floatX, err := cast.ToFloat64E(value) if err != nil { - return 0, sprout.NewErrConvertFailed("float64", x, err) + return 0, sprout.NewErrConvertFailed("float64", value, err) } - floatY, err := cast.ToFloat64E(y) + floatY, err := cast.ToFloat64E(divisor) if err != nil { - return 0, sprout.NewErrConvertFailed("float64", y, err) + return 0, sprout.NewErrConvertFailed("float64", divisor, err) } result := math.Mod(floatX, floatY) // Convert the result to the same type as the input - return reflect.ValueOf(result).Convert(reflect.TypeOf(x)).Interface(), nil + return reflect.ValueOf(result).Convert(reflect.TypeOf(value)).Interface(), nil } // Min returns the minimum value among the provided arguments. // // Parameters: // -// a any - the first number to compare. -// i ...any - additional numbers to compare. +// subtrahend any - the first number to compare. +// values ...any - additional numbers to compare. // // Returns: // // int64 - the smallest number among the inputs. // error - when a value cannot be converted. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: min]. // -// {{ 5, 3, 8, 2 | min }} // Output: 2 -func (nr *NumericRegistry) Min(a any, i ...any) (int64, error) { - intA, err := cast.ToInt64E(a) +// [Sprout Documentation: min]: https://docs.atom.codes/sprout/registries/numeric#min +func (nr *NumericRegistry) Min(subtrahend any, values ...any) (int64, error) { + intA, err := cast.ToInt64E(subtrahend) if err != nil { - return 0, sprout.NewErrConvertFailed("int64", a, err) + return 0, sprout.NewErrConvertFailed("int64", subtrahend, err) } - for _, b := range i { + for _, b := range values { intB, err := cast.ToInt64E(b) if err != nil { return 0, sprout.NewErrConvertFailed("int64", b, err) @@ -306,23 +306,23 @@ func (nr *NumericRegistry) Min(a any, i ...any) (int64, error) { // // Parameters: // -// a any - the first number to compare, expected to be numeric or convertible to float64. -// i ...any - additional numbers to compare. +// subtrahend any - the first number to compare, expected to be numeric or convertible to float64. +// values ...any - additional numbers to compare. // // Returns: // // float64 - the smallest number among the inputs. // error - when a value cannot be converted. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: minf]. // -// {{ 5.2, 3.8, 8.1, 2.6 | minf }} // Output: 2.6 -func (nr *NumericRegistry) Minf(a any, i ...any) (float64, error) { - floatA, err := cast.ToFloat64E(a) +// [Sprout Documentation: minf]: https://docs.atom.codes/sprout/registries/numeric#minf +func (nr *NumericRegistry) Minf(subtrahend any, values ...any) (float64, error) { + floatA, err := cast.ToFloat64E(subtrahend) if err != nil { - return 0, sprout.NewErrConvertFailed("float64", a, err) + return 0, sprout.NewErrConvertFailed("float64", subtrahend, err) } - for _, b := range i { + for _, b := range values { floatB, err := cast.ToFloat64E(b) if err != nil { return 0, sprout.NewErrConvertFailed("float64", b, err) @@ -336,24 +336,24 @@ func (nr *NumericRegistry) Minf(a any, i ...any) (float64, error) { // // Parameters: // -// a any - the first number to compare. -// i ...any - additional numbers to compare. +// value any - the first number to compare. +// values ...any - additional numbers to compare. // // Returns: // // int64 - the largest number among the inputs. // error - when a value cannot be converted. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: max]. // -// {{ 5, 3, 8, 2 | max }} // Output: 8 -func (nr *NumericRegistry) Max(a any, i ...any) (int64, error) { - intA, err := cast.ToInt64E(a) +// [Sprout Documentation: max]: https://docs.atom.codes/sprout/registries/numeric#max +func (nr *NumericRegistry) Max(value any, values ...any) (int64, error) { + intA, err := cast.ToInt64E(value) if err != nil { - return 0, sprout.NewErrConvertFailed("int64", a, err) + return 0, sprout.NewErrConvertFailed("int64", value, err) } - for _, b := range i { + for _, b := range values { intB, err := cast.ToInt64E(b) if err != nil { return 0, sprout.NewErrConvertFailed("int64", b, err) @@ -370,23 +370,23 @@ func (nr *NumericRegistry) Max(a any, i ...any) (int64, error) { // // Parameters: // -// a any - the first number to compare, expected to be numeric or convertible to float64. -// i ...any - additional numbers to compare. +// value any - the first number to compare, expected to be numeric or convertible to float64. +// values .any - additional numbers to compare. // // Returns: // // float64 - the largest number among the inputs. // error - when a value cannot be converted. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: maxf]. // -// {{ 5.2, 3.8, 8.1, 2.6 | maxf }} // Output: 8.1 -func (nr *NumericRegistry) Maxf(a any, i ...any) (float64, error) { - floatA, err := cast.ToFloat64E(a) +// [Sprout Documentation: maxf]: https://docs.atom.codes/sprout/registries/numeric#maxf +func (nr *NumericRegistry) Maxf(value any, values ...any) (float64, error) { + floatA, err := cast.ToFloat64E(value) if err != nil { - return 0, sprout.NewErrConvertFailed("float64", a, err) + return 0, sprout.NewErrConvertFailed("float64", value, err) } - for _, b := range i { + for _, b := range values { floatB, err := cast.ToFloat64E(b) if err != nil { return 0, sprout.NewErrConvertFailed("float64", b, err) diff --git a/registry/numeric/helpers.go b/registry/numeric/helpers.go index b65a8c0..344b472 100644 --- a/registry/numeric/helpers.go +++ b/registry/numeric/helpers.go @@ -21,12 +21,6 @@ import ( // Returns: // // any - Result of the operation, converted to the type of the first slice element. -// -// Example: -// -// add := func(a, b float64) float64 { return a + b } -// result := operateNumeric([]any{1.5, 2.5}, add, 0) -// fmt.Println(result) // Output: 4.0 (type float64 if first element is float64) func operateNumeric(values []any, op numericOperation, initial any) (any, error) { if len(values) == 0 { return initial, nil diff --git a/registry/random/functions.go b/registry/random/functions.go index 0d8a214..bbad823 100644 --- a/registry/random/functions.go +++ b/registry/random/functions.go @@ -10,89 +10,89 @@ import ( // // Parameters: // -// count int - the length of the string to generate. +// size int - the length of the string to generate. // // Returns: // // string - the randomly generated alphanumeric string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: randAlphaNum]. // -// {{ 10 | randAlphaNumeric }} // Output: "a1b2c3d4e5" (output will vary) -func (rr *RandomRegistry) RandAlphaNumeric(count int) string { - return rr.randomString(count, &randomOpts{withLetters: true, withNumbers: true}) +// [Sprout Documentation: randAlphaNum]: https://docs.atom.codes/sprout/registries/random#randalphanum +func (rr *RandomRegistry) RandAlphaNumeric(size int) string { + return rr.randomString(size, &randomOpts{withLetters: true, withNumbers: true}) } // RandAlpha generates a random alphabetic string of specified length. // // Parameters: // -// count int - the length of the string to generate. +// size int - the length of the string to generate. // // Returns: // // string - the randomly generated alphabetic string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: randAlpha]. // -// {{ 10 | randAlpha }} // Output: "abcdefghij" (output will vary) -func (rr *RandomRegistry) RandAlpha(count int) string { - return rr.randomString(count, &randomOpts{withLetters: true}) +// [Sprout Documentation: randAlpha]: https://docs.atom.codes/sprout/registries/random#randalpha +func (rr *RandomRegistry) RandAlpha(size int) string { + return rr.randomString(size, &randomOpts{withLetters: true}) } // RandAscii generates a random ASCII string (character codes 32 to 126) of specified length. // // Parameters: // -// count int - the length of the string to generate. +// size int - the length of the string to generate. // // Returns: // // string - the randomly generated ASCII string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: randAscii]. // -// {{ 10 | randAscii }} // Output: "}]~>_<:^%" (output will vary) -func (rr *RandomRegistry) RandAscii(count int) string { - return rr.randomString(count, &randomOpts{withAscii: true}) +// [Sprout Documentation: randAscii]: https://docs.atom.codes/sprout/registries/random#randascii +func (rr *RandomRegistry) RandAscii(size int) string { + return rr.randomString(size, &randomOpts{withAscii: true}) } // RandNumeric generates a random numeric string of specified length. // // Parameters: // -// count int - the length of the string to generate. +// size int - the length of the string to generate. // // Returns: // // string - the randomly generated numeric string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: randNumeric]. // -// {{ 10 | randNumeric }} // Output: "0123456789" (output will vary) -func (rr *RandomRegistry) RandNumeric(count int) string { - return rr.randomString(count, &randomOpts{withNumbers: true}) +// [Sprout Documentation: randNumeric]: https://docs.atom.codes/sprout/registries/random#randnumeric +func (rr *RandomRegistry) RandNumeric(size int) string { + return rr.randomString(size, &randomOpts{withNumbers: true}) } // RandBytes generates a random byte array of specified length and returns it as a base64 encoded string. // // Parameters: // -// count int - the number of bytes to generate. +// size int - the number of bytes to generate. // // Returns: // // string - the base64 encoded string of the randomly generated bytes. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: randBytes]. // -// {{ 16 | randBytes }} // Output: "c3RhY2thYnVzZSByb2NrcyE=" (output will vary) -func (rr *RandomRegistry) RandBytes(count int) (string, error) { - if count <= 0 { +// [Sprout Documentation: randBytes]: https://docs.atom.codes/sprout/registries/random#randbytes +func (rr *RandomRegistry) RandBytes(size int) (string, error) { + if size <= 0 { return "", nil } - buf := make([]byte, count) + buf := make([]byte, size) _, err := cryptorand.Read(buf) if err != nil { return "", err @@ -110,8 +110,9 @@ func (rr *RandomRegistry) RandBytes(count int) (string, error) { // Returns: // - int: the randomly generated integer. // -// Example: -// {{ randInt 1 10 }} // Output: 5 +// For an example of this function in a Go template, refer to [Sprout Documentation: randInt]. +// +// [Sprout Documentation: randInt]: https://docs.atom.codes/sprout/registries/random#randint func (rr *RandomRegistry) RandInt(min, max int) int { return mathrand.Intn(max-min) + min } diff --git a/registry/random/helpers.go b/registry/random/helpers.go index d6c2a31..362991e 100644 --- a/registry/random/helpers.go +++ b/registry/random/helpers.go @@ -11,7 +11,7 @@ import ( // // Parameters: // -// count int - the length of the string to generate. +// size int - the length of the string to generate. // opts *randomOpts - options specifying character sets to include in the string. // // Returns: @@ -22,8 +22,8 @@ import ( // // opts := &randomOpts{withLetters: true, withNumbers: true} // randomStr := rr.randomString(10, opts) // Generates a 10-character alphanumeric string. -func (rr *RandomRegistry) randomString(count int, opts *randomOpts) string { - if count <= 0 { +func (rr *RandomRegistry) randomString(size int, opts *randomOpts) string { + if size <= 0 { return "" } @@ -57,10 +57,10 @@ func (rr *RandomRegistry) randomString(count int, opts *randomOpts) string { } var builder strings.Builder - builder.Grow(count) + builder.Grow(size) maxIndex := big.NewInt(int64(len(opts.withChars))) - for i := 0; i < count; i++ { + for i := 0; i < size; i++ { index, _ := cryptorand.Int(cryptorand.Reader, maxIndex) builder.WriteRune(opts.withChars[index.Int64()]) } diff --git a/registry/reflect/functions.go b/registry/reflect/functions.go index c6e3477..df0432c 100644 --- a/registry/reflect/functions.go +++ b/registry/reflect/functions.go @@ -8,82 +8,82 @@ import ( "github.com/mitchellh/copystructure" ) -// TypeIs compares the type of 'src' to a target type string 'target'. -// It returns true if the type of 'src' matches the 'target'. +// TypeIs compares the type of 'value' to a target type string 'target'. +// It returns true if the type of 'value' matches the 'target'. // // Parameters: // // target string - the string representation of the type to check against. -// src any - the variable whose type is being checked. +// value any - the variable whose type is being checked. // // Returns: // -// bool - true if 'src' is of type 'target', false otherwise. +// bool - true if 'value' is of type 'target', false otherwise. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: typeIs]. // -// {{ "int", 42 | typeIs }} // Output: true -func (rr *ReflectRegistry) TypeIs(target string, src any) bool { - return target == rr.TypeOf(src) +// [Sprout Documentation: typeIs]: https://docs.atom.codes/sprout/registries/reflect#typeis +func (rr *ReflectRegistry) TypeIs(target string, value any) bool { + return target == rr.TypeOf(value) } -// TypeIsLike compares the type of 'src' to a target type string 'target', -// including a wildcard '*' prefix option. It returns true if 'src' matches +// TypeIsLike compares the type of 'value' to a target type string 'target', +// including a wildcard '*' prefix option. It returns true if 'value' matches // 'target' or '*target'. Useful for checking if a variable is of a specific // type or a pointer to that type. // // Parameters: // // target string - the string representation of the type or its wildcard version. -// src any - the variable whose type is being checked. +// value any - the variable whose type is being checked. // // Returns: // -// bool - true if the type of 'src' matches 'target' or '*'+target, false otherwise. +// bool - true if the type of 'value' matches 'target' or '*'+target, false otherwise. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: typeIsLike]. // -// {{ "*int", 42 | typeIsLike }} // Output: true -func (rr *ReflectRegistry) TypeIsLike(target string, src any) bool { - t := rr.TypeOf(src) +// [Sprout Documentation: typeIsLike]: https://docs.atom.codes/sprout/registries/reflect#typeislike +func (rr *ReflectRegistry) TypeIsLike(target string, value any) bool { + t := rr.TypeOf(value) return target == t || "*"+target == t } -// TypeOf returns the type of 'src' as a string. +// TypeOf returns the type of 'value' as a string. // // Parameters: // -// src any - the variable whose type is being determined. +// value any - the variable whose type is being determined. // // Returns: // -// string - the string representation of 'src's type. +// string - the string representation of 'value's type. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: typeOf]. // -// {{ 42 | typeOf }} // Output: "int" -func (rr *ReflectRegistry) TypeOf(src any) string { - return fmt.Sprintf("%T", src) +// [Sprout Documentation: typeOf]: https://docs.atom.codes/sprout/registries/reflect#typeof +func (rr *ReflectRegistry) TypeOf(value any) string { + return fmt.Sprintf("%T", value) } -// KindIs compares the kind of 'src' to a target kind string 'target'. -// It returns true if the kind of 'src' matches the 'target'. +// KindIs compares the kind of 'value' to a target kind string 'target'. +// It returns true if the kind of 'value' matches the 'target'. // // Parameters: // // target string - the string representation of the kind to check against. -// src any - the variable whose kind is being checked. +// value any - the variable whose kind is being checked. // // Returns: // -// bool - true if 'src's kind is 'target', false otherwise. -// error - when 'src' is nil. +// bool - true if 'value's kind is 'target', false otherwise. +// error - when 'value' is nil. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: kindIs]. // -// {{ "int", 42 | kindIs }} // Output: true -func (rr *ReflectRegistry) KindIs(target string, src any) (bool, error) { - result, err := rr.KindOf(src) +// [Sprout Documentation: kindIs]: https://docs.atom.codes/sprout/registries/reflect#kindis +func (rr *ReflectRegistry) KindIs(target string, value any) (bool, error) { + result, err := rr.KindOf(value) if err != nil { return false, err } @@ -91,26 +91,26 @@ func (rr *ReflectRegistry) KindIs(target string, src any) (bool, error) { return result == target, nil } -// KindOf returns the kind of 'src' as a string. +// KindOf returns the kind of 'value' as a string. // // Parameters: // -// src any - the variable whose kind is being determined. +// value any - the variable whose kind is being determined. // // Returns: // -// string - the string representation of 'src's kind. -// error - when 'src' is nil. +// string - the string representation of 'value's kind. +// error - when 'value' is nil. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: kindOf]. // -// {{ 42 | kindOf }} // Output: "int" -func (rr *ReflectRegistry) KindOf(src any) (string, error) { - if src == nil { - return "", errors.New("src must not be nil") +// [Sprout Documentation: kindOf]: https://docs.atom.codes/sprout/registries/reflect#kindof +func (rr *ReflectRegistry) KindOf(value any) (string, error) { + if value == nil { + return "", errors.New("value must not be nil") } - return reflect.ValueOf(src).Kind().String(), nil + return reflect.ValueOf(value).Kind().String(), nil } // HasField checks whether a struct has a field with a given name. @@ -118,19 +118,18 @@ func (rr *ReflectRegistry) KindOf(src any) (string, error) { // Parameters: // // name string - the name of the field that is being checked. -// src any - the struct that is being checked. +// value any - the struct that is being checked. // // Returns: // -// bool - true if the struct 'src' contains a field with the name 'name', false otherwise. +// bool - true if the struct 'value' contains a field with the name 'name', false otherwise. // error - when the last argument is not a struct. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: hasField]. // -// {{ hasField "someExistingField" .someStruct }} // Output: true -// {{ hasField "someNonExistingField" .someStruct }} // Output: false -func (rr *ReflectRegistry) HasField(name string, src any) (bool, error) { - rv := reflect.Indirect(reflect.ValueOf(src)) +// [Sprout Documentation: hasField]: https://docs.atom.codes/sprout/registries/reflect#hasfield +func (rr *ReflectRegistry) HasField(name string, value any) (bool, error) { + rv := reflect.Indirect(reflect.ValueOf(value)) if rv.Kind() != reflect.Struct { return false, errors.New("last argument must be a struct") } @@ -148,31 +147,31 @@ func (rr *ReflectRegistry) HasField(name string, src any) (bool, error) { // // bool - true if 'x' and 'y' are deeply equal, false otherwise. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: deepEqual]. // -// {{ {"a":1}, {"a":1} | deepEqual }} // Output: true +// [Sprout Documentation: deepEqual]: https://docs.atom.codes/sprout/registries/reflect#deepequal func (rr *ReflectRegistry) DeepEqual(x, y any) bool { return reflect.DeepEqual(y, x) } -// DeepCopy performs a deep copy of 'element' and panics if copying fails. +// DeepCopy performs a deep copy of 'value' and panics if copying fails. // It relies on MustDeepCopy to perform the copy and handle errors internally. // // Parameters: // -// element any - the element to be deeply copied. +// value any - the element to be deeply copied. // // Returns: // -// any - a deep copy of 'element'. -// error - when 'element' is nil. +// any - a deep copy of 'value'. +// error - when 'value' is nil. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: deepCopy]. // -// {{ {"name":"John"} | deepCopy }} // Output: {"name":"John"} -func (rr *ReflectRegistry) DeepCopy(element any) (any, error) { - if element == nil { - return nil, errors.New("element cannot be nil") +// [Sprout Documentation: deepCopy]: https://docs.atom.codes/sprout/registries/reflect#deepcopy +func (rr *ReflectRegistry) DeepCopy(value any) (any, error) { + if value == nil { + return nil, errors.New("value cannot be nil") } - return copystructure.Copy(element) + return copystructure.Copy(value) } diff --git a/registry/reflect/functions_test.go b/registry/reflect/functions_test.go index bb92ac9..9de93b2 100644 --- a/registry/reflect/functions_test.go +++ b/registry/reflect/functions_test.go @@ -63,7 +63,7 @@ func TestKindIs(t *testing.T) { {Name: "TestKindIsString", Input: `{{42 | kindIs "string"}}`, ExpectedOutput: "false"}, {Name: "TestKindIsVariable", Input: `{{$var := 42}}{{kindIs "string" $var}}`, ExpectedOutput: "false"}, {Name: "TestKindIsStruct", Input: `{{.var | kindIs "ptr"}}`, ExpectedOutput: "true", Data: map[string]any{"var": &testStruct{}}}, - {Name: "TestKindIsInterfaceNil", Input: `{{.var | kindIs "ptr"}}`, ExpectedErr: "src must not be nil", Data: map[string]any{"V": nilInterface}}, + {Name: "TestKindIsInterfaceNil", Input: `{{.var | kindIs "ptr"}}`, ExpectedErr: "value must not be nil", Data: map[string]any{"V": nilInterface}}, } pesticide.RunTestCases(t, reflect.NewRegistry(), tc) @@ -80,8 +80,8 @@ func TestKindOf(t *testing.T) { {Name: "TestKindOfStruct", Input: `{{kindOf .var}}`, ExpectedOutput: "ptr", Data: map[string]any{"var": &testStruct{}}}, {Name: "TestKindOfStructWithoutPointerMark", Input: `{{kindOf .var}}`, ExpectedOutput: "struct", Data: map[string]any{"var": testStruct{}}}, {Name: "TestKindOfIntNil", Input: `{{kindOf .V }}`, ExpectedOutput: "ptr", Data: map[string]any{"V": nilPointer}}, - {Name: "TestKindOfInterfaceNil", Input: `{{kindOf .V }}`, ExpectedErr: "src must not be nil", Data: map[string]any{"V": nilInterface}}, - {Name: "TestKindOfAnyNil", Input: `{{kindOf nil}}`, ExpectedErr: "src must not be nil"}, + {Name: "TestKindOfInterfaceNil", Input: `{{kindOf .V }}`, ExpectedErr: "value must not be nil", Data: map[string]any{"V": nilInterface}}, + {Name: "TestKindOfAnyNil", Input: `{{kindOf nil}}`, ExpectedErr: "value must not be nil"}, } pesticide.RunTestCases(t, reflect.NewRegistry(), tc) @@ -139,7 +139,7 @@ func TestDeepCopy(t *testing.T) { {Name: "TestDeepCopyVariable", Input: `{{$a := 42}}{{$b := deepCopy $a}}{{$b}}`, ExpectedOutput: "42"}, {Name: "TestDeepCopyDifferent", Input: `{{$a := 42}}{{$b := deepCopy "42"}}{{$b}}`, ExpectedOutput: "42"}, {Name: "TestDeepCopyDifferentType", Input: `{{$a := 42}}{{$b := deepCopy 42.0}}{{$b}}`, ExpectedOutput: "42"}, - {Name: "TestDeepCopyNil", Input: `{{$b := deepCopy .a}}`, ExpectedErr: "element cannot be nil", Data: map[string]any{"a": nil}}, + {Name: "TestDeepCopyNil", Input: `{{$b := deepCopy .a}}`, ExpectedErr: "value cannot be nil", Data: map[string]any{"a": nil}}, {Input: `{{- $d := dict "a" 1 "b" 2 | deepCopy }}{{ values $d | sortAlpha | join "," }}`, ExpectedOutput: "1,2"}, {Input: `{{- $d := dict "a" 1 "b" 2 | deepCopy }}{{ keys $d | sortAlpha | join "," }}`, ExpectedOutput: "a,b"}, {Input: `{{- $one := dict "foo" (dict "bar" "baz") "qux" true -}}{{ deepCopy $one }}`, ExpectedOutput: "map[foo:map[bar:baz] qux:true]"}, diff --git a/registry/regexp/functions.go b/registry/regexp/functions.go index e5ce842..0887279 100644 --- a/registry/regexp/functions.go +++ b/registry/regexp/functions.go @@ -8,17 +8,17 @@ import ( // // Parameters: // -// s string - the string to be escaped. +// value string - the string to be escaped. // // Returns: // // string - the escaped regex pattern. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: regexQuoteMeta]. // -// {{ regexQuoteMeta ".+*?^$()[]{}|" }} // Output: "\.\+\*\?\^\$\(\)\[\]\{\}\|" -func (rr *RegexpRegistry) RegexQuoteMeta(str string) string { - return regexp.QuoteMeta(str) +// [Sprout Documentation: regexQuoteMeta]: https://docs.atom.codes/sprout/registries/regexp#regexquotemeta +func (rr *RegexpRegistry) RegexQuoteMeta(value string) string { + return regexp.QuoteMeta(value) } // RegexFind searches for the first match of a regex pattern in a string @@ -27,22 +27,22 @@ func (rr *RegexpRegistry) RegexQuoteMeta(str string) string { // Parameters: // // regex string - the regular expression to search with. -// str string - the string to search within. +// value string - the string to search within. // // Returns: // // string - the first regex match found. // error - error if the regex fails to compile. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: regexFind]. // -// {{ "hello world" | RegexFind "hello" }} // Output: "hello", nil -func (rr *RegexpRegistry) RegexFind(regex string, str string) (string, error) { +// [Sprout Documentation: regexFind]: https://docs.atom.codes/sprout/registries/regexp#regexfind +func (rr *RegexpRegistry) RegexFind(regex string, value string) (string, error) { r, err := regexp.Compile(regex) if err != nil { return "", err } - return r.FindString(str), nil + return r.FindString(value), nil } // RegexFindAll finds all matches of a regex pattern in a string up to a @@ -51,7 +51,7 @@ func (rr *RegexpRegistry) RegexFind(regex string, str string) (string, error) { // Parameters: // // regex string - the regular expression to search with. -// str string - the string to search within. +// value string - the string to search within. // n int - the maximum number of matches to return; use -1 for no limit. // // Returns: @@ -59,15 +59,15 @@ func (rr *RegexpRegistry) RegexFind(regex string, str string) (string, error) { // []string - all regex matches found. // error - error if the regex fails to compile. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: regexFindAll]. // -// {{ RegexFindAll "a.", "aba acada afa", 3 }} // Output: ["ab", "ac", "af"], nil -func (rr *RegexpRegistry) RegexFindAll(regex string, str string, n int) ([]string, error) { +// [Sprout Documentation: regexFindAll]: https://docs.atom.codes/sprout/registries/regexp#regexfindall +func (rr *RegexpRegistry) RegexFindAll(regex string, value string, n int) ([]string, error) { r, err := regexp.Compile(regex) if err != nil { return []string{}, err } - return r.FindAllString(str, n), nil + return r.FindAllString(value, n), nil } // RegexMatch checks if a string matches a regex pattern, with error handling. @@ -75,18 +75,18 @@ func (rr *RegexpRegistry) RegexFindAll(regex string, str string, n int) ([]strin // Parameters: // // regex string - the regular expression to match against. -// str string - the string to check. +// value string - the string to check. // // Returns: // // bool - true if the string matches the regex pattern, otherwise false. // error - error if the regex fails to compile. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: regexMatch]. // -// {{ RegexMatch "^[a-zA-Z]+$", "Hello" }} // Output: true, nil -func (rr *RegexpRegistry) RegexMatch(regex string, str string) (bool, error) { - return regexp.MatchString(regex, str) +// [Sprout Documentation: regexMatch]: https://docs.atom.codes/sprout/registries/regexp#regexmatch +func (rr *RegexpRegistry) RegexMatch(regex string, value string) (bool, error) { + return regexp.MatchString(regex, value) } // RegexSplit splits a string by a regex pattern up to a specified number of @@ -95,7 +95,7 @@ func (rr *RegexpRegistry) RegexMatch(regex string, str string) (bool, error) { // Parameters: // // regex string - the regular expression to split by. -// str string - the string to split. +// value string - the string to split. // n int - the maximum number of substrings to return; use -1 for no limit. // // Returns: @@ -103,15 +103,15 @@ func (rr *RegexpRegistry) RegexMatch(regex string, str string) (bool, error) { // []string - the substrings resulting from the split. // error - error if the regex fails to compile. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: regexSplit]. // -// {{ RegexSplit "\\s+", "hello world from Go", 2 }} // Output: ["hello", "world from Go"], nil -func (rr *RegexpRegistry) RegexSplit(regex string, str string, n int) ([]string, error) { +// [Sprout Documentation: regexSplit]: https://docs.atom.codes/sprout/registries/regexp#regexsplit +func (rr *RegexpRegistry) RegexSplit(regex string, value string, n int) ([]string, error) { r, err := regexp.Compile(regex) if err != nil { return []string{}, err } - return r.Split(str, n), nil + return r.Split(value, n), nil } // RegexReplaceAll replaces all occurrences of a regex pattern in a string @@ -120,7 +120,7 @@ func (rr *RegexpRegistry) RegexSplit(regex string, str string, n int) ([]string, // Parameters: // // regex string - the regular expression to replace. -// str string - the string containing the original text. +// value string - the string containing the original text. // replacedBy string - the replacement text. // // Returns: @@ -128,15 +128,15 @@ func (rr *RegexpRegistry) RegexSplit(regex string, str string, n int) ([]string, // string - the modified string after all replacements. // error - error if the regex fails to compile. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: regexReplaceAll]. // -// {{ RegexReplaceAll "\\d", "R2D2 C3PO", "X" }} // Output: "RXDX CXPO", nil -func (rr *RegexpRegistry) RegexReplaceAll(regex string, str string, replacedBy string) (string, error) { +// [Sprout Documentation: regexReplaceAll]: https://docs.atom.codes/sprout/registries/regexp#regexreplaceall +func (rr *RegexpRegistry) RegexReplaceAll(regex string, value string, replacedBy string) (string, error) { r, err := regexp.Compile(regex) if err != nil { return "", err } - return r.ReplaceAllString(str, replacedBy), nil + return r.ReplaceAllString(value, replacedBy), nil } // RegexReplaceAllLiteral replaces all occurrences of a regex pattern in a @@ -145,7 +145,7 @@ func (rr *RegexpRegistry) RegexReplaceAll(regex string, str string, replacedBy s // Parameters: // // regex string - the regular expression to replace. -// s string - the string containing the original text. +// value string - the string containing the original text. // replacedBy string - the literal replacement text. // // Returns: @@ -153,15 +153,15 @@ func (rr *RegexpRegistry) RegexReplaceAll(regex string, str string, replacedBy s // string - the modified string after all replacements, treating the replacement text as literal text. // error - error if the regex fails to compile. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: regexReplaceAllLiteral]. // -// {{ RegexReplaceAllLiteral "world", "hello world", "$1" }} // Output: "hello $1", nil -func (rr *RegexpRegistry) RegexReplaceAllLiteral(regex string, s string, replacedBy string) (string, error) { +// [Sprout Documentation: regexReplaceAllLiteral]: https://docs.atom.codes/sprout/registries/regexp#regexreplaceallliteral +func (rr *RegexpRegistry) RegexReplaceAllLiteral(regex string, value string, replacedBy string) (string, error) { r, err := regexp.Compile(regex) if err != nil { return "", err } - return r.ReplaceAllLiteralString(s, replacedBy), nil + return r.ReplaceAllLiteralString(value, replacedBy), nil } // RegexFindGroups finds the first match of a regex pattern in a string and @@ -170,22 +170,22 @@ func (rr *RegexpRegistry) RegexReplaceAllLiteral(regex string, s string, replace // Parameters: // // regex string - the regular expression to search with. -// str string - the string to search within. +// value string - the string to search within. // // Returns: // // []string - the matched groups from the first regex match found. // error - error if the regex fails to compile. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: regexFindGroups]. // -// {{ "aaabbb" | regexFindGroups "(a+)(b+)" }} // Output: ["aaabbb", "aaa", "bbb"], nil -func (rr *RegexpRegistry) RegexFindGroups(regex string, str string) ([]string, error) { +// [Sprout Documentation: regexFindGroups]: https://docs.atom.codes/sprout/registries/regexp#regexfindgroups +func (rr *RegexpRegistry) RegexFindGroups(regex string, value string) ([]string, error) { r, err := regexp.Compile(regex) if err != nil { return []string{}, err } - matches := r.FindStringSubmatch(str) + matches := r.FindStringSubmatch(value) if len(matches) == 0 { return []string{}, nil } @@ -198,7 +198,7 @@ func (rr *RegexpRegistry) RegexFindGroups(regex string, str string) ([]string, e // Parameters: // // regex string - the regular expression to search with. -// str string - the string to search within. +// value string - the string to search within. // n int - the maximum number of matches to return; use -1 for no limit. // // Returns: @@ -206,15 +206,15 @@ func (rr *RegexpRegistry) RegexFindGroups(regex string, str string) ([]string, e // [][]string - a slice containing the matched groups for each match found. // error - error if the regex fails to compile. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: regexFindAllGroups]. // -// {{ "aaabbb aab aaabbb" | regexFindAllGroups "(a+)(b+)" -1 }} // Output: [["aaabbb", "aaa", "bbb"], ["aab", "aa", "b"], ["aaabbb", "aaa", "bbb"]], nil -func (rr *RegexpRegistry) RegexFindAllGroups(regex string, n int, str string) ([][]string, error) { +// [Sprout Documentation: regexFindAllGroups]: https://docs.atom.codes/sprout/registries/regexp#regexfindallgroups +func (rr *RegexpRegistry) RegexFindAllGroups(regex string, n int, value string) ([][]string, error) { r, err := regexp.Compile(regex) if err != nil { return [][]string{}, err } - matches := r.FindAllStringSubmatch(str, n) + matches := r.FindAllStringSubmatch(value, n) if len(matches) == 0 { return [][]string{}, nil } @@ -228,22 +228,22 @@ func (rr *RegexpRegistry) RegexFindAllGroups(regex string, n int, str string) ([ // Parameters: // // regex string - the regular expression to search with, containing named capturing groups. -// str string - the string to search within. +// value string - the string to search within. // // Returns: // // map[string]string - a map of group names to their corresponding matched strings. // error - error if the regex fails to compile. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: regexFindNamed]. // -// {{ "aaabbb" | regexFindNamed "(?Pa+)(?Pb+)" }} // Output: map["first":"aaa", "second":"bbb"], nil -func (rr *RegexpRegistry) RegexFindNamed(regex string, str string) (map[string]string, error) { +// [Sprout Documentation: regexFindNamed]: https://docs.atom.codes/sprout/registries/regexp#regexfindnamed +func (rr *RegexpRegistry) RegexFindNamed(regex string, value string) (map[string]string, error) { r, err := regexp.Compile(regex) if err != nil { return map[string]string{}, err } - matches := r.FindStringSubmatch(str) + matches := r.FindStringSubmatch(value) if len(matches) == 0 { return map[string]string{}, nil } @@ -264,7 +264,7 @@ func (rr *RegexpRegistry) RegexFindNamed(regex string, str string) (map[string]s // Parameters: // // regex string - the regular expression to search with, containing named capturing groups. -// str string - the string to search within. +// value string - the string to search within. // n int - the maximum number of matches to return; use -1 for no limit. // // Returns: @@ -272,15 +272,15 @@ func (rr *RegexpRegistry) RegexFindNamed(regex string, str string) (map[string]s // []map[string]string - a slice containing a map of group names to their corresponding matched strings for each match found. // error - error if the regex fails to compile. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: regexFindAllNamed]. // -// {{ "aaabbb aab aaabbb" | regexFindAllNamed "(?Pa+)(?Pb+)" -1 }} // Output: [map["first":"aaa", "second":"bbb"], map["first":"aa", "second":"b"], map["first":"aaa", "second":"bbb"]], nil -func (rr *RegexpRegistry) RegexFindAllNamed(regex string, n int, str string) ([]map[string]string, error) { +// [Sprout Documentation: regexFindAllNamed]: https://docs.atom.codes/sprout/registries/regexp#regexfindallnamed +func (rr *RegexpRegistry) RegexFindAllNamed(regex string, n int, value string) ([]map[string]string, error) { r, err := regexp.Compile(regex) if err != nil { return []map[string]string{}, err } - matches := r.FindAllStringSubmatch(str, n) + matches := r.FindAllStringSubmatch(value, n) if len(matches) == 0 { return []map[string]string{}, nil } diff --git a/registry/semver/functions.go b/registry/semver/functions.go index 37407d9..55f5560 100644 --- a/registry/semver/functions.go +++ b/registry/semver/functions.go @@ -8,18 +8,18 @@ import ( // // Parameters: // -// version string - the version string to parse into a semantic version object. +// value string - the version string to parse into a semantic version object. // // Returns: // // *semver.Version - the parsed semantic version object. // error - an error if the version string is invalid. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: semver]. // -// {{ semver "1.0.0" }} // Output: semver.Version object -func (fh *SemverRegistry) Semver(version string) (*semver.Version, error) { - return semver.NewVersion(version) +// [Sprout Documentation: semver]: https://docs.atom.codes/sprout/registries/semver#semver +func (fh *SemverRegistry) Semver(value string) (*semver.Version, error) { + return semver.NewVersion(value) } // SemverCompare checks if a given version string satisfies a specified semantic version constraint. @@ -27,23 +27,23 @@ func (fh *SemverRegistry) Semver(version string) (*semver.Version, error) { // Parameters: // // constraint string - the version constraint to check against. -// version string - the version string to validate against the constraint. +// value string - the version string to validate against the constraint. // // Returns: // // bool - true if the version satisfies the constraint, false otherwise. // error - an error if either the constraint or version string is invalid. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: semverCompare]. // -// {{ semverCompare ">=1.0.0" "1.0.0" }} // Output: true -func (fh *SemverRegistry) SemverCompare(constraint, version string) (bool, error) { +// [Sprout Documentation: semverCompare]: https://docs.atom.codes/sprout/registries/semver#semvercompare +func (fh *SemverRegistry) SemverCompare(constraint, value string) (bool, error) { c, err := semver.NewConstraint(constraint) if err != nil { return false, err } - v, err := semver.NewVersion(version) + v, err := semver.NewVersion(value) if err != nil { return false, err } diff --git a/registry/slices/functions.go b/registry/slices/functions.go index 2c698c3..72a7e0a 100644 --- a/registry/slices/functions.go +++ b/registry/slices/functions.go @@ -22,9 +22,9 @@ import ( // // []any - the created list containing the provided elements. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: list]. // -// {{ 1, 2, 3 | list }} // Output: [1, 2, 3] +// [Sprout Documentation: list]: https://docs.atom.codes/sprout/registries/slices#list func (sr *SlicesRegistry) List(values ...any) []any { return values } @@ -42,9 +42,9 @@ func (sr *SlicesRegistry) List(values ...any) []any { // []any - the new list with the element appended. // error - protect against undesired behavior due to migration to new signature. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: append]. // -// {{ ["a", "b"] | append "c" }} // Output: ["a", "b", "c"], nil +// [Sprout Documentation: append]: https://docs.atom.codes/sprout/registries/slices#append func (sr *SlicesRegistry) Append(args ...any) ([]any, error) { // ! BACKWARDS COMPATIBILITY: deprecated in v1.0 and removed in v1.1 // ! Due to change in signature, this function still supports the old signature @@ -112,9 +112,9 @@ func (sr *SlicesRegistry) Append(args ...any) ([]any, error) { // []any - the new list with the element prepended. // error - protect against undesired behavior due to migration to new signature. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: prepend]. // -// {{ ["b", "c"] | prepend "a" }} // Output: ["a", "b", "c"], nil +// [Sprout Documentation: prepend]: https://docs.atom.codes/sprout/registries/slices#prepend func (sr *SlicesRegistry) Prepend(args ...any) ([]any, error) { // ! BACKWARDS COMPATIBILITY: deprecated in v1.0 and removed in v1.1 // ! Due to change in signature, this function still supports the old signature @@ -168,9 +168,9 @@ func (sr *SlicesRegistry) Prepend(args ...any) ([]any, error) { // // any - a single concatenated list containing elements from all provided lists. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: concat]. // -// {{ ["c", "d"] | concat ["a", "b"] }} // Output: ["a", "b", "c", "d"] +// [Sprout Documentation: concat]: https://docs.atom.codes/sprout/registries/slices#concat func (sr *SlicesRegistry) Concat(lists ...any) any { // Estimate the total length to preallocate the result slice var totalLen int @@ -218,9 +218,9 @@ func (sr *SlicesRegistry) Concat(lists ...any) any { // [][]any - a list of chunks. // error - error if the list is nil or not a slice/array. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: chunk]. // -// {{ ["a", "b", "c", "d"] | chunk 2 }} // Output: [["a", "b"], ["c", "d"]], nil +// [Sprout Documentation: chunk]: https://docs.atom.codes/sprout/registries/slices#chunk func (sr *SlicesRegistry) Chunk(size int, list any) ([][]any, error) { if list == nil { return nil, fmt.Errorf("cannot chunk nil") @@ -270,9 +270,9 @@ func (sr *SlicesRegistry) Chunk(size int, list any) ([][]any, error) { // []any - a list containing only the unique elements. // error - error if the list is nil or not a slice/array. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: uniq]. // -// {{ ["a", "b", "a", "c"] | uniq }} // Output: ["a", "b", "c"], nil +// [Sprout Documentation: uniq]: https://docs.atom.codes/sprout/registries/slices#uniq func (sr *SlicesRegistry) Uniq(list any) ([]any, error) { if list == nil { return nil, fmt.Errorf("cannot uniq nil") @@ -315,9 +315,9 @@ func (sr *SlicesRegistry) Uniq(list any) ([]any, error) { // []any - the list without nil or zero-value elements. // error - error if the list is nil or not a slice/array. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: compact]. // -// {{ [0, 1, nil, 2, "", 3] | compact }} // Output: [1, 2, 3], nil +// [Sprout Documentation: compact]: https://docs.atom.codes/sprout/registries/slices#compact func (sr *SlicesRegistry) Compact(list any) ([]any, error) { if list == nil { return nil, fmt.Errorf("cannot compact nil") @@ -355,9 +355,9 @@ func (sr *SlicesRegistry) Compact(list any) ([]any, error) { // []any - the flattened list. // error - error if the list is nil or not a slice/array. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: flatten]. // -// {{ flatten [[1, 2], [3, 4], 5] }} // Output: [1, 2, 3, 4, 5] +// [Sprout Documentation: flatten]: https://docs.atom.codes/sprout/registries/slices#flatten func (sr *SlicesRegistry) Flatten(list any) ([]any, error) { return sr.FlattenDepth(-1, list) } @@ -375,9 +375,9 @@ func (sr *SlicesRegistry) Flatten(list any) ([]any, error) { // []any - the flattened list. // error - error if the list is nil or not a slice/array. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: flattenDepth]. // -// {{ [[1, 2, [3], 4], 5] | flattenDepth 1 }} // Output: [1, 2, [3], 4, 5] +// [Sprout Documentation: flattenDepth]: https://docs.atom.codes/sprout/registries/slices#flattendepth func (sr *SlicesRegistry) FlattenDepth(deep int, list any) ([]any, error) { if list == nil { return nil, fmt.Errorf("cannot flatten nil") @@ -408,9 +408,9 @@ func (sr *SlicesRegistry) FlattenDepth(deep int, list any) ([]any, error) { // any - the sliced part of the list. // error - protect against undesired behavior due to migration to new signature. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: slice]. // -// {{ [1, 2, 3, 4, 5] | slice 1, 3 }} // Output: [2, 3], nil +// [Sprout Documentation: slice]: https://docs.atom.codes/sprout/registries/slices#slice func (sr *SlicesRegistry) Slice(args ...any) (any, error) { // ! BACKWARDS COMPATIBILITY: deprecated in v1.0 and removed in v1.1 // ! Due to change in signature, this function still supports the old signature @@ -488,9 +488,9 @@ func (sr *SlicesRegistry) Slice(args ...any) (any, error) { // bool - true if the element is found, otherwise false. // error - error if the list is not a type that can be searched (not a slice or array). // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: has]. // -// {{ [1, 2, 3, 4] | has 3 }} // Output: true, nil +// [Sprout Documentation: has]: https://docs.atom.codes/sprout/registries/slices#has func (sr *SlicesRegistry) Has(element any, list any) (bool, error) { if list == nil { return false, nil @@ -527,9 +527,9 @@ func (sr *SlicesRegistry) Has(element any, list any) (bool, error) { // []any - the list excluding the specified elements. // error - protect against undesired behavior due to migration to new signature. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: without]. // -// {{ [1, 2, 3, 4] | without 2, 4 }} // Output: [1, 3], nil +// [Sprout Documentation: without]: https://docs.atom.codes/sprout/registries/slices#without func (sr *SlicesRegistry) Without(args ...any) ([]any, error) { // ! BACKWARDS COMPATIBILITY: deprecated in v1.0 and removed in v1.1 // ! Due to change in signature, this function still supports the old signature @@ -595,9 +595,9 @@ func (sr *SlicesRegistry) Without(args ...any) ([]any, error) { // []any - the list without the first element. // error - error if the list is nil or not a slice/array. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: rest]. // -// {{ [1, 2, 3, 4] | rest }} // Output: [2, 3, 4], nil +// [Sprout Documentation: rest]: https://docs.atom.codes/sprout/registries/slices#rest func (sr *SlicesRegistry) Rest(list any) ([]any, error) { if list == nil { return nil, fmt.Errorf("cannot rest nil") @@ -635,9 +635,9 @@ func (sr *SlicesRegistry) Rest(list any) ([]any, error) { // []any - the list without the last element. // error - error if the list is nil or not a slice/array. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: initial]. // -// {{ [1, 2, 3, 4] | initial }} // Output: [1, 2, 3], nil +// [Sprout Documentation: initial]: https://docs.atom.codes/sprout/registries/slices#initial func (sr *SlicesRegistry) Initial(list any) ([]any, error) { if list == nil { return nil, fmt.Errorf("cannot initial nil") @@ -675,9 +675,9 @@ func (sr *SlicesRegistry) Initial(list any) ([]any, error) { // any - the first element of the list. // error - error if the list is nil, empty, or not a slice/array. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: first]. // -// {{ [1, 2, 3, 4] | first }} // Output: 1, nil +// [Sprout Documentation: first]: https://docs.atom.codes/sprout/registries/slices#first func (sr *SlicesRegistry) First(list any) (any, error) { if list == nil { return nil, fmt.Errorf("cannot first nil") @@ -710,9 +710,9 @@ func (sr *SlicesRegistry) First(list any) (any, error) { // any - the last element of the list. // error - error if the list is nil, empty, or not a slice/array. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: last]. // -// {{ [1, 2, 3, 4] | last }} // Output: 4, nil +// [Sprout Documentation: last]: https://docs.atom.codes/sprout/registries/slices#last func (sr *SlicesRegistry) Last(list any) (any, error) { if list == nil { return nil, fmt.Errorf("cannot last nil") @@ -745,9 +745,9 @@ func (sr *SlicesRegistry) Last(list any) (any, error) { // []any - the list in reverse order. // error - error if the list is nil or not a slice/array. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: reverse]. // -// {{ [1, 2, 3, 4] | reverse }} // Output: [4, 3, 2, 1], nil +// [Sprout Documentation: reverse]: https://docs.atom.codes/sprout/registries/slices#reverse func (sr *SlicesRegistry) Reverse(list any) ([]any, error) { if list == nil { return nil, fmt.Errorf("cannot reverse nil") @@ -782,9 +782,9 @@ func (sr *SlicesRegistry) Reverse(list any) ([]any, error) { // // []string - the sorted list. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: sortAlpha]. // -// {{ ["d", "b", "a", "c"] | sortAlpha }} // Output: ["a", "b", "c", "d"] +// [Sprout Documentation: sortAlpha]: https://docs.atom.codes/sprout/registries/slices#sortalpha func (sr *SlicesRegistry) SortAlpha(list any) []string { kind := reflect.Indirect(reflect.ValueOf(list)).Kind() switch kind { @@ -805,17 +805,17 @@ func (sr *SlicesRegistry) SortAlpha(list any) []string { // Parameters: // // sep string - the delimiter used to split the string. -// str string - the string to split. +// value string - the string to split. // // Returns: // // []string - a slice containing the substrings obtained from splitting the input string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: splitList]. // -// {{ "one, two, three" | splitList ", " }} // Output: ["one", "two", "three"] -func (sr *SlicesRegistry) SplitList(sep string, str string) []string { - return strings.Split(str, sep) +// [Sprout Documentation: splitList]: https://docs.atom.codes/sprout/registries/slices#splitlist +func (sr *SlicesRegistry) SplitList(sep string, value string) []string { + return strings.Split(value, sep) } // StrSlice converts a value to a slice of strings, handling various types @@ -829,9 +829,9 @@ func (sr *SlicesRegistry) SplitList(sep string, str string) []string { // // []string - the converted slice of strings. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: strSlice]. // -// {{ strSlice any["a", "b", "c"] }} // Output: ["a", "b", "c"] +// [Sprout Documentation: strSlice]: https://docs.atom.codes/sprout/registries/slices#strslice func (sr *SlicesRegistry) StrSlice(value any) []string { return helpers.StrSlice(value) } @@ -842,16 +842,17 @@ func (sr *SlicesRegistry) StrSlice(value any) []string { // the range and step dynamically. // // Parameters: -// count int - the endpoint (exclusive) of the range to generate. +// +// count int - the endpoint (exclusive) of the range to generate. // // Returns: -// []int - a slice of integers from 0 to 'count' with the appropriate step -// depending on whether 'count' is positive or negative. // -// Example: -// {{ 5 | until }} // Output: [0 1 2 3 4] -// {{ -3 | until }} // Output: [0 -1 -2] - +// []int - a slice of integers from 0 to 'count' with the appropriate step +// depending on whether 'count' is positive or negative. +// +// For an example of this function in a Go template, refer to [Sprout Documentation: until]. +// +// [Sprout Documentation: until]: https://docs.atom.codes/sprout/registries/slices#until func (sr *SlicesRegistry) Until(count int) []int { step := 1 if count < 0 { @@ -878,10 +879,9 @@ func (sr *SlicesRegistry) Until(count int) []int { // parameters, or an empty slice if the parameters are inconsistent // with the desired range and step. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: untilStep]. // -// {{ 0, 10, 2 | untilStep }} // Output: [0 2 4 6 8] -// {{ 10, 0, -2 | untilStep }} // Output: [10 8 6 4 2] +// [Sprout Documentation: untilStep]: https://docs.atom.codes/sprout/registries/slices#untilstep func (sr *SlicesRegistry) UntilStep(start, stop, step int) []int { return helpers.UntilStep(start, stop, step) } diff --git a/registry/slices/helpers.go b/registry/slices/helpers.go index 5d078a4..6b376f1 100644 --- a/registry/slices/helpers.go +++ b/registry/slices/helpers.go @@ -4,7 +4,18 @@ import ( "reflect" ) -// inList checks if a value is in a slice of any type by comparing values. +// inList checks if the needle is present in the haystack slice. +// It returns true if an element in the haystack is equal to the needle. +// The comparison is performed first by equality if both elements are comparable, +// and then by deep equality if they are of the same type. It returns false otherwise. +// Parameters: +// +// haystack - list of values to search in +// needle - value to search for +// +// Returns: +// +// true if the needle is found in haystack, false otherwise. func (sr *SlicesRegistry) inList(haystack []any, needle any) bool { for _, h := range haystack { if sr.isComparable(h) && h == needle { @@ -18,9 +29,19 @@ func (sr *SlicesRegistry) inList(haystack []any, needle any) bool { return false } -// isComparable checks if a value is a comparable type. -func (sr *SlicesRegistry) isComparable(v any) bool { - switch v.(type) { +// isComparable checks if the given value is of a type that can be compared using +// the equality operator (==). It returns true for basic types such as integers, +// floating-point numbers, strings, and booleans, and false otherwise. +// +// Parameters: +// +// value - the value to check for comparability. +// +// Returns: +// +// true if the value is a basic comparable type, false otherwise. +func (sr *SlicesRegistry) isComparable(value any) bool { + switch value.(type) { case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, string, bool: return true @@ -29,12 +50,24 @@ func (sr *SlicesRegistry) isComparable(v any) bool { } } -// flattenSlice recursively flattens a slice of slices into a single slice. -// It is used by the Flatten function. -func (sr *SlicesRegistry) flattenSlice(val reflect.Value, remainingDeep int) []any { - result := make([]any, 0, val.Len()) - for i := 0; i < val.Len(); i++ { - item := val.Index(i) +// flattenSlice takes a slice or array and recursively flattens it into a +// single-dimensional list of elements. The remainingDeep parameter controls +// the maximum depth of the flattening, with -1 indicating infinite depth and +// 0 indicating no recursion. The function returns a slice of the flattened +// elements. +// +// Parameters: +// +// value - the slice or array to flatten +// remainingDeep - the maximum depth of recursion +// +// Returns: +// +// a single-dimensional list of elements from the input slice or array. +func (sr *SlicesRegistry) flattenSlice(value reflect.Value, remainingDeep int) []any { + result := make([]any, 0, value.Len()) + for i := 0; i < value.Len(); i++ { + item := value.Index(i) if item.Kind() == reflect.Interface { item = item.Elem() diff --git a/registry/std/functions.go b/registry/std/functions.go index 4ad31ab..73e5b0a 100644 --- a/registry/std/functions.go +++ b/registry/std/functions.go @@ -13,12 +13,12 @@ func (sr *StdRegistry) Hello() string { return "Hello!" } -// Default returns the first non-empty value from the given arguments or a +// Default returns the first non-empty value from the value arguments or a // default value if the argument list is empty or the first element is empty. // It accepts a default value `defaultValue` of any type and a variadic slice -// `given` of any type. If `given` is not provided or the first element in -// `given` is empty, it returns `defaultValue`. -// Otherwise, it returns the first element of `given`. +// `value` of any type. If `value` is not provided or the first element in +// `value` is empty, it returns `defaultValue`. +// Otherwise, it returns the first element of `value`. // If you want to catch the first non-empty value from a list of values, use // the `Coalesce` function instead. // @@ -26,55 +26,48 @@ func (sr *StdRegistry) Hello() string { // // defaultValue any - the default value to return if no valid argument is // provided or if the first argument is empty. -// given ...any - a variadic slice of any type to check the first +// value ...any - a variadic slice of any type to check the first // element of it for emptiness. // // Returns: // -// any - the first element of `given`, or `defaultValue` if `given` is empty +// any - the first element of `value`, or `defaultValue` if `value` is empty // or all values are empty. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: default]. // -// {{ nil | default "default" }} // Output: "default" -// {{ "" | default "default" }} // Output: "default" -// {{ "first" | default "default" }} // Output: "first" -// {{ "first" | default "default" "second" }} // Output: "second" -func (sr *StdRegistry) Default(defaultValue any, given ...any) any { - if len(given) == 0 || helpers.Empty(given[0]) { +// [Sprout Documentation: default]: https://docs.atom.codes/sprout/registries/std#default +func (sr *StdRegistry) Default(defaultValue any, value ...any) any { + if len(value) == 0 || helpers.Empty(value[0]) { return defaultValue } - return given[0] + return value[0] } -// Empty evaluates the emptiness of the provided value 'given'. It returns -// true if 'given' is considered empty based on its type. This method is +// Empty evaluates the emptiness of the provided value 'value'. It returns +// true if 'value' is considered empty based on its type. This method is // essential for determining the presence or absence of meaningful value // across various data types. // +// This method utilizes the reflect package to inspect the type and value of +// 'value'. Depending on the type, it checks for nil pointers, zero-length +// collections (arrays, slices, maps, and strings), zero values of numeric +// types (integers, floats, complex numbers, unsigned ints), and false for +// booleans. +// // Parameters: // -// given any - the value to be evaluated for emptiness. +// value any - the value to be evaluated for emptiness. // // Returns: // -// bool - true if 'given' is empty, false otherwise. -// -// This method utilizes the reflect package to inspect the type and value of -// 'given'. Depending on the type, it checks for nil pointers, zero-length -// collections (arrays, slices, maps, and strings), zero values of numeric -// types (integers, floats, complex numbers, unsigned ints), and false for -// booleans. +// bool - true if 'value' is empty, false otherwise. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: empty]. // -// {{ nil | empty }} // Output: true -// {{ "" | empty }} // Output: true -// {{ 0 | empty }} // Output: true -// {{ false | empty }} // Output: true -// {{ struct{}{} | empty }} // Output: false -func (sr *StdRegistry) Empty(given any) bool { - return helpers.Empty(given) +// [Sprout Documentation: empty]: https://docs.atom.codes/sprout/registries/std#empty +func (sr *StdRegistry) Empty(value any) bool { + return helpers.Empty(value) } // All checks if all values in the provided variadic slice are non-empty. @@ -88,10 +81,9 @@ func (sr *StdRegistry) Empty(given any) bool { // // bool - true if all values are non-empty, false otherwise. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: all]. // -// {{ 1, "hello", true | all }} // Output: true -// {{ 1, "", true | all }} // Output: false +// [Sprout Documentation: all]: https://docs.atom.codes/sprout/registries/std#all func (sr *StdRegistry) All(values ...any) bool { for _, val := range values { if helpers.Empty(val) { @@ -105,15 +97,16 @@ func (sr *StdRegistry) All(values ...any) bool { // It returns true if at least one value is non-empty. // // Parameters: +// // values ...any - a variadic parameter list of values to be checked. // // Returns: +// // bool - true if any value is non-empty, false if all are empty. // -// Example: -// {{ "", 0, false | any }} // Output: false -// {{ "", 0, "text" | any }} // Output: true - +// For an example of this function in a Go template, refer to [Sprout Documentation: any]. +// +// [Sprout Documentation: any]: https://docs.atom.codes/sprout/registries/std#any func (sr *StdRegistry) Any(values ...any) bool { for _, val := range values { if !helpers.Empty(val) { @@ -127,15 +120,17 @@ func (sr *StdRegistry) Any(values ...any) bool { // If all values are empty, it returns nil. // // Parameters: -// values ...any - a variadic parameter list of values from which the first -// non-empty value should be selected. +// +// values ...any - a variadic parameter list of values from which the first +// non-empty value should be selected. // // Returns: +// // any - the first non-empty value, or nil if all values are empty. // -// Example: -// {{ nil, "", "first", "second" | coalesce }} // Output: "first" - +// For an example of this function in a Go template, refer to [Sprout Documentation: coalesce]. +// +// [Sprout Documentation: coalesce]: https://docs.atom.codes/sprout/registries/std#coalesce func (sr *StdRegistry) Coalesce(values ...any) any { for _, val := range values { if !helpers.Empty(val) { @@ -158,10 +153,9 @@ func (sr *StdRegistry) Coalesce(values ...any) any { // // any - the result based on the evaluated condition. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: ternary]. // -// {{ "yes", "no", true | ternary }} // Output: "yes" -// {{ "yes", "no", false | ternary }} // Output: "no" +// [Sprout Documentation: ternary]: https://docs.atom.codes/sprout/registries/std#ternary func (sr *StdRegistry) Ternary(trueValue any, falseValue any, condition bool) any { if condition { return trueValue @@ -183,9 +177,9 @@ func (sr *StdRegistry) Ternary(trueValue any, falseValue any, condition bool) an // string - a single string composed of all non-nil input values separated // by spaces. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: cat]. // -// {{ "Hello", nil, 123, true | cat }} // Output: "Hello 123 true" +// [Sprout Documentation: cat]: https://docs.atom.codes/sprout/registries/std#cat func (sr *StdRegistry) Cat(values ...any) string { var builder strings.Builder for i, item := range values { diff --git a/registry/strings/functions.go b/registry/strings/functions.go index 675570f..9efd78d 100644 --- a/registry/strings/functions.go +++ b/registry/strings/functions.go @@ -17,39 +17,39 @@ import ( // // Parameters: // -// str string - the string from which to remove whitespace. +// value string - the string from which to remove whitespace. // // Returns: // // string - the modified string with all whitespace characters removed. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: nospace]. // -// {{ "Hello World" | nospace }} // Output: "HelloWorld" -func (sr *StringsRegistry) Nospace(str string) string { +// [Sprout Documentation: nospace]: https://docs.atom.codes/sprout/registries/strings#nospace +func (sr *StringsRegistry) Nospace(value string) string { return strings.Map(func(r rune) rune { if unicode.IsSpace(r) { return -1 } return r - }, str) + }, value) } // Trim removes leading and trailing whitespace from the string. // // Parameters: // -// str string - the string to trim. +// value string - the string to trim. // // Returns: // // string - the trimmed string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: trim]. // -// {{ " Hello World " | trim }} // Output: "Hello World" -func (sr *StringsRegistry) Trim(str string) string { - return strings.TrimSpace(str) +// [Sprout Documentation: trim]: https://docs.atom.codes/sprout/registries/strings#trim +func (sr *StringsRegistry) Trim(value string) string { + return strings.TrimSpace(value) } // TrimAll removes all occurrences of any characters in 'cutset' from both the @@ -58,17 +58,17 @@ func (sr *StringsRegistry) Trim(str string) string { // Parameters: // // cutset string - a string of characters to remove from the string. -// str string - the string to trim. +// value string - the string to trim. // // Returns: // // string - the string with specified characters removed. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: trimAll]. // -// {{ "xyzHelloxyz" | trimAll "xyz" }} // Output: "Hello" -func (sr *StringsRegistry) TrimAll(cutset string, str string) string { - return strings.Trim(str, cutset) +// [Sprout Documentation: trimAll]: https://docs.atom.codes/sprout/registries/strings#trimall +func (sr *StringsRegistry) TrimAll(cutset string, value string) string { + return strings.Trim(value, cutset) } // TrimPrefix removes the 'prefix' from the start of 'str' if present. @@ -76,17 +76,17 @@ func (sr *StringsRegistry) TrimAll(cutset string, str string) string { // Parameters: // // prefix string - the prefix to remove. -// str string - the string to trim. +// value string - the string to trim. // // Returns: // // string - the string with the prefix removed if it was present. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: trimPrefix]. // -// {{ "HelloWorld" | trimPrefix "Hello" }} // Output: "World" -func (sr *StringsRegistry) TrimPrefix(prefix string, str string) string { - return strings.TrimPrefix(str, prefix) +// [Sprout Documentation: trimPrefix]: https://docs.atom.codes/sprout/registries/strings#trimprefix +func (sr *StringsRegistry) TrimPrefix(prefix string, value string) string { + return strings.TrimPrefix(value, prefix) } // TrimSuffix removes the 'suffix' from the end of 'str' if present. @@ -94,17 +94,17 @@ func (sr *StringsRegistry) TrimPrefix(prefix string, str string) string { // Parameters: // // suffix string - the suffix to remove. -// str string - the string to trim. +// value string - the string to trim. // // Returns: // // string - the string with the suffix removed if it was present. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: trimSuffix]. // -// {{ "HelloWorld" | trimSuffix "World" }} // Output: "Hello" -func (sr *StringsRegistry) TrimSuffix(suffix string, str string) string { - return strings.TrimSuffix(str, suffix) +// [Sprout Documentation: trimSuffix]: https://docs.atom.codes/sprout/registries/strings#trimsuffix +func (sr *StringsRegistry) TrimSuffix(suffix string, value string) string { + return strings.TrimSuffix(value, suffix) } // Contains checks if 'str' contains the 'substring'. @@ -112,17 +112,17 @@ func (sr *StringsRegistry) TrimSuffix(suffix string, str string) string { // Parameters: // // substring string - the substring to search for. -// str string - the string to search within. +// value string - the string to search within. // // Returns: // // bool - true if 'str' contains 'substring', false otherwise. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: contains]. // -// {{ "Hello" | contains "ell" }} // Output: true -func (sr *StringsRegistry) Contains(substring string, str string) bool { - return strings.Contains(str, substring) +// [Sprout Documentation: contains]: https://docs.atom.codes/sprout/registries/strings#contains +func (sr *StringsRegistry) Contains(substring string, value string) bool { + return strings.Contains(value, substring) } // HasPrefix checks if 'str' starts with the specified 'prefix'. @@ -130,17 +130,17 @@ func (sr *StringsRegistry) Contains(substring string, str string) bool { // Parameters: // // prefix string - the prefix to check. -// str string - the string to check. +// value string - the string to check. // // Returns: // // bool - true if 'str' starts with 'prefix', false otherwise. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: hasPrefix]. // -// {{ "HelloWorld" | hasPrefix "Hello" }} // Output: true -func (sr *StringsRegistry) HasPrefix(prefix string, str string) bool { - return strings.HasPrefix(str, prefix) +// [Sprout Documentation: hasPrefix]: https://docs.atom.codes/sprout/registries/strings#hasprefix +func (sr *StringsRegistry) HasPrefix(prefix string, value string) bool { + return strings.HasPrefix(value, prefix) } // HasSuffix checks if 'str' ends with the specified 'suffix'. @@ -148,51 +148,51 @@ func (sr *StringsRegistry) HasPrefix(prefix string, str string) bool { // Parameters: // // suffix string - the suffix to check. -// str string - the string to check. +// value string - the string to check. // // Returns: // // bool - true if 'str' ends with 'suffix', false otherwise. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: hasSuffix]. // -// {{ "HelloWorld" | hasSuffix "World" }} // Output: true -func (sr *StringsRegistry) HasSuffix(suffix string, str string) bool { - return strings.HasSuffix(str, suffix) +// [Sprout Documentation: hasSuffix]: https://docs.atom.codes/sprout/registries/strings#hassuffix +func (sr *StringsRegistry) HasSuffix(suffix string, value string) bool { + return strings.HasSuffix(value, suffix) } // ToLower converts all characters in the provided string to lowercase. // // Parameters: // -// str string - the string to convert. +// value string - the string to convert. // // Returns: // // string - the lowercase version of the input string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toLower]. // -// {{ "HELLO WORLD" | toLower }} // Output: "hello world" -func (sr *StringsRegistry) ToLower(str string) string { - return strings.ToLower(str) +// [Sprout Documentation: toLower]: https://docs.atom.codes/sprout/registries/strings#tolower +func (sr *StringsRegistry) ToLower(value string) string { + return strings.ToLower(value) } // ToUpper converts all characters in the provided string to uppercase. // // Parameters: // -// str string - the string to convert. +// value string - the string to convert. // // Returns: // // string - the uppercase version of the input string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toUpper]. // -// {{ "hello world" | toUpper }} // Output: "HELLO WORLD" -func (sr *StringsRegistry) ToUpper(str string) string { - return strings.ToUpper(str) +// [Sprout Documentation: toUpper]: https://docs.atom.codes/sprout/registries/strings#toupper +func (sr *StringsRegistry) ToUpper(value string) string { + return strings.ToUpper(value) } // Replace replaces all occurrences of 'old' in 'src' with 'new'. @@ -201,17 +201,17 @@ func (sr *StringsRegistry) ToUpper(str string) string { // // old string - the substring to be replaced. // new string - the substring to replace with. -// src string - the source string where replacements take place. +// value string - the source string where replacements take place. // // Returns: // // string - the modified string after all replacements. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: replace]. // -// {{ "banana" | replace "a", "o" }} // Output: "bonono" -func (sr *StringsRegistry) Replace(old, new, src string) string { - return strings.ReplaceAll(src, old, new) +// [Sprout Documentation: replace]: https://docs.atom.codes/sprout/registries/strings#replace +func (sr *StringsRegistry) Replace(old, new, value string) string { + return strings.ReplaceAll(value, old, new) } // Repeat repeats the string 'str' for 'count' times. @@ -219,17 +219,17 @@ func (sr *StringsRegistry) Replace(old, new, src string) string { // Parameters: // // count int - the number of times to repeat. -// str string - the string to repeat. +// value string - the string to repeat. // // Returns: // // string - the repeated string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: repeat]. // -// {{ "ha" | repeat 3 }} // Output: "hahaha" -func (sr *StringsRegistry) Repeat(count int, str string) string { - return strings.Repeat(str, count) +// [Sprout Documentation: repeat]: https://docs.atom.codes/sprout/registries/strings#repeat +func (sr *StringsRegistry) Repeat(count int, value string) string { + return strings.Repeat(value, count) } // Join concatenates the elements of a slice into a single string separated by 'sep'. @@ -239,18 +239,17 @@ func (sr *StringsRegistry) Repeat(count int, str string) string { // Parameters: // // sep string - the separator string. -// v any - the slice to join, can be of any slice type. +// value any - the slice to join, can be of any slice type. // // Returns: // // string - the concatenated string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: join]. // -// {{ $list := slice "apple" "banana" "cherry" }} -// {{ $list | join ", " }} // Output: "apple, banana, cherry" -func (sr *StringsRegistry) Join(sep string, v any) string { - return strings.Join(helpers.StrSlice(v), sep) +// [Sprout Documentation: join]: https://docs.atom.codes/sprout/registries/strings#join +func (sr *StringsRegistry) Join(sep string, value any) string { + return strings.Join(helpers.StrSlice(value), sep) } // Trunc truncates 's' to a maximum length 'count'. If 'count' is negative, it removes @@ -260,49 +259,48 @@ func (sr *StringsRegistry) Join(sep string, v any) string { // // count int - the number of characters to keep. Negative values indicate truncation // from the beginning. -// str string - the string to truncate. +// value string - the string to truncate. // // Returns: // // string - the truncated string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: trunc]. // -// {{ "Hello World" | trunc 5 }} // Output: "Hello" -// {{ "Hello World" | trunc -5 }} // Output: "World" -func (sr *StringsRegistry) Trunc(count int, str string) string { - length := len(str) +// [Sprout Documentation: trunc]: https://docs.atom.codes/sprout/registries/strings#trunc +func (sr *StringsRegistry) Trunc(count int, value string) string { + length := len(value) if count < 0 && length+count > 0 { - return str[length+count:] + return value[length+count:] } if count >= 0 && length > count { - return str[:count] + return value[:count] } - return str + return value } // Shuffle randomly rearranges the characters in 'str'. // // Parameters: // -// str string - the string to shuffle. +// value string - the string to shuffle. // // Returns: // // string - the shuffled string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: shuffle]. // -// {{ "hello" | shuffle }} // Output: "loleh" (output may vary due to randomness) -func (sr *StringsRegistry) Shuffle(str string) string { - r := []rune(str) - mathrand.New(randSource).Shuffle(len(r), func(i, j int) { - r[i], r[j] = r[j], r[i] +// [Sprout Documentation: shuffle]: https://docs.atom.codes/sprout/registries/strings#shuffle +func (sr *StringsRegistry) Shuffle(value string) string { + runes := []rune(value) + mathrand.New(randSource).Shuffle(len(runes), func(i, j int) { + runes[i], runes[j] = runes[j], runes[i] }) - return string(r) + return string(runes) } // Ellipsis truncates 'str' to 'maxWidth' and appends an ellipsis if the string @@ -311,17 +309,17 @@ func (sr *StringsRegistry) Shuffle(str string) string { // Parameters: // // maxWidth int - the maximum width of the string including the ellipsis. -// str string - the string to truncate. +// value string - the string to truncate. // // Returns: // // string - the possibly truncated string with an ellipsis. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: ellipsis]. // -// {{ "Hello World" | ellipsis 10 }} // Output: "Hello W..." -func (sr *StringsRegistry) Ellipsis(maxWidth int, str string) string { - return sr.ellipsis(str, 0, maxWidth) +// [Sprout Documentation: ellipsis]: https://docs.atom.codes/sprout/registries/strings#ellipsis +func (sr *StringsRegistry) Ellipsis(maxWidth int, value string) string { + return sr.ellipsis(value, 0, maxWidth) } // EllipsisBoth truncates 'str' from both ends, preserving the middle part of @@ -331,17 +329,17 @@ func (sr *StringsRegistry) Ellipsis(maxWidth int, str string) string { // // offset int - starting position for preserving text. // maxWidth int - the total maximum width including ellipses. -// str string - the string to truncate. +// value string - the string to truncate. // // Returns: // // string - the truncated string with ellipses on both ends. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: ellipsisBoth]. // -// {{ "Hello World" | ellipsisBoth 1 10 }} // Output: "...lo Wor..." -func (sr *StringsRegistry) EllipsisBoth(offset int, maxWidth int, str string) string { - return sr.ellipsis(str, offset, maxWidth) +// [Sprout Documentation: ellipsisBoth]: https://docs.atom.codes/sprout/registries/strings#ellipsisboth +func (sr *StringsRegistry) EllipsisBoth(offset int, maxWidth int, value string) string { + return sr.ellipsis(value, offset, maxWidth) } // Initials extracts the initials from 'str', using optional 'delimiters' to @@ -349,18 +347,17 @@ func (sr *StringsRegistry) EllipsisBoth(offset int, maxWidth int, str string) st // // Parameters: // -// str string - the string from which to extract initials. -// delimiters string - optional string containing delimiter characters. +// value string - the string from which to extract initials. // // Returns: // // string - the initials of the words in 'str'. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: initials]. // -// {{ "John Doe" | initials }} // Output: "JD" -func (sr *StringsRegistry) Initials(str string) string { - return sr.initials(str, " ") +// [Sprout Documentation: initials]: https://docs.atom.codes/sprout/registries/strings#initials +func (sr *StringsRegistry) Initials(value string) string { + return sr.initials(value, " ") } // Plural returns 'one' if 'count' is 1, otherwise it returns 'many'. @@ -375,10 +372,9 @@ func (sr *StringsRegistry) Initials(str string) string { // // string - either 'one' or 'many' based on 'count'. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: plural]. // -// {{ 1 | plural "apple" "apples" }} // Output: "apple" -// {{ 2 | plural "apple" "apples" }} // Output: "apples" +// [Sprout Documentation: plural]: https://docs.atom.codes/sprout/registries/strings#plural func (sr *StringsRegistry) Plural(one, many string, count int) string { if count == 1 { return one @@ -386,66 +382,62 @@ func (sr *StringsRegistry) Plural(one, many string, count int) string { return many } -// Wrap breaks 'str' into lines with a maximum length of 'length'. +// Wrap breaks 'value' into lines with a maximum length of 'length'. // It ensures that words are not split across lines unless necessary. // // Parameters: // // length int - the maximum length of each line. -// str string - the string to be wrapped. +// value string - the string to be wrapped. // // Returns: // // string - the wrapped string using newline characters to separate lines. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: wrap]. // -// {{ "This is a long string that needs to be wrapped." | wrap 10 }} -// Output: "This is a\nlong\nstring\nthat needs\nto be\nwrapped." -func (sr *StringsRegistry) Wrap(length int, str string) string { - return sr.wordWrap(length, "", false, str) +// [Sprout Documentation: wrap]: https://docs.atom.codes/sprout/registries/strings#wrap +func (sr *StringsRegistry) Wrap(length int, value string) string { + return sr.wordWrap(length, "", false, value) } -// WrapWith breaks 'str' into lines of maximum 'length', using 'newLineCharacter' +// WrapWith breaks 'value' into lines of maximum 'length', using 'newLineCharacter' // to separate lines. It wraps words only when they exceed the line length. // // Parameters: // // length int - the maximum line length. // newLineCharacter string - the character(s) used to denote new lines. -// str string - the string to wrap. +// value string - the string to wrap. // // Returns: // // string - the wrapped string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: wrapWith]. // -// {{ "This is a long string that needs to be wrapped." | wrapWith 10 "
" }} -// Output: "This is a
long
string
that needs
to be
wrapped." -func (sr *StringsRegistry) WrapWith(length int, newLineCharacter string, str string) string { - return sr.wordWrap(length, newLineCharacter, true, str) +// [Sprout Documentation: wrapWith]: https://docs.atom.codes/sprout/registries/strings#wrapwith +func (sr *StringsRegistry) WrapWith(length int, newLineCharacter string, value string) string { + return sr.wordWrap(length, newLineCharacter, true, value) } -// Quote wraps each element in 'elements' with double quotes and separates them with spaces. +// Quote wraps each element in 'values' with double quotes and separates them with spaces. // // Parameters: // -// elements ...any - the elements to be quoted. +// values ...any - the elements to be quoted. // // Returns: // // string - a single string with each element double quoted. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: quote]. // -// {{ $list := slice "hello" "world" 123 }} -// {{ $list | quote }} -// Output: "hello" "world" "123" -func (sr *StringsRegistry) Quote(elements ...any) string { +// [Sprout Documentation: quote]: https://docs.atom.codes/sprout/registries/strings#quote +func (sr *StringsRegistry) Quote(values ...any) string { var build strings.Builder - for i, elem := range elements { + for i, elem := range values { if elem == nil { continue } @@ -457,24 +449,22 @@ func (sr *StringsRegistry) Quote(elements ...any) string { return build.String() } -// Squote wraps each element in 'elements' with single quotes and separates them with spaces. +// Squote wraps each element in 'values' with single quotes and separates them with spaces. // // Parameters: // -// elements ...any - the elements to be single quoted. +// values ...any - the elements to be single quoted. // // Returns: // // string - a single string with each element single quoted. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: squote]. // -// {{ $list := slice "hello" "world" 123 }} -// {{ $list | squote }} -// Output: 'hello' 'world' '123' -func (sr *StringsRegistry) Squote(elements ...any) string { +// [Sprout Documentation: squote]: https://docs.atom.codes/sprout/registries/strings#squote +func (sr *StringsRegistry) Squote(values ...any) string { var builder strings.Builder - for i, elem := range elements { + for i, elem := range values { if elem == nil { continue } @@ -493,24 +483,24 @@ func (sr *StringsRegistry) Squote(elements ...any) string { // // Parameters: // -// str string - the string to convert. +// value string - the string to convert. // // Returns: // // string - the string converted to camelCase. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toCamelCase]. // -// {{ "hello world" | toCamelCase }} // Output: "helloWorld" -func (sr *StringsRegistry) ToCamelCase(str string) string { - return sr.transformString(camelCaseStyle, str) +// [Sprout Documentation: toCamelCase]: https://docs.atom.codes/sprout/registries/strings#tocamelcase +func (sr *StringsRegistry) ToCamelCase(value string) string { + return sr.transformString(camelCaseStyle, value) } // ToKebabCase converts a string to kebab-case. // // Parameters: // -// str string - the string to convert. +// value string - the string to convert. // // Returns: // @@ -519,131 +509,129 @@ func (sr *StringsRegistry) ToCamelCase(str string) string { // Example: // // {{ "hello world" | toKebabCase }} // Output: "hello-world" -func (sr *StringsRegistry) ToKebabCase(str string) string { - return sr.transformString(kebabCaseStyle, str) +func (sr *StringsRegistry) ToKebabCase(value string) string { + return sr.transformString(kebabCaseStyle, value) } // ToPascalCase converts a string to PascalCase. // // Parameters: // -// str string - the string to convert. +// value string - the string to convert. // // Returns: // // string - the string converted to PascalCase. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toPascalCase]. // -// {{ "hello world" | toPascalCase }} // Output: "HelloWorld" -func (sr *StringsRegistry) ToPascalCase(str string) string { - return sr.transformString(pascalCaseStyle, str) +// [Sprout Documentation: toPascalCase]: https://docs.atom.codes/sprout/registries/strings#topascalcase +func (sr *StringsRegistry) ToPascalCase(value string) string { + return sr.transformString(pascalCaseStyle, value) } // ToDotCase converts a string to dot.case. // // Parameters: // -// str string - the string to convert. +// value string - the string to convert. // // Returns: // // string - the string converted to dot.case. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toDotCase]. // -// {{ "hello world" | toDotCase }} // Output: "hello.world" -func (sr *StringsRegistry) ToDotCase(str string) string { - return sr.transformString(dotCaseStyle, str) +// [Sprout Documentation: toDotCase]: https://docs.atom.codes/sprout/registries/strings#todotcase +func (sr *StringsRegistry) ToDotCase(value string) string { + return sr.transformString(dotCaseStyle, value) } // ToPathCase converts a string to path/case. // // Parameters: // -// str string - the string to convert. +// value string - the string to convert. // // Returns: // // string - the string converted to path/case. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toPathCase]. // -// {{ "hello world" | toPathCase }} // Output: "hello/world" -func (sr *StringsRegistry) ToPathCase(str string) string { - return sr.transformString(pathCaseStyle, str) +// [Sprout Documentation: toPathCase]: https://docs.atom.codes/sprout/registries/strings#topathcase +func (sr *StringsRegistry) ToPathCase(value string) string { + return sr.transformString(pathCaseStyle, value) } // ToConstantCase converts a string to CONSTANT_CASE. // // Parameters: // -// str string - the string to convert. +// value string - the string to convert. // // Returns: // -// string - the string converted to CONSTANT_CASE. +// For an example of this function in a Go template, refer to [Sprout Documentation: toConstantCase]. // -// Example: -// -// {{ "hello world" | toConstantCase }} // Output: "HELLO_WORLD" -func (sr *StringsRegistry) ToConstantCase(str string) string { - return sr.transformString(constantCaseStyle, str) +// [Sprout Documentation: toConstantCase]: https://docs.atom.codes/sprout/registries/strings#toconstantcase +func (sr *StringsRegistry) ToConstantCase(value string) string { + return sr.transformString(constantCaseStyle, value) } // ToSnakeCase converts a string to snake_case. // // Parameters: // -// str string - the string to convert. +// value string - the string to convert. // // Returns: // // string - the string converted to snake_case. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toSnakeCase]. // -// {{ "hello world" | toSnakeCase }} // Output: "hello_world" -func (sr *StringsRegistry) ToSnakeCase(str string) string { - return sr.transformString(snakeCaseStyle, str) +// [Sprout Documentation: toSnakeCase]: https://docs.atom.codes/sprout/registries/strings#tosnakecase +func (sr *StringsRegistry) ToSnakeCase(value string) string { + return sr.transformString(snakeCaseStyle, value) } // ToTitleCase converts a string to Title Case. // // Parameters: // -// str string - the string to convert. +// value string - the string to convert. // // Returns: // // string - the string converted to Title Case. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: toTitleCase]. // -// {{ "hello world" | toTitleCase }} // Output: "Hello World" -func (sr *StringsRegistry) ToTitleCase(str string) string { - return cases.Title(language.English).String(str) +// [Sprout Documentation: toTitleCase]: https://docs.atom.codes/sprout/registries/strings#totitlecase +func (sr *StringsRegistry) ToTitleCase(value string) string { + return cases.Title(language.English).String(value) } // Untitle converts the first letter of each word in 'str' to lowercase. // // Parameters: // -// str string - the string to be converted. +// value string - the string to be converted. // // Returns: // // string - the converted string with each word starting in lowercase. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: untitle]. // -// {{ "Hello World" | untitle }} // Output: "hello world" -func (sr *StringsRegistry) Untitle(str string) string { +// [Sprout Documentation: untitle]: https://docs.atom.codes/sprout/registries/strings#untitle +func (sr *StringsRegistry) Untitle(value string) string { var result strings.Builder // Process each rune in the input string startOfWord := true - for _, r := range str { + for _, r := range value { if unicode.IsSpace(r) { startOfWord = true result.WriteRune(r) @@ -660,100 +648,100 @@ func (sr *StringsRegistry) Untitle(str string) string { return result.String() } -// SwapCase switches the case of each letter in 'str'. Lowercase letters become +// SwapCase switches the case of each letter in 'value'. Lowercase letters become // uppercase and vice versa. // // Parameters: // -// str string - the string to convert. +// value string - the string to convert. // // Returns: // // string - the string with each character's case switched. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: swapCase]. // -// {{ "Hello World" | swapCase }} // Output: "hELLO wORLD" -func (sr *StringsRegistry) SwapCase(str string) string { +// [Sprout Documentation: swapCase]: https://docs.atom.codes/sprout/registries/strings#swapcase +func (sr *StringsRegistry) SwapCase(value string) string { return strings.Map(func(r rune) rune { if unicode.IsLower(r) { return unicode.ToUpper(r) } return unicode.ToLower(r) - }, str) + }, value) } -// Capitalize capitalizes the first letter of 'str'. +// Capitalize capitalizes the first letter of 'value'. // // Parameters: // -// str string - the string to capitalize. +// value string - the string to capitalize. // // Returns: // // string - the string with the first letter capitalized. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: capitalize]. // -// {{ "hello world" | capitalize }} // Output: "Hello world" -func (sr *StringsRegistry) Capitalize(str string) string { - return swapFirstLetter(str, true) +// [Sprout Documentation: capitalize]: https://docs.atom.codes/sprout/registries/strings#capitalize +func (sr *StringsRegistry) Capitalize(value string) string { + return swapFirstLetter(value, true) } -// Uncapitalize converts the first letter of 'str' to lowercase. +// Uncapitalize converts the first letter of 'value' to lowercase. // // Parameters: // -// str string - the string to uncapitalize. +// value string - the string to uncapitalize. // // Returns: // // string - the string with the first letter in lowercase. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: uncapitalize]. // -// {{ "Hello World" | uncapitalize }} // Output: "hello World" -func (sr *StringsRegistry) Uncapitalize(str string) string { - return swapFirstLetter(str, false) +// [Sprout Documentation: uncapitalize]: https://docs.atom.codes/sprout/registries/strings#uncapitalize +func (sr *StringsRegistry) Uncapitalize(value string) string { + return swapFirstLetter(value, false) } -// Split divides 'orig' into a map of string parts using 'sep' as the separator. +// Split divides 'value' into a map of string parts using 'sep' as the separator. // // Parameters: // // sep string - the separator string. -// orig string - the original string to split. +// value string - the original string to split. // // Returns: // // map[string]string - a map of the split parts. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: split]. // -// {{ "apple,banana,cherry" | split "," }} // Output: { "_0":"apple", "_1":"banana", "_2":"cherry" } -func (sr *StringsRegistry) Split(sep, str string) map[string]string { - parts := strings.Split(str, sep) +// [Sprout Documentation: split]: https://docs.atom.codes/sprout/registries/strings#split +func (sr *StringsRegistry) Split(sep, value string) map[string]string { + parts := strings.Split(value, sep) return sr.populateMapWithParts(parts) } -// Splitn divides 'orig' into a map of string parts using 'sep' as the separator +// Splitn divides 'value' into a map of string parts using 'sep' as the separator // up to 'n' parts. // // Parameters: // // sep string - the separator string. // n int - the maximum number of substrings to return. -// orig string - the original string to split. +// value string - the original string to split. // // Returns: // // map[string]string - a map of the split parts. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: splitn]. // -// {{ "apple,banana,cherry" | split "," 2 }} // Output: { "_0":"apple", "_1":"banana,cherry" } -func (sr *StringsRegistry) Splitn(sep string, n int, str string) map[string]string { - parts := strings.SplitN(str, sep, n) +// [Sprout Documentation: splitn]: https://docs.atom.codes/sprout/registries/strings#splitn +func (sr *StringsRegistry) Splitn(sep string, n int, value string) map[string]string { + parts := strings.SplitN(value, sep, n) return sr.populateMapWithParts(parts) } @@ -765,17 +753,17 @@ func (sr *StringsRegistry) Splitn(sep string, n int, str string) map[string]stri // // start int - the starting index. // end int - the ending index, exclusive. -// str string - the source string. +// value string - the source string. // // Returns: // // string - the extracted substring. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: substr]. // -// {{ "Hello World" | substring 0 5 }} // Output: "Hello" -func (sr *StringsRegistry) Substring(start, end int, str string) string { - length := len(str) +// [Sprout Documentation: substr]: https://docs.atom.codes/sprout/registries/strings#substr +func (sr *StringsRegistry) Substring(start, end int, value string) string { + length := len(value) if start < 0 { start = length + start @@ -792,27 +780,27 @@ func (sr *StringsRegistry) Substring(start, end int, str string) string { if start > end { return "" } - return str[start:end] + return value[start:end] } -// Indent adds spaces to the beginning of each line in 'str'. +// Indent adds spaces to the beginning of each line in 'value'. // // Parameters: // // spaces int - the number of spaces to add. -// str string - the string to indent. +// value string - the string to indent. // // Returns: // // string - the indented string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: indent]. // -// {{ "Hello\nWorld" | indent 4 }} // Output: " Hello\n World" -func (sr *StringsRegistry) Indent(spaces int, str string) string { +// [Sprout Documentation: indent]: https://docs.atom.codes/sprout/registries/strings#indent +func (sr *StringsRegistry) Indent(spaces int, value string) string { var builder strings.Builder pad := strings.Repeat(" ", spaces) - lines := strings.Split(str, "\n") + lines := strings.Split(value, "\n") for i, line := range lines { if i > 0 { @@ -830,16 +818,17 @@ func (sr *StringsRegistry) Indent(spaces int, str string) string { // // Parameters: // spaces int - the number of spaces to add after the newline. -// str string - the string to indent. +// value string - the string to indent. // // Returns: // string - the indented string with a newline at the start. // -// Example: -// {{ "Hello\nWorld" | nindent 4 }} // Output: "\n Hello\n World" +// For an example of this function in a Go template, refer to [Sprout Documentation: nindent]. +// +// [Sprout Documentation: nindent]: https://docs.atom.codes/sprout/registries/strings#nindent -func (sr *StringsRegistry) Nindent(spaces int, str string) string { - return "\n" + sr.Indent(spaces, str) +func (sr *StringsRegistry) Nindent(spaces int, value string) string { + return "\n" + sr.Indent(spaces, value) } // Seq generates a sequence of numbers as a string. It can take 0, 1, 2, or 3 @@ -854,9 +843,9 @@ func (sr *StringsRegistry) Nindent(spaces int, str string) string { // // string - a space-separated string of numbers in the sequence. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: seq]. // -// {{ seq 1, 2, 10 }} // Output: "1 3 5 7 9" +// [Sprout Documentation: seq]: https://docs.atom.codes/sprout/registries/strings#seq func (sr *StringsRegistry) Seq(params ...int) string { increment := 1 switch len(params) { diff --git a/registry/strings/helpers.go b/registry/strings/helpers.go index be342d5..70827e6 100644 --- a/registry/strings/helpers.go +++ b/registry/strings/helpers.go @@ -7,31 +7,31 @@ import ( "unicode/utf8" ) -// ellipsis truncates 'str' from both ends, preserving the middle part of +// ellipsis truncates 'value' from both ends, preserving the middle part of // the string and appending ellipses to both ends if needed. // // Parameters: // // offset int - starting position for preserving text. // maxWidth int - the maximum width of the string including the ellipsis. -// str string - the string to truncate. +// value string - the string to truncate. // // Returns: // // string - the possibly truncated string with an ellipsis. -func (sr *StringsRegistry) ellipsis(str string, offset int, maxWidth int) string { +func (sr *StringsRegistry) ellipsis(value string, offset int, maxWidth int) string { ellipsis := "..." // Return the original string if maxWidth is less than 4, or the offset // create exclusive dot string, it's not possible to add an ellipsis. if maxWidth < 4 || offset > 0 && maxWidth < 7 { - return str + return value } - runeCount := utf8.RuneCountInString(str) + runeCount := utf8.RuneCountInString(value) // If the string doesn't need trimming, return it as is. if runeCount <= maxWidth || runeCount <= offset { - return str[offset:] + return value[offset:] } // Determine end position for the substring, ensuring room for the ellipsis. @@ -41,7 +41,7 @@ func (sr *StringsRegistry) ellipsis(str string, offset int, maxWidth int) string } // Convert the string to a slice of runes to properly handle multi-byte characters. - runes := []rune(str) + runes := []rune(value) // Return the substring with an ellipsis, directly constructing the string in the return statement. if offset > 0 { @@ -50,26 +50,26 @@ func (sr *StringsRegistry) ellipsis(str string, offset int, maxWidth int) string return string(runes[offset:endPos]) + ellipsis } -// initials extracts the initials from 'str', using 'delimiters' to determine +// initials extracts the initials from 'value', using 'delimiters' to determine // word boundaries. // // Parameters: // -// str string - the string from which to extract initials. +// value string - the string from which to extract initials. // delimiters string - the string containing delimiter characters. // // Returns: // -// string - the initials of the words in 'str'. -func (sr *StringsRegistry) initials(str string, delimiters string) string { +// string - the initials of the words in 'value'. +func (sr *StringsRegistry) initials(value string, delimiters string) string { // Define a function to determine if a rune is a delimiter. isDelimiter := func(r rune) bool { return strings.ContainsRune(delimiters, r) } - words := strings.FieldsFunc(str, isDelimiter) + words := strings.FieldsFunc(value, isDelimiter) runes := make([]rune, len(words)) - for i, word := range strings.FieldsFunc(str, isDelimiter) { + for i, word := range strings.FieldsFunc(value, isDelimiter) { if i == 0 || unicode.IsLetter(rune(word[0])) { runes[i] = rune(word[0]) } @@ -78,7 +78,7 @@ func (sr *StringsRegistry) initials(str string, delimiters string) string { return string(runes) } -// transformString modifies the string 'str' based on various case styling rules +// transformString modifies the string 'value' based on various case styling rules // specified in the 'style' parameter. It can capitalize, lowercase, and insert // separators according to the rules provided. // @@ -87,31 +87,14 @@ func (sr *StringsRegistry) initials(str string, delimiters string) string { // style caseStyle - a struct specifying how to transform the string, including // capitalization rules, insertion of separators, and whether // to force lowercase. -// str string - the string to transform. +// value string - the string to transform. // // Returns: // // string - the transformed string. -// -// Example: -// -// style := caseStyle{ -// Separator: '_', -// CapitalizeNext: true, -// ForceLowercase: false, -// InsertSeparator: true, -// } -// transformed := sr.transformString(style, "hello world") -// Output: "Hello_World" -// -// Note: -// -// This example demonstrates how to use the function to capitalize the first letter of -// each word and insert underscores between words, which is common in identifiers like -// variable names in programming. -func (sr *StringsRegistry) transformString(style caseStyle, str string) string { +func (sr *StringsRegistry) transformString(style caseStyle, value string) string { var result strings.Builder - result.Grow(len(str) + 10) // Allocate a bit more for potential separators + result.Grow(len(value) + 10) // Allocate a bit more for potential separators capitalizeNext := style.CapitalizeNext var lastRune, lastLetter, nextRune rune = 0, 0, 0 @@ -120,9 +103,9 @@ func (sr *StringsRegistry) transformString(style caseStyle, str string) string { capitalizeNext = false } - for i, r := range str { - if i+1 < len(str) { - nextRune = rune(str[i+1]) + for i, r := range value { + if i+1 < len(value) { + nextRune = rune(value[i+1]) } if r == ' ' || r == '-' || r == '_' { @@ -178,12 +161,6 @@ func (sr *StringsRegistry) transformString(style caseStyle, str string) string { // Returns: // // map[string]string - a map where each key corresponds to an index (with an underscore prefix) of the string in the input array. -// -// Example: -// -// parts := []string{"apple", "banana", "cherry"} -// result := sr.populateMapWithParts(parts) -// fmt.Println(result) // Output: {"_0": "apple", "_1": "banana", "_2": "cherry"} func (sr *StringsRegistry) populateMapWithParts(parts []string) map[string]string { res := make(map[string]string, len(parts)) for i, v := range parts { @@ -203,22 +180,16 @@ func (sr *StringsRegistry) populateMapWithParts(parts []string) map[string]strin // Returns: // // string - the resulting string that concatenates all the integers in the array separated by the specified delimiter. -// -// Example: -// -// slice := []int{1, 2, 3, 4, 5} -// result := sr.convertIntArrayToString(slice, ", ") -// fmt.Println(result) // Output: "1, 2, 3, 4, 5" func (sr *StringsRegistry) convertIntArrayToString(slice []int, delimiter string) string { return strings.Trim(strings.Join(strings.Fields(fmt.Sprint(slice)), delimiter), "[]") } -// WordWrap formats 'str' into lines of maximum 'wrapLength', optionally wrapping +// WordWrap formats 'value' into lines of maximum 'wrapLength', optionally wrapping // long words and using 'newLineCharacter' for line breaks. // // Parameters: // -// str string - the string to wrap. +// value string - the string to wrap. // wrapLength int - the maximum length of each line. // newLineCharacter string - the string used to denote new lines. // wrapLongWords bool - true to wrap long words that exceed the line length. @@ -226,12 +197,7 @@ func (sr *StringsRegistry) convertIntArrayToString(slice []int, delimiter string // Returns: // // string - the wrapped string. -// -// Example: -// -// wrapped := sr.wordWrap(10, "\n", true, "This is a long wordwrap example") -// fmt.Println(wrapped) -func (sr *StringsRegistry) wordWrap(wrapLength int, newLineCharacter string, wrapLongWords bool, str string) string { +func (sr *StringsRegistry) wordWrap(wrapLength int, newLineCharacter string, wrapLongWords bool, value string) string { if wrapLength < 1 { wrapLength = 1 } @@ -242,7 +208,7 @@ func (sr *StringsRegistry) wordWrap(wrapLength int, newLineCharacter string, wra var resultBuilder strings.Builder var currentLineLength int - for _, word := range strings.Fields(str) { + for _, word := range strings.Fields(value) { wordLength := utf8.RuneCountInString(word) // If the word is too long and should be wrapped, or it fits in the remaining line length @@ -274,23 +240,18 @@ func (sr *StringsRegistry) wordWrap(wrapLength int, newLineCharacter string, wra return resultBuilder.String() } -// swapFirstLetter swaps the first letter of the string 'str' to uppercase or +// swapFirstLetter swaps the first letter of the string 'value' to uppercase or // lowercase. The casing is determined by the 'casing' parameter. // // Parameters: // -// str string - the string to modify. +// value string - the string to modify. // shouldUppercaseFirst bool - the casing to apply to the first letter. // // Returns: // // string - the modified string with the first letter in the desired casing. -// -// Example: -// -// result := sr.swapFirstLetter("123hello", cassingUpper) -// fmt.Println(result) // Output: "123Hello" -func swapFirstLetter(str string, shouldUppercase bool) string { +func swapFirstLetter(value string, shouldUppercase bool) string { var conditionFunc func(r rune) bool var updateFunc func(r rune) rune @@ -302,13 +263,13 @@ func swapFirstLetter(str string, shouldUppercase bool) string { updateFunc = unicode.ToLower } - buf := []byte(str) + buf := []byte(value) for i := 0; i < len(buf); { r, size := utf8.DecodeRune(buf[i:]) if unicode.IsLetter(r) { if conditionFunc(r) { - return str + return value } upperRune := updateFunc(r) @@ -319,5 +280,5 @@ func swapFirstLetter(str string, shouldUppercase bool) string { i += size } - return str + return value } diff --git a/registry/time/functions.go b/registry/time/functions.go index a3f63da..7e0ad2f 100644 --- a/registry/time/functions.go +++ b/registry/time/functions.go @@ -18,9 +18,9 @@ import ( // string - the formatted date. // error - when the timezone is invalid or the date is not in a valid format. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: date]. // -// {{ "2023-05-04T15:04:05Z" | date "Jan 2, 2006" }} // Output: "May 4, 2023" +// [Sprout Documentation: date]: https://docs.atom.codes/sprout/registries/time#date func (tr *TimeRegistry) Date(fmt string, date any) (string, error) { return tr.DateInZone(fmt, date, "Local") } @@ -38,12 +38,11 @@ func (tr *TimeRegistry) Date(fmt string, date any) (string, error) { // string - the formatted date. // error - when the timezone is invalid or the date is not in a valid format. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: dateInZone]. // -// {{ dateInZone "Jan 2, 2006", "2023-05-04T15:04:05Z", "UTC" }} // Output: "May 4, 2023" -// -// TODO: Change signature +// [Sprout Documentation: dateInZone]: https://docs.atom.codes/sprout/registries/time#dateinzone func (tr *TimeRegistry) DateInZone(fmt string, date any, zone string) (string, error) { + // TODO: Change signature var t time.Time switch date := date.(type) { default: @@ -78,9 +77,9 @@ func (tr *TimeRegistry) DateInZone(fmt string, date any, zone string) (string, e // // string - the human-readable duration. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: duration]. // -// {{ 3661 | duration }} // Output: "1h1m1s" +// [Sprout Documentation: duration]: https://docs.atom.codes/sprout/registries/time#duration func (tr *TimeRegistry) Duration(sec any) string { var n int64 switch value := sec.(type) { @@ -110,9 +109,9 @@ func (tr *TimeRegistry) Duration(sec any) string { // // string - a human-readable string describing how long ago the date was. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: dateAgo]. // -// {{ "2023-05-04T15:04:05Z" | dateAgo }} // Output: "4m" +// [Sprout Documentation: dateAgo]: https://docs.atom.codes/sprout/registries/time#dateago func (tr *TimeRegistry) DateAgo(date any) string { var t time.Time @@ -141,9 +140,9 @@ func (tr *TimeRegistry) DateAgo(date any) string { // // time.Time - the current time. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: now]. // -// {{ now }} // Output: "2023-05-07T15:04:05Z" +// [Sprout Documentation: now]: https://docs.atom.codes/sprout/registries/time#now func (tr *TimeRegistry) Now() time.Time { return time.Now() } @@ -158,9 +157,9 @@ func (tr *TimeRegistry) Now() time.Time { // // string - the Unix timestamp as a string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: unixEpoch]. // -// {{ now | unixEpoch }} // Output: "1683306245" +// [Sprout Documentation: unixEpoch]: https://docs.atom.codes/sprout/registries/time#unixepoch func (tr *TimeRegistry) UnixEpoch(date time.Time) string { return strconv.FormatInt(date.Unix(), 10) } @@ -169,16 +168,18 @@ func (tr *TimeRegistry) UnixEpoch(date time.Time) string { // format is incorrect, it returns an error. // // Parameters: -// fmt string - the duration string to add to the date, such as "2h" for two hours. -// date time.Time - the date to modify. +// +// fmt string - the duration string to add to the date, such as "2h" for two hours. +// date time.Time - the date to modify. // // Returns: -// time.Time - the modified date after adding the duration -// error - an error if the duration format is incorrect // -// Example: -// {{ "2024-05-04T15:04:05Z" | dateModify "48h" }} // Outputs the date two days later - +// time.Time - the modified date after adding the duration +// error - an error if the duration format is incorrect +// +// For an example of this function in a Go template, refer to [Sprout Documentation: dateModify]. +// +// [Sprout Documentation: dateModify]: https://docs.atom.codes/sprout/registries/time#datemodify func (tr *TimeRegistry) DateModify(fmt string, date time.Time) (time.Time, error) { d, err := time.ParseDuration(fmt) if err != nil { @@ -197,9 +198,9 @@ func (tr *TimeRegistry) DateModify(fmt string, date time.Time) (time.Time, error // // string - the rounded duration. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: durationRound]. // -// {{ "3600s" | durationRound }} // Output: "1h" +// [Sprout Documentation: durationRound]: https://docs.atom.codes/sprout/registries/time#durationround func (tr *TimeRegistry) DurationRound(duration any) string { var d time.Duration @@ -276,9 +277,9 @@ func (tr *TimeRegistry) DurationRound(duration any) string { // string - the formatted date in HTML format. // error - when the timezone is invalid or the date is not in a valid format. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: htmlDate]. // -// {{ "2023-05-04T15:04:05Z" | htmlDate }} // Output: "2023-05-04" +// [Sprout Documentation: htmlDate]: https://docs.atom.codes/sprout/registries/time#htmldate func (tr *TimeRegistry) HtmlDate(date any) (string, error) { return tr.DateInZone("2006-01-02", date, "Local") } @@ -295,11 +296,10 @@ func (tr *TimeRegistry) HtmlDate(date any) (string, error) { // string - the formatted date in HTML format. // error - when the timezone is invalid or the date is not in a valid format. // -// Example: -// -// {{ "2023-05-04T15:04:05Z", "UTC" | htmlDateInZone }} // Output: "2023-05-04" +// For an example of this function in a Go template, refer to [Sprout Documentation: htmlDateInZone]. // -// TODO: Change signature +// [Sprout Documentation: htmlDateInZone]: https://docs.atom.codes/sprout/registries/time#htmldateinzone func (tr *TimeRegistry) HtmlDateInZone(date any, zone string) (string, error) { + // TODO: Change signature return tr.DateInZone("2006-01-02", date, zone) } diff --git a/registry/uniqueid/functions.go b/registry/uniqueid/functions.go index 93dc3e4..3cc4174 100644 --- a/registry/uniqueid/functions.go +++ b/registry/uniqueid/functions.go @@ -12,9 +12,9 @@ import ( // // string - a new UUID string. // -// Example: +// For an example of this function in a Go template, refer to [Sprout Documentation: uuidv4]. // -// {{ uuidv4 }} // Output: "3f0c463e-53f5-4f05-a2ec-3c083aa8f937" +// [Sprout Documentation: uuidv4]: https://docs.atom.codes/sprout/registries/uniqueid#uuidv4 func (ur *UniqueIDRegistry) Uuidv4() string { return uuid.New().String() }