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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! The uploading logic was mostly reverse engineered; I wrote it down as
//! documentation at https://warehouse.readthedocs.io/api-reference/legacy/#upload-api

use crate::build_context::hash_file;
use anyhow::{bail, Context, Result};
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use bytesize::ByteSize;
use configparser::ini::Ini;
use fs_err as fs;
use fs_err::File;
use multipart::client::lazy::Multipart;
use regex::Regex;
use serde::Deserialize;
use std::collections::HashMap;
use std::env;
#[cfg(any(feature = "native-tls", feature = "rustls"))]
use std::ffi::OsString;
use std::io;
use std::path::{Path, PathBuf};
use std::time::Duration;
use thiserror::Error;
use tracing::debug;

/// An account with a registry, possibly incomplete
#[derive(Debug, clap::Parser)]
pub struct PublishOpt {
    /// The repository (package index) to upload the package to. Should be a section in the config file.
    ///
    /// Can also be set via MATURIN_REPOSITORY environment variable.
    #[arg(short = 'r', long, env = "MATURIN_REPOSITORY", default_value = "pypi")]
    repository: String,
    /// The URL of the registry where the wheels are uploaded to. This overrides --repository.
    ///
    /// Can also be set via MATURIN_REPOSITORY_URL environment variable.
    #[arg(long, env = "MATURIN_REPOSITORY_URL", overrides_with = "repository")]
    repository_url: Option<String>,
    /// Username for pypi or your custom registry.
    ///
    /// Can also be set via MATURIN_USERNAME environment variable.
    ///
    /// Set MATURIN_PYPI_TOKEN variable to use token-based authentication instead
    #[arg(short, long, env = "MATURIN_USERNAME")]
    username: Option<String>,
    /// Password for pypi or your custom registry.
    ///
    /// Can also be set via MATURIN_PASSWORD environment variable.
    #[arg(short, long, env = "MATURIN_PASSWORD", hide_env_values = true)]
    password: Option<String>,
    /// Continue uploading files if one already exists.
    /// (Only valid when uploading to PyPI. Other implementations may not support this.)
    #[arg(long)]
    skip_existing: bool,
    /// Do not interactively prompt for username/password if the required credentials are missing.
    ///
    /// Can also be set via MATURIN_NON_INTERACTIVE environment variable.
    #[arg(long, env = "MATURIN_NON_INTERACTIVE")]
    non_interactive: bool,
}

impl PublishOpt {
    const DEFAULT_REPOSITORY_URL: &'static str = "https://upload.pypi.org/legacy/";
    const TEST_REPOSITORY_URL: &'static str = "https://test.pypi.org/legacy/";

    /// Set to non interactive mode if we're running on CI
    pub fn non_interactive_on_ci(&mut self) {
        if !self.non_interactive && env::var("CI").map(|v| v == "true").unwrap_or_default() {
            eprintln!("🎛️ Running in non-interactive mode on CI");
            self.non_interactive = true;
        }
    }
}

