Skip to content

Commit

Permalink
fix(golang-rewrite): Fix new lines from asdf set command (#1841)
Browse files Browse the repository at this point in the history
Co-authored-by: Trevor Brown <[email protected]>
  • Loading branch information
AlfredoRamos and Stratus3D authored Jan 14, 2025
1 parent bc08bc2 commit 251812b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
18 changes: 18 additions & 0 deletions internal/cli/set/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,24 @@ func TestAll(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t, "lua 5.2.3\n", string(bytes))
})

t.Run("sets version in current directory only once", func(t *testing.T) {
stdout, stderr := buildOutputs()
dir := t.TempDir()
assert.Nil(t, os.Chdir(dir))

_ = Main(&stdout, &stderr, []string{"lua", "5.2.3"}, false, false, homeFunc)
err := Main(&stdout, &stderr, []string{"lua", "5.2.3"}, false, false, homeFunc)

assert.Nil(t, err)
assert.Equal(t, stdout.String(), "")
assert.Equal(t, stderr.String(), "")

path := filepath.Join(dir, ".tool-versions")
bytes, err := os.ReadFile(path)
assert.Nil(t, err)
assert.Equal(t, "lua 5.2.3\n", string(bytes))
})
}

func buildOutputs() (strings.Builder, strings.Builder) {
Expand Down
12 changes: 9 additions & 3 deletions internal/toolversions/toolversions.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,22 +52,22 @@ func updateContentWithToolVersions(content string, toolVersions []ToolVersions)
// write updated version
newTv := toolVersions[indexMatching]
newTokens := toolVersionsToTokens(newTv)
fmt.Fprintf(&output, "%s\n", encodeLine(newTokens, comment))
writeLine(&output, encodeLine(newTokens, comment))
toolVersions = slices.Delete(toolVersions, indexMatching, indexMatching+1)
continue
}
}

// write back original line
fmt.Fprintf(&output, "%s\n", line)
writeLine(&output, line)
}
}

// If any ToolVersions structs remaining, write them to the end of the file
if len(toolVersions) > 0 {
for _, toolVersion := range toolVersions {
newTokens := toolVersionsToTokens(toolVersion)
fmt.Fprintf(&output, "%s\n", encodeLine(newTokens, ""))
writeLine(&output, encodeLine(newTokens, ""))
}
}

Expand Down Expand Up @@ -261,3 +261,9 @@ func encodeLine(tokens []string, comment string) string {
}
return fmt.Sprintf("%s #%s", tokensStr, comment)
}

func writeLine(output *strings.Builder, line string) {
if strings.TrimSpace(line) != "" {
output.WriteString(line + "\n")
}
}

0 comments on commit 251812b

Please sign in to comment.