caps

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 30, 2023 License: MIT Imports: 6 Imported by: 6

README

caps is a case conversion library for go

Go Reference Latest Version GitHub go.mod Go version GoReportCard Codecov Build Status

caps is a unicode aware, case conversion library for Go.

Supported Case Conversions

The following case conversions are available:

  • Camel Case (e.g. CamelCase)
  • Lower Camel Case (e.g. lowerCamelCase)
  • Snake Case (e.g. snake_case)
  • Screaming Snake Case (e.g. SCREAMING_SNAKE_CASE)
  • Kebab Case (e.g. kebab-case)
  • Screaming Kebab Case(e.g. SCREAMING-KEBAB-CASE)
  • Dot Notation Case (e.g. dot.notation.case)
  • Screaming Dot Notation Case (e.g. DOT.NOTATION.CASE)
  • Title Case (e.g. Title Case)
  • Other deliminations

Install

go get github.com/chanced/caps

Example

package main

import (
	"fmt"
	"github.com/chanced/caps"
)
func main() {
	fmt.Println(caps.ToCamel("http request"))
	// Output:
	// HTTPRequest
	fmt.Println(caps.ToLowerCamel("some_id"))
	// Output:
	// someID
	fmt.Println(caps.ToLowerCamel("SomeID", caps.WithReplaceStyleCamel()))
	// Output:
	// someId

	// Alternatively:
	capsJS := caps.New(caps.Config{
		AllowedSymbols: "$",
		ReplaceStyle:   caps.ReplaceStyleCamel,
	})
	fmt.Println(capsJS.ToCamel("SomeID"))
	// Output:
	// someId
}

go playground link

Word boundaries

Word boundaries are determined by the caps.Converter. The provided implementation, caps.StdConverter, delegates the boundary detection to caps.Tokenizer. The provided implementation, caps.StdTokenizer, uses the following rules:

  • The following characters are considered word breaks " _.!?:;$-(){}[]#@&+~" unless present in AllowedSymbols
  • Strings with all upper case characters are split by the above symbols or by numbers, unless the character is allowed in a number based on the following rules:
    • 'v' or 'V' followed by numbers
    • '.' before/after a number and only once
    • 'e' or 'E' if in the fractional part of a number and only once
    • '-', '+' if at the start and followed by either a number or '.' and a number or in the fractional part proceeded by 'e' or 'E'
    • additional rules can be added through the number rules (e.g. WithNumberRules)
    • NOTE: If '.', '+', '-' are not in the AllowedSymbols they are considered breaks even for numbers
  • When a string consists of both upper case and lower case letters, upper case letters are considered boundaries (e.g. "ThisVar" would be tokenized into ["This", "Var"])
  • When mixed with lower and upper case characters, sequences of upper case are broken up into token strings (e.g. "SomeID" would be tokenized into ["Some", "I", "D"]).
  • Replacement rules are then evaluated based on the token strings, which may combine them based on the rules below.

Replacements

caps.StdConverter also allows users to register caps.Replacements for initialism replacements. Each Replacement is indexed in a trie (see Index).

  • Multi-rune token strings are searched independently unless followed by a number (e.g. "ID", "UTF8").
  • Sequences of single rune token (e.g.["U", "U", "I", "D"]) are evaluated as a potential Replacement until a non-match is found or the sequence is broken by a token string with more than one rune.
Default replacements
{"Acl", "ACL"}
{"Api", "API"}
{"Ascii", "ASCII"}
{"Cpu", "CPU"}
{"Css", "CSS"}
{"Dns", "DNS"}
{"Eof", "EOF"}
{"Guid", "GUID"}
{"Html", "HTML"}
{"Http", "HTTP"}
{"Https", "HTTPS"}
{"Id", "ID"}
{"Ip", "IP"}
{"Json", "JSON"}
{"Lhs", "LHS"}
{"Qps", "QPS"}
{"Ram", "RAM"}
{"Rhs", "RHS"}
{"Rpc", "RPC"}
{"Sla", "SLA"}
{"Smtp", "SMTP"}
{"Sql", "SQL"}
{"Ssh", "SSH"}
{"Tcp", "TCP"}
{"Tls", "TLS"}
{"Ttl", "TTL"}
{"Udp", "UDP"}
{"Ui", "UI"}
{"Uid", "UID"}
{"Uuid", "UUID"}
{"Uri", "URI"}
{"Url", "URL"}
{"Utf8", "UTF8"}
{"Vm", "VM"}
{"Xml", "XML"}
{"Xmpp", "XMPP"}
{"Xsrf", "XSRF"}
{"Xss", "XSS"}

If you would like to add or remove entries from that list, you have a few options. See below.

Customizing the Converter

Using caps.Caps

This is likely your best option. You can create and utilize an instance of caps.Caps which has all of the conversions as methods:

package main

import (
	"fmt"

	"github.com/chanced/caps"
)

func main() {
	c := caps.New(caps.Config{
		Replacements: []caps.Replacement{
			{Camel: "Ex", Screaming: "EX"},
			// ... your replacements
		},
	})
	fmt.Println(c.ToCamel("some ex"))
	// Output:
	// SomeEX
}

go playground link

Creating isolated caps.StdConverter instances

