yandex-tracker-cli 1.1.0

Token-efficient Yandex Tracker CLI for humans and AI agents
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
//! Writing the config file back.
//!
//! `auth login` is the only path that edits configuration, and it edits a file
//! people also write by hand — the docs tell them to. So the edit is surgical:
//! `toml_edit` keeps existing comments, key order and formatting, and only the
//! touched keys change. Serialising the whole struct back would silently delete
//! whatever the user had written around it.

use std::path::Path;

use toml_edit::{DocumentMut, Item, Table, value};

use crate::config::{OrgKind, Profile};

#[derive(Debug, thiserror::Error)]
pub enum StoreError {
    #[error("could not read the configuration file")]
    Read(#[source] std::io::Error),
    #[error("could not write the configuration file")]
    Write(#[source] std::io::Error),
    #[error("the configuration file is not valid TOML; fix or move it first")]
    Parse(#[from] toml_edit::TomlError),
}

/// Add or update an account and, optionally, a profile pointing at it.
///
/// Returns the file's new contents, so a caller can show what changed without
/// reading the file back.
pub fn upsert(
    path: &Path,
    account: &str,
    description: Option<&str>,
    profile: Option<(&str, &Profile)>,
    make_default: bool,
) -> Result<String, StoreError> {
    let existing = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(error) => return Err(StoreError::Read(error)),
    };

    let mut document: DocumentMut = existing.parse()?;

    let accounts = implicit_table(&mut document, "accounts");
    let entry = accounts
        .entry(account)
        .or_insert_with(|| Item::Table(Table::new()));
    if let (Some(table), Some(description)) = (entry.as_table_mut(), description) {
        table["description"] = value(description);
    }

    if let Some((name, profile)) = profile {
        let profiles = implicit_table(&mut document, "profiles");
        let entry = profiles
            .entry(name)
            .or_insert_with(|| Item::Table(Table::new()));
        if let Some(table) = entry.as_table_mut() {
            table["account"] = value(&profile.account);
            table["org_id"] = value(&profile.org_id);
            table["org_kind"] = value(kind_name(profile.org_kind));
            match &profile.default_queue {
                Some(queue) => table["default_queue"] = value(queue),
                None => {
                    table.remove("default_queue");
                }
            }
            // Unlike the keys above, an absent description means "not said"
            // rather than "cleared": login knows the intended queue every time
            // it runs and does not ask about the note unless told to, so
            // rewriting the profile must leave a hand-written one alone.
            // `edit` is how it goes away.
            if let Some(description) = &profile.description {
                table["description"] = value(description);
            }
        }

        // The caller decides whether to become the default; it never happens as
        // a side effect of writing a profile, because which profile is default
        // decides which organisation a bare command touches.
        if make_default {
            document["default_profile"] = value(name);
        }
    }

    let rendered = document.to_string();

    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(StoreError::Write)?;
    }
    write_private(path, &rendered).map_err(StoreError::Write)?;

    Ok(rendered)
}

/// Point `default_profile` at an existing profile.
///
/// Separate from [`upsert`] because changing which organisation a bare command
/// touches is its own decision, not a side effect of writing a profile — and
/// because it must not require a token: switching profiles is a local edit, and
/// asking the keychain for a credential to make one would be theatre.
pub fn set_default(path: &Path, name: &str) -> Result<String, StoreError> {
    let existing = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(error) => return Err(StoreError::Read(error)),
    };

    let mut document: DocumentMut = existing.parse()?;
    document["default_profile"] = value(name);
    let rendered = document.to_string();

    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(StoreError::Write)?;
    }
    write_private(path, &rendered).map_err(StoreError::Write)?;

    Ok(rendered)
}

/// What an edit changes about a profile.
///
/// Two levels of optionality, and they mean different things: the outer
/// `None` is "not mentioned, leave it alone", and `Some(None)` on the fields
/// that have it is "remove this key". A command that edits one thing must not
/// quietly rewrite the rest.
#[derive(Debug, Default)]
pub struct Edits<'a> {
    /// Rename the profile itself.
    pub name: Option<&'a str>,
    pub account: Option<&'a str>,
    pub org_id: Option<&'a str>,
    pub org_kind: Option<OrgKind>,
    pub description: Option<Option<&'a str>>,
    pub default_queue: Option<Option<&'a str>>,
}

impl Edits<'_> {
    /// Nothing to do. The caller refuses rather than rewriting the file for no
    /// reason: a no-op that reports success looks exactly like a change.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.name.is_none()
            && self.account.is_none()
            && self.org_id.is_none()
            && self.org_kind.is_none()
            && self.description.is_none()
            && self.default_queue.is_none()
    }
}

