tro 2.12.0

A Trello API client for 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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
use crate::{cli, find};
use clap::ArgMatches;
use colored::*;
use std::error::Error;
use trello::{
    Attachment, Board, Card, ClientConfig, Label, List, Member, Renderable, SearchOptions,
    TrelloClient, search,
};

type Result<T> = std::result::Result<T, Box<dyn Error>>;

pub fn setup_subcommand(matches: &ArgMatches) -> Result<()> {
    debug!("Running setup subcommand with {:?}", matches);

    println!("{}", "Welcome to tro!".green().bold());
    println!();
    println!(
        "Please generate a Developer {} and {} from https://trello.com/app-key/",
        "key".green(),
        "token".green()
    );
    println!("and enter them below");
    println!();

    let key = cli::get_input("Enter Developer API Key: ")?;
    let token = cli::get_input("Enter Token: ")?;

    let config = ClientConfig {
        host: ClientConfig::default_host(),
        key,
        token,
    };

    let client = TrelloClient::new(config);

    println!();

    match Member::me(&client) {
        Ok(member) => {
            client.config.save_config()?;
            println!(
                "Successfully logged in as {} with tro!",
                member.username.green()
            );
        }
        Err(_) => {
            println!(
                "{}",
                "Unable to validate credentials. Please re-check and try again".red()
            );
        }
    };

    Ok(())
}

pub fn me_subcommand(client: &TrelloClient, matches: &ArgMatches) -> Result<()> {
    debug!("Running me subcommand with {:?}", matches);

    let detailed = matches.is_present("detailed");

    let member = Member::me(client)?;

    if detailed {
        println!("username: {}", member.username);
        println!("full name: {}", member.full_name);
        println!("id: {}", member.id);
    } else {
        println!("{}", member.username);
    }

    Ok(())
}

pub fn show_subcommand(client: &TrelloClient, matches: &ArgMatches) -> Result<()> {
    debug!("Running show subcommand with {:?}", matches);

    let label_filter = matches.value_of("label_filter");
    let interactive = matches.is_present("interactive");
    let headers = !matches.is_present("no_headers");

    let params = find::get_trello_params(matches);
    debug!("Trello Params: {:?}", params);

    let result = find::get_trello_object(client, &params)?;
    trace!("result: {:?}", result);

    if interactive {
        if result.card.is_some() {
            eprintln!("Cannot use interactive code if a card pattern is specified");
        } else if let Some(list) = result.list {
            let cards = Card::get_all(client, &list.id)?;

            if let Some(index) = cli::select_trello_object(&cards)? {
                cli::edit_card(client, &cards[index])?;
            }
        } else if let Some(board) = result.board {
            let lists = List::get_all(client, &board.id, true)?;

            if let Some(index) = cli::select_trello_object(&lists)? {
                // TODO: Allow label filtering
                println!("{}", &lists[index].render(headers));
            }
        } else {
            let mut boards = Board::get_all(client)?;

            if let Some(index) = cli::select_trello_object(&boards)? {
                boards[index].retrieve_nested(client)?;
                println!("{}", &boards[index].render(headers));
            }
        }
    } else if let Some(card) = result.card {
        cli::edit_card(client, &card)?;
    } else if let Some(list) = result.list {
        let list = match label_filter {
            Some(label_filter) => list.filter(label_filter),
            None => list,
        };
        println!("{}", list.render(headers));
    } else if let Some(board) = result.board {
        debug!("Board pattern detected");
        let board = match label_filter {
            Some(label_filter) => board.filter(label_filter),
            None => board,
        };
        println!("{}", board.render(headers));
    } else {
        if headers {
            println!("Open Boards");
            println!("===========");
            println!();
        }

        let boards = Board::get_all(client)?;
        for b in boards {
            println!("* {}", b.name);
        }
    }

    Ok(())
}