You can pass a new instance of caps.StdConverter with a new set of caps.Replacement.

    package main
    import (
        "fmt"
        "github.com/chanced/caps"
        "github.com/chanced/caps/token"
    )
    func main() {
        replacements := []caps.Replacement{
            {"Ex", "EX" },
            // ... your replacements
        }
        converter := caps.NewConverter(replacements, caps.DefaultTokenizer, token.DefaultCaser)
        fmt.Println(caps.ToCamel("ex id", caps.WithConverter(converter)))
        // note: ID was not in the replacement list above
        // Output:
        // "EXId"
       fmt.Println(caps.ToCamel("ex id"))
        // Output:
        // ExID
    }

go playground link

Modifying the caps.DefaultConverter global

You can update caps.DefaultConverter. You should set it before you make any conversions. Otherwise, you'll need guard your usage of the library accordingly (e.g. a mutex).

package main

import (
	"fmt"

	"github.com/chanced/caps"
)

func main() {
	converter, _ := caps.DefaultConverter.(caps.StdConverter)
	converter.Set("Gcp", "GCP")
	fmt.Println(caps.ToCamel("some_gcp_var"))
	// Output:
	// SomeGCPVar
}

go playground link

Creating a custom caps.Converter

Finally, if you are so inclined, you can create your own caps.Converter. This could be as simple as implementing the single Convert method, calling caps.DefaultConverter.Convert, and then modifying the result.

package main
import (
    "fmt"
    "github.com/chanced/caps"
)
type MyConverter struct{}
func (MyConverter) Convert(req caps.ConvertRequest) string {
    res := caps.DefaultConverter.Convert(req)
    if req.Style.IsLowerCamel() && req.ReplaceStyle.IsCamel() && res == "id" {
        return "_id"
    }
    return res
}
func main() {
    fmt.Println(caps.ToLowerCamel("ID", caps.WithReplaceStyleCamel(), caps.WithConverter(MyConverter{})))
    // Output:
    // _id
}

go playground link

Support for special case unicode (e.g. Turkish, Azeri)

caps supports Turkish and Azeri through the token.Caser interface. It is satisfied by unicode.TurkishCase and unicode.AzeriCase. token.TurkishCaser and token.AzeriCaser are available as pointers to those variables (although you can use the unicode variables directly).

For example, to use Turkish, you would need to instantiate a few variables:

package main
import (
    "github.com/chanced/caps"
    "github.com/chanced/caps/token"

)
func main() {
    tokenizer := caps.NewTokenizer(caps.DEFAULT_DELIMITERS, token.TurkishCaser)
    // I suppose these would need to be specific to Turkish?
    // if not, you can just use caps.DefaultReplacements
    replacements := []caps.Replacement{
        { Camel: "Http", Screaming: "HTTP" }, // just an example
    }
    turkish := caps.NewConverter(replacements, tokenizer, token.TurkishCaser)

    // to use this as your default throughout your application
    // you can overwrite caps.DefaultConverter
    //
    // caps.DefaultConverter = turkish
    //
    // otherwise, you can pass in the converter to the config for each call:
    fmt.Println(caps.ToScreamingKebab("i ı", caps.WithConverter(turkish)))
    // Output:
    // İ-I
}

go playground link

text pkg

The text package contains two types:

  • Text which has all of the case conversions and relevant functions from strings as methods.
  • Texts which is a sortable slice of Text with a few helper methods
package main

import (
	"fmt"
	"github.com/chanced/caps/text"
)

func main() {
	t := text.Text("Hello World")
	for _, p := range t.ToKebab().Split("-") {
		fmt.Println(p)
	}
	// Output:
	// hello
	// world
}

go playground link

Benchmarks

input: "Example Uuid."
goos: darwin
goarch: arm64
pkg: github.com/chanced/caps

Using a caps.Caps instance:

BenchmarkCapsToTitle
BenchmarkCapsToTitle-10                   	 2488982	       470.2 ns/op	     200 B/op	       8 allocs/op
BenchmarkCapsToCamel
BenchmarkCapsToCamel-10                   	 2474846	       467.8 ns/op	     200 B/op	       8 allocs/op
BenchmarkCapsToLowerCamel
BenchmarkCapsToLowerCamel-10              	 2650843	       451.0 ns/op	     200 B/op	       8 allocs/op
BenchmarkCapsToSnake
BenchmarkCapsToSnake-10                   	 2619945	       456.9 ns/op	     200 B/op	       8 allocs/op
BenchmarkCapsToScreamingSnake
BenchmarkCapsToScreamingSnake-10          	 2591302	       461.9 ns/op	     200 B/op	       8 allocs/op
BenchmarkCapsToKebab
BenchmarkCapsToKebab-10                   	 2621020	       457.0 ns/op	     200 B/op	       8 allocs/op
BenchmarkCapsToScreamingKebab
BenchmarkCapsToScreamingKebab-10          	 2593428	       466.3 ns/op	     200 B/op	       8 allocs/op
BenchmarkCapsToDotNotation
BenchmarkCapsToDotNotation-10             	 2575178	       463.0 ns/op	     200 B/op	       8 allocs/op
BenchmarkCapsToScreamingDotNotation
BenchmarkCapsToScreamingDotNotation-10    	 2526782	       472.8 ns/op	     200 B/op	       8 allocs/op

