po

package
v2.6.2 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2025 License: MIT Imports: 11 Imported by: 0

README

Po

structure

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrBadPluralEntry = errors.New("the entry can't be plural and singular at the same time")

Functions

func CompareEntriesFunc

func CompareEntriesFunc(a, b Entries, cmp Cmp[Entry]) int

CompareEntriesFunc compares two slices of entries using the given comparison function.

func CompareEntry

func CompareEntry(a, b Entry) int

CompareEntry compares two entries based on their obsolescence, fuzzy flag, location, and ID (in that order).

func CompareEntryByFile

func CompareEntryByFile(a, b Entry) int

CompareEntryByFile compares entries by file paths in their locations.

func CompareEntryByFuzzy

func CompareEntryByFuzzy(a, b Entry) int

CompareEntryByFuzzy compares entries by their fuzzy flag.

func CompareEntryByID

func CompareEntryByID(a, b Entry) int

CompareEntryByID compares entries by their unified ID.

func CompareEntryByLine

func CompareEntryByLine(a, b Entry) int

CompareEntryByLine compares entries by line numbers in their locations.

func CompareEntryByLocation

func CompareEntryByLocation(a, b Entry) int

CompareEntryByLocation compares entries by their location slices.

func CompareEntryByObsolete

func CompareEntryByObsolete(a, b Entry) int

CompareEntryByObsolete compares entries by their obsolescence status.

func CompareEntryByStr

func CompareEntryByStr(a, b Entry) int

CompareEntryByStr compares entries by their translation strings, including plural forms.

func CompareLocation

func CompareLocation(a, b Location) int

CompareLocation compares two locations by file path and then by line number.

func CompareLocationByFile

func CompareLocationByFile(a, b Location) int

CompareLocationByFile compares two locations by cleaned file path string.

func CompareLocationByLine

func CompareLocationByLine(a, b Location) int

CompareLocationByLine compares two locations by line number.

func CompareLocationsFunc

func CompareLocationsFunc(a, b Locations, cmp Cmp[Location]) int

CompareLocationsFunc compares two slices of locations using the given comparison function.

func ComparePluralEntriesFunc

func ComparePluralEntriesFunc(a, b PluralEntries, cmp Cmp[PluralEntry]) int

ComparePluralEntriesFunc compares two plural entry slices using the provided comparison function.

func ComparePluralEntry

func ComparePluralEntry(a, b PluralEntry) int

ComparePluralEntry compares two plural entries by ID and then by translation string.

func ComparePluralEntryByID

func ComparePluralEntryByID(a, b PluralEntry) int

ComparePluralEntryByID compares two plural entries by their numeric IDs.

func ComparePluralEntryByStr

func ComparePluralEntryByStr(a, b PluralEntry) int

ComparePluralEntryByStr compares two plural entries by their translation strings.

func EntryIDMatchRatio

func EntryIDMatchRatio(e1, e2 Entry) int

EntryIDMatchRatio returns the average fuzzy match ratio between the identifiers of two entries. It compares the ID, context (if present), and plural ID (if both are plural entries).

func EntryStrMatchRatio

func EntryStrMatchRatio(e1, e2 Entry) int

EntryStrMatchRatio returns the average fuzzy match ratio between the translation strings of two entries, including plural forms if applicable.

Types

type Cmp

type Cmp[X any] = func(a, b X) int

type Compiler

type Compiler interface {
	SetFile(*File)
	ToWriter(io.Writer) error
	ToBytes() []byte
}

type DuplicatedEntryError added in v2.6.1

type DuplicatedEntryError struct {
	OriginalIndex int
}

func (*DuplicatedEntryError) Error added in v2.6.1

func (e *DuplicatedEntryError) Error() string

type Entries

type Entries []Entry

Entries represents a collection of Entry objects.

func Merge

func Merge(def, ref Entries, options ...MergeOption) Entries

Merge merges def and ref using the default merge configuration, optionally modified by MergeOptions.

func MergeWithConfig

func MergeWithConfig(config MergeConfig, def, ref Entries) Entries

MergeWithConfig merges entries from def and ref using the provided MergeConfig.

If FuzzyMatch is enabled, unmatched entries may be matched based on string similarity. If KeepPreviousIDs is set, original IDs are preserved in unmatched entries. If Sort is enabled, the resulting set is sorted using the given SortMode.

func (Entries) BestIDRatio

func (e Entries) BestIDRatio(e1 Entry) (best, highestRatio int)

func (Entries) BestStrRatio

func (e Entries) BestStrRatio(e1 Entry) (best, highestRatio int)