pub fn move_subcommand(client: &TrelloClient, matches: &ArgMatches) -> Result<()> {
    debug!("Running move subcommand with {:?}", matches);

    let params = find::get_trello_params(matches);
    let result = find::get_trello_object(client, &params)?;

    let new_list_name = matches
        .value_of("new_list_name")
        .ok_or("Missing new list name")?;

    let board = result.board.ok_or("Unable to retrieve board")?;
    let card = result.card.ok_or("Unable to retrieve card")?;
    let list = result
        .list
        .ok_or("Unable to retrieve list. Wildcards are currently unsupported with move")?;

    let board_lists = board.lists.as_ref().ok_or("Missing target board lists")?;

    let new_list = find::get_object_by_name(board_lists, new_list_name, true)?;

    Card::change_list(client, &card.id, &new_list.id)?;

    println!(
        "Moved '{}' from '{}' to '{}'",
        card.name.green(),
        list.name.green(),
        new_list.name.green()
    );

    Ok(())
}

pub fn open_subcommand(client: &TrelloClient, matches: &ArgMatches) -> Result<()> {
    debug!("Running open subcommand with {:?}", matches);

    let id = matches.value_of("id").ok_or("Id not provided")?;
    let object_type = matches.value_of("type").ok_or("type not provided")?;

    if object_type == "board" {
        debug!("Re-opening board with id {}", &id);
        let board = Board::open(client, id)?;

        eprintln!("Opened board: {}", &board.name.green());
        eprintln!("id: {}", &board.id);
    } else if object_type == "list" {
        debug!("Re-opening list with id {}", &id);
        let list = List::open(client, id)?;

        eprintln!("Opened list: {}", &list.name.green());
        eprintln!("id: {}", &list.id);
    } else if object_type == "card" {
        debug!("Re-openning card with id {}", &id);
        let card = Card::open(client, id)?;

        eprintln!("Opened card: {}", &card.name.green());
        eprintln!("id: {}", &card.id);
    } else {
        unreachable!("Unknown object_type '{}' (this is a clap bug)", object_type);
    }

    Ok(())
}

// TODO: The three functions below can be generalised using traits
fn close_board(client: &TrelloClient, board: &mut Board) -> Result<()> {
    board.closed = true;
    Board::update(client, board)?;

    eprintln!("Closed board: '{}'", &board.name.green());
    eprintln!("id: {}", &board.id);

    Ok(())
}

fn close_list(client: &TrelloClient, list: &mut List) -> Result<()> {
    list.closed = true;
    List::update(client, list)?;

    eprintln!("Closed list: '{}'", &list.name.green());
    eprintln!("id: {}", &list.id);

    Ok(())
}

fn close_card(client: &TrelloClient, card: &mut Card) -> Result<()> {
    card.closed = true;
    Card::update(client, card)?;

    eprintln!("Closed card: '{}'", &card.name.green());
    eprintln!("id: {}", &card.id);

    Ok(())
}

pub fn close_subcommand(client: &TrelloClient, matches: &ArgMatches) -> Result<()> {
    debug!("Running close subcommand with {:?}", matches);

    let params = find::get_trello_params(matches);
    let result = find::get_trello_object(client, &params)?;

    let interactive = matches.is_present("interactive");

    trace!("result: {:?}", result);

    if interactive {
        if result.card.is_some() {
            eprintln!("Cannot run interactive mode if you specify a card pattern");
        } else if let Some(list) = result.list {
            let mut cards = Card::get_all(client, &list.id)?;

            for index in cli::multiselect_trello_object(&cards, &[])? {
                close_card(client, &mut cards[index])?;
            }
        } else if let Some(board) = result.board {
            let mut lists = List::get_all(client, &board.id, false)?;

            for index in cli::multiselect_trello_object(&lists, &[])? {
                close_list(client, &mut lists[index])?;
            }
        } else {
            let mut boards = Board::get_all(client)?;

            for index in cli::multiselect_trello_object(&boards, &[])? {
                close_board(client, &mut boards[index])?;
            }
        }
    } else if let Some(mut card) = result.card {
        close_card(client, &mut card)?;
    } else if let Some(mut list) = result.list {
        close_list(client, &mut list)?;
    } else if let Some(mut board) = result.board {
        close_board(client, &mut board)?;
    }

    Ok(())
}