Using top-level functions:

BenchmarkToTitle
BenchmarkToTitle-10                       	 2316468	       519.1 ns/op	     200 B/op	       8 allocs/op
BenchmarkToCamel
BenchmarkToCamel-10                       	 2327542	       516.8 ns/op	     200 B/op	       8 allocs/op
BenchmarkToLowerCamel
BenchmarkToLowerCamel-10                  	 2372518	       505.3 ns/op	     200 B/op	       8 allocs/op
BenchmarkToSnake
BenchmarkToSnake-10                       	 2337992	       511.8 ns/op	     200 B/op	       8 allocs/op
BenchmarkToScreamingSnake
BenchmarkToScreamingSnake-10              	 2313232	       518.8 ns/op	     200 B/op	       8 allocs/op
BenchmarkToKebab
BenchmarkToKebab-10                       	 2333046	       513.7 ns/op	     200 B/op	       8 allocs/op
BenchmarkToScreamingKebab
BenchmarkToScreamingKebab-10              	 2274729	       521.3 ns/op	     200 B/op	       8 allocs/op
BenchmarkToDotNotation
BenchmarkToDotNotation-10                 	 2319278	       511.0 ns/op	     200 B/op	       8 allocs/op
BenchmarkToScreamingDotNotation
BenchmarkToScreamingDotNotation-10        	 2310217	       518.5 ns/op	     200 B/op	       8 allocs/op

License

MIT

Documentation

Overview

Package caps is a unicode aware case conversion library.

Index

Examples

Constants

View Source
const (
	// DEFAULT_DELIMITERS is the default set of delimiters in string convert.
	DEFAULT_DELIMITERS string = " _.!?:;$-(){}[]#@&+~"
)

Variables

View Source
var DefaultReplacements []Replacement = []Replacement{
	{"Acl", "ACL"},
	{"Api", "API"},
	{"Ascii", "ASCII"},
	{"Cpu", "CPU"},
	{"Css", "CSS"},
	{"Dns", "DNS"},
	{"Eof", "EOF"},
	{"Guid", "GUID"},
	{"Html", "HTML"},
	{"Http", "HTTP"},
	{"Https", "HTTPS"},
	{"Id", "ID"},
	{"Ip", "IP"},
	{"Json", "JSON"},
	{"Lhs", "LHS"},
	{"Qps", "QPS"},
	{"Ram", "RAM"},
	{"Rhs", "RHS"},
	{"Rpc", "RPC"},
	{"Sla", "SLA"},
	{"Smtp", "SMTP"},
	{"Sql", "SQL"},
	{"Ssh", "SSH"},
	{"Tcp", "TCP"},
	{"Tls", "TLS"},
	{"Ttl", "TTL"},
	{"Udp", "UDP"},
	{"Ui", "UI"},
	{"Uid", "UID"},
	{"Uuid", "UUID"},
	{"Uri", "URI"},
	{"Url", "URL"},
	{"Utf8", "UTF8"},
	{"Vm", "VM"},
	{"Xml", "XML"},
	{"Xmpp", "XMPP"},
	{"Xsrf", "XSRF"},
	{"Xss", "XSS"},
}

DefaultReplacements is the list of Replacements passed to DefaultConverter.

{"Acl", "ACL"},
{"Api", "API"},
{"Ascii", "ASCII"},
{"Cpu", "CPU"},
{"Css", "CSS"},
{"Dns", "DNS"},
{"Eof", "EOF"},
{"Guid", "GUID"},
{"Html", "HTML"},
{"Http", "HTTP"},
{"Https", "HTTPS"},
{"Id", "ID"},
{"Ip", "IP"},
{"Json", "JSON"},
{"Lhs", "LHS"},
{"Qps", "QPS"},
{"Ram", "RAM"},
{"Rhs", "RHS"},
{"Rpc", "RPC"},
{"Sla", "SLA"},
{"Smtp", "SMTP"},
{"Sql", "SQL"},
{"Ssh", "SSH"},
{"Tcp", "TCP"},
{"Tls", "TLS"},
{"Ttl", "TTL"},
{"Udp", "UDP"},
{"Ui", "UI"},
{"Uid", "UID"},
{"Uuid", "UUID"},
{"Uri", "URI"},
{"Url", "URL"},
{"Utf8", "UTF8"},
{"Vm", "VM"},
{"Xml", "XML"},
{"Xmpp", "XMPP"},
{"Xsrf", "XSRF"},
{"Xss", "XSS"},

Functions

func FormatToken

func FormatToken(caser token.Caser, style Style, index int, tok string) string

FormatToken formats the str with the desired style.

func LowerFirst

func LowerFirst[T ~string](str T) T

LowerFirst converts the first rune of str to lowercase.

func ToCamel

func ToCamel[T ~string](str T, options ...Opts) T

ToCamel transforms the case of str into Camel Case (e.g. AnExampleString) using either the provided Converter or the DefaultConverter otherwise.

The default Converter detects case so that "AN_EXAMPLE_STRING" becomes "AnExampleString". It also has a configurable set of replacements, such that "some_json" becomes "SomeJSON" so long as opts.ReplacementStyle is set to ReplaceStyleScreaming. A ReplaceStyle of ReplaceStyleCamel would result in "SomeJson".

