stringutils

package module
v0.0.0-...-bf4fec3 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2024 License: MIT Imports: 17 Imported by: 21

README

String utilities for Golang. Nothing major. No rocket science.

This package has no external dependencies beyond the standard library.

Why this package exists:

  • A reluctance to use regular expressions in XML processing (they be slow).
  • XML allows both single and double quotes (and the code to process it can get very ugly):
    "A quoted string."
    'A quoted string.'
    <mytag myatt1="Ain't trip'd up" myatt2='by "weird" quoting'>
    

This package takes a liberal view towards trimming leading and trailing whitespace. Whitespace treatment is one of those very irritating things about XML.

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

Examples

Constants

View Source
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"
)
View Source
const PathSep = string(os.PathSeparator)

A token nod to Windoze compatibility.

Variables

View Source
var IndentationPrefix = "  "

IndentationPrefix is for all sorts of output. TODO Make it configurable.

View Source
var Rbg, Ybg, Gbg, Rfg, Yfg, Gfg func(...interface{}) string

Functions that are created via the library.

View Source
var Wfg, Blubg, Cyanbg func(...interface{}) string

Functions

func AddIndent

func AddIndent(in string, indentString string, nr int) string

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 B

func B(s string) []byte

B is just shorthand for converting a string to []byte, i.e.

... = []byte(s)

func ColorDemo

func ColorDemo()

ColorDemo can be run from anywhere anytime to see samples.

func ConcatAll

func ConcatAll(values ...string) string

ConcatAll concatenates all its (vargs) arguments into a new string. It uses a bytes.Buffer for efficiency.

func ConcatAllSpaced

func ConcatAllSpaced(values ...string) string

ConcatAllSpaced concatenates all its (vargs) arguments into a new string, with spaces inserted in-between 'em. It uses a bytes.Buffer for efficiency.

func DBSimple

func DBSimple() error

func DeleteEmptyStrings

func DeleteEmptyStrings(in []string) (out []string)

DeleteEmptyStrings returns the slice with any empty strings omitted.

func DirNameFromFileName

func DirNameFromFileName(path string, suffixToAdd string) (dirName string, usable bool)

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 ElideCWD

func ElideCWD(s string) string

func ElideHomeDir

func ElideHomeDir(s string) string

ElideHomeDir doesn't try to deal with a relative path that starts with "."

func Enslice

func Enslice(in string) []string

Enslice turns the string into a string slice of length 1.

func FilterStringsBySuffix

func FilterStringsBySuffix(inputs []string,
	okayExts []string) (OKoutputs []string)

func GetHomeDir

func GetHomeDir() string

GetHomeDir is a convenience function, and refers to the invoking user's home directory.

func GetIndent

func GetIndent(depth int) (pfx string)

GetIndent returns a string that has `depth` instances of the standard indent string (two spaces, unless otherwise modified).

func IndentWith

func IndentWith(prefix string, textquote string) string

func IsInSlice

func IsInSlice(s string, ss []string) (int, bool)

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

func IsInSliceIgnoreCase(s string, ss []string) bool

IsInSliceIgnoreCase is like IsInSlice but without case matching.

func IsXmlQuote

func IsXmlQuote(s string) bool

IsXmlQuote checks whether the string is either one single quote *or* one double quote.

func IsXmlQuoted

func IsXmlQuoted(txt string) bool

IsXmlQuoted checks whether the string is surrounded by either single quotes *or* double quotes.

func Ito09az

func Ito09az(i int) string

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

func LS_lh(fi fs.FileInfo, optPath string) string

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 MakeCSV

func MakeCSV(ss []string) string

func MakeQuotedCSV

func MakeQuotedCSV(ss []string) string

func MustXmlUnquote

func MustXmlUnquote(txt string) string

MustXmlUnquote removes either paired single quotes or paired double quotes. It panics if neither is found.

func NormalizeWhitespace

func NormalizeWhitespace(s string) string

NormalizeWhitespace replaces weird whitespace junk (including newlines) with spaces.

func Now

func Now() string

func NowAsYM

func NowAsYM() string

NowAsYM maps (reversibly) the current year+month to "YM".

func NowAsYMDHM

func NowAsYMDHM() string

NowAsYMDHM maps (reversibly) the current time to "YMDhm" (where m is minutes / 2).

func NowPlus

func NowPlus() string

func PadLeftToLen

func PadLeftToLen(str, pad string, lingth int) string

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

func PadRightToLen(str, pad string, lingth int) string

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

func ParseYamlMetadata(instr string) (map[string]interface{}, error)

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

func PrettifyISO(in string) string

PrettifyISO converts 2022-02-17T15:22:07+02:00 to 2022-02-17/15:22:07/+02

func SizeLS

func SizeLS(size int) string

func SplitOffFirstWord

func SplitOffFirstWord(in string) (string, string)

SplitOffFirstWord splits the input string around the first whitespace, as defined by `strings.Fields(..)`, which uses `unicode.IsSpace`.

func SplitOffQuotedToken

func SplitOffQuotedToken(in string) (string, string, error)

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 StringToBytes(s string) []byte

func StripDelimiters

func StripDelimiters(in string, delims string, must bool) (string, error)

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

func StripQuotes(in string, must bool) (out string, success bool)

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 Tildotted

func Tildotted(s string) string

Tildotted shortens a filepath by substituting "~" or ".".

func TrimMatchingDelims

func TrimMatchingDelims(txt string, delim string) (string, error)

TrimMatchingDelims tried to strip off matching first and last characters. It is basically a simplified version of `StripDelimiters(..)`.

func TrimMatchingQuotes

func TrimMatchingQuotes(s string) (string, error)

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

func TrimYamlMetadataDelimiters(s string) string

TrimYamlMetadataDelimiters supplies a trailing newline.

func TruncateTo

func TruncateTo(in string, outmaxlen int) string

TruncateTo truncates & ends the string with triple dots if it's too long.

func YamlMetadataHeaderRange

func YamlMetadataHeaderRange(s string) (int, error)

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

func Yn(b bool) string

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

type PropSet map[string]string

func GetYamlMetadataAsPropSet

func GetYamlMetadataAsPropSet(instr string) (PropSet, error)

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

type StringChainger func(string) string

StringChainger is a func that is String In, String out, and therefore chainable.

type Stringser

type Stringser interface {
	Echo() string
	Info() string
	Debug() string
}

type Stringstack

type Stringstack []string

Stringstack is a LIFO stack for strings.

func (Stringstack) IsEmpty

func (ss Stringstack) IsEmpty() bool

IsEmpty is a no-brainer.

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.

func (*Stringstack) Push

func (ss *Stringstack) Push(s string)

Push might reslice the stack.

Jump to

Keyboard shortcuts

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