xurl-rs 2.1.0

A fast, ergonomic CLI for the X (Twitter) API — OAuth1/2, Bearer, media upload, streaming
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
563
564
565
//! Build script. Codegen `SkillHost` enum, `KNOWN_HOSTS` const, and
//! `resolve_host` / `host_envelope_str` functions from
//! `src/skill_install/skill.json`. Also codegen the auth-method matrix
//! from `vendor/x-api-openapi.json` into `$OUT_DIR/auth_matrix.rs`.
//!
//! Both source files are the single source of truth — updating either one
//! regenerates the consuming Rust modules on the next `cargo build` (via
//! `cargo::rerun-if-changed`). Mirrors the pattern in
//! `agentnative-cli/build.rs`.

use std::collections::BTreeMap;
use std::env;
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};

use serde::Deserialize;

fn main() {
    let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
    emit_skill_hosts(&manifest_dir);
    emit_auth_matrix(&manifest_dir);
    emit_build_info(&manifest_dir);
}

/// Emit `$OUT_DIR/generated_hosts.rs` from `src/skill_install/skill.json`.
///
/// Reads the manifest's `install` map and emits, for every `<host>` key:
///
/// - a `SkillHost` enum variant (PascalCase of the snake_case key) with
///   `clap::ValueEnum` derive + `#[value(rename_all = "snake_case")]` so
///   surface names round-trip back to the JSON key verbatim;
/// - an entry in `KNOWN_HOSTS: &[&str]`;
/// - a match arm in `resolve_host(SkillHost) -> (&'static str, &'static str)`
///   returning the `(url, dest_template)` parsed from the host's install
///   command;
/// - a match arm in `host_envelope_str(SkillHost) -> &'static str` returning
///   the canonical JSON-key surface name.
///
/// Each install command MUST have the canonical shape
/// `git clone --depth 1 <url> <dest>` — six whitespace-separated tokens.
/// Anything else panics the build with the offending host and command.
fn emit_skill_hosts(manifest_dir: &Path) {
    let skill_json_path = manifest_dir.join("src/skill_install/skill.json");
    println!("cargo:rerun-if-changed=src/skill_install/skill.json");

    let content = fs::read_to_string(&skill_json_path)
        .unwrap_or_else(|e| panic!("read {}: {e}", skill_json_path.display()));
    let manifest: serde_json::Value = serde_json::from_str(&content)
        .unwrap_or_else(|e| panic!("parse {}: {e}", skill_json_path.display()));

    let install = manifest
        .get("install")
        .and_then(|v| v.as_object())
        .unwrap_or_else(|| {
            panic!(
                "{}: \"install\" must be an object (host -> command map)",
                skill_json_path.display()
            )
        });

    if install.is_empty() {
        panic!(
            "{}: install map is empty — at least one host required",
            skill_json_path.display()
        );
    }

    // Sorted by JSON key so the generated source has stable byte output.
    let mut hosts: Vec<(String, String, String, String)> = Vec::with_capacity(install.len());
    for (key, cmd_value) in install {
        let cmd = cmd_value.as_str().unwrap_or_else(|| {
            panic!(
                "{}: install.{key:?} must be a string",
                skill_json_path.display()
            )
        });
        let tokens: Vec<&str> = cmd.split_whitespace().collect();
        if tokens.len() != 6
            || tokens[0] != "git"
            || tokens[1] != "clone"
            || tokens[2] != "--depth"
            || tokens[3] != "1"
        {
            panic!(
                "{}: install.{key:?} must match `git clone --depth 1 <url> <dest>` (got {} tokens: {cmd:?})",
                skill_json_path.display(),
                tokens.len(),
            );
        }
        let url = tokens[4].to_string();
        let dest = tokens[5].to_string();
        if dest.ends_with(".git") {
            panic!(
                "{}: install.{key:?} dest {dest:?} ends in `.git` — host commands must terminate with an explicit destination, not the bare repo name",
                skill_json_path.display()
            );
        }
        let variant = pascal_case(key).unwrap_or_else(|e| {
            panic!(
                "{}: install.{key:?} is not a valid Rust identifier: {e}",
                skill_json_path.display()
            )
        });
        hosts.push((key.clone(), variant, url, dest));
    }
    hosts.sort_by(|a, b| a.0.cmp(&b.0));

    let mut src = String::new();
    src.push_str(
        "// @generated by build.rs from src/skill_install/skill.json. Do not edit by hand.\n",
    );
    src.push_str(
        "// Add or remove hosts via the JSON file and `cargo build` regenerates this file.\n\n",
    );

    src.push_str("/// Hosts the binary knows how to install into. Surface names match\n");
    src.push_str("/// `src/skill_install/skill.json` keys verbatim via\n");
    src.push_str("/// `rename_all = \"snake_case\"`.\n");
    src.push_str("#[derive(Clone, Copy, Debug, PartialEq, Eq, ::clap::ValueEnum)]\n");
    src.push_str("#[value(rename_all = \"snake_case\")]\n");
    src.push_str("pub enum SkillHost {\n");
    for (_, variant, _, _) in &hosts {
        src.push_str(&format!("    {variant},\n"));
    }
    src.push_str("}\n\n");

    src.push_str("/// Host names accepted by `xr skill install <host>`, in JSON-key sort order.\n");
    src.push_str("/// Stays in lockstep with [`SkillHost`] because both are generated from the\n");
    src.push_str("/// same source.\n");
    src.push_str("pub const KNOWN_HOSTS: &[&str] = &[\n");
    for (key, _, _, _) in &hosts {
        src.push_str(&format!("    {key:?},\n"));
    }
    src.push_str("];\n\n");

    src.push_str("/// Resolve a host enum to its `(url, dest_template)` pair, parsed at build\n");
    src.push_str("/// time from the install command in `src/skill_install/skill.json`. Pure\n");
    src.push_str("/// function — no I/O, no side effects.\n");
    src.push_str("pub fn resolve_host(host: SkillHost) -> (&'static str, &'static str) {\n");
    src.push_str("    match host {\n");
    for (_, variant, url, dest) in &hosts {
        src.push_str(&format!(
            "        SkillHost::{variant} => ({url:?}, {dest:?}),\n"
        ));
    }
    src.push_str("    }\n");
    src.push_str("}\n\n");

    src.push_str("/// JSON-key string for the envelope's `host` field. Generated alongside the\n");
    src.push_str("/// enum so the surface stays in lockstep with the JSON contract.\n");
    src.push_str("pub fn host_envelope_str(host: SkillHost) -> &'static str {\n");
    src.push_str("    match host {\n");
    for (key, variant, _, _) in &hosts {
        src.push_str(&format!("        SkillHost::{variant} => {key:?},\n"));
    }
    src.push_str("    }\n");
    src.push_str("}\n");

    let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));
    let out_path = out_dir.join("generated_hosts.rs");
    fs::write(&out_path, src)
        .unwrap_or_else(|e| panic!("cannot write {}: {e}", out_path.display()));
}