caps.ToCamel("This is [an] {example}${id32}.") // ThisIsAnExampleID32
caps.ToCamel("AN_EXAMPLE_STRING", ) // AnExampleString
Example
package main

import (
	"fmt"

	"github.com/chanced/caps"
)

func main() {
	fmt.Println(caps.ToCamel("This is [an] {example}${id32}."))
	fmt.Println(caps.ToCamel("AN_EXAMPLE_STRING"))
}
Output:

ThisIsAnExampleID32
AnExampleString

func ToDelimited

func ToDelimited[T ~string](str T, delimiter string, lowercase bool, options ...Opts) T

ToDelimited transforms the case of str into a string separated by delimiter, using either the provided Converter or the DefaultConverter otherwise.

If lowercase is false, the output will be all uppercase.

See Options for more information on available configuration

Example

caps.ToDelimited("This is [an] {example}${id}.#32", ".", true) // this.is.an.example.id.32
caps.ToDelimited("This is [an] {example}${id}.break32", ".", false) // THIS.IS.AN.EXAMPLE.ID.BREAK.32
caps.ToDelimited("This is [an] {example}${id}.v32", ".", true, caps.Opts{AllowedSymbols: "$"}) // this.is.an.example.$.id.v32
Example
package main

import (
	"fmt"

	"github.com/chanced/caps"
)

func main() {
	fmt.Println(caps.ToDelimited("This is [an] {example}${id}.#32", ".", true))
	fmt.Println(caps.ToDelimited("This is [an] {example}${id}.break32", ".", false))
	fmt.Println(caps.ToDelimited("This is [an] {example}${id}.v32", ".", true, caps.Opts{AllowedSymbols: "$"}))

}
Output:

this.is.an.example.id.32
THIS.IS.AN.EXAMPLE.ID.BREAK.32
this.is.an.example.$.id.v32

func ToDotNotation added in v0.3.0

func ToDotNotation[T ~string](str T, options ...Opts) T

ToDotNotation transforms the case of str into Lower Dot Notation Case (e.g. an.example.string) using either the provided Converter or the DefaultConverter otherwise.

caps.ToDotNotation("This is [an] {example}${id32}.") // this.is.an.example.id.32
Example
package main

import (
	"fmt"

	"github.com/chanced/caps"
)

func main() {
	fmt.Println(caps.ToDotNotation("This is [an] {example}${id32}."))
}
Output:

this.is.an.example.id.32

func ToKebab

func ToKebab[T ~string](str T, options ...Opts) T

ToKebab transforms the case of str into Lower Kebab Case (e.g. an-example-string) using either the provided Converter or the DefaultConverter otherwise.

caps.ToKebab("This is [an] {example}${id32}.") // this-is-an-example-id-32
Example
package main

import (
	"fmt"

	"github.com/chanced/caps"
)

func main() {
	fmt.Println(caps.ToKebab("This is [an] {example}${id32}."))
}
Output:

this-is-an-example-id-32

func ToLower added in v0.2.3

func ToLower[T ~string](str T) T

ToLower returns s with all Unicode letters mapped to their lower case.

func ToLowerCamel

func ToLowerCamel[T ~string](str T, options ...Opts) T

ToLowerCamel transforms the case of str into Lower Camel Case (e.g. anExampleString) using either the provided Converter or the DefaultConverter otherwise.

The default Converter detects case so that "AN_EXAMPLE_STRING" becomes "anExampleString". It also has a configurable set of replacements, such that "some_json" becomes "someJSON" so long as opts.ReplacementStyle is set to ReplaceStyleScreaming. A ReplaceStyle of ReplaceStyleCamel would result in "someJson".

caps.ToLowerCamel("This is [an] {example}${id32}.") // thisIsAnExampleID32
Example
package main

import (
	"fmt"

	"github.com/chanced/caps"
)

func main() {
	fmt.Println(caps.ToLowerCamel("This is [an] {example}${id32}."))
	fmt.Println(caps.ToLowerCamel("entity id"))
	fmt.Println(caps.ToLowerCamel("entity id", caps.WithReplaceStyleCamel()))
}
Output:

thisIsAnExampleID32
entityID
entityId

func ToScreamingDotNotation added in v0.3.0

func ToScreamingDotNotation[T ~string](str T, options ...Opts) T

ToScreamingDotNotation transforms the case of str into Screaming Kebab Case (e.g. AN.EXAMPLE.STRING) using either the provided Converter or the DefaultConverter otherwise.

caps.ToScreamingDotNotation("This is [an] {example}${id32}.") // THIS.IS.AN.EXAMPLE.ID.32
Example
package main

import (
	"fmt"

	"github.com/chanced/caps"
)

func main() {
	fmt.Println(caps.ToScreamingDotNotation("This is [an] {example}${id32}."))
}
Output:

THIS.IS.AN.EXAMPLE.ID.32

func ToScreamingKebab

func ToScreamingKebab[T ~string](str T, options ...Opts) T

ToScreamingKebab transforms the case of str into Screaming Kebab Snake (e.g. AN-EXAMPLE-STRING) using either the provided Converter or the DefaultConverter otherwise.

caps.ToScreamingKebab("This is [an] {example}${id32}.") // THIS-IS-AN-EXAMPLE-ID-32
Example
package main