#[derive(Debug, thiserror::Error)]
pub enum EditError {
    #[error("no profile called `{0}` in the configuration file")]
    Unknown(String),
    #[error("a profile called `{0}` already exists; pick another name or remove that one")]
    NameTaken(String),
    #[error(transparent)]
    Store(#[from] StoreError),
}

/// Change an existing profile in place, optionally renaming it.
///
/// Its own function rather than a mode of [`upsert`], and for the same reason
/// [`set_default`] is: editing a profile is a local edit to a file the user
/// owns, and making them log in again — token, verification and all — to fix a
/// typo in an organisation id would be theatre.
///
/// A rename moves the table rather than copying its fields, so `[profiles.x.display]`
/// and anything hand-written inside it travel with it, and `default_profile` is
/// carried across because a default naming a profile that no longer exists
/// breaks every later command.
pub fn edit(path: &Path, profile: &str, edits: &Edits<'_>) -> Result<String, EditError> {
    let existing = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(error) => return Err(StoreError::Read(error).into()),
    };

    let mut document: DocumentMut = existing.parse().map_err(StoreError::from)?;

    let profiles = implicit_table(&mut document, "profiles");
    if !profiles.contains_key(profile) {
        return Err(EditError::Unknown(profile.to_owned()));
    }
    if let Some(taken) = edits
        .name
        .filter(|name| *name != profile && profiles.contains_key(name))
    {
        return Err(EditError::NameTaken(taken.to_owned()));
    }

    let entry = profiles
        .entry(profile)
        .or_insert_with(|| Item::Table(Table::new()));
    if let Some(table) = entry.as_table_mut() {
        if let Some(account) = edits.account {
            table["account"] = value(account);
        }
        if let Some(org_id) = edits.org_id {
            table["org_id"] = value(org_id);
        }
        if let Some(org_kind) = edits.org_kind {
            table["org_kind"] = value(kind_name(org_kind));
        }
        if let Some(description) = edits.description {
            set_or_remove(table, "description", description);
        }
        if let Some(queue) = edits.default_queue {
            set_or_remove(table, "default_queue", queue);
        }
    }

    if let Some(new_name) = edits.name.filter(|name| *name != profile) {
        if let Some(moved) = profiles.remove(profile) {
            profiles.insert(new_name, moved);
        }
        if document.get("default_profile").and_then(Item::as_str) == Some(profile) {
            document["default_profile"] = value(new_name);
        }
    }

    let rendered = document.to_string();

    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(StoreError::Write)?;
    }
    write_private(path, &rendered).map_err(StoreError::Write)?;

    Ok(rendered)
}

fn set_or_remove(table: &mut Table, key: &str, wanted: Option<&str>) {
    match wanted {
        Some(text) => table[key] = value(text),
        None => {
            table.remove(key);
        }
    }
}

fn kind_name(kind: OrgKind) -> &'static str {
    match kind {
        OrgKind::Cloud => "cloud",
        OrgKind::Yandex360 => "yandex360",
    }
}

/// Write with owner-only permissions.
///
/// The file holds no secrets by design, but it does name organisations and
/// accounts, and a config a group can rewrite is a config someone else can point
/// at their own organisation.
fn write_private(path: &Path, contents: &str) -> std::io::Result<()> {
    std::fs::write(path, contents)?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
    }

    Ok(())
}

