@@ -3,22 +3,29 @@ package utils
33import (
44 "fmt"
55 "io"
6+ "log"
67 "net/http"
78 "os"
89 "path/filepath"
910)
1011
1112func DownloadFile (url string , destDir string ) (string , error ) {
13+ log .Printf ("Attempting to download from URL: %s" , url )
14+
1215 // Get the file name from the URL
1316 fileName := filepath .Base (url )
17+ log .Printf ("Target filename: %s" , fileName )
1418
1519 // Create the destination file path
1620 destPath := filepath .Join (destDir , fileName )
21+ log .Printf ("Destination path: %s" , destPath )
1722
1823 _ , errInfo := os .Stat (destPath )
1924 if errInfo != nil && os .IsExist (errInfo ) {
25+ log .Printf ("File already exists at destination, skipping download" )
2026 return destPath , nil
2127 }
28+
2229 // Create the destination file
2330 outFile , err := os .Create (destPath )
2431 if err != nil {
@@ -27,22 +34,36 @@ func DownloadFile(url string, destDir string) (string, error) {
2734 defer outFile .Close ()
2835
2936 // Make the HTTP GET request
30- resp , err := http .Get (url )
37+ log .Printf ("Making HTTP GET request..." )
38+ client := & http.Client {}
39+ req , err := http .NewRequest ("GET" , url , nil )
40+ if err != nil {
41+ return "" , fmt .Errorf ("failed to create request: %w" , err )
42+ }
43+ req .Header .Set ("User-Agent" , "Codacy-CLI" )
44+ resp , err := client .Do (req )
3145 if err != nil {
3246 return "" , fmt .Errorf ("failed to make GET request: %w" , err )
3347 }
3448 defer resp .Body .Close ()
3549
3650 // Check if the request was successful
3751 if resp .StatusCode != http .StatusOK {
38- return "" , fmt .Errorf ("failed to download file: status code %d" , resp .StatusCode )
52+ body , _ := io .ReadAll (resp .Body )
53+ return "" , fmt .Errorf ("failed to download file: status code %d, URL: %s, Response: %s" , resp .StatusCode , url , string (body ))
3954 }
4055
4156 // Copy the response body to the destination file
42- _ , err = io .Copy (outFile , resp .Body )
57+ log .Printf ("Downloading file content..." )
58+ written , err := io .Copy (outFile , resp .Body )
4359 if err != nil {
4460 return "" , fmt .Errorf ("failed to copy file contents: %w" , err )
4561 }
62+ log .Printf ("Downloaded %d bytes" , written )
63+
64+ if written == 0 {
65+ return "" , fmt .Errorf ("downloaded file is empty (0 bytes)" )
66+ }
4667
4768 return destPath , nil
4869}
0 commit comments