gtars_bbcache/
utils.rs

1//! Utility functions for bbcache configuration and display.
2//!
3//! This module provides helper functions for:
4//! - Determining default cache locations and API endpoints
5//! - Formatting and displaying cached resources in tabular form
6
7use super::consts::{BBCLIENT_CACHE_ENV, BEDBASE_API_ENV};
8use biocrs::models::Resource;
9use dirs::home_dir;
10use std::env;
11use std::path::PathBuf;
12use tabled::{Table, Tabled};
13
14/// Printable representation of a cached resource for display in tables.
15///
16/// This struct is used internally by [`print_resources`] to format resource
17/// information in a human-readable tabular format.
18#[derive(Tabled)]
19pub struct ResourcePrint {
20    /// Resource identifier (e.g., BED file or BED set ID)
21    id: String,
22    /// Local filesystem path to the cached resource
23    path: String,
24}
25
26/// Returns the default cache folder path.
27///
28/// The cache folder is determined in the following priority order:
29/// 1. `BBCLIENT_CACHE` environment variable if set
30/// 2. `$HOME/.bbcache/` if home directory is available
31/// 3. `/tmp/.bbcache/` as a fallback
32///
33/// # Returns
34///
35/// A [`PathBuf`] pointing to the cache folder location.
36///
37/// # Examples
38///
39/// ```rust
40/// use gtars_bbcache::utils::get_default_cache_folder;
41///
42/// let cache_path = get_default_cache_folder();
43/// println!("Cache will be stored at: {:?}", cache_path);
44/// ```
45///
46/// # Environment Variables
47///
48/// - `BBCLIENT_CACHE`: Custom cache directory path (highest priority)
49/// - `HOME`: User's home directory (used for default location)
50pub fn get_default_cache_folder() -> PathBuf {
51    if let Ok(val) = env::var(BBCLIENT_CACHE_ENV) {
52        PathBuf::from(val)
53    } else {
54        let home = env::var("HOME")
55            .or_else(|_| {
56                home_dir()
57                    .map(|p| p.to_string_lossy().into_owned())
58                    .ok_or(std::env::VarError::NotPresent)
59            })
60            .unwrap_or_else(|_| "/tmp".to_string());
61
62        let mut path = PathBuf::from(home);
63        path.push(".bbcache/");
64        path
65    }
66}
67
68/// Returns the default BEDbase API endpoint URL.
69///
70/// The API endpoint is determined in the following priority order:
71/// 1. `BEDBASE_API` environment variable if set
72/// 2. `https://api.bedbase.org` as the default
73///
74/// # Returns
75///
76/// A [`String`] containing the BEDbase API endpoint URL.
77///
78/// # Examples
79///
80/// ```rust
81/// use gtars_bbcache::utils::get_default_bedbase_api;
82///
83/// let api_url = get_default_bedbase_api();
84/// println!("Using BEDbase API at: {}", api_url);
85/// ```
86///
87/// # Environment Variables
88///
89/// - `BEDBASE_API`: Custom BEDbase API endpoint
90pub fn get_default_bedbase_api() -> String {
91    env::var(BEDBASE_API_ENV).unwrap_or_else(|_| "https://api.bedbase.org".to_string())
92}
93
94/// Prints a list of resources in a formatted table.
95///
96/// This function takes a vector of [`Resource`] objects and displays them
97/// in a tabular format showing identifiers and paths. Useful for displaying
98/// the results of [`BBClient::list_beds`] or [`BBClient::list_bedsets`].
99///
100/// # Arguments
101///
102/// * `resources` - Vector of resources to display
103///
104/// # Examples
105///
106/// ```rust,no_run
107/// use gtars_bbcache::client::BBClient;
108/// use gtars_bbcache::utils::print_resources;
109///
110/// # fn main() -> anyhow::Result<()> {
111/// let mut client = BBClient::builder().finish()?;
112/// let beds = client.list_beds()?;
113/// print_resources(beds);
114/// # Ok(())
115/// # }
116/// ```
117///
118/// # Output Format
119///
120/// ```text
121/// ┌────────────────────────────────┬─────────────────────────┐
122/// │ id                             │ path                    │
123/// ├────────────────────────────────┼─────────────────────────┤
124/// │ 6b2e163a1d4319d99bd465c6c78... │ /path/to/cache/6/b/...  │
125/// └────────────────────────────────┴─────────────────────────┘
126/// ```
127pub fn print_resources(resources: Vec<Resource>) {
128    let mut resource_print: Vec<ResourcePrint> = Vec::new();
129
130    for resource in resources {
131        resource_print.push(ResourcePrint {
132            id: resource.rname,
133            path: resource.rpath,
134        })
135    }
136
137    let table = Table::new(resource_print);
138
139    println!("{}", table);
140}