pkgctl/
args.rs

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
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use argh::FromArgs;
use fidl_fuchsia_pkg_ext::BlobId;
use fidl_fuchsia_pkg_rewrite_ext::RuleConfig;
use std::path::PathBuf;

#[derive(FromArgs, Debug, PartialEq)]
/// Various operations on packages, package repositories, and the package cache.
pub struct Args {
    #[argh(subcommand)]
    pub command: Command,
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand)]
pub enum Command {
    Resolve(ResolveCommand),
    Open(OpenCommand),
    Repo(RepoCommand),
    Rule(RuleCommand),
    Gc(GcCommand),
    GetHash(GetHashCommand),
    PkgStatus(PkgStatusCommand),
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "resolve")]
/// Resolve a package.
pub struct ResolveCommand {
    #[argh(positional)]
    pub pkg_url: String,

    /// prints the contents of the resolved package, which can be slow for large packages.
    #[argh(switch, short = 'v')]
    pub verbose: bool,
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "open")]
/// Open a package by merkle root.
pub struct OpenCommand {
    #[argh(positional)]
    pub meta_far_blob_id: BlobId,
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(
    subcommand,
    name = "repo",
    note = "A fuchsia package URL contains a repository hostname to identify the package's source.\n",
    note = "Without any arguments the command outputs the list of configured repository URLs.\n",
    note = "Note that repo commands expect the full repository URL, not just the hostname, e.g:",
    note = "$ pkgctl repo rm fuchsia-pkg://example.com"
)]
/// Manage one or more known repositories.
pub struct RepoCommand {
    /// verbose output
    #[argh(switch, short = 'v')]
    pub verbose: bool,

    #[argh(subcommand)]
    pub subcommand: Option<RepoSubCommand>,
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand)]
pub enum RepoSubCommand {
    Add(RepoAddCommand),
    Remove(RepoRemoveCommand),
    Show(RepoShowCommand),
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "add")]
/// Add a source repository.
pub struct RepoAddCommand {
    #[argh(subcommand)]
    pub subcommand: RepoAddSubCommand,
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand)]
pub enum RepoAddSubCommand {
    File(RepoAddFileCommand),
    Url(RepoAddUrlCommand),
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "file")]
/// Add a repository config from a local file, in JSON format, which contains the different repository metadata and URLs.
pub struct RepoAddFileCommand {
    /// persist TUF metadata for repositories provided to the RepoManager.
    #[argh(switch, short = 'p')]
    pub persist: bool,
    /// name of the source (a name from the URL will be derived if not provided).
    #[argh(option, short = 'n')]
    pub name: Option<String>,
    /// repository config file, in JSON format, which contains the different repository metadata and URLs.
    #[argh(positional)]
    pub file: PathBuf,
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "url")]
/// Add a repository config via http, in JSON format, which contains the different repository metadata and URLs.
pub struct RepoAddUrlCommand {
    /// persist TUF metadata for repositories provided to the RepoManager.
    #[argh(switch, short = 'p')]
    pub persist: bool,
    /// name of the source (a name from the URL will be derived if not provided).
    #[argh(option, short = 'n')]
    pub name: Option<String>,
    /// http(s) URL pointing to a repository config file, in JSON format, which contains the different repository metadata and URLs.
    #[argh(positional)]
    pub repo_url: String,
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "rm")]
/// Remove a configured source repository.
pub struct RepoRemoveCommand {
    #[argh(positional)]
    pub repo_url: String,
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "show")]
/// Show JSON-formatted details of a configured source repository.
pub struct RepoShowCommand {
    #[argh(positional)]
    pub repo_url: String,
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "rule")]
/// Manage URL rewrite rules applied to package URLs during package resolution.
pub struct RuleCommand {
    #[argh(subcommand)]
    pub subcommand: RuleSubCommand,
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand)]
pub enum RuleSubCommand {
    Clear(RuleClearCommand),
    DumpDynamic(RuleDumpDynamicCommand),
    List(RuleListCommand),
    Replace(RuleReplaceCommand),
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "clear")]
/// Clear all URL rewrite rules.
pub struct RuleClearCommand {}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "list")]
/// List all URL rewrite rules.
pub struct RuleListCommand {}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "dump-dynamic")]
/// Dumps all dynamic rewrite rules.
pub struct RuleDumpDynamicCommand {}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "replace")]
/// Replace all dynamic rules with the provided rules.
pub struct RuleReplaceCommand {
    #[argh(subcommand)]
    pub subcommand: RuleReplaceSubCommand,
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand)]
pub enum RuleReplaceSubCommand {
    File(RuleReplaceFileCommand),
    Json(RuleReplaceJsonCommand),
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "file")]
/// Replace all rewrite rules with ones specified in a file
pub struct RuleReplaceFileCommand {
    #[argh(positional)]
    pub file: PathBuf,
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "json")]
/// Replace all rewrite rules with JSON from the command line
pub struct RuleReplaceJsonCommand {
    #[argh(positional, from_str_fn(parse_rule_config))]
    pub config: RuleConfig,
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(
    subcommand,
    name = "gc",
    note = "This deletes any cached packages that are not present in the static and dynamic index.",
    note = "Any blobs associated with these packages will be removed if they are not referenced by another component or package.",
    note = "The static index currently is located at /system/data/static_packages, but this location is likely to change.",
    note = "The dynamic index is dynamically calculated, and cannot easily be queried at this time."
)]
/// Trigger a manual garbage collection of the package cache.
pub struct GcCommand {}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "get-hash")]
/// Get the hash of a package.
pub struct GetHashCommand {
    #[argh(positional)]
    pub pkg_url: String,
}

