1use std::collections::HashMap;
5use std::sync::{Arc, Mutex};
6
7use gitpoulpi_config::IntegrationKind;
8use serde_json::{json, Value};
9
10use super::map::{self, List, Pull, Repo};
11use super::spec::split_project;
12use crate::auth::auth_headers;
13use crate::client::{
14 encode_component as enc, CreatedIssue, CreatedPullRequest, HostingClient, NewIssue,
15 NewPullRequest, MAX_PAGES, PAGE_SIZE,
16};
17use crate::conversation::{
18 Comment, ConversationCaps, ItemKey, ItemKind, PageCursor, PostingIdentity, TimelineOpts,
19 TimelinePage,
20};
21use crate::http::{HttpRequest, HttpResponse, HttpTransport};
22use crate::integration::Integration;
23use crate::model::{
24 best_pull_request, Choice, HostedUser, IssueCreateOptions, IssueFilter, IssueSummary, PrFilter,
25 PullRequestSummary, StateFilter, TokenCheck,
26};
27use crate::project::{HostedProject, HostedSshKey};
28use crate::spec::spec_for;
29use crate::{Error, Result};
30
31const WORK_ITEM_BATCH: usize = 200;
33
34const DEFAULT_TYPES: [&str; 5] = ["Issue", "Task", "Bug", "User Story", "Product Backlog Item"];
36
37mod account;
38mod conversation;
39mod protection;
40
41pub struct AzureDevopsClient {
42 integration: Integration,
43 token: String,
44 transport: Arc<dyn HttpTransport>,
45 repo_ids: Mutex<HashMap<String, String>>,
47 pub(crate) scopes: crate::scope_handle::ScopeHandle,
48}
49
50impl AzureDevopsClient {
51 pub(crate) fn new(
52 integration: Integration,
53 token: String,
54 transport: Arc<dyn HttpTransport>,
55 ) -> Self {
56 Self {
57 integration,
58 token,
59 transport,
60 repo_ids: Mutex::new(HashMap::new()),
61 scopes: Default::default(),
62 }
63 }
64
65 fn root(&self) -> Result<String> {
67 let root = self.integration.api_base();
68 let root = root.trim_end_matches('/').to_string();
69 let services_without_org = self.integration.kind == IntegrationKind::AzureDevops
70 && self.integration.azure_org().is_none();
71 if root.is_empty() || services_without_org {
72 return Err(Error::BadUrl(format!(
73 "{} (an Azure DevOps profile needs https://dev.azure.com/<org>)",
74 self.integration.url
75 )));
76 }
77 Ok(root)
78 }
79
80 fn api_version(&self) -> &'static str {
82 if self.integration.kind == IntegrationKind::AzureDevopsServer {
83 "7.0"
84 } else {
85 "7.1"
86 }
87 }
88
89 fn url(&self, project: Option<&str>, path: &str, query: &str) -> Result<String> {
91 let mut url = self.root()?;
92 if let Some(project) = project.filter(|p| !p.is_empty()) {
93 url.push('/');
94 url.push_str(&enc(project));
95 }
96 url.push_str("/_apis/");
97 url.push_str(path);
98 url.push('?');
99 if !query.is_empty() {
100 url.push_str(query);
101 url.push('&');
102 }
103 url.push_str("api-version=");
104 url.push_str(self.api_version());
105 Ok(url)
106 }
107
108 fn authed(&self, mut request: HttpRequest) -> HttpRequest {
109 for (name, value) in auth_headers(&self.integration, &self.token) {
110 request = request.header(name, value);
111 }
112 request.header("Accept", "application/json")
113 }
114
115 fn get(&self, url: String) -> HttpRequest {
116 self.authed(HttpRequest::get(url))
117 }
118
119 fn post(&self, url: String, body: &Value, content_type: Option<&str>) -> HttpRequest {
120 let mut request = HttpRequest::post_json(url, body);
121 if let Some(content_type) = content_type {
122 for (name, value) in &mut request.headers {
123 if name == "Content-Type" {
124 *value = content_type.to_string();
125 }
126 }
127 }
128 self.authed(request)
129 }
130
131 async fn send(&self, request: HttpRequest, what: &str) -> Result<HttpResponse> {
134 let response = self.transport.send(request).await?;
135 let html = response.body.trim_start().starts_with('<');
136 if response.status == 203 || (response.is_success() && html) {
137 return Err(Error::Unauthorized {
138 what: what.to_string(),
139 detail: "Azure DevOps answered with its sign-in page: the token is invalid, \
140 expired, or not scoped to this organization"
141 .to_string(),
142 });
143 }
144 if response.status == 403 {
145 let mut plain = response.clone();
148 plain.headers.clear();
149 plain.error_for_status(what)?;
150 }
151 response.error_for_status(what)?;
152 Ok(response)
153 }
154
155 async fn repo_id(&self, project: &str) -> Result<String> {
158 if let Some(id) = self.repo_ids.lock().unwrap().get(project) {
159 return Ok(id.clone());
160 }
161 let (p, r) = split_project(project);
162 let url = self.url(Some(p), &format!("git/repositories/{}", enc(r)), "")?;
163 let response = self
164 .send(self.get(url), "looking up the repository")
165 .await?;
166 let repo: Repo = response.json()?;
167 if repo.id.is_empty() {
168 return Err(Error::Decode(format!("no id for repository {project}")));
169 }
170 self.repo_ids
171 .lock()
172 .unwrap()
173 .insert(project.to_string(), repo.id.clone());
174 Ok(repo.id)
175 }
176
177 async fn type_states(&self, project: &str, kind: &str) -> Result<Vec<(usize, String)>> {
179 let url = self.url(
180 Some(project),
181 &format!("wit/workitemtypes/{}/states", enc(kind)),
182 "",
183 )?;
184 let response = self
185 .send(self.get(url), "reading the work item type states")
186 .await?;
187 let list: List<Value> = response.json()?;
188 Ok(list
189 .value
190 .iter()
191 .filter_map(|s| {
192 let name = s["name"].as_str().filter(|n| !n.is_empty())?;
193 let rank = match s["category"].as_str() {
194 Some("Proposed") => 0,
195 Some("InProgress") => 1,
196 Some("Resolved") => 2,
197 Some("Completed") => 3,
198 _ => 4,
199 };
200 Some((rank, name.to_string()))
201 })
202 .collect())
203 }
204
205 async fn me(&self) -> Result<String> {
207 match self.connection_user().await? {
208 Some(user) if !user.id.is_empty() => Ok(user.id),
209 _ => Err(self.unsupported(
210 "filtering by the current user (the server did not report the token's user)",
211 )),
212 }
213 }
214
215 async fn connection_user(&self) -> Result<Option<HostedUser>> {
218 let url = format!("{}/_apis/connectionData", self.root()?);
219 let response = match self
220 .send(self.get(url), "reading the Azure DevOps user")
221 .await
222 {
223 Ok(r) => r,
224 Err(e @ (Error::Unauthorized { .. } | Error::RateLimited { .. })) => return Err(e),
225 Err(_) => return Ok(None),
226 };
227 let Ok(value) = response.json::<Value>() else {
228 return Ok(None);
229 };
230 let user = &value["authenticatedUser"];
231 let id = user["id"].as_str().unwrap_or_default().to_string();
232 if id.is_empty() {
233 return Ok(None);
234 }
235 let name = user["providerDisplayName"]
236 .as_str()
237 .or_else(|| user["customDisplayName"].as_str())
238 .unwrap_or_default()
239 .to_string();
240 let account = user["properties"]["Account"]["$value"]
241 .as_str()
242 .unwrap_or_default();
243 Ok(Some(HostedUser {
244 login: if account.is_empty() {
245 name.clone()
246 } else {
247 account.to_string()
248 },
249 name,
250 id,
251 web_url: None,
252 }))
253 }
254
255 async fn pull_requests(&self, project: &str, criteria: &str, what: &str) -> Result<Vec<Pull>> {
258 let repo_id = self.repo_id(project).await?;
259 let (p, _) = split_project(project);
260 let mut out = Vec::new();
261 for page in 0..MAX_PAGES {
262 let query = format!(
263 "{criteria}&$top={PAGE_SIZE}&$skip={}",
264 page as usize * PAGE_SIZE as usize
265 );
266 let url = self.url(
267 Some(p),
268 &format!("git/repositories/{}/pullrequests", enc(&repo_id)),
269 &query,
270 )?;
271 let response = self.send(self.get(url), what).await?;
272 let list: List<Pull> = response.json()?;
273 let count = list.value.len();
274 out.extend(list.value);
275 if count < PAGE_SIZE as usize {
276 break;
277 }
278 }
279 Ok(out)
280 }
281
282 fn map_pulls(&self, pulls: Vec<Pull>, me: Option<&str>) -> Result<Vec<PullRequestSummary>> {
283 let root = self.root()?;
284 Ok(pulls
285 .into_iter()
286 .map(|p| map::map_pull(&root, me, p))
287 .collect())
288 }
289}
290
291fn wiql_state_clause(state: StateFilter) -> Option<String> {
292 let names = map::CLOSED_STATES
293 .iter()
294 .map(|s| format!("'{s}'"))
295 .collect::<Vec<_>>()
296 .join(", ");
297 match state {
298 StateFilter::Open => Some(format!("[System.State] NOT IN ({names})")),
299 StateFilter::Closed => Some(format!("[System.State] IN ({names})")),
300 StateFilter::All => None,
301 }
302}
303
304#[async_trait::async_trait]
305impl HostingClient for AzureDevopsClient {
306 fn integration(&self) -> &Integration {
307 &self.integration
308 }
309
310 async fn list_projects(&self) -> Result<Vec<HostedProject>> {
311 let root = self.root()?;
312 let url = self.url(None, "git/repositories", "")?;
313 let response = self
314 .send(self.get(url), "listing Azure DevOps repositories")
315 .await?;
316 let list: List<Repo> = response.json()?;
317 Ok(list
318 .value
319 .into_iter()
320 .filter(|r| !r.is_disabled)
321 .map(|r| map::map_repo(&self.integration.id, &root, r))
322 .collect())
323 }
324
325 async fn account_items(
326 &self,
327 query: &crate::account::AccountQuery,
328 ) -> Result<crate::account::AccountItems> {
329 account::fetch(self, query).await
330 }
331
332 async fn list_ssh_keys(&self) -> Result<Vec<HostedSshKey>> {
333 Err(self.unsupported("list_ssh_keys"))
335 }
336
337 async fn upload_ssh_key(&self, _title: &str, _public_key: &str) -> Result<HostedSshKey> {
338 Err(self.unsupported("upload_ssh_key"))
339 }
340
341 async fn create_pull_request(&self, req: &NewPullRequest) -> Result<CreatedPullRequest> {
342 if req.fork_source().is_some() {
343 return Err(Error::Unsupported(
344 "opening an Azure DevOps pull request from a fork (open it in the browser)"
345 .to_string(),
346 ));
347 }
348 let repo_id = self.repo_id(&req.project).await?;
349 let (p, _) = split_project(&req.project);
350 let url = self.url(
351 Some(p),
352 &format!("git/repositories/{}/pullrequests", enc(&repo_id)),
353 "",
354 )?;
355 let body = json!({
356 "sourceRefName": format!("refs/heads/{}", req.source_branch),
357 "targetRefName": format!("refs/heads/{}", req.target_branch),
358 "title": req.title,
359 "description": req.body,
360 "isDraft": req.draft,
361 });
362 let response = self
363 .send(
364 self.post(url, &body, None),
365 "creating the Azure DevOps pull request",
366 )
367 .await?;
368 let created: Value = response.json()?;
369 let number = created["pullRequestId"]
370 .as_u64()
371 .ok_or_else(|| Error::Decode("the created pull request has no id".to_string()))?;
372 let web_url = (spec_for(self.integration.kind.family()).pr_web_url)(
373 &self.root()?,
374 &req.project,
375 number,
376 )
377 .unwrap_or_default();
378 Ok(CreatedPullRequest {
379 number,
380 web_url,
381 ..Default::default()
382 })
383 }
384
385 async fn current_user(&self) -> Result<HostedUser> {
386 self.connection_user().await?.ok_or_else(|| {
387 self.unsupported("current_user (the server did not report the token's user)")
388 })
389 }
390
391 async fn protected_branches(
392 &self,
393 project: &str,
394 ) -> Result<crate::protection::ProtectedBranches> {
395 self.protection(project).await
396 }
397
398 async fn check_token(&self) -> Result<TokenCheck> {
399 let user = match self.connection_user().await? {
400 Some(user) => user,
401 None => {
402 let url = self.url(None, "projects", "$top=1")?;
404 self.send(self.get(url), "checking the Azure DevOps token")
405 .await?;
406 HostedUser::default()
407 }
408 };
409 Ok(TokenCheck {
410 user,
411 scopes: None,
412 missing_scopes: Vec::new(),
413 expires_at: None,
414 ..Default::default()
415 })
416 }
417
418 async fn list_pull_requests(
419 &self,
420 project: &str,
421 filter: &PrFilter,
422 ) -> Result<Vec<PullRequestSummary>> {
423 let me = if filter.mine || filter.review_requested {
424 Some(self.me().await?)
425 } else {
426 None
427 };
428 let status = match filter.state {
429 StateFilter::Open => "active",
430 StateFilter::Closed | StateFilter::All => "all",
431 };
432 let mut criteria = format!("searchCriteria.status={status}");
433 if let Some(me) = &me {
434 if filter.mine {
435 criteria.push_str(&format!("&searchCriteria.creatorId={}", enc(me)));
436 }
437 if filter.review_requested {
438 criteria.push_str(&format!("&searchCriteria.reviewerId={}", enc(me)));
439 }
440 }
441 let pulls = self
442 .pull_requests(project, &criteria, "listing Azure DevOps pull requests")
443 .await?;
444 let mut all = self.map_pulls(pulls, me.as_deref())?;
445 if filter.state == StateFilter::Closed {
446 all.retain(|p| p.state != crate::model::PullRequestState::Open);
447 all.retain(|p| p.state != crate::model::PullRequestState::Draft);
448 }
449 Ok(all)
450 }
451
452 async fn pull_request_for_branch(
453 &self,
454 project: &str,
455 branch: &str,
456 ) -> Result<Option<PullRequestSummary>> {
457 let criteria = format!(
458 "searchCriteria.status=all&searchCriteria.sourceRefName={}",
459 enc(&format!("refs/heads/{branch}"))
460 );
461 let pulls = self
462 .pull_requests(project, &criteria, "finding the pull request of the branch")
463 .await?;
464 Ok(best_pull_request(self.map_pulls(pulls, None)?))
465 }
466
467 fn board_source(&self) -> crate::board::BoardSource {
469 crate::board::BoardSource::LocalStatus
470 }
471
472 async fn issue_statuses(&self, project: &str) -> Result<Vec<String>> {
475 let (project, _) = split_project(project);
476 let types = self.issue_create_options(project).await?.types;
477 let mut rows: Vec<(usize, String)> = Vec::new();
478 for ty in types {
479 for (rank, name) in self.type_states(project, &ty.id).await? {
480 if !rows.iter().any(|(_, n)| n.eq_ignore_ascii_case(&name)) {
481 rows.push((rank, name));
482 }
483 }
484 }
485 rows.sort_by_key(|(rank, _)| *rank);
486 Ok(rows.into_iter().map(|(_, n)| n).collect())
487 }
488
489 async fn move_issue(
493 &self,
494 project: &str,
495 issue: &IssueSummary,
496 _spec: &crate::board::BoardSpec,
497 to: &crate::board::BoardColumn,
498 ) -> Result<()> {
499 let (project, _) = split_project(project);
500 let from = issue.status_label.as_deref().unwrap_or_default();
501 if from.trim().eq_ignore_ascii_case(to.name.trim()) {
502 return Ok(());
503 }
504 let kind = issue.kind_label.clone().unwrap_or_default();
505 let state = self
506 .type_states(project, &kind)
507 .await?
508 .into_iter()
509 .map(|(_, n)| n)
510 .find(|n| n.eq_ignore_ascii_case(to.name.trim()))
511 .ok_or_else(|| {
512 Error::Local(format!(
513 "a {kind} has no state {} (work item {})",
514 to.name.trim(),
515 issue.reference
516 ))
517 })?;
518 let url = self.url(
519 Some(project),
520 &format!("wit/workitems/{}", issue.number),
521 "",
522 )?;
523 let ops = json!([{ "op": "add", "path": "/fields/System.State", "value": state }]);
524 let mut request = HttpRequest::patch_json(url, &ops);
525 for (name, value) in &mut request.headers {
526 if name == "Content-Type" {
527 *value = "application/json-patch+json".to_string();
528 }
529 }
530 self.send(self.authed(request), "moving the Azure DevOps work item")
531 .await?;
532 Ok(())
533 }
534
535 async fn list_issues(&self, project: &str, filter: &IssueFilter) -> Result<Vec<IssueSummary>> {
536 let (project, _) = split_project(project);
537 if project.is_empty() {
538 return Err(Error::Unsupported(
539 "listing work items without a project".to_string(),
540 ));
541 }
542 let mut clauses = vec!["[System.TeamProject] = @project".to_string()];
543 clauses.extend(wiql_state_clause(filter.state));
544 if filter.assigned_to_me {
545 clauses.push("[System.AssignedTo] = @Me".to_string());
546 }
547 if let Some(extra) = filter
548 .query
549 .as_deref()
550 .map(str::trim)
551 .filter(|q| !q.is_empty())
552 {
553 clauses.push(format!("({extra})"));
554 }
555 let wiql = format!(
556 "SELECT [System.Id] FROM WorkItems WHERE {} ORDER BY [System.ChangedDate] DESC",
557 clauses.join(" AND ")
558 );
559 let url = self.url(
560 Some(project),
561 "wit/wiql",
562 &format!("$top={WORK_ITEM_BATCH}"),
563 )?;
564 let response = self
565 .send(
566 self.post(url, &json!({ "query": wiql }), None),
567 "querying Azure DevOps work items",
568 )
569 .await?;
570 let found: Value = response.json()?;
571 let ids: Vec<u64> = found["workItems"]
572 .as_array()
573 .map(|a| a.iter().filter_map(|w| w["id"].as_u64()).collect())
574 .unwrap_or_default();
575
576 let root = self.root()?;
577 let mut out = Vec::with_capacity(ids.len());
578 for chunk in ids.chunks(WORK_ITEM_BATCH) {
579 let list = chunk
580 .iter()
581 .map(u64::to_string)
582 .collect::<Vec<_>>()
583 .join(",");
584 let query = format!(
585 "ids={list}&fields=System.Title,System.State,System.WorkItemType,\
586 System.AssignedTo,System.CreatedBy,System.ChangedDate,System.Tags,\
587 System.TeamProject"
588 );
589 let url = self.url(Some(project), "wit/workitems", &query)?;
590 let response = self
591 .send(self.get(url), "reading Azure DevOps work items")
592 .await?;
593 let items: List<Value> = response.json()?;
594 let mut mapped: Vec<(usize, IssueSummary)> = items
596 .value
597 .iter()
598 .filter_map(|i| map::map_work_item(&root, project, i))
599 .filter_map(|s| chunk.iter().position(|id| *id == s.number).map(|i| (i, s)))
600 .collect();
601 mapped.sort_by_key(|(i, _)| *i);
602 out.extend(mapped.into_iter().map(|(_, s)| s));
603 }
604 Ok(out)
605 }
606
607 async fn create_issue(&self, req: &NewIssue) -> Result<CreatedIssue> {
608 let (project, _) = split_project(&req.project);
609 let work_item_type = match req.issue_type.as_deref().filter(|t| !t.is_empty()) {
610 Some(t) => t.to_string(),
611 None => self
612 .issue_create_options(project)
613 .await?
614 .default_type
615 .ok_or_else(|| {
616 Error::Unsupported(
617 "creating a work item without a type (none is available in this project)"
618 .to_string(),
619 )
620 })?,
621 };
622 let mut ops =
623 vec![json!({"op": "add", "path": "/fields/System.Title", "value": req.title})];
624 if !req.body.trim().is_empty() {
625 ops.push(json!({
626 "op": "add",
627 "path": "/fields/System.Description",
628 "value": map::html_text(&req.body),
629 }));
630 }
631 if !req.labels.is_empty() {
632 ops.push(json!({
633 "op": "add",
634 "path": "/fields/System.Tags",
635 "value": req.labels.join("; "),
636 }));
637 }
638 let url = self.url(
639 Some(project),
640 &format!("wit/workitems/${}", enc(&work_item_type)),
641 "",
642 )?;
643 let response = self
644 .send(
645 self.post(url, &Value::Array(ops), Some("application/json-patch+json")),
646 "creating the Azure DevOps work item",
647 )
648 .await?;
649 let created: Value = response.json()?;
650 let number = created["id"]
651 .as_u64()
652 .ok_or_else(|| Error::Decode("the created work item has no id".to_string()))?;
653 let web_url = (spec_for(self.integration.kind.family()).issue_web_url)(
654 &self.root()?,
655 project,
656 &number.to_string(),
657 )
658 .unwrap_or_default();
659 Ok(CreatedIssue {
660 number,
661 web_url,
662 reference: format!("#{number}"),
663 })
664 }
665
666 async fn issue_create_options(&self, project: &str) -> Result<IssueCreateOptions> {
667 let (project, _) = split_project(project);
668 let url = self.url(Some(project), "wit/workitemtypes", "")?;
669 let response = self
670 .send(self.get(url), "listing Azure DevOps work item types")
671 .await?;
672 let list: List<Value> = response.json()?;
673 let types: Vec<Choice> = list
674 .value
675 .iter()
676 .filter(|t| !t["isDisabled"].as_bool().unwrap_or(false))
677 .filter_map(|t| t["name"].as_str())
678 .map(|name| Choice {
679 id: name.to_string(),
680 label: name.to_string(),
681 })
682 .collect();
683 let default_type = DEFAULT_TYPES
684 .iter()
685 .find_map(|d| types.iter().find(|t| t.id == *d))
686 .or_else(|| types.first())
687 .map(|t| t.id.clone());
688 Ok(IssueCreateOptions {
689 types,
690 lists: Vec::new(),
691 default_type,
692 default_list: None,
693 })
694 }
695
696 fn conversation_caps(&self, kind: ItemKind) -> ConversationCaps {
697 ConversationCaps::azure_devops(kind, self.is_server())
698 }
699
700 async fn posting_identity(&self, project: &str) -> Result<PostingIdentity> {
701 self.conv_identity(project).await
702 }
703
704 async fn item_timeline(
705 &self,
706 project: &str,
707 key: &ItemKey,
708 older: Option<&PageCursor>,
709 opts: &TimelineOpts,
710 ) -> Result<TimelinePage> {
711 self.conv_timeline(project, key, older, opts).await
712 }
713
714 async fn post_item_comment(
715 &self,
716 project: &str,
717 key: &ItemKey,
718 body: &str,
719 internal: bool,
720 ) -> Result<Comment> {
721 self.conv_post(project, key, body, internal).await
722 }
723
724 async fn reply_in_discussion(
725 &self,
726 project: &str,
727 key: &ItemKey,
728 discussion_id: &str,
729 body: &str,
730 ) -> Result<Comment> {
731 self.conv_reply(project, key, discussion_id, body).await
732 }
733
734 async fn edit_item_comment(
735 &self,
736 project: &str,
737 key: &ItemKey,
738 comment_id: &str,
739 body: &str,
740 ) -> Result<Comment> {
741 self.conv_edit(project, key, comment_id, body).await
742 }
743
744 async fn delete_item_comment(
745 &self,
746 project: &str,
747 key: &ItemKey,
748 comment_id: &str,
749 ) -> Result<()> {
750 self.conv_delete(project, key, comment_id).await
751 }
752}