12 Commits

Author SHA1 Message Date
f971f3ba81 Add package yaml 2025-01-09 17:10:51 +01:00
0919a189cf Table for github compatability 2025-01-09 17:10:20 +01:00
f4c1b04edb Include ECB logo 2025-01-09 17:10:20 +01:00
68f63e9cea Update the install instructions 2025-01-09 17:10:20 +01:00
ec8aa710e0 More readme 2025-01-09 16:00:11 +01:00
52377e9988 update to - 2025-01-09 15:45:55 +01:00
c381ed2a79 Simplify down to show-days 2025-01-09 15:44:09 +01:00
f501569040 Readme with images 2025-01-09 15:06:00 +01:00
a39d0331b3 Merge branch 'faster-cache' 2025-01-09 14:44:58 +01:00
1431e2b14f Keep caches in different files 2025-01-09 14:43:46 +01:00
65ad88acae rename view 2025-01-09 14:11:46 +01:00
5f3a075580 Merge branch 'perspective' 2025-01-09 13:57:45 +01:00
18 changed files with 425 additions and 115 deletions

51
.github/workflows/package.yml vendored Normal file
View File

@ -0,0 +1,51 @@
name: Build Packages
on:
push:
tags:
- "v*" # Triggers on tags starting with 'v'
permissions:
contents: write # Needed for creating releases
jobs:
build_and_release:
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Install Rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Install packaging tools
run: |
cargo install cargo-deb
cargo install cargo-generate-rpm
- name: Build Debian package
run: cargo deb
- id: get_tag_info
name: Get Tag Info
run: |
tag="${GITHUB_REF##*/}"
echo "Found tag: $tag"
message=$(git tag -l --format='%(contents)' "$tag")
# Set outputs using the recommended environment files approach
echo "tag=$tag" >> $GITHUB_OUTPUT
echo "message=$message" >> $GITHUB_OUTPUT
- name: Create GitHub Release
uses: ncipollo/release-action@v1
with:
tag: ${{ steps.get_tag_info.outputs.tag }}
name: Release ${{ steps.get_tag_info.outputs.tag }}
body: ${{ steps.get_tag_info.outputs.message }}
artifacts: |
target/debian/*.deb
token: ${{ secrets.GITHUB_TOKEN }}
allowUpdates: true

2
Cargo.lock generated
View File

@ -252,7 +252,7 @@ dependencies = [
[[package]] [[package]]
name = "ecb-rates" name = "ecb-rates"
version = "0.1.0" version = "1.0.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"chrono", "chrono",

View File

@ -1,7 +1,7 @@
[package] [package]
name = "ecb-rates" name = "ecb-rates"
description = "Query exchange rates from the European Central Bank (ECB)" description = "Query exchange rates from the European Central Bank (ECB)"
version = "0.1.0" version = "1.0.0"
edition = "2021" edition = "2021"
authors = ["Love Billenius <lovebillenius@disroot.org>"] authors = ["Love Billenius <lovebillenius@disroot.org>"]
license-file = "LICENSE" license-file = "LICENSE"

View File

@ -1,45 +1,85 @@
# ECB Rates # ECB Rates
A cli utility to fetch the currency rates against the Euro from the ECB. <p style="text-align: center">
<img
src="images/Logo_European_Central_Bank.svg"
width="200"
alt="European Central Bank Logo"
align="left"
/>
A CLI utility to fetch exchange reates from the European Central Bank.
<br />
<br />
<br />
<br />
<br />
<br />
<br />
</p>
## Install ## Install
First, make sure that you have the rust toolchain installed. If not, then go to [rustup](https://rustup.rs) to install it. First, make sure that you have the rust toolchain installed. If not, then go to [rustup](https://rustup.rs) to install it.
Now, Git clone the project, then cd into the projects root-dir. Thereafter run: Now, run the following cargo command:
```sh ```sh
cargo install --path . cargo install --git https://github.com/lov3b/ecb-rates.git
``` ```
Congratulations! Now the cli binary `ecb-rates` will be in your cargo bin folder. Congratulations! Now the cli binary `ecb-rates` will be in your cargo bin folder.
## Features ## Features
- Fetch and display select currencies: #### Fetch as many days as you want
- as an ASCII table
- in JSON prettified
- in JSON minified
- Fetch in different "resolutions":
- Last available day.
- Since the dawn of the *EUR*
- in day resolution
- in 90 day resolution
### Example It will fetch any of the following api nodes, and reduce them for you.
```sh - Last available day.
ecb-rates -c sek -c nok -c usd - Last 90 days
``` - Since the dawn of the *EUR*
```plain #### Display select currencies
2025-01-07
Currency Rate - as an ASCII table
--------------------- - in JSON prettified
USD 1.0393 - in JSON minified
SEK 11.475
NOK 11.7385 #### Cache
```
It features an extensive cache, which will [calculate hollidays](src/holiday.rs) in order to know whether to invalidate it or not.
#### Show the rates in your way
Change the rates for the perspective of any currency with the `--perspective` or `-p` flag.
Flip it from `EUR to ALL` to `ALL to EUR` with the `--invert` or `-i` flag. It will work as expected with the *perspective* option.
#### Fast
It wouldn't be a rust project without being *BLAZINGLY FAST*! When the cache is valid a single day will on my computer be shown in 3 ms. When the cache isn't being used it will be ~90ms. The cache speed will largely depend on your drive, the latter will depend on your network speed. Both options are fast enought to be in a `.bashrc` or `.zshrc`
### Examples
#### Show the original data from ECB
![eur-to-all](images/eur-to-all.png)
#### ...with only select currencies
![eur-to-all](images/eur-to-all-select.png)
#### Put the exchange rate in the perspective of any currency
![usd-to-all](images/usd-to-all.png)
#### Flip it
![all-to-usd](images/all-to-usd.png)
#### Show multiple days
![eur-to-all-multiple-days](images/eur-to-all-multiple-days.png)
## Acknowledgment ## Acknowledgment

View File

@ -0,0 +1,154 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:i="http://ns.adobe.com/AdobeIllustrator/10.0/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="398.5"
height="329.42899"
id="svg2362"
sodipodi:version="0.32"
inkscape:version="0.92.1 r15371"
version="1.0"
sodipodi:docname="Logo_European_Central_Bank.svg"
inkscape:output_extension="org.inkscape.output.svg.inkscape">
<defs
id="defs3" />
<sodipodi:namedview
inkscape:document-units="mm"
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.70710678"
inkscape:cx="-3.3417132"
inkscape:cy="39.599076"
inkscape:current-layer="layer1"
inkscape:window-width="1600"
inkscape:window-height="837"
inkscape:window-x="-8"
inkscape:window-y="-8"
showgrid="false"
inkscape:window-maximized="1" />
<metadata
id="metadata4">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-150.75,-367.64768)">
<g
id="g2384">
<path
i:knockout="Off"
d="M 496.009,494.23968 C 496.071,495.97068 496.267,497.65768 496.267,499.40768 C 496.267,579.87268 430.849,645.29868 350.388,645.29868 C 269.915,645.29868 204.476,579.87268 204.476,499.40768 C 204.476,497.65768 204.679,495.97068 204.742,494.23968 L 150.75,494.23968 L 150.75,697.07668 L 549.25,697.07668 L 549.25,494.23968 L 496.009,494.23968"
id="path13"
style="fill:#003399;fill-opacity:1" />
<path
i:knockout="Off"
d="M 218.624,499.40768 C 218.624,426.74068 277.712,367.64768 350.388,367.64768 C 423.056,367.64768 482.14,426.74068 482.14,499.40768 C 482.14,572.07468 423.056,631.15868 350.388,631.15868 C 277.712,631.15868 218.624,572.07468 218.624,499.40768"
id="path15"
style="fill:#003399;fill-opacity:1" />
<polygon
i:knockout="Off"
points="893.164,12.178 890.506,20.424 881.746,20.424 888.885,25.756 886.117,34.219 893.164,29.002 900.223,34.219 897.48,25.756 904.553,20.424 895.758,20.424 893.164,12.178 "
id="polygon17"
style="fill:#ffcc00;fill-opacity:1"
transform="translate(-542.487,367.64768)" />
<polygon
i:knockout="Off"
points="839.947,26.717 837.285,34.972 828.518,34.972 835.674,40.304 832.889,48.766 839.947,43.55 847.002,48.766 844.242,40.304 851.346,34.972 842.537,34.972 839.947,26.717 "
id="polygon19"
style="fill:#ffcc00;fill-opacity:1"
transform="translate(-542.487,367.64768)" />
<polygon
i:knockout="Off"
points="800.373,64.744 797.717,72.99 788.949,72.99 796.092,78.322 793.32,86.785 800.373,81.577 807.42,86.785 804.674,78.322 811.764,72.99 802.969,72.99 800.373,64.744 "
id="polygon21"
style="fill:#ffcc00;fill-opacity:1"
transform="translate(-542.487,367.64768)" />
<polygon
i:knockout="Off"
points="784.711,120.441 782.053,128.696 773.285,128.687 780.432,134.027 777.656,142.49 784.711,137.273 791.77,142.49 789.02,134.027 796.1,128.696 787.305,128.696 784.711,120.441 "
id="polygon23"
style="fill:#ffcc00;fill-opacity:1"
transform="translate(-542.487,367.64768)" />
<polygon
i:knockout="Off"
points="801.535,172.971 798.877,181.217 790.117,181.217 797.266,186.558 794.48,195.012 801.535,189.804 808.594,195.012 805.844,186.558 812.938,181.217 804.139,181.217 801.535,172.971 "
id="polygon25"
style="fill:#ffcc00;fill-opacity:1"
transform="translate(-542.487,367.64768)" />
<polygon
i:knockout="Off"
points="837.967,211.207 835.311,219.453 826.541,219.453 833.686,224.784 830.904,233.247 837.967,228.04 845.014,233.247 842.275,224.784 849.357,219.453 840.562,219.453 837.967,211.207 "
id="polygon27"
style="fill:#ffcc00;fill-opacity:1"
transform="translate(-542.487,367.64768)" />
<polygon
i:knockout="Off"
points="892.584,229.292 889.936,237.539 881.166,237.539 888.314,242.879 885.537,251.342 892.584,246.125 899.65,251.342 896.9,242.879 903.986,237.539 895.188,237.539 892.584,229.292 "
id="polygon29"
style="fill:#ffcc00;fill-opacity:1"
transform="translate(-542.487,367.64768)" />
<polygon
i:knockout="Off"
points="947.262,211.517 944.613,219.763 935.854,219.763 942.984,225.103 940.221,233.566 947.262,228.349 954.33,233.566 951.584,225.103 958.66,219.763 949.857,219.763 947.262,211.517 "
id="polygon31"
style="fill:#ffcc00;fill-opacity:1"
transform="translate(-542.487,367.64768)" />
<polygon
i:knockout="Off"
points="983.902,173.48 981.246,181.722 972.486,181.722 979.633,187.067 976.854,195.525 983.902,190.313 990.953,195.525 988.217,187.067 995.293,181.722 986.498,181.722 983.902,173.48 "
id="polygon33"
style="fill:#ffcc00;fill-opacity:1"
transform="translate(-542.487,367.64768)" />
<polygon
i:knockout="Off"
points="1001.059,121.021 998.402,129.267 989.625,129.267 996.781,134.607 994,143.062 1001.059,137.854 1008.1,143.062 1005.363,134.607 1012.449,129.267 1003.645,129.267 1001.059,121.021 "
id="polygon35"
style="fill:#ffcc00;fill-opacity:1"
transform="translate(-542.487,367.64768)" />
<polygon
i:knockout="Off"
points="985.684,65.262 983.018,73.517 974.258,73.517 981.404,78.849 978.623,87.312 985.684,82.095 992.732,87.312 989.988,78.849 997.072,73.517 988.277,73.517 985.684,65.262 "
id="polygon37"
style="fill:#ffcc00;fill-opacity:1"
transform="translate(-542.487,367.64768)" />
<polygon
i:knockout="Off"
points="946.322,27.018 943.666,35.259 934.896,35.259 942.035,40.6 939.256,49.054 946.322,43.851 953.363,49.054 950.619,40.6 957.713,35.259 948.908,35.259 946.322,27.018 "
id="polygon39"
style="fill:#ffcc00;fill-opacity:1"
transform="translate(-542.487,367.64768)" />
<path
i:knockout="Off"
clip-rule="evenodd"
d="M 357.036,558.23968 C 333.548,558.23968 313.673,540.80068 306.972,516.75868 L 379.452,516.75868 L 384.456,504.87768 L 304.823,504.87768 C 304.651,502.92868 304.55,500.93168 304.55,498.93468 C 304.55,496.92468 304.652,494.94468 304.823,492.98768 L 389.452,492.98768 L 394.456,481.10668 L 306.972,481.10668 C 313.673,457.06468 333.548,439.63368 357.036,439.63368 C 373.173,439.63368 390.647,447.84868 403.003,460.77968 L 407.696,449.58868 C 393.684,436.06868 374.917,427.65868 357.036,427.65868 C 327.647,427.65868 302.956,450.36768 295.954,481.10568 L 279.511,481.10568 L 274.511,492.98668 L 294.183,492.98668 C 294.029,494.95268 293.966,496.93268 293.966,498.93368 C 293.966,500.93168 294.028,502.91968 294.183,504.87668 L 279.454,504.87668 L 274.458,516.75768 L 295.954,516.75768 C 302.956,547.50468 327.647,570.20468 357.036,570.20468 C 372.995,570.20468 389.647,563.49968 403.02,552.45468 L 403.02,537.13668 L 403.002,537.08768 C 390.648,550.01668 373.173,558.23968 357.036,558.23968"
id="path41"
style="fill:#ffec00;fill-rule:evenodd" />
<path
i:knockout="Off"
d="M 357.036,558.23968 C 333.548,558.23968 313.673,540.80068 306.972,516.75868 L 379.452,516.75868 L 384.456,504.87768 L 304.823,504.87768 C 304.651,502.92868 304.55,500.93168 304.55,498.93468 C 304.55,496.92468 304.652,494.94468 304.823,492.98768 L 389.452,492.98768 L 394.456,481.10668 L 306.972,481.10668 C 313.673,457.06468 333.548,439.63368 357.036,439.63368 C 373.173,439.63368 390.647,447.84868 403.003,460.77968 L 407.696,449.58868 C 393.684,436.06868 374.917,427.65868 357.036,427.65868 C 327.647,427.65868 302.956,450.36768 295.954,481.10568 L 279.511,481.10568 L 274.511,492.98668 L 294.183,492.98668 C 294.029,494.95268 293.966,496.93268 293.966,498.93368 C 293.966,500.93168 294.028,502.91968 294.183,504.87668 L 279.454,504.87668 L 274.458,516.75768 L 295.954,516.75768 C 302.956,547.50468 327.647,570.20468 357.036,570.20468 C 372.995,570.20468 389.647,563.49968 403.02,552.45468 L 403.02,537.13668 L 403.002,537.08768 C 390.648,550.01668 373.173,558.23968 357.036,558.23968 z "
id="path43"
style="fill:#ffcc00;stroke:#ffec00;stroke-width:0.1;fill-opacity:1" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 8.9 KiB

BIN
images/all-to-usd.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

BIN
images/eur-to-all.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

BIN
images/usd-to-all.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

63
src/cache/cache.rs vendored
View File

@ -1,26 +1,19 @@
use std::fs; use std::fs;
use std::io::{BufReader, BufWriter}; use std::io::{BufReader, BufWriter};
use std::path::Path; use std::path::{Path, PathBuf};
use anyhow::Context;
use serde::{Deserialize, Serialize};
use crate::cli::Resolution;
use crate::os::Os;
use super::CacheLine; use super::CacheLine;
use crate::os::Os;
use crate::View;
const FILE_NAME: &'static str = "cache.json"; #[derive(Debug)]
#[derive(Serialize, Deserialize, Debug)]
pub struct Cache { pub struct Cache {
day: Option<CacheLine>, cache_line: Option<CacheLine>,
hist_90: Option<CacheLine>, config_path: PathBuf,
hist_day: Option<CacheLine>,
} }
impl Cache { impl Cache {
pub fn load() -> Option<Self> { pub fn load(view: &View) -> Option<Self> {
let config_opt = Os::get_current()?.get_config_path(); let config_opt = Os::get_current()?.get_config_path();
let mut config_path = match config_opt { let mut config_path = match config_opt {
Ok(k) => k, Ok(k) => k,
@ -33,17 +26,19 @@ impl Cache {
eprintln!("Failed to create config dir: {:?}", e); eprintln!("Failed to create config dir: {:?}", e);
return None; return None;
} }
config_path.push(FILE_NAME); config_path.push(format!("{}.json", view.get_name()));
if !config_path.try_exists().unwrap_or_default() { if !config_path.try_exists().unwrap_or_default() {
return Some(Self { return Some(Self {
day: None, cache_line: None,
hist_90: None, config_path,
hist_day: None,
}); });
} }
match Self::read_config(&config_path) { match Self::read_config(&config_path) {
Ok(k) => Some(k), Ok(cache_line) => Some(Self {
cache_line: Some(cache_line),
config_path,
}),
Err(e) => { Err(e) => {
eprintln!("Config path is invalid, or cannot be created: {:?}", e); eprintln!("Config path is invalid, or cannot be created: {:?}", e);
None None
@ -51,44 +46,28 @@ impl Cache {
} }
} }
pub fn get_cache_line(&self, resolution: Resolution) -> Option<&CacheLine> { pub fn get_cache_line(&self) -> Option<&CacheLine> {
match resolution { self.cache_line.as_ref()
Resolution::TODAY => self.day.as_ref(),
Resolution::HistDays90 => self.hist_90.as_ref(),
Resolution::HistDaysAll => self.hist_day.as_ref(),
}
} }
pub fn set_cache_line(&mut self, resolution: Resolution, cache_line: CacheLine) { pub fn set_cache_line(&mut self, cache_line: CacheLine) {
let cache_line_opt = Some(cache_line); self.cache_line = Some(cache_line);
match resolution {
Resolution::TODAY => self.day = cache_line_opt,
Resolution::HistDays90 => self.hist_90 = cache_line_opt,
Resolution::HistDaysAll => self.hist_day = cache_line_opt,
}
} }
pub fn save(&self) -> anyhow::Result<()> { pub fn save(&self) -> anyhow::Result<()> {
let mut config_path = Os::get_current()
.context("Failed to get config home")?
.get_config_path()?;
fs::create_dir_all(&config_path)?;
config_path.push(FILE_NAME);
let file = fs::File::options() let file = fs::File::options()
.write(true) .write(true)
.create(true) .create(true)
.truncate(true) .truncate(true)
.open(&config_path)?; .open(&self.config_path)?;
let writer = BufWriter::new(file); let writer = BufWriter::new(file);
serde_json::to_writer(writer, self)?; serde_json::to_writer(writer, &self.cache_line)?;
Ok(()) Ok(())
} }
fn read_config(path: &Path) -> anyhow::Result<Self> { fn read_config(path: &Path) -> anyhow::Result<CacheLine> {
let file = fs::File::open(path)?; let file = fs::File::open(path)?;
let reader = BufReader::new(file); let reader = BufReader::new(file);
Ok(serde_json::from_reader(reader)?) Ok(serde_json::from_reader(reader)?)

View File

@ -1,6 +1,6 @@
use clap::{arg, Parser, ValueEnum}; use clap::{arg, Parser, ValueEnum};
use crate::ecb_url; use super::{ShowDays, SortBy};
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[command(author, version, about)] #[command(author, version, about)]
@ -30,7 +30,7 @@ pub struct Cli {
pub force_color: bool, pub force_color: bool,
/// Sort by the currency name (in alphabetical order), or by the rate value (low -> high) /// Sort by the currency name (in alphabetical order), or by the rate value (low -> high)
#[arg(value_enum, long = "sort-by", short = 's', default_value_t = SortBy::Currency)] #[arg(value_enum, long = "sort-by", default_value_t = SortBy::Currency)]
pub sort_by: SortBy, pub sort_by: SortBy,
/// Recalculate to the perspective from an included currency /// Recalculate to the perspective from an included currency
@ -46,42 +46,8 @@ pub struct Cli {
pub max_decimals: u8, pub max_decimals: u8,
/// Amount of data /// Amount of data
#[arg(value_enum, default_value_t = Resolution::TODAY, long="resolution", short='r')] #[arg(default_value_t = ShowDays::Days(1), long="show-days", short='s')]
pub resolution: Resolution, pub show_days: ShowDays,
}
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum SortBy {
Currency,
Rate,
}
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum Resolution {
TODAY,
#[clap(name = "hist-90-days")]
HistDays90,
#[clap(name = "hist-all-days")]
HistDaysAll,
}
impl Resolution {
pub fn to_ecb_url(&self) -> &'static str {
match self {
Resolution::TODAY => ecb_url::TODAY,
Resolution::HistDays90 => ecb_url::hist::DAYS_90,
Resolution::HistDaysAll => ecb_url::hist::DAYS_ALL,
}
}
}
impl SortBy {
pub fn get_comparer(&self) -> fn(&(&str, f64), &(&str, f64)) -> std::cmp::Ordering {
match self {
Self::Currency => |a, b| a.0.cmp(&b.0),
Self::Rate => |a, b| a.1.total_cmp(&b.1),
}
}
} }
#[derive(Debug, Clone, Copy, ValueEnum)] #[derive(Debug, Clone, Copy, ValueEnum)]

7
src/cli/mod.rs Normal file
View File

@ -0,0 +1,7 @@
mod cli_t;
mod since;
mod sort_by;
pub use cli_t::{Cli, FormatOption};
pub use since::ShowDays;
pub use sort_by::SortBy;

54
src/cli/since.rs Normal file
View File

@ -0,0 +1,54 @@
use crate::View;
use std::{fmt, str::FromStr};
#[derive(Debug, Clone, Copy)]
pub enum ShowDays {
Days(usize),
All,
}
impl FromStr for ShowDays {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.eq_ignore_ascii_case("all") {
return Ok(ShowDays::All);
}
s.parse::<usize>().map(ShowDays::Days).map_err(|_| {
format!(
"Invalid value for since: '{}'. Use a positive integer or 'start'.",
s
)
})
}
}
impl fmt::Display for ShowDays {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ShowDays::Days(days) => write!(f, "{}", days),
ShowDays::All => write!(f, "all"),
}
}
}
impl ShowDays {
/// None represents infinity
pub fn to_option(&self) -> Option<usize> {
match self {
ShowDays::Days(d) => Some(*d),
ShowDays::All => None,
}
}
pub fn to_view(&self) -> Option<View> {
match self {
ShowDays::Days(d) => match d {
0 => None,
1 => Some(View::TODAY),
2..=90 => Some(View::HistDays90),
91.. => Some(View::HistDaysAll),
},
ShowDays::All => Some(View::HistDaysAll),
}
}
}

16
src/cli/sort_by.rs Normal file
View File

@ -0,0 +1,16 @@
use clap::ValueEnum;
#[derive(Debug, ValueEnum, Clone)]
pub enum SortBy {
Currency,
Rate,
}
impl SortBy {
pub fn get_comparer(&self) -> fn(&(&str, f64), &(&str, f64)) -> std::cmp::Ordering {
match self {
Self::Currency => |a, b| a.0.cmp(&b.0),
Self::Rate => |a, b| a.1.total_cmp(&b.1),
}
}
}

View File

@ -7,9 +7,11 @@ pub mod os;
pub mod parsing; pub mod parsing;
pub mod table; pub mod table;
pub mod utils_calc; pub mod utils_calc;
mod view;
pub use header_description::HeaderDescription; pub use header_description::HeaderDescription;
pub use holiday::Hollidays; pub use holiday::Hollidays;
pub use view::View;
const APP_NAME: &'static str = "ECB-rates"; const APP_NAME: &'static str = "ECB-rates";
const DEFAULT_WIDTH: usize = 20; const DEFAULT_WIDTH: usize = 20;

View File

@ -25,25 +25,29 @@ async fn main() -> ExitCode {
let mut header_description = HeaderDescription::new(); let mut header_description = HeaderDescription::new();
let use_cache = !cli.no_cache; let use_cache = !cli.no_cache;
let mut cache = if use_cache { Cache::load() } else { None }; let view = match cli.show_days.to_view() {
Some(v) => v,
None => {
eprintln!("It doesn't make any sence to fetch 0 days right?");
return ExitCode::SUCCESS;
}
};
let mut cache = if use_cache { Cache::load(&view) } else { None };
let cache_ok = cache.as_ref().map_or_else( let cache_ok = cache.as_ref().map_or_else(
|| false, || false,
|c| { |c| c.get_cache_line().map_or_else(|| false, |cl| cl.is_valid()),
c.get_cache_line(cli.resolution)
.map_or_else(|| false, |cl| cl.is_valid())
},
); );
let mut parsed = if cache_ok { let mut parsed = if cache_ok {
// These are safe unwraps // These are safe unwraps
cache cache
.as_ref() .as_ref()
.unwrap() .unwrap()
.get_cache_line(cli.resolution) .get_cache_line()
.unwrap() .unwrap()
.exchange_rate_results .exchange_rate_results
.clone() .clone()
} else { } else {
let parsed = match get_and_parse(cli.resolution.to_ecb_url()).await { let parsed = match get_and_parse(view.to_ecb_url()).await {
Ok(k) => k, Ok(k) => k,
Err(e) => { Err(e) => {
eprintln!("Failed to get/parse data from ECB: {}", e); eprintln!("Failed to get/parse data from ECB: {}", e);
@ -56,7 +60,7 @@ async fn main() -> ExitCode {
|| true, || true,
|cache_local| { |cache_local| {
cache_local cache_local
.get_cache_line(cli.resolution) .get_cache_line()
.map_or_else(|| true, |cache_line| cache_line == &parsed) .map_or_else(|| true, |cache_line| cache_line == &parsed)
}, },
); );
@ -64,7 +68,7 @@ async fn main() -> ExitCode {
if not_equal_cache { if not_equal_cache {
if let Some(cache_safe) = cache.as_mut() { if let Some(cache_safe) = cache.as_mut() {
let cache_line = CacheLine::new(parsed.clone()); let cache_line = CacheLine::new(parsed.clone());
cache_safe.set_cache_line(cli.resolution, cache_line); cache_safe.set_cache_line(cache_line);
if let Err(e) = cache_safe.save() { if let Err(e) = cache_safe.save() {
eprintln!("Failed to save to cache with: {:?}", e); eprintln!("Failed to save to cache with: {:?}", e);
} }
@ -101,6 +105,18 @@ async fn main() -> ExitCode {
filter_currencies(&mut parsed, &currencies); filter_currencies(&mut parsed, &currencies);
} }
parsed.reverse();
let parsed = match cli.show_days.to_option() {
Some(n) => {
if parsed.len() <= n {
parsed.as_slice()
} else {
&parsed[0..n]
}
}
None => parsed.as_slice(),
};
let output = match cli.command { let output = match cli.command {
FormatOption::Json => { FormatOption::Json => {
let mut json_values = parsed let mut json_values = parsed

25
src/view.rs Normal file
View File

@ -0,0 +1,25 @@
use crate::ecb_url;
pub enum View {
TODAY,
HistDays90,
HistDaysAll,
}
impl View {
pub fn to_ecb_url(&self) -> &'static str {
match self {
Self::TODAY => ecb_url::TODAY,
Self::HistDays90 => ecb_url::hist::DAYS_90,
Self::HistDaysAll => ecb_url::hist::DAYS_ALL,
}
}
pub fn get_name(&self) -> &'static str {
match self {
Self::TODAY => "today",
Self::HistDays90 => "last-90-days",
Self::HistDaysAll => "all-days",
}
}
}