home

My NixOS systems configurations.
Log | Files | Refs | LICENSE

main.go (1735B)


      1 package main
      2 
      3 import (
      4 	"context"
      5 	"flag"
      6 	"log"
      7 	"os"
      8 	"path/filepath"
      9 	"time"
     10 
     11 	"github.com/vdemeester/home/tools/go-org-readwise/internal/org"
     12 	"github.com/vdemeester/home/tools/go-org-readwise/internal/readwise"
     13 )
     14 
     15 func main() {
     16 	apiKeyFile := flag.String("apiKeyFile", "", "File to load the apiKey from. If empty, it will defer to the READWISE_KEY environment variable")
     17 	targetFolder := flag.String("targetFolder", "", "Folder to write highlights (in org file) into")
     18 	flag.Parse()
     19 
     20 	if *targetFolder == "" {
     21 		log.Fatal("-targetFolder is a required flag")
     22 	}
     23 
     24 	apiKeyData, err := os.ReadFile(*apiKeyFile)
     25 	if err != nil && !os.IsNotExist(err) {
     26 		log.Fatalf("Error reading apiKeyFile %s: %v", *apiKeyFile, err)
     27 	}
     28 	apikey := string(apiKeyData)
     29 	if apikey == "" {
     30 		apikey = os.Getenv("READWISE_KEY")
     31 	}
     32 
     33 	stateFile := filepath.Join(*targetFolder, ".readwise-sync.state")
     34 	updateAfter, err := getUpdateAfterFromFile(stateFile)
     35 	if err != nil {
     36 		log.Fatalf("Error reading readwise state file from %s: %v", stateFile, err)
     37 	}
     38 	ctx := context.Background()
     39 	results, err := readwise.FetchFromAPI(ctx, apikey, updateAfter)
     40 	if err != nil {
     41 		log.Fatalf("Error while fetching results: %v", err)
     42 	}
     43 
     44 	if err := org.Sync(ctx, *targetFolder, results); err != nil {
     45 		log.Fatalf("Error syncing readwise and org file in %s folder: %v", *targetFolder, err)
     46 	}
     47 }
     48 
     49 func getUpdateAfterFromFile(stateFile string) (*time.Time, error) {
     50 	data, err := os.ReadFile(stateFile)
     51 	if err != nil && !os.IsNotExist(err) {
     52 		return nil, err
     53 	}
     54 	// If the file doesn't exists, do not fail
     55 	if os.IsNotExist(err) {
     56 		return nil, nil
     57 	}
     58 	t, err := time.Parse(readwise.FormatUpdatedAfter, string(data))
     59 	if err != nil {
     60 		return nil, err
     61 	}
     62 	return &t, nil
     63 }