stringutils

package module
v0.0.0-...-339670f Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2025 License: MIT Imports: 16 Imported by: 23

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 things with atrings.

Some notes about this package:

  • It does not use any logging.
  • It does not use regular expressions anywhere.
  • It 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

View Source
const PathSep = string(os.PathSeparator)

PathSep is 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

These are all functions that are created via the imported library color.

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 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 DeleteEmptyStrings

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

DeleteEmptyStrings returns the slice with any empty or all-whitespace strings deleted. It also compacts the slice, so element indices change.

func ElideCWD

func ElideCWD(s string) string

ElideCWD has effects that are session-specific, so it should only be used to make better user messages.

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 FilterStringList

func FilterStringList(inlist, prefixes, midfixes, suffixes []string) []string

FilterStringList filters out filenames that match simple patterns (prefixes, "midfixes", suffixes). We provide this instead of some regex nonsense.

func FilterStringsBySuffix

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

FilterStringsBySuffix takes a list of filenames and filters out those whose file extensions are not in the list that is passed in. NOTE:

  • No periods on the okay file extensions.
  • The comparison is case-INsensitive.
  • This func is not currently used anywhere (2025.01), but it's useful so leave it in anyways.

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 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.

NOTE that this func is not currently used, but it's left here anyways for its potential usabililty. .

func MakeCSV

func MakeCSV(ss []string) string

MakeCSV returns the string slice as a CSV string. A final (comma + space) is omitted.

func MakeQuotedCSV

func MakeQuotedCSV(ss []string) string

MakeQuotedCSV places double-quotes around the output of MakeCSV.

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

NowPlus returns the current local date+time in a sensible format, i.e. "2006-01-02-mon/15:04:05/-07".

BTW "T" in ISO date-times is horrible for readability; use "_" instead.

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 SplitOffFirstWord

func SplitOffFirstWord(in string) (string, string)

SplitOffFirstWord splits the input string around the first whitespace, as defined by func 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 a single quote or a double quote, but not any wrongly- named "smart quotes"); 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

StringToBytes uses both reflect and unsafe, so it's a bit of a turd.

func StripDelimiters

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

StripDelimiters tries to remove corresponding characters from both ends of the input string. From the resulting string, surrounding spaces get trimmed. If an error is returned, the original string is also returned.

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) (string, error)

StripQuotes tries to strip off matching XML quotes (i.e. either single or double quotes). From the resulting string, surrounding spaces get trimmed. If an error is returned, the original string is also returned.

func Tildotted

func Tildotted(s string) string

Tildotted shortens a filepath by ediding the current user's home directory, or the current working directory, by eliding "~" or "." respectively.

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 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. .

Types

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 Raw_type

type Raw_type D.SemanticFieldType
const (
	// Raw_type_BIN is opaque
	Raw_type_BIN Raw_type = Raw_type(D.SFT_BLOB_)
	// Raw_type_XML is assumed to be well-formed
	Raw_type_XML Raw_type = Raw_type(D.SFT_XTEXT)
	// Raw_type_HTML is assumed to be HTML5
	Raw_type_HTML Raw_type = Raw_type(D.SFT_HTEXT)
	// Raw_type_MKDN is assumed to be CommonMark (or GFM?)
	Raw_type_MKDN Raw_type = Raw_type(D.SFT_MTEXT)
	// Raw_type_SQL is, well, hey why not eh
	Raw_type_SQL Raw_type = Raw_type(D.SFT_QTEXT)
	// Raw_type_NIL is none (or too little) to figure out what kind
	Raw_type_NIL Raw_type = Raw_type(D.SFT_0TEXT)
	// Raw_type_DIRLIKE is a hack 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 "is/has link(s)
	// to other stuff" - i.e. it is a directory or symbolic link.
	// Used by [ctoken.TypedRaw].
	Raw_type_DIRLIKE Raw_type = "dirlk"
)

type StringChainger

type StringChainger func(string) string

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

NOTE this func is not currently used, but we keep it for possible future use.

type Stringser

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

Stringser is a handy interface for content. Echo reproduces the content, Info is a normal level of debuggery, and Debug should be verbose.

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