func (Entries) CatchDuplicateEntries added in v2.6.1

func (e Entries) CatchDuplicateEntries() []error

func (Entries) CleanDuplicates

func (e Entries) CleanDuplicates() Entries

CleanDuplicates removes duplicate entries with the same ID and context, merging their locations.

func (Entries) CleanEmpties added in v2.3.0

func (e Entries) CleanEmpties() Entries

func (Entries) CleanFuzzy

func (e Entries) CleanFuzzy() Entries

func (Entries) CleanObsoletes

func (e Entries) CleanObsoletes() Entries

func (Entries) ContainsFunc added in v2.3.0

func (e Entries) ContainsFunc(f func(e Entry) bool) bool

func (Entries) ContainsUnifiedID

func (e Entries) ContainsUnifiedID(uid string) bool

func (Entries) CutHeader

func (e Entries) CutHeader() Entries

func (Entries) Equal

func (e Entries) Equal(e2 Entries) bool

func (Entries) FuzzyFind

func (e Entries) FuzzyFind(id, context string) int

func (Entries) HasDuplicates

func (e Entries) HasDuplicates() bool

func (Entries) Header

func (e Entries) Header() (h Header)

func (Entries) Index

func (e Entries) Index(id, context string) int

func (Entries) IndexByUnifiedID

func (e Entries) IndexByUnifiedID(uid string) int

func (Entries) IndexFunc added in v2.3.0

func (e Entries) IndexFunc(f func(Entry) bool) int

func (Entries) IsSorted

func (e Entries) IsSorted() bool

func (Entries) IsSortedFunc

func (e Entries) IsSortedFunc(cmp Cmp[Entry]) bool

func (Entries) PrepareSorter

func (e Entries) PrepareSorter(cmp Cmp[Entry]) func() Entries

func (Entries) Solve

func (e Entries) Solve() Entries

Solve is a convenience method that uses the default SolveMerge function to resolve duplicates in Entries. It calls SolveFunc with SolveMerge as the merger function.

func (Entries) SolveFunc

func (e Entries) SolveFunc(merger MergeFunc) Entries

SolveFunc processes a slice of Entries using a provided merging function (merger). It groups entries by a unified identifier (UnifiedID) and merges duplicates using the merger. The result is a cleaned list of Entries with duplicates resolved.

func (Entries) Sort

func (e Entries) Sort() Entries

Sort organizes the entries by grouping them by file and sorting them by line.

func (Entries) SortFunc

func (e Entries) SortFunc(cmp Cmp[Entry]) Entries

func (Entries) String added in v2.6.0

func (e Entries) String() string

func (Entries) Validate added in v2.3.0

func (e Entries) Validate() []error

type EntriesOrFile

type EntriesOrFile = interface{ Entries | *File | File }

type Entry

type Entry struct {
	Flags             []string // List of flags (e.g., "fuzzy").
	Comments          []string // Translator comments.
	ExtractedComments []string // Automatically extracted comments.
	Previous          []string // Previous msgid or msgstr lines.

	Obsolete  bool          // Indicates whether the entry is obsolete.
	ID        string        // The original string to be translated.
	Context   string        // Context of the string, if any.
	Plural    string        // The plural form of the original string, if applicable.
	Plurals   PluralEntries // List of plural translations.
	Str       string        // Translated string (singular).
	Locations Locations     // List of source code references.
}

Entry represents a single translatable message in a PO file.

It may include context, plural forms, translation string(s), comments, flags, and source code locations.

func SolveMerge

func SolveMerge(a, b Entry) *Entry

SolveMerge merges two Entry objects based on certain preference criteria. It prefers the Entry with a higher priority according to CompareEntry. It combines the Locations from both entries. Then, it chooses the Str and Plurals fields based on CompareEntryByStr.

func (Entry) Equal

func (e Entry) Equal(x Entry) bool

Equal reports whether two entries are semantically equivalent.

It compares ID, context, translation string, flags, and obsolete status.

func (Entry) FullHash added in v2.5.0

func (e Entry) FullHash() uint32

FullHash returns a hash based on the unified ID including context and plural.

WARNING: This is intended for internal use and is not compatible with gettext's hash.

func (Entry) HasContext

func (e Entry) HasContext() bool

HasContext reports whether the entry has a non-empty context.

func (Entry) Hash added in v2.3.0

func (e Entry) Hash() uint32

Hash returns a hash based on context and ID.

This is useful for identifying entries with or without plural forms.

func (Entry) IsFuzzy