/// Error type for different types of errors that can happen when uploading a
/// wheel.
///
/// The most interesting type is AuthenticationError because it allows asking
/// the user to reenter the password
#[derive(Error, Debug)]
#[error("Uploading to the registry failed")]
pub enum UploadError {
    /// Any ureq error
    #[error("Http error")]
    UreqError(#[source] Box<ureq::Error>),
    /// The registry returned a "403 Forbidden"
    #[error("Username or password are incorrect")]
    AuthenticationError(String),
    /// Reading the wheel failed
    #[error("IO Error")]
    IoError(#[source] io::Error),
    /// The registry returned something else than 200
    #[error("Failed to upload the wheel with status {0}: {1}")]
    StatusCodeError(String, String),
    /// File already exists
    #[error("File already exists: {0}")]
    FileExistsError(String),
    /// Read package metadata error
    #[error("Could not read the metadata from the package at {0}")]
    PkgInfoError(PathBuf, #[source] python_pkginfo::Error),
    /// TLS error
    #[cfg(feature = "native-tls")]
    #[error("TLS Error")]
    TlsError(#[source] native_tls::Error),
}

impl From<io::Error> for UploadError {
    fn from(error: io::Error) -> Self {
        UploadError::IoError(error)
    }
}

impl From<ureq::Error> for UploadError {
    fn from(error: ureq::Error) -> Self {
        UploadError::UreqError(Box::new(error))
    }
}

#[cfg(feature = "native-tls")]
impl From<native_tls::Error> for UploadError {
    fn from(error: native_tls::Error) -> Self {
        UploadError::TlsError(error)
    }
}

/// A pip registry such as pypi or testpypi with associated credentials, used
/// for uploading wheels
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Registry {
    /// The username
    pub username: String,
    /// The password
    pub password: String,
    /// The url endpoint for legacy uploading
    pub url: String,
}

impl Registry {
    /// Creates a new registry
    pub fn new(username: String, password: String, url: String) -> Registry {
        Registry {
            username,
            password,
            url,
        }
    }
}

/// Attempts to fetch the password from the keyring (if enabled)
/// and falls back to the interactive password prompt.
fn get_password(_username: &str) -> String {
    #[cfg(feature = "keyring")]
    {
        let service = env!("CARGO_PKG_NAME");
        let keyring = keyring::Entry::new(service, _username);
        if let Ok(password) = keyring.and_then(|keyring| keyring.get_password()) {
            return password;
        };
    }

    dialoguer::Password::new()
        .with_prompt("Please enter your password")
        .interact()
        .unwrap_or_else(|_| {
            // So we need this fallback for pycharm on windows
            let mut password = String::new();
            io::stdin()
                .read_line(&mut password)
                .expect("Failed to read line");
            password.trim().to_string()
        })
}

fn get_username() -> String {
    eprintln!("Please enter your username:");
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    line.trim().to_string()
}

fn load_pypirc() -> Ini {
    let mut config = Ini::new();
    if let Some(mut config_path) = dirs::home_dir() {
        config_path.push(".pypirc");
        if let Ok(pypirc) = fs::read_to_string(config_path.as_path()) {
            let _ = config.read(pypirc);
        }
    }
    config
}

fn load_pypi_cred_from_config(config: &Ini, registry_name: &str) -> Option<(String, String)> {
    if let (Some(username), Some(password)) = (
        config.get(registry_name, "username"),
        config.get(registry_name, "password"),
    ) {
        return Some((username, password));
    }
    None
}

/// Gets the PyPI credentials from (in precedence order):
///
/// 1. `MATURIN_PYPI_TOKEN` environment variable
/// 2. `.pypirc` config file
/// 3. maturin command arguments
/// 4. `MATURIN_USERNAME` and `MATURIN_PASSWORD` environment variables
/// 5. the password keyring
/// 6. interactive prompt
fn resolve_pypi_cred(
    opt: &PublishOpt,
    config: &Ini,
    registry_name: Option<&str>,
    registry_url: &str,
) -> Result<(String, String)> {
    // API token from environment variable takes priority
    if let Ok(token) = env::var("MATURIN_PYPI_TOKEN") {
        return Ok(("__token__".to_string(), token));
    }

    // Try to get a token via OIDC exchange
    match resolve_pypi_token_via_oidc(registry_url) {
        Ok(Some(token)) => {
            eprintln!("🔐 Using trusted publisher for upload");
            return Ok(("__token__".to_string(), token));
        }
        Ok(None) => {}
        Err(e) => eprintln!("⚠️ Warning: Failed to resolve PyPI token via OIDC: {}", e),
    }

    if let Some((username, password)) =
        registry_name.and_then(|name| load_pypi_cred_from_config(config, name))
    {
        eprintln!("🔐 Using credential in pypirc for upload");
        return Ok((username, password));
    }

    // fallback to username and password
    if opt.non_interactive && (opt.username.is_none() || opt.password.is_none()) {
        bail!("Credentials not found and non-interactive mode is enabled");
    }
    let username = opt.username.clone().unwrap_or_else(get_username);
    let password = opt
        .password
        .clone()
        .unwrap_or_else(|| get_password(&username));
    Ok((username, password))
}

#[derive(Debug, Deserialize)]
struct OidcAudienceResponse {
    audience: String,
}

#[derive(Debug, Deserialize)]
struct OidcTokenResponse {
    value: String,
}

#[derive(Debug, Deserialize)]
struct MintTokenResponse {
    token: String,
}

/// Trusted Publisher support for GitHub Actions
fn resolve_pypi_token_via_oidc(registry_url: &str) -> Result<Option<String>> {
    if env::var_os("GITHUB_ACTIONS").is_none() {
        return Ok(None);
    }
    if let (Ok(req_token), Ok(req_url)) = (
        env::var("ACTIONS_ID_TOKEN_REQUEST_TOKEN"),
        env::var("ACTIONS_ID_TOKEN_REQUEST_URL"),
    ) {
        let registry_url = url::Url::parse(registry_url)?;
        let mut audience_url = registry_url.clone();
        audience_url.set_path("_/oidc/audience");
        debug!("Requesting OIDC audience from {}", audience_url);
        let agent = http_agent()?;
        let audience_res = agent
            .get(audience_url.as_str())
            .timeout(Duration::from_secs(30))
            .call()?;
        if audience_res.status() == 404 {
            // OIDC is not enabled/supported on this registry
            return Ok(None);
        }
        let audience = audience_res.into_json::<OidcAudienceResponse>()?.audience;

        debug!("Requesting OIDC token for {} from {}", audience, req_url);
        let request_token_res: OidcTokenResponse = agent
            .get(&req_url)
            .query("audience", &audience)
            .set("Authorization", &format!("bearer {req_token}"))
            .timeout(Duration::from_secs(30))
            .call()?
            .into_json()?;
        let oidc_token = request_token_res.value;

        let mut mint_token_url = registry_url;
        mint_token_url.set_path("_/oidc/github/mint-token");
        debug!("Requesting API token from {}", mint_token_url);
        let mut mint_token_req = HashMap::new();
        mint_token_req.insert("token", oidc_token);
        let mint_token_res = agent
            .post(mint_token_url.as_str())
            .timeout(Duration::from_secs(30))
            .send_json(mint_token_req)?
            .into_json::<MintTokenResponse>()?;
        return Ok(Some(mint_token_res.token));
    }
    Ok(None)
}

/// Asks for username and password for a registry account where missing.
fn complete_registry(opt: &PublishOpt) -> Result<Registry> {
    // load creds from pypirc if found
    let pypirc = load_pypirc();
    let (registry_name, registry_url) = if let Some(repository_url) = opt.repository_url.as_deref()
    {
        let name = match repository_url {
            PublishOpt::DEFAULT_REPOSITORY_URL => Some("pypi"),
            PublishOpt::TEST_REPOSITORY_URL => Some("testpypi"),
            _ => None,
        };
        (name, repository_url.to_string())
    } else if let Some(url) = pypirc.get(&opt.repository, "repository") {
        (Some(opt.repository.as_str()), url)
    } else if opt.repository == "pypi" {
        (Some("pypi"), PublishOpt::DEFAULT_REPOSITORY_URL.to_string())
    } else if opt.repository == "testpypi" {
        (
            Some("testpypi"),
            PublishOpt::TEST_REPOSITORY_URL.to_string(),
        )
    } else {
        bail!(
            "Failed to get registry {} in .pypirc. \
                Note: Your index didn't start with http:// or https://, \
                which is required for non-pypirc indices.",
            opt.repository
        );
    };
    let (username, password) = resolve_pypi_cred(opt, &pypirc, registry_name, &registry_url)?;
    let registry = Registry::new(username, password, registry_url);

    Ok(registry)
}

/// Port of pip's `canonicalize_name`
/// https://github.com/pypa/pip/blob/b33e791742570215f15663410c3ed987d2253d5b/src/pip/_vendor/packaging/utils.py#L18-L25
fn canonicalize_name(name: &str) -> String {
    Regex::new("[-_.]+")
        .unwrap()
        .replace_all(name, "-")
        .to_lowercase()
}

#[cfg(any(feature = "native-tls", feature = "rustls"))]
fn tls_ca_bundle() -> Option<OsString> {
    env::var_os("MATURIN_CA_BUNDLE")
        .or_else(|| env::var_os("REQUESTS_CA_BUNDLE"))
        .or_else(|| env::var_os("CURL_CA_BUNDLE"))
}

// Prefer rustls if both native-tls and rustls features are enabled
#[cfg(all(feature = "native-tls", not(feature = "rustls")))]
#[allow(clippy::result_large_err)]
fn http_agent() -> Result<ureq::Agent, UploadError> {
    use std::sync::Arc;

    let mut builder = ureq::builder().try_proxy_from_env(true);
    let mut tls_builder = native_tls::TlsConnector::builder();
    if let Some(ca_bundle) = tls_ca_bundle() {
        let mut reader = io::BufReader::new(File::open(ca_bundle)?);
        for cert in rustls_pemfile::certs(&mut reader) {
            let cert = cert?;
            tls_builder.add_root_certificate(native_tls::Certificate::from_pem(&cert)?);
        }
    }
    builder = builder.tls_connector(Arc::new(tls_builder.build()?));
    Ok(builder.build())
}

#[cfg(feature = "rustls")]
#[allow(clippy::result_large_err)]
fn http_agent() -> Result<ureq::Agent, UploadError> {
    use std::sync::Arc;

    let builder = ureq::builder().try_proxy_from_env(true);
    if let Some(ca_bundle) = tls_ca_bundle() {
        let mut reader = io::BufReader::new(File::open(ca_bundle)?);
        let certs = rustls_pemfile::certs(&mut reader).collect::<Result<Vec<_>, _>>()?;
        let mut root_certs = rustls::RootCertStore::empty();
        root_certs.add_parsable_certificates(certs);
        let client_config = rustls::ClientConfig::builder()
            .with_root_certificates(root_certs)
            .with_no_client_auth();
        Ok(builder.tls_config(Arc::new(client_config)).build())
    } else {
        Ok(builder.build())
    }
}

#[cfg(not(any(feature = "native-tls", feature = "rustls")))]
#[allow(clippy::result_large_err)]
fn http_agent() -> Result<ureq::Agent, UploadError> {
    let builder = ureq::builder().try_proxy_from_env(true);
    Ok(builder.build())
}

/// Uploads a single wheel to the registry
#[allow(clippy::result_large_err)]
pub fn upload(registry: &Registry, wheel_path: &Path) -> Result<(), UploadError> {
    let hash_hex = hash_file(wheel_path)?;

    let dist = python_pkginfo::Distribution::new(wheel_path)
        .map_err(|err| UploadError::PkgInfoError(wheel_path.to_owned(), err))?;
    let metadata = dist.metadata();

    let mut api_metadata = vec![
        (":action", "file_upload".to_string()),
        ("sha256_digest", hash_hex),
        ("protocol_version", "1".to_string()),
        ("metadata_version", metadata.metadata_version.clone()),
        ("name", canonicalize_name(&metadata.name)),
        ("version", metadata.version.clone()),
        ("pyversion", dist.python_version().to_string()),
        ("filetype", dist.r#type().to_string()),
    ];

    let mut add_option = |name, value: &Option<String>| {
        if let Some(some) = value.clone() {
            api_metadata.push((name, some));
        }
    };

    // https://github.com/pypa/warehouse/blob/75061540e6ab5aae3f8758b569e926b6355abea8/warehouse/forklift/legacy.py#L424
    add_option("summary", &metadata.summary);
    add_option("description", &metadata.description);
    add_option(
        "description_content_type",
        &metadata.description_content_type,
    );
    add_option("author", &metadata.author);
    add_option("author_email", &metadata.author_email);
    add_option("maintainer", &metadata.maintainer);
    add_option("maintainer_email", &metadata.maintainer_email);
    add_option("license", &metadata.license);
    add_option("keywords", &metadata.keywords);
    add_option("home_page", &metadata.home_page);
    add_option("download_url", &metadata.download_url);
    add_option("requires_python", &metadata.requires_python);

    if metadata.requires_python.is_none() {
        // GitLab PyPI repository API implementation requires this metadata field
        // and twine always includes it in the request, even when it's empty.
        api_metadata.push(("requires_python", "".to_string()));
    }

    let mut add_vec = |name, values: &[String]| {
        for i in values {
            api_metadata.push((name, i.clone()));
        }
    };

    add_vec("classifiers", &metadata.classifiers);
    add_vec("platform", &metadata.platforms);
    add_vec("requires_dist", &metadata.requires_dist);
    add_vec("provides_dist", &metadata.provides_dist);
    add_vec("obsoletes_dist", &metadata.obsoletes_dist);
    add_vec("requires_external", &metadata.requires_external);
    add_vec("project_urls", &metadata.project_urls);

    let wheel = File::open(wheel_path)?;
    let wheel_name = wheel_path
        .file_name()
        .expect("Wheel path has a file name")
        .to_string_lossy();

    let mut form = Multipart::new();
    for (key, value) in api_metadata {
        form.add_text(key, value);
    }

    form.add_stream("content", &wheel, Some(wheel_name), None);
    let multipart_data = form.prepare().map_err(|e| e.error)?;
    let encoded = STANDARD.encode(format!("{}:{}", registry.username, registry.password));

    let agent = http_agent()?;

    let response = agent
        .post(registry.url.as_str())
        .set(
            "Content-Type",
            &format!(
                "multipart/form-data; boundary={}",
                multipart_data.boundary()
            ),
        )
        .set(
            "User-Agent",
            &format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")),
        )
        .set("Authorization", &format!("Basic {encoded}"))
        .send(multipart_data);

    match response {
        Ok(_) => Ok(()),
        Err(ureq::Error::Status(status, response)) => {
            let err_text = response.into_string().unwrap_or_else(|e| {
                format!(
                    "The registry should return some text, \
                    even in case of an error, but didn't ({e})"
                )
            });
            debug!("Upload error response: {}", err_text);
            // Detect FileExistsError the way twine does
            // https://github.com/pypa/twine/blob/87846e5777b380d4704704a69e1f9a7a1231451c/twine/commands/upload.py#L30
            if status == 403 {
                if err_text.contains("overwrite artifact") {
                    // Artifactory (https://jfrog.com/artifactory/)
                    Err(UploadError::FileExistsError(err_text))
                } else {
                    Err(UploadError::AuthenticationError(err_text))
                }
            } else {
                let status_string = status.to_string();
                if status == 409 // conflict, pypiserver (https://pypi.org/project/pypiserver)
            // PyPI / TestPyPI
            || (status == 400 && err_text.contains("already exists"))
            // Nexus Repository OSS (https://www.sonatype.com/nexus-repository-oss)
            || (status == 400 && err_text.contains("updating asset"))
            // # Gitlab Enterprise Edition (https://about.gitlab.com)
            || (status == 400 && err_text.contains("already been taken"))
                {
                    Err(UploadError::FileExistsError(err_text))
                } else {
                    Err(UploadError::StatusCodeError(status_string, err_text))
                }
            }
        }
        Err(err) => Err(UploadError::UreqError(err.into())),
    }
}

/// Handles authentication/keyring integration and retrying of the publish subcommand
pub fn upload_ui(items: &[PathBuf], publish: &PublishOpt) -> Result<()> {
    let registry = complete_registry(publish)?;

    eprintln!("🚀 Uploading {} packages", items.len());

    for i in items {
        let upload_result = upload(&registry, i);

        match upload_result {
            Ok(()) => (),
            Err(UploadError::AuthenticationError(msg)) => {
                let title_re = regex::Regex::new(r"<title>(.+?)</title>").unwrap();
                let title = title_re
                    .captures(&msg)
                    .and_then(|c| c.get(1))
                    .map(|m| m.as_str());
                match title {
                    Some(title) => {
                        eprintln!("⛔ {title}");
                    }
                    None => eprintln!("⛔ Username and/or password are wrong"),
                }

                #[cfg(feature = "keyring")]
                {
                    // Delete the wrong password from the keyring
                    let old_username = registry.username;
                    match keyring::Entry::new(env!("CARGO_PKG_NAME"), &old_username)
                        .and_then(|keyring| keyring.delete_password())
                    {
                        Ok(()) => {
                            eprintln!("🔑 Removed wrong password from keyring")
                        }
                        Err(keyring::Error::NoEntry)
                        | Err(keyring::Error::NoStorageAccess(_))
                        | Err(keyring::Error::PlatformFailure(_)) => {}
                        Err(err) => {
                            eprintln!("⚠️ Warning: Failed to remove password from keyring: {err}")
                        }
                    }
                }

                bail!("Username and/or password are possibly wrong");
            }
            Err(err) => {
                let filename = i.file_name().unwrap_or(i.as_os_str());
                if let UploadError::FileExistsError(_) = err {
                    if publish.skip_existing {
                        eprintln!(
                            "⚠️ Note: Skipping {filename:?} because it appears to already exist"
                        );
                        continue;
                    }
                }
                let filesize = fs::metadata(i)
                    .map(|x| ByteSize(x.len()).to_string())
                    .unwrap_or_else(|e| format!("Failed to get the filesize of {:?}: {}", &i, e));
                return Err(err).context(format!("💥 Failed to upload {filename:?} ({filesize})"));
            }
        }
    }

    eprintln!("✨ Packages uploaded successfully");

    #[cfg(feature = "keyring")]
    {
        // We know the password is correct, so we can save it in the keyring
        let username = registry.username.clone();
        let password = registry.password;
        match keyring::Entry::new(env!("CARGO_PKG_NAME"), &username)
            .and_then(|keyring| keyring.set_password(&password))
        {
            Ok(())
            | Err(keyring::Error::NoStorageAccess(_))
            | Err(keyring::Error::PlatformFailure(_)) => {}
            Err(err) => {
                eprintln!("⚠️ Warning: Failed to store the password in the keyring: {err:?}");
            }
        }
    }

    Ok(())
}