From 73df83fffdbcafa12f2d694bd09ebc29a5b1e9e7 Mon Sep 17 00:00:00 2001 From: Mahmood Ali Date: Tue, 10 Nov 2020 14:48:29 -0500 Subject: [PATCH] Custom message when job file is HCL2 incompatible Use a custom message when the job file is a valid HCL1 but no longer valid under HCL 2 syntax. --- command/helpers.go | 7 ++++++ command/helpers_test.go | 48 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/command/helpers.go b/command/helpers.go index 0f87cf140..cc7f2289d 100644 --- a/command/helpers.go +++ b/command/helpers.go @@ -458,7 +458,14 @@ func (j *JobGetter) ApiJobWithArgs(jpath string, vars []string, varfiles []strin ArgVars: vars, AllowFS: true, }) + + if err != nil { + if _, merr := jobspec.Parse(&buf); merr == nil { + return nil, fmt.Errorf("Failed to parse using HCL 2. Use the HCL 1 parser with `nomad run -hcl1`, or address the following issues:\n%v", err) + } + } } + if err != nil { return nil, fmt.Errorf("Error parsing job file from %s:\n%v", jpath, err) } diff --git a/command/helpers_test.go b/command/helpers_test.go index dbead5b62..84f9d753a 100644 --- a/command/helpers_test.go +++ b/command/helpers_test.go @@ -280,6 +280,54 @@ func TestJobGetter_LocalFile(t *testing.T) { } } +// TestJobGetter_LocalFile_InvalidHCL2 asserts that a custom message is emited +// if the file is a valid HCL1 but not HCL2 +func TestJobGetter_LocalFile_InvalidHCL2(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + hcl string + expectHCL1Message bool + }{ + { + "invalid HCL", + "nothing", + false, + }, + { + "invalid HCL2", + `job "example" { + meta = { "a" = "b" } +}`, + true, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + fh, err := ioutil.TempFile("", "nomad") + require.NoError(t, err) + defer os.Remove(fh.Name()) + defer fh.Close() + + _, err = fh.WriteString(c.hcl) + require.NoError(t, err) + + j := &JobGetter{} + _, err = j.ApiJob(fh.Name()) + require.Error(t, err) + + exptMessage := "Failed to parse using HCL 2. Use the HCL 1" + if c.expectHCL1Message { + require.Contains(t, err.Error(), exptMessage) + } else { + require.NotContains(t, err.Error(), exptMessage) + } + }) + } +} + // Test StructJob with jobfile from HTTP Server func TestJobGetter_HTTPServer(t *testing.T) { t.Parallel()