add pttodo export file option

This commit is contained in:
Bel LaPointe
2022-01-06 22:13:22 -05:00
parent 19aa5f82fb
commit fc95242c94
3 changed files with 126 additions and 1 deletions

View File

@@ -1,6 +1,7 @@
package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
@@ -8,10 +9,13 @@ import (
"net/http"
"net/url"
"os"
"path"
"regexp"
"strconv"
"strings"
"time"
yaml "gopkg.in/yaml.v2"
)
func Upload(config Config, transaction *Transaction) error {
@@ -20,6 +24,8 @@ func Upload(config Config, transaction *Transaction) error {
return uploadTodo(config, transaction)
case UploaderLedger:
return uploadLedger(config, transaction)
case UploaderPTTodo:
return uploadPTTodo(config, transaction)
default:
return errors.New("not impl: uploader")
}
@@ -49,6 +55,43 @@ func uploadTodo(config Config, transaction *Transaction) error {
return nil
}
func uploadPTTodo(config Config, transaction *Transaction) error {
b, err := ioutil.ReadFile(config.TodoAddr)
if os.IsNotExist(err) {
b = []byte("todo:\n")
} else if err != nil {
return err
} else if len(b) == 0 {
b = []byte("todo:\n")
}
f, err := ioutil.TempFile(os.TempDir(), path.Base(config.TodoAddr))
if err != nil {
return err
}
defer f.Close()
sep := []byte{'\n'}
seek := []byte("todo:")
for len(b) > 0 {
idx := bytes.Index(b, sep)
if idx == -1 {
idx = len(b) - 1
}
fmt.Fprintf(f, "%s\n", b[:idx])
if bytes.Equal(bytes.TrimSpace(b[:idx]), seek) {
fmt.Fprintf(f, `- {"todo":%q, "tags":%q}%s`, transaction.Format(), config.TodoTag, "\n")
}
b = b[idx+1:]
}
f.Close()
var v interface{}
if b, err := ioutil.ReadFile(f.Name()); err != nil {
return err
} else if err := yaml.Unmarshal(b, &v); err != nil {
return err
}
return os.Rename(f.Name(), config.TodoAddr)
}
func uploadLedger(config Config, transaction *Transaction) error {
f, err := os.OpenFile(config.TodoAddr, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {