timesheet

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 25 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Timesheet input and validation

Package timesheet reads a single FYT, JSON, or YAML file into *v1alpha1.TimeEntryList:

list, err := timesheet.ListFromFile(path)

Use FromFiles to collect multiple inputs into a *Timesheet:

sheet, err := timesheet.FromFiles("work.fyt", "array.json", "list.yaml")

sheet.Lists contains one list per input file, including empty files. It preserves file order and record order within each file. Each list stores the supplied path once in Meta[timesheet.SourceFileKey] (fyt.queueb.org/source-file). This value replaces any imported source path; other list metadata and entry metadata are preserved.

sheet.Entries() returns []*v1alpha1.TimeEntry sorted by ascending start time, comparing absolute instants across time zones. Equal start times retain file and record order. The returned slice points to the stored items; sorting does not reorder the source lists.

FromFiles attempts all inputs and aggregates their errors. Any input error returns a nil timesheet without partial lists. No paths produce a non-nil timesheet with a non-nil empty Lists slice. Entries() returns a non-nil empty slice when there are no entries, including for a zero-value Timesheet.

The .json, .yaml, and .yml extensions select API decoding, case-insensitively. The scheme decoder recognizes the serialization format from the content. Other extensions and paths without an extension select the four-field user timesheet format. A parse error never triggers a retry with another reader.

API import accepts versions registered in the API scheme and these root formats:

  • A JSON or YAML array of TimeEntry objects, each with its own apiVersion and kind.
  • A JSON or YAML TimeEntryList object with apiVersion and kind at the root. Its items may omit these fields and are decoded according to the list's schema.
[
  {
    "apiVersion": "fyt.queueb.org/v1alpha1",
    "kind": "TimeEntry",
    "start": "2026-09-08T09:00:00+03:00",
    "end": "2026-09-08T10:00:00+03:00",
    "ticket": "FYT-1",
    "description": "Implement JSON input"
  }
]
{
  "apiVersion": "fyt.queueb.org/v1alpha1",
  "kind": "TimeEntryList",
  "items": [
    {
      "start": "2026-10-01T09:00:00+03:00",
      "end": "2026-10-01T10:00:00+03:00",
      "description": "Review input handling"
    }
  ]
}

The API scheme's strict universal decoder handles format recognition, decoding, type metadata, unknown fields, and duplicate keys. It converts supported wire versions to v1alpha1.TimeEntry and v1alpha1.TimeEntryList objects using the registered scheme conversions. The root-array adapter reads JSON records directly and converts YAML arrays strictly, rejecting duplicate keys before conversion. The resulting list contains versioned entries in source order. A strict decoding error or an unsupported TimeEntryList version at the root is returned immediately. Other decoding failures still allow the array adapter to try the input.

An unsupported external apiVersion produces a diagnostic with the declared version and the API scheme's external versions for the expected kind, TimeEntryList at the root or TimeEntry in an array. Array diagnostics include the one-based entry number.

Empty input collections are allowed. The text parser already returns v1alpha1.TimeEntry objects, which are collected directly into a versioned list.

API loading performs decoding and version selection. Call sheet.Validate() afterwards to check required values, interval ordering and whole-second precision. GenerateCommand.Run calls this method after collecting all inputs for documents generate; see the command documentation.

Record order is preserved within each list. A read, parse, or decode error returns a nil list. Empty collections produce an empty list. Source files are never modified. FromFiles collects lists across files; processing policies belong to subsequent stages.

Entry validation

sheet, err := timesheet.FromFiles("work.fyt", "list.json")
if err != nil {
    return err
}
if err := sheet.Validate(); err != nil {
    return err
}

Validate uses api/core/validation.ValidateVersionedCreate to convert each stored entry to core.TimeEntry for OnCreateTimeEntry. It checks entries in file and record order and aggregates field and conversion errors. Each error wraps its cause and includes the supplied source path and a one-based entry number, for example work.fyt: entry 2: description: Required value: .... The entry number identifies its position within the file's list, rather than a physical line in the source file. Lists constructed without Meta[SourceFileKey] are identified as list 1, list 2, and so on.

Every entry receives the result of its latest validation in Status.Conditions:

Result Ready Failed Reason
No recorded validation result absent or Unknown absent or Unknown —
Valid entry (green) True False ValidationSucceeded
Field or conversion error (red) False True ValidationFailed

