kasl-cli 1.10.0

Work activity tracker CLI: automatic workday and break detection, task management with Jira/GitLab integration, productivity reports and exports
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
//! Task template management command.
//!
//! Provides comprehensive template management functionality for kasl, enabling users to create, edit, delete, and search reusable task templates.
//!
//! ## Usage
//!
//! ```bash
//! # List all templates
//! kasl template list
//!
//! # Create new template
//! kasl template add --name "bug-fix"
//!
//! # Search templates
//! kasl template search "development"
//!
//! # Delete template
//! kasl template remove "old-template"
//! ```

use crate::{
    db::templates::{TaskTemplate, Templates},
    libs::{
        messages::Message,
        pick,
        prompt::{ensure_interactive, is_interactive},
        view::View,
    },
    msg_error, msg_info, msg_print, msg_success,
};
use anyhow::Result;
use clap::{Args, Subcommand};
use dialoguer::{Confirm, Input, Select, theme::ColorfulTheme};

/// Command-line arguments for template management operations.
#[derive(Debug, Args)]
pub struct TemplateArgs {
    #[command(subcommand)]
    command: Option<TemplateCommand>,
}

/// Available template management operations.
#[derive(Debug, Subcommand)]
enum TemplateCommand {
    /// Add a new task template
    ///
    /// Creates a new reusable template with specified or interactive values.
    /// Templates provide default values for task creation, streamlining
    /// workflows for frequently created task types.
    Add {
        /// Unique name identifier for the template
        ///
        /// Must be unique across all templates and should be descriptive
        /// enough to easily identify the template's purpose. Used for
        /// referencing the template in task creation commands.
        #[arg(short, long)]
        name: Option<String>,

        /// Task name the template fills in
        ///
        /// Supplying it - along with `--name` - is what makes template
        /// creation scriptable; the remaining fields fall back to an empty
        /// comment and 100% completeness.
        #[arg(short = 't', long)]
        task_name: Option<String>,

        /// Comment the template fills in
        #[arg(long)]
        comment: Option<String>,

        /// Default completion percentage (0-100)
        #[arg(short, long)]
        completeness: Option<i32>,
    },

    /// List all available templates
    ///
    /// Displays a formatted table of all existing templates with their
    /// names, task names, comments, and default completion values.
    /// Useful for reviewing available templates and their configurations.
    List,

    /// Show a single template's contents
    ///
    /// Displays the task name, comment and default completeness stored in
    /// the template, so its effect on task creation is visible before use.
    Show {
        /// Name of the template to show
        name: Option<String>,
    },

    /// Edit an existing template
    ///
    /// Modifies an existing template's properties including task name,
    /// comment, and completion status. Provides interactive interface
    /// for template selection if name is not specified.
    Edit {
        /// Name of the template to edit
        ///
        /// If not provided, an interactive selection interface will be
        /// presented with all available templates.
        name: Option<String>,
    },

    /// Remove a template
    ///
    /// Permanently removes a template from the system. Includes confirmation
    /// prompt to prevent accidental removal. Removing a template does not
    /// affect tasks that were previously created from it.
    Remove {
        /// Name of the template to remove
        ///
        /// If not provided, an interactive selection interface will be
        /// presented with all available templates.
        name: Option<String>,

        /// Remove without asking for confirmation
        #[arg(long, short = 'y')]
        yes: bool,
    },

    /// Search templates by name or content
    ///
    /// Performs a text search across template names and task names,
    /// returning all matching templates. Useful for finding templates
    /// in large template libraries.
    Search {
        /// Search query string
        ///
        /// Searches both template names and task names for matches.
        /// Case-insensitive partial matching is supported.
        query: String,
    },
}