pub fn create_subcommand(client: &TrelloClient, matches: &ArgMatches) -> Result<()> {
    debug!("Running create subcommand with {:?}", matches);

    let params = find::get_trello_params(matches);
    let result = find::get_trello_object(client, &params)?;

    let show = matches.is_present("show");

    trace!("result: {:?}", result);

    if let Some(list) = result.list {
        let labels_to_apply = if let Some(label_names) = matches.values_of("label") {
            let mut target_labels = vec![];
            let labels =
                Label::get_all(client, &result.board.ok_or("Unable to retrieve board")?.id)?;

            for name in label_names {
                match find::get_object_by_name(&labels, name, true) {
                    // TODO: Cloning below is not great. The entire thing feels quite messy
                    Ok(l) => target_labels.push(l.clone()),
                    Err(e) => {
                        eprintln!("{}", e);
                        return Ok(());
                    }
                };
            }
            target_labels
        } else {
            vec![]
        };

        let name = match matches.value_of("name") {
            Some(n) => String::from(n),
            None => cli::get_input("Card name: ")?,
        };

        let card = Card::create(client, &list.id, &Card::new("", &name, "", None, "", None))?;

        for label in labels_to_apply {
            match Label::apply(client, &card.id, &label.id) {
                Ok(_) => eprintln!("Applied {} label", &label.simple_render(),),
                Err(e) => eprintln!("Unable to apply {} label: {}", &label.simple_render(), e),
            };
        }

        if show {
            cli::edit_card(client, &card)?;
        }
    } else if let Some(board) = result.board {
        let name = match matches.value_of("name") {
            Some(n) => String::from(n),
            None => cli::get_input("List name: ")?,
        };

        List::create(client, &board.id, &name)?;
    } else {
        let name = match matches.value_of("name") {
            Some(n) => String::from(n),
            None => cli::get_input("Board name: ")?,
        };

        Board::create(client, &name)?;
    }

    Ok(())
}
pub fn attachments_subcommand(client: &TrelloClient, matches: &ArgMatches) -> Result<()> {
    debug!("Running attachments subcommand with {:?}", matches);

    let params = find::get_trello_params(matches);
    let result = find::get_trello_object(client, &params)?;

    let card = result.card.ok_or("Unable to find card")?;

    let attachments = Attachment::get_all(client, &card.id)?;

    for att in attachments {
        println!("{}", &att.url);
    }

    Ok(())
}

pub fn attach_subcommand(client: &TrelloClient, matches: &ArgMatches) -> Result<()> {
    debug!("Running attach subcommand with {:?}", matches);

    let params = find::get_trello_params(matches);
    let result = find::get_trello_object(client, &params)?;

    let path = matches.value_of("path").ok_or("Missing path argument")?;

    let card = result.card.ok_or("Unable to find card")?;

    let attachment = Attachment::apply(client, &card.id, path)?;

    println!("{}", attachment.render(true));

    Ok(())
}

pub fn url_subcommand(client: &TrelloClient, matches: &ArgMatches) -> Result<()> {
    debug!("Running url subcommand with {:?}", matches);

    let params = find::get_trello_params(matches);
    let result = find::get_trello_object(client, &params)?;

    if let Some(card) = result.card {
        println!("{}", card.url);
    } else if result.list.is_some() {
        // Lists do not have a target url
        // We can display the parent board url instead
        println!("{}", result.board.ok_or("Unable to retrieve board")?.url);
    } else if let Some(board) = result.board {
        println!("{}", board.url);
    }
    Ok(())
}