The condition types are available as conditions.ConditionReady and conditions.ConditionFailed from queueb.org/apimachinery/pkg/conditions. Conditions are updated through conditions.AddOrUpdate using the entry's conditions.Accessor implementation. Before validating each entry, conditions.Set(entry, nil) clears all previous conditions, including imported results, duplicate condition types and unrelated conditions. Validation creates exactly one Ready and one Failed condition from scratch. Both conditions include the field errors, conversion error, or success message for the entry. Conditions record ObservedGeneration from the entry. The library assigns a fresh LastTransitionTime to each new condition on every call, even when the validation outcome has not changed. This time represents creation of the current result; previous transition history is discarded.

Each invocation checks all entries again, including entries with existing or imported conditions. Editing an entry requires another call to refresh its result. Entry values, metadata and source order are preserved. Errors leave the complete timesheet available with updated statuses for both valid and invalid entries. Empty timesheets and empty lists validate successfully.

After successful validation, call ApplyDuplicatePolicy(policy) to get the chronological entries for further processing. The default Merge counts one entry per proven duplicate group and preserves every source occurrence. Error rejects proven duplicates. Conflicts return errors in both modes, with source coordinates and differing fields. The original lists are available through Timesheet.Lists. Pass the processed entries to ValidateOverlaps to check their original intervals. Touching bounds are allowed. Positive overlaps with equal tickets and descriptions produce a mixed/ambiguous error. Each overlap diagnostic carries both full intervals and their source occurrences.

Diagnostics

Input and validation errors carry *timesheet.Diagnostic context. timesheet.Diagnostics(err) expands wrapped and joined errors in the order supplied by the stage that produced them. File loading and individual entry validation follow input order. Overlap checks visit entries in start-time order.

for _, problem := range timesheet.Diagnostics(err) {
    logger.With("source", problem.Source, "stage", problem.Stage).Error(problem.Reason)
}

Source contains the supplied input path, or a list N label for a manually constructed list without a source path. Stage identifies file reading (read), FYT parsing (parse), API decoding and version selection (decode), conversion for validation (convert), entry validation (validate), duplicate handling (duplicates), or overlap validation (overlap).

FYT parsing diagnostics contain the original one-based physical Line, field and source value. API array decoding errors carry a one-based Entry when available; validation-stage errors contain the one-based entry number, and field errors also contain the field and bad value. Unavailable coordinates remain zero. Decoder field details that are only present in an error's text remain in Reason; no field paths or line numbers are inferred from strings. Successful parsing does not retain FYT line coordinates for later model validation or checks of the complete input set.

The original error chains remain available through errors.Is and errors.As, including parser.ErrParse, filesystem errors, *parser.Error, and *field.Error. Diagnostics(nil) returns no problems. The parser.ErrParse classification is not emitted as an additional problem. Values keep their types, including logging values such as alog.Sensitive. The package collects diagnostics without logging; the calling application owns their presentation.

For errors handled through Unwrap() error, a non-nil cause continues the traversal. A nil cause makes the current error a terminal problem rather than discarding it. The resulting diagnostic preserves the accumulated context and explicit Reason; without one, it uses the current error's message. Its Err retains that same terminal error. An ordinary outer wrapper can supply a fallback message as described below. This also applies within joined errors.

Nested Diagnostic wrappers inherit missing attributes from their outer context. The innermost supplied value takes precedence: empty strings in Source, Stage, Field, and Reason, zero Line and Entry, and a nil Value mean unspecified. For an unchanged or omitted Field, a nil Value inherits the outer value. Changing Field prevents inheriting a value belonging to the previous field. Empty strings, zero and false in Value remain explicit values with their original types. A nil Value cannot explicitly clear an inherited value for the same field.

Underlying typed errors still refine the concrete facts: parser.Error supplies the physical line, field and value, field.Error supplies its field and bad value, and read errors identify the read stage. A non-empty Reason from the innermost wrapper that supplies one is preserved for every error type. Only an absent reason is derived from the underlying error; validation errors use their detail or, when absent, their error type. Context is copied for each aggregate branch, leaving sibling diagnostics and the original wrappers unchanged. Err is not inherited as an attribute; each resulting diagnostic retains its concrete cause.

Ordinary single-cause wrappers retain their outermost message as a separate fallbackMessage during traversal. Message priority is an explicit Reason, then the existing message extraction for parser.Error, field.Error or os.PathError, then the wrapper fallback, and finally the terminal error's message. For example, a wrapped strconv.NumError retains its operation and invalid input instead of reporting only invalid syntax. Err still refers to the concrete cause rather than the wrapper used for its message.

