tme

Toggl like Time Manager
git clone git://gtms.dev:tme
Log | Files | Refs

completed_entry.go (1514B)


      1 package main
      2 
      3 import (
      4 	"errors"
      5 	"fmt"
      6 	"os"
      7 	"path"
      8 	"strings"
      9 	"time"
     10 )
     11 
     12 type CompletedEntry struct {
     13 	Start time.Time
     14 	Stop  time.Time
     15 }
     16 
     17 func NewCompletedEntry(start time.Time, stop time.Time) (CompletedEntry, error) {
     18 	if start.After(stop) {
     19 		return CompletedEntry{}, errors.New("duration must be positive")
     20 	}
     21 
     22 	return CompletedEntry{
     23 		Start: start,
     24 		Stop:  stop,
     25 	}, nil
     26 }
     27 
     28 func NewCompletedEntryFromPath(entryPath string, entryTime *Time) (CompletedEntry, error) {
     29 	if _, err := os.Stat(entryPath); os.IsNotExist(err) {
     30 		return CompletedEntry{}, err
     31 	}
     32 
     33 	data, err := os.ReadFile(entryPath)
     34 	if err != nil {
     35 		return CompletedEntry{}, err
     36 	}
     37 
     38 	// TODO(tms) 11.11.22: format check
     39 
     40 	lines := strings.Split(string(data), "\n")
     41 	start, _ := entryTime.ParseEntry(lines[0])
     42 	stop, _ := entryTime.ParseEntry(lines[1])
     43 
     44 	return CompletedEntry{
     45 		Start: start,
     46 		Stop:  stop,
     47 	}, nil
     48 }
     49 
     50 func (e CompletedEntry) Data() string {
     51 	return fmt.Sprintf("%s\n%s\n", e.Start.Format(DataTimeLayout), e.Stop.Format(DataTimeLayout))
     52 }
     53 
     54 func (e CompletedEntry) FileName() string {
     55 	return strings.Join([]string{e.Start.Format(FileNameLayout), e.Stop.Format(FileNameLayout)}, "_")
     56 }
     57 
     58 func (e CompletedEntry) FullPath(group Group) string {
     59 	return path.Join(group.FullPath(), e.FileName())
     60 }
     61 
     62 func (e CompletedEntry) Exists(group Group) bool {
     63 	if _, err := os.Stat(e.FullPath(group)); !os.IsNotExist(err) {
     64 		return true
     65 	}
     66 	return false
     67 }
     68 
     69 func (e CompletedEntry) Duration() time.Duration {
     70 	return e.Stop.Sub(e.Start)
     71 }