@@ -677,6 +677,35 @@ func (m *Manager) DownloadLibraryToDir(ctx context.Context, lib Library, libsDir
677677 return m .downloadLibraryToDir (ctx , lib , libsDir , progressFn )
678678}
679679
680+ // downloadToFile reads from reader into tmpFile in chunks, reporting progress
681+ // and returning the total bytes written. It closes tmpFile before returning.
682+ func downloadToFile (tmpFile * os.File , reader io.Reader , size int64 , progressFn func (downloaded , total int64 )) (int64 , error ) {
683+ var downloadedBytes int64
684+ buf := make ([]byte , 32 * 1024 )
685+ for {
686+ n , readErr := reader .Read (buf )
687+ if n > 0 {
688+ if _ , writeErr := tmpFile .Write (buf [:n ]); writeErr != nil {
689+ _ = tmpFile .Close ()
690+ return 0 , fmt .Errorf ("failed to write file: %w" , writeErr )
691+ }
692+ downloadedBytes += int64 (n )
693+ if progressFn != nil {
694+ progressFn (downloadedBytes , size )
695+ }
696+ }
697+ if readErr == io .EOF {
698+ break
699+ }
700+ if readErr != nil {
701+ _ = tmpFile .Close ()
702+ return 0 , fmt .Errorf ("failed to read response: %w" , readErr )
703+ }
704+ }
705+ _ = tmpFile .Close ()
706+ return downloadedBytes , nil
707+ }
708+
680709// downloadLibraryToDir downloads a library to a specific libs directory.
681710// Shared libraries (.so/.dll) go to libsDir; binaries go to cache root.
682711//
@@ -742,31 +771,12 @@ func (m *Manager) downloadLibraryToDir(ctx context.Context, lib Library, libsDir
742771
743772 // Download with progress and hash verification
744773 hash := sha256 .New ()
745- var downloadedBytes int64
746774 reader := io .TeeReader (resp .Body , hash )
747775
748- buf := make ([]byte , 32 * 1024 )
749- for {
750- n , readErr := reader .Read (buf )
751- if n > 0 {
752- if _ , writeErr := tmpFile .Write (buf [:n ]); writeErr != nil {
753- _ = tmpFile .Close ()
754- return fmt .Errorf ("failed to write file: %w" , writeErr )
755- }
756- downloadedBytes += int64 (n )
757- if progressFn != nil {
758- progressFn (downloadedBytes , lib .Size )
759- }
760- }
761- if readErr == io .EOF {
762- break
763- }
764- if readErr != nil {
765- _ = tmpFile .Close ()
766- return fmt .Errorf ("failed to read response: %w" , readErr )
767- }
776+ downloadedBytes , err := downloadToFile (tmpFile , reader , lib .Size , progressFn )
777+ if err != nil {
778+ return err
768779 }
769- _ = tmpFile .Close ()
770780
771781 // Verify hash (skip if SHA256 is empty)
772782 if lib .SHA256 != "" {
0 commit comments