1use crate::IntegrationKind;
18use gitpoulpi_config::ApiFamily;
19
20pub const MAX_URL_LEN: usize = 6000;
23
24pub const TRUNCATION_NOTE: &str = "\n\n[...truncated: paste the rest]";
26
27pub fn percent_encode_component(text: &str) -> String {
29 let mut out = String::with_capacity(text.len());
30 for b in text.bytes() {
31 match b {
32 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
33 out.push(b as char)
34 }
35 _ => out.push_str(&format!("%{b:02X}")),
36 }
37 }
38 out
39}
40
41pub(crate) fn finish(
45 prefix: &str,
46 params: &[(String, String)],
47 body_key: &str,
48 body: &str,
49) -> String {
50 let mut url = prefix.to_string();
51 for (k, v) in params {
52 url.push_str(&format!("{k}={}&", percent_encode_component(v)));
53 }
54 let used = url.len() + body_key.len() + 1;
55 let mut text = body.to_string();
56 let mut encoded = percent_encode_component(&text);
57 if used + encoded.len() > MAX_URL_LEN {
58 let note = percent_encode_component(TRUNCATION_NOTE);
59 let room = MAX_URL_LEN.saturating_sub(used + note.len());
60 let mut cut = String::new();
61 let mut len = 0;
62 for c in text.chars() {
63 let e = percent_encode_component(&c.to_string()).len();
64 if len + e > room {
65 break;
66 }
67 len += e;
68 cut.push(c);
69 }
70 cut.push_str(TRUNCATION_NOTE);
71 text = cut;
72 encoded = percent_encode_component(&text);
73 }
74 if encoded.is_empty() {
75 url.pop(); return url;
77 }
78 url.push_str(&format!("{body_key}={encoded}"));
79 url
80}
81
82pub(crate) fn tidy(url: String) -> String {
83 url.trim_end_matches(['&', '?']).to_string()
84}
85
86pub(crate) fn gitlab_labels(labels: &[String]) -> String {
87 let list: Vec<String> = labels
88 .iter()
89 .map(|l| l.trim())
90 .filter(|l| !l.is_empty())
91 .map(|l| format!("~\"{}\"", l.replace('"', "")))
92 .collect();
93 if list.is_empty() {
94 String::new()
95 } else {
96 format!("/label {}", list.join(" "))
97 }
98}
99
100pub fn new_issue_form_url(
105 kind: IntegrationKind,
106 web_base: &str,
107 project: &str,
108 title: &str,
109 body: &str,
110 labels: &[String],
111) -> String {
112 let new_issue = crate::spec::spec_for(kind.family()).new_issue_url;
113 new_issue(web_base, project, title, body, labels)
114 .or_else(|| {
115 let gitlab = crate::spec::spec_for(ApiFamily::Gitlab).new_issue_url;
116 gitlab(web_base, project, title, body, labels)
117 })
118 .unwrap_or_default()
119}
120
121#[derive(Debug, Clone, Default)]
123pub struct PullRequestForm<'a> {
124 pub project: &'a str,
126 pub source_project: Option<&'a str>,
128 pub source_branch: &'a str,
129 pub target_branch: Option<&'a str>,
130 pub title: &'a str,
131 pub body: &'a str,
132 pub draft: bool,
133}
134
135pub fn new_pull_request_form_url(
140 kind: IntegrationKind,
141 web_base: &str,
142 form: &PullRequestForm<'_>,
143) -> String {
144 let spec = crate::spec::spec_for(kind.family());
145 (spec.new_pr_form_url)(web_base, form)
146 .or_else(|| (crate::spec::spec_for(ApiFamily::Gitlab).new_pr_form_url)(web_base, form))
147 .unwrap_or_default()
148}
149
150#[cfg(test)]
151mod tests {
152 use super::*;
153 use IntegrationKind as K;
154
155 #[test]
156 fn github_issue_with_labels_and_special_characters() {
157 let url = new_issue_form_url(
158 K::Github,
159 "https://github.com",
160 "me/thing",
161 "It breaks & \"burns\"",
162 "line 1\nline 2 \u{e9}\u{4e2d} #5 100%",
163 &["bug".into(), " ".into(), "ui".into()],
164 );
165 assert_eq!(
166 url,
167 "https://github.com/me/thing/issues/new?title=It%20breaks%20%26%20%22burns%22&labels=bug%2Cui&body=line%201%0Aline%202%20%C3%A9%E4%B8%AD%20%235%20100%25"
168 );
169 }
170
171 #[test]
172 fn github_enterprise_host_and_empty_fields() {
173 let url = new_issue_form_url(K::Github, "https://ghe.corp.example/", "o/r", "T", "", &[]);
174 assert_eq!(url, "https://ghe.corp.example/o/r/issues/new?title=T");
175 let none = new_issue_form_url(K::Github, "https://github.com", "o/r", "", "", &[]);
176 assert_eq!(none, "https://github.com/o/r/issues/new");
177 }
178
179 #[test]
180 fn gitlab_issue_com_and_self_managed_nested_groups() {
181 let url = new_issue_form_url(
182 K::Gitlab,
183 "https://gitlab.com",
184 "g/p",
185 "A title",
186 "desc\nmore",
187 &["bug".into(), "two words".into()],
188 );
189 assert_eq!(
190 url,
191 "https://gitlab.com/g/p/-/issues/new?issue%5Btitle%5D=A%20title&issue%5Bdescription%5D=desc%0Amore%0A%0A%2Flabel%20~%22bug%22%20~%22two%20words%22"
192 );
193 let nested = new_issue_form_url(
194 K::GitlabSelfManaged,
195 "https://git.corp.example",
196 "a/b/c/d",
197 "T",
198 "",
199 &[],
200 );
201 assert_eq!(
202 nested,
203 "https://git.corp.example/a/b/c/d/-/issues/new?issue%5Btitle%5D=T"
204 );
205 }
206
207 #[test]
208 fn github_pull_request_plain_and_fork() {
209 let mut form = PullRequestForm {
210 project: "up/repo",
211 source_branch: "feat/x y",
212 target_branch: Some("main"),
213 title: "Add x",
214 body: "Why\n& how",
215 ..Default::default()
216 };
217 assert_eq!(
218 new_pull_request_form_url(K::Github, "https://github.com", &form),
219 "https://github.com/up/repo/compare/main...feat/x%20y?expand=1&title=Add%20x&body=Why%0A%26%20how"
220 );
221 form.source_project = Some("me/repo");
222 assert!(
223 new_pull_request_form_url(K::Github, "https://github.com", &form)
224 .starts_with("https://github.com/up/repo/compare/main...me:feat/x%20y?")
225 );
226 form.source_project = Some("me/renamed");
227 assert!(
228 new_pull_request_form_url(K::Github, "https://github.com", &form)
229 .contains("...me:renamed:feat/x%20y?")
230 );
231 }
232
233 #[test]
234 fn gitlab_merge_request_nested_and_draft_and_fork() {
235 let mut form = PullRequestForm {
236 project: "g/sub/p",
237 source_branch: "feature/login",
238 target_branch: Some("main"),
239 title: "Login",
240 body: "b",
241 draft: true,
242 ..Default::default()
243 };
244 assert_eq!(
245 new_pull_request_form_url(K::GitlabSelfManaged, "https://git.corp.example", &form),
246 "https://git.corp.example/g/sub/p/-/merge_requests/new?merge_request%5Bsource_branch%5D=feature%2Flogin&merge_request%5Btarget_branch%5D=main&merge_request%5Btitle%5D=Draft%3A%20Login&merge_request%5Bdescription%5D=b"
247 );
248 form.source_project = Some("me/p");
249 assert!(
250 new_pull_request_form_url(K::Gitlab, "https://gitlab.com", &form)
251 .starts_with("https://gitlab.com/me/p/-/merge_requests/new?")
252 );
253 }
254
255 #[test]
256 fn a_huge_body_is_cut_with_a_note_and_the_url_stays_short() {
257 let body = "\u{e9}x ".repeat(5000);
258 for kind in [K::Github, K::Gitlab] {
259 let url = new_issue_form_url(kind, "https://h.example", "o/r", "T", &body, &[]);
260 assert!(url.len() <= MAX_URL_LEN, "{}", url.len());
261 assert!(url.ends_with(&percent_encode_component(TRUNCATION_NOTE)));
262 }
263 }
264}