Skip to content

Commit

Permalink
feat: handle links with the same name
Browse files Browse the repository at this point in the history
  • Loading branch information
michalczmiel committed Feb 4, 2024
1 parent 5725c33 commit e172c51
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
13 changes: 12 additions & 1 deletion internal/images.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package internal

import (
"fmt"
"path"
"sync"
)
Expand All @@ -21,12 +22,22 @@ type DownloadInput struct {
func PrepareLinksForDownload(links []string, parameters *Parameters) []DownloadInput {
var downloadInputs []DownloadInput

for _, link := range links {
// set is not available in Go, so we use map instead to remove duplicates
var alreadyTakenNames = map[string]struct{}{}

for index, link := range links {
fileName, err := GetFileNameFromUrl(link)
if err != nil {
continue
}

_, exists := alreadyTakenNames[fileName]
if exists {
fileName = fmt.Sprint(index) + fileName
}

alreadyTakenNames[fileName] = struct{}{}

filePath := path.Join(parameters.Directory, fileName)
downloadInputs = append(downloadInputs, DownloadInput{Url: link, FilePath: filePath})
}
Expand Down
31 changes: 31 additions & 0 deletions internal/images_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package internal

import "testing"

func TestPrepareLinksForDownload(t *testing.T) {
urls := []string{
"https://example.com/v2/file/5a9abk2-PL/image;s=200x0;q=50",
"https://example.com/v2/file/fad6g2x-PL/image;s=200x0;q=50",
}

parameters := &Parameters{
Directory: "images",
}

given := PrepareLinksForDownload(urls, parameters)

expected := []DownloadInput{
{Url: "https://example.com/v2/file/5a9abk2-PL/image;s=200x0;q=50", FilePath: "images/image;s=200x0;q=50"},
{Url: "https://example.com/v2/file/fad6g2x-PL/image;s=200x0;q=50", FilePath: "images/1image;s=200x0;q=50"},
}

for i, input := range given {
if input.Url != expected[i].Url {
t.Errorf("got %v expected %v", input.Url, expected[i].Url)
}

if input.FilePath != expected[i].FilePath {
t.Errorf("got %v expected %v", input.FilePath, expected[i].FilePath)
}
}
}

0 comments on commit e172c51

Please sign in to comment.