pace_core 0.19.0

pace-core - 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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! Pace Config

use std::path::{Path, PathBuf};
use std::{fmt::Display, fs};

use chrono_tz::Tz;
use getset::{Getters, MutGetters};
use serde_derive::{Deserialize, Serialize};

use directories::ProjectDirs;
use strum_macros::EnumString;

use crate::{
    domain::{priority::ItemPriorityKind, reflection::ReflectionsFormatKind},
    error::{PaceErrorKind, PaceResult},
};

/// The pace configuration file
///
/// The pace configuration file is a TOML file that contains the configuration for the pace application.
#[derive(Debug, Deserialize, Default, Serialize, Getters, Clone, MutGetters)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "kebab-case")]
#[getset(get = "pub")]
pub struct PaceConfig {
    /// General configuration for the pace application
    #[getset(get = "pub", get_mut = "pub")]
    general: GeneralConfig,

    /// Reflections configuration for the pace application
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[getset(get = "pub", get_mut = "pub")]
    reflections: Option<ReflectionsConfig>,

    /// Export configuration for the pace application
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[getset(get = "pub", get_mut = "pub")]
    export: Option<ExportConfig>,

    /// Database configuration for the pace application
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[getset(get = "pub", get_mut = "pub")]
    database: Option<DatabaseConfig>, // Optional because it's only needed if log_storage is "database"

    /// Pomodoro configuration for the pace application
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[getset(get = "pub", get_mut = "pub")]
    pomodoro: Option<PomodoroConfig>,

    /// Inbox configuration for the pace application
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[getset(get = "pub", get_mut = "pub")]
    inbox: Option<InboxConfig>,

    /// Auto-archival configuration for the pace application
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[getset(get = "pub", get_mut = "pub")]
    auto_archival: Option<AutoArchivalConfig>,
}

impl PaceConfig {
    /// Create a new [`PaceConfig`] with the given path to an activity log file
    ///
    /// # Arguments
    ///
    /// `activity_log` - The path to the activity log file
    pub fn set_activity_log_path(&mut self, activity_log: impl AsRef<Path>) {
        *self.general_mut().activity_log_options_mut().path_mut() =
            activity_log.as_ref().to_path_buf();
    }

    pub fn set_time_zone(&mut self, time_zone: Tz) {
        *self.general_mut().default_time_zone_mut() = Some(time_zone);
    }
}

/// The general configuration for the pace application
#[derive(Debug, Deserialize, Serialize, Getters, MutGetters, Clone)]
#[getset(get = "pub")]
#[serde(rename_all = "kebab-case")]
pub struct GeneralConfig {
    #[serde(flatten)]
    #[getset(get = "pub", get_mut = "pub")]
    activity_log_options: ActivityLogOptions,

    /// The default category separator
    /// Default: `::`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    category_separator: Option<String>,

    /// The default priority
    /// Default: `medium`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    default_priority: Option<ItemPriorityKind>,

    /// The most recent count of activities to show
    /// Default: `9`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    most_recent_count: Option<u8>,

    /// The default time zone
    /// Default: `UTC`
    #[getset(get = "pub", get_mut = "pub", set = "pub")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    default_time_zone: Option<Tz>,
}

#[derive(Debug, Deserialize, Serialize, Getters, MutGetters, Clone, Default)]
#[getset(get = "pub")]
#[serde(rename_all = "kebab-case")]
pub struct ActivityLogOptions {
    /// The path to the activity log file
    /// Default is operating system dependent
    /// Use `pace setup config` to set this value initially
    #[getset(get_mut = "pub")]
    path: PathBuf,

    /// The format for the activity log
    /// Default: `toml`
    #[getset(get_mut = "pub")]
    format_kind: Option<ActivityLogFormatKind>,

    /// The storage type for the activity log
    /// Default: `file`
    storage_kind: ActivityLogStorageKind,
}

/// The kind of activity log format
/// Default: `toml`
///
/// Options: `toml`, `json`, `yaml`
#[derive(Debug, Deserialize, Serialize, Clone, Copy, Default, EnumString)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ActivityLogFormatKind {
    #[default]
    Toml,
}

/// The kind of log storage
/// Default: `file`
///
/// Options: `file`, `database`
#[derive(Debug, Deserialize, Serialize, Clone, Copy, Default)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum ActivityLogStorageKind {
    #[default]
    File,
    Database,
    #[cfg(test)]
    InMemory,
}

impl Default for GeneralConfig {
    fn default() -> Self {
        Self {
            activity_log_options: ActivityLogOptions::default(),
            category_separator: Some("::".to_string()),
            default_priority: Some(ItemPriorityKind::default()),
            most_recent_count: Some(9),
            default_time_zone: Some(Tz::UTC),
        }
    }
}

/// The reflections configuration for the pace application
#[derive(Debug, Deserialize, Default, Serialize, Getters, Clone)]
#[getset(get = "pub")]
#[serde(rename_all = "kebab-case")]
pub struct ReflectionsConfig {
    /// The directory to store the reflections
    directory: PathBuf,

    /// The format for the reflections
    format: ReflectionsFormatKind,
}

