From fc5a41b5e54e4a52def6344371dbbcb895d6c2d2 Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Tue, 20 Oct 2020 14:53:38 -0700 Subject: [PATCH] depsfile: Allow loading locks from a byte array in memory This won't be a typical usage pattern for normal code, but will be useful for tests that need to work with locks as input so that they don't need to write out a temporary file on disk just to read it back in immediately. --- internal/depsfile/locks_file.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/internal/depsfile/locks_file.go b/internal/depsfile/locks_file.go index 1fd7f5586..bf7fd26ab 100644 --- a/internal/depsfile/locks_file.go +++ b/internal/depsfile/locks_file.go @@ -31,12 +31,32 @@ import ( // If the returned diagnostics contains errors then the returned Locks may // be incomplete or invalid. func LoadLocksFromFile(filename string) (*Locks, tfdiags.Diagnostics) { + return loadLocks(func(parser *hclparse.Parser) (*hcl.File, hcl.Diagnostics) { + return parser.ParseHCLFile(filename) + }) +} + +// LoadLocksFromBytes reads locks from the given byte array, pretending that +// it was read from the given filename. +// +// The constraints and behaviors are otherwise the same as for +// LoadLocksFromFile. LoadLocksFromBytes is primarily to allow more convenient +// integration testing (avoiding creating temporary files on disk); if you +// are writing non-test code, consider whether LoadLocksFromFile might be +// more appropriate to call. +func LoadLocksFromBytes(src []byte, filename string) (*Locks, tfdiags.Diagnostics) { + return loadLocks(func(parser *hclparse.Parser) (*hcl.File, hcl.Diagnostics) { + return parser.ParseHCL(src, filename) + }) +} + +func loadLocks(loadParse func(*hclparse.Parser) (*hcl.File, hcl.Diagnostics)) (*Locks, tfdiags.Diagnostics) { ret := NewLocks() var diags tfdiags.Diagnostics parser := hclparse.NewParser() - f, hclDiags := parser.ParseHCLFile(filename) + f, hclDiags := loadParse(parser) ret.sources = parser.Sources() diags = diags.Append(hclDiags)