func (e Entry) IsFuzzy() bool

IsFuzzy reports whether the entry is marked as "fuzzy".

func (Entry) IsHeader

func (e Entry) IsHeader() bool

IsHeader reports whether the entry is a header (i.e., both ID and context are empty).

func (Entry) IsPlural

func (e Entry) IsPlural() bool

IsPlural reports whether the entry is plural or contains plural forms.

func (Entry) String

func (e Entry) String() string

String returns a formatted representation of the entry for debugging or display.

func (Entry) UnifiedID

func (e Entry) UnifiedID() string

UnifiedID returns the unique identifier for the entry formatted for MO files.

This includes the context, msgid, and plural (if any), separated by '\x04' and '\x00' as per gettext MO format.

func (Entry) UnifiedStr

func (e Entry) UnifiedStr() string

UnifiedStr returns the translation string formatted for MO files.

For plural entries, it joins all plural forms using '\x00'. For singular entries, it returns the Str field.

func (Entry) Validate

func (e Entry) Validate() []error

Validate checks the entry for internal inconsistencies. It returns an error if the entry is both plural and singular.

type File

type File struct {
	Name    string // File name or path.
	Entries        // List of translation entries.
}

File represents a PO file with a name and a list of entries.

func NewFile

func NewFile(name string, entries ...Entry) *File

NewFile returns a new *File with the given name and entries.

func (File) CatchDuplicateEntries added in v2.6.1

func (f File) CatchDuplicateEntries() []error

func (File) Equal

func (f File) Equal(f2 File) bool

Equal reports whether f and f2 contain the same entries and metadata.

func (File) Load

func (f File) Load(id string, context string) string

Load returns the translation string for the entry with the given ID and context. If no such entry exists, it returns an empty string.

func (File) LoadByUnifiedID

func (f File) LoadByUnifiedID(uid string) string

LoadByUnifiedID returns the translation string for the entry with the given unified ID. If no such entry exists, it returns an empty string.

func (*File) Set

func (f *File) Set(id, context string, e Entry)

Set sets the entry with the given id and context to e. If the entry exists, it is replaced; otherwise, it is appended.

func (File) String added in v2.6.0

func (f File) String() string

String returns the formatted representation of the file contents.

func (File) Validate

func (f File) Validate() []error
type Header struct {
	Template bool
	Fields   []HeaderField // A slice storing all registered header fields.
}

Header represents a collection of header fields.

func NewHeader

func NewHeader(options ...HeaderOption) Header

func (*Header) Load

func (h *Header) Load(key string) string

Load retrieves the value associated with a given key from the Header object. Parameters: - key: The name of the header field to retrieve. Returns: - The value associated with the key if found; otherwise, an empty string ("").

func (Header) Nplurals

func (h Header) Nplurals() (nplurals uint)

func (*Header) Register

func (h *Header) Register(key string, d ...string)

Register adds a new header field to the Header object if the key does not already exist. Parameters:

  • key: The name of the header field to register.
  • d: Optional variadic arguments representing the value(s) to associate with the key. If provided, they are concatenated into a single string using fmt.Sprint.

func (*Header) Set

func (h *Header) Set(key, value string)

Set updates the value of an existing header field or adds a new field if the key does not exist. Parameters: - key: The name of the header field to update or add. - value: The new value to associate with the key.

func (Header) String added in v2.6.0

func (h Header) String() string

func (Header) ToConfig added in v2.6.0

func (h Header) ToConfig() HeaderConfig

func (Header) ToEntry

func (h Header) ToEntry() Entry

type HeaderConfig

type HeaderConfig struct {
	Template                bool
	ProjectIDVersion        string
	ReportMsgidBugsTo       string
	POTCreationDate         string
	PORevisionDate          string
	LastTranslator          string
	LanguageTeam            string
	Language                string
	MimeVersion             string
	MediaType               string
	Charset                 string
	ContentTransferEncoding string
	Nplurals                uint
	Plural                  string
	XGenerator              string
}

func DefaultHeaderConfig

func DefaultHeaderConfig(opts ...HeaderOption) HeaderConfig

func DefaultTemplateHeaderConfig added in v2.6.0

func DefaultTemplateHeaderConfig(opts ...HeaderOption) HeaderConfig

func HeaderConfigFromOptions

func HeaderConfigFromOptions(options ...HeaderOption) HeaderConfig

func (HeaderConfig) String added in v2.6.0

func (h HeaderConfig) String() string

func (HeaderConfig) ToHeader

func (cfg HeaderConfig) ToHeader() (h Header)

