Encode serializes an Artifact to its portable on-disk form: --- --- Output is deterministic: two Encode calls on the same Artifact produce byte-identical output. The body is emitted verbatim, normalized to end with exactly one trailing newline, separated from the clo
(a Artifact)
| 21 | // exactly one trailing newline, separated from the closing fence by exactly |
| 22 | // one blank line. |
| 23 | func Encode(a Artifact) ([]byte, error) { |
| 24 | keys, err := FieldKeysForKind(a.Kind) |
| 25 | if err != nil { |
| 26 | return nil, fmt.Errorf("encode: %w", err) |
| 27 | } |
| 28 | |
| 29 | fm := frontmatter{ |
| 30 | PadArtifact: a.Kind, |
| 31 | FormatVersion: a.FormatVersion, |
| 32 | Title: a.Title, |
| 33 | Provenance: a.Provenance, |
| 34 | } |
| 35 | if fm.FormatVersion == 0 { |
| 36 | fm.FormatVersion = FormatVersion |
| 37 | } |
| 38 | if fm.Provenance.FormatVersion == 0 { |
| 39 | fm.Provenance.FormatVersion = FormatVersion |
| 40 | } |
| 41 | |
| 42 | for _, k := range keys { |
| 43 | v, ok := a.Fields[k] |
| 44 | if !ok || v == nil { |
| 45 | continue |
| 46 | } |
| 47 | switch k { |
| 48 | case "status": |
| 49 | fm.Status = toString(v) |
| 50 | case "trigger": |
| 51 | fm.Trigger = toString(v) |
| 52 | case "scope": |
| 53 | fm.Scope = toString(v) |
| 54 | case "invocation_slug": |
| 55 | fm.InvocationSlug = toString(v) |
| 56 | case "priority": |
| 57 | fm.Priority = toString(v) |
| 58 | case "role": |
| 59 | fm.Role = toString(v) |
| 60 | case "arguments": |
| 61 | fm.Arguments = normalizeArguments(v) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | var buf bytes.Buffer |
| 66 | enc := yaml.NewEncoder(&buf) |
| 67 | enc.SetIndent(2) |
| 68 | if err := enc.Encode(&fm); err != nil { |
| 69 | return nil, fmt.Errorf("encode: marshal frontmatter: %w", err) |
| 70 | } |
| 71 | if err := enc.Close(); err != nil { |
| 72 | return nil, fmt.Errorf("encode: close encoder: %w", err) |
| 73 | } |
| 74 | |
| 75 | body := normalizeBody(a.Body) |
| 76 | |
| 77 | var out bytes.Buffer |
| 78 | out.WriteString("---\n") |
| 79 | out.Write(buf.Bytes()) |
| 80 | out.WriteString("---\n\n") |