// Because clap interprets parameters that start with "-" as flags
// we need to provide an alternative way for users to specify the
// "negative" search operator. In this case, we allow for '~' to
// be specified as the negative search operator
fn replace_negative_prefix(query: &str) -> String {
    if query.starts_with('~') {
        query.replacen('~', "-", 1)
    } else {
        query.to_string()
    }
}

pub fn search_subcommand(client: &TrelloClient, matches: &ArgMatches) -> Result<()> {
    debug!("Running search subcommand with {:?}", matches);

    let query = matches
        .values_of("query")
        .ok_or("Missing query value")?
        .map(replace_negative_prefix)
        .collect::<Vec<String>>()
        .join(" ");
    let partial = matches.is_present("partial");
    let interactive = matches.is_present("interactive");

    let cards_limit = if let Some(v) = matches.value_of("limit") {
        Some(v.parse()?)
    } else {
        None
    };

    let params = SearchOptions {
        cards_limit,
        // Seems that 0 cannot be passed
        // so we just pass the lowest accepted value instead
        boards_limit: Some(1),
        partial,
    };

    let results = search(client, &query, &params)?;

    if interactive {
        if let Some(index) = cli::select_trello_object(&results.cards)? {
            cli::edit_card(client, &results.cards[index])?;
        }
    } else if !&results.cards.is_empty() {
        for card in &results.cards {
            println!(
                "{} {}",
                card.simple_render(),
                format!("id: {}", card.id).green()
            );
        }
    }

    Ok(())
}

fn delete_label(client: &TrelloClient, card: &Card, label: &Label) -> Result<()> {
    Label::remove(client, &card.id, &label.id)?;

    eprintln!(
        "Removed {} label from '{}'",
        &label.simple_render(),
        &card.name.green(),
    );

    Ok(())
}

fn apply_label(client: &TrelloClient, card: &Card, label: &Label) -> Result<()> {
    Label::apply(client, &card.id, &label.id)?;

    eprintln!(
        "Applied {} label to '{}'",
        &label.simple_render(),
        &card.name.green()
    );

    Ok(())
}

pub fn label_subcommand(client: &TrelloClient, matches: &ArgMatches) -> Result<()> {
    debug!("Running label subcommand with {:?}", matches);

    let params = find::get_trello_params(matches);
    let result = find::get_trello_object(client, &params)?;

    let interactive = matches.is_present("interactive");
    let delete = matches.is_present("delete");
    let label_names = matches.values_of("label_name");

    let card = result.card.ok_or("Unable to find card")?;
    let card_labels = card.labels.as_ref().ok_or("Unable to get card labels")?;

    if delete {
        let labels = card_labels;
        let label_names = label_names.ok_or("Label names must be specified")?;

        for name in label_names {
            let label = match find::get_object_by_name(labels, name, true) {
                Ok(l) => l,
                Err(e) => {
                    eprintln!("{}", e);
                    continue;
                }
            };

            delete_label(client, &card, label)?;
        }
    } else {
        let board = result.board.ok_or("Unable to retrieve board")?;
        let mut labels = Label::get_all(client, &board.id)?;
        labels.sort_by_cached_key(|l| l.name.clone());

        if interactive {
            let selected_labels = cli::multiselect_trello_object(&labels, card_labels)?
                .into_iter()
                .map(|i| &labels[i])
                .collect::<Vec<&Label>>();

            for label in &selected_labels {
                if !card_labels.contains(label) {
                    apply_label(client, &card, label)?;
                }
            }

            for label in card_labels {
                if !selected_labels.contains(&label) {
                    delete_label(client, &card, label)?;
                }
            }
        } else {
            let label_names = label_names.ok_or("Label names must be specified")?;

            for name in label_names {
                let label = match find::get_object_by_name(&labels, name, true) {
                    Ok(l) => l,
                    Err(e) => {
                        eprintln!(
                            "Label with pattern '{}' not found or is already assigned",
                            name
                        );
                        debug!("{}", e);
                        continue;
                    }
                };

                apply_label(client, &card, label)?;
            }
        }
    }

    Ok(())
}