thirdshift 0.31.0

Turn a GitHub issue into a ready-for-review pull request, unattended
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
//! Console settings and narrowly scoped, comment-preserving look writes.
use anyhow::{Result, ensure};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

use crate::console::Scope;

pub mod fleet;
pub mod report;
pub mod themes;

pub const THEME_FAMILIES: &[&str] = &["focus", "plain", "press", "signal", "garden", "factory"];
pub const SECTIONS: &[&str] = &[
    "needs-you",
    "ready-for-review",
    "landing",
    "working",
    "done",
    "resolved",
];

pub fn theme_names() -> Vec<String> {
    THEME_FAMILIES
        .iter()
        .flat_map(|family| ["auto", "light", "dark"].map(|mode| format!("{family}-{mode}")))
        .collect()
}

pub fn validate_theme(theme: &str) -> Result<()> {
    themes::Theme::export(theme)
        .map_err(|error| anyhow::anyhow!("unknown or invalid Console Theme {theme}: {error}"))?;
    Ok(())
}

pub fn validate_sections(sections: &[String]) -> Result<()> {
    ensure!(
        sections
            .iter()
            .all(|section| SECTIONS.contains(&section.as_str())),
        "unknown Console section; choose {}",
        SECTIONS.join(", ")
    );
    Ok(())
}

/// The Console settings Setup asks about; other Console settings stay put.
#[derive(Clone)]
pub struct ConsoleAccess {
    pub address: String,
    pub allowed_emails: Vec<String>,
    pub other_accounts: OtherAccounts,
}

#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum OtherAccounts {
    Mode(AccountMode),
    Named(Vec<String>),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AccountMode {
    None,
    Readable,
}

impl Default for OtherAccounts {
    fn default() -> Self {
        Self::Mode(AccountMode::None)
    }
}

impl OtherAccounts {
    pub fn parse(value: &str) -> Result<Self> {
        let setting = match value {
            "none" => Self::default(),
            "readable" => Self::Mode(AccountMode::Readable),
            _ => Self::Named(
                value
                    .split(',')
                    .map(|name| name.trim().to_owned())
                    .collect(),
            ),
        };
        setting.validate()?;
        Ok(setting)
    }

    fn validate(&self) -> Result<()> {
        if let Self::Named(names) = self {
            ensure!(
                names.iter().all(|name| !name.is_empty()
                    && name
                        .bytes()
                        .all(|b| b.is_ascii_alphanumeric() || b"_-.$".contains(&b))),
                "console.other_accounts must be none, readable, or local account names (comma-separated on the CLI)"
            );
        }
        Ok(())
    }

    pub fn value(&self) -> toml_edit::Value {
        match self {
            Self::Mode(AccountMode::None) => "none".into(),
            Self::Mode(AccountMode::Readable) => "readable".into(),
            Self::Named(names) => names.iter().collect::<toml_edit::Array>().into(),
        }
    }
}

impl std::fmt::Display for OtherAccounts {
    fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Mode(AccountMode::None) => out.write_str("none"),
            Self::Mode(AccountMode::Readable) => out.write_str("readable"),
            Self::Named(names) if names.is_empty() => out.write_str("none"),
            Self::Named(names) => out.write_str(&names.join(",")),
        }
    }
}

pub fn other_accounts(value: Option<&str>, json: bool) -> Result<String> {
    let settings = match value {
        Some(value) => edit(None, &[], &[], Some(OtherAccounts::parse(value)?), None)?,
        None => super::UserConfig::load()?.console,
    };
    Ok(if json {
        serde_json::to_string(&settings.other_accounts)?
    } else {
        settings.other_accounts.to_string()
    })
}

#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct ConsoleSettings {
    pub address: String,
    pub port: u16,
    pub allowed_emails: Vec<String>,
    #[serde(skip_serializing)]
    pub address_scopes: BTreeMap<String, Vec<Scope>>,
    pub fleet: Vec<fleet::Entry>,
    pub report: Vec<report::Destination>,
    #[serde(skip_serializing)]
    pub(crate) other_consoles: Vec<String>,
    pub other_accounts: OtherAccounts,
    pub theme: String,
    pub hidden_sections: Vec<String>,
}

