gilt 0.11.2

Fast, beautiful terminal formatting for Rust — styles, tables, trees, syntax highlighting, progress bars, markdown.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
//! HTTP/reqwest integration module -- pre-built progress for HTTP requests.
//!
//! Provides an extension trait for [`reqwest::RequestBuilder`] that adds progress
//! tracking to HTTP requests, with curl-style progress display showing transfer
//! speed, downloaded size, total size, ETA, and a progress bar.
//!
//! # Features
//!
//! This module requires the `http` feature to be enabled:
//!
//! ```toml
//! [dependencies]
//! gilt = { version = "0.8", features = ["http"] }
//! ```
//!
//! # Examples
//!
//! ## Simple download with progress
//!
//! ```rust,no_run
//! use gilt::http::RequestBuilderProgress;
//!
//! # async fn example() -> reqwest::Result<()> {
//! let response = reqwest::Client::new()
//!     .get("https://api.example.com/data.json")
//!     .with_progress("Downloading")
//!     .send()
//!     .await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Download to file
//!
//! ```rust,no_run
//! use std::path::Path;
//!
//! # async fn example() -> reqwest::Result<()> {
//! let bytes = gilt::http::download_with_progress(
//!     "https://example.com/file.zip",
//!     Path::new("file.zip"),
//!     "Downloading file"
//! ).await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Read JSON response with progress
//!
//! ```rust,no_run
//! use serde::Deserialize;
//! use gilt::http::RequestBuilderProgress;
//!
//! #[derive(Deserialize)]
//! struct Data {
//!     name: String,
//! }
//!
//! # async fn example() -> reqwest::Result<()> {
//! let data: Data = reqwest::Client::new()
//!     .get("https://api.example.com/data.json")
//!     .with_progress("Fetching data")
//!     .send()
//!     .await?
//!     .json()
//!     .await?;
//! # Ok(())
//! # }
//! ```

use std::fmt;
use std::io;
use std::path::Path;

use bytes::Bytes;
use reqwest::{Client, RequestBuilder, Response, StatusCode};

use crate::progress::{
    BarColumn, DownloadColumn, Progress, ProgressColumn, TaskId, TextColumn, TimeRemainingColumn,
    TransferSpeedColumn,
};

// Re-export reqwest types for convenience
pub use reqwest::{Error, Result};

// ---------------------------------------------------------------------------
// Error types
// ---------------------------------------------------------------------------

/// Error type for text() method.
#[derive(Debug)]
pub enum TextError {
    /// A reqwest error occurred.
    Reqwest(reqwest::Error),
    /// The response body was not valid UTF-8.
    Utf8(std::string::FromUtf8Error),
}

impl fmt::Display for TextError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TextError::Reqwest(e) => write!(f, "request error: {}", e),
            TextError::Utf8(e) => write!(f, "UTF-8 error: {}", e),
        }
    }
}

impl std::error::Error for TextError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            TextError::Reqwest(e) => Some(e),
            TextError::Utf8(e) => Some(e),
        }
    }
}

impl From<reqwest::Error> for TextError {
    fn from(e: reqwest::Error) -> Self {
        TextError::Reqwest(e)
    }
}

/// Error type for json() method.
#[derive(Debug)]
pub enum JsonError {
    /// A reqwest error occurred.
    Reqwest(reqwest::Error),
    /// JSON parsing failed.
    Json(serde_json::Error),
}

impl fmt::Display for JsonError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            JsonError::Reqwest(e) => write!(f, "request error: {}", e),
            JsonError::Json(e) => write!(f, "JSON error: {}", e),
        }
    }
}

impl std::error::Error for JsonError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            JsonError::Reqwest(e) => Some(e),
            JsonError::Json(e) => Some(e),
        }
    }
}

impl From<reqwest::Error> for JsonError {
    fn from(e: reqwest::Error) -> Self {
        JsonError::Reqwest(e)
    }
}

/// Error type for download operations.
#[derive(Debug)]
pub enum DownloadError {
    /// An HTTP error occurred.
    Http(reqwest::Error),
    /// An I/O error occurred.
    Io(io::Error),
}

impl fmt::Display for DownloadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DownloadError::Http(e) => write!(f, "HTTP error: {}", e),
            DownloadError::Io(e) => write!(f, "I/O error: {}", e),
        }
    }
}