/// Executes template management operations based on the specified subcommand.
///
/// # Examples
///
/// ```bash
/// # Create a new template interactively
/// kasl template add
///
/// # Create template with specific name
/// kasl template add --name daily-standup
///
/// # List all templates
/// kasl template list
///
/// # Edit a template
/// kasl template edit daily-standup
///
/// # Search for templates
/// kasl template search meeting
///
/// # Interactive mode
/// kasl template
/// ```
pub fn cmd(args: TemplateArgs) -> Result<()> {
    match args.command {
        Some(TemplateCommand::Add {
            name,
            task_name,
            comment,
            completeness,
        }) => handle_create(name, task_name, comment, completeness),
        Some(TemplateCommand::List) => handle_list(),
        Some(TemplateCommand::Show { name }) => handle_show(name),
        Some(TemplateCommand::Edit { name }) => handle_edit(name),
        Some(TemplateCommand::Remove { name, yes }) => handle_delete(name, yes),
        Some(TemplateCommand::Search { query }) => handle_search(query),
        None => {
            ensure_interactive("no subcommand given; run `kasl template list` or see `kasl template --help`")?;
            handle_interactive()
        }
    }
}

/// Handles template creation with validation and uniqueness checking.
///
/// Every field has a flag, so a template can be created from a script; what is
/// left out is asked for in a terminal and defaulted outside one. The name is
/// the exception - without it there is nothing to ask for outside a terminal,
/// so the command refuses instead of prompting into a void.
fn handle_create(name: Option<String>, task_name: Option<String>, comment: Option<String>, completeness: Option<i32>) -> Result<()> {
    let mut templates_db = Templates::new()?;

    if name.is_none() {
        ensure_interactive("template name is required; pass --name outside an interactive terminal")?;
    }

    let name = match name {
        Some(n) => n,
        None => Input::with_theme(&ColorfulTheme::default())
            .with_prompt(Message::PromptTemplateName.to_string())
            .interact_text()?,
    };

    // Validate template name uniqueness
    if templates_db.exists(&name)? {
        msg_error!(Message::TemplateAlreadyExists(name));
        return Ok(());
    }

    let interactive = is_interactive();

    let task_name = match task_name {
        Some(t) => t,
        // A template whose task name is the template name is still usable, and
        // beats refusing the whole command over a field that has a sane guess.
        None if !interactive => name.clone(),
        None => Input::with_theme(&ColorfulTheme::default())
            .with_prompt(Message::PromptTemplateTaskName.to_string())
            .interact_text()?,
    };

    let comment = match comment {
        Some(c) => c,
        None if !interactive => String::new(),
        None => Input::with_theme(&ColorfulTheme::default())
            .with_prompt(Message::PromptTemplateComment.to_string())
            .allow_empty(true)
            .interact_text()?,
    };

    let completeness_range_msg = Message::TaskCompletenessRange.to_string();
    let completeness = match completeness {
        Some(c) => {
            if !(0..=100).contains(&c) {
                msg_error!(Message::TaskCompletenessRange);
                return Ok(());
            }
            c
        }
        None if !interactive => 100,
        None => Input::with_theme(&ColorfulTheme::default())
            .with_prompt(Message::PromptTemplateCompleteness.to_string())
            .default(100)
            .validate_with(|input: &i32| -> Result<(), &str> {
                if *input >= 0 && *input <= 100 { Ok(()) } else { Err(&completeness_range_msg) }
            })
            .interact_text()?,
    };

    // Create and save the template
    let template = TaskTemplate::new(name.clone(), task_name, comment, completeness);
    templates_db.create(&template)?;

    msg_success!(Message::TemplateCreated(name));
    Ok(())
}

/// Displays all available templates in a formatted table.
fn handle_list() -> Result<()> {
    let mut templates_db = Templates::new()?;
    let templates = templates_db.get_all()?;

    if templates.is_empty() {
        msg_info!(Message::NoTemplatesFound);
        return Ok(());
    }

    msg_print!(Message::TemplateListHeader, true);
    View::templates(&templates)?;
    Ok(())
}

/// Displays a single template's stored values.
///
/// Reuses the same table rendering as `list` so a template reads identically
/// whether shown alone or among others. Without a name, the template is picked
/// interactively.
fn handle_show(name: Option<String>) -> Result<()> {
    let mut templates_db = Templates::new()?;

    let name = match name {
        Some(n) => n,
        None => {
            ensure_interactive("template name is required outside an interactive terminal")?;

            let templates = templates_db.get_all()?;
            if templates.is_empty() {
                msg_info!(Message::NoTemplatesFound);
                return Ok(());
            }

            pick::template(&templates, &Message::SelectTemplate.to_string())?
        }
    };

    match templates_db.get(&name)? {
        Some(template) => {
            msg_print!(Message::TemplateListHeader, true);
            View::templates(&[template])?;
        }
        None => msg_error!(Message::TemplateNotFound(name)),
    }

    Ok(())
}