/// Convert a snake_case ASCII identifier to PascalCase. Rejects empty
/// strings, leading digits, and any character outside `[a-z0-9_]` so the
/// emitted variant is always a valid Rust identifier.
fn pascal_case(snake: &str) -> Result<String, String> {
    if snake.is_empty() {
        return Err("empty identifier".into());
    }
    if snake.starts_with(|c: char| c.is_ascii_digit()) {
        return Err(format!("{snake:?} starts with a digit"));
    }
    if !snake
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
    {
        return Err(format!(
            "{snake:?} contains non-snake_case ASCII characters"
        ));
    }
    let mut out = String::with_capacity(snake.len());
    for word in snake.split('_') {
        let mut chars = word.chars();
        if let Some(first) = chars.next() {
            out.push(first.to_ascii_uppercase());
            out.push_str(chars.as_str());
        }
    }
    Ok(out)
}

// ── Auth matrix codegen ─────────────────────────────────────────────────
//
// Walks `vendor/x-api-openapi.json`, filters to the shortcut-layer allowlist
// (the (method, path) pairs reachable from `src/api/shortcuts.rs` and
// `src/api/media.rs` after normalizing local param names to the spec), and
// emits a `phf::Map<&'static str, &'static [AuthScheme]>` keyed on
// `"METHOD\0/path/template"`. Wrapped at runtime by `src/api/auth_matrix.rs`.
//
// Missing or empty `security:` arrays are treated as "no entry" — the
// runtime treats those as permissive. Unknown spec security-scheme keys
// panic the build so silent matrix corruption is impossible.

