shims

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

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

Go to latest
Published: Mar 30, 2026 License: BSD-3-Clause-Clear Imports: 45 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OrderPermute = 0
	OrderRequire = 1
	OrderReturn  = 2
)

Ordering constants

Variables

View Source
var FindPruneError = os.ErrPermission // reuse as sentinel

FindPruneError is a sentinel error used to skip directories in Find.find.

Functions

func Abbrev

func Abbrev(words []string) map[string]string

Abbrev computes the set of unambiguous abbreviations for a list of strings. Given ["ruby", "rules"], returns {"rub" => "ruby", "ruby" => "ruby", "rul" => "rules", "rule" => "rules", "rules" => "rules"}.

func AppendNewline

func AppendNewline(s string) string

AppendNewline adds a trailing newline, matching Ruby's Base64.encode64 behavior.

func BenchmarkJobItem

func BenchmarkJobItem(label string, f func())

BenchmarkJobItem is a stub for Benchmark::Job#item.

func BenchmarkJobReport

func BenchmarkJobReport()

BenchmarkJobReport is a stub for Benchmark::Job#report.

func BenchmarkJobWidth

func BenchmarkJobWidth() int

BenchmarkJobWidth is a stub for Benchmark::Job#width.

func BenchmarkRealtime

func BenchmarkRealtime(f func()) float64

BenchmarkRealtime executes f and returns the elapsed wall-clock time in seconds. This mirrors Ruby's Benchmark.realtime { }.

func BenchmarkReportReport

func BenchmarkReportReport()

BenchmarkReportReport is a stub for Benchmark::Report#report.

func CurrentFile

func CurrentFile() string

CurrentFile returns the file path of the caller. Used for __dir__.

func CurrentMethodName

func CurrentMethodName() string

CurrentMethodName returns the name of the calling function. Used for __method__.

func DateAsctime

func DateAsctime(t time.Time) string

DateAsctime formats like ctime: "Mon Jan 2 00:00:00 2006".

func DateCWDay

func DateCWDay(t time.Time) int

DateCWDay returns the commercial week day (Monday=1..Sunday=7).

func DateCWYear

func DateCWYear(t time.Time) int

DateCWYear returns the ISO week-numbering year.

func DateCWeek

func DateCWeek(t time.Time) int

DateCWeek returns the ISO week number.

func DateCivil

func DateCivil(year, month, day int) time.Time

DateCivil creates a Date from year, month, day.

func DateDownto

func DateDownto(start, end time.Time, fn func(time.Time))

DateDownto iterates from start down to end, calling fn for each date.

func DateHttpdate

func DateHttpdate(t time.Time) string

DateHttpdate formats a date for HTTP headers.

func DateISO8601

func DateISO8601(str string) time.Time

DateISO8601 parses an ISO 8601 date string.

func DateISO8601Format

func DateISO8601Format(t time.Time) string

DateISO8601Format formats a date as ISO 8601.

func DateInspect

func DateInspect(t time.Time) string

DateInspect returns the inspect representation.

func DateIsLeapYear

func DateIsLeapYear(year int) bool

DateIsLeapYear is a class method version.

func DateJD

func DateJD(jd int) time.Time

DateJD creates a Date from a Julian day number.

func DateLeap

func DateLeap(t time.Time) bool

DateLeap returns whether the year is a leap year.

func DateNextDay

func DateNextDay(t time.Time, n int) time.Time

DateNextDay returns the date n days from now.

func DateNextMonth

func DateNextMonth(t time.Time, n int) time.Time

DateNextMonth returns the date n months from now.

func DateNextYear

func DateNextYear(t time.Time, n int) time.Time

DateNextYear returns the date n years from now.

func DateParse

func DateParse(str string) time.Time

DateParse parses a date string heuristically.

func DatePrevDay

func DatePrevDay(t time.Time, n int) time.Time

DatePrevDay returns the date n days ago.

func DatePrevMonth

func DatePrevMonth(t time.Time, n int) time.Time

DatePrevMonth returns the date n months ago.

func DatePrevYear

func DatePrevYear(t time.Time, n int) time.Time

DatePrevYear returns the date n years ago.

func DateRFC2822

func DateRFC2822(t time.Time) string

DateRFC2822 formats a date as RFC 2822.

func DateRFC3339

func DateRFC3339(t time.Time) string

DateRFC3339 formats a date as RFC 3339.

func DateShiftMonths

func DateShiftMonths(t time.Time, n int) time.Time