/// Handles template editing with interactive or direct name specification.
fn handle_edit(name: Option<String>) -> Result<()> {
    let mut templates_db = Templates::new()?;

    // Get template name (direct or interactive selection)
    let name = match name {
        Some(n) => n,
        None => {
            let templates = templates_db.get_all()?;
            if templates.is_empty() {
                msg_info!(Message::NoTemplatesFound);
                return Ok(());
            }

            pick::template(&templates, &Message::SelectTemplateToEdit.to_string())?
        }
    };

    // Fetch the template to edit
    let template = match templates_db.get(&name)? {
        Some(t) => t,
        None => {
            msg_error!(Message::TemplateNotFound(name));
            return Ok(());
        }
    };

    msg_print!(Message::EditingTemplate(template.name.clone()), true);

    // Interactive editing with current values as defaults
    let task_name = Input::with_theme(&ColorfulTheme::default())
        .with_prompt(Message::PromptTemplateTaskName.to_string())
        .default(template.task_name.clone())
        .interact_text()?;

    let comment = Input::with_theme(&ColorfulTheme::default())
        .with_prompt(Message::PromptTemplateComment.to_string())
        .default(template.comment.clone())
        .allow_empty(true)
        .interact_text()?;

    let completeness_range_msg = Message::TaskCompletenessRange.to_string();
    let completeness = Input::with_theme(&ColorfulTheme::default())
        .with_prompt(Message::PromptTemplateCompleteness.to_string())
        .default(template.completeness)
        .validate_with(|input: &i32| -> Result<(), &str> {
            if *input >= 0 && *input <= 100 { Ok(()) } else { Err(&completeness_range_msg) }
        })
        .interact_text()?;

    // Update the template
    let updated_template = TaskTemplate::new(name.clone(), task_name, comment, completeness);
    templates_db.update(&updated_template)?;

    msg_success!(Message::TemplateUpdated(name));
    Ok(())
}

/// Handles safe template deletion with confirmation.
fn handle_delete(name: Option<String>, assume_yes: bool) -> Result<()> {
    let mut templates_db = Templates::new()?;

    // Get template name (direct or interactive selection)
    let name = match name {
        Some(n) => n,
        None => {
            ensure_interactive("template name is required outside an interactive terminal")?;

            let templates = templates_db.get_all()?;
            if templates.is_empty() {
                msg_info!(Message::NoTemplatesFound);
                return Ok(());
            }

            pick::template(&templates, &Message::SelectTemplateToDelete.to_string())?
        }
    };

    if !assume_yes {
        // Never block on a prompt when there is no one to answer it.
        ensure_interactive(&format!("refusing to remove template '{}' without --yes outside an interactive terminal", name))?;

        let confirmed = Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt(Message::ConfirmDeleteTemplate(name.clone()).to_string())
            .default(false)
            .interact()?;

        if !confirmed {
            msg_info!(Message::OperationCancelled);
            return Ok(());
        }
    }

    templates_db.delete(&name)?;
    msg_success!(Message::TemplateDeleted(name));

    Ok(())
}

/// Handles template search functionality.
fn handle_search(query: String) -> Result<()> {
    let mut templates_db = Templates::new()?;
    let templates = templates_db.search(&query)?;

    if templates.is_empty() {
        msg_info!(Message::NoTemplatesMatchingQuery(query));
        return Ok(());
    }

    msg_print!(Message::TemplateSearchResults(query), true);
    View::templates(&templates)?;
    Ok(())
}

/// Handles interactive template management when no subcommand is provided.
fn handle_interactive() -> Result<()> {
    let options = vec!["Add new template", "List templates", "Show template", "Edit template", "Remove template"];

    let selection = Select::with_theme(&ColorfulTheme::default())
        .with_prompt(Message::SelectTemplateAction.to_string())
        .items(&options)
        .interact()?;

    match selection {
        0 => handle_create(None, None, None, None),
        1 => handle_list(),
        2 => handle_show(None),
        3 => handle_edit(None),
        4 => handle_delete(None, false),
        _ => Ok(()),
    }
}