/// The export configuration for the pace application
#[derive(Debug, Deserialize, Default, Serialize, Getters, Clone)]
#[getset(get = "pub")]
#[serde(rename_all = "kebab-case")]
pub struct ExportConfig {
    /// If the export should include descriptions
    include_descriptions: bool,

    /// If the export should include tags
    include_tags: bool,

    /// The time format within the export
    time_format: String,
}

/// The kind of database engine
/// Default: `sqlite`
///
/// Options: `sqlite`, `postgres`, `mysql`, `sql-server`
#[derive(Debug, Deserialize, Serialize, Clone, Copy, Default)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum DatabaseEngineKind {
    #[default]
    Sqlite,
    Postgres,
    Mysql,
    SqlServer,
}

/// The database configuration for the pace application
#[derive(Debug, Deserialize, Default, Serialize, Getters, Clone)]
#[getset(get = "pub")]
#[serde(rename_all = "kebab-case")]
pub struct DatabaseConfig {
    /// The connection string for the database
    connection_string: String,

    /// The kind of database engine
    engine: DatabaseEngineKind,
}

/// The pomodoro configuration for the pace application
#[derive(Debug, Deserialize, Serialize, Getters, Clone, Copy)]
#[getset(get = "pub")]
#[serde(rename_all = "kebab-case")]
pub struct PomodoroConfig {
    /// The duration of a short break in minutes
    /// Default: `5`
    break_duration_minutes: u32,

    /// The duration of a long break in minutes
    /// Default: `15`
    long_break_duration_minutes: u32,

    /// The number of work sessions before a long break
    /// Default: `4`
    sessions_before_long_break: u32,

    /// The duration of a work session in minutes
    /// Default: `25`
    work_duration_minutes: u32,
}

impl Default for PomodoroConfig {
    fn default() -> Self {
        Self {
            break_duration_minutes: 5,
            long_break_duration_minutes: 15,
            sessions_before_long_break: 4,
            work_duration_minutes: 25,
        }
    }
}

/// The inbox configuration for the pace application
#[derive(Debug, Deserialize, Default, Serialize, Getters, Clone)]
#[getset(get = "pub")]
#[serde(rename_all = "kebab-case")]
pub struct InboxConfig {
    /// The default time to auto-archive items in the inbox (in days)
    auto_archive_after_days: u32,

    /// The default category for items in the inbox
    default_priority: String,

    /// The maximum items the inbox should hold
    max_size: u32,
}

/// The auto-archival configuration for the pace application
#[derive(Debug, Deserialize, Default, Serialize, Getters, Clone)]
#[getset(get = "pub")]
#[serde(rename_all = "kebab-case")]
pub struct AutoArchivalConfig {
    /// The default auto-archival time after which items should be archived (in days)
    archive_after_days: u32,

    /// The path to the archive file
    archive_path: String,

    /// If auto-archival is enabled
    enabled: bool,
}

/// Get the current directory and then search upwards in the directory hierarchy for a file name
///
/// # Arguments
///
/// * `starting_directory` - The directory to start searching from
/// * `file_name` - The name of the file to search for
///
/// # Returns
///
/// The path to the file if found, otherwise None
pub fn find_root_project_file(
    starting_directory: impl AsRef<Path>,
    file_name: &str,
) -> Option<PathBuf> {
    let mut current_dir = starting_directory.as_ref();

    loop {
        let config_path = current_dir.join(file_name);

        // Check if the config file exists in the current directory
        if fs::metadata(&config_path).is_ok() {
            return Some(config_path);
        }

        // Attempt to move up to the parent directory
        match current_dir.parent() {
            Some(parent) => current_dir = parent,
            None => break, // No more parent directories, stop searching
        }
    }

    None // No config file found
}

/// Find a config file in the current directory and upwards in the directory hierarchy and return the path
///
/// # Arguments
///
/// * `file_name` - The name of the file to search for
///
/// # Errors
///
/// [`PaceErrorKind::ConfigFileNotFound`] - If the current directory value is invalid
/// [`std::io::Error`] - If there is an error accessing the current directory (e.g. insufficient permissions)
/// or the current directory does not exist
///
/// # Returns
///
/// The path to the file if found
#[tracing::instrument(skip(current_dir))]
pub fn find_root_config_file_path(
    current_dir: impl AsRef<Path>,
    file_name: &str,
) -> PaceResult<PathBuf> {
    find_root_project_file(&current_dir, file_name).ok_or_else(|| {
        PaceErrorKind::ConfigFileNotFound {
            current_dir: current_dir.as_ref().to_string_lossy().to_string(),
            file_name: file_name.to_string(),
        }
        .into()
    })
}

/// Get the paths to the activity log file
///
/// # Arguments
///
/// * `filename` - name of the config file
///
/// # Returns
///
/// A vector of [`PathBuf`]s to the activity log files
#[must_use]
#[tracing::instrument]
pub fn get_activity_log_paths(filename: &str) -> Vec<PathBuf> {
    vec![
        ProjectDirs::from("org", "pace-rs", "pace").map(|project_dirs| {
            project_dirs
                .data_local_dir()
                .to_path_buf()
                .join("activities")
        }),
        // Fallback to the current directory
        Some(PathBuf::from(".")),
    ]
    .into_iter()
    .filter_map(|path| path.map(|p| p.join(filename)))
    .collect::<Vec<_>>()
}

