corretto/
lib.rs

1#![deny(missing_docs)]
2#![doc = include_str!("../README.md")]
3
4mod cpu_arch;
5mod ext;
6mod jdk_desc;
7mod os;
8mod version_info;
9
10use std::{
11    fmt::Display,
12    io::Write,
13    path::{Path, PathBuf},
14};
15
16pub use cpu_arch::CpuArch;
17pub use ext::Ext;
18pub use jdk_desc::JdkDesc;
19pub use os::Os;
20use serde::{Deserialize, Serialize};
21pub use version_info::VersionInfo;
22
23/// An error that can occur while downloading a JDK.
24#[derive(Debug, thiserror::Error)]
25pub enum DownloadError {
26    /// An IO error.
27    #[error("IO error: {0}")]
28    Io(#[from] std::io::Error),
29    /// A [reqwest] error.
30    #[error("Reqwest error: {0}")]
31    Reqwest(#[from] reqwest::Error),
32}
33
34/// Options for downloading a JDK.
35pub struct DownloadOpts {
36    /// Whether to create the directory (and all parent directories) in which the JDK is downloaded.
37    pub create_dir: bool,
38}
39
40impl Default for DownloadOpts {
41    fn default() -> Self {
42        Self { create_dir: true }
43    }
44}
45
46/// A newtype wrapper around a version of Corretto distribution of Open Java Development Kit ([OpenJDK]).
47///
48/// [OpenJDK]: https://en.wikipedia.org/wiki/OpenJDK
49#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord, Serialize, Deserialize)]
50#[serde(transparent)]
51pub struct Version(u8);
52
53impl Display for Version {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        write!(f, "{}", self.0)
56    }
57}
58
59/// A URL from which a JDK can be downloaded.
60pub struct DownloadURL(String);
61
62impl DownloadURL {
63    /// Downloads the JDK from the URL to the specified directory. Returns the path to the downloaded file.
64    pub async fn download(
65        &self,
66        dir_path: impl AsRef<Path>,
67        opts: DownloadOpts,
68    ) -> Result<PathBuf, DownloadError> {
69        let DownloadOpts { create_dir } = opts;
70
71        let DownloadURL(url) = self;
72        let filename = url
73            .strip_prefix("https://corretto.aws/downloads/latest/")
74            .unwrap();
75        let response = reqwest::get(url).await?;
76        let path = dir_path.as_ref().join(filename);
77        if create_dir {
78            std::fs::create_dir_all(&dir_path)?;
79        }
80        let mut file = std::fs::File::create(&path)?;
81        let bytes = response.bytes().await?;
82        file.write_all(&bytes)?;
83        Ok(path)
84    }
85
86    /// Downloads the JDK from the URL to a temporary directory. Returns the path to the downloaded file.
87    pub async fn download_tmp(&self) -> Result<PathBuf, DownloadError> {
88        let dir = tempfile::tempdir()?;
89        self.download(dir.path(), DownloadOpts { create_dir: false })
90            .await
91    }
92}