From dc5c56eb1a1250c8d8e05514d0bdebb970ba2658 Mon Sep 17 00:00:00 2001 From: Alessio Perugini Date: Mon, 2 Oct 2023 09:21:03 +0200 Subject: [PATCH] fix wrong IndexFile truncate (#2346) --- arduino/resources/index.go | 11 ++++++++--- arduino/resources/resources_test.go | 23 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/arduino/resources/index.go b/arduino/resources/index.go index c1412c5ba61..ffd9bb4b0b0 100644 --- a/arduino/resources/index.go +++ b/arduino/resources/index.go @@ -42,11 +42,16 @@ type IndexResource struct { // IndexFileName returns the index file name as it is saved in data dir (package_xxx_index.json). func (res *IndexResource) IndexFileName() (string, error) { filename := path.Base(res.URL.Path) // == package_index.json[.gz] || packacge_index.tar.bz2 - if filename == "." || filename == "" { + if filename == "." || filename == "" || filename == "/" { return "", &arduino.InvalidURLError{} } - if i := strings.Index(filename, "."); i != -1 { - filename = filename[:i] + switch { + case strings.HasSuffix(filename, ".json"): + return filename, nil + case strings.HasSuffix(filename, ".gz"): + return strings.TrimSuffix(filename, ".gz"), nil + case strings.HasSuffix(filename, ".tar.bz2"): + return strings.TrimSuffix(filename, ".tar.bz2") + ".json", nil } return filename + ".json", nil } diff --git a/arduino/resources/resources_test.go b/arduino/resources/resources_test.go index fe489f00ecf..9cf8ae54509 100644 --- a/arduino/resources/resources_test.go +++ b/arduino/resources/resources_test.go @@ -18,6 +18,7 @@ package resources import ( "crypto" "encoding/hex" + "fmt" "net" "net/http" "net/url" @@ -148,3 +149,25 @@ func TestIndexDownloadAndSignatureWithinArchive(t *testing.T) { require.False(t, invDestDir.Join("package_index.json").Exist()) require.False(t, invDestDir.Join("package_index.json.sig").Exist()) } + +func TestIndexFileName(t *testing.T) { + tests := []struct { + url string + expected string + }{ + {url: "package_index.json", expected: "package_index.json"}, + {url: "package_index.json.gz", expected: "package_index.json"}, + {url: "package_index.tar.bz2", expected: "package_index.json"}, + // https://github.com/arduino/arduino-cli/issues/2345 + {url: "package_arduino.cc_index.json", expected: "package_arduino.cc_index.json"}, + {url: "package_arduino.cc_index.json.gz", expected: "package_arduino.cc_index.json"}, + {url: "package_arduino.cc_index.tar.bz2", expected: "package_arduino.cc_index.json"}, + {url: "http://drazzy.com/package_drazzy.com_index.json", expected: "package_drazzy.com_index.json"}, + } + for _, tc := range tests { + ir := IndexResource{URL: &url.URL{Path: tc.url}} + name, err := ir.IndexFileName() + require.NoError(t, err, fmt.Sprintf("error trying url: %v", tc)) + require.Equal(t, tc.expected, name) + } +}