/// (METHOD, spec path) tuples the shortcut + media layer actually calls.
/// Param names match the spec verbatim — code that uses different local
/// names normalizes at the shortcut site.
const SHORTCUT_TEMPLATES: &[(&str, &str)] = &[
    // tweets
    ("POST", "/2/tweets"),
    ("GET", "/2/tweets/{id}"),
    ("DELETE", "/2/tweets/{id}"),
    ("GET", "/2/tweets/search/recent"),
    // users (reads)
    ("GET", "/2/users/me"),
    ("GET", "/2/users/by/username/{username}"),
    ("GET", "/2/users/{id}/timelines/reverse_chronological"),
    ("GET", "/2/users/{id}/mentions"),
    ("GET", "/2/users/{id}/followers"),
    ("GET", "/2/users/{id}/liked_tweets"),
    ("GET", "/2/users/{id}/blocking"),
    // likes
    ("POST", "/2/users/{id}/likes"),
    ("DELETE", "/2/users/{id}/likes/{tweet_id}"),
    // retweets
    ("POST", "/2/users/{id}/retweets"),
    ("DELETE", "/2/users/{id}/retweets/{source_tweet_id}"),
    // bookmarks
    ("GET", "/2/users/{id}/bookmarks"),
    ("POST", "/2/users/{id}/bookmarks"),
    ("DELETE", "/2/users/{id}/bookmarks/{tweet_id}"),
    // following
    ("GET", "/2/users/{id}/following"),
    ("POST", "/2/users/{id}/following"),
    (
        "DELETE",
        "/2/users/{source_user_id}/following/{target_user_id}",
    ),
    // muting
    ("GET", "/2/users/{id}/muting"),
    ("POST", "/2/users/{id}/muting"),
    (
        "DELETE",
        "/2/users/{source_user_id}/muting/{target_user_id}",
    ),
    // DMs
    ("POST", "/2/dm_conversations/with/{participant_id}/messages"),
    ("GET", "/2/dm_events"),
    // usage
    ("GET", "/2/usage/tweets"),
    // media
    ("POST", "/2/media/upload"),
    ("GET", "/2/media/upload"),
    ("POST", "/2/media/upload/initialize"),
    ("POST", "/2/media/upload/{id}/append"),
    ("POST", "/2/media/upload/{id}/finalize"),
];

#[derive(Deserialize)]
struct Spec {
    #[serde(default)]
    paths: BTreeMap<String, PathItem>,
}

#[derive(Deserialize, Default)]
struct PathItem {
    #[serde(default)]
    get: Option<Operation>,
    #[serde(default)]
    post: Option<Operation>,
    #[serde(default)]
    put: Option<Operation>,
    #[serde(default)]
    delete: Option<Operation>,
    #[serde(default)]
    patch: Option<Operation>,
}

#[derive(Deserialize)]
struct Operation {
    #[serde(default)]
    security: Option<Vec<BTreeMap<String, Vec<String>>>>,
}

/// One concrete matrix entry, ready to emit.
struct Entry {
    method: &'static str,
    path: &'static str,
    schemes: Vec<SchemeRepr>,
}

/// In-memory representation of an `AuthScheme` value pre-codegen.
enum SchemeRepr {
    Bearer,
    OAuth1User,
    OAuth2User(Vec<String>),
}