/// Get the paths to the config file
///
/// # Arguments
///
/// * `filename` - name of the config file
///
/// # Returns
///
/// A vector of [`PathBuf`]s to the config files
#[must_use]
#[tracing::instrument]
pub fn get_config_paths(filename: &str) -> Vec<PathBuf> {
    #[allow(unused_mut)]
    let mut paths = vec![
        get_home_config_path(),
        ProjectDirs::from("org", "pace-rs", "pace")
            .map(|project_dirs| project_dirs.config_dir().to_path_buf()),
        get_global_config_path(),
        // Fallback to the current directory
        Some(PathBuf::from(".")),
    ];

    #[cfg(target_os = "windows")]
    {
        if let Some(win_compatibility_paths) = get_windows_portability_config_directories() {
            paths.extend(win_compatibility_paths);
        };
    }

    paths
        .into_iter()
        .filter_map(|path| path.map(|p| p.join(filename)))
        .collect::<Vec<_>>()
}

/// Get the path to the home activity log directory.
///
/// # Returns
///
/// The path to the home activity log directory.
/// If the environment variable `PACE_HOME` is not set, `None` is returned.
#[tracing::instrument]
pub fn get_home_activity_log_path() -> Option<PathBuf> {
    std::env::var_os("PACE_HOME").map(|home_dir| PathBuf::from(home_dir).join("activities"))
}

/// Get the path to the home config directory.
///
/// # Returns
///
/// The path to the home config directory.
/// If the environment variable `PACE_HOME` is not set, `None` is returned.
#[tracing::instrument]
pub fn get_home_config_path() -> Option<PathBuf> {
    std::env::var_os("PACE_HOME").map(|home_dir| PathBuf::from(home_dir).join("config"))
}

/// Get the paths to the user profile config directories on Windows.
///
/// # Returns
///
/// A collection of possible paths to the user profile config directory on Windows.
///
/// # Note
///
/// If the environment variable `USERPROFILE` is not set, `None` is returned.
#[tracing::instrument]
#[cfg(target_os = "windows")]
fn get_windows_portability_config_directories() -> Option<Vec<Option<PathBuf>>> {
    std::env::var_os("USERPROFILE").map(|path| {
        vec![
            Some(PathBuf::from(path.clone()).join(r".config\pace")),
            Some(PathBuf::from(path).join(".pace")),
        ]
    })
}

/// Get the path to the global config directory on Windows.
///
/// # Returns
///
/// The path to the global config directory on Windows.
/// If the environment variable `PROGRAMDATA` is not set, `None` is returned.
#[tracing::instrument]
#[cfg(target_os = "windows")]
fn get_global_config_path() -> Option<PathBuf> {
    std::env::var_os("PROGRAMDATA")
        .map(|program_data| PathBuf::from(program_data).join(r"pace\config"))
}

/// Get the path to the global config directory on ios and wasm targets.
///
/// # Returns
///
/// `None` is returned.
#[tracing::instrument]
#[cfg(any(target_os = "ios", target_arch = "wasm32"))]
fn get_global_config_path() -> Option<PathBuf> {
    None
}

/// Get the path to the global config directory on non-Windows,
/// non-iOS, non-wasm targets.
///
/// # Returns
///
/// "/etc/pace" is returned.
#[tracing::instrument]
#[cfg(not(any(target_os = "windows", target_os = "ios", target_arch = "wasm32")))]
fn get_global_config_path() -> Option<PathBuf> {
    Some(PathBuf::from("/etc/pace"))
}

impl Display for PaceConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Ok(config) = toml::to_string_pretty(self) else {
            return write!(f, "Error: Could not serialize config to TOML");
        };

        write!(f, "{config}")
    }
}

#[cfg(test)]
mod tests {

    use crate::error::TestResult;

    use super::*;
    use rstest::*;
    use std::{fs, path::PathBuf};

    #[rstest]
    fn test_parse_pace_config_passes(
        #[files("../../config/pace.toml")] config_path: PathBuf,
    ) -> TestResult<()> {
        let toml_string = fs::read_to_string(config_path)?;
        let _ = toml::from_str::<PaceConfig>(&toml_string)?;

        Ok(())
    }

    #[test]
    fn test_add_activity_log_path_passes() {
        let mut config = PaceConfig::default();
        let activity_log = "activity.log";
        config.set_activity_log_path(activity_log);

        assert_eq!(
            config.general().activity_log_options().path(),
            Path::new(activity_log)
        );
    }

    #[test]
    fn test_pomodoro_default_values_passes() {
        let pomodoro = PomodoroConfig::default();

        assert_eq!(*pomodoro.break_duration_minutes(), 5);
        assert_eq!(*pomodoro.long_break_duration_minutes(), 15);
        assert_eq!(*pomodoro.sessions_before_long_break(), 4);
        assert_eq!(*pomodoro.work_duration_minutes(), 25);
    }
}