toha 0.4.0

Generate projects and files from templates through one interview for people, scripts, agents, and Rust callers.
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
552
553
554
555
556
557
558
559
560
561
562
//! Template addresses and immutable Git fetches.
use base64::Engine;
use gix::bstr::ByteSlice;
use indexmap::IndexMap;
use std::{
    io::Write,
    path::{Path, PathBuf},
    sync::atomic::AtomicBool,
};
mod credentials;
pub(crate) use credentials::Supplied;
pub use credentials::{
    Credential, CredentialRequest, CredentialResolver, with_credential_resolver,
};
pub type Hosts = IndexMap<String, String>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Address {
    Git {
        repo: String,
        reference: Option<String>,
        path: Option<String>,
    },
    Folder(PathBuf),
    Name(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefKind {
    Branch,
    Tag,
    Commit,
    DefaultBranch,
}
#[derive(Debug, Clone)]
pub struct Fetched {
    pub commit: String,
    pub reference_kind: RefKind,
}
#[derive(Debug, thiserror::Error)]
pub enum SourceError {
    #[error("invalid template address: {0}")]
    Address(String),
    #[error("{0}: {1}")]
    Io(PathBuf, #[source] std::io::Error),
    #[error("git fetch failed: {0}")]
    Git(String),
}
fn split_git(value: &str) -> Result<(&str, Option<String>, Option<String>), SourceError> {
    let (before_path, path) = value
        .split_once('#')
        .map_or((value, None), |(a, b)| (a, Some(b.to_string())));
    if path.as_deref() == Some("") {
        return Err(SourceError::Address("empty template path".into()));
    }
    let start = if before_path.starts_with("git@") {
        before_path.find(':').map_or(0, |p| p + 1)
    } else {
        before_path.find("://").map_or(0, |p| {
            let authority = p + 3;
            before_path[authority..]
                .find('/')
                .map_or(before_path.len(), |slash| authority + slash + 1)
        })
    };
    let (repo, reference) = before_path[start..]
        .rfind('@')
        .map_or((before_path, None), |p| {
            (
                &before_path[..start + p],
                Some(before_path[start + p + 1..].to_string()),
            )
        });
    if repo.is_empty() || reference.as_deref() == Some("") {
        return Err(SourceError::Address("invalid repository or ref".into()));
    }
    Ok((repo, reference, path))
}
pub fn parse(arg: &str, hosts: &Hosts, cwd: &Path, home: &Path) -> Result<Address, SourceError> {
    if arg.contains("://") || arg.starts_with("git@") {
        let (repo, reference, path) = split_git(arg)?;
        return Ok(Address::Git {
            repo: repo.into(),
            reference,
            path,
        });
    }
    if let Some((prefix, rest)) = arg.split_once(':')
        && let Some(base) = hosts.get(prefix)
    {
        let (repo, reference, path) = split_git(rest)?;
        if !repo.contains('/') {
            return Err(SourceError::Address(
                "host address requires owner/repository".into(),
            ));
        }
        return Ok(Address::Git {
            repo: format!("{}/{}", base.trim_end_matches('/'), repo),
            reference,
            path,
        });
    }
    let drive = arg.as_bytes().get(0..3).is_some_and(|v| {
        v[0].is_ascii_alphabetic() && v[1] == b':' && matches!(v[2], b'/' | b'\\')
    });
    if arg.starts_with('.') || Path::new(arg).is_absolute() || arg.starts_with('~') || drive {
        let value = if arg == "~" {
            home.to_path_buf()
        } else if let Some(rest) = arg.strip_prefix("~/") {
            home.join(rest)
        } else {
            PathBuf::from(arg)
        };
        let absolute = if value.is_absolute() {
            value
        } else {
            cwd.join(value)
        };
        return Ok(Address::Folder(
            absolute
                .canonicalize()
                .map_err(|e| SourceError::Io(absolute, e))?,
        ));
    }
    Ok(Address::Name(arg.into()))
}
impl Address {
    pub fn formal_name(&self, hosts: &Hosts) -> String {
        match self {
            Self::Name(name) => name.clone(),
            Self::Folder(path) => path.to_string_lossy().into_owned(),
            Self::Git {
                repo,
                reference,
                path,
            } => {
                let safe_repo = without_userinfo(repo);
                let mut name = hosts
                    .iter()
                    .find_map(|(prefix, base)| {
                        let remainder = safe_repo
                            .strip_prefix(base.trim_end_matches('/'))?
                            .strip_prefix('/')?;
                        if remainder.is_empty() || !remainder.contains('/') {
                            return None;
                        }
                        Some(format!("{prefix}:{remainder}"))
                    })
                    .or_else(|| {
                        hosts.iter().find_map(|(prefix, base)| {
                            let host = base.split("://").nth(1)?.trim_end_matches('/');
                            let remainder = repo
                                .strip_prefix("git@")?
                                .strip_prefix(host)?
                                .strip_prefix(':')?;
                            Some(format!("{prefix}:{remainder}"))
                        })
                    })
                    .unwrap_or(safe_repo);
                if name.ends_with(".git") {
                    name.truncate(name.len() - 4);
                }
                if let Some(reference) = reference {
                    name.push('@');
                    name.push_str(reference);
                }
                if let Some(path) = path {
                    name.push('#');
                    name.push_str(path);
                }
                name
            }
        }
    }
}
/// A source suitable for durable registry and cache identifiers.
pub fn without_userinfo(repo: &str) -> String {
    if let Some(scheme) = repo.find("://") {
        let authority_start = scheme + 3;
        let authority_end = repo[authority_start..]
            .find('/')
            .map_or(repo.len(), |slash| authority_start + slash);
        if let Some(at) = repo[authority_start..authority_end].rfind('@') {
            return format!(
                "{}{}",
                &repo[..authority_start],
                &repo[authority_start + at + 1..]
            );
        }
    }
    if let Some(rest) = repo.strip_prefix("git@") {
        if let Some((host, path)) = rest.split_once(':') {
            return format!("ssh://{host}/{path}");
        }
        return format!("ssh://{rest}");
    }
    repo.to_string()
}
/// The fetch failure for `error`, without the credentials of `repo` or any
/// password `supplied` saw.
fn git_error(error: impl std::fmt::Display, repo: &str, supplied: &Supplied) -> SourceError {
    SourceError::Git(supplied.message(redacted(&error.to_string(), repo)))
}
/// `message` with the credentials of `repo` removed wherever it names them.
pub(crate) fn redacted(message: &str, repo: &str) -> String {
    let safe = without_userinfo(repo);
    let mut message = message.replace(repo, &safe);
    if let Some(scheme) = repo.find("://") {
        let start = scheme + 3;
        let end = repo[start..]
            .find('/')
            .map_or(repo.len(), |slash| start + slash);
        if let Some(at) = repo[start..end].rfind('@') {
            message = message.replace(&repo[start..start + at + 1], "");
        }
    }
    message
}
pub fn cache_path(cache: &Path, address: &Address, hosts: &Hosts, commit: &str) -> PathBuf {
    cache
        .join("sources")
        .join(install_key(&address.formal_name(hosts)))
        .join(commit)
}
pub fn install_key(formal: &str) -> String {
    formal
        .split('#')
        .next()
        .unwrap_or(formal)
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || "._-".contains(c) {
                c
            } else {
                '_'
            }
        })
        .collect()
}
fn reference_kind(repo: &str, reference: Option<&str>) -> Result<RefKind, SourceError> {
    let Some(reference) = reference else {
        return Ok(RefKind::DefaultBranch);
    };
    if let Some(local) = local_git_path(repo) {
        let remote = gix::open(local).map_err(|e| SourceError::Git(e.to_string()))?;
        if remote
            .find_reference(&format!("refs/tags/{reference}"))
            .is_ok()
        {
            return Ok(RefKind::Tag);
        }
        if remote
            .find_reference(&format!("refs/heads/{reference}"))
            .is_ok()
        {
            return Ok(RefKind::Branch);
        }
    }
    if reference.len() >= 4 && reference.bytes().all(|c| c.is_ascii_hexdigit()) {
        Ok(RefKind::Commit)
    } else {
        Ok(RefKind::Branch)
    }
}
fn local_git_path(repo: &str) -> Option<&str> {
    let local = repo.strip_prefix("file://")?;
    if cfg!(windows) {
        Some(windows_local_git_path(local))
    } else {
        Some(local)
    }
}
fn windows_local_git_path(local: &str) -> &str {
    if local.starts_with('/') && local.as_bytes().get(2) == Some(&b':') {
        &local[1..]
    } else {
        local
    }
}
fn expand_commit(repo: &str, short: &str, dest: &Path) -> Result<String, SourceError> {
    if short.len() == 40 {
        return Ok(short.into());
    }
    let local = local_git_path(repo).unwrap_or(repo);
    if repo.starts_with("file://") {
        return gix::open(local)
            .map_err(|e| SourceError::Git(e.to_string()))?
            .rev_parse_single(short)
            .map(|id| id.to_string())
            .map_err(|e| SourceError::Git(e.to_string()));
    }
    let parent = dest
        .parent()
        .ok_or_else(|| SourceError::Address("destination has no parent".into()))?;
    let temporary = tempfile::tempdir_in(parent).map_err(|e| SourceError::Io(parent.into(), e))?;
    let lookup = temporary.path().join("lookup");
    fetch(
        &Address::Git {
            repo: repo.into(),
            reference: None,
            path: None,
        },
        &lookup,
    )?;
    gix::open(&lookup)
        .map_err(|e| SourceError::Git(e.to_string()))?
        .rev_parse_single(short)
        .map(|id| id.to_string())
        .map_err(|e| SourceError::Git(e.to_string()))
}
/// The roots Toha hands a bundled rustls transport, written once per connection
/// owner and kept alive for as long as the connection may read them.
pub(crate) type NativeRoots = Option<tempfile::NamedTempFile>;
/// A connection Toha opens to a Git remote.
pub(crate) type Connection<'a, 'b, 'c> = gix::remote::Connection<
    'a,
    'b,
    'c,
    Box<dyn gix::protocol::transport::client::blocking_io::Transport + Send>,
>;
/// Prepare every connection Toha opens: answer HTTPS challenges from the
/// operation's credential resolver, and set the HTTP options.
pub(crate) fn prepare_connection(
    connection: &mut Connection<'_, '_, '_>,
    native_roots: &mut NativeRoots,
    supplied: &Supplied,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let resolving = supplied.attach(connection);
    configure_http(connection, native_roots, resolving)
}
/// Point an HTTPS connection at the platform's trusted roots. System curl
/// backends already use platform trust. Bundled rustls needs a CA bundle when
/// Git has not supplied one. When `quiet`, curl's verbose output is off, as it
/// writes request headers, a resolver's credential among them, to stderr.
fn configure_http(
    connection: &mut Connection<'_, '_, '_>,
    native_roots: &mut NativeRoots,
    quiet: bool,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let rustls = curl::Version::get()
        .ssl_version()
        .is_some_and(|backend| backend.starts_with("rustls"));
    if !rustls && !quiet {
        return Ok(());
    }
    let url = connection.transport_mut().to_url().into_owned();
    let remote = connection.remote();
    let Some(mut options) = remote
        .repo()
        .transport_options(url.as_bstr(), remote.name().map(gix::remote::Name::as_bstr))?
    else {
        return Ok(());
    };
    if let Some(http) =
        options.downcast_mut::<gix::protocol::transport::client::blocking_io::http::Options>()
    {
        if quiet {
            http.verbose = false;
        }
        if rustls && http.ssl_ca_info.is_none() && http.ssl_verify {
            if native_roots.is_none() {
                let loaded = rustls_native_certs::load_native_certs();
                if loaded.certs.is_empty() {
                    // Plain HTTP does not require CA roots. With no bundle,
                    // curl still verifies and rejects an untrusted TLS peer.
                    connection.set_transport_options(options);
                    return Ok(());
                }
                let mut bundle = tempfile::NamedTempFile::new()?;
                for cert in loaded.certs {
                    writeln!(bundle, "-----BEGIN CERTIFICATE-----")?;
                    let encoded = base64::engine::general_purpose::STANDARD.encode(cert.as_ref());
                    for line in encoded.as_bytes().chunks(64) {
                        bundle.write_all(line)?;
                        bundle.write_all(b"\n")?;
                    }
                    writeln!(bundle, "-----END CERTIFICATE-----")?;
                }
                bundle.flush()?;
                *native_roots = Some(bundle);
            }
            http.ssl_ca_info = Some(native_roots.as_ref().unwrap().path().to_owned());
        }
    }
    connection.set_transport_options(options);
    Ok(())
}
pub fn fetch(address: &Address, dest: &Path) -> Result<Fetched, SourceError> {
    let Address::Git {
        repo, reference, ..
    } = address
    else {
        return Err(SourceError::Address("a git address is required".into()));
    };
    let mut kind = reference_kind(repo, reference.as_deref())?;
    if dest.exists() {
        return Err(SourceError::Address(format!(
            "destination exists: {}",
            dest.display()
        )));
    }
    let resolved_commit = if kind == RefKind::Commit {
        Some(expand_commit(repo, reference.as_deref().unwrap(), dest)?)
    } else {
        None
    };
    let mut native_roots = None;
    let supplied = Supplied::default();
    let attach = supplied.clone();
    let mut clone = gix::prepare_clone(repo.as_str(), dest)
        .map_err(|e| git_error(e, repo, &supplied))?
        .configure_connection(move |connection| {
            prepare_connection(connection, &mut native_roots, &attach)
        });
    if credentials::resolving() {
        // gix retries a clone whose remote has a `refs/heads/HEAD` branch on a
        // second connection it does not let Toha prepare, so that connection
        // would skip the resolver. Excluding the branch removes the retry. Setting
        // the remote here also means gix leaves tags to it, so ask for all tags,
        // as a clone does without this setting.
        clone = clone.configure_remote(|remote| {
            Ok(remote
                .with_refspecs(["^refs/heads/HEAD"], gix::remote::Direction::Fetch)?
                .with_fetch_tags(gix::remote::fetch::Tags::All))
        });
    }
    if let Some(reference) = reference {
        clone = if kind == RefKind::Commit {
            clone
                .with_revision(Some(resolved_commit.as_deref().unwrap()))
                .map_err(|e| git_error(e, repo, &supplied))?
        } else {
            clone
                .with_ref_name(Some(reference.as_str()))
                .map_err(|e| git_error(e, repo, &supplied))?
        };
    }
    let (mut checkout, _) = clone
        .fetch_then_checkout(gix::progress::Discard, &AtomicBool::new(false))
        .map_err(|e| git_error(e, repo, &supplied))?;
    let (checkout_repo, _) = checkout
        .main_worktree(gix::progress::Discard, &AtomicBool::new(false))
        .map_err(|e| git_error(e, repo, &supplied))?;
    if kind == RefKind::Branch
        && reference.as_ref().is_some_and(|r| {
            checkout_repo
                .find_reference(&format!("refs/tags/{r}"))
                .is_ok()
        })
    {
        kind = RefKind::Tag;
    }
    let commit = checkout_repo
        .head_id()
        .map_err(|e| git_error(e, repo, &supplied))?
        .to_string();
    Ok(Fetched {
        commit,
        reference_kind: kind,
    })
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn local_file_url_uses_platform_path() {
        assert_eq!(windows_local_git_path("/C:/sample/repo"), "C:/sample/repo");
        let expected = if cfg!(windows) {
            "C:/sample/repo"
        } else {
            "/sample/repo"
        };
        let input = if cfg!(windows) {
            "file:///C:/sample/repo"
        } else {
            "file:///sample/repo"
        };
        assert_eq!(local_git_path(input), Some(expected));
    }
    #[test]
    fn parse_order_and_formal_names() {
        let root = tempfile::tempdir().unwrap();
        let hosts = Hosts::from([
            ("gh".into(), "https://github.com".into()),
            ("local".into(), format!("file://{}", root.path().display())),
        ]);
        let cwd = root.path();
        let folder = cwd.join("folder");
        std::fs::create_dir(&folder).unwrap();
        let table = [
            ("https://github.com/a/b.git@main#sub", "gh:a/b@main#sub"),
            ("git@github.com:a/b.git@main#sub", "gh:a/b@main#sub"),
            ("https://user@github.com/a/b", "gh:a/b"),
            ("https://user@github.com/a/b@v1#p", "gh:a/b@v1#p"),
            ("git@github.com:a/b@main", "gh:a/b@main"),
            (
                "https://user:token@else.invalid/a/b",
                "https://else.invalid/a/b",
            ),
            ("gh:a/b@main#sub", "gh:a/b@main#sub"),
            ("local:a/b#sub", "local:a/b#sub"),
            ("https://else.invalid/a/b.git", "https://else.invalid/a/b"),
            (
                "https://github.com.evil/a/b.git",
                "https://github.com.evil/a/b",
            ),
        ];
        for (input, formal) in table {
            let address = parse(input, &hosts, cwd, cwd).unwrap();
            assert_eq!(address.formal_name(&hosts), formal, "{input}");
            if let Address::Git {
                repo, reference, ..
            } = &address
            {
                assert!(!without_userinfo(repo).contains("token"));
                assert!(
                    !cache_path(cwd, &address, &hosts, "abc")
                        .to_string_lossy()
                        .contains("token")
                );
                if input.contains("@v1") {
                    assert_eq!(reference.as_deref(), Some("v1"));
                }
            }
        }
        assert!(matches!(
            parse("./folder", &hosts, cwd, cwd).unwrap(),
            Address::Folder(_)
        ));
        let canonical = folder.canonicalize().unwrap();
        let parsed = parse(canonical.to_str().unwrap(), &hosts, cwd, cwd).unwrap();
        assert!(matches!(parsed, Address::Folder(path) if path == canonical));
        let names: &[&str] = if cfg!(windows) {
            &["C:relative"]
        } else {
            &[r"\\?\C:\sample", r"\\server\share", "C:relative"]
        };
        for &name in names {
            assert_eq!(
                parse(name, &hosts, cwd, cwd).unwrap(),
                Address::Name(name.into())
            );
        }
        assert_eq!(
            parse("plain", &hosts, cwd, cwd).unwrap(),
            Address::Name("plain".into())
        );
        assert!(parse("gh:invalid", &hosts, cwd, cwd).is_err());
        let address = parse("gh:a/b#sub", &hosts, cwd, cwd).unwrap();
        assert_eq!(
            cache_path(cwd, &address, &hosts, "abc"),
            cwd.join("sources/gh_a_b/abc")
        );
        let repo = "https://user:token@host.invalid/o/r";
        let error = git_error(
            format!("clone failed for {repo}"),
            repo,
            &Supplied::default(),
        )
        .to_string();
        assert!(!error.contains("token"));
        assert!(error.contains("https://host.invalid/o/r"));
    }
}