func (HeaderConfig) Validate added in v2.6.0

func (h HeaderConfig) Validate() []error

type HeaderField

type HeaderField struct {
	Key   string // The name of the header field.
	Value string // The value associated with the header field.
}

HeaderField represents a single key-value pair in a header.

type HeaderOption

type HeaderOption func(*HeaderConfig)

func HeaderWithCharset added in v2.6.0

func HeaderWithCharset(charset string) HeaderOption

func HeaderWithConfig

func HeaderWithConfig(c HeaderConfig) HeaderOption

func HeaderWithLanguage

func HeaderWithLanguage(lang string) HeaderOption

func HeaderWithLanguageTeam

func HeaderWithLanguageTeam(team string) HeaderOption

func HeaderWithLastTranslator

func HeaderWithLastTranslator(translator string) HeaderOption

func HeaderWithMediaType added in v2.6.0

func HeaderWithMediaType(t string) HeaderOption

func HeaderWithMimeVersion added in v2.6.0

func HeaderWithMimeVersion(version string) HeaderOption

func HeaderWithNplurals

func HeaderWithNplurals(n uint) HeaderOption

func HeaderWithPORevisionDate added in v2.6.0

func HeaderWithPORevisionDate(r string) HeaderOption

func HeaderWithPOTCreationDate added in v2.6.0

func HeaderWithPOTCreationDate(c string) HeaderOption

func HeaderWithPlural added in v2.6.0

func HeaderWithPlural(p string) HeaderOption

func HeaderWithProjectIDVersion

func HeaderWithProjectIDVersion(v string) HeaderOption

func HeaderWithReportMsgidBugsTo

func HeaderWithReportMsgidBugsTo(r string) HeaderOption

func HeaderWithTemplate added in v2.6.0

func HeaderWithTemplate(t bool) HeaderOption

func HeaderWithXGenerator added in v2.6.0

func HeaderWithXGenerator(g string) HeaderOption

func HeaderWtihContentTransferEncoding added in v2.6.0

func HeaderWtihContentTransferEncoding(c string) HeaderOption

type InvalidEntryAtIndexError added in v2.6.1

type InvalidEntryAtIndexError struct {
	Index  int
	Reason error
}

func (*InvalidEntryAtIndexError) Error added in v2.6.1

func (e *InvalidEntryAtIndexError) Error() string

func (*InvalidEntryAtIndexError) Unwrap added in v2.6.1

func (e *InvalidEntryAtIndexError) Unwrap() error

type InvalidEntryError added in v2.6.1

type InvalidEntryError struct {
	ID     string
	Reason error
}

func (*InvalidEntryError) Error added in v2.6.1

func (e *InvalidEntryError) Error() string

func (*InvalidEntryError) Unwrap added in v2.6.1

func (e *InvalidEntryError) Unwrap() error

type InvalidFileError added in v2.6.1

type InvalidFileError struct {
	Filename string
	Reason   error
}

func (*InvalidFileError) Error added in v2.6.1

func (e *InvalidFileError) Error() string

func (*InvalidFileError) Unwrap added in v2.6.1

func (e *InvalidFileError) Unwrap() error

type Location

type Location struct {
	Line int
	File string
}

Location represents the location of a translation string in the source code.

func (Location) Equal

func (l Location) Equal(l2 Location) bool

func (Location) String added in v2.6.0

func (l Location) String() string

type Locations

type Locations []Location

func (Locations) Equal

func (l Locations) Equal(l2 Locations) bool

func (Locations) IsSorted

func (l Locations) IsSorted() bool

func (Locations) IsSortedFunc

func (l Locations) IsSortedFunc(cmp Cmp[Location]) bool

func (Locations) Sort

func (l Locations) Sort() Locations

func (Locations) SortFunc

func (l Locations) SortFunc(cmp Cmp[Location]) Locations

func (Locations) String added in v2.6.0

func (l Locations) String() string

type MergeConfig

type MergeConfig struct {
	FuzzyMatch      bool     // Enables fuzzy matching of entries.
	KeepPreviousIDs bool     // Retains original IDs on unmatched entries.
	Sort            bool     // Enables sorting after merge.
	SortMode        SortMode // Sort order to use if sorting is enabled.
}

MergeConfig specifies options for merging entry sets.

func DefaultMergeConfig

func DefaultMergeConfig(opts ...MergeOption) MergeConfig

DefaultMergeConfig returns a MergeConfig with default values, optionally modified by MergeOptions.

func (*MergeConfig) ApplyOption

func (m *MergeConfig) ApplyOption(opts ...MergeOption)

