MCPcopy Create free account
hub / github.com/github/gh-aw / addFieldToFrontmatter

Function addFieldToFrontmatter

pkg/cli/frontmatter_editor.go:146–189  ·  view source on GitHub ↗

addFieldToFrontmatter adds a new field to the frontmatter while preserving formatting. This is used when we know the field doesn't exist yet. When trailingBlankLine is true, a blank line is appended after the new field to provide visual separation from fields added subsequently (e.g., separating eng

(content, fieldName, fieldValue string, trailingBlankLine bool)

Source from the content-addressed store, hash-verified

144// When trailingBlankLine is true, a blank line is appended after the new field to provide
145// visual separation from fields added subsequently (e.g., separating engine from source).
146func addFieldToFrontmatter(content, fieldName, fieldValue string, trailingBlankLine bool) (string, error) {
147 // Parse frontmatter using parser package
148 result, err := parser.ExtractFrontmatterFromContent(content)
149 if err != nil {
150 return "", fmt.Errorf("failed to parse frontmatter: %w", err)
151 }
152
153 // Try to preserve original frontmatter formatting by manually inserting the field
154 if len(result.FrontmatterLines) > 0 {
155 // Check if field already exists
156 if result.Frontmatter != nil {
157 if _, exists := result.Frontmatter[fieldName]; exists {
158 // Field exists, update it instead
159 return UpdateFieldInFrontmatter(content, fieldName, fieldValue)
160 }
161 }
162
163 // Field doesn't exist, add it manually to preserve formatting
164 frontmatterLines := append([]string(nil), result.FrontmatterLines...)
165
166 // Add field at the end of the frontmatter, preserving original formatting
167 newField := fmt.Sprintf("%s: %s", fieldName, fieldValue)
168 frontmatterLines = append(frontmatterLines, newField)
169 if trailingBlankLine {
170 frontmatterLines = append(frontmatterLines, "")
171 }
172
173 // Reconstruct the file with preserved formatting
174 var lines []string
175 lines = append(lines, "---")
176 lines = append(lines, frontmatterLines...)
177 lines = append(lines, "---")
178 if result.Markdown != "" {
179 // Add empty line before markdown content to match original format
180 lines = append(lines, "")
181 lines = append(lines, result.Markdown)
182 }
183
184 return strings.Join(lines, "\n"), nil
185 }
186
187 // Fallback to original behavior if no frontmatter lines are available
188 return updateFieldInFrontmatterFallback(result, fieldName, fieldValue)
189}
190
191// RemoveFieldFromOnTrigger removes a field from the 'on' trigger object in the frontmatter.
192// This handles nested fields like "stop-after" which are located under the "on" key.

Callers 2

addSourceToWorkflowFunction · 0.85
addEngineToWorkflowFunction · 0.85

Calls 4

UpdateFieldInFrontmatterFunction · 0.85
ErrorfMethod · 0.45

Tested by

no test coverage detected