1+ // Package ledger provides primitives for operating on the user's
2+ // git-ledger.
13package ledger
24
35import (
@@ -12,22 +14,34 @@ import (
1214 "github.com/BurntSushi/toml"
1315)
1416
17+ // Record entry in the git-ledger.
1518type Record struct {
1619 Path string
1720 Slug string
1821}
1922
20- type Records struct {
23+ // Struct of Records, for toml parsing.
24+ type records struct {
2125 Record []Record
2226}
2327
28+ // Get the path of the git-ledger.
2429func Path () string {
2530 home , _ := pathutil .HomeDir ()
2631 return path .Join (home , ".git-ledger" )
2732}
2833
34+ // Return true if dir contains a .git directory.
35+ func IsGitProject (dir string ) bool {
36+ stat , err := os .Stat (path .Join (dir , ".git" ))
37+ isProject := err == nil && stat .IsDir ()
38+ return isProject
39+ }
40+
41+
42+ // Get a list of records currently in the git-ledger.
2943func GetRecords () ([]Record , error ) {
30- var ledger Records
44+ var ledger records
3145
3246 b , err := ioutil .ReadFile (Path ())
3347 if err != nil {
@@ -41,6 +55,7 @@ func GetRecords() ([]Record, error) {
4155 return ledger .Record , err
4256}
4357
58+ // Look-up a record from the git-ledger by slug.
4459func GetBySlug (slug string ) (Record , error ) {
4560 var match Record
4661
@@ -56,12 +71,29 @@ func GetBySlug(slug string) (Record, error) {
5671 return match , errors .New (fmt .Sprintf ("Unknown project: %s" , slug ))
5772}
5873
59- // fixme: remove duplicated code
74+ // Look-up a record from the git-ledger by path.
75+ func GetByPath (path string ) (Record , error ) {
76+ var match Record
77+
78+ records , err := GetRecords ()
79+ if err != nil {
80+ return match , err
81+ }
82+ for _ , r := range records {
83+ if r .Path == path {
84+ return r , nil
85+ }
86+ }
87+ return match , errors .New (fmt .Sprintf ("Unknown project: %s" , path ))
88+ }
89+
90+ // Return the current record as a toml string.
6091func (r Record ) String () string {
6192 return fmt .Sprintf ("[[Record]]\n path = \" %s\" \n slug = \" %s\" \n \n " , r .Path , r .Slug )
6293}
6394
64- // comparison by Path
95+ // Remove record from the git-ledger. Will remove all records
96+ // matching this records path from the ledger.
6597func (r Record ) RemoveFromLedger () error {
6698 records , err := GetRecords ()
6799 if err != nil {
@@ -79,6 +111,7 @@ func (r Record) RemoveFromLedger() error {
79111 return nil
80112}
81113
114+ // Add record to the git-ledger.
82115func (r Record ) AddToLedger () {
83116 f , err := os .OpenFile (Path (), os .O_APPEND | os .O_WRONLY | os .O_CREATE , 0644 )
84117 if err != nil {
0 commit comments