ApplyOption applies a sequence of MergeOptions to the MergeConfig.

type MergeFunc

type MergeFunc func(a, b Entry) *Entry

MergeFunc defines a function type that takes two Entry objects and returns a merged Entry pointer.

func MergeAndMarkObsoleteIfNotPrioritized

func MergeAndMarkObsoleteIfNotPrioritized(priorList []string) MergeFunc

MergeAndMarkObsoleteIfNotPrioritized returns a MergeFunc that merges two entries using SolveMerge. If the UnifiedID of the entry is not found in the priorList, the resulting merged entry is marked as obsolete. This is useful for keeping non-prioritized entries while flagging them as deprecated or no longer in use.

func MergeIfInPriorityList

func MergeIfInPriorityList(priorList []string) MergeFunc

MergeIfInPriorityList returns a MergeFunc that applies SolveMerge only if the entry's UnifiedID is present in the provided list of priority IDs (priorList). If the UnifiedID is not found in the list, the merge is skipped and nil is returned.

func MergeUsingPriorAsBase

func MergeUsingPriorAsBase(priorList Entries) MergeFunc

MergeUsingPriorAsBase returns a MergeFunc that prefers using the version of the entry from priorList as the base. If a matching UnifiedID is found in priorList, it merges that entry with 'b'. Otherwise, it merges 'a' and 'b' as usual using SolveMerge.

func MergeUsingPriorityOrFallback

func MergeUsingPriorityOrFallback(priorList Entries) MergeFunc

MergeUsingPriorityOrFallback returns a MergeFunc that prioritizes the version from priorList if found, otherwise it falls back to SolveMerge.

type MergeOption

type MergeOption func(mc *MergeConfig)

MergeOption modifies a MergeConfig.

func MergeWithFuzzyMatch

func MergeWithFuzzyMatch(f bool) MergeOption

MergeWithFuzzyMatch returns a MergeOption that enables or disables fuzzy matching.

func MergeWithKeepPreviousIDs

func MergeWithKeepPreviousIDs(k bool) MergeOption

MergeWithKeepPreviousIDs returns a MergeOption that enables or disables retention of previous IDs.

func MergeWithMergeConfig

func MergeWithMergeConfig(n MergeConfig) MergeOption

MergeWithMergeConfig returns a MergeOption that replaces the current config.

func MergeWithSort

func MergeWithSort(s bool) MergeOption

MergeWithSort returns a MergeOption that enables or disables sorting.

func MergeWithSortMode

func MergeWithSortMode(sm SortMode) MergeOption

MergeWithSortMode returns a MergeOption that sets the SortMode.

type Parser

type Parser interface {
	Parse() *File
	Error() error
	Errors() []error
}

type PluralEntries

type PluralEntries []PluralEntry

func (PluralEntries) Equal

func (p PluralEntries) Equal(p2 PluralEntries) bool

func (PluralEntries) IsSorted

func (p PluralEntries) IsSorted() bool

func (PluralEntries) IsSortedFunc

func (p PluralEntries) IsSortedFunc(cmp Cmp[PluralEntry]) bool

func (PluralEntries) Solve

func (p PluralEntries) Solve() PluralEntries

func (PluralEntries) Sort

func (p PluralEntries) Sort() PluralEntries

func (PluralEntries) SortFunc

func (p PluralEntries) SortFunc(cmp Cmp[PluralEntry]) PluralEntries

func (PluralEntries) String added in v2.6.0

func (p PluralEntries) String() string

type PluralEntry

type PluralEntry struct {
	ID  int
	Str string
}

func (PluralEntry) Equal

func (p PluralEntry) Equal(p2 PluralEntry) bool

func (PluralEntry) String added in v2.6.0

func (p PluralEntry) String() string

type SortMode

type SortMode int

SortMode defines the mode used to sort PO entries.

const (
	SortByAll      SortMode = iota // Sort by all criteria.
	SortByID                       // Sort by entry ID.
	SortByFile                     // Sort by source file.
	SortByLine                     // Sort by line number.
	SortByFuzzy                    // Sort by fuzzy status.
	SortByObsolete                 // Sort by obsolete status.
)

func (SortMode) SortMethod

func (mode SortMode) SortMethod(entries Entries) func() Entries

SortMethod returns a sorting function for the given SortMode.

Directories

Path Synopsis
The compile package contains structures and functions used to compile Mo/Po files with their respective options.
The compile package contains structures and functions used to compile Mo/Po files with their respective options.

Jump to

Keyboard shortcuts

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