DateShiftMonths shifts by n months (Ruby's << and >> operators).

func DateStep

func DateStep(start, end time.Time, step int, fn func(time.Time))

DateStep iterates from start to end with step, calling fn for each date.

func DateStrftime

func DateStrftime(t time.Time, format string) string

DateStrftime formats a date using a Ruby strftime string.

func DateStrptime

func DateStrptime(str, format string) time.Time

DateStrptime parses a date with a specific format.

func DateToJD

func DateToJD(t time.Time) int

DateToJD converts a Date to Julian day number.

func DateToMJD

func DateToMJD(t time.Time) int

DateToMJD converts a Date to Modified Julian day number.

func DateToS

func DateToS(t time.Time) string

DateToS formats a date as "YYYY-MM-DD".

func DateToday

func DateToday() time.Time

DateToday returns today's date as a time.Time with zero time component.

func DateUpto

func DateUpto(start, end time.Time, fn func(time.Time))

DateUpto iterates from start to end, calling fn for each date.

func DigestConstMissing

func DigestConstMissing(name string) string

DigestConstMissing is a stub for Digest.const_missing. In Ruby this auto-requires algorithm modules; in Go all algorithms are available at import time.

func DigestHexencode

func DigestHexencode(data string) string

DigestHexencode encodes a binary string to hex (Digest.hexencode).

func DigestMD5Base64digest

func DigestMD5Base64digest(data string) string

func DigestMD5Digest

func DigestMD5Digest(data string) string

func DigestMD5File

func DigestMD5File(path string) string

func DigestMD5Hexdigest

func DigestMD5Hexdigest(data string) string

func DigestSHA1Base64digest

func DigestSHA1Base64digest(data string) string

func DigestSHA1Digest

func DigestSHA1Digest(data string) string

func DigestSHA1File

func DigestSHA1File(path string) string

func DigestSHA1Hexdigest

func DigestSHA1Hexdigest(data string) string

func DigestSHA256Base64digest

func DigestSHA256Base64digest(data string) string

func DigestSHA256Digest

func DigestSHA256Digest(data string) string

func DigestSHA256File

func DigestSHA256File(path string) string

func DigestSHA256Hexdigest

func DigestSHA256Hexdigest(data string) string

func DigestSHA384Base64digest

func DigestSHA384Base64digest(data string) string

func DigestSHA384Digest

func DigestSHA384Digest(data string) string

func DigestSHA384File

func DigestSHA384File(path string) string

func DigestSHA384Hexdigest

func DigestSHA384Hexdigest(data string) string

func DigestSHA512Base64digest

func DigestSHA512Base64digest(data string) string

func DigestSHA512Digest

func DigestSHA512Digest(data string) string

func DigestSHA512File

func DigestSHA512File(path string) string

func DigestSHA512Hexdigest

func DigestSHA512Hexdigest(data string) string

func DirChildren

func DirChildren(path string) []string

DirChildren returns entries of a directory without . and ..

func DirEmpty

func DirEmpty(path string) bool

DirEmpty returns true if a directory has no entries.

func DirEntries

func DirEntries(path string) []string

DirEntries returns the entries of a directory (like . and ..).

func DirExist

func DirExist(path string) bool

DirExist returns true if the path exists and is a directory.

func DirGlob

func DirGlob(pattern string) []string

DirGlob returns file paths matching a shell pattern.

func DirHome

func DirHome() string

DirHome returns the current user's home directory.

func DirMktmpdir

func DirMktmpdir(prefix string) string

DirMktmpdir creates a temporary directory with the given prefix and returns its path.

func DirPwd

func DirPwd() string

DirPwd returns the current working directory.

func ERBVersion

func ERBVersion() string

ERBVersion returns the ERB version string.

func EnvDelete

func EnvDelete(key string) string

EnvDelete removes an environment variable and returns its previous value.

func EnvFetch

func EnvFetch(key, defaultVal string) string

EnvFetch returns the value of the environment variable or the default.

func EnvHasKey

func EnvHasKey(key string) bool

EnvHasKey returns true if the environment variable is set.

func EnvKeys

func EnvKeys() []string

EnvKeys returns a slice of all environment variable names.

func EnvToMap

func EnvToMap() map[string]string

EnvToMap returns all environment variables as a map.

func EnvValues

func EnvValues() []string

EnvValues returns a slice of all environment variable values.

func EtcConfstr

func EtcConfstr(name int) string

EtcConfstr returns a system configuration string. Stubs common POSIX confstr values.

func EtcEndgrent

func EtcEndgrent()

EtcEndgrent is a no-op (closes the group database).

func EtcEndpwent

func EtcEndpwent()

EtcEndpwent is a no-op (closes the password database).

func EtcGetlogin

func EtcGetlogin() string

EtcGetlogin returns the login name of the current user.

func EtcHome

func EtcHome() string

EtcHome returns the home directory of the current user (or the named user).

func EtcHomeForUser

func EtcHomeForUser(name string) string

EtcHomeForUser returns the home directory for the specified user.

func EtcNprocessors

func EtcNprocessors() int

EtcNprocessors returns the number of CPUs available.

func EtcSetgrent

func EtcSetgrent()

EtcSetgrent is a no-op (rewinds the group database).

func EtcSetpwent

func EtcSetpwent()

EtcSetpwent is a no-op (rewinds the password database).

func EtcSysconf

func EtcSysconf(name int) int

EtcSysconf returns a system configuration long value. Stubs common POSIX sysconf values.

func EtcSysconfdir

func EtcSysconfdir() string

EtcSysconfdir returns the system configuration directory.

func EtcSystmpdir

func EtcSystmpdir() string

EtcSystmpdir returns the system temporary directory.

func EtcTmpdir

func EtcTmpdir() string

EtcTmpdir returns the system temporary directory.

func EtcUname

func EtcUname() map[string]string

EtcUname returns system information as a hash.

func FileUtilsChdir

func FileUtilsChdir(path string)

FileUtilsChdir changes the current working directory to path.

func FileUtilsChmod

func FileUtilsChmod(mode int, path string)

FileUtilsChmod changes the permission bits of path to mode.

func FileUtilsChmodR

func FileUtilsChmodR(mode int, path string)

FileUtilsChmodR recursively changes permission bits.

func FileUtilsChown

func FileUtilsChown(user, group, path string)

FileUtilsChown changes ownership of a file (no-op on systems without chown).

func FileUtilsChownR

func FileUtilsChownR(user, group, path string)

FileUtilsChownR recursively changes ownership.

func FileUtilsCollectMethod

func FileUtilsCollectMethod(name string) string

FileUtilsCollectMethod returns a method proc (stub — returns empty string).

func FileUtilsCommands

func FileUtilsCommands() []string

FileUtilsCommands returns all available FileUtils command names.

func FileUtilsCompareFile

func FileUtilsCompareFile(a, b string) bool

FileUtilsCompareFile returns true if the two files have identical contents.

func FileUtilsCopyEntry

func FileUtilsCopyEntry(src, dst string)

FileUtilsCopyEntry copies a file or directory entry.

func FileUtilsCopyStream

func FileUtilsCopyStream(src, dst string)

FileUtilsCopyStream copies from one IO to another (not directly usable from facade).

func FileUtilsCp

func FileUtilsCp(src, dst string)

func FileUtilsCpLr

func FileUtilsCpLr(src, dst string)

FileUtilsCpLr copies using hard links (falls back to copy).

func FileUtilsCpR

func FileUtilsCpR(src, dst string)

FileUtilsCpR copies src to dst recursively.

func FileUtilsHaveOption

func FileUtilsHaveOption(cmd, opt string) bool

FileUtilsHaveOption always returns false (Ruby-specific metadata).

func FileUtilsInstall

func FileUtilsInstall(src, dst string)

FileUtilsInstall copies src to dst and optionally sets permissions.

func FileUtilsLn

func FileUtilsLn(src, dst string)

FileUtilsLn creates a hard link from src to dst.

func FileUtilsLnS

func FileUtilsLnS(src, dst string)

FileUtilsLnS creates a symbolic link dst -> src.

func FileUtilsLnSF

func FileUtilsLnSF(src, dst string)

FileUtilsLnSF creates a symbolic link dst -> src, removing dst first if it exists.

func FileUtilsLnSr

func FileUtilsLnSr(src, dst string)

FileUtilsLnSr creates a relative symlink.

func FileUtilsMkdir

func FileUtilsMkdir(path string)

FileUtilsMkdir creates a single directory (not parents).

func FileUtilsMkdirP

func FileUtilsMkdirP(path string)

func FileUtilsMv

func FileUtilsMv(src, dst string)

FileUtilsMv moves src to dst, using os.Rename.

func FileUtilsOptions

func FileUtilsOptions() []string

FileUtilsOptions returns available options for a command (stub).

func FileUtilsOptionsOf

func FileUtilsOptionsOf(cmd string) []string

FileUtilsOptionsOf returns options for a specific command (stub).

func FileUtilsPwd

func FileUtilsPwd() string

FileUtilsPwd returns the current working directory.

func FileUtilsRemoveEntry

func FileUtilsRemoveEntry(path string)

FileUtilsRemoveEntry removes a file or directory tree.

func FileUtilsRm

func FileUtilsRm(path string)

func FileUtilsRmF

func FileUtilsRmF(path string)

FileUtilsRmF removes a file, ignoring any error (like rm -f).

func FileUtilsRmRf

func FileUtilsRmRf(path string)

func FileUtilsRmdir

func FileUtilsRmdir(path string)

FileUtilsRmdir removes an empty directory.

func FileUtilsTouch

func FileUtilsTouch(path string)

FileUtilsTouch creates the file if it does not exist and updates its modification time if it does, matching FileUtils.touch behavior.

func FileUtilsUptodate

func FileUtilsUptodate(dst string, srcs []string) bool

FileUtilsUptodate returns true if dst is newer than all sources.

func FindCollect

func FindCollect(dirs ...string) []string

FindCollect walks directory trees and returns all paths found.

func FindPrune

func FindPrune()

FindPrune is a no-op placeholder. In Ruby, Find.prune skips the current directory during Find.find. In our translation, Find.find collects all paths upfront, so prune has no effect.

func GetoptLongEach

func GetoptLongEach(g *GetoptLong, fn func(string, string))

GetoptLongEach iterates over all remaining options, calling fn for each.

func GetoptLongErrorMessage

func GetoptLongErrorMessage(g *GetoptLong) string

GetoptLongErrorMessage returns the current error message.

func GetoptLongGet

func GetoptLongGet(g *GetoptLong) (string, string)

GetoptLongGet returns the next option and its argument (if any). Returns empty strings when all options have been consumed.

func GetoptLongHasError

func GetoptLongHasError(g *GetoptLong) bool

GetoptLongHasError returns whether an error occurred.

func GetoptLongIsQuiet

func GetoptLongIsQuiet(g *GetoptLong) bool

GetoptLongIsQuiet returns the quiet setting.

func GetoptLongIsTerminated

func GetoptLongIsTerminated(g *GetoptLong) bool

GetoptLongIsTerminated returns whether parsing has been terminated.

func GetoptLongOrdering

func GetoptLongOrdering(g *GetoptLong) int

GetoptLongOrdering returns the current ordering mode.

func GetoptLongSetError

func GetoptLongSetError(g *GetoptLong, msg string)

GetoptLongSetError sets an error message on the parser.

func GetoptLongSetOptions

func GetoptLongSetOptions(g *GetoptLong, opts ...any)

GetoptLongSetOptions configures the recognized options. Each option is a name string and a boolean for whether it takes an argument.

func GetoptLongSetOrdering

func GetoptLongSetOrdering(g *GetoptLong, order int)

GetoptLongSetOrdering sets the ordering mode.

func GetoptLongSetQuiet

func GetoptLongSetQuiet(g *GetoptLong, q bool)

GetoptLongSetQuiet sets the quiet mode.

func GetoptLongTerminate

func GetoptLongTerminate(g *GetoptLong)

GetoptLongTerminate marks parsing as terminated.

func Gets

func Gets() string

Gets reads a line from stdin.

func IPAddrNtop

func IPAddrNtop(s string) string

IPAddrNtop converts a network-byte-order binary string to a human-readable IP address string. Mirrors Ruby's IPAddr.ntop(binary_string).

func JSONBracket

func JSONBracket(s string) map[string]string

JSONBracket is an alias for parse.

func JSONCreateFastState

func JSONCreateFastState() string

JSONCreateFastState returns empty string (internal Ruby state).

func JSONCreateID

func JSONCreateID() string

JSONCreateID returns the default create_id string.

func JSONCreatePrettyState

func JSONCreatePrettyState() string

JSONCreatePrettyState returns empty string.

func JSONDeepConstGet

func JSONDeepConstGet(path string) string

JSONDeepConstGet returns empty string (Ruby-specific).

func JSONDumpDefaultOptions

func JSONDumpDefaultOptions() map[string]string

JSONDumpDefaultOptions returns empty map (config stub).

func JSONGenerate

func JSONGenerate(v interface{}) string

JSONGenerate converts any value to a JSON string. Mirrors Ruby's JSON.generate(obj) and obj.to_json.

func JSONGenerator

func JSONGenerator() string

JSONGenerator returns "json/pure" (Ruby module name stub).

func JSONIconv

func JSONIconv(to, from, str string) string

JSONIconv is a stub for the deprecated iconv method.

func JSONLoadDefaultOptions

func JSONLoadDefaultOptions() map[string]string

JSONLoadDefaultOptions returns empty map (config stub).

func JSONLoadFile

func JSONLoadFile(path string) map[string]string

JSONLoadFile reads a JSON file from disk and parses it into a map[string]string.

func JSONLoadFileStrict

func JSONLoadFileStrict(path string) map[string]string

JSONLoadFileStrict is the same as JSONLoadFile (Ruby's load_file!).

func JSONParse

func JSONParse(s string) map[string]string

JSONParse parses a JSON string into a map[string]string. Mirrors Ruby's JSON.parse(str) for object inputs. Values are coerced to strings since thanos hashes are homogeneously typed.

func JSONParser

func JSONParser() string

JSONParser returns "json/pure" (Ruby module name stub).

func JSONPrettyGenerate

func JSONPrettyGenerate(v interface{}) string

JSONPrettyGenerate converts any value to a pretty-printed JSON string. Mirrors Ruby's JSON.pretty_generate(obj).

func JSONRecurseProc

func JSONRecurseProc(obj, proc string)

JSONRecurseProc is a no-op (applies proc recursively to parsed objects).

func JSONSetCreateID

func JSONSetCreateID(id string)

JSONSetCreateID is a no-op (sets the create_id, unused in Go).

func JSONSetDumpDefaultOptions

func JSONSetDumpDefaultOptions(opts map[string]string)

JSONSetDumpDefaultOptions is a no-op.

func JSONSetGenerator

func JSONSetGenerator(gen string)

JSONSetGenerator is a no-op.

func JSONSetLoadDefaultOptions

func JSONSetLoadDefaultOptions(opts map[string]string)

JSONSetLoadDefaultOptions is a no-op.

func JSONSetParser

func JSONSetParser(p string)

JSONSetParser is a no-op.

func JSONSetState

func JSONSetState(s string)

JSONSetState is a no-op.

func JSONState

func JSONState() string

JSONState returns empty string.

func LoggerAdd

func LoggerAdd(logger *slog.Logger, severity int, msg string)

LoggerAdd logs a message at the given Ruby Logger severity level. Ruby severity constants: DEBUG=0, INFO=1, WARN=2, ERROR=3, FATAL=4, UNKNOWN=5

func LoggerFormatterCall

func LoggerFormatterCall(severity, datetime, progname, msg string) string

LoggerFormatterCall is a stub for Logger::Formatter#call.

func LoggerFormatterDatetimeFormat

func LoggerFormatterDatetimeFormat() string

LoggerFormatterDatetimeFormat is a stub for Logger::Formatter#datetime_format.

func LoggerFormatterSetDatetimeFormat

func LoggerFormatterSetDatetimeFormat(fmt string) string

LoggerFormatterSetDatetimeFormat is a stub for Logger::Formatter#datetime_format=.

func LoggerLogDeviceClose

func LoggerLogDeviceClose()

LoggerLogDeviceClose is a stub for Logger::LogDevice#close.

func LoggerLogDeviceDev

func LoggerLogDeviceDev() string

LoggerLogDeviceDev is a stub for Logger::LogDevice#dev.

func LoggerLogDeviceFilename

func LoggerLogDeviceFilename() string

LoggerLogDeviceFilename is a stub for Logger::LogDevice#filename.

func LoggerLogDeviceReopen

func LoggerLogDeviceReopen()

LoggerLogDeviceReopen is a stub for Logger::LogDevice#reopen.

func LoggerLogDeviceWrite

func LoggerLogDeviceWrite(msg string)

LoggerLogDeviceWrite is a stub for Logger::LogDevice#write.

func LoggerPeriodNextRotateTime

func LoggerPeriodNextRotateTime() string

LoggerPeriodNextRotateTime is a stub for Logger::Period.next_rotate_time.

func LoggerPeriodPreviousPeriodEnd

func LoggerPeriodPreviousPeriodEnd() string

LoggerPeriodPreviousPeriodEnd is a stub for Logger::Period.previous_period_end.

func MutexAppendFeatures

func MutexAppendFeatures(m *MutexM)

MutexAppendFeatures is a no-op hook (Ruby module callback).

func MutexDefineAliases

func MutexDefineAliases(m *MutexM)

MutexDefineAliases is a no-op hook (Ruby module callback).

func MutexExtendObject

func MutexExtendObject(m *MutexM)

MutexExtendObject is a no-op hook (Ruby module callback).

func MutexExtended

func MutexExtended(m *MutexM)

MutexExtended is a no-op callback invoked when Mutex_m is mixed into a module.

func MutexIsLocked

func MutexIsLocked(m *MutexM) bool

MutexIsLocked returns whether the mutex is currently locked.

func MutexLock

func MutexLock(m *MutexM)

MutexLock acquires the mutex.

func MutexSleep

func MutexSleep(m *MutexM, seconds float64)

MutexSleep releases the lock, sleeps for the given duration, then reacquires.

func MutexSynchronize

func MutexSynchronize(m *MutexM, fn func())

MutexSynchronize executes fn while holding the lock.

func MutexTryLock

func MutexTryLock(m *MutexM) bool

MutexTryLock attempts to acquire the mutex without blocking. Returns true if the lock was acquired, false otherwise.

func MutexUnlock

func MutexUnlock(m *MutexM)

MutexUnlock releases the mutex.

func ObservableAddObserver

func ObservableAddObserver(o *Observable, name string, fn func(...any))

ObservableAddObserver adds a named observer callback.

func ObservableCountObservers

func ObservableCountObservers(o *Observable) int

ObservableCountObservers returns the number of registered observers.

func ObservableDeleteObserver

func ObservableDeleteObserver(o *Observable, name string)

ObservableDeleteObserver removes a named observer.

func ObservableDeleteObservers

func ObservableDeleteObservers(o *Observable)

ObservableDeleteObservers removes all observers.

func ObservableIsChanged

func ObservableIsChanged(o *Observable) bool

ObservableIsChanged returns whether the observable has been marked changed.

func ObservableNotifyObservers

func ObservableNotifyObservers(o *Observable, args ...any)

ObservableNotifyObservers notifies all observers if the observable is changed, then clears the changed flag.

func ObservableSetChanged

func ObservableSetChanged(o *Observable)

ObservableSetChanged marks the observable as changed.

func Open3Capture2

func Open3Capture2(cmd string) []string

Open3Capture2 runs a command and returns [stdout, status].

func Open3Capture2e

func Open3Capture2e(cmd string) []string

Open3Capture2e runs a command and returns [combined_output, status].

func Open3Capture3

func Open3Capture3(cmd string) []string

Open3Capture3 runs a command and returns [stdout, stderr, status].

func Open3Pipeline

func Open3Pipeline(cmds ...string) []string

Open3Pipeline runs a pipeline of commands, returns array of exit statuses.

func Open3PipelineR

func Open3PipelineR(cmds ...string) string

Open3PipelineR runs a pipeline and returns the final stdout.

func Open3PipelineRW

func Open3PipelineRW(cmds ...string) string

Open3PipelineRW runs a pipeline and returns final output.

func Open3PipelineStart

func Open3PipelineStart(cmds ...string) []string

Open3PipelineStart starts a pipeline (same as Pipeline).

func Open3PipelineW

func Open3PipelineW(cmds ...string) []string

Open3PipelineW runs a pipeline (same as Pipeline).

func Open3Popen2

func Open3Popen2(cmd string) []string

Open3Popen2 simplified — returns [stdout, status].

func Open3Popen2e

func Open3Popen2e(cmd string) []string

Open3Popen2e simplified — returns [combined, status].

func Open3Popen3

func Open3Popen3(cmd string) []string

Open3Popen3 simplified — runs command synchronously, returns [stdout, stderr, status].

func OpenURIBaseURI

func OpenURIBaseURI(url string) string

OpenURIBaseURI returns the URL that was fetched.

func OpenURICharset

func OpenURICharset(url string) string

OpenURICharset returns the charset from the Content-Type header.

func OpenURIContentEncoding

func OpenURIContentEncoding(url string) []string

OpenURIContentEncoding returns the content encoding(s) from the response.

func OpenURIContentType

func OpenURIContentType(url string) string

OpenURIContentType returns the Content-Type header from fetching the URL.

func OpenURILastModified

func OpenURILastModified(url string) string

OpenURILastModified returns the Last-Modified header value.

func OpenURIMeta

func OpenURIMeta(url string) map[string]string

OpenURIMeta returns all response headers as a map.

func OpenURIOpen

func OpenURIOpen(url string) *bytes.Buffer

OpenURIOpen is an alias for OpenURIRead (Ruby's Kernel#open with URI).

func OpenURIRead

func OpenURIRead(url string) *bytes.Buffer

OpenURIRead fetches the URL and returns the body as a *bytes.Buffer. This mirrors Ruby's OpenURI.open_uri(url) which returns a StringIO-like IO. Returning *bytes.Buffer lets the result support StringIO methods like .read.

func OpenURIReadBody

func OpenURIReadBody(url string) string

OpenURIReadBody fetches the URL and returns the body as a string.

func OpenURIStatus

func OpenURIStatus(url string) []string

OpenURIStatus returns [status_code, message] as a two-element string slice.

func PPGenspace

func PPGenspace(n int) string

PPGenspace returns n spaces (PrettyPrint default genspace).

func PPNewline

func PPNewline() string

PPNewline returns a newline string (PrettyPrint default newline).

func PPSetSharingDetection

func PPSetSharingDetection(v bool)

PPSetSharingDetection sets the sharing detection flag.

func PPSharingDetection

func PPSharingDetection() bool

PPSharingDetection returns the current sharing detection flag.

func PPWidthFor

func PPWidthFor(out any) int

PPWidthFor returns a display width for the given output. In Ruby this computes terminal width; here we default to 79.

func ProcessClockGettime

func ProcessClockGettime() float64

ProcessClockGettime returns the current monotonic clock time as a float64 of seconds.

func ProcessGroups

func ProcessGroups() []int

ProcessGroups returns the supplementary group IDs of the calling process.

func ProcessKill

func ProcessKill(signal interface{}, pid int) int

ProcessKill sends a signal to a process. Signal can be int or string.

func ProcessSpawn

func ProcessSpawn(args ...string) int

ProcessSpawn starts a command and returns its PID.

func ProcessWait

func ProcessWait() int

ProcessWait waits for any child process and returns its PID.

func RandomBytes

func RandomBytes(rng *rand.Rand, n int) string

RandomBytes generates n random bytes from the given rand.Rand and returns as string.

func RegexpCasefold

func RegexpCasefold(re *regexp.Regexp) bool

RegexpCasefold returns true if the regexp has the case-insensitive flag.

func RegexpNamedCaptures

func RegexpNamedCaptures(re *regexp.Regexp) map[string][]int

RegexpNamedCaptures returns a map of capture group names to their indices.

func RegexpUnion

func RegexpUnion(patterns ...string) *regexp.Regexp

RegexpUnion creates a regexp that matches any of the given patterns.

func SecureRandomAlphanumeric

func SecureRandomAlphanumeric(n ...int) string

SecureRandomAlphanumeric generates a random alphanumeric string. n is the length (default 16).

func SecureRandomBase64

func SecureRandomBase64(n ...int) string

SecureRandomBase64 generates a random base64 string. n is the number of random bytes (default 16).

func SecureRandomBytes

func SecureRandomBytes(n int) []byte

SecureRandomBytes generates n random bytes.

func SecureRandomHex

func SecureRandomHex(n ...int) string

SecureRandomHex generates a random hex string. n is the number of random bytes (default 16); the hex output is 2*n chars.

func SecureRandomNumber

func SecureRandomNumber(n ...int) int

SecureRandomNumber generates a random number. With no args: returns a float in [0, 1). With an int arg: returns an int in [0, n). With a float arg: returns a float in [0, n).

func SecureRandomURLSafeBase64

func SecureRandomURLSafeBase64(n ...int) string

SecureRandomURLSafeBase64 generates a random URL-safe base64 string. n is the number of random bytes (default 16).

func SecureRandomUUID

func SecureRandomUUID() string

SecureRandomUUID generates a random v4 UUID string.

func ShellEscape

func ShellEscape(str string) string

ShellEscape escapes a string for safe use in a shell command. Implements Ruby's Shellwords.escape / shellescape.

func ShellJoin

func ShellJoin(words []string) string

ShellJoin joins an array of strings into a shell-safe command. Implements Ruby's Shellwords.join / shelljoin.

func ShellSplit

func ShellSplit(line string) []string

ShellSplit splits a command-line string into words, respecting quotes. Implements Ruby's Shellwords.split / shellsplit / shellwords.

func SingletonClone

func SingletonClone(obj any) any

SingletonClone returns the receiver (Singleton#clone raises in Ruby; in Go we just return self).

func SingletonDump

func SingletonDump(obj any) string

SingletonDump returns an empty string (serialization stub).

func SingletonDup

func SingletonDup(obj any) any

SingletonDup returns the receiver (Singleton#dup raises in Ruby; in Go we just return self).

func SingletonIncluded

func SingletonIncluded(obj any)

SingletonIncluded is a no-op hook called when Singleton is included in a class.

func SingletonInit

func SingletonInit(obj any)

SingletonInit is a no-op initialization hook.

func SingletonInstance

func SingletonInstance(obj any) any

SingletonInstance returns the receiver itself (no-op in Go).

func SingletonLoad

func SingletonLoad(data string) any

SingletonLoad returns nil (deserialization stub).

func StringIOGetbyte

func StringIOGetbyte(buf *bytes.Buffer) int

StringIOGetbyte reads one byte from buf as an integer. Returns -1 at EOF.

func StringIOGetc

func StringIOGetc(buf *bytes.Buffer) string

StringIOGetc reads one character (byte) from buf. Returns empty string at EOF.

func StringIOGets

func StringIOGets(buf *bytes.Buffer) string

StringIOGets reads until the next newline (inclusive). Returns empty string at EOF.

func StringIOPutc

func StringIOPutc(buf *bytes.Buffer, ch string) string

StringIOPutc writes one character to buf and returns it.

func StringIOReadlines

func StringIOReadlines(buf *bytes.Buffer) []string

StringIOReadlines returns all remaining content split into lines. Each line includes its trailing newline, except possibly the last line if the content does not end with a newline.

func StringIOUngetbyte

func StringIOUngetbyte(buf *bytes.Buffer, b int)

StringIOUngetbyte pushes a byte back to the front of the buffer.

func StringIOUngetc

func StringIOUngetc(buf *bytes.Buffer, c string)

StringIOUngetc pushes a character back to the front of the buffer.

func SyslogAlert

func SyslogAlert(msg string)

SyslogAlert logs a message at LOG_ALERT priority.

func SyslogClose

func SyslogClose()

SyslogClose closes the syslog connection.

func SyslogConstantsIncluded

func SyslogConstantsIncluded()

SyslogConstantsIncluded is a no-op stub for Syslog::Constants.included hook.

func SyslogCrit

func SyslogCrit(msg string)

SyslogCrit logs a message at LOG_CRIT priority.

func SyslogDebug

func SyslogDebug(msg string)

SyslogDebug logs a message at LOG_DEBUG priority.

func SyslogEmerg

func SyslogEmerg(msg string)

SyslogEmerg logs a message at LOG_EMERG priority.

func SyslogErr

func SyslogErr(msg string)

SyslogErr logs a message at LOG_ERR priority.

func SyslogFacility

func SyslogFacility() int

SyslogFacility returns the current syslog facility.

func SyslogIdent

func SyslogIdent() string

SyslogIdent returns the current syslog ident string.

func SyslogInfo

func SyslogInfo(msg string)

SyslogInfo logs a message at LOG_INFO priority.

func SyslogInspect

func SyslogInspect() string

SyslogInspect returns a description string for the Syslog connection.

func SyslogInstance

func SyslogInstance() string

SyslogInstance returns the ident of the current syslog connection. Mirrors Ruby's Syslog.instance (returns Syslog itself; here we return ident as a proxy since Go has no module-as-value semantics).

func SyslogLog

func SyslogLog(level int, msg string)

SyslogLog logs a message at an arbitrary priority level. Mirrors Ruby's Syslog.log(level, msg).

func SyslogLogMask

func SyslogLogMask(priority int) int

SyslogLogMask computes the log mask bit for a single priority level. Mirrors Ruby's Syslog::Macros#LOG_MASK(pri) → 1 << pri.

func SyslogLogUpTo

func SyslogLogUpTo(priority int) int

SyslogLogUpTo computes the log mask for all priorities up to and including pri. Mirrors Ruby's Syslog::Macros#LOG_UPTO(pri) → (1 << (pri+1)) - 1.

func SyslogMacrosIncluded

func SyslogMacrosIncluded()

SyslogMacrosIncluded is a no-op stub for Syslog::Macros.included hook.

func SyslogMask

func SyslogMask() int

SyslogMask returns the current log priority mask.

func SyslogNotice

func SyslogNotice(msg string)

SyslogNotice logs a message at LOG_NOTICE priority.

func SyslogOpen

func SyslogOpen(ident string, rest ...int)

SyslogOpen opens a connection to the system logger. Mirrors Ruby's Syslog.open(ident, options=0, facility=LOG_USER).

func SyslogOpened

func SyslogOpened() bool

SyslogOpened returns true if the syslog connection is open.

func SyslogOptions

func SyslogOptions() int

SyslogOptions returns the current syslog options.

func SyslogSetMask

func SyslogSetMask(mask int) int

SyslogSetMask sets the log priority mask and returns the previous mask.

func SyslogWarning

func SyslogWarning(msg string)

SyslogWarning logs a message at LOG_WARNING priority.

func System

func System(args ...string) bool

System runs a command via the shell and returns true if it succeeds.

func Timeout

func Timeout(seconds float64, fn func())

Timeout runs fn with a timeout of seconds. Panics with TimeoutError if exceeded.

func TimeoutErrorMessage

func TimeoutErrorMessage(e *TimeoutError) string

TimeoutErrorMessage returns the error message from a TimeoutError.

func TmsToA

func TmsToA(t *BenchmarkTms) []float64

TmsToA returns the Tms fields as a slice: [label, utime, stime, cutime, cstime, real]. The label is represented as 0.0 since this returns []float64 (the label field in Ruby's to_a is a string, but thanos simplifies to float64 array).

func TmsToH

func TmsToH(t *BenchmarkTms) map[string]float64

TmsToH returns the Tms fields as a map.

func ToFloat

func ToFloat(val interface{}) float64

ToFloat converts a value to float64, similar to Ruby's Float().

func ToInteger

func ToInteger(val interface{}) int

ToInteger converts a value to int, similar to Ruby's Integer().

func TsortDo

func TsortDo(eachNode func(func(string)), eachChild func(string, func(string))) []string

TsortDo performs a topological sort given two iterator functions. eachNode iterates over all nodes by calling its argument for each one. eachChild iterates over the children of a node by calling its argument for each child. Returns nodes in topological order (dependencies before dependents). Panics if the graph has a cycle (matching Ruby's TSort::Cyclic error).

func TsortFromHash

func TsortFromHash(deps map[string][]string) []string

TsortFromHash performs a topological sort on a hash where keys depend on their values. The hash maps each node to a slice of its dependencies.

func TsortSCCDo

func TsortSCCDo(eachNode func(func(string)), eachChild func(string, func(string))) [][]string

TsortSCCDo computes strongly connected components using Kosaraju's algorithm. eachNode iterates over all nodes; eachChild iterates over children of a node. Returns a slice of SCCs, each SCC is a slice of nodes, ordered so that dependencies come before dependents (matching Ruby's TSort#strongly_connected_components).

func TsortSCCFromDo

func TsortSCCFromDo(node string, eachNode func(func(string)), eachChild func(string, func(string))) [][]string

TsortSCCFromDo computes strongly connected components that contain a specific node, using the provided iterator functions (for the mixin's each_strongly_connected_component_from).

func TsortSCCFromHash

func TsortSCCFromHash(deps map[string][]string) [][]string

TsortSCCFromHash computes strongly connected components from a dependency hash.

func TsortSCCFromNode

func TsortSCCFromNode(node string, deps map[string][]string) [][]string

TsortSCCFromNode computes the SCC containing a specific node from a dependency hash.

func URIBuildQuery

func URIBuildQuery(parts [][]string) string

URIBuildQuery builds a query string from parts.

func URIDecodeComponent

func URIDecodeComponent(s string) string

URIDecodeComponent decodes a percent-encoded URI component string.

func URIDecodeWwwForm

func URIDecodeWwwForm(s string) [][]string

URIDecodeWwwForm decodes a query string into key-value pairs.

func URIEncodeComponent

func URIEncodeComponent(s string) string

URIEncodeComponent encodes a string as a URI component (RFC 3986 §2.1). Unreserved chars (A-Za-z0-9 - _ . ~) are kept; everything else is percent-encoded.

func URIEncodeWwwForm

func URIEncodeWwwForm(m *stdlib.OrderedMap[string, string]) string

URIEncodeWwwForm encodes a hash as application/x-www-form-urlencoded. Takes an OrderedMap[string, string] and returns the encoded string.

func URIEncodeWwwFormFromPairs

func URIEncodeWwwFormFromPairs(pairs [][]string) string

Small helper: URIEncodeWwwFormFromPairs handles Ruby's array-of-arrays form

func URIEscape

func URIEscape(s string) string

URIEscape is an alias for URI.encode_www_form_component (deprecated in Ruby).

func URIExtract

func URIExtract(str string) []string

URIExtract extracts URIs from a string.

func URIFor

func URIFor(scheme string) string

URIFor creates a URI from a scheme string (stub).

func URIGetEncoding

func URIGetEncoding(charset string) string

URIGetEncoding returns the encoding for a given charset (stub).

func URIOpen

func URIOpen(s string) string

URIOpen is a stub that returns the string of the URI (real open-uri is separate).

func URIRegexp

func URIRegexp() string

URIRegexp returns a simple URI-matching regexp pattern string.

func URIRegisterScheme

func URIRegisterScheme(scheme, klass string)

URIRegisterScheme is a no-op (registers a URI scheme handler).

func URISchemeList

func URISchemeList() map[string]string

URISchemeList returns known URI schemes.

func URISplit

func URISplit(str string) []string

URISplit splits a URI string into components: [scheme, userinfo, host, port, registry, path, opaque, query, fragment].

func URIUnescape

func URIUnescape(s string) string

URIUnescape is an alias for URI.decode_www_form_component (deprecated in Ruby).

func WeakRefAlive

func WeakRefAlive(w *WeakRef) bool

WeakRefAlive always returns true in Go (no weak references).

func WeakRefGetObj

func WeakRefGetObj(w *WeakRef) any

WeakRefGetObj returns the wrapped object.

func WeakRefSetObj

func WeakRefSetObj(w *WeakRef, obj any)

WeakRefSetObj replaces the wrapped object.

func YAMLAddBuiltinType

func YAMLAddBuiltinType(tag string)

YAMLAddBuiltinType is a no-op.

func YAMLAddDomainType

func YAMLAddDomainType(domain, tag string)

YAMLAddDomainType is a no-op.

func YAMLAddTag

func YAMLAddTag(tag, klass string)

YAMLAddTag is a no-op (registers a tag).

func YAMLConfig

func YAMLConfig() string

YAMLConfig returns nil (stub for Psych.config).

func YAMLDomainTypes

func YAMLDomainTypes() map[string]string

YAMLDomainTypes returns empty map (stub).

func YAMLDump

func YAMLDump(v interface{}) string

YAMLDump serializes a Go value to a YAML string. Prepends "--- " to match Ruby's YAML.dump output format.

func YAMLDumpStream

func YAMLDumpStream(objects ...interface{}) string

YAMLDumpStream dumps multiple objects as a YAML stream.

func YAMLDumpTags

func YAMLDumpTags() map[string]string

YAMLDumpTags returns empty map (stub).

func YAMLLibyamlVersion

func YAMLLibyamlVersion() string

YAMLLibyamlVersion returns the libyaml version (stub).

func YAMLLoad

func YAMLLoad(s string) interface{}

YAMLLoad parses a YAML string and returns the result as a Go interface{}. For simple scalar values, returns string. For complex structures, returns map[string]interface{} or []interface{}.

func YAMLLoadFile

func YAMLLoadFile(filename string) interface{}

YAMLLoadFile reads and parses a YAML file.

func YAMLLoadStream

func YAMLLoadStream(s string) interface{}

YAMLLoadStream parses a YAML stream (simplified: parses first document).

func YAMLLoadTags

func YAMLLoadTags() map[string]string

YAMLLoadTags returns empty map (stub).

func YAMLParse

func YAMLParse(s string) interface{}

YAMLParse parses YAML and returns the raw structure (same as Load for our purposes).

func YAMLParseFile

func YAMLParseFile(filename string) interface{}

YAMLParseFile parses a YAML file.

func YAMLParseStream

func YAMLParseStream(s string) interface{}

YAMLParseStream is the same as LoadStream.

func YAMLParser

func YAMLParser() string

YAMLParser returns a string identifier (stub).

func YAMLRemoveType

func YAMLRemoveType(tag string)

YAMLRemoveType is a no-op.

func YAMLSafeDump

func YAMLSafeDump(v interface{}) string

YAMLSafeDump is the same as YAMLDump (Go yaml.v3 is always safe).

func YAMLSafeLoadFile

func YAMLSafeLoadFile(filename string) interface{}

YAMLSafeLoadFile is the same as YAMLLoadFile.

func YAMLSetDomainTypes

func YAMLSetDomainTypes(types map[string]string)

YAMLSetDomainTypes is a no-op.

func YAMLSetDumpTags

func YAMLSetDumpTags(tags map[string]string)

YAMLSetDumpTags is a no-op.

func YAMLSetLoadTags

func YAMLSetLoadTags(tags map[string]string)

YAMLSetLoadTags is a no-op.

func YAMLToJSON

func YAMLToJSON(v interface{}) string

YAMLToJSON converts a YAML value to JSON string.

func YAMLUnsafeLoad

func YAMLUnsafeLoad(s string) interface{}

YAMLUnsafeLoad is the same as YAMLLoad (no unsafe distinction in Go).

func YAMLUnsafeLoadFile

func YAMLUnsafeLoadFile(filename string) interface{}

YAMLUnsafeLoadFile is the same as YAMLLoadFile.

func ZlibAdler32

func ZlibAdler32(s string) int

ZlibAdler32 computes the Adler-32 checksum of the given string.

func ZlibAdler32Combine

func ZlibAdler32Combine(a1 int, a2 int, len2 int) int

ZlibAdler32Combine combines two Adler-32 checksums.

func ZlibBestCompression

func ZlibBestCompression() int

ZlibBestCompression returns the best compression level constant.

func ZlibBestSpeed

func ZlibBestSpeed() int

ZlibBestSpeed returns the best speed compression level constant.

func ZlibCompress

func ZlibCompress(s string) string

ZlibCompress compresses a string using zlib (not raw deflate).

func ZlibCrc32

func ZlibCrc32(s string) int

ZlibCrc32 computes the CRC-32 checksum of the given string.

func ZlibCrc32Combine

func ZlibCrc32Combine(crc1 int, crc2 int, len2 int) int

ZlibCrc32Combine combines two CRC-32 checksums.

func ZlibCrcTable

func ZlibCrcTable() string

ZlibCrcTable returns the CRC-32 polynomial table as a string representation.

func ZlibDefaultCompression

func ZlibDefaultCompression() int

ZlibDefaultCompression returns the default compression level constant.

func ZlibDeflate

func ZlibDeflate(s string) string

ZlibDeflate compresses a string using zlib/deflate.

func ZlibDeflateLevel

func ZlibDeflateLevel(s string, level int) string

ZlibDeflateLevel compresses with a specified compression level (0-9).

func ZlibGunzip

func ZlibGunzip(s string) string

ZlibGunzip decompresses a gzip-compressed string.

func ZlibGzip

func ZlibGzip(s string) string

ZlibGzip compresses a string using gzip.

func ZlibGzipLevel

func ZlibGzipLevel(s string, level int) string

ZlibGzipLevel compresses using gzip with a specified compression level.

func ZlibInflate

func ZlibInflate(s string) string

ZlibInflate decompresses a deflate-compressed string.

func ZlibNoCompression

func ZlibNoCompression() int

ZlibNoCompression returns the no-compression level constant.

func ZlibUncompress

func ZlibUncompress(s string) string

ZlibUncompress decompresses a zlib-compressed string.

func ZlibVersion

func ZlibVersion() string

ZlibVersion returns the zlib version string. Go doesn't expose the underlying C zlib version, so we return the Go compress version.

Types

type BenchmarkTms

type BenchmarkTms struct {
	Label  string
	Utime  float64 // user CPU time (approximated as real time)
	Stime  float64 // system CPU time (approximated as 0)
	CUtime float64 // children user CPU time
	CStime float64 // children system CPU time
	Real   float64 // real (wall-clock) elapsed time in seconds
}

BenchmarkTms holds the timing result of a single Benchmark.measure call. It mirrors Ruby's Benchmark::Tms struct, though on most platforms utime/stime are not obtainable without cgo, so they default to the real elapsed time.

func BenchmarkBenchmark

func BenchmarkBenchmark(f func()) []*BenchmarkTms

BenchmarkBenchmark runs a block and returns an empty slice of Tms results. The block is expected to use Benchmark::Report#item internally, but since we don't model the report object, this just executes the block.

func BenchmarkJobList

func BenchmarkJobList() []*BenchmarkTms

BenchmarkJobList is a stub for Benchmark::Job#list.

func BenchmarkMeasure

func BenchmarkMeasure(label string, f func()) *BenchmarkTms

BenchmarkMeasure executes f, measures elapsed time, and returns a BenchmarkTms. utime/stime are approximated: real time is used for utime, stime is 0.

func BenchmarkReportItem

func BenchmarkReportItem(label string, f func()) *BenchmarkTms

BenchmarkReportItem is a stub for Benchmark::Report#item.

func BenchmarkReportList

func BenchmarkReportList() []*BenchmarkTms

BenchmarkReportList is a stub for Benchmark::Report#list.

func TmsAdd

func TmsAdd(a, b *BenchmarkTms) *BenchmarkTms

TmsAdd adds two BenchmarkTms structs and returns a new one.

func TmsDiv

func TmsDiv(a *BenchmarkTms, s float64) *BenchmarkTms

TmsDiv divides a BenchmarkTms by a scalar.

func TmsMul

func TmsMul(a *BenchmarkTms, s float64) *BenchmarkTms

TmsMul multiplies a BenchmarkTms by a scalar.

func TmsSub

func TmsSub(a, b *BenchmarkTms) *BenchmarkTms

TmsSub subtracts one BenchmarkTms from another.

func (*BenchmarkTms) Inspect

func (t *BenchmarkTms) Inspect() string

Inspect formats the Tms with label like Ruby's Benchmark::Tms#to_s with label.

func (*BenchmarkTms) TmsCStime

func (t *BenchmarkTms) TmsCStime() float64

TmsCStime returns children system CPU time.

func (*BenchmarkTms) TmsCUtime

func (t *BenchmarkTms) TmsCUtime() float64

TmsCUtime returns children user CPU time.

func (*BenchmarkTms) TmsLabel

func (t *BenchmarkTms) TmsLabel() string

TmsLabel returns the label string.

func (*BenchmarkTms) TmsReal

func (t *BenchmarkTms) TmsReal() float64

TmsReal returns the real elapsed time.

func (*BenchmarkTms) TmsStime

func (t *BenchmarkTms) TmsStime() float64

TmsStime returns system CPU time.

func (*BenchmarkTms) TmsUtime

func (t *BenchmarkTms) TmsUtime() float64

TmsUtime returns user CPU time.

func (*BenchmarkTms) ToS

func (t *BenchmarkTms) ToS() string

ToS formats the Tms like Ruby's Benchmark::Tms#to_s: " u s cu cs real"

func (*BenchmarkTms) Total

func (t *BenchmarkTms) Total() float64

Total returns utime + stime, matching Ruby's Benchmark::Tms#total.

type DigestInstance

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

DigestInstance wraps a hash.Hash for Ruby's incremental Digest instance API. Ruby usage: d = Digest::MD5.new; d.update("data"); d.hexdigest

func NewDigestMD5

func NewDigestMD5() *DigestInstance

func NewDigestSHA1

func NewDigestSHA1() *DigestInstance

func NewDigestSHA256

func NewDigestSHA256() *DigestInstance

func NewDigestSHA384

func NewDigestSHA384() *DigestInstance

func NewDigestSHA512

func NewDigestSHA512() *DigestInstance

func (*DigestInstance) AppendBytes

func (d *DigestInstance) AppendBytes(data []byte) *DigestInstance

AppendBytes feeds a byte slice into the hash and returns self (for Ruby's << operator).

func (*DigestInstance) Base64digest

func (d *DigestInstance) Base64digest() string

Base64digest returns the Base64-encoded digest without resetting.

func (*DigestInstance) Base64digestBang

func (d *DigestInstance) Base64digestBang() string

Base64digestBang returns the Base64 digest and resets the hash state.

func (*DigestInstance) BlockSize

func (d *DigestInstance) BlockSize() int

BlockSize returns the hash's block size in bytes (Ruby: block_length).

func (*DigestInstance) DigestBytes

func (d *DigestInstance) DigestBytes() string

DigestBytes returns the raw binary digest without resetting.

func (*DigestInstance) DigestBytesBang

func (d *DigestInstance) DigestBytesBang() string

DigestBytesBang returns the raw binary digest and resets the hash state.

func (*DigestInstance) DigestSize

func (d *DigestInstance) DigestSize() int

DigestSize returns the number of bytes in the digest output (Ruby: length / size / digest_length).

func (*DigestInstance) Equal

func (d *DigestInstance) Equal(other *DigestInstance) bool

Equal returns true if other has the same hex digest (Ruby: ==).

func (*DigestInstance) File

func (d *DigestInstance) File(path string) *DigestInstance

File reads the file at path and feeds its content into the hash (Ruby: file).

func (*DigestInstance) Hexdigest

func (d *DigestInstance) Hexdigest() string

Hexdigest returns the hex-encoded digest of data fed so far without resetting.

func (*DigestInstance) HexdigestBang

func (d *DigestInstance) HexdigestBang() string

HexdigestBang returns the hex digest and resets the hash state.

func (*DigestInstance) Inspect

func (d *DigestInstance) Inspect() string

Inspect returns a Ruby-style inspect string.

func (*DigestInstance) New

func (d *DigestInstance) New() *DigestInstance

New returns a fresh DigestInstance of the same algorithm (Ruby: Digest::Instance#new).

func (*DigestInstance) Reset

func (d *DigestInstance) Reset() *DigestInstance

Reset clears all data fed so far and returns self.

func (*DigestInstance) ToS

func (d *DigestInstance) ToS() string

ToS returns the hex digest string (Ruby: to_s).

func (*DigestInstance) Update

func (d *DigestInstance) Update(data string) *DigestInstance

Update feeds data into the hash and returns self for chaining (Ruby: update / <<).

type ERB

type ERB struct {
	Src      string
	Filename string
	Lineno   int
	Encoding string
}

ERB provides a simple template engine that maps Ruby's ERB to Go's text/template. Note: real ERB uses <% %> tags; this shim expects Go template syntax {{ }} since the transpiler converts template strings.

func NewERB

func NewERB(src string) *ERB

NewERB creates a new ERB instance from a template string.

func (*ERB) DefClass

func (e *ERB) DefClass(_ string, _ string) string

DefClass is a no-op compatibility stub for ERB#def_class.

func (*ERB) DefMethod

func (e *ERB) DefMethod(_ interface{}, _ string, _ string)

DefMethod is a no-op compatibility stub for ERB#def_method.

func (*ERB) DefModule

func (e *ERB) DefModule(_ string) string

DefModule is a no-op compatibility stub for ERB#def_module.

func (*ERB) MakeCompiler

func (e *ERB) MakeCompiler(_ string) string

MakeCompiler returns the compiler class name (compatibility stub).

func (*ERB) Result

func (e *ERB) Result() string

Result executes the template with no bindings and returns the result string.

func (*ERB) ResultWithHash

func (e *ERB) ResultWithHash(data map[string]any) string

ResultWithHash executes the template with a data map and returns the result.

func (*ERB) Run

func (e *ERB) Run()

Run executes the template and prints the result to stdout.

func (*ERB) SetEoutvar

func (e *ERB) SetEoutvar(_ string)

SetEoutvar sets the output variable name (no-op in Go shim; for compatibility).

func (*ERB) SetFilename

func (e *ERB) SetFilename(name string)

SetFilename sets the filename for the ERB template.

func (*ERB) SetLineno

func (e *ERB) SetLineno(n int)

SetLineno sets the starting line number.

type EtcGroupEntry

type EtcGroupEntry struct {
	Name   string
	Passwd string
	GID    int
	Mem    []string
}

EtcGroupEntry represents a group database entry.

func EtcGetgrent

func EtcGetgrent() *EtcGroupEntry

EtcGetgrent returns the next group entry (stub: returns current user's group).

func EtcGetgrgid

func EtcGetgrgid(gid int) *EtcGroupEntry

EtcGetgrgid looks up a group by GID.

func EtcGetgrnam

func EtcGetgrnam(name string) *EtcGroupEntry

EtcGetgrnam looks up a group by name.

func EtcGroup

func EtcGroup() *EtcGroupEntry

EtcGroup returns the current user's group entry (simulates Etc.group without block).

func (*EtcGroupEntry) String

func (e *EtcGroupEntry) String() string

type EtcPasswdEntry

type EtcPasswdEntry struct {
	Name   string
	Passwd string
	UID    int
	GID    int
	Gecos  string
	Dir    string
	Shell  string
}

EtcPasswdEntry represents a password database entry.

func EtcGetpwent

func EtcGetpwent() *EtcPasswdEntry

EtcGetpwent returns the next password entry (stub: returns current user).

func EtcGetpwnam

func EtcGetpwnam(name string) *EtcPasswdEntry

EtcGetpwnam looks up a user by name.

func EtcGetpwuid

func EtcGetpwuid(uid int) *EtcPasswdEntry

EtcGetpwuid looks up a user by UID.

func EtcPasswd

func EtcPasswd() *EtcPasswdEntry

EtcPasswd returns the current user's passwd entry (simulates Etc.passwd without block).

func (*EtcPasswdEntry) String

func (e *EtcPasswdEntry) String() string

type GetoptLong

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

GetoptLong provides a simple option parser that maps Ruby's GetoptLong to a Go-native argument parser. This is a basic implementation that handles long options with optional arguments.

func NewGetoptLong

func NewGetoptLong() *GetoptLong

NewGetoptLong creates a new option parser.

type IPAddr

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

IPAddr wraps a Go net.IP plus an optional mask, mirroring Ruby's IPAddr. Both single addresses (mask all-ones) and CIDR networks are represented.

func NewIPAddr

func NewIPAddr(s string) *IPAddr

NewIPAddr parses a string in IP or CIDR notation (e.g. "192.168.1.1", "192.168.0.0/24", "::1", "2001:db8::/32").

func NewIPAddrNtoh

func NewIPAddrNtoh(s string) *IPAddr

NewIPAddrNtoh creates an IPAddr from a network-byte-order binary string. Mirrors Ruby's IPAddr.new_ntoh(binary_string).

func (*IPAddr) And

func (a *IPAddr) And(b *IPAddr) *IPAddr

And returns the bitwise AND of two IP addresses (same family).

func (*IPAddr) Compare

func (a *IPAddr) Compare(b *IPAddr) int

Compare compares two IPAddr values lexicographically by address bytes. Returns -1, 0, or 1.

func (*IPAddr) Eql

func (a *IPAddr) Eql(b *IPAddr) bool

Eql reports whether two IPAddr values represent the same address and mask.

func (*IPAddr) Family

func (a *IPAddr) Family() int

Family returns the address family: syscall.AF_INET for IPv4, syscall.AF_INET6 for IPv6. This matches Ruby's IPAddr#family which returns Socket::AF_INET or Socket::AF_INET6.

func (*IPAddr) HashCode

func (a *IPAddr) HashCode() int

HashCode returns a stable integer hash for the IPAddr (address + mask).

func (*IPAddr) Hton

func (a *IPAddr) Hton() string

Hton returns the binary representation of the IP address in network byte order.

func (*IPAddr) Include

func (a *IPAddr) Include(other *IPAddr) bool

Include returns true if other is within the network represented by a.

func (*IPAddr) Inspect

func (a *IPAddr) Inspect() string

Inspect returns the Ruby-style inspect string, e.g. "#<IPAddr: IPv4:192.168.1.1/255.255.255.255>" or "#<IPAddr: IPv6:0000:0000:0000:0000:0000:0000:0000:0001/ffff:ffff:...>".

func (*IPAddr) Ip6Arpa

func (a *IPAddr) Ip6Arpa() string

Ip6Arpa returns the ip6.arpa reverse-lookup name for an IPv6 address.

func (*IPAddr) Ip6Int

func (a *IPAddr) Ip6Int() string

Ip6Int returns the deprecated ip6.int reverse-lookup name for an IPv6 address.

func (*IPAddr) Ipv4Compat

func (a *IPAddr) Ipv4Compat() *IPAddr

Ipv4Compat returns the deprecated IPv4-compatible IPv6 form of an IPv4 address. For ::1.2.3.4 format (prefix all-zeros, not ffff).

func (*IPAddr) Ipv4Mapped

func (a *IPAddr) Ipv4Mapped() *IPAddr

Ipv4Mapped returns the IPv4-mapped IPv6 form (::ffff:a.b.c.d) of an IPv4 address.

func (*IPAddr) IsIPv4

func (a *IPAddr) IsIPv4() bool

IsIPv4 returns true if the address is an IPv4 address.

func (*IPAddr) IsIPv4Compat

func (a *IPAddr) IsIPv4Compat() bool

IsIPv4Compat reports the deprecated IPv4-compatible form. An IPv6 address is IPv4-compatible when its first 12 bytes are all zero and the last 4 bytes represent a value greater than 1 (excluding :: and ::1).

func (*IPAddr) IsIPv4Mapped

func (a *IPAddr) IsIPv4Mapped() bool

IsIPv4Mapped returns true if the address is an IPv4-mapped IPv6 address.

func (*IPAddr) IsIPv6

func (a *IPAddr) IsIPv6() bool

IsIPv6 returns true if the address is an IPv6 address.

func (*IPAddr) IsLinkLocal

func (a *IPAddr) IsLinkLocal() bool

IsLinkLocal returns true if the address is a link-local unicast address.

func (*IPAddr) IsLoopback

func (a *IPAddr) IsLoopback() bool

IsLoopback returns true if the address is a loopback address.

func (*IPAddr) IsPrivate

func (a *IPAddr) IsPrivate() bool

IsPrivate returns true if the address falls in a private/reserved range.

func (*IPAddr) Mask

func (a *IPAddr) Mask(prefixLen int) *IPAddr

Mask applies a new prefix length and returns the network address.

func (*IPAddr) MaskBang

func (a *IPAddr) MaskBang(prefixLen int) *IPAddr

MaskBang applies a new prefix length in-place and returns self.

func (*IPAddr) Native

func (a *IPAddr) Native() *IPAddr

Native converts an IPv4-mapped IPv6 address to plain IPv4; otherwise returns self.

func (*IPAddr) Netmask

func (a *IPAddr) Netmask() string

Netmask returns the dotted-decimal or colon-separated netmask string.

func (*IPAddr) Not

func (a *IPAddr) Not() *IPAddr

Not returns the bitwise complement of the IP address.

func (*IPAddr) Or

func (a *IPAddr) Or(b *IPAddr) *IPAddr

Or returns the bitwise OR of two IP addresses (same family).

func (*IPAddr) Prefix

func (a *IPAddr) Prefix() int

Prefix returns the CIDR prefix length.

func (*IPAddr) Reverse

func (a *IPAddr) Reverse() string

Reverse returns the reverse-DNS lookup name for the address. IPv4: "1.0.168.192.in-addr.arpa", IPv6: full nibble form + ".ip6.arpa"

func (*IPAddr) SetAddr

func (a *IPAddr) SetAddr(s string) *IPAddr

SetAddr parses a new address string and replaces the current address in-place.

func (*IPAddr) SetPrefix

func (a *IPAddr) SetPrefix(prefixLen int)

SetPrefix sets the CIDR prefix length in-place.

func (*IPAddr) SetZoneId

func (a *IPAddr) SetZoneId(id string)

SetZoneId sets the IPv6 zone ID.

func (*IPAddr) ShiftLeft

func (a *IPAddr) ShiftLeft(n int) *IPAddr

ShiftLeft shifts the IP address integer left by n bits, returning a host address. Mirrors Ruby's IPAddr#<< operator.

func (*IPAddr) ShiftRight

func (a *IPAddr) ShiftRight(n int) *IPAddr

ShiftRight shifts the IP address integer right by n bits, returning a host address. Mirrors Ruby's IPAddr#>> operator.

func (*IPAddr) String

func (a *IPAddr) String() string

String returns the canonical string form of the IP address. For IPv4-mapped (::ffff:a.b.c.d) and IPv4-compat (::a.b.c.d) addresses, Go's net.IP.String() collapses them to just the IPv4 part, so we override.

func (*IPAddr) Succ

func (a *IPAddr) Succ() *IPAddr

Succ returns the next IP address (increments the host address by 1).

func (*IPAddr) ToI

func (a *IPAddr) ToI() *big.Int

ToI returns the IP address as a *big.Int (Ruby returns an arbitrary-precision integer).

func (*IPAddr) ToInt

func (a *IPAddr) ToInt() *big.Int

ToInt returns the IP address as a *big.Int (Ruby's to_i). Alias for ToI; ToI is used internally by ShiftLeft/ShiftRight.

func (*IPAddr) ToRange

func (a *IPAddr) ToRange() []*IPAddr

ToRange returns the first and last addresses of the network as a two-element slice [first, last]. This is used by the compiler to translate IPAddr#to_range.

func (*IPAddr) ToS

func (a *IPAddr) ToS() string

ToS is an alias for String, used by thanos method dispatch.

func (*IPAddr) ToString

func (a *IPAddr) ToString() string

ToString returns the full string representation without compression. For IPv4: dotted decimal. For IPv6: fully expanded colon-hex (no ::).

func (*IPAddr) ZoneId

func (a *IPAddr) ZoneId() string

ZoneId returns the zone ID for the address.

type MutexM

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

MutexM wraps sync.Mutex to implement Ruby's Mutex_m mixin.

func NewMutexM

func NewMutexM() *MutexM

NewMutexM creates a new MutexM instance.

type Observable

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

Observable implements Ruby's Observer pattern (Observable mixin) as a Go helper. Observers are tracked by string key mapped to callback functions.

func NewObservable

func NewObservable() *Observable

NewObservable creates a new Observable instance.

type OpenStruct

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

OpenStruct emulates Ruby's OpenStruct using a map[string]interface{}.

func NewOpenStruct

func NewOpenStruct(attrs map[string]interface{}) *OpenStruct

NewOpenStruct creates an OpenStruct, optionally initialized from a map.

func NewOpenStructEmpty

func NewOpenStructEmpty() *OpenStruct

NewOpenStructEmpty creates an empty OpenStruct.

func (*OpenStruct) DeleteField

func (o *OpenStruct) DeleteField(key string) interface{}

DeleteField removes a field and returns its value.

func (*OpenStruct) EachPair

func (o *OpenStruct) EachPair(fn func(string, interface{}))

EachPair iterates over key-value pairs, calling fn for each.

func (*OpenStruct) Eql

func (o *OpenStruct) Eql(other *OpenStruct) bool

Eql checks structural equality with another OpenStruct.

func (*OpenStruct) Freeze

func (o *OpenStruct) Freeze() *OpenStruct

Freeze marks the OpenStruct as frozen.

func (*OpenStruct) Get

func (o *OpenStruct) Get(key string) interface{}

Get retrieves an attribute by name (for [] access).

func (*OpenStruct) GetString

func (o *OpenStruct) GetString(key string) string

GetString retrieves an attribute as a string.

func (*OpenStruct) Hash

func (o *OpenStruct) Hash() int

Hash returns a hash code for the OpenStruct.

func (*OpenStruct) Inspect

func (o *OpenStruct) Inspect() string

Inspect returns a detailed string representation.

func (*OpenStruct) IsFrozen

func (o *OpenStruct) IsFrozen() bool

IsFrozen returns whether the OpenStruct is frozen.

func (*OpenStruct) MarshalDump

func (o *OpenStruct) MarshalDump() map[string]interface{}

MarshalDump returns the attributes map for serialization.

func (*OpenStruct) MarshalLoad

func (o *OpenStruct) MarshalLoad(data map[string]interface{})

MarshalLoad restores attributes from a map.

func (*OpenStruct) RespondTo

func (o *OpenStruct) RespondTo(method string) bool

RespondTo returns true if the OpenStruct has the given attribute or method.

func (*OpenStruct) Set

func (o *OpenStruct) Set(key string, value interface{})

Set sets an attribute by name (for []= access).

func (*OpenStruct) ToH

func (o *OpenStruct) ToH() map[string]interface{}

ToH returns the attributes as a map.

func (*OpenStruct) ToS

func (o *OpenStruct) ToS() string

ToS returns a string representation.

type OpenURIResponse

type OpenURIResponse struct {
	Body        string
	ContentType string
	Charset     string
	StatusCode  int
	StatusMsg   string
	BaseURI     string
	Headers     map[string]string
}

OpenURIResponse holds the result of an open-uri HTTP fetch.

type OptionParser

type OptionParser struct {
	Banner      string
	Version     string
	ProgramName string
	// contains filtered or unexported fields
}

OptionParser provides a simple option parser that maps Ruby's OptionParser.

func NewOptionParser

func NewOptionParser() *OptionParser

NewOptionParser creates a new OptionParser.

func NewOptionParserWithBanner

func NewOptionParserWithBanner(banner string) *OptionParser

NewOptionParserWithBanner creates a new OptionParser with a custom banner.

func (*OptionParser) Accept

func (op *OptionParser) Accept(_ string)

Accept is a no-op compatibility stub (type coercion registry).

func (*OptionParser) Getopts

func (op *OptionParser) Getopts(args []string, specs []string) map[string]string

Getopts is a simplified interface: returns a map of option names to values.

func (*OptionParser) Help

func (op *OptionParser) Help() string

Help returns formatted help text.

func (*OptionParser) On

func (op *OptionParser) On(flags []string, desc string, callback func(string))

On registers an option with a description and callback. flags can be "-s", "--long", "--long VALUE", "-s VALUE", etc.

func (*OptionParser) OnHead

func (op *OptionParser) OnHead(flags []string, desc string, callback func(string))

OnHead registers an option at the head of the list.

func (*OptionParser) OnTail

func (op *OptionParser) OnTail(flags []string, desc string, callback func(string))

OnTail registers an option at the tail of the list.

func (*OptionParser) Order

func (op *OptionParser) Order(args []string) []string

Order processes arguments in order mode (stops at first non-option).

func (*OptionParser) OrderBang

func (op *OptionParser) OrderBang(args []string) []string

OrderBang is the destructive version of Order.

func (*OptionParser) Parse

func (op *OptionParser) Parse(args []string) []string

Parse parses the given arguments and returns remaining non-option args.

func (*OptionParser) ParseBang

func (op *OptionParser) ParseBang(args []string) []string

ParseBang parses os.Args[1:] in-place (destructive parse).

func (*OptionParser) Reject

func (op *OptionParser) Reject(_ string)

Reject is a no-op compatibility stub.

func (*OptionParser) Separator

func (op *OptionParser) Separator(text string)

Separator adds a separator line to the help output.

func (*OptionParser) SetBanner

func (op *OptionParser) SetBanner(b string)

SetBanner sets the banner string.

func (*OptionParser) SetProgramName

func (op *OptionParser) SetProgramName(name string)

SetProgramName sets the program name.

func (*OptionParser) SetVersion

func (op *OptionParser) SetVersion(v string)

SetVersion sets the version string.

func (*OptionParser) ToS

func (op *OptionParser) ToS() string

ToS returns the help text.

type PStore

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

PStore is a simple persistent key-value store backed by a file. Mirrors Ruby's PStore class using Go's encoding/gob.

func NewPStore

func NewPStore(path string) *PStore

NewPStore creates or opens a PStore at the given path.

func (*PStore) Abort

func (ps *PStore) Abort()

Abort rolls back changes made in the current transaction. Mirrors PStore#abort.

func (*PStore) Commit

func (ps *PStore) Commit()

Commit saves the current state. Mirrors PStore#commit.

func (*PStore) Delete

func (ps *PStore) Delete(key string) string

Delete removes a key and returns its value. Mirrors PStore#delete.

func (*PStore) Fetch

func (ps *PStore) Fetch(key string) string

Fetch retrieves a value by key. Mirrors PStore#fetch.

func (*PStore) Get

func (ps *PStore) Get(key string) string

Get retrieves a value by key. Mirrors PStore#[].

func (*PStore) GetUltraSafe

func (ps *PStore) GetUltraSafe() bool

GetUltraSafe returns the ultra_safe flag.

func (*PStore) Path

func (ps *PStore) Path() string

Path returns the file path of the store. Mirrors PStore#path.

func (*PStore) RootExists

func (ps *PStore) RootExists(key string) bool

RootExists checks if a key exists. Mirrors PStore#root?.

func (*PStore) Roots

func (ps *PStore) Roots() []string

Roots returns all keys sorted. Mirrors PStore#roots.

func (*PStore) Set

func (ps *PStore) Set(key string, value string) string

Set stores a value by key. Mirrors PStore#[]=.

func (*PStore) SetUltraSafe

func (ps *PStore) SetUltraSafe(v bool)

SetUltraSafe sets the ultra_safe flag.

func (*PStore) Transaction

func (ps *PStore) Transaction(fn func())

Transaction starts a transaction, runs the given function, and commits. Mirrors PStore#transaction { ... }.

type Pathname

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

Pathname wraps a file path string, mirroring Ruby's Pathname class.

func NewPathname

func NewPathname(path string) *Pathname

NewPathname creates a new Pathname from a path string.

func (*Pathname) Ascend

func (p *Pathname) Ascend() []*Pathname

Ascend yields the path and each parent up to the root, returning them as a slice.

func (*Pathname) Atime

func (p *Pathname) Atime() time.Time

Atime returns the access time of the file (falls back to mtime on platforms that don't expose it).

func (*Pathname) Basename

func (p *Pathname) Basename() string

func (*Pathname) Binread

func (p *Pathname) Binread() string

Binread reads the file as raw bytes and returns it as a string.

func (*Pathname) Binwrite

func (p *Pathname) Binwrite(data string)

Binwrite writes a raw byte string to the file.

func (*Pathname) Birthtime

func (p *Pathname) Birthtime() time.Time

Birthtime returns the creation time of the file (best effort, falls back to mtime).

func (*Pathname) Children

func (p *Pathname) Children() []*Pathname

Children returns the contents of the directory as a slice of Pathnames.

func (*Pathname) Chmod

func (p *Pathname) Chmod(mode int)

Chmod changes the file permissions.

func (*Pathname) Chown

func (p *Pathname) Chown(uid, gid int)

Chown changes the owner and group of the file.

func (*Pathname) Cleanpath

func (p *Pathname) Cleanpath() *Pathname

Cleanpath returns the cleaned version of the path as a new Pathname.

func (*Pathname) Compare

func (p *Pathname) Compare(other *Pathname) int

Compare compares the path strings lexicographically. Returns -1, 0, or 1.

func (*Pathname) Concat

func (p *Pathname) Concat(other string) *Pathname

Concat joins the given string to the path (same semantics as Join for porting purposes).

func (*Pathname) Ctime

func (p *Pathname) Ctime() time.Time

Ctime returns the inode change time (falls back to mtime on platforms without direct support).

func (*Pathname) Descend

func (p *Pathname) Descend() []*Pathname

Descend yields the root and each directory down to the full path, returning them as a slice.

func (*Pathname) Dirname

func (p *Pathname) Dirname() string

func (*Pathname) EachChild

func (p *Pathname) EachChild() []*Pathname

EachChild returns the children of the directory (same as Children).

func (*Pathname) EachEntry

func (p *Pathname) EachEntry() []*Pathname

EachEntry returns directory entries as Pathnames (same as Entries but without . and ..).

func (*Pathname) EachFilename

func (p *Pathname) EachFilename() []string

EachFilename returns each component of the path as a string slice.

func (*Pathname) EachLine

func (p *Pathname) EachLine() []string

EachLine returns the lines of the file as a slice (like Readlines).

func (*Pathname) Empty

func (p *Pathname) Empty() bool

Empty returns true if the file is empty or the directory has no entries.

func (*Pathname) Entries

func (p *Pathname) Entries() []*Pathname

Entries returns the directory contents (including "." and "..") as Pathnames.

func (*Pathname) Eql

func (p *Pathname) Eql(other *Pathname) bool

Eql returns true if both Pathnames have the same path string.

func (*Pathname) Exist

func (p *Pathname) Exist() bool

func (*Pathname) ExpandPath

func (p *Pathname) ExpandPath() string

func (*Pathname) Extname

func (p *Pathname) Extname() string

func (*Pathname) Find

func (p *Pathname) Find() []*Pathname

Find recursively walks the path tree and returns all entries as Pathnames.

func (*Pathname) Fnmatch

func (p *Pathname) Fnmatch(pattern string) bool

Fnmatch reports whether the path matches the given shell pattern using Ruby semantics: * matches any character sequence including path separators.

func (*Pathname) Freeze

func (p *Pathname) Freeze() *Pathname

Freeze is a no-op for Go.

func (*Pathname) Frozen

func (p *Pathname) Frozen() bool

Frozen always returns true for Go.

func (*Pathname) Ftype

func (p *Pathname) Ftype() string

Ftype returns the file type string: "file", "directory", "link", "characterSpecial", "blockSpecial", "fifo", "socket", or "unknown".

func (*Pathname) Glob

func (p *Pathname) Glob(pattern string) []*Pathname

Glob returns pathnames matching the given pattern within this directory.

func (*Pathname) Hash

func (p *Pathname) Hash() int

Hash returns a hash value for the pathname (based on the path string).

func (*Pathname) Inspect

func (p *Pathname) Inspect() string

Inspect returns the Ruby-style inspect representation of the path.

func (*Pathname) IsAbsolute

func (p *Pathname) IsAbsolute() bool

IsAbsolute returns true if the path is absolute.

func (*Pathname) IsBlockdev

func (p *Pathname) IsBlockdev() bool

IsBlockdev returns true if the path is a block device.

func (*Pathname) IsChardev

func (p *Pathname) IsChardev() bool

IsChardev returns true if the path is a character device.

func (*Pathname) IsDirectory

func (p *Pathname) IsDirectory() bool

func (*Pathname) IsExecutable

func (p *Pathname) IsExecutable() bool

IsExecutable returns true if the file has any execute permission bits set.

func (*Pathname) IsExecutableReal

func (p *Pathname) IsExecutableReal() bool

IsExecutableReal returns true if the real user has execute permission.

func (*Pathname) IsFile

func (p *Pathname) IsFile() bool

func (*Pathname) IsGrpowned

func (p *Pathname) IsGrpowned() bool

IsGrpowned returns true if the file is group-owned by the current user's group.

func (*Pathname) IsMountpoint

func (p *Pathname) IsMountpoint() bool

IsMountpoint checks if the path is a mount point. On most systems, we check if the device of the path differs from its parent.

func (*Pathname) IsOwned

func (p *Pathname) IsOwned() bool

IsOwned returns true if the current user owns the file.

func (*Pathname) IsPipe

func (p *Pathname) IsPipe() bool

IsPipe returns true if the path is a named pipe.

func (*Pathname) IsReadable

func (p *Pathname) IsReadable() bool

IsReadable returns true if the file has any read permission bits set.

func (*Pathname) IsReadableReal

func (p *Pathname) IsReadableReal() bool

IsReadableReal returns true if the real user has read permission.

func (*Pathname) IsRelative

func (p *Pathname) IsRelative() bool

IsRelative returns true if the path is relative.

func (*Pathname) IsRoot

func (p *Pathname) IsRoot() bool

IsRoot returns true if the path is the filesystem root.

func (*Pathname) IsSetgid

func (p *Pathname) IsSetgid() bool

IsSetgid returns true if the setgid bit is set.

func (*Pathname) IsSetuid

func (p *Pathname) IsSetuid() bool

IsSetuid returns true if the setuid bit is set.

func (*Pathname) IsSocket

func (p *Pathname) IsSocket() bool

IsSocket returns true if the path is a socket.

func (*Pathname) IsSticky

func (p *Pathname) IsSticky() bool

IsSticky returns true if the sticky bit is set.

func (p *Pathname) IsSymlink() bool

IsSymlink returns true if the path is a symbolic link.

func (*Pathname) IsWorldReadable

func (p *Pathname) IsWorldReadable() bool

IsWorldReadable returns true if the file is world-readable.

func (*Pathname) IsWorldWritable

func (p *Pathname) IsWorldWritable() bool

IsWorldWritable returns true if the file is world-writable.

func (*Pathname) IsWritable

func (p *Pathname) IsWritable() bool

IsWritable returns true if the file has any write permission bits set.

func (*Pathname) IsWritableReal

func (p *Pathname) IsWritableReal() bool

IsWritableReal returns true if the real user has write permission.

func (*Pathname) IsZero

func (p *Pathname) IsZero() bool

IsZero returns true if the file exists and has zero bytes.

func (*Pathname) Join

func (p *Pathname) Join(other string) *Pathname

func (*Pathname) Lchmod

func (p *Pathname) Lchmod(mode int)

Lchmod is a no-op on most platforms (only some Unix support lchmod).

func (*Pathname) Lchown

func (p *Pathname) Lchown(uid, gid int)

Lchown changes the owner and group of the symlink itself.

func (*Pathname) Lstat

func (p *Pathname) Lstat() os.FileInfo

Lstat returns the FileInfo for the path (not following symlinks).

func (*Pathname) Lutime

func (p *Pathname) Lutime(atime, mtime time.Time)

Utime sets the access and modification times of the file.

func (p *Pathname) MakeLink(target string)

MakeLink creates a hard link at p.path pointing to target.

func (p *Pathname) MakeSymlink(target string)

MakeSymlink creates a symlink at p.path pointing to target.

func (*Pathname) MarshalText

func (p *Pathname) MarshalText() ([]byte, error)

MarshalText makes Pathname print correctly with fmt.Println.

func (*Pathname) Mkdir

func (p *Pathname) Mkdir()

Mkdir creates the directory at the path.

func (*Pathname) Mkpath

func (p *Pathname) Mkpath()

Mkpath creates the directory and all parents (like mkdir -p).

func (*Pathname) Mtime

func (p *Pathname) Mtime() time.Time

Mtime returns the modification time of the file.

func (*Pathname) Open

func (p *Pathname) Open() (*os.File, error)

Open opens the file at the path. Caller must close the returned file.

func (*Pathname) Opendir

func (p *Pathname) Opendir() ([]*Pathname, error)

Opendir opens the directory at the path for reading entries.

func (*Pathname) Parent

func (p *Pathname) Parent() *Pathname

Parent returns the parent directory as a new Pathname.

func (*Pathname) Read

func (p *Pathname) Read() string

func (*Pathname) Readlines

func (p *Pathname) Readlines() []string

Readlines returns the lines of the file as a slice of strings (with newlines).

func (p *Pathname) Readlink() *Pathname

Readlink returns the target of the symbolic link as a new Pathname.

func (*Pathname) Realdirpath

func (p *Pathname) Realdirpath() *Pathname

Realdirpath resolves symlinks in the directory part; the final component need not exist (mirrors Ruby's Pathname#realdirpath).

func (*Pathname) Realpath

func (p *Pathname) Realpath() *Pathname

Realpath resolves symlinks and returns the canonical path.

func (*Pathname) RelativePathFrom

func (p *Pathname) RelativePathFrom(base string) *Pathname

RelativePathFrom returns a relative path from the given base directory.

func (*Pathname) Rename

func (p *Pathname) Rename(dest string)

Rename renames the file to the given destination path.

func (*Pathname) Rmdir

func (p *Pathname) Rmdir()

Rmdir removes the (empty) directory at the path.

func (*Pathname) Rmtree

func (p *Pathname) Rmtree()

Rmtree removes the path and all its children.

func (*Pathname) Size

func (p *Pathname) Size() int64

Size returns the file size in bytes.

func (*Pathname) SizeQ

func (p *Pathname) SizeQ() int64

SizeQ returns the file size, or 0 if the file does not exist (Ruby's size?).

func (*Pathname) SplitPath

func (p *Pathname) SplitPath() []*Pathname

SplitPath returns [dir, base] as a two-element Pathname slice.

func (*Pathname) Stat

func (p *Pathname) Stat() os.FileInfo

Stat returns the FileInfo for the path.

func (*Pathname) String

func (p *Pathname) String() string

func (*Pathname) Sub

func (p *Pathname) Sub(pattern, replacement string) *Pathname

Sub replaces the first occurrence of pattern with replacement in the path string.

func (*Pathname) SubExt

func (p *Pathname) SubExt(ext string) *Pathname

SubExt replaces the file extension with the given extension.

func (*Pathname) Sysopen

func (p *Pathname) Sysopen() int

Sysopen opens the file and returns the file descriptor as an integer.

func (*Pathname) Taint

func (p *Pathname) Taint() *Pathname

Taint is a no-op (Ruby taint is removed in Ruby 3+).

func (*Pathname) Tainted

func (p *Pathname) Tainted() bool

Tainted always returns false.

func (*Pathname) ToPath

func (p *Pathname) ToPath() string

func (*Pathname) Truncate

func (p *Pathname) Truncate(length int)

Truncate truncates the file to the given length.

func (p *Pathname) Unlink()

Unlink removes the file at the path.

func (*Pathname) Untaint

func (p *Pathname) Untaint() *Pathname

Untaint is a no-op.

func (*Pathname) Utime

func (p *Pathname) Utime(atime, mtime time.Time)

Utime sets the access and modification times of the file.

func (*Pathname) Write

func (p *Pathname) Write(content string)

type StringScanner

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

StringScanner implements Ruby's StringScanner class for sequential string parsing. It tracks a current position and provides anchored/unanchored regexp scanning.

func NewStringScanner

func NewStringScanner(str string) *StringScanner

NewStringScanner creates a new StringScanner positioned at the start of str.

func (*StringScanner) BolP

func (ss *StringScanner) BolP() bool

BolP returns true if the current position is at the beginning of a line.

func (*StringScanner) Captures

func (ss *StringScanner) Captures() []string

Captures returns the capture groups from the last match as a slice of strings, excluding the full match at index 0. Returns nil if there was no match.

func (*StringScanner) Check

func (ss *StringScanner) Check(pattern *regexp.Regexp) string

Check attempts to match pattern anchored at the current position without advancing. Returns matched string or "" on no match.

func (*StringScanner) CheckUntil

func (ss *StringScanner) CheckUntil(pattern *regexp.Regexp) string

CheckUntil scans forward without advancing to find pattern. Returns the substring up through the match end, or "" on no match.

func (*StringScanner) Concat

func (ss *StringScanner) Concat(str string) *StringScanner

Concat appends str to the scanner's string and returns the scanner.

func (*StringScanner) EOS

func (ss *StringScanner) EOS() bool

EOS returns true if the scanner is at the end of the string.

func (*StringScanner) Exist

func (ss *StringScanner) Exist(pattern *regexp.Regexp) int

Exist checks whether pattern matches anywhere in the remaining string. Returns the number of bytes from the current position to the end of the match, or -1 if there is no match. (Ruby returns nil on no match.)

func (*StringScanner) Getch

func (ss *StringScanner) Getch() string

Getch returns the next character and advances the position by one. Returns "" if at end of string.

func (*StringScanner) Inspect

func (ss *StringScanner) Inspect() string

Inspect returns a human-readable description of the scanner state.

func (*StringScanner) MatchSize

func (ss *StringScanner) MatchSize(pattern *regexp.Regexp) int

MatchSize returns the length of the match if pattern matches at the current position (anchored), without advancing. Returns -1 on no match. Ruby: match? returns nil on no match; -1 is the Go sentinel.

func (*StringScanner) Matched

func (ss *StringScanner) Matched() string

Matched returns the last matched string. Returns "" if no prior match.

func (*StringScanner) MatchedP

func (ss *StringScanner) MatchedP() bool

MatchedP returns true if the last operation produced a match.

func (*StringScanner) MatchedSize

func (ss *StringScanner) MatchedSize() int

MatchedSize returns the byte length of the last matched string, or -1 if there was no match. (Ruby returns nil on no match.)

func (*StringScanner) NamedCapture

func (ss *StringScanner) NamedCapture(name string) string

NamedCapture returns the value of a single named capture group from the last match. Returns "" if the group does not exist or there was no match.

func (*StringScanner) NamedCaptures

func (ss *StringScanner) NamedCaptures() map[string]string

NamedCaptures returns a map of named capture group names to their matched strings from the last match. Returns an empty map if no match or no named groups.

func (*StringScanner) Peek

func (ss *StringScanner) Peek(n int) string

Peek returns the next n characters without advancing the position.

func (*StringScanner) Pos

func (ss *StringScanner) Pos() int

Pos returns the current scanner position (byte offset).

func (*StringScanner) PostMatch

func (ss *StringScanner) PostMatch() string

PostMatch returns the portion of the string after the last match.

func (*StringScanner) PreMatch

func (ss *StringScanner) PreMatch() string

PreMatch returns the portion of the string before the last match.

func (*StringScanner) Reset

func (ss *StringScanner) Reset() *StringScanner

Reset moves the position back to the beginning of the string and clears match state.

func (*StringScanner) Rest

func (ss *StringScanner) Rest() string

Rest returns the substring from the current position to the end of the string.

func (*StringScanner) RestP

func (ss *StringScanner) RestP() bool

RestP returns true if there are characters remaining (i.e. not at end of string).

func (*StringScanner) RestSize

func (ss *StringScanner) RestSize() int

RestSize returns the number of characters remaining from the current position.

func (*StringScanner) Scan

func (ss *StringScanner) Scan(pattern *regexp.Regexp) string

Scan attempts to match pattern anchored at the current position. On match: advances pos past the match and returns the matched string. On no match: returns "" and sets matched? to false.

func (*StringScanner) ScanUntil

func (ss *StringScanner) ScanUntil(pattern *regexp.Regexp) string

ScanUntil scans forward from the current position until pattern matches. Returns the substring from the current position up through the end of the match, and advances pos. Returns "" on no match.

func (*StringScanner) SetPos

func (ss *StringScanner) SetPos(n int)

SetPos sets the current scanner position (byte offset).

func (*StringScanner) SetStr

func (ss *StringScanner) SetStr(s string)

SetStr replaces the string being scanned and resets position.

func (*StringScanner) Size

func (ss *StringScanner) Size() int

Size returns the total number of captures in the last match (including the full match at index 0), or -1 if there was no match.

func (*StringScanner) Skip

func (ss *StringScanner) Skip(pattern *regexp.Regexp) int

Skip attempts to match pattern anchored at the current position and advances past it. Returns the number of bytes skipped, or 0 on no match.

func (*StringScanner) SkipUntil

func (ss *StringScanner) SkipUntil(pattern *regexp.Regexp) int

SkipUntil scans forward until pattern matches and advances pos to end of match. Returns the number of bytes advanced, or 0 on no match.

func (*StringScanner) Str

func (ss *StringScanner) Str() string

Str returns the string being scanned.

func (*StringScanner) Terminate

func (ss *StringScanner) Terminate() *StringScanner

Terminate moves the position to the end of the string and clears match state.

func (*StringScanner) Unscan

func (ss *StringScanner) Unscan() *StringScanner

Unscan rewinds pos to the position before the most recent match.

type Tempfile

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

Tempfile is a shim for Ruby's Tempfile class. It wraps *os.File and tracks the path so it remains accessible after Close.

func NewTempfile

func NewTempfile(prefix string) *Tempfile

NewTempfile creates a new temporary file with the given prefix. Mirrors Ruby's Tempfile.new(prefix).

func TempfileCreate

func TempfileCreate(prefix string) *Tempfile

TempfileCreate creates a temp file, yields it to a function, then cleans up. Mirrors Ruby's Tempfile.create(prefix).

func TempfileOpen

func TempfileOpen(prefix string) *Tempfile

TempfileOpen creates a temp file (like new) for use with Tempfile.open. Mirrors Ruby's Tempfile.open(prefix).

func (*Tempfile) Close

func (t *Tempfile) Close()

Close closes the file without deleting it. Mirrors Ruby's Tempfile#close.

func (t *Tempfile) CloseAndUnlink()

CloseAndUnlink closes and deletes the file. Mirrors Ruby's Tempfile#close!.

func (*Tempfile) Flush

func (t *Tempfile) Flush()

Flush syncs buffered data to the underlying storage. Mirrors Ruby's Tempfile#flush.

func (*Tempfile) Open

func (t *Tempfile) Open()

Open reopens the underlying temp file for reading/writing. Mirrors Ruby's Tempfile#open.

func (*Tempfile) Path

func (t *Tempfile) Path() string

Path returns the absolute path to the temporary file. Mirrors Ruby's Tempfile#path.

func (*Tempfile) Read

func (t *Tempfile) Read() string

Read seeks to the start of the file and returns its full contents. Mirrors Ruby's Tempfile#read.

func (*Tempfile) Rewind

func (t *Tempfile) Rewind() int

Rewind seeks to the beginning of the file and returns 0. Mirrors Ruby's Tempfile#rewind.

func (*Tempfile) Size

func (t *Tempfile) Size() int

Size returns the current size of the file in bytes. Mirrors Ruby's Tempfile#size / Tempfile#length.

func (*Tempfile) Truncate

func (t *Tempfile) Truncate(size int) int

Truncate truncates the file to at most size bytes. Mirrors Ruby's Tempfile#truncate(size).

func (t *Tempfile) Unlink()

Unlink deletes the file from the filesystem. Mirrors Ruby's Tempfile#unlink / Tempfile#delete.

func (*Tempfile) Write

func (t *Tempfile) Write(s string) int

Write writes s to the file and returns the number of bytes written. Mirrors Ruby's Tempfile#write(str).

type TimeoutError

type TimeoutError struct {
	Message string
}

TimeoutError is raised when a timeout expires.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

type URI

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

URI wraps *url.URL to provide Ruby-compatible accessor methods.

func URIJoin

func URIJoin(parts ...string) *URI

URIJoin joins URI strings by resolving each relative to the previous.

func URIParse

func URIParse(s string) *URI

URIParse wraps url.Parse, ignoring errors like Ruby's URI.parse.

func (*URI) Absolute

func (u *URI) Absolute() bool

Absolute returns true if the URI has a scheme (is absolute).

func (*URI) Authority

func (u *URI) Authority() string

Authority returns host:port, or just host if no port is set.

func (*URI) DecodedPassword

func (u *URI) DecodedPassword() string

DecodedPassword returns the percent-decoded password component.

func (*URI) DecodedUser

func (u *URI) DecodedUser() string

DecodedUser returns the percent-decoded username component.

func (*URI) DefaultPort

func (u *URI) DefaultPort() int

DefaultPort returns the default port for the URI's scheme (http=80, https=443, etc.). Returns 0 for unknown schemes.

func (*URI) Dup

func (u *URI) Dup() *URI

Dup returns a copy of the URI.

func (*URI) Equal

func (u *URI) Equal(other *URI) bool

Equal compares two URIs by their string representation (Ruby: ==).

func (*URI) Format

func (u *URI) Format(f interface{ WriteString(string) (int, error) }, _ rune)

StringForPuts allows fmt.Println to output the URI string directly.

func (*URI) Fragment

func (u *URI) Fragment() string

func (*URI) Freeze

func (u *URI) Freeze() *URI

Freeze is a no-op for Go (Ruby frozen semantics).

func (*URI) Frozen

func (u *URI) Frozen() bool

Frozen always returns true (Go values are effectively immutable structurally).

func (*URI) GoString

func (u *URI) GoString() string

Implement fmt.Stringer for puts support.

func (*URI) Host

func (u *URI) Host() string

func (*URI) Hostname

func (u *URI) Hostname() string

func (*URI) Inspect

func (u *URI) Inspect() string

Inspect returns a Ruby-style inspect string for a URI. Matches Ruby's format: "#<URI::HTTP ...>" or "#<URI::Generic ...>" for relative URIs.

func (*URI) IsHierarchical

func (u *URI) IsHierarchical() bool

IsHierarchical returns true if the URI is hierarchical (has an authority or path).

func (*URI) MarshalText

func (u *URI) MarshalText() ([]byte, error)

MarshalText makes URI print correctly with fmt.Println.

func (*URI) Merge

func (u *URI) Merge(other string) *URI

Merge resolves other (a URI string) against u, returning a new URI. This mirrors Ruby's URI#merge and URI#+ methods.

func (*URI) Normalize

func (u *URI) Normalize() *URI

Normalize returns a new URI with the scheme and host lowercased.

func (*URI) Opaque

func (u *URI) Opaque() string

Opaque returns the opaque component of the URI (non-hierarchical URIs).

func (*URI) Origin

func (u *URI) Origin() string

Origin returns scheme://host (with port only if non-standard).

func (*URI) Password

func (u *URI) Password() string

Password returns the password component of the URI, or empty string.

func (*URI) Path

func (u *URI) Path() string

func (*URI) Port

func (u *URI) Port() int

Port returns the port as an integer, or 0 if not present.

func (*URI) Query

func (u *URI) Query() string

func (*URI) Relative

func (u *URI) Relative() bool

Relative returns true if the URI has no scheme (is relative).

func (*URI) RequestURI

func (u *URI) RequestURI() string

RequestURI returns the path and query string (e.g. "/path?q=1").

func (*URI) RouteFrom

func (u *URI) RouteFrom(other string) *URI

RouteFrom returns the relative path from other to u.

func (*URI) RouteTo

func (u *URI) RouteTo(other string) *URI

RouteTo returns the relative path from u to other.

func (*URI) Scheme

func (u *URI) Scheme() string

func (*URI) Select

func (u *URI) Select(components ...string) []string

Select returns the components of the URI that the given selectors match. This is a simplified version: returns all non-empty components.

func (*URI) SetFragment

func (u *URI) SetFragment(f string) string

SetFragment sets the fragment and returns the new value (Ruby: fragment=).

func (*URI) SetHost

func (u *URI) SetHost(h string) string

SetHost sets the host component of the URI and returns it.

func (*URI) SetHostname

func (u *URI) SetHostname(h string) string

SetHostname sets just the hostname (preserving port) and returns it.

func (*URI) SetPassword

func (u *URI) SetPassword(p string) string

SetPassword sets the password component of the URI and returns it.

func (*URI) SetPath

func (u *URI) SetPath(p string) string

SetPath sets the path and returns the new value (Ruby: path=).

func (*URI) SetPort

func (u *URI) SetPort(p int) int

SetPort sets the port component of the URI and returns it.

func (*URI) SetQuery

func (u *URI) SetQuery(q string) string

SetQuery sets the raw query string and returns the new value (Ruby: query=).

func (*URI) SetScheme

func (u *URI) SetScheme(s string) string

SetScheme sets the scheme component of the URI and returns it.

func (*URI) SetUser

func (u *URI) SetUser(name string) string

SetUser sets the username component of the URI and returns it.

func (*URI) SetUserinfo

func (u *URI) SetUserinfo(info string) string

SetUserinfo sets the userinfo component ("user:password") and returns it.

func (*URI) String

func (u *URI) String() string

func (*URI) User

func (u *URI) User() string

User returns the username component of the URI, or empty string.

func (*URI) Userinfo

func (u *URI) Userinfo() string

Userinfo returns "user:password" if both are present, or just "user".

type WeakRef

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

WeakRef wraps an arbitrary value. In Go there are no weak references, so this is effectively a strong reference that satisfies the Ruby WeakRef API.

func NewWeakRef

func NewWeakRef(obj any) *WeakRef

NewWeakRef creates a WeakRef wrapping the given object.

Jump to

Keyboard shortcuts

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