The fallback is cleared when expanding joined or strict decoder aggregates, so each branch builds its own message instead of repeating the aggregate's full text. Structured context and an explicit Reason survive that reset. Fallback messages are not parsed or shortened; paths or entry numbers in ordinary wrapper text can repeat the corresponding structured attributes.

Strict decoder aggregates are expanded through runtime.AsStrictDecodingError into one diagnostic per underlying violation, without an additional aggregate message. Each diagnostic retains the accumulated file and entry context and any explicit Reason; otherwise its reason comes from the individual violation. Files and entries retain their input order, while violations within a strict aggregate retain the order returned by the decoder. Field paths and coordinates available only in error text are not inferred. The returned input error chain is unchanged; each diagnostic's Err refers to its individual cause.

API document boundaries

Reader{RequireSingleDocument: true} checks that each JSON or YAML input contains exactly one document. The CLI enables this reader with documents generate --strict. A second document, including an empty YAML document, or malformed trailing content produces a decode error. JSON whitespace, YAML comments and a YAML end marker are valid after a document. The boundary check uses the bytes already read from the file and leaves format recognition, strict schema checks and conversion to the existing decoder.

The default reader skips the extra pass and may accept a valid initial document with trailing content. For example, the default reader loads the first document from this input:

apiVersion: fyt.queueb.org/v1alpha1
kind: TimeEntryList
items: []
---
invalid: [

The default reader can also accept this array with trailing text:

[{"apiVersion":"fyt.queueb.org/v1alpha1","kind":"TimeEntry","ticket":"FIRST"}] trailing

Known issues

YAML key conversion collisions

The YAML array adapter converts records to JSON before scheme decoding. Distinct YAML keys can become the same JSON string key during this conversion. Strict YAML decoding does not detect this collision because the original keys have different types, and one value can be silently overwritten before the scheme sees it.

For example, this input currently succeeds with metadata.labels["1"] containing SECOND; the FIRST value is lost:

- apiVersion: fyt.queueb.org/v1alpha1
  kind: TimeEntry
  metadata:
    labels:
      1: FIRST
      "1": SECOND

This is a known correctness limitation of the YAML-to-JSON conversion path. Its fix is intentionally deferred, and the current behavior is accepted for later reassessment as practical usage clarifies its significance.

Possible future approaches include detecting collisions when YAML keys are converted to strings, or rejecting non-string keys before conversion. Any fix must preserve the original distinction long enough to report an error, before values are overwritten in the JSON representation.

Documentation

Overview

Package timesheet reads FYT and API files into versioned time entry lists.

Index

Constants

View Source
const SourceFileKey = "fyt.queueb.org/source-file"

SourceFileKey identifies the input path in TimeEntryList.Meta.

Variables

View Source
var (
	ErrDuplicateEntry     = errors.New("duplicate time entry")
	ErrConflictingEntries = errors.New("conflicting time entries")
)
View Source
var (
	ErrOverlappingEntries    = errors.New("overlapping time entries")
	ErrMixedAmbiguousEntries = errors.New("mixed/ambiguous time entries")
)

Functions

func ListFromFile

func ListFromFile(path string) (*v1alpha1.TimeEntryList, error)

ListFromFile loads one input using the default Reader.

func ValidateOverlaps

func ValidateOverlaps(entries []ProcessedEntry) error

ValidateOverlaps checks the start-sorted result of ApplyDuplicatePolicy. It reports one error per pair overlapping for a positive duration.

Types

type Diagnostic

type Diagnostic struct {
	Stage  Stage
	Source string
	Line   int
	Entry  int
	Field  string
	Value  any
	Reason string
	Err    error
	// Differences contains the compared fields and their original sources.
	Differences *EntryDifferences
}

Diagnostic wraps an error with input context. Diagnostics expands wrapped and joined errors into individual problems with the available coordinates and cause. Source is the input path, or a list label when no input path was recorded. Line and Entry are one-based; zero means that a coordinate is unavailable. A non-empty Reason overrides the message derived from the underlying error.

func Diagnostics

func Diagnostics(err error) []Diagnostic

Diagnostics expands errors into individual problems in the order supplied by the stage that produced them and inherits context from Diagnostic wrappers. It does not parse error strings or invent coordinates. The parser's ErrParse sentinel is a classification, not a separate problem.

func (*Diagnostic) Error

func (d *Diagnostic) Error() string

Error preserves the wrapped error's text.

func (*Diagnostic) Unwrap

func (d *Diagnostic) Unwrap() error

Unwrap preserves access to the original error through errors.Is and errors.As.

type EntryDifferences

type EntryDifferences struct {
	Fields       []EntryField
	Entries      []EntryReference
	OtherEntries []EntryReference
}

EntryDifferences references the entries and fields involved in one diagnostic. OtherEntries contains the second interval's sources for a mixed/ambiguous pair.

type EntryField

type EntryField struct {
	// contains filtered or unexported fields
}

EntryField identifies a compared field or a key in a metadata map.

func (EntryField) String

func (f EntryField) String() string

func (EntryField) Value

func (f EntryField) Value(entry *v1alpha1.TimeEntry) (string, bool)

Value returns the field value and whether it is present in the entry.

type EntryReference

type EntryReference struct {
	Source string
	Number int
	Entry  *v1alpha1.TimeEntry
}

EntryReference locates a stored entry by its one-based position in Source. Lists without a file path use a one-based "list N" label as Source.

type ProcessedEntry

type ProcessedEntry struct {
	Entry   *v1alpha1.TimeEntry
	Sources []EntryReference
}

ProcessedEntry is one entry to account for and all its original occurrences. Entry points to the first occurrence in Sources.

type Reader

type Reader struct {
	// RequireSingleDocument checks the entire contents of JSON and YAML inputs.
	RequireSingleDocument bool
}

Reader loads timesheet files using the configured input checks.

func (Reader) FromFiles

func (r Reader) FromFiles(paths ...string) (*Timesheet, error)

FromFiles collects one list per path, preserving file and record order. Input errors are aggregated and return a nil timesheet without partial lists. No paths produce a timesheet with a non-nil empty Lists slice.

func (Reader) ListFromFile

func (r Reader) ListFromFile(path string) (*v1alpha1.TimeEntryList, error)

ListFromFile selects API decoding for .json, .yaml, and .yml paths, case-insensitively; other paths use the user timesheet parser. Each file produces a v1alpha1 list, including an empty input collection. Its Meta[SourceFileKey] records path as supplied, replacing any imported value. A parser failure never triggers another format.

type SameKeyGroup

type SameKeyGroup struct {
	Entries     []EntryReference
	Differences []string
	// contains filtered or unexported fields
}

SameKeyGroup contains all entries with the same start and end instants. An empty Differences slice identifies a proven duplicate group. Otherwise the group is a conflict, with sorted paths of all fields that differ.

type Stage

type Stage string

Stage identifies the operation that reported a problem.

const (
	StageRead       Stage = "read"
	StageParse      Stage = "parse"
	StageDecode     Stage = "decode"
	StageConvert    Stage = "convert"
	StageValidate   Stage = "validate"
	StageDuplicates Stage = "duplicates"
	StageOverlap    Stage = "overlap"
)

type Timesheet

type Timesheet struct {
	Lists []*v1alpha1.TimeEntryList
}

Timesheet contains one list per input file, in input order.

func FromFiles

func FromFiles(paths ...string) (*Timesheet, error)

FromFiles collects inputs using the default Reader.

func (*Timesheet) ApplyDuplicatePolicy

func (t *Timesheet) ApplyDuplicatePolicy(policy v1alpha1.DuplicatePolicy) ([]ProcessedEntry, error)

ApplyDuplicatePolicy processes validated entries. Call it after Validate succeeds. An empty policy uses Merge. The result is sorted by start time, retaining source order for equal starts. Any error yields no processed entries.

func (*Timesheet) CompareSameKeyEntries

func (t *Timesheet) CompareSameKeyEntries() []SameKeyGroup

CompareSameKeyEntries groups entries with repeated keys. Call it after Validate succeeds. Groups follow the order of their first entry in the input.

func (*Timesheet) Entries

func (t *Timesheet) Entries() []*v1alpha1.TimeEntry

Entries returns pointers to all stored entries, sorted by start time. Equal start times retain file and record order. Sorting leaves Lists unchanged.

func (*Timesheet) Validate

func (t *Timesheet) Validate() error

Validate checks every entry in source order and records Ready/Failed conditions. Conversion and field errors include the source path and one-based entry number. Lists without a source path are identified by their one-based list number. Every call discards all previous conditions and rebuilds the validation result. Entry values, metadata and source order are preserved.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL