gr/
remote.rs

1use std::fmt::{self, Display, Formatter};
2use std::fs::File;
3use std::path::{Path, PathBuf};
4
5use crate::api_traits::{
6    Cicd, CicdJob, CicdRunner, CodeGist, CommentMergeRequest, ContainerRegistry, Deploy,
7    DeployAsset, MergeRequest, ProjectMember, RemoteProject, RemoteTag, TrendingProjectURL,
8    UserInfo,
9};
10use crate::cache::{filesystem::FileCache, nocache::NoCache};
11use crate::config::{env_token, ConfigFile, NoConfig};
12use crate::display::Format;
13use crate::error::GRError;
14use crate::github::Github;
15use crate::gitlab::Gitlab;
16use crate::io::{CmdInfo, HttpResponse, HttpRunner, ShellResponse, TaskRunner};
17use crate::time::Milliseconds;
18use crate::{cli, error, get_default_config_path, http, log_debug, log_info};
19use crate::{git, Result};
20use std::sync::Arc;
21
22pub mod query;
23
24/// List cli args can be used across multiple APIs that support pagination.
25#[derive(Builder, Clone)]
26pub struct ListRemoteCliArgs {
27    #[builder(default)]
28    pub from_page: Option<i64>,
29    #[builder(default)]
30    pub to_page: Option<i64>,
31    #[builder(default)]
32    pub num_pages: bool,
33    #[builder(default)]
34    pub num_resources: bool,
35    #[builder(default)]
36    pub page_number: Option<i64>,
37    #[builder(default)]
38    pub created_after: Option<String>,
39    #[builder(default)]
40    pub created_before: Option<String>,
41    #[builder(default)]
42    pub sort: ListSortMode,
43    #[builder(default)]
44    pub flush: bool,
45    #[builder(default)]
46    pub throttle_time: Option<Milliseconds>,
47    #[builder(default)]
48    pub throttle_range: Option<(Milliseconds, Milliseconds)>,
49    #[builder(default)]
50    pub get_args: GetRemoteCliArgs,
51}
52
53impl ListRemoteCliArgs {
54    pub fn builder() -> ListRemoteCliArgsBuilder {
55        ListRemoteCliArgsBuilder::default()
56    }
57}
58
59#[derive(Builder, Clone, Default)]
60pub struct GetRemoteCliArgs {
61    #[builder(default)]
62    pub no_headers: bool,
63    #[builder(default)]
64    pub format: Format,
65    #[builder(default)]
66    pub cache_args: CacheCliArgs,
67    #[builder(default)]
68    pub display_optional: bool,
69    #[builder(default)]
70    pub backoff_max_retries: u32,
71    #[builder(default)]
72    pub backoff_retry_after: u64,
73}
74
75impl GetRemoteCliArgs {
76    pub fn builder() -> GetRemoteCliArgsBuilder {
77        GetRemoteCliArgsBuilder::default()
78    }
79}
80
81#[derive(Builder, Clone, Default)]
82pub struct CacheCliArgs {
83    #[builder(default)]
84    pub refresh: bool,
85    #[builder(default)]
86    pub no_cache: bool,
87}
88
89impl CacheCliArgs {
90    pub fn builder() -> CacheCliArgsBuilder {
91        CacheCliArgsBuilder::default()
92    }
93}
94
95/// List body args is a common structure that can be used across multiple APIs
96/// that support pagination. `list` operations in traits that accept some sort
97/// of List related arguments can encapsulate this structure. Example of those
98/// is `MergeRequestListBodyArgs`. This can be consumed by Github and Gitlab
99/// clients when executing HTTP requests.
100#[derive(Builder, Clone)]
101pub struct ListBodyArgs {
102    #[builder(setter(strip_option), default)]
103    pub page: Option<i64>,
104    #[builder(setter(strip_option), default)]
105    pub max_pages: Option<i64>,
106    #[builder(default)]
107    pub created_after: Option<String>,
108    #[builder(default)]
109    pub created_before: Option<String>,
110    #[builder(default)]
111    pub sort_mode: ListSortMode,
112    #[builder(default)]
113    pub flush: bool,
114    #[builder(default)]
115    pub throttle_time: Option<Milliseconds>,
116    #[builder(default)]
117    pub throttle_range: Option<(Milliseconds, Milliseconds)>,
118    // Carry display format for flush operations
119    #[builder(default)]
120    pub get_args: GetRemoteCliArgs,
121}
122
123impl ListBodyArgs {
124    pub fn builder() -> ListBodyArgsBuilder {
125        ListBodyArgsBuilder::default()
126    }
127}
128
129pub fn validate_from_to_page(remote_cli_args: &ListRemoteCliArgs) -> Result<Option<ListBodyArgs>> {
130    if remote_cli_args.page_number.is_some() {
131        return Ok(Some(
132            ListBodyArgs::builder()
133                .page(remote_cli_args.page_number.unwrap())
134                .max_pages(1)
135                .sort_mode(remote_cli_args.sort.clone())
136                .created_after(remote_cli_args.created_after.clone())
137                .created_before(remote_cli_args.created_before.clone())
138                .build()
139                .unwrap(),
140        ));
141    }
142    // TODO - this can probably be validated at the CLI level
143    let body_args = match (remote_cli_args.from_page, remote_cli_args.to_page) {
144        (Some(from_page), Some(to_page)) => {
145            if from_page < 0 || to_page < 0 {
146                return Err(GRError::PreconditionNotMet(
147                    "from_page and to_page must be a positive number".to_string(),
148                )
149                .into());
150            }
151            if from_page >= to_page {
152                return Err(GRError::PreconditionNotMet(
153                    "from_page must be less than to_page".to_string(),
154                )
155                .into());
156            }
157
158            let max_pages = to_page - from_page + 1;
159            Some(
160                ListBodyArgs::builder()
161                    .page(from_page)
162                    .max_pages(max_pages)
163                    .sort_mode(remote_cli_args.sort.clone())
164                    .flush(remote_cli_args.flush)
165                    .throttle_time(remote_cli_args.throttle_time)
166                    .throttle_range(remote_cli_args.throttle_range)
167                    .get_args(remote_cli_args.get_args.clone())
168                    .build()
169                    .unwrap(),
170            )
171        }
172        (Some(_), None) => {
173            return Err(
174                GRError::PreconditionNotMet("from_page requires the to_page".to_string()).into(),
175            );
176        }
177        (None, Some(to_page)) => {
178            if to_page < 0 {
179                return Err(GRError::PreconditionNotMet(
180                    "to_page must be a positive number".to_string(),
181                )
182                .into());
183            }
184            Some(
185                ListBodyArgs::builder()
186                    .page(1)
187                    .max_pages(to_page)
188                    .sort_mode(remote_cli_args.sort.clone())
189                    .flush(remote_cli_args.flush)
190                    .throttle_time(remote_cli_args.throttle_time)
191                    .throttle_range(remote_cli_args.throttle_range)
192                    .get_args(remote_cli_args.get_args.clone())
193                    .build()
194                    .unwrap(),
195            )
196        }
197        (None, None) => None,
198    };
199    match (
200        remote_cli_args.created_after.clone(),
201        remote_cli_args.created_before.clone(),
202    ) {
203        (Some(created_after), Some(created_before)) => {
204            if let Some(body_args) = &body_args {
205                return Ok(Some(
206                    ListBodyArgs::builder()
207                        .page(body_args.page.unwrap())
208                        .max_pages(body_args.max_pages.unwrap())
209                        .created_after(Some(created_after.to_string()))
210                        .created_before(Some(created_before.to_string()))
211                        .sort_mode(remote_cli_args.sort.clone())
212                        .flush(remote_cli_args.flush)
213                        .throttle_time(remote_cli_args.throttle_time)
214                        .throttle_range(remote_cli_args.throttle_range)
215                        .get_args(remote_cli_args.get_args.clone())
216                        .build()
217                        .unwrap(),
218                ));
219            }
220            Ok(Some(
221                ListBodyArgs::builder()
222                    .created_after(Some(created_after.to_string()))
223                    .created_before(Some(created_before.to_string()))
224                    .sort_mode(remote_cli_args.sort.clone())
225                    .flush(remote_cli_args.flush)
226                    .throttle_time(remote_cli_args.throttle_time)
227                    .throttle_range(remote_cli_args.throttle_range)
228                    .get_args(remote_cli_args.get_args.clone())
229                    .build()
230                    .unwrap(),
231            ))
232        }
233        (Some(created_after), None) => {
234            if let Some(body_args) = &body_args {
235                return Ok(Some(
236                    ListBodyArgs::builder()
237                        .page(body_args.page.unwrap())
238                        .max_pages(body_args.max_pages.unwrap())
239                        .created_after(Some(created_after.to_string()))
240                        .sort_mode(remote_cli_args.sort.clone())
241                        .flush(remote_cli_args.flush)
242                        .throttle_time(remote_cli_args.throttle_time)
243                        .throttle_range(remote_cli_args.throttle_range)
244                        .get_args(remote_cli_args.get_args.clone())
245                        .build()
246                        .unwrap(),
247                ));
248            }
249            Ok(Some(
250                ListBodyArgs::builder()
251                    .created_after(Some(created_after.to_string()))
252                    .sort_mode(remote_cli_args.sort.clone())
253                    .flush(remote_cli_args.flush)
254                    .throttle_time(remote_cli_args.throttle_time)
255                    .throttle_range(remote_cli_args.throttle_range)
256                    .get_args(remote_cli_args.get_args.clone())
257                    .build()
258                    .unwrap(),
259            ))
260        }
261        (None, Some(created_before)) => {
262            if let Some(body_args) = &body_args {
263                return Ok(Some(
264                    ListBodyArgs::builder()
265                        .page(body_args.page.unwrap())
266                        .max_pages(body_args.max_pages.unwrap())
267                        .created_before(Some(created_before.to_string()))
268                        .sort_mode(remote_cli_args.sort.clone())
269                        .flush(remote_cli_args.flush)
270                        .throttle_time(remote_cli_args.throttle_time)
271                        .throttle_range(remote_cli_args.throttle_range)
272                        .get_args(remote_cli_args.get_args.clone())
273                        .build()
274                        .unwrap(),
275                ));
276            }
277            Ok(Some(
278                ListBodyArgs::builder()
279                    .created_before(Some(created_before.to_string()))
280                    .sort_mode(remote_cli_args.sort.clone())
281                    .flush(remote_cli_args.flush)
282                    .throttle_time(remote_cli_args.throttle_time)
283                    .throttle_range(remote_cli_args.throttle_range)
284                    .get_args(remote_cli_args.get_args.clone())
285                    .build()
286                    .unwrap(),
287            ))
288        }
289        (None, None) => {
290            if let Some(body_args) = &body_args {
291                return Ok(Some(
292                    ListBodyArgs::builder()
293                        .page(body_args.page.unwrap())
294                        .max_pages(body_args.max_pages.unwrap())
295                        .sort_mode(remote_cli_args.sort.clone())
296                        .flush(remote_cli_args.flush)
297                        .throttle_time(remote_cli_args.throttle_time)
298                        .throttle_range(remote_cli_args.throttle_range)
299                        .get_args(remote_cli_args.get_args.clone())
300                        .build()
301                        .unwrap(),
302                ));
303            }
304            Ok(Some(
305                ListBodyArgs::builder()
306                    .sort_mode(remote_cli_args.sort.clone())
307                    .flush(remote_cli_args.flush)
308                    .throttle_time(remote_cli_args.throttle_time)
309                    .throttle_range(remote_cli_args.throttle_range)
310                    .get_args(remote_cli_args.get_args.clone())
311                    .build()
312                    .unwrap(),
313            ))
314        }
315    }
316}
317
318pub struct URLQueryParamBuilder {
319    url: String,
320}
321
322impl URLQueryParamBuilder {
323    pub fn new(url: &str) -> Self {
324        URLQueryParamBuilder {
325            url: url.to_string(),
326        }
327    }
328
329    pub fn add_param(&mut self, key: &str, value: &str) -> &mut Self {
330        if self.url.contains('?') {
331            self.url.push_str(&format!("&{key}={value}"));
332        } else {
333            self.url.push_str(&format!("?{key}={value}"));
334        }
335        self
336    }
337
338    pub fn build(&self) -> String {
339        self.url.clone()
340    }
341}
342
343#[derive(Clone, Debug, Default, PartialEq)]
344pub enum ListSortMode {
345    #[default]
346    Asc,
347    Desc,
348}
349
350#[derive(Clone, Debug, PartialEq)]
351pub enum CacheType {
352    File,
353    None,
354}
355
356use crate::config::ConfigProperties;
357macro_rules! get {
358    ($func_name:ident, $trait_name:ident) => {
359        paste::paste! {
360            pub fn $func_name(
361                domain: String,
362                path: String,
363                config: Arc<dyn ConfigProperties + Send + Sync + 'static>,
364                cache_args: Option<&CacheCliArgs>,
365                cache_type: CacheType,
366            ) -> Result<Arc<dyn $trait_name + Send + Sync + 'static>> {
367                let refresh_cache = cache_args.map_or(false, |args| args.refresh);
368                let no_cache_args = cache_args.map_or(false, |args| args.no_cache);
369
370                log_debug!("cache_type: {:?}", cache_type);
371                log_debug!("no_cache_args: {:?}", no_cache_args);
372                log_debug!("cache location: {:?}", config.cache_location());
373
374                if cache_type == CacheType::None || no_cache_args || config.cache_location().is_none() {
375                    log_info!("No cache used for {}", stringify!($func_name));
376                    let runner = Arc::new(http::Client::new(NoCache, config.clone(), refresh_cache));
377                    [<create_remote_ $func_name>](domain, path, config, runner)
378                } else {
379                    log_info!("File cache used for {}", stringify!($func_name));
380                    let file_cache = FileCache::new(config.clone());
381                    file_cache.validate_cache_location()?;
382                    let runner = Arc::new(http::Client::new(file_cache, config.clone(), refresh_cache));
383                    [<create_remote_ $func_name>](domain, path, config, runner)
384                }
385            }
386
387            fn [<create_remote_ $func_name>]<R>(
388                domain: String,
389                path: String,
390                config: Arc<dyn ConfigProperties>,
391                runner: Arc<R>,
392            ) -> Result<Arc<dyn $trait_name + Send + Sync + 'static>>
393            where
394                R: HttpRunner<Response = HttpResponse> + Send + Sync + 'static,
395            {
396                let github_domain_regex = regex::Regex::new(r"^github").unwrap();
397                let gitlab_domain_regex = regex::Regex::new(r"^gitlab").unwrap();
398                let remote: Arc<dyn $trait_name + Send + Sync + 'static> =
399                    if github_domain_regex.is_match(&domain) {
400                        Arc::new(Github::new(config, &domain, &path, runner))
401                    } else if gitlab_domain_regex.is_match(&domain) {
402                        Arc::new(Gitlab::new(config, &domain, &path, runner))
403                    } else {
404                        return Err(error::gen(format!("Unsupported domain: {}", &domain)));
405                    };
406                Ok(remote)
407            }
408        }
409    };
410}
411
412get!(get_mr, MergeRequest);
413get!(get_cicd, Cicd);
414get!(get_project, RemoteProject);
415get!(get_tag, RemoteTag);
416get!(get_user, UserInfo);
417get!(get_project_member, ProjectMember);
418get!(get_registry, ContainerRegistry);
419get!(get_deploy, Deploy);
420get!(get_deploy_asset, DeployAsset);
421get!(get_auth_user, UserInfo);
422get!(get_cicd_runner, CicdRunner);
423get!(get_comment_mr, CommentMergeRequest);
424get!(get_trending, TrendingProjectURL);
425get!(get_gist, CodeGist);
426get!(get_cicd_job, CicdJob);
427
428pub fn extract_domain_path(repo_cli: &str) -> (String, String) {
429    let parts: Vec<&str> = repo_cli.split('/').collect();
430    let domain = parts[0].to_string();
431    let path = parts[1..].join("/");
432    (domain, path)
433}
434
435/// Given a CLI command, the command can work as long as user is in a cd
436/// repository, user passes --domain flag (DomainArgs) or --repo flag
437/// (RepoArgs). Some CLI commands might work with one variant, with both, with
438/// all or might have no requirement at all.
439pub enum CliDomainRequirements {
440    CdInLocalRepo,
441    DomainArgs,
442    RepoArgs,
443}
444
445#[derive(Clone, Debug, Default)]
446pub struct RemoteURL {
447    /// Domain of the project. Ex github.com
448    domain: String,
449    /// Path to the project. Ex jordilin/gitar
450    path: String,
451    /// Config encoded project path. Ex jordilin_gitar
452    /// This is used as a key in TOML configuration in order to retrieve project
453    /// specific configuration that overrides its domain specific one.
454    config_encoded_project_path: String,
455    config_encoded_domain: String,
456}
457
458impl RemoteURL {
459    pub fn new(domain: String, path: String) -> Self {
460        let config_encoded_project_path = path.replace("/", "_");
461        let config_encoded_domain = domain.replace(".", "_");
462        RemoteURL {
463            domain,
464            path,
465            config_encoded_project_path,
466            config_encoded_domain,
467        }
468    }
469
470    pub fn domain(&self) -> &str {
471        &self.domain
472    }
473
474    pub fn path(&self) -> &str {
475        &self.path
476    }
477
478    pub fn config_encoded_project_path(&self) -> &str {
479        &self.config_encoded_project_path
480    }
481
482    pub fn config_encoded_domain(&self) -> &str {
483        &self.config_encoded_domain
484    }
485}
486
487impl CliDomainRequirements {
488    pub fn check<R: TaskRunner<Response = ShellResponse>>(
489        &self,
490        cli_args: &cli::CliArgs,
491        runner: &R,
492        mr_target_repo: &Option<&str>,
493    ) -> Result<RemoteURL> {
494        match self {
495            CliDomainRequirements::CdInLocalRepo => match git::remote_url(runner) {
496                Ok(CmdInfo::RemoteUrl(url)) => {
497                    // If target_repo is provided, then target's
498                    // <repo_owner>/<repo_name> takes preference. Domain is kept
499                    // as is from the forked repo.
500                    if let Some(target_repo) = mr_target_repo {
501                        Ok(RemoteURL::new(
502                            url.domain().to_string(),
503                            target_repo.to_string(),
504                        ))
505                    } else {
506                        Ok(url)
507                    }
508                }
509                Err(err) => Err(GRError::GitRemoteUrlNotFound(format!("{err}")).into()),
510                _ => Err(GRError::ApplicationError(
511                    "Could not get remote url during startup. \
512                        main::get_config_domain_path - Please open a bug to \
513                        https://github.com/jordilin/gitar"
514                        .to_string(),
515                )
516                .into()),
517            },
518            CliDomainRequirements::DomainArgs => {
519                if cli_args.domain.is_some() {
520                    Ok(RemoteURL::new(
521                        cli_args.domain.as_ref().unwrap().to_string(),
522                        "".to_string(),
523                    ))
524                } else {
525                    Err(GRError::DomainExpected("Missing domain information".to_string()).into())
526                }
527            }
528            CliDomainRequirements::RepoArgs => {
529                if cli_args.repo.is_some() {
530                    let (domain, path) = extract_domain_path(cli_args.repo.as_ref().unwrap());
531                    Ok(RemoteURL::new(domain, path))
532                } else {
533                    Err(GRError::RepoExpected("Missing repository information".to_string()).into())
534                }
535            }
536        }
537    }
538}
539
540impl Display for CliDomainRequirements {
541    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
542        match self {
543            CliDomainRequirements::CdInLocalRepo => write!(f, "cd to a git repository"),
544            CliDomainRequirements::DomainArgs => write!(f, "provide --domain option"),
545            CliDomainRequirements::RepoArgs => write!(f, "provide --repo option"),
546        }
547    }
548}
549
550pub fn url<R: TaskRunner<Response = ShellResponse>>(
551    cli_args: &cli::CliArgs,
552    requirements: &[CliDomainRequirements],
553    runner: &R,
554    mr_target_repo: &Option<&str>,
555) -> Result<RemoteURL> {
556    let mut errors = Vec::new();
557    for requirement in requirements {
558        match requirement.check(cli_args, runner, mr_target_repo) {
559            Ok(url) => return Ok(url),
560            Err(err) => {
561                errors.push(err);
562            }
563        }
564    }
565    let trace = errors
566        .iter()
567        .map(|e| format!("{e}"))
568        .collect::<Vec<String>>()
569        .join("\n");
570
571    let expectations_missed_trace = requirements
572        .iter()
573        .map(|r| format!("{r}"))
574        .collect::<Vec<String>>()
575        .join(" OR ");
576
577    Err(GRError::PreconditionNotMet(format!(
578        "\n\nMissed requirements: {expectations_missed_trace}\n\n Errors:\n\n {trace}"
579    ))
580    .into())
581}
582
583/// Reads configuration from TOML file. The config_file is the main default
584/// config file and it holds global configuration. Additionally, this function
585/// will attempt to gather configurations named after the domain and the project
586/// we are targeting. This is so the main config does not become unnecessarily
587/// large when providing merge request configuration for a specific project. The
588/// total configuration is as if we concatenated them all into one, so headers
589/// cannot be named the same across different configuration files. The
590/// configuration for a specific domain or project can go to either config file
591/// but cannot be mixed. Ex.
592///
593/// - gitar.toml - left empty
594/// - github_com.toml - holds configuration for github.com
595/// - github_com_jordilin_gitar.toml - holds configuration for jordilin/gitar
596///
597/// But also, we could just have:
598///
599/// - gitar.toml - left empty
600/// - github_com_jordilin_gitar.toml - holds configuration for gitub.com and
601///   jordilin/gitar
602/// - github_com.toml - left empty
603///
604/// Up to the user how he/she wants to organize the TOML configuration across
605/// files as long as TOML headers are unique and abide by the configuration
606/// format supported by Gitar.
607///
608/// If all files are missing, then a default configuration is returned. That is
609/// gitar works with no configuration as long as auth tokens are provided via
610/// environment variables. Ex. CI/CD use cases and one-offs.
611pub fn read_config(
612    config_path: ConfigFilePath,
613    url: &RemoteURL,
614) -> Result<Arc<dyn ConfigProperties>> {
615    let enc_domain = url.config_encoded_domain();
616
617    let domain_config_file = config_path.directory.join(format!("{enc_domain}.toml"));
618    let domain_project_file = config_path.directory.join(format!(
619        "{}_{}.toml",
620        enc_domain,
621        url.config_encoded_project_path()
622    ));
623
624    log_debug!("config_file: {:?}", config_path.file_name);
625    log_debug!("domain_config_file: {:?}", domain_config_file);
626    log_debug!("domain_project_config_file: {:?}", domain_project_file);
627
628    let mut extra_configs = [domain_config_file, domain_project_file]
629        .into_iter()
630        .collect::<Vec<PathBuf>>();
631
632    fn open_files(file_paths: &[PathBuf]) -> Vec<File> {
633        file_paths
634            .iter()
635            .filter_map(|path| match File::open(path) {
636                Ok(file) => Some(file),
637                Err(e) => {
638                    log_debug!("Could not open file: {:?} - {}", path, e);
639                    None
640                }
641            })
642            .collect()
643    }
644
645    extra_configs.push(config_path.file_name);
646    let files = open_files(&extra_configs);
647    if files.is_empty() {
648        let config = NoConfig::new(url.domain(), env_token)?;
649        return Ok(Arc::new(config));
650    }
651    let config = ConfigFile::new(files, url, env_token)?;
652    Ok(Arc::new(config))
653}
654
655/// ConfigFilePath is in charge of computing the default config file name and
656/// its parent directory based on global CLI arguments.
657pub struct ConfigFilePath {
658    directory: PathBuf,
659    file_name: PathBuf,
660}
661
662impl ConfigFilePath {
663    pub fn new(cli_args: &cli::CliArgs) -> Self {
664        let directory = if let Some(ref config) = cli_args.config {
665            &Path::new(config).to_path_buf()
666        } else {
667            get_default_config_path()
668        };
669        let file_name = directory.join("gitar.toml");
670        ConfigFilePath {
671            directory: directory.clone(),
672            file_name,
673        }
674    }
675
676    pub fn directory(&self) -> &PathBuf {
677        &self.directory
678    }
679
680    pub fn file_name(&self) -> &PathBuf {
681        &self.file_name
682    }
683}
684
685#[cfg(test)]
686mod test {
687    use cli::CliArgs;
688
689    use crate::test::utils::MockRunner;
690
691    use super::*;
692
693    #[test]
694    fn test_cli_from_to_pages_valid_range() {
695        let from_page = Option::Some(1);
696        let to_page = Option::Some(3);
697        let args = ListRemoteCliArgs::builder()
698            .from_page(from_page)
699            .to_page(to_page)
700            .build()
701            .unwrap();
702        let args = validate_from_to_page(&args).unwrap().unwrap();
703        assert_eq!(args.page, Some(1));
704        assert_eq!(args.max_pages, Some(3));
705    }
706
707    #[test]
708    fn test_cli_from_to_pages_invalid_range() {
709        let from_page = Some(5);
710        let to_page = Some(2);
711        let args = ListRemoteCliArgs::builder()
712            .from_page(from_page)
713            .to_page(to_page)
714            .build()
715            .unwrap();
716        let args = validate_from_to_page(&args);
717        match args {
718            Err(err) => match err.downcast_ref::<error::GRError>() {
719                Some(error::GRError::PreconditionNotMet(_)) => (),
720                _ => panic!("Expected error::GRError::PreconditionNotMet"),
721            },
722            _ => panic!("Expected error"),
723        }
724    }
725
726    #[test]
727    fn test_cli_from_page_negative_number_is_error() {
728        let from_page = Some(-5);
729        let to_page = Some(5);
730        let args = ListRemoteCliArgs::builder()
731            .from_page(from_page)
732            .to_page(to_page)
733            .build()
734            .unwrap();
735        let args = validate_from_to_page(&args);
736        match args {
737            Err(err) => match err.downcast_ref::<error::GRError>() {
738                Some(error::GRError::PreconditionNotMet(_)) => (),
739                _ => panic!("Expected error::GRError::PreconditionNotMet"),
740            },
741            _ => panic!("Expected error"),
742        }
743    }
744
745    #[test]
746    fn test_cli_to_page_negative_number_is_error() {
747        let from_page = Some(5);
748        let to_page = Some(-5);
749        let args = ListRemoteCliArgs::builder()
750            .from_page(from_page)
751            .to_page(to_page)
752            .build()
753            .unwrap();
754        let args = validate_from_to_page(&args);
755        match args {
756            Err(err) => match err.downcast_ref::<error::GRError>() {
757                Some(error::GRError::PreconditionNotMet(_)) => (),
758                _ => panic!("Expected error::GRError::PreconditionNotMet"),
759            },
760            _ => panic!("Expected error"),
761        }
762    }
763
764    #[test]
765    fn test_cli_from_page_without_to_page_is_error() {
766        let from_page = Some(5);
767        let to_page = None;
768        let args = ListRemoteCliArgs::builder()
769            .from_page(from_page)
770            .to_page(to_page)
771            .build()
772            .unwrap();
773        let args = validate_from_to_page(&args);
774        match args {
775            Err(err) => match err.downcast_ref::<error::GRError>() {
776                Some(error::GRError::PreconditionNotMet(_)) => (),
777                _ => panic!("Expected error::GRError::PreconditionNotMet"),
778            },
779            _ => panic!("Expected error"),
780        }
781    }
782
783    #[test]
784    fn test_if_from_and_to_provided_must_be_positive() {
785        let from_page = Some(-5);
786        let to_page = Some(-5);
787        let args = ListRemoteCliArgs::builder()
788            .from_page(from_page)
789            .to_page(to_page)
790            .build()
791            .unwrap();
792        let args = validate_from_to_page(&args);
793        match args {
794            Err(err) => match err.downcast_ref::<error::GRError>() {
795                Some(error::GRError::PreconditionNotMet(_)) => (),
796                _ => panic!("Expected error::GRError::PreconditionNotMet"),
797            },
798            _ => panic!("Expected error"),
799        }
800    }
801
802    #[test]
803    fn test_if_page_number_provided_max_pages_is_1() {
804        let page_number = Some(5);
805        let args = ListRemoteCliArgs::builder()
806            .page_number(page_number)
807            .build()
808            .unwrap();
809        let args = validate_from_to_page(&args).unwrap().unwrap();
810        assert_eq!(args.page, Some(5));
811        assert_eq!(args.max_pages, Some(1));
812    }
813
814    #[test]
815    fn test_include_created_after_in_list_body_args() {
816        let created_after = "2021-01-01T00:00:00Z";
817        let args = ListRemoteCliArgs::builder()
818            .created_after(Some(created_after.to_string()))
819            .build()
820            .unwrap();
821        let args = validate_from_to_page(&args).unwrap().unwrap();
822        assert_eq!(args.created_after.unwrap(), created_after);
823    }
824
825    #[test]
826    fn test_includes_from_to_page_and_created_after_in_list_body_args() {
827        let from_page = Some(1);
828        let to_page = Some(3);
829        let created_after = "2021-01-01T00:00:00Z";
830        let args = ListRemoteCliArgs::builder()
831            .from_page(from_page)
832            .to_page(to_page)
833            .created_after(Some(created_after.to_string()))
834            .build()
835            .unwrap();
836        let args = validate_from_to_page(&args).unwrap().unwrap();
837        assert_eq!(args.page, Some(1));
838        assert_eq!(args.max_pages, Some(3));
839        assert_eq!(args.created_after.unwrap(), created_after);
840    }
841
842    #[test]
843    fn test_includes_sort_mode_in_list_body_args_used_with_created_after() {
844        let args = ListRemoteCliArgs::builder()
845            .created_after(Some("2021-01-01T00:00:00Z".to_string()))
846            .sort(ListSortMode::Desc)
847            .build()
848            .unwrap();
849        let args = validate_from_to_page(&args).unwrap().unwrap();
850        assert_eq!(args.sort_mode, ListSortMode::Desc);
851    }
852
853    #[test]
854    fn test_includes_sort_mode_in_list_body_args_used_with_from_to_page() {
855        let from_page = Some(1);
856        let to_page = Some(3);
857        let args = ListRemoteCliArgs::builder()
858            .from_page(from_page)
859            .to_page(to_page)
860            .sort(ListSortMode::Desc)
861            .build()
862            .unwrap();
863        let args = validate_from_to_page(&args).unwrap().unwrap();
864        assert_eq!(args.sort_mode, ListSortMode::Desc);
865    }
866
867    #[test]
868    fn test_includes_sort_mode_in_list_body_args_used_with_page_number() {
869        let page_number = Some(1);
870        let args = ListRemoteCliArgs::builder()
871            .page_number(page_number)
872            .sort(ListSortMode::Desc)
873            .build()
874            .unwrap();
875        let args = validate_from_to_page(&args).unwrap().unwrap();
876        assert_eq!(args.sort_mode, ListSortMode::Desc);
877    }
878
879    #[test]
880    fn test_add_created_after_with_page_number() {
881        let page_number = Some(1);
882        let created_after = "2021-01-01T00:00:00Z";
883        let args = ListRemoteCliArgs::builder()
884            .page_number(page_number)
885            .created_after(Some(created_after.to_string()))
886            .build()
887            .unwrap();
888        let args = validate_from_to_page(&args).unwrap().unwrap();
889        assert_eq!(args.page.unwrap(), 1);
890        assert_eq!(args.max_pages.unwrap(), 1);
891        assert_eq!(args.created_after.unwrap(), created_after);
892    }
893
894    #[test]
895    fn test_add_created_before_with_page_number() {
896        let page_number = Some(1);
897        let created_before = "2021-01-01T00:00:00Z";
898        let args = ListRemoteCliArgs::builder()
899            .page_number(page_number)
900            .created_before(Some(created_before.to_string()))
901            .build()
902            .unwrap();
903        let args = validate_from_to_page(&args).unwrap().unwrap();
904        assert_eq!(args.page.unwrap(), 1);
905        assert_eq!(args.max_pages.unwrap(), 1);
906        assert_eq!(args.created_before.unwrap(), created_before);
907    }
908
909    #[test]
910    fn test_add_created_before_with_from_to_page() {
911        let from_page = Some(1);
912        let to_page = Some(3);
913        let created_before = "2021-01-01T00:00:00Z";
914        let args = ListRemoteCliArgs::builder()
915            .from_page(from_page)
916            .to_page(to_page)
917            .created_before(Some(created_before.to_string()))
918            .sort(ListSortMode::Desc)
919            .build()
920            .unwrap();
921        let args = validate_from_to_page(&args).unwrap().unwrap();
922        assert_eq!(args.page.unwrap(), 1);
923        assert_eq!(args.max_pages.unwrap(), 3);
924        assert_eq!(args.created_before.unwrap(), created_before);
925        assert_eq!(args.sort_mode, ListSortMode::Desc);
926    }
927
928    #[test]
929    fn test_add_crated_before_with_no_created_after_option_and_no_page_number() {
930        let created_before = "2021-01-01T00:00:00Z";
931        let args = ListRemoteCliArgs::builder()
932            .created_before(Some(created_before.to_string()))
933            .sort(ListSortMode::Desc)
934            .build()
935            .unwrap();
936        let args = validate_from_to_page(&args).unwrap().unwrap();
937        assert_eq!(args.created_before.unwrap(), created_before);
938        assert_eq!(args.sort_mode, ListSortMode::Desc);
939    }
940
941    #[test]
942    fn test_adds_created_after_and_created_before_with_from_to_page() {
943        let from_page = Some(1);
944        let to_page = Some(3);
945        let created_after = "2021-01-01T00:00:00Z";
946        let created_before = "2021-01-02T00:00:00Z";
947        let args = ListRemoteCliArgs::builder()
948            .from_page(from_page)
949            .to_page(to_page)
950            .created_after(Some(created_after.to_string()))
951            .created_before(Some(created_before.to_string()))
952            .sort(ListSortMode::Desc)
953            .build()
954            .unwrap();
955        let args = validate_from_to_page(&args).unwrap().unwrap();
956        assert_eq!(args.page.unwrap(), 1);
957        assert_eq!(args.max_pages.unwrap(), 3);
958        assert_eq!(args.created_after.unwrap(), created_after);
959        assert_eq!(args.created_before.unwrap(), created_before);
960        assert_eq!(args.sort_mode, ListSortMode::Desc);
961    }
962
963    #[test]
964    fn test_add_created_after_and_before_no_from_to_page_options() {
965        let created_after = "2021-01-01T00:00:00Z";
966        let created_before = "2021-01-02T00:00:00Z";
967        let args = ListRemoteCliArgs::builder()
968            .created_after(Some(created_after.to_string()))
969            .created_before(Some(created_before.to_string()))
970            .sort(ListSortMode::Desc)
971            .build()
972            .unwrap();
973        let args = validate_from_to_page(&args).unwrap().unwrap();
974        assert_eq!(args.created_after.unwrap(), created_after);
975        assert_eq!(args.created_before.unwrap(), created_before);
976        assert_eq!(args.sort_mode, ListSortMode::Desc);
977    }
978
979    #[test]
980    fn test_if_only_to_page_provided_max_pages_is_to_page() {
981        let to_page = Some(3);
982        let args = ListRemoteCliArgs::builder()
983            .to_page(to_page)
984            .build()
985            .unwrap();
986        let args = validate_from_to_page(&args).unwrap().unwrap();
987        assert_eq!(args.page, Some(1));
988        assert_eq!(args.max_pages, Some(3));
989    }
990
991    #[test]
992    fn test_if_only_to_page_provided_and_negative_number_is_error() {
993        let to_page = Some(-3);
994        let args = ListRemoteCliArgs::builder()
995            .to_page(to_page)
996            .build()
997            .unwrap();
998        let args = validate_from_to_page(&args);
999        match args {
1000            Err(err) => match err.downcast_ref::<error::GRError>() {
1001                Some(error::GRError::PreconditionNotMet(_)) => (),
1002                _ => panic!("Expected error::GRError::PreconditionNotMet"),
1003            },
1004            _ => panic!("Expected error"),
1005        }
1006    }
1007
1008    #[test]
1009    fn test_if_sort_provided_use_it() {
1010        let args = ListRemoteCliArgs::builder()
1011            .sort(ListSortMode::Desc)
1012            .build()
1013            .unwrap();
1014        let args = validate_from_to_page(&args).unwrap().unwrap();
1015        assert_eq!(args.sort_mode, ListSortMode::Desc);
1016    }
1017
1018    #[test]
1019    fn test_if_flush_option_provided_use_it() {
1020        let args = ListRemoteCliArgs::builder().flush(true).build().unwrap();
1021        let args = validate_from_to_page(&args).unwrap().unwrap();
1022        assert!(args.flush);
1023    }
1024
1025    #[test]
1026    fn test_query_param_builder_no_params() {
1027        let url = "https://example.com";
1028        let url = URLQueryParamBuilder::new(url).build();
1029        assert_eq!(url, "https://example.com");
1030    }
1031
1032    #[test]
1033    fn test_query_param_builder_with_params() {
1034        let url = "https://example.com";
1035        let url = URLQueryParamBuilder::new(url)
1036            .add_param("key", "value")
1037            .add_param("key2", "value2")
1038            .build();
1039        assert_eq!(url, "https://example.com?key=value&key2=value2");
1040    }
1041
1042    #[test]
1043    fn test_retrieve_domain_path_from_repo_cli_flag() {
1044        let repo_cli = "github.com/jordilin/gitar";
1045        let (domain, path) = extract_domain_path(repo_cli);
1046        assert_eq!("github.com", domain);
1047        assert_eq!("jordilin/gitar", path);
1048    }
1049
1050    #[test]
1051    fn test_cli_requires_cd_local_repo_run_git_remote() {
1052        let cli_args = CliArgs::new(0, None, None, None);
1053        let response = ShellResponse::builder()
1054            .body("git@github.com:jordilin/gitar.git".to_string())
1055            .build()
1056            .unwrap();
1057        let runner = MockRunner::new(vec![response]);
1058        let requirements = vec![CliDomainRequirements::CdInLocalRepo];
1059        let url = url(&cli_args, &requirements, &runner, &None).unwrap();
1060        assert_eq!("github.com", url.domain());
1061        assert_eq!("jordilin/gitar", url.path());
1062    }
1063
1064    #[test]
1065    fn test_cli_requires_cd_local_repo_run_git_remote_error() {
1066        let cli_args = CliArgs::new(0, None, None, None);
1067        let response = ShellResponse::builder()
1068            .body("".to_string())
1069            .build()
1070            .unwrap();
1071        let runner = MockRunner::new(vec![response]);
1072        let requirements = vec![CliDomainRequirements::CdInLocalRepo];
1073        let result = url(&cli_args, &requirements, &runner, &None);
1074        match result {
1075            Err(err) => match err.downcast_ref::<error::GRError>() {
1076                Some(error::GRError::PreconditionNotMet(_)) => (),
1077                _ => panic!("Expected error::GRError::GitRemoteUrlNotFound"),
1078            },
1079            _ => panic!("Expected error"),
1080        }
1081    }
1082
1083    #[test]
1084    fn test_cli_requires_repo_args_or_cd_repo_fails_on_cd_repo() {
1085        let cli_args = CliArgs::new(0, Some("github.com/jordilin/gitar".to_string()), None, None);
1086        let requirements = vec![
1087            CliDomainRequirements::CdInLocalRepo,
1088            CliDomainRequirements::RepoArgs,
1089        ];
1090        let response = ShellResponse::builder()
1091            .body("".to_string())
1092            .build()
1093            .unwrap();
1094        let url = url(
1095            &cli_args,
1096            &requirements,
1097            &MockRunner::new(vec![response]),
1098            &None,
1099        )
1100        .unwrap();
1101        assert_eq!("github.com", url.domain());
1102        assert_eq!("jordilin/gitar", url.path());
1103        assert_eq!("jordilin_gitar", url.config_encoded_project_path());
1104    }
1105
1106    #[test]
1107    fn test_cli_requires_domain_args_or_cd_repo_fails_on_cd_repo() {
1108        let cli_args = CliArgs::new(0, None, Some("github.com".to_string()), None);
1109        let requirements = vec![
1110            CliDomainRequirements::CdInLocalRepo,
1111            CliDomainRequirements::DomainArgs,
1112        ];
1113        let response = ShellResponse::builder()
1114            .body("".to_string())
1115            .build()
1116            .unwrap();
1117        let url = url(
1118            &cli_args,
1119            &requirements,
1120            &MockRunner::new(vec![response]),
1121            &None,
1122        )
1123        .unwrap();
1124        assert_eq!("github.com", url.domain());
1125        assert_eq!("", url.path());
1126    }
1127
1128    #[test]
1129    fn test_remote_url() {
1130        let remote_url = RemoteURL::new("github.com".to_string(), "jordilin/gitar".to_string());
1131        assert_eq!("github.com", remote_url.domain());
1132        assert_eq!("jordilin/gitar", remote_url.path());
1133    }
1134
1135    #[test]
1136    fn test_get_config_encoded_project_path() {
1137        let remote_url = RemoteURL::new("github.com".to_string(), "jordilin/gitar".to_string());
1138        assert_eq!("jordilin_gitar", remote_url.config_encoded_project_path());
1139    }
1140
1141    #[test]
1142    fn test_get_config_encoded_project_path_multiple_groups() {
1143        let remote_url = RemoteURL::new(
1144            "gitlab.com".to_string(),
1145            "team/subgroup/project".to_string(),
1146        );
1147        assert_eq!(
1148            "team_subgroup_project",
1149            remote_url.config_encoded_project_path()
1150        );
1151    }
1152
1153    #[test]
1154    fn test_get_config_encoded_domain() {
1155        let remote_url = RemoteURL::new("github.com".to_string(), "jordilin/gitar".to_string());
1156        assert_eq!("github_com", remote_url.config_encoded_domain());
1157    }
1158
1159    #[test]
1160    fn test_remote_url_from_optional_target_repo() {
1161        let target_repo = Some("jordilin/gitar");
1162        let cli_args = CliArgs::default();
1163        // Huck Finn opens a PR from a forked repo over to the main repo
1164        // jordilin/gitar
1165        let response = ShellResponse::builder()
1166            .body("git@github.com:hfinn/gitar.git".to_string())
1167            .build()
1168            .unwrap();
1169        let runner = MockRunner::new(vec![response]);
1170        let requirements = vec![CliDomainRequirements::CdInLocalRepo];
1171        let url = url(&cli_args, &requirements, &runner, &target_repo).unwrap();
1172        assert_eq!("github.com", url.domain());
1173        assert_eq!("jordilin/gitar", url.path());
1174    }
1175}