import (
	"fmt"

	"github.com/chanced/caps"
)

func main() {
	fmt.Println(caps.ToScreamingKebab("This is [an] {example}${id32}."))
}
Output:

THIS-IS-AN-EXAMPLE-ID-32

func ToScreamingSnake

func ToScreamingSnake[T ~string](str T, options ...Opts) T

ToScreamingSnake transforms the case of str into Screaming Snake Case (e.g. AN_EXAMPLE_STRING) using either the provided Converter or the DefaultConverter otherwise.

caps.ToScreamingSnake("This is [an] {example}${id32}.") // THIS_IS_AN_EXAMPLE_ID_32
Example
package main

import (
	"fmt"

	"github.com/chanced/caps"
)

func main() {
	fmt.Println(caps.ToScreamingSnake("This is [an] {example}${id32}."))
}
Output:

THIS_IS_AN_EXAMPLE_ID_32

func ToSnake

func ToSnake[T ~string](str T, options ...Opts) T

ToSnake transforms the case of str into Lower Snake Case (e.g. an_example_string) using either the provided Converter or the DefaultConverter otherwise.

caps.ToSnake("This is [an] {example}${id32}.") // this_is_an_example_id_32
Example
package main

import (
	"fmt"

	"github.com/chanced/caps"
)

func main() {
	fmt.Println(caps.ToSnake("This is [an] {example}${id32}."))
	fmt.Println(caps.ToSnake("v3.2.2"))
}
Output:

this_is_an_example_id_32
v3_2_2

func ToTitle

func ToTitle[T ~string](str T, options ...Opts) T

ToTitle transforms the case of str into Title Case (e.g. An Example String) using either the provided Converter or the DefaultConverter otherwise.

caps.ToTitle("This is [an] {example}${id32}.") // This Is An Example ID 32
Example
package main

import (
	"fmt"

	"github.com/chanced/caps"
)

func main() {
	fmt.Println(caps.ToTitle("This is [an] {example}${id32}."))
}
Output:

This Is An Example ID 32

func ToUpper added in v0.2.3

func ToUpper[T ~string](str T) T

ToUpper returns s with all Unicode letters mapped to their upper case.

func UpperFirst

func UpperFirst[T ~string](str T) T

UpperFirst converts the first rune of str to unicode upper case.

This method does not support special cases (such as Turkish and Azeri)

func WithoutNumbers

func WithoutNumbers[T ~string](s T) T

Without numbers returns the string with all numeric runes removed.

It does not currently use any logic to determine if a rune (e.g. '.') is part of a number. This may change in the future.

Types

type Caps added in v0.7.0

type Caps struct {
	// contains filtered or unexported fields
}

Caps provides configured case conversion methods.

func New added in v0.7.0

func New(options ...Config) Caps

New returns a new Caps instance with the provided options.

if caser is nil, token.DefaultCaser is used (which relies on the default unicode functions)

func (Caps) AllowedSymbols added in v0.7.0

func (c Caps) AllowedSymbols() string

AllowedSymbols returns the configured AllowedSymbols of c

func (Caps) Converter added in v0.7.5

func (c Caps) Converter() Converter

Converter returns the provided Converter of c

func (Caps) LowerFirst added in v0.7.0

func (c Caps) LowerFirst(str string) string

LowerFirst converts the first rune of str to lowercase.

func (Caps) NumberRules added in v0.7.0

func (c Caps) NumberRules() token.NumberRules

NumberRules returns the configured NumberRules of c

func (Caps) ReplaceStyle added in v0.7.0

func (c Caps) ReplaceStyle() ReplaceStyle

ReplaceStyle returns the configured ReplaceStyle of c

func (Caps) ToCamel added in v0.7.0

func (c Caps) ToCamel(str string) string

ToCamel transforms the case of str into Camel Case (e.g. AnExampleString) using either the provided Converter or the DefaultConverter otherwise.

The default Converter detects case so that "AN_EXAMPLE_STRING" becomes "AnExampleString". It also has a configurable set of replacements, such that "some_json" becomes "SomeJSON" so long as opts.ReplacementStyle is set to ReplaceStyleScreaming. A ReplaceStyle of ReplaceStyleCamel would result in "SomeJson".

caps.ToCamel("This is [an] {example}${id32}.") // ThisIsAnExampleID32
caps.ToCamel("AN_EXAMPLE_STRING", ) // AnExampleString

func (Caps) ToDelimited added in v0.7.0

func (c Caps) ToDelimited(str string, delimiter string, lowercase bool) string

ToDelimited transforms the case of str into a string separated by delimiter, using either the provided Converter or the DefaultConverter otherwise.

If lowercase is false, the output will be all uppercase.

See Options for more information on available configuration

Example

caps.ToDelimited("This is [an] {example}${id}.#32", ".", true) // this.is.an.example.id.32
caps.ToDelimited("This is [an] {example}${id}.break32", ".", false) // THIS.IS.AN.EXAMPLE.ID.BREAK.32
caps.ToDelimited("This is [an] {example}${id}.v32", ".", true, caps.Opts{AllowedSymbols: "$"}) // this.is.an.example.$.id.v32

func (Caps) ToDotNotation added in v0.7.0

