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.