Documentation ¶
Overview ¶
Package stringutils does string things, and does not use any logging.
This package does not use regular expressions anywhere. Also, this package accommodates XML string quoting conventions by allowing the use of either single quotes or double quotes.
For functions that return a string or two plus a possibly-nil error, they can be wrapped in functions Must(..) or Must2(..), respectively, which either return successfully or a panic.
Index ¶
- Constants
- Variables
- func AddIndent(in string, indentString string, nr int) string
- func B(s string) []byte
- func ColorDemo()
- func ConcatAll(values ...string) string
- func ConcatAllSpaced(values ...string) string
- func DBSimple() error
- func DeleteEmptyStrings(in []string) (out []string)
- func DirNameFromFileName(path string, suffixToAdd string) (dirName string, usable bool)
- func ElideCWD(s string) string
- func ElideHomeDir(s string) string
- func Enslice(in string) []string
- func FilterStringsBySuffix(inputs []string, okayExts []string) (OKoutputs []string)
- func GetHomeDir() string
- func GetIndent(depth int) (pfx string)
- func IndentWith(prefix string, textquote string) string
- func IsInSlice(s string, ss []string) (int, bool)
- func IsInSliceIgnoreCase(s string, ss []string) bool
- func IsXmlQuote(s string) bool
- func IsXmlQuoted(txt string) bool
- func Ito09az(i int) string
- func LS_lh(fi fs.FileInfo, optPath string) string
- func MakeCSV(ss []string) string
- func MakeQuotedCSV(ss []string) string
- func MustXmlUnquote(txt string) string
- func NormalizeWhitespace(s string) string
- func Now() string
- func NowAsYM() string
- func NowAsYMDHM() string
- func NowPlus() string
- func PadLeftToLen(str, pad string, lingth int) string
- func PadRightToLen(str, pad string, lingth int) string
- func ParseYamlMetadata(instr string) (map[string]interface{}, error)
- func PrettifyISO(in string) string
- func SizeLS(size int) string
- func SplitOffFirstWord(in string) (string, string)
- func SplitOffQuotedToken(in string) (string, string, error)
- func StringToBytes(s string) []byte
- func StripDelimiters(in string, delims string, must bool) (string, error)
- func StripQuotes(in string, must bool) (out string, success bool)
- func Tildotted(s string) string
- func TrimMatchingDelims(txt string, delim string) (string, error)
- func TrimMatchingQuotes(s string) (string, error)
- func TrimYamlMetadataDelimiters(s string) string
- func TruncateTo(in string, outmaxlen int) string
- func YamlMetadataHeaderRange(s string) (int, error)
- func Yn(b bool) string
- type MarkupType
- type PropSet
- type Splitter
- type StringChainger
- type Stringser
- type Stringstack
Examples ¶
Constants ¶
const ( MU_type_UNK MarkupType = "UNK" // UNKNOWN // MU_type_XML is assumed to be well-formed MU_type_XML = "XML" // MU_type_HTML is assumed to be HTML5 MU_type_HTML = "HTML" // MU_type_MKDN is assumed to be CommonMark (or GFM?) MU_type_MKDN = "MKDN" // MU_type_BIN is opaque MU_type_BIN = "BIN" // MU_type_SQL is, well, hey why not eh MU_type_SQL = "SQL" // MU_type_DIRLIKE is a placeholder for consistent handling // (because of consistent problems in code): IsDirlike is // a more general case of IsDir() - shorthand for "is not // possible to have own content" - but this can be more // formally defined as "ia/has link(s) to other stuff" // - i.e. it is a directory or symbolic link. Used by // [ctoken.TypedRaw]. MU_type_DIRLIKE = "DIRLIKE" )
const PathSep = string(os.PathSeparator)
A token nod to Windoze compatibility.
Variables ¶
var IndentationPrefix = " "
IndentationPrefix is for all sorts of output. TODO Make it configurable.
var Rbg, Ybg, Gbg, Rfg, Yfg, Gfg func(...interface{}) string
Functions that are created via the library.
var Wfg, Blubg, Cyanbg func(...interface{}) string
Functions ¶
func AddIndent ¶
AddIndent prefixes `in` string with `nr` occurrences of `indentString`. Either string argument may be `""` i.e. empty. If `indentString` is the standard two (or whatever) spaces, use `GetIndent(..)` instead.
func ConcatAll ¶
ConcatAll concatenates all its (vargs) arguments into a new string. It uses a bytes.Buffer for efficiency.
func ConcatAllSpaced ¶
ConcatAllSpaced concatenates all its (vargs) arguments into a new string, with spaces inserted in-between 'em. It uses a bytes.Buffer for efficiency.
func DeleteEmptyStrings ¶
DeleteEmptyStrings returns the slice with any empty strings omitted.
func DirNameFromFileName ¶
DirNameFromFileName takes a file name and appends a specified suffix-to-add (like, say, "_xml") in order to create a directory that will hold files somehow related to the input file. NO period on suffix!
func ElideHomeDir ¶
ElideHomeDir doesn't try to deal with a relative path that starts with "."
func FilterStringsBySuffix ¶
func GetHomeDir ¶
func GetHomeDir() string
GetHomeDir is a convenience function, and refers to the invoking user's home directory.
func GetIndent ¶
GetIndent returns a string that has `depth` instances of the standard indent string (two spaces, unless otherwise modified).
func IndentWith ¶
func IsInSlice ¶
IsInSlice returns (`i,true`) if the string is found in the slice. It returns (`-1,false`) if not found (or an argument is bad).
func IsInSliceIgnoreCase ¶
IsInSliceIgnoreCase is like IsInSlice but without case matching.
func IsXmlQuote ¶
IsXmlQuote checks whether the string is either one single quote *or* one double quote.
func IsXmlQuoted ¶
IsXmlQuoted checks whether the string is surrounded by either single quotes *or* double quotes.
func Ito09az ¶
Ito09az converts its int arg (0..35) to a string of length one, in the range (for int 0..9) "0".."9", (for int 10..35) "a".."z"
func LS_lh ¶
LS_lh generates a file listing string like for "ls -l -h". If optPath is "" or "." then the file base name is taken from the FileInfo argument. .
func MakeQuotedCSV ¶
func MustXmlUnquote ¶
MustXmlUnquote removes either paired single quotes or paired double quotes. It panics if neither is found.
func NormalizeWhitespace ¶
NormalizeWhitespace replaces weird whitespace junk (including newlines) with spaces.
func NowAsYMDHM ¶
func NowAsYMDHM() string
NowAsYMDHM maps (reversibly) the current time to "YMDhm" (where m is minutes / 2).
func PadLeftToLen ¶
PadLeftToLen adds leading `pad` characters to hit the target length. Example: A new string 5 characters long, left-padded with spaces:
fmt.Println(PadLeftToLen("12", " ", 5)) // yields " 12"
func PadRightToLen ¶
PadRightToLen adds trailing `pad` characters to hit the target length.
Example: A new string 5 characters long, right-padded with zeros:
fmt.Println(PadRightToLen("12.", "0", 5)) // yields "12.00"
func ParseYamlMetadata ¶
ParseYamlMetadata tries to extract a YAML metadata block (YMB) - as a map - from the (start of the) input string `instring`.
Only simple fields are supported - no tree structure.
func PrettifyISO ¶
PrettifyISO converts 2022-02-17T15:22:07+02:00 to 2022-02-17/15:22:07/+02
func SplitOffFirstWord ¶
SplitOffFirstWord splits the input string around the first whitespace, as defined by `strings.Fields(..)`, which uses `unicode.IsSpace`.
func SplitOffQuotedToken ¶
SplitOffQuotedToken expects the string to start with an XML quote (i.e. either single quote or double quote); it splits off the entire quoted string, returned without the quotes, and the rest of the input string is returned in the other return value.
func StringToBytes ¶
func StripDelimiters ¶
StripDelimiters tries to remove corresponding characters from both ends of the input string; `must`==`true` makes it mandatory. From the resulting string, surrounding spaces get trimmed.
If `must`==`true`, it returns an error if the delimiters are not found. If `must`==`false`, an error is returned *iff* an argument was bad.
About the meaning of "corresponding": If `delimiters` is a single character (like a single or double quote), it tries to remove that character from both ends of the input string. If `delimiters` is two characters (like parentheses, braces, brackets), they are assumed to form a left/right pair, and so the ends of the input string are treated differently.
func StripQuotes ¶
StripQuotes tries to strip off matching XML quotes (i.e. either single or double quotes). `success` indicates whether matching quotes were found, and `must` makes the function fail if they are not found.
func TrimMatchingDelims ¶
TrimMatchingDelims tried to strip off matching first and last characters. It is basically a simplified version of `StripDelimiters(..)`.
func TrimMatchingQuotes ¶
TrimMatchingQuotes tries to strip off matching XML quotes (i.e. either single or double quotes). It is basically a simpliied version of `StripQuotes(..)`.
func TrimYamlMetadataDelimiters ¶
TrimYamlMetadataDelimiters supplies a trailing newline.
func TruncateTo ¶
TruncateTo truncates & ends the string with triple dots if it's too long.
func YamlMetadataHeaderRange ¶
YamlMetadataHeaderRange wants "---" at the start of the file at the start of a line (maybe after whitespace) to open the block, and "---" or "..." at the start of a new line to end the block. NOTE tho that the leading whitespace should already be trimmed away.
func Yn ¶
Yn returns (as a string) a single character, `Y` or `n`.
They are different case to improve readability, *duh!*
In a table, it can be even more readable to use "-" for false.
People who fill tables with `Y` and `N` (or 'y' and 'n') defeat simple visual scanning and are idiots. .
Example ¶
package main import ( "fmt" SU "github.com/fbaube/stringutils" ) func main() { fmt.Println(SU.Yn(true)) fmt.Println(SU.Yn(false)) }
Output: Y n
Types ¶
type MarkupType ¶
type MarkupType string
MarkupType specifies the top-level, most general type of content in a content entity: XML, HTML, Markdown, or BIN (binary, "none of the above").
There is also "Dirlike", for consistent handling of this field in a tree environment.
Note that altho HTML is "obviously" XML, HTML is separated out here because HTML5 doesn't have a really good definition (like DTD or XSD), and also because HTML has a dedicated parser in the Go std lib that is quite a bit more liberal than the XML parser.
MarkupType implements interface stringutils.Stringser.
NOTE that for source code that uses this enum, files can be named "*_xml.go", "*_html.go", "*_mkdn.go". .
func (MarkupType) Debug ¶
func (mt MarkupType) Debug() string
func (MarkupType) Echo ¶
func (mt MarkupType) Echo() string
func (MarkupType) Info ¶
func (mt MarkupType) Info() string
type PropSet ¶
func GetYamlMetadataAsPropSet ¶
GetYamlMetadataAsPropSet is a convenience function. It assume that all the metadata values are top-level and can be represented as strings. The metadata is unmarshalled into a map (i.e. a `PropSet`), so variables can be freely added, but there is no checking for required fields.
func YamlMapAsPropSet ¶
func YamlMapAsPropSet(u map[interface{}]interface{}) (ps PropSet)
YamlMapAsPropSet returns a PropSet, i.e. a map[string]string
type Splitter ¶
type Splitter interface { // TryToSplit is so named because "Try" // says, that it can fail and return `nil`. TryToSplit(s string) (ss []string) }
Splitter is a common pattern, but it has to be a method of a struct. So for example to split off a XML prolog, it is necessary to define an associated struct, which might as well be a new empty XmlProlog, in which case it could also be modified by the method, if it is implemented as a pointer receiver.
We could define it wherever the input and outputs are well defined: RawAttList => []RawAtt; RawAtt => name,"=",value; etc.
type StringChainger ¶
StringChainger is a func that is String In, String out, and therefore chainable.
type Stringstack ¶
type Stringstack []string
Stringstack is a LIFO stack for strings.
func (Stringstack) Peek ¶
func (ss Stringstack) Peek() string
Peek returns empty string ("") on an empty stack.
func (*Stringstack) Pop ¶
func (ss *Stringstack) Pop() string
Pop returns empty string ("") on an empty stack.
Source Files ¶
- asbytes.go
- colors.go
- concat.go
- dbsimple.go
- dirnamefromfilename.go
- doc.go
- elisions.go
- filter.go
- findinslice.go
- humanreadable.go
- indentwith.go
- ls-lh.go
- makecsv.go
- maps.go
- markuptype.go
- now.go
- paddings.go
- slicemisc.go
- splitoff.go
- splitter.go
- stringchainger.go
- stringser.go
- stringstack.go
- stringtobytes.go
- stripdelimiters.go
- time.go
- trimmatching.go
- xmlquotes.go
- yamlmetadata.go
- yntruth.go