func (c Caps) ToDotNotation(str string) string

ToDotNotation transforms the case of str into Lower Dot Notation Case (e.g. an.example.string) using either the provided Converter or the DefaultConverter otherwise.

caps.ToDotNotation("This is [an] {example}${id32}.") // this.is.an.example.id.32

func (Caps) ToKebab added in v0.7.0

func (c Caps) ToKebab(str string) string

ToKebab transforms the case of str into Lower Kebab Case (e.g. an-example-string) using either the provided Converter or the DefaultConverter otherwise.

caps.ToKebab("This is [an] {example}${id32}.") // this-is-an-example-id-32

func (Caps) ToLowerCamel added in v0.7.0

func (c Caps) ToLowerCamel(str string) string

ToLowerCamel transforms the case of str into Lower Camel Case (e.g. anExampleString) using either the provided Converter or the DefaultConverter otherwise.

The default Converter detects case so that "AN_EXAMPLE_STRING" becomes "anExampleString". It also has a configurable set of replacements, such that "some_json" becomes "someJSON" so long as opts.ReplacementStyle is set to ReplaceStyleScreaming. A ReplaceStyle of ReplaceStyleCamel would result in "someJson".

caps.ToLowerCamel("This is [an] {example}${id32}.") // thisIsAnExampleID32

func (Caps) ToScreamingDotNotation added in v0.7.0

func (c Caps) ToScreamingDotNotation(str string) string

ToScreamingDotNotation transforms the case of str into Screaming Kebab Case (e.g. AN.EXAMPLE.STRING) using either the provided Converter or the DefaultConverter otherwise.

caps.ToScreamingDotNotation("This is [an] {example}${id32}.") // THIS.IS.AN.EXAMPLE.ID.32

func (Caps) ToScreamingKebab added in v0.7.0

func (c Caps) ToScreamingKebab(str string) string

ToScreamingKebab transforms the case of str into Screaming Kebab Snake (e.g. AN-EXAMPLE-STRING) using either the provided Converter or the DefaultConverter otherwise.

caps.ToScreamingKebab("This is [an] {example}${id32}.") // THIS-IS-AN-EXAMPLE-ID-32

func (Caps) ToScreamingSnake added in v0.7.0

func (c Caps) ToScreamingSnake(str string) string

ToScreamingSnake transforms the case of str into Screaming Snake Case (e.g. AN_EXAMPLE_STRING) using either the provided Converter or the DefaultConverter otherwise.

caps.ToScreamingSnake("This is [an] {example}${id32}.") // THIS_IS_AN_EXAMPLE_ID_32

func (Caps) ToSnake added in v0.7.0

func (c Caps) ToSnake(str string) string

ToSnake transforms the case of str into Lower Snake Case (e.g. an_example_string) using either the provided Converter or the DefaultConverter otherwise.

caps.ToSnake("This is [an] {example}${id32}.") // this_is_an_example_id_32

func (Caps) ToTitle added in v0.7.0

func (c Caps) ToTitle(str string) string

ToTitle transforms the case of str into Title Case (e.g. An Example String) using either the provided Converter or the DefaultConverter otherwise.

caps.ToTitle("This is [an] {example}${id32}.") // This Is An Example ID 32

func (Caps) UpperFirst added in v0.7.0

func (c Caps) UpperFirst(str string) string

UpperFirst converts the first rune of str to unicode upper case.

This method does not support special cases (such as Turkish and Azeri)

func (Caps) WithoutNumbers added in v0.7.0

func (c Caps) WithoutNumbers(s string) string

Without numbers returns the string with all numeric runes removed.

It does not currently use any logic to determine if a rune (e.g. ".") is part of a number. This may change in the future.

type Config added in v0.7.6

type Config struct {
	// Any characters within this string will be allowed in the output.
	//
	// This does not affect delimiters (e.g. "_", "-", ".") as they are added
	// post-tokenization.
	//
	// Default:
	//  ""
	AllowedSymbols string
	// The Converter to use.
	//
	// Default:
	// 	A StdConverter with the Replacements, Caser, and Tokenizer.
	Converter Converter

	// If not set, this will be DefaultReplacements.
	Replacements []Replacement

	// ReplaceStyle overwrites the way words are replaced.
	//
	// A typical call to ToLowerCamel for "ServeJSON" with a Converter that
	// contains {"Json": "JSON"} would result in "serveJSON" by using the
	// ReplaceStyleScreaming variant. If ReplacementStyle was set to
	// ReplaceStyleCamel, on the call to ToLowerCamel then the result would
	// be "serveHttp".
	//
	// The default replacement style is dependent upon the target Style.
	ReplaceStyle ReplaceStyle
	// NumberRules are used by the DefaultTokenizer to augment the standard
	// rules for determining if a rune is part of a number.
	//
	// Note, if you add special characters here, they must be present in the
	// AllowedSymbols string for them to be part of the output.
	NumberRules token.NumberRules
	// Special unicode case rules.
	// See unicode.SpecialCase or token.Caser for more information.
	//
	// Default: token.DefaultCaser (which relies on the default unicode
	// functions)
	Caser token.Caser

	// If not set, uses StdTokenizer with the provided delimiters and token.Caser.
	Tokenizer Tokenizer
}

Config include configurable options for Caps instances.