impl Default for ConsoleSettings {
    fn default() -> Self {
        Self {
            address: String::new(),
            port: 8711,
            allowed_emails: Vec::new(),
            address_scopes: BTreeMap::new(),
            fleet: Vec::new(),
            report: Vec::new(),
            other_consoles: Vec::new(),
            other_accounts: OtherAccounts::default(),
            theme: "focus-auto".into(),
            hidden_sections: Vec::new(),
        }
    }
}

impl ConsoleSettings {
    pub(crate) fn migrate_fleet(&mut self) -> Result<()> {
        for address in std::mem::take(&mut self.other_consoles) {
            if self.fleet.iter().any(|entry| entry.address == address) {
                continue;
            }
            let url = fleet::link_address(&address)?;
            let host = url.host_str().expect("validated host");
            let mut name = host.to_owned();
            let mut suffix = 2;
            while self.fleet.iter().any(|entry| entry.name == name) {
                name = format!("{host}-{suffix}");
                suffix += 1;
            }
            self.fleet.push(fleet::Entry::link(name, address));
        }
        Ok(())
    }

    pub(crate) fn scopes_for(&self, email: &str) -> Vec<Scope> {
        self.address_scopes
            .get(email)
            .cloned()
            .unwrap_or_else(|| Scope::PERSON.to_vec())
    }

    /// The HTTPS site's DNS name, accepted with or without `https://`.
    pub fn hostname(&self) -> Result<&str> {
        let host = self
            .address
            .strip_prefix("https://")
            .unwrap_or(&self.address);
        let host = host.strip_suffix('/').unwrap_or(host);
        ensure!(
            !host.is_empty()
                && host.len() <= 253
                && host.split('.').all(|label| {
                    !label.is_empty()
                        && label.len() <= 63
                        && !label.starts_with('-')
                        && !label.ends_with('-')
                        && label
                            .bytes()
                            .all(|b| b.is_ascii_alphanumeric() || b == b'-')
                }),
            "console.address must be an HTTPS DNS name, such as https://console.example.com, without a port or path"
        );
        Ok(host)
    }

    pub(crate) fn validate(&self) -> Result<()> {
        self.other_accounts.validate()?;
        if !self.address.is_empty() {
            self.hostname()?;
        }
        let addresses = self
            .allowed_emails
            .iter()
            .map(|email| ("allowed_emails", email))
            .chain(
                self.address_scopes
                    .keys()
                    .map(|email| ("address_scopes", email)),
            );
        for (key, email) in addresses {
            ensure!(
                email.split_once('@').is_some_and(|(local, domain)| {
                    !local.is_empty()
                        && !domain.contains('@')
                        && domain.contains('.')
                        && !domain.starts_with('.')
                        && !domain.ends_with('.')
                }) && !email.chars().any(char::is_whitespace),
                "console.{key}: {email:?} is not an email address"
            );
        }
        for (email, scopes) in &self.address_scopes {
            ensure!(
                !scopes.contains(&Scope::Report),
                "console.address_scopes: {email:?} cannot hold report, a machine token's scope"
            );
        }
        validate_theme(&self.theme)?;
        validate_sections(&self.hidden_sections)?;
        fleet::validate(&self.fleet)?;
        report::validate(&self.report)?;
        Ok(())
    }
}

/// The caller can change only the two look keys. Lock the read/edit/replace
/// across CLI processes and HTTP requests so independent look writes compose.
pub fn write_look(
    theme: Option<&str>,
    hide: &[String],
    show: &[String],
) -> Result<ConsoleSettings> {
    edit(theme, hide, show, None, None)
}

/// CLI-only access change, serialized with all other Console config writes.
pub(crate) fn write_address_scopes(email: &str, scopes: Vec<Scope>) -> Result<ConsoleSettings> {
    edit(None, &[], &[], None, Some((email, scopes)))
}

