newFieldRemovalCodemod creates a Codemod that: 1. Checks that the parent key is present in the frontmatter and is a map. 2. Checks that the child field is present in that map. 3. Removes the field (and any nested content) from the YAML block. 4. Optionally invokes PostTransform for any additional li
(cfg fieldRemovalCodemodConfig)
| 31 | // 3. Removes the field (and any nested content) from the YAML block. |
| 32 | // 4. Optionally invokes PostTransform for any additional line-level changes. |
| 33 | func newFieldRemovalCodemod(cfg fieldRemovalCodemodConfig) Codemod { |
| 34 | return Codemod{ |
| 35 | ID: cfg.ID, |
| 36 | Name: cfg.Name, |
| 37 | Description: cfg.Description, |
| 38 | IntroducedIn: cfg.IntroducedIn, |
| 39 | Apply: func(content string, frontmatter map[string]any) (string, bool, error) { |
| 40 | parentValue, hasParent := frontmatter[cfg.ParentKey] |
| 41 | if !hasParent { |
| 42 | return content, false, nil |
| 43 | } |
| 44 | |
| 45 | parentMap, ok := parentValue.(map[string]any) |
| 46 | if !ok { |
| 47 | return content, false, nil |
| 48 | } |
| 49 | |
| 50 | fieldValue, hasField := parentMap[cfg.FieldKey] |
| 51 | if !hasField { |
| 52 | return content, false, nil |
| 53 | } |
| 54 | |
| 55 | newContent, applied, err := applyFrontmatterLineTransform(content, func(lines []string) ([]string, bool) { |
| 56 | result, modified := removeFieldFromBlock(lines, cfg.FieldKey, cfg.ParentKey) |
| 57 | if !modified { |
| 58 | return lines, false |
| 59 | } |
| 60 | |
| 61 | if cfg.PostTransform != nil { |
| 62 | result = cfg.PostTransform(result, frontmatter, fieldValue) |
| 63 | } |
| 64 | |
| 65 | return result, true |
| 66 | }) |
| 67 | if applied { |
| 68 | cfg.Log.Print(cfg.LogMsg) |
| 69 | } |
| 70 | return newContent, applied, err |
| 71 | }, |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | // moveToOnBlockConfig holds the configuration for a codemod that moves a top-level |
| 76 | // frontmatter key into the 'on:' block. |