/// Emit `$OUT_DIR/auth_matrix.rs` from `vendor/x-api-openapi.json`.
///
/// The output is a `phf::Map<&'static str, &'static [AuthScheme]>` plus one
/// `static SUP_<N>` slice per entry. Keys are packed as `"METHOD\0/path"`.
/// Iteration order over `SHORTCUT_TEMPLATES` plus the BTreeMap-backed spec
/// keeps the emitted source byte-deterministic.
fn emit_auth_matrix(manifest_dir: &Path) {
    let spec_path = manifest_dir.join("vendor").join("x-api-openapi.json");
    println!("cargo::rerun-if-changed=vendor/x-api-openapi.json");

    let content = fs::read_to_string(&spec_path)
        .unwrap_or_else(|e| panic!("read {}: {e}", spec_path.display()));
    let spec: Spec = serde_json::from_str(&content)
        .unwrap_or_else(|e| panic!("parse {}: {e}", spec_path.display()));

    let mut entries: Vec<Entry> = Vec::with_capacity(SHORTCUT_TEMPLATES.len());
    for (method, path) in SHORTCUT_TEMPLATES {
        let item = spec.paths.get(*path).unwrap_or_else(|| {
            panic!(
                "{}: SHORTCUT_TEMPLATES references {path:?} but spec has no such path; \
                 fix the allowlist or refresh the spec",
                spec_path.display()
            )
        });
        let op = match *method {
            "GET" => item.get.as_ref(),
            "POST" => item.post.as_ref(),
            "PUT" => item.put.as_ref(),
            "DELETE" => item.delete.as_ref(),
            "PATCH" => item.patch.as_ref(),
            other => panic!("SHORTCUT_TEMPLATES has unsupported method {other:?} for {path:?}"),
        };
        let Some(op) = op else {
            panic!(
                "{}: spec path {path:?} declares no `{method}` operation; \
                 the shortcut layer claims to call it — fix the allowlist or refresh the spec",
                spec_path.display()
            );
        };
        let Some(security) = op.security.as_ref() else {
            continue;
        };
        if security.is_empty() {
            continue;
        }
        let mut schemes = Vec::with_capacity(security.len());
        for entry in security {
            if entry.len() != 1 {
                panic!(
                    "{}: {method} {path}: each security entry must name exactly one scheme \
                     (got {} keys: {:?})",
                    spec_path.display(),
                    entry.len(),
                    entry.keys().collect::<Vec<_>>(),
                );
            }
            let (key, scopes) = entry.iter().next().expect("len == 1 above");
            let scheme = match key.as_str() {
                "BearerToken" => SchemeRepr::Bearer,
                "OAuth2UserToken" => SchemeRepr::OAuth2User(scopes.clone()),
                "UserToken" => SchemeRepr::OAuth1User,
                other => panic!(
                    "{}: {method} {path}: unknown security scheme {other:?} — \
                     extend the build.rs translation table or update the spec",
                    spec_path.display()
                ),
            };
            schemes.push(scheme);
        }
        entries.push(Entry {
            method,
            path,
            schemes,
        });
    }

    let mut src = String::new();
    src.push_str(
        "// @generated by build.rs from vendor/x-api-openapi.json. Do not edit by hand.\n",
    );
    src.push_str("// Refresh via scripts/refresh-vendor-spec.sh; `cargo build` regenerates.\n\n");

    for (i, entry) in entries.iter().enumerate() {
        writeln!(
            &mut src,
            "static SUP_{i}: &[AuthScheme] = &[{}];",
            render_schemes(&entry.schemes)
        )
        .expect("write to String never fails");
    }
    src.push('\n');

    let mut map = phf_codegen::Map::new();
    let values: Vec<String> = (0..entries.len()).map(|i| format!("&SUP_{i}")).collect();
    for (entry, value) in entries.iter().zip(values.iter()) {
        let key = format!("{}\0{}", entry.method, entry.path);
        map.entry(key, value.as_str());
    }
    writeln!(
        &mut src,
        "pub static AUTH_MATRIX: phf::Map<&'static str, &'static [AuthScheme]> = {};",
        map.build()
    )
    .expect("write to String never fails");

    // Emit SHORTCUT_TEMPLATES alongside AUTH_MATRIX so the runtime mirror
    // is regenerated from this same source list every build. Removes the
    // manual hand-copy at src/api/auth_matrix.rs and the test that existed
    // solely to catch drift between the two.
    src.push('\n');
    src.push_str("pub const SHORTCUT_TEMPLATES: &[(&str, &str)] = &[\n");
    for entry in SHORTCUT_TEMPLATES {
        writeln!(&mut src, "    ({:?}, {:?}),", entry.0, entry.1)
            .expect("write to String never fails");
    }
    src.push_str("];\n");

    let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));
    let out_path = out_dir.join("auth_matrix.rs");
    fs::write(&out_path, src)
        .unwrap_or_else(|e| panic!("cannot write {}: {e}", out_path.display()));
}

// ── Build-info emission ─────────────────────────────────────────────────
//
// Populates compile-time env vars consumed by `src/lib.rs`'s `BUILD_INFO`
// const.
//
// API spec metadata (`info_version`, `content_sha256`, `refreshed_at`) is
// vendored alongside the spec itself at `vendor/spec-metadata.json` and
// read from disk here. The sidecar exists so the metadata always describes
// the actual bytes that ship: an uncommitted local refresh sees the new
// metadata immediately, and a crates.io tarball build (no `.git`) carries
// the metadata in the published package. `scripts/refresh-x-openapi.sh`
// writes the sidecar atomically alongside `vendor/x-api-openapi.json`.
//
// Crate git SHA is genuinely build-context provenance and stays
// best-effort: `git rev-parse HEAD` runs when a `.git` directory exists
// and resolves to `None` on crates.io tarball installs.