impl std::error::Error for DownloadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            DownloadError::Http(e) => Some(e),
            DownloadError::Io(e) => Some(e),
        }
    }
}

impl From<reqwest::Error> for DownloadError {
    fn from(e: reqwest::Error) -> Self {
        DownloadError::Http(e)
    }
}

impl From<io::Error> for DownloadError {
    fn from(e: io::Error) -> Self {
        DownloadError::Io(e)
    }
}

// ---------------------------------------------------------------------------
// RequestBuilderProgress trait
// ---------------------------------------------------------------------------

/// Extension trait for [`reqwest::RequestBuilder`] that adds progress tracking.
///
/// This trait provides the [`with_progress`](RequestBuilderProgress::with_progress)
/// method to wrap a request builder with progress tracking.
///
/// # Examples
///
/// ```rust,no_run
/// use gilt::http::RequestBuilderProgress;
///
/// # async fn example() -> reqwest::Result<()> {
/// let response = reqwest::Client::new()
///     .get("https://example.com/file.zip")
///     .with_progress("Downloading file")
///     .send()
///     .await?;
/// # Ok(())
/// # }
/// ```
pub trait RequestBuilderProgress: Sized {
    /// Add progress tracking to this request.
    ///
    /// Returns a [`ProgressRequestBuilder`] that will display a progress bar
    /// when the request is sent. The progress bar shows:
    /// - Transfer speed (e.g., "45.2 MB/s")
    /// - Downloaded size / Total size (e.g., "45.2/100.0 MB")
    /// - ETA (estimated time remaining)
    /// - A visual progress bar
    ///
    /// When the content length is unknown (no `Content-Length` header),
    /// the progress bar falls back to a spinner animation.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use gilt::http::RequestBuilderProgress;
    ///
    /// # async fn example() -> reqwest::Result<()> {
    /// let response = reqwest::Client::new()
    ///     .get("https://example.com/large-file.zip")
    ///     .with_progress("Downloading large file")
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    fn with_progress(self, description: &str) -> ProgressRequestBuilder;
}

impl RequestBuilderProgress for RequestBuilder {
    fn with_progress(self, description: &str) -> ProgressRequestBuilder {
        ProgressRequestBuilder {
            inner: self,
            description: description.to_string(),
        }
    }
}

// ---------------------------------------------------------------------------
// ProgressRequestBuilder
// ---------------------------------------------------------------------------

/// A wrapper around [`reqwest::RequestBuilder`] that adds progress tracking.
///
/// Created by calling [`with_progress`](RequestBuilderProgress::with_progress)
/// on a [`reqwest::RequestBuilder`]. The progress display starts when
/// [`send`](ProgressRequestBuilder::send) is called and automatically stops
/// when the response body has been fully received.
///
/// # Examples
///
/// ```rust,no_run
/// use gilt::http::RequestBuilderProgress;
///
/// # async fn example() -> reqwest::Result<()> {
/// let response = reqwest::Client::new()
///     .get("https://example.com/data.json")
///     .with_progress("Fetching data")
///     .send()
///     .await?;
/// # Ok(())
/// # }
/// ```
pub struct ProgressRequestBuilder {
    inner: RequestBuilder,
    description: String,
}

impl ProgressRequestBuilder {
    /// Send the request with progress tracking.
    ///
    /// This method sends the request and displays a progress bar while
    /// receiving the response body. The progress bar shows transfer speed,
    /// downloaded/total size, ETA, and a visual bar.
    ///
    /// Returns a [`ProgressResponse`] that can be used to read the response
    /// body with continued progress tracking.
    ///
    /// # Errors
    ///
    /// Returns a [`reqwest::Error`] if the request fails or if there are
    /// network errors.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use gilt::http::RequestBuilderProgress;
    ///
    /// # async fn example() -> reqwest::Result<()> {
    /// let response = reqwest::Client::new()
    ///     .get("https://example.com/file.zip")
    ///     .with_progress("Downloading")
    ///     .send()
    ///     .await?;
    ///
    /// // Read the body with progress tracking
    /// let bytes = response.bytes().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn send(self) -> Result<ProgressResponse> {
        let description = self.description.clone();
        let response = self.inner.send().await?;
        Ok(ProgressResponse::new(response, description))
    }
}

