pace_cli 0.4.5

pace-cli - library to support timetracking on the command line
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
use std::{
    fmt::Display,
    fs::create_dir_all,
    path::{Path, PathBuf},
};

use dialoguer::{
    console::{style, Term},
    theme::ColorfulTheme,
    Confirm,
};
use eyre::Result;
use getset::{Getters, MutGetters};
use tracing::{debug, info};
use typed_builder::TypedBuilder;

use pace_core::{
    constants::PACE_ACTIVITY_LOG_FILENAME,
    constants::PACE_CONFIG_FILENAME,
    prelude::{get_activity_log_paths, get_config_paths, ActivityLog, PaceConfig},
    toml,
};

use crate::{
    prompt::{prompt_activity_log_path, prompt_config_file_path},
    prompt_time_zone, PACE_ART,
};

#[derive(Debug, TypedBuilder, Getters)]
pub struct PathOptions {
    /// Path to the activity log file
    #[getset(get = "pub")]
    activity_log: Option<PathBuf>,
}

/// Final paths for the configuration and activity log files
///
/// This struct is used to store the final paths for the configuration and activity log files
#[derive(Debug, TypedBuilder, Getters, MutGetters)]
pub struct FinalSetupPaths {
    /// The path to the activity log file
    #[builder(default)]
    #[getset(get = "pub")]
    activity_log_path: PathBuf,

    /// The root directory for the activity log file
    #[builder(default)]
    #[getset(get = "pub")]
    activity_log_root: PathBuf,

    /// The path to the configuration file
    #[builder(default, setter(strip_option))]
    #[getset(get = "pub", get_mut = "pub")]
    config_path: Option<PathBuf>,

    /// The root directory for the configuration file
    #[builder(default, setter(strip_option))]
    #[getset(get = "pub", get_mut = "pub")]
    config_root: Option<PathBuf>,
}

impl Display for FinalSetupPaths {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let config_root = self
            .config_root
            .clone()
            .map_or_else(PathBuf::new, |config_root| config_root);

        let config_path = self
            .config_path
            .clone()
            .map_or_else(PathBuf::new, |config_path| config_path);

        writeln!(f, "Configuration root: {:?}", style(config_root).cyan())?;
        writeln!(f, "Configuration: {:?}", style(config_path).cyan())?;
        writeln!(
            f,
            "Activity log root: {:?}",
            style(&self.activity_log_root).cyan()
        )?;
        writeln!(
            f,
            "Activity log: {:?}",
            style(&self.activity_log_path).cyan()
        )
    }
}

/// Asks the user if they know how to set environment variables
/// and provides a guide if they don't
///
/// # Arguments
///
/// * `term` - The terminal to use for the prompt
/// * `config_root` - The root directory for the configuration file
///
/// # Errors
///
/// Returns an error if the prompt fails
///
/// # Returns
///
/// Returns `Ok(())` if the prompt succeeds
pub fn env_knowledge_loop(term: &Term, config_root: &Path) -> Result<()> {
    let env_var_knowledge = Confirm::with_theme(&ColorfulTheme::default())
        .with_prompt("Do you know how to set environment variables?")
        .default(true)
        .interact()?;

    println!();

    'env: loop {
        term.clear_screen()?;

        if env_var_knowledge {
            break 'env;
        }

        println!(
            "To prioritize this configuration, set the `{}` environment variable to '{}'.",
            style("PACE_HOME").bold().red(),
            style(config_root.display()).bold().green()
        );
        println!(
                "You can check out this guide: {}",
                style("https://web.archive.org/web/20240110123209/https://www3.ntu.edu.sg/home/ehchua/programming/howto/Environment_Variables.html")
                    .bold()
                    .blue()
            );

        let ready_to_continue = Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt("Are you ready to continue?")
            .default(false)
            .interact()?;

        if !ready_to_continue {
            break 'env;
        }
    }

    Ok(())
}

/// Writes the configuration to the file system
///
/// # Arguments
///
/// * `config` - The configuration to write
/// * `config_root` - The root directory for the configuration file
/// * `config_path` - The path to the configuration file
///
/// # Errors
///
/// Returns an error if the configuration cannot be written to the file system
///
/// # Returns
///
/// Returns `Ok(())` if the configuration is written successfully
pub fn write_config(
    config: &PaceConfig,
    config_root: &PathBuf,
    config_path: &PathBuf,
) -> Result<()> {
    let config_content = toml::to_string_pretty(&config)?;

    create_dir_all(config_root)?;

    if config_root.exists() {
        // Create a backup before writing the new configuration
        if config_path.exists() {
            info!("A configuration already exists, creating a backup next to the existing one.");
            let backup_path = config_path.with_extension("toml.bak");

            _ = std::fs::copy(config_path, backup_path)?;
        }

        // Write the pace.toml file
        std::fs::write(config_path, config_content.as_bytes())?;

        debug!("Configuration written successfully.");
    }

    Ok(())
}

