hlgo

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2025 License: MPL-2.0 Imports: 18 Imported by: 0

README

hlgo

GitHub License GitHub go.mod Go version (branch) GitHub Actions Workflow Status

A Go binding for the hledger CLI accounting tool.

Installation

$ go get github.com/shlewislee/hlgo

hledger installation is also required. By default, hlgo will look in PATH and then the user cache directory(.cache).

You can also explicitly provide hledger path.

Installing hledger

You can also use the built-in Install function to download and install the hledger binary into the user cache directory:

binPath, err := hlgo.Install(context.Background(), nil)
if err != nil {
  log.Fatal(err)
}
fmt.Println(binPath)

You can either provide the downloaded path to New() or just let hlgo look for the .cache directory.

Note that hledger installation via hlgo is only for x86 Linux. The installer does not check the OS and will proceed without error even if the OS differs.

Usage

ctx := context.Background()

hl, err := hlgo.New(&hlgo.NewHledgerOption{
  LedgerPaths: []string{"examples/example.journal"},
})
if err != nil {
  log.Panic(err)
}

v, _ := hl.Version(ctx)
fmt.Println(v)

cmd := hl.NewCommand(
  "bal",
  hlgo.WithAccount("bank"),
  hlgo.WithPeriod(hlgo.PeriodDaily),
  hlgo.WithValuation("KRW", hlgo.ValuationThen),
  hlgo.WithInferMarketPrice(),
  hlgo.WithDate("2025-01-01.."),
  hlgo.WithHistorical(),
)

res, _ := cmd.Run(ctx) // []byte

fmt.Println(string(res))

There are also a few examples in the examples/ directory.

Streaming Output

For large reports (e.g. HTML, JSON output), you can also use Command.Stream to write output directly to an io.Writer(e.g. os.Stdout).

cmdStream := hl.NewCommand("bal")
err = cmdStream.Stream(ctx, os.Stdout)
if err != nil {
    log.Fatal(err)
}

Authors

License

This project is licensed under the Mozilla Public License Version 2.0 (MPL-2.0).

For the full license text, please see the LICENSE file.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Install

func Install(ctx context.Context, opts *InstallHledgerOption) (string, error)

Install downloads the hledger binary to the given path.

Use this before New or manually install hledger.

func IsInstalled

func IsInstalled() (string, bool)

Types

type AccountType

type AccountType string
const (
	AccountTypeAsset      AccountType = "A"
	AccountTypeLiability  AccountType = "L"
	AccountTypeEquity     AccountType = "E"
	AccountTypeRevenue    AccountType = "R"
	AccountTypeExpense    AccountType = "X"
	AccountTypeCash       AccountType = "C"
	AccountTypeConversion AccountType = "V"
)

type Command

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

func (*Command) Run

func (c *Command) Run(ctx context.Context) ([]byte, error)

Run executes the hledger command and captures its stdout and stderr. It returns the stdout output as a byte slice.

If the command fails, it returns a *CommandError containing the command's stderr.

func (*Command) Stream

func (c *Command) Stream(ctx context.Context, w io.Writer) error

Stream executes the hledger command and writes its stdout directly to the provided io.Writer. This is typically used for generating large reports (like CSV or JSON) to avoid buffering the entire output into memory.

If the command fails, it returns a *CommandError containing the command's stderr.

func (*Command) String

func (c *Command) String() string

String returns the full shell command string. It includes the binary path, default arguments, and command options. Uses context.TODO() during build. Intended for **debugging, logging, and fmt.Stringer**.

type CommandError

type CommandError struct {
	Command string
	Stderr  string
	Err     error
}

func (*CommandError) Error

func (e *CommandError) Error() string

func (*CommandError) Unwrap

func (e *CommandError) Unwrap() error

type Hledger

type Hledger struct {
	Binary       string
	JournalPaths []string
	DefaultArgs  []Option
}

func New

func New(opts *NewHledgerOption) (*Hledger, error)

New starts a Hledger instance.

Requires hledger installation. New will check the user cache directory if hledger is not available on PATH or if no explicit binary path is given.

If multiple hledger versions are found in the cache directory, New will use the latest version determined with semver

func (*Hledger) NewCommand

func (client *Hledger) NewCommand(command string, options ...Option) *Command

NewCommand returns a *Command instance with the given options applied.

command can be an empty string(e.g. to use --version flag)

func (*Hledger) Version

func (hl *Hledger) Version(ctx context.Context) (string, error)

Version returns version string generated with

$ hledger --version

. (hledger v0.00.0, linux-x86_64)

type InstallHledgerOption

type InstallHledgerOption struct {
	Dir     string
	Version string

	Logger   *slog.Logger
	LogLevel slog.Level
}

if Logger is not nil, LogLevel will be ignored.

type NewHledgerOption

type NewHledgerOption struct {
	BinaryPath  string
	LedgerPaths []string
	DefaultArgs []Option
}

type Option

type Option func(*Command)

func WithAccount

func WithAccount(account ...string) Option

func WithAccountTypes

func WithAccountTypes(acctTypes ...AccountType) Option

func WithAlias

func WithAlias(a, b string) Option

func WithArg

func WithArg(arg ...string) Option

WithArg will simply append given string arguments. Use WithArg if a specific argument option is not implemented by the library.

func WithAuto

func WithAuto() Option

func WithAverage

func WithAverage() Option

func WithBudget

func WithBudget(descPattern ...string) Option

descPattern is optional. It will only parse the very first argument

func WithCommodityStyle

func WithCommodityStyle(style string) Option

func WithCost

func WithCost() Option

func WithCount

func WithCount() Option

func WithCumulative

func WithCumulative() Option

func WithDate

func WithDate(dateStr string) Option

func WithDeclared

func WithDeclared() Option

func WithDepth

func WithDepth(level int, filter string) Option

show only top `level` levels of accounts. If `filter` is set, only apply limiting to accounts matching the regular expression.

func WithDrop

func WithDrop(n int) Option

func WithEmpty

func WithEmpty() Option

func WithForecast

func WithForecast(period ...string) Option

Period is optional. It will only parse the very first argument.

func WithFormat

func WithFormat(format string) Option

func WithHistorical

func WithHistorical() Option

Calculate with postings from journal start to column end, ie "all postings from before report start date until this column's end"

func WithIgnoreAssertions

func WithIgnoreAssertions() Option

func WithInferMarketPrice

func WithInferMarketPrice() Option

func WithInvert

func WithInvert() Option

func WithNoTotal

func WithNoTotal() Option

func WithNotQuery

func WithNotQuery(queryType QueryType, value string) Option

WithNotQuery prepends `not:` to a query to negate the match.

func WithOutputType

func WithOutputType(outputType OutputType) Option

See https://hledger.org/1.50/hledger.html#output-format for supported formats. Note that this library will not check the availability.

func WithPercent

func WithPercent() Option

func WithPivot

func WithPivot(tagName string) Option

With --pivot PIVOTEXPR, some other field's (or multiple fields') value is used as a synthetic account name, causing different grouping and display.

See https://hledger.org/1.50/hledger.html#pivoting

func WithPretty

func WithPretty() Option

func WithQuery

func WithQuery(queryType QueryType, value string) Option

Check https://hledger.org/1.50/hledger.html#queries for more information.

func WithRowTotal

func WithRowTotal() Option

show a row total column

func WithSortAmount

func WithSortAmount() Option

func WithStatus

func WithStatus(trStatus TrStatusType) Option

Match unmarked, pending, or cleared transactions respectively.

func WithStrict

func WithStrict() Option

func WithToday

func WithToday(date string) Option

func WithTree

func WithTree() Option

func WithTxnBalancing

func WithTxnBalancing(balancingType TxnBalancingType) Option

func WithValuation

func WithValuation(commodity string, valType ValuationType) Option

show amounts converted to their value on the specified date(s) in their default valuation

func WithValueChange

func WithValueChange() Option

type OutputType

type OutputType string
const (
	OutputTXT  OutputType = "txt"
	OutputCSV  OutputType = "csv"
	OutputHTML OutputType = "html"
	OutputTSV  OutputType = "tsv"
	OutputJSON OutputType = "json"
	OutputFODS OutputType = "fods"
)

type PeriodType

type PeriodType string
const (
	PeriodDaily     PeriodType = "--daily"
	PeriodWeekly    PeriodType = "--weekly"
	PeriodMonthly   PeriodType = "--monthly"
	PeriodQuarterly PeriodType = "--quarterly"
	PeriodYearly    PeriodType = "--yearly"
)

type QueryType

type QueryType string
const (
	QueryTypeAcct  QueryType = "acct"  // acct:REGEX
	QueryTypeAmt   QueryType = "amt"   // amt:N, amt:'<N', amt:'<=N', amt:'>N', amt:'>=N'
	QueryTypeCode  QueryType = "code"  // code:REGEX
	QueryTypeCur   QueryType = "cur"   // cur:REGEX
	QueryTypeDesc  QueryType = "desc"  // desc:REGEX
	QueryTypeDate2 QueryType = "date2" // date2:PERIODEXPR
	QueryTypeNote  QueryType = "note"  // note:REGEX
	QueryTypePayee QueryType = "payee" // payee:REGEX
	QueryTypeReal  QueryType = "real"  // real:, real:0
	QueryTypeTag   QueryType = "tag"   // tag:NAMEREGEX[=VALREGEX]
)

type TrStatusType

type TrStatusType string
const (
	TrStatusUnmarked TrStatusType = ""
	TrStatusPending  TrStatusType = "!"
	TrStatusCleared  TrStatusType = "*"
)

type TxnBalancingType

type TxnBalancingType string
const (
	TxnBalancingOld   TxnBalancingType = "old"
	TxnBalancingExact TxnBalancingType = "exact"
)

type ValuationType

type ValuationType string

You can also do

WithValuation(ValuationType("YYYY-mm-dd"))

to use custom date.

const (
	// Convert amounts to their value in the default valuation commodity using current market prices (as of when report is generated).
	ValuationNow ValuationType = "now"
	// Convert amounts to their value in the default valuation commodity, using market prices on the last day of the report period (or if unspecified, the journal's end date); or in multiperiod reports, market prices on the last day of each subperiod.
	ValuationEnd ValuationType = "end"
	// Convert amounts to their value in the default valuation commodity, using market prices on each posting's date.
	ValuationThen ValuationType = "then"
)

Directories

Path Synopsis
examples
command_err command
default_args command
install command
stream command

Jump to

Keyboard shortcuts

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