// ---------------------------------------------------------------------------
// ProgressResponse
// ---------------------------------------------------------------------------

/// A wrapper around [`reqwest::Response`] that provides progress tracking
/// while reading the response body.
///
/// Created by calling [`send`](ProgressRequestBuilder::send) on a
/// [`ProgressRequestBuilder`]. The progress display automatically starts
/// when the response is received and stops when the body is fully consumed.
///
/// # Examples
///
/// ```rust,no_run
/// use gilt::http::RequestBuilderProgress;
///
/// # async fn example() -> reqwest::Result<()> {
/// let response = reqwest::Client::new()
///     .get("https://example.com/file.zip")
///     .with_progress("Downloading")
///     .send()
///     .await?;
///
/// // Read all bytes with progress tracking
/// let bytes = response.bytes().await?;
/// println!("Downloaded {} bytes", bytes.len());
/// # Ok(())
/// # }
/// ```
pub struct ProgressResponse {
    inner: Option<Response>,
    progress: Option<Progress>,
    task_id: TaskId,
    total: Option<f64>,
    #[allow(dead_code)]
    description: String,
}

impl ProgressResponse {
    /// Create a new `ProgressResponse` from a [`reqwest::Response`].
    fn new(response: Response, description: String) -> Self {
        // Get content length if available
        let total = response.content_length().map(|n| n as f64);

        // Create progress display
        let mut progress = create_progress(total);
        let task_id = progress.add_task(&description, total);
        progress.start();

        Self {
            inner: Some(response),
            progress: Some(progress),
            task_id,
            total,
            description,
        }
    }

    /// Returns the status code of the response.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use gilt::http::RequestBuilderProgress;
    ///
    /// # async fn example() -> reqwest::Result<()> {
    /// let response = reqwest::Client::new()
    ///     .get("https://example.com/file.zip")
    ///     .with_progress("Downloading")
    ///     .send()
    ///     .await?;
    ///
    /// println!("Status: {}", response.status());
    /// # Ok(())
    /// # }
    /// ```
    pub fn status(&self) -> StatusCode {
        self.inner
            .as_ref()
            .map(|r| r.status())
            .unwrap_or(StatusCode::OK)
    }

