From d2406fb6dac7289abf46fd73157217964de68e64 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 21 Jul 2022 11:15:53 -0400 Subject: [PATCH] fix: append trailing newline to .tool-versions files when missing If a .tool-versions file did not end with a newline new tools and versions would get appended to the same line rather than properly added on a new line in the file Fixes #1299 --- lib/functions/versions.bash | 4 ++++ test/version_commands.bats | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/lib/functions/versions.bash b/lib/functions/versions.bash index 4e27ce834..91fd54fd2 100644 --- a/lib/functions/versions.bash +++ b/lib/functions/versions.bash @@ -64,6 +64,10 @@ version_command() { sed -i.bak -e "s|^$plugin_name .*$|$plugin_name ${resolved_versions[*]}|" "$file" rm -f "$file".bak else + # Add a trailing newline at the end of the file if missing + [[ -n "$(tail -c1 "$file")" && -f "$file" ]] && printf '\n' >>"$file" + + # Add a new version line to the end of the file printf "%s %s\\n" "$plugin_name" "${resolved_versions[*]}" >>"$file" fi } diff --git a/test/version_commands.bats b/test/version_commands.bats index 815a58119..b93e1af20 100644 --- a/test/version_commands.bats +++ b/test/version_commands.bats @@ -126,6 +126,22 @@ teardown() { [ "$(cat $PROJECT_DIR/.tool-versions)" = "dummy 1.1.0" ] } +@test "local should append trailing newline before appending new version when missing" { + echo -n 'foobar 1.0.0' >>$PROJECT_DIR/.tool-versions + + run asdf local "dummy" "1.1.0" + [ "$status" -eq 0 ] + [ "$(cat $PROJECT_DIR/.tool-versions)" = $'foobar 1.0.0\ndummy 1.1.0' ] +} + +@test "local should not append trailing newline before appending new version when one present" { + echo 'foobar 1.0.0' >>$PROJECT_DIR/.tool-versions + + run asdf local "dummy" "1.1.0" + [ "$status" -eq 0 ] + [ "$(cat $PROJECT_DIR/.tool-versions)" = $'foobar 1.0.0\ndummy 1.1.0' ] +} + @test "local should fail to set a path:dir if dir does not exists " { run asdf local "dummy" "path:$PROJECT_DIR/local" [ "$output" = "version path:$PROJECT_DIR/local is not installed for dummy" ] @@ -236,6 +252,22 @@ teardown() { [ "$(cat $HOME/.tool-versions)" = "dummy 1.1.0" ] } +@test "global should append trailing newline before appending new version when missing" { + echo -n 'foobar 1.0.0' >>$HOME/.tool-versions + + run asdf global "dummy" "1.1.0" + [ "$status" -eq 0 ] + [ "$(cat $HOME/.tool-versions)" = $'foobar 1.0.0\ndummy 1.1.0' ] +} + +@test "global should not append trailing newline before appending new version when one present" { + echo 'foobar 1.0.0' >>$HOME/.tool-versions + + run asdf global "dummy" "1.1.0" + [ "$status" -eq 0 ] + [ "$(cat $HOME/.tool-versions)" = $'foobar 1.0.0\ndummy 1.1.0' ] +} + @test "global should fail to set a path:dir if dir does not exists " { run asdf global "dummy" "path:$PROJECT_DIR/local" [ "$output" = "version path:$PROJECT_DIR/local is not installed for dummy" ]