/// A `[accounts.x]`-style parent table, created without emitting an empty
/// `[accounts]` header of its own.
fn implicit_table<'a>(document: &'a mut DocumentMut, name: &str) -> &'a mut Table {
    let entry = document
        .entry(name)
        .or_insert_with(|| Item::Table(Table::new()));
    if let Some(table) = entry.as_table_mut() {
        table.set_implicit(true);
    }
    entry
        .as_table_mut()
        .unwrap_or_else(|| unreachable!("just inserted a table"))
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::config::Display;

    fn profile() -> Profile {
        Profile {
            account: "work".to_owned(),
            org_id: "12345".to_owned(),
            org_kind: OrgKind::Cloud,
            description: None,
            default_queue: Some("PROJ".to_owned()),
            display: Display::default(),
        }
    }

    /// The config is a file people write by hand, and the docs tell them to.
    /// Switching the default must not cost them their comments.
    #[test]
    fn setting_the_default_keeps_what_was_written_around_it() {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("config.toml");
        std::fs::write(
            &path,
            "# my notes\ndefault_profile = \"work\"\n\n[profiles.home]\naccount = \"me\"\n",
        )
        .expect("write");

        let written = set_default(&path, "home").expect("set default");

        assert!(written.contains("# my notes"));
        assert!(written.contains(r#"default_profile = "home""#));
        assert!(written.contains("[profiles.home]"));
    }

    #[test]
    fn writes_a_file_that_did_not_exist() {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("nested").join("config.toml");

        let written = upsert(
            &path,
            "work",
            Some("main"),
            Some(("work", &profile())),
            true,
        )
        .expect("written");

        assert!(written.contains("[accounts.work]"));
        assert!(written.contains("[profiles.work]"));
        assert!(written.contains(r#"org_kind = "cloud""#));
        assert!(written.contains(r#"default_profile = "work""#));
        assert!(path.exists());
    }

    /// People hand-write this file; the docs tell them to. An edit must not eat
    /// what they wrote around it.
    #[test]
    fn keeps_comments_and_unrelated_entries() {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("config.toml");
        std::fs::write(
            &path,
            r#"# my notes about which org is which
default_profile = "other"

[accounts.personal]
description = "everyday login"

[profiles.other]
account = "personal"
org_id = "98765"
org_kind = "yandex360"
"#,
        )
        .expect("write");

        let written = upsert(
            &path,
            "work",
            Some("admin"),
            Some(("work", &profile())),
            false,
        )
        .expect("written");

        assert!(written.contains("# my notes about which org is which"));
        assert!(written.contains("[accounts.personal]"));
        assert!(written.contains("[profiles.other]"));
        assert!(written.contains("[profiles.work]"));
        // An existing default is not moved unless asked.
        assert!(written.contains(r#"default_profile = "other""#));
    }

    #[test]
    fn updating_an_existing_profile_replaces_its_fields() {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("config.toml");
        upsert(&path, "work", None, Some(("work", &profile())), true).expect("first");

        let mut moved = profile();
        moved.org_id = "999".to_owned();
        moved.org_kind = OrgKind::Yandex360;
        moved.default_queue = None;
        let written = upsert(&path, "work", None, Some(("work", &moved)), false).expect("second");

        assert!(written.contains(r#"org_id = "999""#));
        assert!(written.contains(r#"org_kind = "yandex360""#));
        assert!(!written.contains("default_queue"));
        assert_eq!(written.matches("[profiles.work]").count(), 1);
    }

    /// The note is about the organisation, which has not changed because a
    /// token was renewed. A login that does not mention it must leave it be.
    #[test]
    fn a_login_that_says_nothing_about_the_description_keeps_the_one_on_file() {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("config.toml");
        let mut described = profile();
        described.description = Some("production — customer data".to_owned());
        upsert(&path, "work", None, Some(("work", &described)), true).expect("first");

        let written =
            upsert(&path, "work", None, Some(("work", &profile())), false).expect("second");

        assert!(written.contains(r#"description = "production — customer data""#));
    }

    #[test]
    fn a_description_can_be_set_and_removed_without_touching_anything_else() {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("config.toml");
        std::fs::write(
            &path,
            "# my notes\n\n[profiles.work]\naccount = \"me\"\norg_id = \"12345\"\n",
        )
        .expect("write");

        let written = edit(
            &path,
            "work",
            &Edits {
                description: Some(Some("sandbox")),
                ..Edits::default()
            },
        )
        .expect("set");
        assert!(written.contains(r#"description = "sandbox""#));
        assert!(written.contains("# my notes"));
        assert!(written.contains(r#"org_id = "12345""#));

        let cleared = edit(
            &path,
            "work",
            &Edits {
                description: Some(None),
                ..Edits::default()
            },
        )
        .expect("clear");
        assert!(!cleared.contains("description"));
        assert!(cleared.contains(r#"org_id = "12345""#));
    }

    /// A rename that loses the display settings, or leaves `default_profile`
    /// pointing at a name that no longer exists, is worse than no rename.
    #[test]
    fn renaming_moves_the_whole_profile_and_the_default_with_it() {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("config.toml");
        std::fs::write(
            &path,
            r#"default_profile = "work"

[profiles.work]
account = "me"
org_id = "12345"
org_kind = "cloud"

[profiles.work.display]
limit = 5
"#,
        )
        .expect("write");

        let written = edit(
            &path,
            "work",
            &Edits {
                name: Some("prod"),
                description: Some(Some("production")),
                ..Edits::default()
            },
        )
        .expect("renamed");

        assert!(written.contains("[profiles.prod]"));
        assert!(written.contains("[profiles.prod.display]"));
        assert!(written.contains("limit = 5"));
        assert!(written.contains(r#"default_profile = "prod""#));
        assert!(written.contains(r#"description = "production""#));
        assert!(!written.contains("[profiles.work]"));
    }

    /// Renaming onto a name in use would merge two organisations into one
    /// profile, silently. It is refused instead.
    #[test]
    fn renaming_onto_an_existing_profile_is_refused() {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("config.toml");
        std::fs::write(
            &path,
            "[profiles.work]\naccount = \"me\"\n\n[profiles.home]\naccount = \"me\"\n",
        )
        .expect("write");

        let error = edit(
            &path,
            "work",
            &Edits {
                name: Some("home"),
                ..Edits::default()
            },
        )
        .expect_err("refused");

        assert!(matches!(error, EditError::NameTaken(name) if name == "home"));
        let still = std::fs::read_to_string(&path).expect("readable");
        assert!(still.contains("[profiles.work]"));
    }

    #[test]
    fn editing_a_profile_that_does_not_exist_says_so() {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[profiles.work]\naccount = \"me\"\n").expect("write");

        let error = edit(
            &path,
            "nope",
            &Edits {
                org_id: Some("1"),
                ..Edits::default()
            },
        )
        .expect_err("refused");

        assert!(matches!(error, EditError::Unknown(name) if name == "nope"));
    }

    #[test]
    fn a_broken_file_is_reported_rather_than_overwritten() {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "this is not [[[ toml").expect("write");

        assert!(upsert(&path, "work", None, None, false).is_err());
        assert_eq!(
            std::fs::read_to_string(&path).expect("still there"),
            "this is not [[[ toml"
        );
    }
}