See the documentation for the individual fields for more information.

type ConvertRequest added in v0.5.0

type ConvertRequest struct {
	Style          Style
	ReplaceStyle   ReplaceStyle
	Input          string
	Join           string
	AllowedSymbols string
	NumberRules    map[rune]func(index int, r rune, val string) bool
}

type Converter added in v0.2.0

type Converter interface {
	Convert(req ConvertRequest) string
}

Converter is an interface satisfied by types which can convert the case of a string.

ConverterImpl is provided as a default implementation. If you have edge cases which require custom formatting, you can implement your own Converter by wrapping ConverterImpl:

type MyConverter struct {}
func(MyConverter) Convert(style Style, repStyle ReplaceStyle, input string, join string, allowedSymbols []rune, numberRules map[rune]func(index int, r rune, val []rune) bool) string{
	formatted := caps.DefaultConverter.Convert(style, repStyle, input, join, allowedSymbols, numberRules)
	if formatted == "something_unusual" {
	  	return "replaced"
 	}
 	return formatted
}

Parameters

style:          Expected output caps.Style of the string.
repStyle:       The caps.ReplaceStyle to use if a word needs to be replaced.
join:           The delimiter to use when joining the words. For Camel, this is an empty string.
allowedSymbols: The set of allowed symbols. If set, these should take precedence over any delimiters
numberRules:    Any custom rules dictating how to handle special characters in numbers.

DefaultConverter is the default Converter instance.

type ConverterImpl deprecated added in v0.2.0

type ConverterImpl = StdConverter

Deprecated: Use StdConverter

type NumberRules added in v0.7.0

type NumberRules = token.NumberRules

type Opts

type Opts struct {
	// Any characters within this string will be allowed in the output.
	//
	// This does not affect delimiters (e.g. '_', '-', '.') as they are added
	// post-tokenization.
	//
	// Default:
	//  ""
	AllowedSymbols string
	// The Converter to use.
	//
	// Default:
	// 	DefaultConverter
	Converter Converter

	// ReplaceStyle overwrites the way Replacements are cased.
	//
	// A typical call to ToLowerCamel for "ServeJSON" with a Converter that
	// contains {"Json": "JSON"} would result in "serveJSON" by using the
	// ReplaceStyleScreaming variant. If ReplacementStyle was set to
	// ReplaceStyleCamel then a call to ToLowerCamel then the result would be
	// "serveHttp".
	//
	// The default ReplaceStyle is dependent upon the target Style.
	ReplaceStyle ReplaceStyle
	// NumberRules are used by the DefaultTokenizer to augment the standard
	// rules for determining if a rune is part of a number.
	//
	// Note, if you add special characters here, they must be present in the
	// AllowedSymbols string for them to be part of the output.
	NumberRules token.NumberRules
}

Opts include configurable options for case conversion.

See the documentation for the individual fields for more information.

func WithAllowedSymbols added in v0.7.5

func WithAllowedSymbols(symbols string) Opts

WithAllowedSymbols sets the AllowedSymbols to use

func WithConverter added in v0.4.1

func WithConverter(converter Converter) Opts

WithConverter sets the Converter to use

func WithNumberRules added in v0.4.1

func WithNumberRules(rules NumberRules) Opts

WithNumberRules sets the NumberRules to use

func WithReplaceStyle added in v0.4.1

func WithReplaceStyle(style ReplaceStyle) Opts

WithReplaceStyle sets the ReplaceStyle to use

There are also methods for each ReplaceStyle (e.g. WithReplaceStyleCamel)

func WithReplaceStyleCamel added in v0.4.1

func WithReplaceStyleCamel() Opts

WithReplaceStyleCamel indicates Replacements should use the Camel variant (e.g. "Json").

func WithReplaceStyleLower added in v0.4.1

func WithReplaceStyleLower() Opts

WithReplaceStyleLower indicates Replacements should use the lowercase variant (e.g. "json").

func WithReplaceStyleScreaming added in v0.4.1

func WithReplaceStyleScreaming() Opts

WithReplaceStyleScreaming indicates Replacements should use the screaming variant (e.g. "JSON").

type ReplaceStyle

type ReplaceStyle uint8

ReplaceStyle is used to indicate the case style that text should be transformed to when performing replacement in a Converter.

For example, a call to ToCamel with a ReplaceStyleScreaming with an input of "MarshalJson" will return "MarshaalJSON" while ReplaceStyleCamel would return "MarshalJson"

const (
	ReplaceStyleNotSpecified ReplaceStyle = iota
	ReplaceStyleCamel                     // Text should be replaced with the Camel variant (e.g. "Json").
	ReplaceStyleScreaming                 // Text should be replaced with the screaming variant (e.g. "JSON").
	ReplaceStyleLower                     // Text should be replaced with the lowercase variant (e.g. "json").
)

func (ReplaceStyle) IsCamel added in v0.5.1

func (rs ReplaceStyle) IsCamel() bool

IsCamel returns true if rs equals ReplaceStyleCamel

func (ReplaceStyle) IsLower added in v0.5.1

func (rs ReplaceStyle) IsLower() bool

IsLower returns true if rs equals ReplaceStyleLower

func (ReplaceStyle) IsScreaming added in v0.5.1