/// Emit `XURL_CRATE_GIT_SHA`, `XURL_API_SPEC_VERSION`, `XURL_API_SPEC_SHA256`,
/// and `XURL_API_SPEC_DATE` env vars for `src/lib.rs` to consume via
/// `env!` / `option_env!`. Panics if the vendored spec and sidecar
/// disagree on `info.version` (a stale sidecar — re-run
/// `scripts/refresh-x-openapi.sh`).
fn emit_build_info(manifest_dir: &Path) {
    // Invalidate the build when HEAD moves so `XURL_CRATE_GIT_SHA` tracks
    // the actual current commit on rebuild.
    println!("cargo:rerun-if-changed=.git/HEAD");
    println!("cargo:rerun-if-changed=vendor/spec-metadata.json");

    if let Some(sha) = run_git(manifest_dir, &["rev-parse", "HEAD"]) {
        println!("cargo:rustc-env=XURL_CRATE_GIT_SHA={sha}");
    }

    // Read the vendored metadata sidecar. The sidecar is the source of
    // truth for shipped spec identity.
    let metadata_path = manifest_dir.join("vendor").join("spec-metadata.json");
    let metadata_content = fs::read_to_string(&metadata_path).unwrap_or_else(|e| {
        panic!(
            "read {}: {e} — run scripts/refresh-x-openapi.sh to regenerate",
            metadata_path.display()
        )
    });
    let metadata: serde_json::Value = serde_json::from_str(&metadata_content).unwrap_or_else(|e| {
        panic!("parse {}: {e}", metadata_path.display());
    });
    let metadata_version = string_field(&metadata, "info_version", &metadata_path);
    let metadata_sha256 = string_field(&metadata, "content_sha256", &metadata_path);
    let metadata_refreshed = string_field(&metadata, "refreshed_at", &metadata_path);

    // Cross-check: the sidecar's `info_version` must match the vendored
    // JSON's `info.version`. A mismatch means one was updated without the
    // other; fail the build with a pointer to the refresh script rather
    // than letting drifted metadata reach consumers.
    let spec_path = manifest_dir.join("vendor").join("x-api-openapi.json");
    let spec_content = fs::read_to_string(&spec_path)
        .unwrap_or_else(|e| panic!("read {}: {e}", spec_path.display()));
    let spec: serde_json::Value = serde_json::from_str(&spec_content)
        .unwrap_or_else(|e| panic!("parse {}: {e}", spec_path.display()));
    let spec_info_version = spec
        .get("info")
        .and_then(|v| v.get("version"))
        .and_then(|v| v.as_str())
        .unwrap_or_else(|| {
            panic!(
                "{}: must have an `info.version` string field",
                spec_path.display()
            )
        });
    if spec_info_version != metadata_version {
        panic!(
            "vendor/x-api-openapi.json `info.version` is {spec_info_version:?} but \
             vendor/spec-metadata.json `info_version` is {metadata_version:?} — \
             run scripts/refresh-x-openapi.sh to resync"
        );
    }

    println!("cargo:rustc-env=XURL_API_SPEC_VERSION={metadata_version}");
    println!("cargo:rustc-env=XURL_API_SPEC_SHA256={metadata_sha256}");
    println!("cargo:rustc-env=XURL_API_SPEC_DATE={metadata_refreshed}");
}

/// Extract a required string field from a `serde_json::Value` object;
/// panic with a helpful message that names the file and field when
/// missing.
fn string_field<'a>(value: &'a serde_json::Value, field: &str, path: &Path) -> &'a str {
    value
        .get(field)
        .and_then(|v| v.as_str())
        .unwrap_or_else(|| {
            panic!(
                "{}: missing required string field {field:?} — \
                 run scripts/refresh-x-openapi.sh to regenerate",
                path.display()
            )
        })
}

/// Run `git <args>` from `cwd` and return trimmed stdout on success.
/// Returns `None` when git is unavailable, the command fails, or stdout
/// is empty. Used for best-effort provenance metadata that must degrade
/// gracefully on crates.io tarball builds (no `.git` directory).
fn run_git(cwd: &Path, args: &[&str]) -> Option<String> {
    let output = std::process::Command::new("git")
        .current_dir(cwd)
        .args(args)
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let stdout = String::from_utf8(output.stdout).ok()?;
    let trimmed = stdout.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// Render a slice of `SchemeRepr` as the body of a `&[AuthScheme]` literal.
fn render_schemes(schemes: &[SchemeRepr]) -> String {
    let mut out = String::new();
    for (i, s) in schemes.iter().enumerate() {
        if i > 0 {
            out.push_str(", ");
        }
        match s {
            SchemeRepr::Bearer => out.push_str("AuthScheme::Bearer"),
            SchemeRepr::OAuth1User => out.push_str("AuthScheme::OAuth1User"),
            SchemeRepr::OAuth2User(scopes) => {
                out.push_str("AuthScheme::OAuth2User(&[");
                for (j, scope) in scopes.iter().enumerate() {
                    if j > 0 {
                        out.push_str(", ");
                    }
                    write!(&mut out, "{scope:?}").expect("write to String never fails");
                }
                out.push_str("])");
            }
        }
    }
    out
}