    /// Returns the content length of the response if available.
    ///
    /// This is the value from the `Content-Length` header, if present.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use gilt::http::RequestBuilderProgress;
    ///
    /// # async fn example() -> reqwest::Result<()> {
    /// let response = reqwest::Client::new()
    ///     .get("https://example.com/file.zip")
    ///     .with_progress("Downloading")
    ///     .send()
    ///     .await?;
    ///
    /// if let Some(len) = response.content_length() {
    ///     println!("Content length: {} bytes", len);
    /// }
    ///
    /// let bytes = response.bytes().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn content_length(&self) -> Option<u64> {
        self.inner.as_ref().and_then(|r| r.content_length())
    }

    /// Read the response body as bytes with progress tracking.
    ///
    /// This method reads the entire response body into memory as [`Bytes`].
    /// The progress bar updates as data is received.
    ///
    /// # Errors
    ///
    /// Returns a [`reqwest::Error`] if there are network errors or if the
    /// body cannot be read.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use gilt::http::RequestBuilderProgress;
    ///
    /// # async fn example() -> reqwest::Result<()> {
    /// let response = reqwest::Client::new()
    ///     .get("https://example.com/file.zip")
    ///     .with_progress("Downloading")
    ///     .send()
    ///     .await?;
    ///
    /// let bytes = response.bytes().await?;
    /// println!("Downloaded {} bytes", bytes.len());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn bytes(mut self) -> Result<Bytes> {
        let result = self.collect_body().await;
        self.stop_progress();
        result
    }

    /// Read the response body as a string with progress tracking.
    ///
    /// This method reads the entire response body and converts it to a `String`.
    /// The progress bar updates as data is received.
    ///
    /// # Errors
    ///
    /// Returns a [`reqwest::Error`] if there are network errors or if the body
    /// cannot be read. Returns a `FromUtf8Error` if the body is not valid UTF-8.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use gilt::http::RequestBuilderProgress;
    ///
    /// # async fn example() -> reqwest::Result<()> {
    /// let response = reqwest::Client::new()
    ///     .get("https://api.example.com/data.json")
    ///     .with_progress("Fetching JSON")
    ///     .send()
    ///     .await?;
    ///
    /// let text = response.text().await?;
    /// println!("Response: {}", text);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn text(mut self) -> std::result::Result<String, TextError> {
        let bytes = self.collect_body().await.map_err(TextError::Reqwest)?;
        self.stop_progress();
        String::from_utf8(bytes.to_vec()).map_err(TextError::Utf8)
    }

    /// Parse the response body as JSON with progress tracking.
    ///
    /// This method reads the entire response body and deserializes it as JSON
    /// into the target type `T`. The progress bar updates as data is received.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The target type to deserialize into. Must implement [`serde::de::DeserializeOwned`].
    ///
    /// # Errors
    ///
    /// Returns a [`JsonError`] if there are network errors, if the body
    /// cannot be read, or if the JSON is invalid.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use serde::Deserialize;
    /// use gilt::http::RequestBuilderProgress;
    ///
    /// #[derive(Deserialize)]
    /// struct User {
    ///     name: String,
    ///     email: String,
    /// }
    ///
    /// # async fn example() -> reqwest::Result<()> {
    /// let user: User = reqwest::Client::new()
    ///     .get("https://api.example.com/user/1")
    ///     .with_progress("Loading user")
    ///     .send()
    ///     .await?
    ///     .json()
    ///     .await?;
    ///
    /// println!("User: {}", user.name);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn json<T: serde::de::DeserializeOwned>(
        mut self,
    ) -> std::result::Result<T, JsonError> {
        let bytes = self.collect_body().await.map_err(JsonError::Reqwest)?;
        self.stop_progress();
        serde_json::from_slice(&bytes).map_err(JsonError::Json)
    }

    /// Collect the response body into bytes with progress updates.
    async fn collect_body(&mut self) -> Result<Bytes> {
        use futures_util::StreamExt;

        // Take ownership of the inner response to consume the body
        let response = self.inner.take().expect("inner response already consumed");
        let mut body_stream = response.bytes_stream();
        let mut collected = Vec::new();

        while let Some(chunk) = body_stream.next().await {
            let chunk: Bytes = chunk?;
            collected.extend_from_slice(&chunk);

            // Update progress
            if let Some(ref mut progress) = self.progress {
                progress.advance(self.task_id, chunk.len() as f64);
                progress.refresh();
            }
        }

        Ok(Bytes::from(collected))
    }

    /// Stop the progress display.
    fn stop_progress(&mut self) {
        if let Some(mut progress) = self.progress.take() {
            // Mark task as complete
            if let Some(total) = self.total {
                progress.update(self.task_id, Some(total), None, None, None, None);
            }
            progress.stop();
        }
    }
}

impl Drop for ProgressResponse {
    fn drop(&mut self) {
        self.stop_progress();
    }
}

// ---------------------------------------------------------------------------
// Convenience functions
// ---------------------------------------------------------------------------

/// Perform a GET request with progress tracking.
///
/// This is a convenience function that creates a new [`reqwest::Client`],
/// sends a GET request to the specified URL, and returns a [`ProgressResponse`]
/// with progress tracking enabled.
///
/// # Arguments
///
/// * `url` - The URL to request.
///
/// # Errors
///
/// Returns a [`reqwest::Error`] if the request fails.
///
/// # Examples
///
/// ```rust,no_run
/// # async fn example() -> reqwest::Result<()> {
/// let response = gilt::http::get("https://api.example.com/data.json").await?;
/// let bytes = response.bytes().await?;
/// # Ok(())
/// # }
/// ```
pub async fn get(url: &str) -> Result<ProgressResponse> {
    Client::new()
        .get(url)
        .with_progress("Downloading")
        .send()
        .await
}

/// Perform a POST request with progress tracking.
///
/// This is a convenience function that creates a new [`reqwest::Client`],
/// sends a POST request to the specified URL, and returns a [`ProgressResponse`]
/// with progress tracking enabled.
///
/// # Arguments
///
/// * `url` - The URL to request.
///
/// # Errors
///
/// Returns a [`reqwest::Error`] if the request fails.
///
/// # Examples
///
/// ```rust,no_run
/// # async fn example() -> reqwest::Result<()> {
/// let response = gilt::http::post("https://api.example.com/upload").await?;
/// let bytes = response.bytes().await?;
/// # Ok(())
/// # }
/// ```
pub async fn post(url: &str) -> Result<ProgressResponse> {
    Client::new()
        .post(url)
        .with_progress("Uploading")
        .send()
        .await
}