#[derive(FromArgs, Debug, PartialEq)]
#[argh(
    subcommand,
    name = "pkg-status",
    note = "Exit codes:",
    note = "    0 - pkg in tuf repo and on disk",
    note = "    2 - pkg in tuf repo but not on disk",
    note = "    3 - pkg not in tuf repo",
    note = "    1 - any other misc application error"
)]
/// Determine if a pkg is in a registered tuf repo and/or on disk.
pub struct PkgStatusCommand {
    #[argh(positional)]
    pub pkg_url: String,
}

fn parse_rule_config(config: &str) -> Result<RuleConfig, String> {
    serde_json::from_str(config).map_err(|e| e.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use assert_matches::assert_matches;

    const REPO_URL: &str = "fuchsia-pkg://fuchsia.com";
    const CONFIG_JSON: &str = r#"{"version": "1", "content": []}"#;
    const CMD_NAME: &[&str] = &["pkgctl"];

    #[test]
    fn resolve() {
        fn check(args: &[&str], expected_pkg_url: &str, expected_verbose: bool) {
            assert_eq!(
                Args::from_args(CMD_NAME, args),
                Ok(Args {
                    command: Command::Resolve(ResolveCommand {
                        pkg_url: expected_pkg_url.to_string(),
                        verbose: expected_verbose,
                    })
                })
            );
        }

        let url = "fuchsia-pkg://fuchsia.com/foo/bar";

        check(&["resolve", url], url, false);
        check(&["resolve", "--verbose", url], url, true);
        check(&["resolve", "-v", url], url, true);
    }

    #[test]
    fn open() {
        fn check(args: &[&str], expected_blob_id: &str) {
            assert_eq!(
                Args::from_args(CMD_NAME, args),
                Ok(Args {
                    command: Command::Open(OpenCommand {
                        meta_far_blob_id: expected_blob_id.parse().unwrap(),
                    })
                })
            )
        }

        let blob_id = "1111111111111111111111111111111111111111111111111111111111111111";
        check(&["open", blob_id], blob_id);

        check(&["open", blob_id], blob_id);
    }

    #[test]
    fn open_reject_malformed_blobs() {
        match Args::from_args(CMD_NAME, &["open", "bad_id"]) {
            Err(argh::EarlyExit { output: _, status: _ }) => {}
            result => panic!("unexpected result {result:?}"),
        }
    }

    #[test]
    fn repo() {
        fn check(args: &[&str], expected: RepoCommand) {
            assert_eq!(
                Args::from_args(CMD_NAME, args),
                Ok(Args { command: Command::Repo(expected) })
            )
        }

        check(&["repo"], RepoCommand { verbose: false, subcommand: None });
        check(&["repo", "-v"], RepoCommand { verbose: true, subcommand: None });
        check(&["repo", "--verbose"], RepoCommand { verbose: true, subcommand: None });
        check(
            &["repo", "add", "file", "foo"],
            RepoCommand {
                verbose: false,
                subcommand: Some(RepoSubCommand::Add(RepoAddCommand {
                    subcommand: RepoAddSubCommand::File(RepoAddFileCommand {
                        persist: false,
                        name: None,
                        file: "foo".into(),
                    }),
                })),
            },
        );
        check(
            &["repo", "add", "file", "-p", "foo"],
            RepoCommand {
                verbose: false,
                subcommand: Some(RepoSubCommand::Add(RepoAddCommand {
                    subcommand: RepoAddSubCommand::File(RepoAddFileCommand {
                        persist: true,
                        name: None,
                        file: "foo".into(),
                    }),
                })),
            },
        );
        check(
            &["repo", "add", "file", "-n", "devhost", "foo"],
            RepoCommand {
                verbose: false,
                subcommand: Some(RepoSubCommand::Add(RepoAddCommand {
                    subcommand: RepoAddSubCommand::File(RepoAddFileCommand {
                        persist: false,
                        name: Some("devhost".to_string()),
                        file: "foo".into(),
                    }),
                })),
            },
        );
        check(
            &["repo", "add", "url", "-n", "devhost", "http://foo.tld/fuchsia/config.json"],
            RepoCommand {
                verbose: false,
                subcommand: Some(RepoSubCommand::Add(RepoAddCommand {
                    subcommand: RepoAddSubCommand::Url(RepoAddUrlCommand {
                        persist: false,
                        name: Some("devhost".to_string()),
                        repo_url: "http://foo.tld/fuchsia/config.json".into(),
                    }),
                })),
            },
        );
        check(
            &["repo", "add", "url", "-p", "-n", "devhost", "http://foo.tld/fuchsia/config.json"],
            RepoCommand {
                verbose: false,
                subcommand: Some(RepoSubCommand::Add(RepoAddCommand {
                    subcommand: RepoAddSubCommand::Url(RepoAddUrlCommand {
                        persist: true,
                        name: Some("devhost".to_string()),
                        repo_url: "http://foo.tld/fuchsia/config.json".into(),
                    }),
                })),
            },
        );
        check(
            &["repo", "add", "url", "-p", "-n", "devhost", "http://foo.tld/fuchsia/config.json"],
            RepoCommand {
                verbose: false,
                subcommand: Some(RepoSubCommand::Add(RepoAddCommand {
                    subcommand: RepoAddSubCommand::Url(RepoAddUrlCommand {
                        persist: true,
                        name: Some("devhost".to_string()),
                        repo_url: "http://foo.tld/fuchsia/config.json".into(),
                    }),
                })),
            },
        );
        check(
            &["repo", "rm", REPO_URL],
            RepoCommand {
                verbose: false,
                subcommand: Some(RepoSubCommand::Remove(RepoRemoveCommand {
                    repo_url: REPO_URL.to_string(),
                })),
            },
        );
        check(
            &["repo", "show", REPO_URL],
            RepoCommand {
                verbose: false,
                subcommand: Some(RepoSubCommand::Show(RepoShowCommand {
                    repo_url: REPO_URL.to_string(),
                })),
            },
        );
    }

    #[test]
    fn rule() {
        fn check(args: &[&str], expected: RuleCommand) {
            match Args::from_args(CMD_NAME, args).unwrap() {
                Args { command: Command::Rule(cmd) } => {
                    assert_eq!(cmd, expected);
                }
                result => panic!("unexpected result {result:?}"),
            }
        }

        check(
            &["rule", "list"],
            RuleCommand { subcommand: RuleSubCommand::List(RuleListCommand {}) },
        );
        check(
            &["rule", "clear"],
            RuleCommand { subcommand: RuleSubCommand::Clear(RuleClearCommand {}) },
        );
        check(
            &["rule", "dump-dynamic"],
            RuleCommand { subcommand: RuleSubCommand::DumpDynamic(RuleDumpDynamicCommand {}) },
        );
        check(
            &["rule", "replace", "file", "foo"],
            RuleCommand {
                subcommand: RuleSubCommand::Replace(RuleReplaceCommand {
                    subcommand: RuleReplaceSubCommand::File(RuleReplaceFileCommand {
                        file: "foo".into(),
                    }),
                }),
            },
        );
        check(
            &["rule", "replace", "json", CONFIG_JSON],
            RuleCommand {
                subcommand: RuleSubCommand::Replace(RuleReplaceCommand {
                    subcommand: RuleReplaceSubCommand::Json(RuleReplaceJsonCommand {
                        config: RuleConfig::Version1(vec![]),
                    }),
                }),
            },
        );
    }

    #[test]
    fn rule_replace_json_rejects_malformed_json() {
        assert_matches!(
            Args::from_args(CMD_NAME, &["rule", "replace", "json", "{"]),
            Err(argh::EarlyExit { output: _, status: _ })
        );
    }

    #[test]
    fn gc() {
        match Args::from_args(CMD_NAME, &["gc"]).unwrap() {
            Args { command: Command::Gc(GcCommand {}) } => {}
            result => panic!("unexpected result {result:?}"),
        }
    }

    #[test]
    fn get_hash() {
        let url = "fuchsia-pkg://fuchsia.com/foo/bar";
        match Args::from_args(CMD_NAME, &["get-hash", url]).unwrap() {
            Args { command: Command::GetHash(GetHashCommand { pkg_url }) } if pkg_url == url => {}
            result => panic!("unexpected result {result:?}"),
        }
    }

    #[test]
    fn pkg_status() {
        let url = "fuchsia-pkg://fuchsia.com/foo/bar";
        match Args::from_args(CMD_NAME, &["pkg-status", url]).unwrap() {
            Args { command: Command::PkgStatus(PkgStatusCommand { pkg_url }) }
                if pkg_url == url => {}
            result => panic!("unexpected result {result:?}"),
        }
    }
}