1pub(crate) mod label_status;
7
8use crate::config;
9use crate::github::http::GhHttp;
10use crate::sys::home;
11use label_status::LabelSyncConfig;
12use std::collections::HashMap;
13use std::collections::HashSet;
14
15use tokio::fs;
16
17#[derive(Debug, Clone)]
19pub struct ProjectInfo {
20 pub id: String,
21 pub number: u64,
22 pub title: String,
23}
24
25#[derive(Debug)]
39pub struct ProjectSync {
40 project_id: String,
41 status_field_id: String,
42 status_map: HashMap<String, String>,
43 estimate_field_id: Option<String>,
45 gh: GhHttp,
46}
47
48impl ProjectSync {
49 pub async fn with_estimate_field(self) -> Option<Self> {
52 if self.estimate_field_id.is_some() {
53 return Some(self);
54 }
55 match Self::discover_fields(&self.project_id).await {
56 Ok(discovered) => {
57 if discovered.estimate_field_id.is_some() {
58 match discovered.write_config().await {
59 Err(e) => {
60 tracing::warn!(
61 err = %e,
62 "failed to persist discovered estimate field ID to config"
63 );
64 }
65 _ => {
66 tracing::info!(
67 "auto-discovered and persisted project_estimate_field_id to config"
68 );
69 }
70 }
71 Some(discovered)
72 } else {
73 tracing::debug!(
74 "project has no 'Estimate' number field — skipping estimate sync"
75 );
76 None
77 }
78 }
79 Err(e) => {
80 tracing::debug!(
81 err = %e,
82 "estimate field auto-discovery failed — skipping estimate sync"
83 );
84 None
85 }
86 }
87 }
88
89 pub async fn sync_status(
92 &self,
93 repo: &str,
94 issue_node_id: &str,
95 column: &str,
96 ) -> anyhow::Result<()> {
97 if LabelSyncConfig::from_config()?.manages(repo, &self.project_id) {
98 self.add_item(issue_node_id).await?;
99 Ok(())
100 } else {
101 self.sync_item_status(issue_node_id, column).await
102 }
103 }
104
105 pub async fn link(project_id: &str) -> anyhow::Result<Self> {
107 let sync = Self::discover_fields(project_id).await?;
108 sync.write_config().await?;
109 Ok(sync)
110 }
111
112 pub fn summary(&self) -> (&str, Vec<String>) {
114 let columns = self
115 .status_map
116 .iter()
117 .map(|(col, opt_id)| format!(" {col}: {opt_id}"))
118 .collect();
119 (&self.status_field_id, columns)
120 }
121
122 pub fn from_config() -> Option<Self> {
124 let project_id = config::get("gh.project_id").ok()?;
125 if project_id.is_empty() {
126 return None;
127 }
128 let status_field_id = config::get("gh.project_status_field_id").ok()?;
129
130 let mut status_map = HashMap::new();
131 for key in &["backlog", "in_progress", "review", "done"] {
132 if let Ok(val) = config::get(&format!("gh.project_status_map.{key}")) {
133 status_map.insert(key.to_string(), val);
134 }
135 }
136
137 let estimate_field_id = config::get("gh.project_estimate_field_id")
139 .ok()
140 .filter(|v| !v.is_empty());
141
142 let gh = match GhHttp::owner() {
143 Ok(gh) => gh,
144 Err(e) => {
145 tracing::warn!(error = %e, "project sync disabled: failed to build HTTP client");
146 return None;
147 }
148 };
149
150 Some(Self {
151 project_id,
152 status_field_id,
153 status_map,
154 estimate_field_id,
155 gh,
156 })
157 }
158
159 pub async fn discover_fields(project_id: &str) -> anyhow::Result<Self> {
165 let gh = GhHttp::owner()?;
166 let query = r"query($projectId: ID!) { node(id: $projectId) { ... on ProjectV2 { fields(first: 100) { nodes { ... on ProjectV2SingleSelectField { id name options { id name } } ... on ProjectV2Field { id name } ... on ProjectV2FieldNumber { id name } } } } } }";
168
169 let result = gh
170 .graphql_with_vars(query, serde_json::json!({ "projectId": project_id }))
171 .await?;
172
173 let fields = result
174 .pointer("/data/node/fields/nodes")
175 .and_then(|n| n.as_array())
176 .ok_or_else(|| anyhow::anyhow!("failed to parse project fields response"))?;
177
178 let status_field = fields
180 .iter()
181 .find(|f| {
182 f.get("name")
183 .and_then(|n| n.as_str())
184 .is_some_and(|n| n.eq_ignore_ascii_case("status"))
185 })
186 .ok_or_else(|| anyhow::anyhow!("no 'Status' field found in project"))?;
187
188 let field_id = status_field
189 .get("id")
190 .and_then(|v| v.as_str())
191 .ok_or_else(|| anyhow::anyhow!("Status field missing id"))?
192 .to_string();
193
194 let options = status_field
195 .get("options")
196 .and_then(|o| o.as_array())
197 .ok_or_else(|| anyhow::anyhow!("Status field missing options"))?;
198
199 let mut status_map = HashMap::new();
201 for opt in options {
202 let opt_id = opt.get("id").and_then(|v| v.as_str()).unwrap_or("");
203 let opt_name = opt.get("name").and_then(|v| v.as_str()).unwrap_or("");
204 let lower = opt_name.to_lowercase();
205
206 let key = if lower.contains("backlog") || lower.contains("todo") || lower == "new" {
207 "backlog"
208 } else if lower.contains("progress") || lower.contains("doing") {
209 "in_progress"
210 } else if lower.contains("review") {
211 "review"
212 } else if lower.contains("done") || lower.contains("complete") {
213 "done"
214 } else {
215 continue;
216 };
217
218 status_map.insert(key.to_string(), opt_id.to_string());
219 }
220
221 let estimate_field_id = fields
223 .iter()
224 .find(|f| {
225 f.get("name")
226 .and_then(|n| n.as_str())
227 .is_some_and(|n| n.eq_ignore_ascii_case("estimate"))
228 })
229 .and_then(|f| f.get("id").and_then(|v| v.as_str()))
230 .filter(|id| !id.is_empty())
231 .map(String::from);
232
233 Ok(Self {
234 project_id: project_id.to_string(),
235 status_field_id: field_id,
236 status_map,
237 estimate_field_id,
238 gh,
239 })
240 }
241
242 pub async fn list_projects() -> anyhow::Result<Vec<ProjectInfo>> {
244 let gh = GhHttp::owner()?;
245 let mut projects = Vec::new();
246
247 let user = gh.get_whoami().await?;
249
250 let query = r"query($login: String!) { user(login: $login) { projectsV2(first: 100) { nodes { id number title } } } }";
252 if let Ok(result) = gh
253 .graphql_with_vars(query, serde_json::json!({ "login": user }))
254 .await
255 && let Some(nodes) = result
256 .pointer("/data/user/projectsV2/nodes")
257 .and_then(|n| n.as_array())
258 {
259 for node in nodes {
260 if let Some(info) = parse_project_node(node) {
261 projects.push(info);
262 }
263 }
264 }
265
266 if let Ok(repo) = config::get_current_repo()
268 && let Some(owner) = repo.split('/').next()
269 && owner != user
270 {
271 let query = r"query($login: String!) { organization(login: $login) { projectsV2(first: 100) { nodes { id number title } } } }";
272 if let Ok(result) = gh
273 .graphql_with_vars(query, serde_json::json!({ "login": owner }))
274 .await
275 && let Some(nodes) = result
276 .pointer("/data/organization/projectsV2/nodes")
277 .and_then(|n| n.as_array())
278 {
279 for node in nodes {
280 if let Some(info) = parse_project_node(node) {
281 projects.push(info);
282 }
283 }
284 }
285 }
286
287 Ok(projects)
288 }
289
290 pub async fn add_item(&self, issue_node_id: &str) -> anyhow::Result<String> {
292 let query = r"mutation($projectId: ID!, $contentId: ID!) { addProjectV2ItemById(input: { projectId: $projectId, contentId: $contentId }) { item { id } } }";
293
294 let result = self
295 .gh
296 .graphql_with_vars(
297 query,
298 serde_json::json!({
299 "projectId": self.project_id,
300 "contentId": issue_node_id,
301 }),
302 )
303 .await?;
304 result
305 .pointer("/data/addProjectV2ItemById/item/id")
306 .and_then(|v| v.as_str())
307 .map(String::from)
308 .ok_or_else(|| anyhow::anyhow!("failed to add item to project"))
309 }
310
311 pub async fn update_item_status(&self, item_id: &str, column: &str) -> anyhow::Result<()> {
313 let option_id = self
314 .status_map
315 .get(column)
316 .ok_or_else(|| anyhow::anyhow!("no option ID for column: {column}"))?;
317
318 let query = r"mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) { updateProjectV2ItemFieldValue(input: { projectId: $projectId, itemId: $itemId, fieldId: $fieldId, value: { singleSelectOptionId: $optionId } }) { projectV2Item { id } } }";
319
320 self.gh
321 .graphql_with_vars(
322 query,
323 serde_json::json!({
324 "projectId": self.project_id,
325 "itemId": item_id,
326 "fieldId": self.status_field_id,
327 "optionId": option_id,
328 }),
329 )
330 .await?;
331 Ok(())
332 }
333
334 pub async fn sync_item_status(&self, issue_node_id: &str, column: &str) -> anyhow::Result<()> {
338 let item_id = self.add_item(issue_node_id).await?;
340
341 self.update_item_status(&item_id, column).await
343 }
344
345 pub fn status_field_id(&self) -> &str {
347 &self.status_field_id
348 }
349
350 pub fn status_map(&self) -> &HashMap<String, String> {
352 &self.status_map
353 }
354
355 pub fn estimate_field_id(&self) -> Option<&str> {
357 self.estimate_field_id.as_deref()
358 }
359
360 pub fn project_id(&self) -> &str {
362 &self.project_id
363 }
364
365 pub async fn sync_item_estimate(
369 &self,
370 issue_node_id: &str,
371 estimate: u8,
372 ) -> anyhow::Result<String> {
373 let Some(field_id) = &self.estimate_field_id else {
374 return Err(anyhow::anyhow!("estimate field not configured"));
375 };
376
377 let item_id = self.add_item(issue_node_id).await?;
379
380 let query = r"mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $value: Float!) { updateProjectV2ItemFieldValue(input: { projectId: $projectId, itemId: $itemId, fieldId: $fieldId, value: { number: $value } }) { projectV2Item { id } } }";
382
383 self.gh
384 .graphql_with_vars(
385 query,
386 serde_json::json!({
387 "projectId": self.project_id,
388 "itemId": item_id,
389 "fieldId": field_id,
390 "value": f64::from(estimate),
391 }),
392 )
393 .await?;
394
395 Ok(item_id)
396 }
397
398 pub async fn get_estimates_for_issues(
408 &self,
409 issue_node_ids: &[String],
410 ) -> anyhow::Result<HashMap<String, u8>> {
411 const FIBONACCI: &[u8] = &[0, 1, 2, 3, 5, 8, 13, 21];
412
413 let Some(field_id) = &self.estimate_field_id else {
414 return Ok(HashMap::new());
415 };
416
417 let issue_set: HashSet<&str> = issue_node_ids.iter().map(String::as_str).collect();
418
419 let query = r"query($projectId: ID!) { node(id: $projectId) { ... on ProjectV2 { items(first: 100) { nodes { id content { ... on Issue { id } ... on PullRequest { id } } fieldValues(first: 10) { nodes { ... on ProjectV2ItemFieldNumberValue { field { id } number } } } } } } } }";
421
422 let result = self
423 .gh
424 .graphql_with_vars(query, serde_json::json!({ "projectId": self.project_id }))
425 .await?;
426
427 let items = result
428 .pointer("/data/node/items/nodes")
429 .and_then(|n| n.as_array())
430 .ok_or_else(|| anyhow::anyhow!("failed to parse project items"))?;
431
432 let mut estimates = HashMap::new();
433
434 for item in items {
435 let Some(content) = item.get("content") else {
437 continue;
438 };
439 let Some(content_id) = content.get("id").and_then(|v| v.as_str()) else {
440 continue;
441 };
442
443 if !issue_set.contains(content_id) {
445 continue;
446 }
447
448 let Some(field_values) = item
450 .get("fieldValues")
451 .and_then(|fv| fv.get("nodes"))
452 .and_then(|n| n.as_array())
453 else {
454 continue;
455 };
456 #[expect(
457 clippy::cast_possible_truncation,
458 clippy::cast_sign_loss,
459 reason = "the saturating cast is fine, only fibonacci values up to 21 are kept"
460 )]
461 let estimate = field_values
462 .iter()
463 .find(|fv| {
464 fv.get("field")
465 .and_then(|f| f.get("id"))
466 .and_then(|id| id.as_str())
467 .is_some_and(|id| id == field_id)
468 })
469 .and_then(|fv| fv.get("number"))
470 .and_then(serde_json::Value::as_f64)
471 .unwrap_or(0.0) as u8;
472
473 if FIBONACCI.contains(&estimate) {
475 estimates.insert(content_id.to_string(), estimate);
476 }
477 }
478
479 Ok(estimates)
480 }
481}
482
483fn parse_project_node(node: &serde_json::Value) -> Option<ProjectInfo> {
485 Some(ProjectInfo {
486 id: node.get("id")?.as_str()?.to_string(),
487 number: node.get("number")?.as_u64()?,
488 title: node.get("title")?.as_str()?.to_string(),
489 })
490}
491
492impl ProjectSync {
493 pub async fn write_config(&self) -> anyhow::Result<()> {
495 let config_path = home::config_path()?;
496 let content = if config_path.exists() {
497 fs::read_to_string(&config_path).await?
498 } else {
499 String::new()
500 };
501
502 let mut doc: serde_norway::Value = if content.is_empty() {
504 serde_norway::Value::Mapping(serde_norway::Mapping::new())
505 } else {
506 serde_norway::from_str(&content)?
507 };
508
509 let root = doc
510 .as_mapping_mut()
511 .ok_or_else(|| anyhow::anyhow!("config is not a YAML mapping"))?;
512
513 let gh_key = serde_norway::Value::String("gh".to_string());
515 if !root.contains_key(&gh_key) {
516 root.insert(
517 gh_key.clone(),
518 serde_norway::Value::Mapping(serde_norway::Mapping::new()),
519 );
520 }
521 let gh = root
522 .get_mut(&gh_key)
523 .and_then(|v| v.as_mapping_mut())
524 .ok_or_else(|| anyhow::anyhow!("gh config is not a mapping"))?;
525
526 gh.insert(
528 serde_norway::Value::String("project_id".to_string()),
529 serde_norway::Value::String(self.project_id.clone()),
530 );
531 gh.insert(
532 serde_norway::Value::String("project_status_field_id".to_string()),
533 serde_norway::Value::String(self.status_field_id.clone()),
534 );
535
536 let mut map = serde_norway::Mapping::new();
538 for (key, val) in &self.status_map {
539 map.insert(
540 serde_norway::Value::String(key.clone()),
541 serde_norway::Value::String(val.clone()),
542 );
543 }
544 gh.insert(
545 serde_norway::Value::String("project_status_map".to_string()),
546 serde_norway::Value::Mapping(map),
547 );
548
549 if let Some(ref field_id) = self.estimate_field_id {
551 gh.insert(
552 serde_norway::Value::String("project_estimate_field_id".to_string()),
553 serde_norway::Value::String(field_id.clone()),
554 );
555 }
556
557 fs::write(&config_path, serde_norway::to_string(&doc)?).await?;
558 Ok(())
559 }
560}
561
562#[cfg(test)]
563mod tests {
564 use std::env;
565 use std::fs as std_fs;
566 use std::panic;
567 use std::panic::AssertUnwindSafe;
568
569 use super::*;
570
571 #[test]
572 fn parse_project_node_valid() {
573 let node = serde_json::json!({
574 "id": "PVT_kwHOA123",
575 "number": 42,
576 "title": "My Project"
577 });
578 let info = parse_project_node(&node).unwrap();
579 assert_eq!(info.id, "PVT_kwHOA123");
580 assert_eq!(info.number, 42);
581 assert_eq!(info.title, "My Project");
582 }
583
584 #[test]
585 fn parse_project_node_missing_field() {
586 let node = serde_json::json!({ "id": "PVT_kwHOA123" });
587 assert!(parse_project_node(&node).is_none());
588 }
589
590 #[test]
591 fn from_config_returns_none_when_not_configured() {
592 let original_cwd = env::current_dir().unwrap();
597 let prev_orch_home = env::var("ORCH_HOME").ok();
598
599 let temp_cwd = tempfile::tempdir().unwrap();
600 let temp_orch_home = tempfile::tempdir().unwrap();
601 let orch_dir = temp_orch_home.path().join(".orch");
602 std_fs::create_dir_all(&orch_dir).unwrap();
603
604 env::set_current_dir(temp_cwd.path()).unwrap();
605 unsafe { env::set_var("ORCH_HOME", &orch_dir) };
607 config::clear_test_cache();
608
609 let result = panic::catch_unwind(AssertUnwindSafe(|| {
610 assert!(ProjectSync::from_config().is_none());
611 }));
612
613 env::set_current_dir(&original_cwd).unwrap();
614 if let Some(prev) = prev_orch_home {
615 unsafe { env::set_var("ORCH_HOME", prev) };
617 } else {
618 unsafe { env::remove_var("ORCH_HOME") };
620 }
621 result.unwrap();
622 }
623
624 #[test]
625 fn get_estimates_filters_non_fibonacci_values() {
626 const FIBONACCI: &[u8] = &[0, 1, 2, 3, 5, 8, 13, 21];
630
631 for &v in FIBONACCI {
633 assert!(
634 FIBONACCI.contains(&v),
635 "Fibonacci value {v} should be accepted"
636 );
637 }
638
639 let non_fib = [4, 6, 7, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 22];
641 for &v in &non_fib {
642 assert!(
643 !FIBONACCI.contains(&v),
644 "Non-Fibonacci value {v} should NOT be accepted"
645 );
646 }
647 }
648
649 #[test]
650 fn estimate_field_id_is_optional() {
651 let original_cwd = env::current_dir().unwrap();
654 let prev_orch_home = env::var("ORCH_HOME").ok();
655
656 let temp_cwd = tempfile::tempdir().unwrap();
657 let temp_orch_home = tempfile::tempdir().unwrap();
658 let orch_dir = temp_orch_home.path().join(".orch");
659 std_fs::create_dir_all(&orch_dir).unwrap();
660
661 env::set_current_dir(temp_cwd.path()).unwrap();
662 unsafe { env::set_var("ORCH_HOME", &orch_dir) };
664 config::clear_test_cache();
665
666 let config_path = orch_dir.join("config.yml");
668 std_fs::write(
669 &config_path,
670 r#"
671gh:
672 project_id: "PVT_kwHOAB123"
673 project_status_field_id: "PVTSSF_123"
674 project_status_map:
675 backlog: "opt1"
676"#,
677 )
678 .unwrap();
679
680 let result = panic::catch_unwind(AssertUnwindSafe(|| {
681 let sync = ProjectSync::from_config();
682 assert!(
683 sync.is_some(),
684 "should be Some when project_id is configured"
685 );
686 assert_eq!(
687 sync.unwrap().estimate_field_id(),
688 None,
689 "estimate_field_id should be None when not configured"
690 );
691 }));
692
693 env::set_current_dir(&original_cwd).unwrap();
694 if let Some(prev) = prev_orch_home {
695 unsafe { env::set_var("ORCH_HOME", prev) };
697 } else {
698 unsafe { env::remove_var("ORCH_HOME") };
700 }
701 result.unwrap();
702 }
703}