src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

entries.go (1963B)


      1 package store
      2 
      3 import (
      4 	"encoding/json"
      5 	"fmt"
      6 	"os"
      7 	"path/filepath"
      8 	"sort"
      9 	"sync"
     10 
     11 	"code.dwrz.net/src/pkg/dqs/entry"
     12 )
     13 
     14 func (s *Store) DeleteEntry(date string) error {
     15 	name := fmt.Sprintf("%s/%s.json", s.Dir, date)
     16 
     17 	if err := os.Remove(name); err != nil {
     18 		return err
     19 	}
     20 
     21 	return nil
     22 }
     23 
     24 func (s *Store) GetAllEntries() ([]*entry.Entry, error) {
     25 	files, err := os.ReadDir(s.Dir)
     26 	if err != nil {
     27 		return nil, err
     28 	}
     29 
     30 	var (
     31 		echan       = make(chan *entry.Entry, len(files))
     32 		errs        = make(chan error, len(files))
     33 		concurrency = 24
     34 		sem         = make(chan struct{}, concurrency)
     35 		wg          sync.WaitGroup
     36 	)
     37 
     38 	wg.Add(len(files))
     39 
     40 	for _, f := range files {
     41 		go func(name string) {
     42 			defer func() { <-sem }()
     43 			defer wg.Done()
     44 
     45 			sem <- struct{}{}
     46 
     47 			if name == userFile {
     48 				return
     49 			}
     50 
     51 			date := name[:len(name)-len(filepath.Ext(name))]
     52 
     53 			entry, err := s.GetEntry(date)
     54 			if err != nil {
     55 				errs <- err
     56 			}
     57 
     58 			echan <- entry
     59 		}(f.Name())
     60 	}
     61 
     62 	wg.Wait()
     63 	close(errs)
     64 	close(echan)
     65 
     66 	if len(errs) > 0 {
     67 		return nil, <-errs
     68 	}
     69 
     70 	var entries = []*entry.Entry{}
     71 	for entry := range echan {
     72 		entries = append(entries, entry)
     73 	}
     74 
     75 	sort.Slice(entries, func(i, j int) bool {
     76 		return entries[i].Date.Before(entries[j].Date)
     77 	})
     78 
     79 	return entries, nil
     80 }
     81 
     82 func (s *Store) GetEntry(date string) (*entry.Entry, error) {
     83 	name := fmt.Sprintf("%s/%s.json", s.Dir, date)
     84 
     85 	data, err := os.ReadFile(name)
     86 	if err != nil {
     87 		return nil, fmt.Errorf("failed to open entry file: %w", err)
     88 	}
     89 
     90 	var e = &entry.Entry{}
     91 	if err := json.Unmarshal(data, e); err != nil {
     92 		return nil, fmt.Errorf("failed to parse entry file: %w", err)
     93 	}
     94 
     95 	return e, nil
     96 }
     97 
     98 func (s *Store) UpdateEntry(e *entry.Entry) error {
     99 	data, err := json.Marshal(e)
    100 	if err != nil {
    101 		return err
    102 	}
    103 
    104 	name := fmt.Sprintf(
    105 		"%s/%s.json", s.Dir, e.Date.Format(entry.DateFormat),
    106 	)
    107 
    108 	if err := os.WriteFile(name, data, permissions); err != nil {
    109 		return err
    110 	}
    111 
    112 	return nil
    113 }