ParseFile is a convenience wrapper around Parse that first attempts to load data from the given filename, passing the result to Parse if successful. If the file cannot be read, an error diagnostic with nil context is returned.
(filename string)
| 93 | // |
| 94 | // If the file cannot be read, an error diagnostic with nil context is returned. |
| 95 | func ParseFile(filename string) (rf *hcl.File, diags hcl.Diagnostics) { |
| 96 | f, err := os.Open(filename) |
| 97 | if err != nil { |
| 98 | diags = append(diags, &hcl.Diagnostic{ |
| 99 | Severity: hcl.DiagError, |
| 100 | Summary: "Failed to open file", |
| 101 | Detail: fmt.Sprintf("The file %q could not be opened.", filename), |
| 102 | }) |
| 103 | return |
| 104 | } |
| 105 | defer func() { |
| 106 | err := f.Close() |
| 107 | if err != nil { |
| 108 | diags = append(diags, &hcl.Diagnostic{ |
| 109 | Severity: hcl.DiagWarning, |
| 110 | Summary: "Failed to close file", |
| 111 | Detail: fmt.Sprintf("The file %q was opened, but an error occured while closing it.", filename), |
| 112 | }) |
| 113 | } |
| 114 | }() |
| 115 | |
| 116 | src, err := io.ReadAll(f) |
| 117 | if err != nil { |
| 118 | return nil, hcl.Diagnostics{ |
| 119 | { |
| 120 | Severity: hcl.DiagError, |
| 121 | Summary: "Failed to read file", |
| 122 | Detail: fmt.Sprintf("The file %q was opened, but an error occured while reading it.", filename), |
| 123 | }, |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | return Parse(src, filename) |
| 128 | } |