/// Download a file from a URL to a local path with progress tracking.
///
/// This function downloads the content at the specified URL and saves it to
/// the given file path. A progress bar is displayed during the download.
///
/// # Arguments
///
/// * `url` - The URL to download from.
/// * `path` - The local file path to save to.
///
/// # Returns
///
/// Returns the number of bytes downloaded on success.
///
/// # Errors
///
/// Returns a [`DownloadError`] if the download fails or if there are I/O errors.
///
/// # Examples
///
/// ```rust,no_run
/// use std::path::Path;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let bytes_written = gilt::http::download(
///     "https://example.com/file.zip",
///     Path::new("file.zip")
/// ).await?;
/// println!("Downloaded {} bytes", bytes_written);
/// # Ok(())
/// # }
/// ```
pub async fn download(url: &str, path: &Path) -> std::result::Result<u64, DownloadError> {
    download_with_progress(url, path, "Downloading").await
}

/// Download a file from a URL to a local path with custom progress description.
///
/// This function is similar to [`download`], but allows you to specify a custom
/// description for the progress bar.
///
/// # Arguments
///
/// * `url` - The URL to download from.
/// * `path` - The local file path to save to.
/// * `description` - The description to show in the progress bar.
///
/// # Returns
///
/// Returns the number of bytes downloaded on success.
///
/// # Errors
///
/// Returns a [`DownloadError`] if the download fails or if there are I/O errors.
///
/// # Examples
///
/// ```rust,no_run
/// use std::path::Path;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let bytes_written = gilt::http::download_with_progress(
///     "https://example.com/large-file.zip",
///     Path::new("large-file.zip"),
///     "Downloading archive"
/// ).await?;
/// println!("Downloaded {} bytes", bytes_written);
/// # Ok(())
/// # }
/// ```
pub async fn download_with_progress(
    url: &str,
    path: &Path,
    description: &str,
) -> std::result::Result<u64, DownloadError> {
    use std::fs::File;
    use std::io::Write;

    let response = Client::new()
        .get(url)
        .with_progress(description)
        .send()
        .await?;

    let bytes = response.bytes().await.map_err(DownloadError::Http)?;
    let len = bytes.len() as u64;

    // Write to file
    let mut file = File::create(path)?;
    file.write_all(&bytes)?;

    Ok(len)
}

// ---------------------------------------------------------------------------
// Helper functions
// ---------------------------------------------------------------------------

/// Create a progress display with appropriate columns for HTTP downloads.
///
/// This creates a progress bar with:
/// - Description column
/// - Progress bar column
/// - Downloaded/Total size column
/// - Transfer speed column
/// - Time remaining column
///
/// If `total` is `None`, the bar will show a spinner instead of a progress bar
/// (indeterminate mode).
fn create_progress(_total: Option<f64>) -> Progress {
    let columns: Vec<Box<dyn ProgressColumn>> = vec![
        Box::new(TextColumn::new("{task.description}")),
        Box::new(BarColumn::new()),
        Box::new(DownloadColumn::new()),
        Box::new(TransferSpeedColumn::new()),
        Box::new(TimeRemainingColumn::new()),
    ];

    Progress::new(columns)
        .with_auto_refresh(true)
        .with_refresh_per_second(10.0)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // Note: Most tests would require a mock HTTP server.
    // These are basic unit tests for the types.

    #[test]
    fn test_progress_request_builder_creation() {
        let builder = Client::new().get("https://example.com");
        let progress_builder = builder.with_progress("Test");
        assert_eq!(progress_builder.description, "Test");
    }

    #[test]
    fn test_create_progress_with_total() {
        let _progress = create_progress(Some(1000.0));
        // Progress should be created successfully
        // We can't easily inspect the internal state, but we can verify it doesn't panic
    }

    #[test]
    fn test_create_progress_without_total() {
        let _progress = create_progress(None);
        // Progress should be created successfully for indeterminate mode
    }
}