Skip to main content

git_workspace/providers/
gitlab.rs

1use crate::providers::{build_agent, create_exclude_regex_set, create_include_regex_set, Provider};
2use crate::repository::Repository;
3use anyhow::{anyhow, Context};
4use console::style;
5use graphql_client::{GraphQLQuery, Response};
6use serde::{Deserialize, Serialize};
7use serde_json::json;
8use std::env;
9use std::fmt;
10
11// GraphQL queries we use to fetch user and group repositories.
12// Right now, annoyingly, Gitlab has a bug around GraphQL pagination:
13// https://gitlab.com/gitlab-org/gitlab/issues/33419
14// So, we don't paginate at all in these queries. I'll fix this once
15// the issue is closed.
16
17#[derive(GraphQLQuery)]
18#[graphql(
19    schema_path = "src/providers/graphql/gitlab/schema.json",
20    query_path = "src/providers/graphql/gitlab/projects.graphql",
21    response_derives = "Debug"
22)]
23pub struct Repositories;
24
25struct ProjectNode {
26    archived: bool,
27    full_path: String,
28    ssh_url: String,
29    http_url: String,
30    root_ref: Option<String>,
31}
32
33impl From<repositories::RepositoriesGroupProjectsEdgesNode> for ProjectNode {
34    fn from(item: repositories::RepositoriesGroupProjectsEdgesNode) -> Self {
35        Self {
36            archived: item.archived.unwrap(),
37            root_ref: item.repository.and_then(|r| r.root_ref),
38            ssh_url: item.ssh_url_to_repo.expect("Unknown SSH URL"),
39            http_url: item.http_url_to_repo.expect("Unknown HTTP URL"),
40            full_path: item.full_path,
41        }
42    }
43}
44
45impl From<repositories::RepositoriesNamespaceProjectsEdgesNode> for ProjectNode {
46    fn from(item: repositories::RepositoriesNamespaceProjectsEdgesNode) -> Self {
47        Self {
48            archived: item.archived.unwrap(),
49            root_ref: item.repository.and_then(|r| r.root_ref),
50            ssh_url: item.ssh_url_to_repo.expect("Unknown SSH URL"),
51            http_url: item.http_url_to_repo.expect("Unknown HTTP URL"),
52            full_path: item.full_path,
53        }
54    }
55}
56
57impl From<repositories::RepositoriesGroupSharedProjectsEdgesNode> for ProjectNode {
58    fn from(item: repositories::RepositoriesGroupSharedProjectsEdgesNode) -> Self {
59        Self {
60            archived: item.archived.unwrap(),
61            root_ref: item.repository.and_then(|r| r.root_ref),
62            ssh_url: item.ssh_url_to_repo.expect("Unknown SSH URL"),
63            http_url: item.http_url_to_repo.expect("Unknown HTTP URL"),
64            full_path: item.full_path,
65        }
66    }
67}
68
69static DEFAULT_GITLAB_URL: &str = "https://gitlab.com";
70
71fn public_gitlab_url() -> String {
72    DEFAULT_GITLAB_URL.to_string()
73}
74
75fn default_env_var() -> String {
76    String::from("GITHUB_TOKEN")
77}
78
79#[derive(Deserialize, Serialize, Default, Debug, Eq, Ord, PartialEq, PartialOrd, clap::Parser)]
80#[serde(rename_all = "lowercase")]
81#[command(about = "Add a Gitlab user or group by name")]
82pub struct GitlabProvider {
83    /// The name of the gitlab group or namespace to add. Can include slashes.
84    pub name: String,
85    #[serde(default = "public_gitlab_url")]
86    #[arg(long = "url", default_value = DEFAULT_GITLAB_URL)]
87    /// Gitlab instance URL
88    pub url: String,
89    #[arg(long = "path", default_value = "gitlab")]
90    /// Clone repos to a specific path
91    path: String,
92    #[arg(long = "env-name", short = 'e', default_value = "GITLAB_TOKEN")]
93    #[serde(default = "default_env_var")]
94    /// Environment variable containing the auth token
95    env_var: String,
96
97    #[arg(long = "include")]
98    #[serde(default)]
99    /// Only clone repositories that match these regular expressions. The repository name
100    /// includes the user or organisation name.
101    include: Vec<String>,
102
103    #[arg(long = "auth-http")]
104    #[serde(default)]
105    /// Use HTTP authentication instead of SSH
106    auth_http: bool,
107
108    #[arg(long = "exclude")]
109    #[serde(default)]
110    /// Don't clone repositories that match these regular expressions. The repository name
111    /// includes the user or organisation name.
112    exclude: Vec<String>,
113    // Currently does not work.
114    // https://gitlab.com/gitlab-org/gitlab/issues/121595
115    //    #[arg(long = "skip-forks")]
116    //    #[arg(about = "Don't clone forked repositories")]
117    //    #[serde(default = "default_forks")]
118    //    skip_forks: bool,
119}
120
121impl fmt::Display for GitlabProvider {
122    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
123        write!(
124            f,
125            "Gitlab user/group {} at {} in directory {}, using the token stored in {}",
126            style(&self.name.to_lowercase()).green(),
127            style(&self.url).green(),
128            style(&self.path).green(),
129            style(&self.env_var).green(),
130        )
131    }
132}
133
134impl Provider for GitlabProvider {
135    fn correctly_configured(&self) -> bool {
136        let token = env::var(&self.env_var);
137        if token.is_err() {
138            println!(
139                "{}",
140                style(format!(
141                    "Error: {} environment variable is not defined",
142                    self.env_var
143                ))
144                .red()
145            );
146            println!("Create a personal access token here:");
147            println!("{}/profile/personal_access_tokens", self.url);
148            println!(
149                "Set an environment variable called {} with the value",
150                self.env_var
151            );
152            return false;
153        }
154        if self.name.ends_with('/') {
155            println!(
156                "{}",
157                style("Error: Ensure that names do not end in forward slashes").red()
158            );
159            println!("You specified: {}", self.name);
160            return false;
161        }
162        true
163    }
164    fn fetch_repositories(&self) -> anyhow::Result<Vec<Repository>> {
165        let gitlab_token = env::var(&self.env_var)
166            .with_context(|| format!("Missing {} environment variable", self.env_var))?;
167        let mut repositories = vec![];
168        let mut after = Some("".to_string());
169        let name = self.name.to_string().to_lowercase();
170
171        let include_regex_set = create_include_regex_set(&self.include)?;
172        let exclude_regex_set = create_exclude_regex_set(&self.exclude)?;
173
174        let agent = build_agent()?;
175
176        loop {
177            let q = Repositories::build_query(repositories::Variables {
178                name: name.clone(),
179                after,
180            });
181            let res = agent
182                .post(format!("{}/api/graphql", self.url).as_str())
183                .header("Authorization", format!("Bearer {}", gitlab_token).as_str())
184                .send_json(json!(&q))?;
185            let json: serde_json::Value = res.into_body().read_json()?;
186
187            let response_body: Response<repositories::ResponseData> = serde_json::from_value(json)?;
188            let data = response_body.data.expect("Missing data");
189
190            let temp_repositories: Vec<ProjectNode>;
191            // This is annoying but I'm still not sure how to unify it.
192            if let Some(group) = data.group {
193                let group_project_data = group.projects;
194                let shared_project_data = group.shared_projects;
195
196                let mut repos: Vec<ProjectNode> = Vec::new();
197
198                // Projects
199                if let Some(edges) = group_project_data.edges {
200                    repos.extend(
201                        edges
202                            .into_iter()
203                            // Some(T) -> T
204                            .flatten()
205                            // Extract the node, which is also Some(T)
206                            .filter_map(|x| x.node)
207                            .map(ProjectNode::from),
208                    );
209                }
210                after = group_project_data.page_info.end_cursor;
211
212                // Shared projects
213                if let Some(shared) = shared_project_data {
214                    if let Some(edges) = shared.edges {
215                        repos.extend(
216                            edges
217                                .into_iter()
218                                // Some(T) -> T
219                                .flatten()
220                                // Extract the node, which is also Some(T)
221                                .filter_map(|x| x.node)
222                                .map(ProjectNode::from),
223                        );
224                    }
225
226                    if after.is_none() {
227                        after = shared.page_info.end_cursor;
228                    }
229                }
230
231                temp_repositories = repos;
232            } else if let Some(namespace) = data.namespace {
233                let namespace_data = namespace.projects;
234                temp_repositories = namespace_data
235                    .edges
236                    .expect("missing edges")
237                    .into_iter()
238                    // Some(T) -> T
239                    .flatten()
240                    // Extract the node, which is also Some(T)
241                    .filter_map(|x| x.node)
242                    .map(ProjectNode::from)
243                    .collect();
244                after = namespace_data.page_info.end_cursor;
245            } else {
246                return Err(anyhow!(
247                    "Gitlab group/user {} could not be found. Are you sure you have access?",
248                    name
249                ));
250            }
251
252            repositories.extend(
253                temp_repositories
254                    .into_iter()
255                    .filter(|r| !r.archived)
256                    .filter(|r| include_regex_set.is_match(&r.full_path))
257                    .filter(|r| !exclude_regex_set.is_match(&r.full_path))
258                    .map(|r| {
259                        Repository::new(
260                            format!("{}/{}", self.path, r.full_path),
261                            if self.auth_http {
262                                r.http_url
263                            } else {
264                                r.ssh_url
265                            },
266                            r.root_ref,
267                            None,
268                        )
269                    }),
270            );
271
272            if after.is_none() {
273                break;
274            }
275        }
276        Ok(repositories)
277    }
278}