Validate the limit argument

This commit is contained in:
Aleksey Kladov 2018-03-10 17:42:08 +03:00
parent c180e17666
commit 823f1ff32a
4 changed files with 18 additions and 15 deletions

View file

@ -442,8 +442,7 @@ fn execute_subcommand(config: &mut Config, args: ArgMatches) -> CliResult {
("search", Some(args)) => {
let registry = args.registry(config)?;
let index = args.index(config)?;
let limit: Option<u8> = args.value_of("limit")
.and_then(|v| v.parse().ok()); //FIXME: validation
let limit = args.value_of_u32("limit")?;
let limit = min(100, limit.unwrap_or(10));
let query: Vec<&str> = args.values_of("query").unwrap_or_default().collect();
let query: String = query.join("+");

View file

@ -171,6 +171,18 @@ pub fn subcommand(name: &'static str) -> App {
pub trait ArgMatchesExt {
fn value_of_u32(&self, name: &str) -> CargoResult<Option<u32>> {
let arg = match self._value_of(name) {
None => None,
Some(arg) => Some(arg.parse::<u32>().map_err(|_| {
clap::Error::value_validation_auto(
format!("could not parse `{}` as a number", arg)
)
})?)
};
Ok(arg)
}
fn root_manifest(&self, config: &Config) -> CargoResult<PathBuf> {
let manifest_path = self._value_of("manifest-path");
find_root_manifest_for_wd(manifest_path, config.cwd())
@ -182,15 +194,7 @@ pub trait ArgMatchesExt {
}
fn jobs(&self) -> CargoResult<Option<u32>> {
let jobs = match self._value_of("jobs") {
None => None,
Some(jobs) => Some(jobs.parse::<u32>().map_err(|_| {
clap::Error::value_validation_auto(
format!("could not parse `{}` as a number", jobs)
)
})?)
};
Ok(jobs)
self.value_of_u32("jobs")
}
fn target(&self) -> Option<String> {

View file

@ -486,7 +486,7 @@ pub fn yank(config: &Config,
pub fn search(query: &str,
config: &Config,
index: Option<String>,
limit: u8,
limit: u32,
reg: Option<String>) -> CargoResult<()> {
fn truncate_with_ellipsis(s: &str, max_width: usize) -> String {
// We should truncate at grapheme-boundary and compute character-widths,

View file

@ -202,10 +202,10 @@ impl Registry {
})
}
pub fn search(&mut self, query: &str, limit: u8) -> Result<(Vec<Crate>, u32)> {
let formated_query = percent_encode(query.as_bytes(), QUERY_ENCODE_SET);
pub fn search(&mut self, query: &str, limit: u32) -> Result<(Vec<Crate>, u32)> {
let formatted_query = percent_encode(query.as_bytes(), QUERY_ENCODE_SET);
let body = self.req(
format!("/crates?q={}&per_page={}", formated_query, limit),
format!("/crates?q={}&per_page={}", formatted_query, limit),
None, Auth::Unauthorized
)?;