func (rs ReplaceStyle) IsScreaming() bool

IsScreaming returns true if rs equals ReplaceStyleScreaming

func (ReplaceStyle) String added in v0.7.5

func (rs ReplaceStyle) String() string

type Replacement

type Replacement struct {
	// Camel case variant of the word which should be replaced.
	// e.g. "Http"
	Camel string
	// Screaming (all upper case) representation of the word to replace.
	// e.g. "HTTP"
	Screaming string
}

type StdConverter added in v0.4.9

type StdConverter struct {
	// contains filtered or unexported fields
}

StdConverter contains a table of words to their desired replacement. Tokens will be compared against the keys of this table to determine if the string should be replaced with the value of the table.

This is primarily designed for acronyms but it could be used for other purposes.

The default Replacements can be found in the DefaultReplacements variable.

func NewConverter added in v0.2.0

func NewConverter(replacements []Replacement, tokenizer Tokenizer, caser token.Caser) StdConverter

NewConverter creates a new Converter which is used to convert the input text to the desired output.

replacements are used to make replacements of tokens to the specified formatting (e.g. { "Json", "JSON"}).

tokenizer is used to tokenize the input text.

func (StdConverter) Contains added in v0.4.9

func (sc StdConverter) Contains(key string) bool

Contains reports whether a key is in the Converter's replacement table.

func (StdConverter) Convert added in v0.4.9

func (sc StdConverter) Convert(req ConvertRequest) string

Convert formats the string with the desired style.

func (*StdConverter) Delete added in v0.4.9

func (sc *StdConverter) Delete(key string)

Remove deletes the key from the map. Either variant is sufficient.

func (StdConverter) Index added in v0.4.9

func (sc StdConverter) Index() index.Index

func (StdConverter) Replacements added in v0.4.9

func (sc StdConverter) Replacements() []Replacement

Replacements returns a slice of Replacement in the lookup trie.

func (*StdConverter) Set added in v0.4.9

func (sc *StdConverter) Set(key, value string)

Set adds the key/value pair to the table.

type StdTokenizer added in v0.4.9

type StdTokenizer struct {
	// contains filtered or unexported fields
}

StdTokenizer is the provided implementation of the Tokenizer interface.

StdTokenizer tokenizes the input text into token.Tokens based on a set of delimiters (runes).

If you need custom logic, consider wrapping the logic by implementing Tokenizer and then calling a StdTokenizer's Tokenize method.

Example:

DefaultTokenizer is the default Tokenizer.

func NewTokenizer

func NewTokenizer(delimiters string, caser token.Caser) StdTokenizer

NewTokenizer creates and returns a new TokenizerImpl which implements the Tokenizer interface.

Tokenizers are used by ConverterImpl to tokenize the input text into token.Tokens that are then formatted.

func (StdTokenizer) Tokenize added in v0.4.9

func (ti StdTokenizer) Tokenize(str string, allowedSymbols string, numberRules NumberRules) []string

Tokenize splits a string into a list of token.Tokens based on the case of each rune, it's delimiters, and the specified allowedSymbols.

For example:

t.Tokenize("ASnakecaseVariable", nil) -> ["A", "Snakecase", "Variable"]

Tokenizer attempts to detect formatting, such that a screaming snakecase str will be inferred accordingly.

For example:

t.Tokenize("A_SCREAMING_SNAKECASE_VARIABLE", nil) -> ["A", "SCREAMING", "SNAKECASE", "VARIABLE"]

If allowedSymbols is not nil, then those symbols will be treated as non-delimiters even if they are in the delimiters list.

For example:

t := caps.token.Newizer("_")
t.Tokenize("A_SCREAMING_SNAKECASE_VARIABLE", []rune{'_'}) -> ["A_SCREAMING_SNAKECASE_VARIABLE"]

type Style

type Style uint8
const (
	StyleNotSpecified Style = iota
	StyleLower              // The output should be lowercase (e.g. "an_example")
	StyleScreaming          // The output should be screaming (e.g. "AN_EXAMPLE")
	StyleCamel              // The output should be camel case (e.g. "AnExample")
	StyleLowerCamel         // The output should be lower camel case (e.g. "anExample")
)

func (Style) IsCamel added in v0.5.1

func (s Style) IsCamel() bool

func (Style) IsLower added in v0.5.1

func (s Style) IsLower() bool

func (Style) IsLowerCamel added in v0.5.1

func (s Style) IsLowerCamel() bool

func (Style) IsScreaming added in v0.5.1

func (s Style) IsScreaming() bool

func (Style) String added in v0.7.5

func (s Style) String() string

type Tokenizer

type Tokenizer interface {
	Tokenize(value string, allowedSymbols string, numberRules NumberRules) []string
}

Tokenizer is an interface satisfied by tyeps which can

type TokenizerImpl deprecated

type TokenizerImpl = StdTokenizer

Deprecated: Use StdTokenizer.

Directories

Path Synopsis
Package index contains a trie index used by StdConverter to lookup Replacements.
Package index contains a trie index used by StdConverter to lookup Replacements.
Package text contains a single Text type with functions from caps and strings as methods.
Package text contains a single Text type with functions from caps and strings as methods.
Package token contains functions for working with a string as a token.
Package token contains functions for working with a string as a token.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL