ledger-ui/ledger.go

56 lines
1.0 KiB
Go

package main
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
)
type Ledger struct {
path string
}
func NewLedger(path string) (Ledger, error) {
info, err := os.Stat(path)
if err == nil && info.IsDir() {
return Ledger{}, errors.New("path is dir")
}
return Ledger{
path: path,
}, err
}
func (ledger Ledger) Transactions() ([]Transaction, error) {
f, err := ledger.open()
if err != nil {
return nil, err
}
defer f.Close()
transactions := make([]Transaction, 0)
for err == nil {
var transaction Transaction
transaction, err = readTransaction(f)
if err == io.EOF {
} else if err == nil {
transactions = append(transactions, transaction)
} else {
err = fmt.Errorf("error parsing transaction #%d: %v", len(transactions), err)
}
}
if err == io.EOF {
err = nil
}
return transactions, err
}
func (ledger Ledger) open() (io.ReadCloser, error) {
f, err := os.Open(ledger.path)
if os.IsNotExist(err) {
return ioutil.NopCloser(bytes.NewReader([]byte{})), nil
}
return f, err
}