pofile

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2025 License: MIT Imports: 10 Imported by: 0

README

Pofile

Go Report Card Go Reference License

A Gettext .po file parser written in Go.

Features

  • Parse po file headers into a structured format with easy access methods
  • Full support for parsing po file elements:
    • Translator comments
    • Extracted comments
    • References
    • Flags
    • Message context (msgctxt)
    • Message ID (msgid)
    • Plural message ID (msgid_plural)
    • Translations (msgstr)
  • Automatic handling of fuzzy translations
  • Convert po files to map/dictionary format (suitable for JSON conversion)
  • Command-line interface for batch processing of po files

Installation

Library
go get github.com/0xJacky/pofile
CLI Tool

Download the binary from Releases or install from source:

go install github.com/0xJacky/pofile/cmd/pofile@latest

Usage

Library Usage
package main

import (
	"encoding/json"
	"fmt"
	"github.com/0xJacky/pofile"
	"log"
	"os"
)

func main() {
	// Parse a po file
	p, err := pofile.Parse("path/to/your.po")
	if err != nil {
		log.Fatalf("Failed to parse po file: %v", err)
	}
	
	// Access header information
	fmt.Printf("Language: %s\n", p.Header.Language)
	fmt.Printf("Custom header field: %v\n", p.Header.Get("X-Generator"))
	
	// Process translations
	for _, item := range p.Items {
		fmt.Printf("Original: %s\n", item.MsgId)
		fmt.Printf("Translation: %s\n", item.MsgStr[0])
	}
	
	// Convert to dictionary and save as JSON
	dict := p.ToDict()
	bytes, _ := json.MarshalIndent(dict, "", "  ")
	os.WriteFile("translations.json", bytes, 0644)
}
Multiple Language Support
package main

import (
	"encoding/json"
	"github.com/0xJacky/pofile"
	"log"
	"os"
	"path/filepath"
)

func main() {
	dict := make(pofile.Dict)
	languages := []string{"de", "en", "fr", "ja", "ko", "zh_TW"}
	
	for _, lang := range languages {
		poPath := filepath.Join("locale", lang, "LC_MESSAGES", "app.po")
		p, err := pofile.Parse(poPath)
		if err != nil {
			log.Printf("Failed to parse %s: %v", poPath, err)
			continue
		}
		dict[p.Header.Language] = p.ToDict()
	}
	
	bytes, _ := json.MarshalIndent(dict, "", "  ")
	os.WriteFile("all_translations.json", bytes, 0644)
}
CLI Usage

Convert a single po file to JSON:

pofile build --file path/to/file.po

Convert all po files in a directory:

pofile build --file path/to/directory

API Reference

Core Types
Pofile
type Pofile struct {
	Header Header
	Items  []Item
}

// Convert pofile to dictionary format
func (p *Pofile) ToDict() Dict
Header
type Header struct {
	ProjectIdVersion        string     `key:"Project-Id-Version"`
	ReportMsgBugsTo         string     `key:"Report-Msgid-Bugs-To"`
	POTCreationDate         *time.Time `key:"POT-Creation-Date"`
	PORevisionDate          *time.Time `key:"PO-Revision-Date"`
	LastTranslator          string     `key:"Last-Translator"`
	Language                string     `key:"Language"`
	LanguageTeam            string     `key:"Language-Team"`
	ContentType             string     `key:"Content-Type"`
	ContentTransferEncoding string     `key:"Content-Transfer-Encoding"`
	PluralForms             string     `key:"Plural-Forms"`
}

// Get custom header field
func (h *Header) Get(key string) interface{}
Item
type Item struct {
	TranslatorComments []string
	ExtractedComments  []string
	Reference          []string
	Flags              []string
	Msgctxt            string
	MsgId              string
	MsgIdPlural        string
	MsgStr             []string
}
Main Functions
// Parse a .po file at the specified path
func Parse(path string) (p *Pofile, err error)

License

MIT

Documentation

Index

Constants

View Source
const (
	MSGID = iota
	MSGIDPLURAL
	MSGSTR
	MSGCTXT
	COMPLATE
)

Variables

View Source
var (
	// ErrKeyNotFound is returned when a translation key is not found in the dictionary
	ErrKeyNotFound = errors.New("translation key not found")
	// ErrJSONMarshal is returned when JSON marshaling fails
	ErrJSONMarshal = errors.New("failed to marshal JSON data")
	// ErrJSONUnmarshal is returned when JSON unmarshaling fails
	ErrJSONUnmarshal = errors.New("failed to unmarshal JSON data")
	// ErrInvalidArgument is returned when an invalid argument type is provided
	ErrInvalidArgument = errors.New("invalid argument type")
)

Common error types

Functions

This section is empty.

Types

type Dict

type Dict map[string]any

func (Dict) Translate

func (d Dict) Translate(key string, args ...any) (string, error)

Translate returns the translated string for the given key and optional arguments. It may return an error if the key is not found or if there are issues with JSON processing.

type Header struct {
	ProjectIdVersion        string     `key:"Project-Id-Version"`
	ReportMsgBugsTo         string     `key:"Report-Msgid-Bugs-To"`
	POTCreationDate         *time.Time `key:"POT-Creation-Date"`
	PORevisionDate          *time.Time `key:"PO-Revision-Date"`
	LastTranslator          string     `key:"Last-Translator"`
	Language                string     `key:"Language"`
	LanguageTeam            string     `key:"Language-Team"`
	ContentType             string     `key:"Content-Type"`
	ContentTransferEncoding string     `key:"Content-Transfer-Encoding"`
	PluralForms             string     `key:"Plural-Forms"`
	// contains filtered or unexported fields
}

func (*Header) Get

func (h *Header) Get(key string) interface{}

type Item

type Item struct {
	TranslatorComments []string
	ExtractedComments  []string
	Reference          []string
	Flags              []string
	Msgctxt            string
	MsgId              string
	MsgIdPlural        string
	MsgStr             []string
}

type Pofile

type Pofile struct {
	Header Header
	Items  []Item
}

func Parse

func Parse(path string) (p *Pofile, err error)

func ParseText

func ParseText(text string) (p *Pofile, err error)

func (*Pofile) ToDict

func (p *Pofile) ToDict() (dict Dict)

type TranslateError

type TranslateError struct {
	Type    string
	Message string
	Err     error
}

TranslateError represents a specific translation error

func (*TranslateError) Error

func (e *TranslateError) Error() string

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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