/// Writes the activity log to the file system
///
/// # Arguments
///
/// * `final_paths` - The final paths for the activity log file
///
/// # Errors
///
/// Returns an error if the activity log cannot be written to the file system
///
/// # Returns
///
/// Returns `Ok(())` if the activity log is written successfully
pub fn write_activity_log(final_paths: &FinalSetupPaths) -> Result<()> {
    let activity_log = ActivityLog::default();

    let activity_log_content = toml::to_string_pretty(&activity_log)?;

    create_dir_all(&final_paths.activity_log_root)?;

    if final_paths.activity_log_root.exists() {
        // Create a backup before writing the new activity log
        if final_paths.activity_log_path.exists() {
            info!("An activity log already exists, creating a backup next to the existing one.");
            let backup_path = &final_paths.activity_log_path.with_extension("toml.bak");

            _ = std::fs::copy(&final_paths.activity_log_path, backup_path)?;
        }

        // Write the activity log file
        std::fs::write(
            &final_paths.activity_log_path,
            activity_log_content.as_bytes(),
        )?;
        debug!("Activity log written successfully.");
    }

    Ok(())
}

/// Prints the introduction to the setup assistant
///
/// # Arguments
///
/// * `term` - The terminal to use for the prompt
///
/// # Errors
///
/// Returns an error if the prompt fails
///
/// # Returns
///
/// Returns `Ok(())` if the prompt succeeds
pub fn print_intro(term: &Term) -> Result<()> {
    // Font name: Font Name: Georgia11
    // Source: https://patorjk.com/software/taag/#p=display&f=Georgia11&t=PACE

    let logo = style(PACE_ART.to_string()).italic().green().bold();

    let assistant_headline = style("Setup Assistant")
        .white()
        .on_black()
        .bold()
        .underlined();

    term.clear_screen()?;

    println!("{logo}");

    println!("{assistant_headline}");

    let intro_text = r"
Keep the pace on your command line. Time tracking and management.

Use this assistant to setup your pace environment and preferences.

- Use UP / Down arrows to choose options
- or Enter for default choice when applicable

Preferences will only be saved if you complete the setup.
Use Q, ESC, or Ctrl-C to exit gracefully at any time.";

    println!("{intro_text}\n");

    let confirmation = Confirm::with_theme(&ColorfulTheme::default())
        .with_prompt("Ready to start?")
        .default(true)
        .interact()?;

    if !confirmation {
        eyre::bail!("Setup exited without changes.");
    }

    Ok(())
}

/// Prompts the user to confirm their choices or break the setup assistant
///
/// # Arguments
///
/// * `prompt` - The prompt to display to the user
///
/// # Errors
///
/// Returns an error if the wants to break the setup assistant or
/// if the prompt fails
///
/// # Returns
///
/// Returns `Ok(())` if the user confirms their choices
pub fn confirmation_or_break(prompt: &str) -> Result<()> {
    let confirmation = Confirm::with_theme(&ColorfulTheme::default())
        .with_prompt(prompt)
        .default(true)
        .interact()?;

    if !confirmation {
        eyre::bail!("Setup exited without changes. No changes were made.");
    }

    Ok(())
}

/// The `setup` commands interior for the pace application
///
/// # Arguments
///
/// * `term` - The terminal to use for the prompt
///
/// # Errors
///
/// Returns an error if the setup assistant fails
///
/// # Returns
///
/// Returns `Ok(())` if the setup assistant succeeds
pub fn setup_config(term: &Term, path_opts: &PathOptions) -> Result<()> {
    let mut config = PaceConfig::default();

    let config_paths = get_config_paths(PACE_CONFIG_FILENAME)
        .into_iter()
        .map(|f| f.to_string_lossy().to_string())
        .collect::<Vec<String>>();

    let mut activity_log_paths = get_activity_log_paths(PACE_ACTIVITY_LOG_FILENAME)
        .into_iter()
        .map(|f| f.to_string_lossy().to_string())
        .collect::<Vec<String>>();

    // Add the custom path from the cli input to the activity log paths
    if let Some(mut custom_path) = path_opts.activity_log().clone() {
        custom_path.push(PACE_ACTIVITY_LOG_FILENAME);
        activity_log_paths.push(custom_path.to_string_lossy().to_string());
    }

    print_intro(term)?;

    term.clear_screen()?;

    let time_zone = prompt_time_zone()?;

    term.clear_screen()?;

    let final_paths = prompt_activity_log_path(&activity_log_paths)?;

    config.set_activity_log_path(final_paths.activity_log_path());
    config.set_time_zone(time_zone);

    let final_paths = prompt_config_file_path(final_paths, config_paths.as_slice())?;

    let prompt = "Do you want the files to be written?";

    confirmation_or_break(prompt)?;

    term.clear_screen()?;

    write_activity_log(&final_paths)?;

    let Some(config_root) = final_paths.config_root() else {
        eyre::bail!("No config root. Setup exited without changes.");
    };

    let Some(config_path) = final_paths.config_path() else {
        eyre::bail!("No config path. Setup exited without changes.");
    };

    write_config(&config, config_root, config_path)?;

    println!(
        "To prioritize this configuration, set the `{}` environment variable to '{}'.",
        style("PACE_HOME").bold().red(),
        style(config_root.display()).bold().green()
    );

    env_knowledge_loop(term, config_root)?;

    term.clear_screen()?;

    println!(
        "{}",
        style("Configuration assistant completed successfully, here are the final paths:").green()
    );

    println!();

    println!(
        "Environment variable: PACE_HOME=\"{}\".",
        style(config_root.display()).cyan()
    );

    println!("{final_paths}");

    println!(
        "For optimal user experience, it's essential to read our Getting Started guide here: {}",
        style("https://pace.cli.rs/docs/getting_started.html")
            .bold()
            .red()
    );

    Ok(())
}