leo_lang/cli/helpers/
updater.rs

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
// Copyright (C) 2019-2025 Provable Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.

use leo_errors::{CliError, Result};

use aleo_std;

use colored::Colorize;
use self_update::{Status, backends::github, version::bump_is_greater};
use std::{
    fmt::Write as _,
    fs,
    path::{Path, PathBuf},
    time::{Duration, SystemTime, UNIX_EPOCH},
};

pub struct Updater;

// TODO Add logic for users to easily select release versions.
impl Updater {
    const LEO_BIN_NAME: &'static str = "leo";
    const LEO_CACHE_LAST_CHECK_FILE: &'static str = "leo_cache_last_update_check";
    const LEO_CACHE_VERSION_FILE: &'static str = "leo_cache_latest_version";
    const LEO_REPO_NAME: &'static str = "leo";
    const LEO_REPO_OWNER: &'static str = "AleoHQ";
    // 24 hours
    const LEO_UPDATE_CHECK_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);

    /// Show all available releases for `leo`.
    pub fn show_available_releases() -> Result<String> {
        let releases = github::ReleaseList::configure()
            .repo_owner(Self::LEO_REPO_OWNER)
            .repo_name(Self::LEO_REPO_NAME)
            .build()
            .map_err(CliError::self_update_error)?
            .fetch()
            .map_err(CliError::could_not_fetch_versions)?;

        let mut output = "\nList of available versions\n".to_string();
        for release in releases {
            let _ = writeln!(output, "  * {}", release.version);
        }

        Ok(output)
    }

    /// Update `leo` to the latest release.
    pub fn update_to_latest_release(show_output: bool) -> Result<Status> {
        let status = github::Update::configure()
            .repo_owner(Self::LEO_REPO_OWNER)
            .repo_name(Self::LEO_REPO_NAME)
            .bin_name(Self::LEO_BIN_NAME)
            .current_version(env!("CARGO_PKG_VERSION"))
            .show_download_progress(show_output)
            .no_confirm(true)
            .show_output(show_output)
            .build()
            .map_err(CliError::self_update_build_error)?
            .update()
            .map_err(CliError::self_update_error)?;

        Ok(status)
    }

    /// Check if there is an available update for `leo` and return the newest release.
    pub fn update_available() -> Result<String> {
        let updater = github::Update::configure()
            .repo_owner(Self::LEO_REPO_OWNER)
            .repo_name(Self::LEO_REPO_NAME)
            .bin_name(Self::LEO_BIN_NAME)
            .current_version(env!("CARGO_PKG_VERSION"))
            .build()
            .map_err(CliError::self_update_error)?;

        let current_version = updater.current_version();
        let latest_release = updater.get_latest_release().map_err(CliError::self_update_error)?;

        if bump_is_greater(&current_version, &latest_release.version).map_err(CliError::self_update_error)? {
            Ok(latest_release.version)
        } else {
            Err(CliError::old_release_version(current_version, latest_release.version).into())
        }
    }

    /// Read the latest version from the version file.
    pub fn read_latest_version() -> Result<Option<String>, CliError> {
        let version_file_path = Self::get_version_file_path();
        match fs::read_to_string(version_file_path) {
            Ok(version) => Ok(Some(version.trim().to_string())),
            Err(_) => Ok(None),
        }
    }

    /// Generate the CLI message if a new version is available.
    pub fn get_cli_string() -> Result<Option<String>, CliError> {
        if let Some(latest_version) = Self::read_latest_version()? {
            let colorized_message = format!(
                "\n🟢 {} {} {}",
                "A new version is available! Run".bold().green(),
                "`leo update`".bold().white(),
                format!("to update to v{}.", latest_version).bold().green()
            );
            Ok(Some(colorized_message))
        } else {
            Ok(None)
        }
    }

    /// Display the CLI message if a new version is available.
    pub fn print_cli() -> Result<(), CliError> {
        if let Some(message) = Self::get_cli_string()? {
            println!("{}", message);
        }
        Ok(())
    }

    /// Check for updates, respecting the update interval. (Currently once per day.)
    /// If a new version is found, write it to a cache file and alert in every call.
    pub fn check_for_updates(force: bool) -> Result<bool, CliError> {
        // Get the cache directory and relevant file paths.
        let cache_dir = Self::get_cache_dir();
        let last_check_file = cache_dir.join(Self::LEO_CACHE_LAST_CHECK_FILE);
        let version_file = Self::get_version_file_path();

        // Determine if we should check for updates.
        let should_check = force || Self::should_check_for_updates(&last_check_file)?;

        if should_check {
            match Self::update_available() {
                Ok(latest_version) => {
                    // A new version is available
                    Self::update_check_files(&cache_dir, &last_check_file, &version_file, &latest_version)?;
                    Ok(true)
                }
                Err(_) => {
                    // No new version available or error occurred
                    // We'll treat both cases as "no update" for simplicity
                    Self::update_check_files(&cache_dir, &last_check_file, &version_file, env!("CARGO_PKG_VERSION"))?;
                    Ok(false)
                }
            }
        } else if version_file.exists() {
            if let Ok(stored_version) = fs::read_to_string(&version_file) {
                let current_version = env!("CARGO_PKG_VERSION");
                Ok(bump_is_greater(current_version, stored_version.trim()).map_err(CliError::self_update_error)?)
            } else {
                // If we can't read the file, assume no update is available
                Ok(false)
            }
        } else {
            Ok(false)
        }
    }

    /// Updates the check files with the latest version information and timestamp.
    ///
    /// This function creates the cache directory if it doesn't exist, writes the current time
    /// to the last check file, and writes the latest version to the version file.
    fn update_check_files(
        cache_dir: &Path,
        last_check_file: &Path,
        version_file: &Path,
        latest_version: &str,
    ) -> Result<(), CliError> {
        // Recursively create the cache directory and all of its parent components if they are missing.
        fs::create_dir_all(cache_dir).map_err(CliError::cli_io_error)?;

        // Get the current time.
        let current_time = Self::get_current_time()?;

        // Write the current time to the last check file.
        fs::write(last_check_file, current_time.to_string()).map_err(CliError::cli_io_error)?;

        // Write the latest version to the version file.
        fs::write(version_file, latest_version).map_err(CliError::cli_io_error)?;

        Ok(())
    }

    /// Determines if an update check should be performed based on the last check time.
    ///
    /// This function reads the last check timestamp from a file and compares it with
    /// the current time to decide if enough time has passed for a new check.
    fn should_check_for_updates(last_check_file: &Path) -> Result<bool, CliError> {
        match fs::read_to_string(last_check_file) {
            Ok(contents) => {
                // Parse the last check timestamp from the file.
                let last_check = contents
                    .parse::<u64>()
                    .map_err(|e| CliError::cli_runtime_error(format!("Failed to parse last check time: {}", e)))?;

                // Get the current time.
                let current_time = Self::get_current_time()?;

                // Check if enough time has passed since the last check.
                Ok(current_time.saturating_sub(last_check) > Self::LEO_UPDATE_CHECK_INTERVAL.as_secs())
            }
            // If we can't read the file, assume we should check
            Err(_) => Ok(true),
        }
    }

    /// Gets the current system time as seconds since the Unix epoch.
    fn get_current_time() -> Result<u64, CliError> {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|e| CliError::cli_runtime_error(format!("System time error: {}", e)))
            .map(|duration| duration.as_secs())
    }

    /// Get the path to the file storing the latest version information.
    fn get_version_file_path() -> PathBuf {
        Self::get_cache_dir().join(Self::LEO_CACHE_VERSION_FILE)
    }

    /// Get the cache directory for Leo.
    fn get_cache_dir() -> PathBuf {
        aleo_std::aleo_dir().join("leo")
    }
}