Skip to main content

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 let Some(page_number) = remote_cli_args.page_number {
131        return Ok(Some(
132            ListBodyArgs::builder()
133                .page(page_number)
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 let Some(domain) = &cli_args.domain {
520                    Ok(RemoteURL::new(domain.to_string(), "".to_string()))
521                } else {
522                    Err(GRError::DomainExpected("Missing domain information".to_string()).into())
523                }
524            }
525            CliDomainRequirements::RepoArgs => {
526                if let Some(repo) = &cli_args.repo {
527                    let (domain, path) = extract_domain_path(repo);
528                    Ok(RemoteURL::new(domain, path))
529                } else {
530                    Err(GRError::RepoExpected("Missing repository information".to_string()).into())
531                }
532            }
533        }
534    }
535}
536
537impl Display for CliDomainRequirements {
538    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
539        match self {
540            CliDomainRequirements::CdInLocalRepo => write!(f, "cd to a git repository"),
541            CliDomainRequirements::DomainArgs => write!(f, "provide --domain option"),
542            CliDomainRequirements::RepoArgs => write!(f, "provide --repo option"),
543        }
544    }
545}
546
547pub fn url<R: TaskRunner<Response = ShellResponse>>(
548    cli_args: &cli::CliArgs,
549    requirements: &[CliDomainRequirements],
550    runner: &R,
551    mr_target_repo: &Option<&str>,
552) -> Result<RemoteURL> {
553    let mut errors = Vec::new();
554    for requirement in requirements {
555        match requirement.check(cli_args, runner, mr_target_repo) {
556            Ok(url) => return Ok(url),
557            Err(err) => {
558                errors.push(err);
559            }
560        }
561    }
562    let trace = errors
563        .iter()
564        .map(|e| format!("{e}"))
565        .collect::<Vec<String>>()
566        .join("\n");
567
568    let expectations_missed_trace = requirements
569        .iter()
570        .map(|r| format!("{r}"))
571        .collect::<Vec<String>>()
572        .join(" OR ");
573
574    Err(GRError::PreconditionNotMet(format!(
575        "\n\nMissed requirements: {expectations_missed_trace}\n\n Errors:\n\n {trace}"
576    ))
577    .into())
578}
579
580/// Reads configuration from TOML file. The config_file is the main default
581/// config file and it holds global configuration. Additionally, this function
582/// will attempt to gather configurations named after the domain and the project
583/// we are targeting. This is so the main config does not become unnecessarily
584/// large when providing merge request configuration for a specific project. The
585/// total configuration is as if we concatenated them all into one, so headers
586/// cannot be named the same across different configuration files. The
587/// configuration for a specific domain or project can go to either config file
588/// but cannot be mixed. Ex.
589///
590/// - gitar.toml - left empty
591/// - github_com.toml - holds configuration for github.com
592/// - github_com_jordilin_gitar.toml - holds configuration for jordilin/gitar
593///
594/// But also, we could just have:
595///
596/// - gitar.toml - left empty
597/// - github_com_jordilin_gitar.toml - holds configuration for gitub.com and
598///   jordilin/gitar
599/// - github_com.toml - left empty
600///
601/// Up to the user how he/she wants to organize the TOML configuration across
602/// files as long as TOML headers are unique and abide by the configuration
603/// format supported by Gitar.
604///
605/// If all files are missing, then a default configuration is returned. That is
606/// gitar works with no configuration as long as auth tokens are provided via
607/// environment variables. Ex. CI/CD use cases and one-offs.
608pub fn read_config(
609    config_path: ConfigFilePath,
610    url: &RemoteURL,
611) -> Result<Arc<dyn ConfigProperties>> {
612    let enc_domain = url.config_encoded_domain();
613
614    let domain_config_file = config_path.directory.join(format!("{enc_domain}.toml"));
615    let domain_project_file = config_path.directory.join(format!(
616        "{}_{}.toml",
617        enc_domain,
618        url.config_encoded_project_path()
619    ));
620
621    log_debug!("config_file: {:?}", config_path.file_name);
622    log_debug!("domain_config_file: {:?}", domain_config_file);
623    log_debug!("domain_project_config_file: {:?}", domain_project_file);
624
625    let mut extra_configs = [domain_config_file, domain_project_file]
626        .into_iter()
627        .collect::<Vec<PathBuf>>();
628
629    fn open_files(file_paths: &[PathBuf]) -> Vec<File> {
630        file_paths
631            .iter()
632            .filter_map(|path| match File::open(path) {
633                Ok(file) => Some(file),
634                Err(e) => {
635                    log_debug!("Could not open file: {:?} - {}", path, e);
636                    None
637                }
638            })
639            .collect()
640    }
641
642    extra_configs.push(config_path.file_name);
643    let files = open_files(&extra_configs);
644    if files.is_empty() {
645        let config = NoConfig::new(url.domain(), env_token)?;
646        return Ok(Arc::new(config));
647    }
648    let config = ConfigFile::new(files, url, env_token)?;
649    Ok(Arc::new(config))
650}
651
652/// ConfigFilePath is in charge of computing the default config file name and
653/// its parent directory based on global CLI arguments.
654pub struct ConfigFilePath {
655    directory: PathBuf,
656    file_name: PathBuf,
657}
658
659impl ConfigFilePath {
660    pub fn new(cli_args: &cli::CliArgs) -> Self {
661        let directory = if let Some(ref config) = cli_args.config {
662            &Path::new(config).to_path_buf()
663        } else {
664            get_default_config_path()
665        };
666        let file_name = directory.join("gitar.toml");
667        ConfigFilePath {
668            directory: directory.clone(),
669            file_name,
670        }
671    }
672
673    pub fn directory(&self) -> &PathBuf {
674        &self.directory
675    }
676
677    pub fn file_name(&self) -> &PathBuf {
678        &self.file_name
679    }
680}
681
682#[cfg(test)]
683mod test {
684    use cli::CliArgs;
685
686    use crate::test::utils::MockRunner;
687
688    use super::*;
689
690    #[test]
691    fn test_cli_from_to_pages_valid_range() {
692        let from_page = Option::Some(1);
693        let to_page = Option::Some(3);
694        let args = ListRemoteCliArgs::builder()
695            .from_page(from_page)
696            .to_page(to_page)
697            .build()
698            .unwrap();
699        let args = validate_from_to_page(&args).unwrap().unwrap();
700        assert_eq!(args.page, Some(1));
701        assert_eq!(args.max_pages, Some(3));
702    }
703
704    #[test]
705    fn test_cli_from_to_pages_invalid_range() {
706        let from_page = Some(5);
707        let to_page = Some(2);
708        let args = ListRemoteCliArgs::builder()
709            .from_page(from_page)
710            .to_page(to_page)
711            .build()
712            .unwrap();
713        let args = validate_from_to_page(&args);
714        match args {
715            Err(err) => match err.downcast_ref::<error::GRError>() {
716                Some(error::GRError::PreconditionNotMet(_)) => (),
717                _ => panic!("Expected error::GRError::PreconditionNotMet"),
718            },
719            _ => panic!("Expected error"),
720        }
721    }
722
723    #[test]
724    fn test_cli_from_page_negative_number_is_error() {
725        let from_page = Some(-5);
726        let to_page = Some(5);
727        let args = ListRemoteCliArgs::builder()
728            .from_page(from_page)
729            .to_page(to_page)
730            .build()
731            .unwrap();
732        let args = validate_from_to_page(&args);
733        match args {
734            Err(err) => match err.downcast_ref::<error::GRError>() {
735                Some(error::GRError::PreconditionNotMet(_)) => (),
736                _ => panic!("Expected error::GRError::PreconditionNotMet"),
737            },
738            _ => panic!("Expected error"),
739        }
740    }
741
742    #[test]
743    fn test_cli_to_page_negative_number_is_error() {
744        let from_page = Some(5);
745        let to_page = Some(-5);
746        let args = ListRemoteCliArgs::builder()
747            .from_page(from_page)
748            .to_page(to_page)
749            .build()
750            .unwrap();
751        let args = validate_from_to_page(&args);
752        match args {
753            Err(err) => match err.downcast_ref::<error::GRError>() {
754                Some(error::GRError::PreconditionNotMet(_)) => (),
755                _ => panic!("Expected error::GRError::PreconditionNotMet"),
756            },
757            _ => panic!("Expected error"),
758        }
759    }
760
761    #[test]
762    fn test_cli_from_page_without_to_page_is_error() {
763        let from_page = Some(5);
764        let to_page = None;
765        let args = ListRemoteCliArgs::builder()
766            .from_page(from_page)
767            .to_page(to_page)
768            .build()
769            .unwrap();
770        let args = validate_from_to_page(&args);
771        match args {
772            Err(err) => match err.downcast_ref::<error::GRError>() {
773                Some(error::GRError::PreconditionNotMet(_)) => (),
774                _ => panic!("Expected error::GRError::PreconditionNotMet"),
775            },
776            _ => panic!("Expected error"),
777        }
778    }
779
780    #[test]
781    fn test_if_from_and_to_provided_must_be_positive() {
782        let from_page = Some(-5);
783        let to_page = Some(-5);
784        let args = ListRemoteCliArgs::builder()
785            .from_page(from_page)
786            .to_page(to_page)
787            .build()
788            .unwrap();
789        let args = validate_from_to_page(&args);
790        match args {
791            Err(err) => match err.downcast_ref::<error::GRError>() {
792                Some(error::GRError::PreconditionNotMet(_)) => (),
793                _ => panic!("Expected error::GRError::PreconditionNotMet"),
794            },
795            _ => panic!("Expected error"),
796        }
797    }
798
799    #[test]
800    fn test_if_page_number_provided_max_pages_is_1() {
801        let page_number = Some(5);
802        let args = ListRemoteCliArgs::builder()
803            .page_number(page_number)
804            .build()
805            .unwrap();
806        let args = validate_from_to_page(&args).unwrap().unwrap();
807        assert_eq!(args.page, Some(5));
808        assert_eq!(args.max_pages, Some(1));
809    }
810
811    #[test]
812    fn test_include_created_after_in_list_body_args() {
813        let created_after = "2021-01-01T00:00:00Z";
814        let args = ListRemoteCliArgs::builder()
815            .created_after(Some(created_after.to_string()))
816            .build()
817            .unwrap();
818        let args = validate_from_to_page(&args).unwrap().unwrap();
819        assert_eq!(args.created_after.unwrap(), created_after);
820    }
821
822    #[test]
823    fn test_includes_from_to_page_and_created_after_in_list_body_args() {
824        let from_page = Some(1);
825        let to_page = Some(3);
826        let created_after = "2021-01-01T00:00:00Z";
827        let args = ListRemoteCliArgs::builder()
828            .from_page(from_page)
829            .to_page(to_page)
830            .created_after(Some(created_after.to_string()))
831            .build()
832            .unwrap();
833        let args = validate_from_to_page(&args).unwrap().unwrap();
834        assert_eq!(args.page, Some(1));
835        assert_eq!(args.max_pages, Some(3));
836        assert_eq!(args.created_after.unwrap(), created_after);
837    }
838
839    #[test]
840    fn test_includes_sort_mode_in_list_body_args_used_with_created_after() {
841        let args = ListRemoteCliArgs::builder()
842            .created_after(Some("2021-01-01T00:00:00Z".to_string()))
843            .sort(ListSortMode::Desc)
844            .build()
845            .unwrap();
846        let args = validate_from_to_page(&args).unwrap().unwrap();
847        assert_eq!(args.sort_mode, ListSortMode::Desc);
848    }
849
850    #[test]
851    fn test_includes_sort_mode_in_list_body_args_used_with_from_to_page() {
852        let from_page = Some(1);
853        let to_page = Some(3);
854        let args = ListRemoteCliArgs::builder()
855            .from_page(from_page)
856            .to_page(to_page)
857            .sort(ListSortMode::Desc)
858            .build()
859            .unwrap();
860        let args = validate_from_to_page(&args).unwrap().unwrap();
861        assert_eq!(args.sort_mode, ListSortMode::Desc);
862    }
863
864    #[test]
865    fn test_includes_sort_mode_in_list_body_args_used_with_page_number() {
866        let page_number = Some(1);
867        let args = ListRemoteCliArgs::builder()
868            .page_number(page_number)
869            .sort(ListSortMode::Desc)
870            .build()
871            .unwrap();
872        let args = validate_from_to_page(&args).unwrap().unwrap();
873        assert_eq!(args.sort_mode, ListSortMode::Desc);
874    }
875
876    #[test]
877    fn test_add_created_after_with_page_number() {
878        let page_number = Some(1);
879        let created_after = "2021-01-01T00:00:00Z";
880        let args = ListRemoteCliArgs::builder()
881            .page_number(page_number)
882            .created_after(Some(created_after.to_string()))
883            .build()
884            .unwrap();
885        let args = validate_from_to_page(&args).unwrap().unwrap();
886        assert_eq!(args.page.unwrap(), 1);
887        assert_eq!(args.max_pages.unwrap(), 1);
888        assert_eq!(args.created_after.unwrap(), created_after);
889    }
890
891    #[test]
892    fn test_add_created_before_with_page_number() {
893        let page_number = Some(1);
894        let created_before = "2021-01-01T00:00:00Z";
895        let args = ListRemoteCliArgs::builder()
896            .page_number(page_number)
897            .created_before(Some(created_before.to_string()))
898            .build()
899            .unwrap();
900        let args = validate_from_to_page(&args).unwrap().unwrap();
901        assert_eq!(args.page.unwrap(), 1);
902        assert_eq!(args.max_pages.unwrap(), 1);
903        assert_eq!(args.created_before.unwrap(), created_before);
904    }
905
906    #[test]
907    fn test_add_created_before_with_from_to_page() {
908        let from_page = Some(1);
909        let to_page = Some(3);
910        let created_before = "2021-01-01T00:00:00Z";
911        let args = ListRemoteCliArgs::builder()
912            .from_page(from_page)
913            .to_page(to_page)
914            .created_before(Some(created_before.to_string()))
915            .sort(ListSortMode::Desc)
916            .build()
917            .unwrap();
918        let args = validate_from_to_page(&args).unwrap().unwrap();
919        assert_eq!(args.page.unwrap(), 1);
920        assert_eq!(args.max_pages.unwrap(), 3);
921        assert_eq!(args.created_before.unwrap(), created_before);
922        assert_eq!(args.sort_mode, ListSortMode::Desc);
923    }
924
925    #[test]
926    fn test_add_crated_before_with_no_created_after_option_and_no_page_number() {
927        let created_before = "2021-01-01T00:00:00Z";
928        let args = ListRemoteCliArgs::builder()
929            .created_before(Some(created_before.to_string()))
930            .sort(ListSortMode::Desc)
931            .build()
932            .unwrap();
933        let args = validate_from_to_page(&args).unwrap().unwrap();
934        assert_eq!(args.created_before.unwrap(), created_before);
935        assert_eq!(args.sort_mode, ListSortMode::Desc);
936    }
937
938    #[test]
939    fn test_adds_created_after_and_created_before_with_from_to_page() {
940        let from_page = Some(1);
941        let to_page = Some(3);
942        let created_after = "2021-01-01T00:00:00Z";
943        let created_before = "2021-01-02T00:00:00Z";
944        let args = ListRemoteCliArgs::builder()
945            .from_page(from_page)
946            .to_page(to_page)
947            .created_after(Some(created_after.to_string()))
948            .created_before(Some(created_before.to_string()))
949            .sort(ListSortMode::Desc)
950            .build()
951            .unwrap();
952        let args = validate_from_to_page(&args).unwrap().unwrap();
953        assert_eq!(args.page.unwrap(), 1);
954        assert_eq!(args.max_pages.unwrap(), 3);
955        assert_eq!(args.created_after.unwrap(), created_after);
956        assert_eq!(args.created_before.unwrap(), created_before);
957        assert_eq!(args.sort_mode, ListSortMode::Desc);
958    }
959
960    #[test]
961    fn test_add_created_after_and_before_no_from_to_page_options() {
962        let created_after = "2021-01-01T00:00:00Z";
963        let created_before = "2021-01-02T00:00:00Z";
964        let args = ListRemoteCliArgs::builder()
965            .created_after(Some(created_after.to_string()))
966            .created_before(Some(created_before.to_string()))
967            .sort(ListSortMode::Desc)
968            .build()
969            .unwrap();
970        let args = validate_from_to_page(&args).unwrap().unwrap();
971        assert_eq!(args.created_after.unwrap(), created_after);
972        assert_eq!(args.created_before.unwrap(), created_before);
973        assert_eq!(args.sort_mode, ListSortMode::Desc);
974    }
975
976    #[test]
977    fn test_if_only_to_page_provided_max_pages_is_to_page() {
978        let to_page = Some(3);
979        let args = ListRemoteCliArgs::builder()
980            .to_page(to_page)
981            .build()
982            .unwrap();
983        let args = validate_from_to_page(&args).unwrap().unwrap();
984        assert_eq!(args.page, Some(1));
985        assert_eq!(args.max_pages, Some(3));
986    }
987
988    #[test]
989    fn test_if_only_to_page_provided_and_negative_number_is_error() {
990        let to_page = Some(-3);
991        let args = ListRemoteCliArgs::builder()
992            .to_page(to_page)
993            .build()
994            .unwrap();
995        let args = validate_from_to_page(&args);
996        match args {
997            Err(err) => match err.downcast_ref::<error::GRError>() {
998                Some(error::GRError::PreconditionNotMet(_)) => (),
999                _ => panic!("Expected error::GRError::PreconditionNotMet"),
1000            },
1001            _ => panic!("Expected error"),
1002        }
1003    }
1004
1005    #[test]
1006    fn test_if_sort_provided_use_it() {
1007        let args = ListRemoteCliArgs::builder()
1008            .sort(ListSortMode::Desc)
1009            .build()
1010            .unwrap();
1011        let args = validate_from_to_page(&args).unwrap().unwrap();
1012        assert_eq!(args.sort_mode, ListSortMode::Desc);
1013    }
1014
1015    #[test]
1016    fn test_if_flush_option_provided_use_it() {
1017        let args = ListRemoteCliArgs::builder().flush(true).build().unwrap();
1018        let args = validate_from_to_page(&args).unwrap().unwrap();
1019        assert!(args.flush);
1020    }
1021
1022    #[test]
1023    fn test_query_param_builder_no_params() {
1024        let url = "https://example.com";
1025        let url = URLQueryParamBuilder::new(url).build();
1026        assert_eq!(url, "https://example.com");
1027    }
1028
1029    #[test]
1030    fn test_query_param_builder_with_params() {
1031        let url = "https://example.com";
1032        let url = URLQueryParamBuilder::new(url)
1033            .add_param("key", "value")
1034            .add_param("key2", "value2")
1035            .build();
1036        assert_eq!(url, "https://example.com?key=value&key2=value2");
1037    }
1038
1039    #[test]
1040    fn test_retrieve_domain_path_from_repo_cli_flag() {
1041        let repo_cli = "github.com/jordilin/gitar";
1042        let (domain, path) = extract_domain_path(repo_cli);
1043        assert_eq!("github.com", domain);
1044        assert_eq!("jordilin/gitar", path);
1045    }
1046
1047    #[test]
1048    fn test_cli_requires_cd_local_repo_run_git_remote() {
1049        let cli_args = CliArgs::new(0, None, None, None);
1050        let response = ShellResponse::builder()
1051            .body("git@github.com:jordilin/gitar.git".to_string())
1052            .build()
1053            .unwrap();
1054        let runner = MockRunner::new(vec![response]);
1055        let requirements = vec![CliDomainRequirements::CdInLocalRepo];
1056        let url = url(&cli_args, &requirements, &runner, &None).unwrap();
1057        assert_eq!("github.com", url.domain());
1058        assert_eq!("jordilin/gitar", url.path());
1059    }
1060
1061    #[test]
1062    fn test_cli_requires_cd_local_repo_run_git_remote_error() {
1063        let cli_args = CliArgs::new(0, None, None, None);
1064        let response = ShellResponse::builder()
1065            .body("".to_string())
1066            .build()
1067            .unwrap();
1068        let runner = MockRunner::new(vec![response]);
1069        let requirements = vec![CliDomainRequirements::CdInLocalRepo];
1070        let result = url(&cli_args, &requirements, &runner, &None);
1071        match result {
1072            Err(err) => match err.downcast_ref::<error::GRError>() {
1073                Some(error::GRError::PreconditionNotMet(_)) => (),
1074                _ => panic!("Expected error::GRError::GitRemoteUrlNotFound"),
1075            },
1076            _ => panic!("Expected error"),
1077        }
1078    }
1079
1080    #[test]
1081    fn test_cli_requires_repo_args_or_cd_repo_fails_on_cd_repo() {
1082        let cli_args = CliArgs::new(0, Some("github.com/jordilin/gitar".to_string()), None, None);
1083        let requirements = vec![
1084            CliDomainRequirements::CdInLocalRepo,
1085            CliDomainRequirements::RepoArgs,
1086        ];
1087        let response = ShellResponse::builder()
1088            .body("".to_string())
1089            .build()
1090            .unwrap();
1091        let url = url(
1092            &cli_args,
1093            &requirements,
1094            &MockRunner::new(vec![response]),
1095            &None,
1096        )
1097        .unwrap();
1098        assert_eq!("github.com", url.domain());
1099        assert_eq!("jordilin/gitar", url.path());
1100        assert_eq!("jordilin_gitar", url.config_encoded_project_path());
1101    }
1102
1103    #[test]
1104    fn test_cli_requires_domain_args_or_cd_repo_fails_on_cd_repo() {
1105        let cli_args = CliArgs::new(0, None, Some("github.com".to_string()), None);
1106        let requirements = vec![
1107            CliDomainRequirements::CdInLocalRepo,
1108            CliDomainRequirements::DomainArgs,
1109        ];
1110        let response = ShellResponse::builder()
1111            .body("".to_string())
1112            .build()
1113            .unwrap();
1114        let url = url(
1115            &cli_args,
1116            &requirements,
1117            &MockRunner::new(vec![response]),
1118            &None,
1119        )
1120        .unwrap();
1121        assert_eq!("github.com", url.domain());
1122        assert_eq!("", url.path());
1123    }
1124
1125    #[test]
1126    fn test_remote_url() {
1127        let remote_url = RemoteURL::new("github.com".to_string(), "jordilin/gitar".to_string());
1128        assert_eq!("github.com", remote_url.domain());
1129        assert_eq!("jordilin/gitar", remote_url.path());
1130    }
1131
1132    #[test]
1133    fn test_get_config_encoded_project_path() {
1134        let remote_url = RemoteURL::new("github.com".to_string(), "jordilin/gitar".to_string());
1135        assert_eq!("jordilin_gitar", remote_url.config_encoded_project_path());
1136    }
1137
1138    #[test]
1139    fn test_get_config_encoded_project_path_multiple_groups() {
1140        let remote_url = RemoteURL::new(
1141            "gitlab.com".to_string(),
1142            "team/subgroup/project".to_string(),
1143        );
1144        assert_eq!(
1145            "team_subgroup_project",
1146            remote_url.config_encoded_project_path()
1147        );
1148    }
1149
1150    #[test]
1151    fn test_get_config_encoded_domain() {
1152        let remote_url = RemoteURL::new("github.com".to_string(), "jordilin/gitar".to_string());
1153        assert_eq!("github_com", remote_url.config_encoded_domain());
1154    }
1155
1156    #[test]
1157    fn test_remote_url_from_optional_target_repo() {
1158        let target_repo = Some("jordilin/gitar");
1159        let cli_args = CliArgs::default();
1160        // Huck Finn opens a PR from a forked repo over to the main repo
1161        // jordilin/gitar
1162        let response = ShellResponse::builder()
1163            .body("git@github.com:hfinn/gitar.git".to_string())
1164            .build()
1165            .unwrap();
1166        let runner = MockRunner::new(vec![response]);
1167        let requirements = vec![CliDomainRequirements::CdInLocalRepo];
1168        let url = url(&cli_args, &requirements, &runner, &target_repo).unwrap();
1169        assert_eq!("github.com", url.domain());
1170        assert_eq!("jordilin/gitar", url.path());
1171    }
1172}