fn edit(
    theme: Option<&str>,
    hide: &[String],
    show: &[String],
    other_accounts: Option<OtherAccounts>,
    address_scopes: Option<(&str, Vec<Scope>)>,
) -> Result<ConsoleSettings> {
    use toml_edit::{Item, Table, Value};

    if let Some(theme) = theme {
        validate_theme(theme)?;
    }
    validate_sections(hide)?;
    validate_sections(show)?;
    update(|settings, document| {
        if let Some(theme) = theme {
            settings.theme = theme.into();
        }
        settings
            .hidden_sections
            .retain(|section| !show.contains(section));
        for section in hide {
            if !settings.hidden_sections.contains(section) {
                settings.hidden_sections.push(section.clone());
            }
        }
        if !document.contains_key("console") {
            document["console"] = Item::Table(Table::new());
        }
        let mut set = |key: &str, value: Value| {
            let table = document["console"]
                .as_table_like_mut()
                .expect("validated console table");
            if table.contains_key(key) {
                super::set(document, "console", key, value);
            } else {
                table.insert(key, Item::Value(value));
            }
        };
        if theme.is_some() {
            set("theme", settings.theme.clone().into());
        }
        if !hide.is_empty() || !show.is_empty() {
            set(
                "hidden_sections",
                settings
                    .hidden_sections
                    .iter()
                    .collect::<toml_edit::Array>()
                    .into(),
            );
        }
        if let Some(other_accounts) = other_accounts {
            set("other_accounts", other_accounts.value());
            settings.other_accounts = other_accounts;
        }
        if let Some((email, scopes)) = address_scopes {
            ensure!(
                settings
                    .allowed_emails
                    .iter()
                    .any(|allowed| allowed == email),
                "address is not allowed in console.allowed_emails"
            );
            let table = document["console"]
                .as_table_like_mut()
                .expect("validated console table");
            if !table.contains_key("address_scopes") {
                table.insert(
                    "address_scopes",
                    Item::Value(toml_edit::InlineTable::new().into()),
                );
            }
            table
                .get_mut("address_scopes")
                .and_then(Item::as_table_like_mut)
                .expect("validated address scopes table")
                .insert(
                    email,
                    Item::Value(
                        scopes
                            .iter()
                            .map(|scope| scope.name())
                            .collect::<toml_edit::Array>()
                            .into(),
                    ),
                );
            settings.address_scopes.insert(email.to_owned(), scopes);
        }
        Ok(())
    })
}

/// Replace the `[console]` list `key` with `entries`, adding the table if
/// it is missing.
fn write_entries<T: Serialize>(
    document: &mut toml_edit::DocumentMut,
    key: &str,
    entries: &[T],
) -> Result<()> {
    if !document.contains_key("console") {
        document["console"] = toml_edit::Item::Table(toml_edit::Table::new());
    }
    let value: toml_edit::DocumentMut =
        toml::to_string(&BTreeMap::from([(key, entries)]))?.parse()?;
    document["console"]
        .as_table_like_mut()
        .expect("validated console table")
        .insert(key, value[key].clone());
    Ok(())
}

/// Serialize comment-preserving Console writes, including Fleet migration.
fn update(
    change: impl FnOnce(&mut ConsoleSettings, &mut toml_edit::DocumentMut) -> Result<()>,
) -> Result<ConsoleSettings> {
    use std::fs::{self, OpenOptions};
    use std::io::Write;
    let (home, path) = super::home_and_path()?;
    let root = path.parent().expect("User config directory");
    fs::create_dir_all(root)?;
    let lock = OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .open(root.join("config.lock"))?;
    lock.lock()?;
    let text = match fs::read_to_string(&path) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(error) => return Err(error.into()),
    };
    let mut settings = super::UserConfig::parse(&text, &path, &home)?.console;
    let mut document = text.parse()?;
    fleet::migrate_document(&mut document, &settings.fleet);
    change(&mut settings, &mut document)?;
    let rendered = document.to_string();
    if path.exists() {
        super::replace(&path, &rendered)?;
    } else {
        let mut file = tempfile::NamedTempFile::new_in(root)?;
        file.write_all(rendered.as_bytes())?;
        file.persist(&path)?;
    }
    Ok(settings)
}