Debian Codegraph @

src/org/team.rs

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 use std::collections::BTreeMap;
2
3 use clap::{Args, Subcommand};
4 use eyre::OptionExt;
5 use forgejo_api::{
6 structs::{
7 CreateTeamOption, EditTeamOption, OrgListTeamMembersQuery, OrgListTeamReposQuery,
8 OrgListTeamsQuery,
9 },
10 Forgejo,
11 };
12
13 use crate::SpecialRender;
14
15 #[derive(Subcommand, Clone, Debug)]
16 pub enum TeamSubcommand {
17 /// View all the teams in an organization
18 List {
19 /// The name of the organization to list the teams in.
20 org: String,
21 },
22 /// View info about a single team
23 View {
24 /// The name of the organization the team is part of.
25 org: String,
26 /// The name of the new team
27 name: String,
28 #[clap(long, short = 'p')]
29 list_permissions: bool,
30 },
31 /// Create a new team
32 Create {
33 /// The name of the organization to create the team in.
34 org: String,
35 /// The name of the new team
36 ///
37 /// This must only contain alphanumeric characters.
38 name: String,
39 #[clap(flatten)]
40 flags: TeamCreateFlags,
41 #[clap(flatten)]
42 options: TeamOptions,
43 },
44 /// Edit a team's information and permissions
45 Edit {
46 /// The name of the organization the team is in.
47 org: String,
48 /// The name of the team to edit
49 name: String,
50 /// Can members of this team to create repos in the organization?
51 #[clap(long, short)]
52 new_name: Option<String>,
53 #[clap(flatten)]
54 flags: TeamEditFlags,
55 #[clap(flatten)]
56 options: TeamOptions,
57 },
58 /// Delete a team from an organization.
59 ///
60 /// Note that this does NOT delete the repos the team has!
61 Delete {
62 /// The name of the organization the team is in.
63 org: String,
64 /// The name of the team to delete
65 name: String,
66 },
67 #[clap(subcommand)]
68 Repo(TeamRepoSubcommand),
69 #[clap(subcommand)]
70 Member(TeamMemberSubcommand),
71 }
72
73 #[derive(Args, Clone, Debug)]
74 pub struct TeamOptions {
75 /// A description of what the team does.
76 #[clap(long, short)]
77 description: Option<String>,
78 /// A comma-separated list of read permissions to give this team
79 ///
80 /// List of permissions:
81 /// - wiki
82 /// - ext_wiki
83 /// - issues
84 /// - ext_issues
85 /// - pulls
86 /// - projects
87 /// - actions
88 /// - code
89 /// - releases
90 /// - packages
91 ///
92 /// Alternatively, you can use `all` to allow every read permission.
93 #[clap(long, short)]
94 read_permissions: Option<String>,
95 /// A comma-separated list of read+write permissions to give this team
96 ///
97 /// List of permissions:
98 /// - wiki
99 /// - ext_wiki
100 /// - issues
101 /// - ext_issues
102 /// - pulls
103 /// - projects
104 /// - actions
105 /// - code
106 /// - releases
107 /// - packages
108 ///
109 /// Alternatively, you can use `all` to allow every read+write permission
110 #[clap(long, short)]
111 write_permissions: Option<String>,
112 }
113
114 #[derive(Args, Clone, Debug)]
115 pub struct TeamCreateFlags {
116 /// Allow members of this team to create repos in the organization.
117 #[clap(long, short)]
118 can_create_repos: bool,
119 /// Give this team access to every repo.
120 #[clap(long, short)]
121 include_all_repos: bool,
122 /// Give this team administrator abilities in the organization.
123 #[clap(long, short = 'A')]
124 admin: bool,
125 }
126
127 #[derive(Args, Clone, Debug)]
128 pub struct TeamEditFlags {
129 /// Allow members of this team to create repos in the organization.
130 #[clap(long, short)]
131 can_create_repos: Option<bool>,
132 /// Give this team access to every repo.
133 #[clap(long, short)]
134 include_all_repos: Option<bool>,
135 /// Give this team administrator abilities in the organization.
136 #[clap(long, short = 'A')]
137 admin: Option<bool>,
138 }
139
140 impl TeamSubcommand {
141 pub async fn run(self, api: &forgejo_api::Forgejo) -> eyre::Result<()> {
142 match self {
143 TeamSubcommand::List { org } => list_teams(&api, org).await?,
144 TeamSubcommand::View {
145 org,
146 name,
147 list_permissions,
148 } => view_team(&api, org, name, list_permissions).await?,
149 TeamSubcommand::Create {
150 org,
151 name,
152 flags,
153 options,
154 } => create_team(&api, org, name, flags, options).await?,
155 TeamSubcommand::Edit {
156 org,
157 name,
158 new_name,
159 flags,
160 options,
161 } => edit_team(&api, org, name, new_name, flags, options).await?,
162 TeamSubcommand::Delete { org, name } => delete_team(&api, org, name).await?,
163 TeamSubcommand::Repo(subcommand) => subcommand.run(&api).await?,
164 TeamSubcommand::Member(subcommand) => subcommand.run(&api).await?,
165 }
166 Ok(())
167 }
168 }
169
170 async fn find_team_by_name(
171 api: &Forgejo,
172 org: &str,
173 name: &str,
174 ) -> eyre::Result<forgejo_api::structs::Team> {
175 let mut seen = 0;
176 for page in 1.. {
177 let query = OrgListTeamsQuery {
178 page: Some(page),
179 limit: None,
180 };
181 let (headers, teams) = api.org_list_teams(&org, query).await?;
182 seen += teams.len();
183 for team in teams {
184 if team
185 .name
186 .as_deref()
187 .is_some_and(|team_name| team_name == name)
188 {
189 return Ok(team);
190 }
191 }
192 if seen >= headers.x_total_count.unwrap_or_default() as usize {
193 break;
194 }
195 }
196 eyre::bail!("Unknown team {name}");
197 }
198
199 async fn list_teams(api: &Forgejo, org: String) -> eyre::Result<()> {
200 let mut teams = Vec::new();
201 for page_idx in 1.. {
202 let query = OrgListTeamsQuery {
203 page: Some(page_idx),
204 limit: None,
205 };
206 let (headers, page) = api.org_list_teams(&org, query).await?;
207 teams.extend(page);
208 if teams.len() >= headers.x_total_count.unwrap_or_default() as usize {
209 break;
210 }
211 }
212 teams.sort_unstable_by_key(permission_sort_id);
213
214 let SpecialRender {
215 bright_blue,
216 bold,
217 reset,
218 bullet,
219 ..
220 } = crate::special_render();
221 for team in teams {
222 let team_name = team.name.as_deref().ok_or_eyre("team does not have name")?;
223 println!("{bullet} {bold}{bright_blue}{team_name}{reset}");
224 }
225 Ok(())
226 }
227
228 fn permission_sort_id(team: &forgejo_api::structs::Team) -> u32 {
229 use forgejo_api::structs::TeamPermission as Perm;
230 match &team.permission {
231 Some(Perm::Owner) => 0,
232 Some(Perm::Admin) => 1,
233 Some(Perm::Write) => 2,
234 Some(Perm::Read) => 3,
235 Some(Perm::None) | None => 4,
236 }
237 }
238
239 const ALL_UNITS: &[&str] = &[
240 "repo.wiki",
241 "repo.ext_wiki",
242 "repo.issues",
243 "repo.ext_issues",
244 "repo.pulls",
245 "repo.projects",
246 "repo.actions",
247 "repo.code",
248 "repo.releases",
249 "repo.packages",
250 ];
251
252 async fn view_team(
253 api: &Forgejo,
254 org: String,
255 name: String,
256 list_permissions: bool,
257 ) -> eyre::Result<()> {
258 let team = find_team_by_name(api, &org, &name).await?;
259
260 let SpecialRender {
261 bright_blue,
262 bright_red,
263 bold,
264 reset,
265 dash,
266 ..
267 } = crate::special_render();
268
269 print!("{bright_blue}{bold}{name}{reset} {dash} in org {bold}{org}{reset}");
270 if team
271 .permission
272 .is_some_and(|p| p == forgejo_api::structs::TeamPermission::Admin)
273 {
274 print!(" {dash} {bright_red}Admin{reset}");
275 }
276 println!();
277
278 if let Some(description) = &team.description {
279 if !description.is_empty() {
280 println!("\n{}", crate::markdown(description));
281 }
282 }
283
284 if list_permissions {
285 println!();
286 let units = team
287 .units_map
288 .as_ref()
289 .ok_or_eyre("team does not have permission units")?;
290 let mut ro_perms = Vec::new();
291 let mut rw_perms = Vec::new();
292 for (unit, permission) in units {
293 match &**permission {
294 "read" => ro_perms.push(unit),
295 "write" | "admin" | "owner" => rw_perms.push(unit),
296 _ => (),
297 }
298 }
299
300 let get_unit_name = |unit| match unit {
301 "repo.wiki" => "Wikis",
302 "repo.ext_wiki" => "External Wikis",
303 "repo.issues" => "Issues",
304 "repo.ext_issues" => "External Issues",
305 "repo.pulls" => "Pull Requests",
306 "repo.projects" => "Projects",
307 "repo.actions" => "CI",
308 "repo.code" => "Code",
309 "repo.releases" => "Releases",
310 "repo.packages" => "Packages",
311 _ => "Unknown",
312 };
313 if !ro_perms.is_empty() {
314 print!("Read Only: ");
315 for (i, unit) in ro_perms.iter().enumerate() {
316 let unit_name = get_unit_name(unit);
317 if i > 0 {
318 print!(", ");
319 }
320 print!("{unit_name}");
321 }
322 println!();
323 }
324 if !rw_perms.is_empty() {
325 print!("Read/Write: ");
326 for (i, unit) in rw_perms.iter().enumerate() {
327 let unit_name = get_unit_name(unit);
328 if i != 0 {
329 print!(", ");
330 }
331 print!("{unit_name}");
332 }
333 println!();
334 }
335 }
336
337 Ok(())
338 }
339
340 fn create_unit_map(ro_perms: Option<&str>, rw_perms: Option<&str>) -> BTreeMap<String, String> {
341 let mut units = BTreeMap::new();
342 if let Some(ro_perms) = ro_perms {
343 if ro_perms == "all" {
344 for ro in ALL_UNITS {
345 units.insert(ro.to_string(), "read".to_owned());
346 }
347 } else {
348 for ro in ro_perms.split(",") {
349 units.insert(format!("repo.{ro}"), "read".to_owned());
350 }
351 }
352 }
353 if let Some(rw_perms) = rw_perms {
354 if rw_perms.trim() == "all" {
355 for rw in ALL_UNITS {
356 units.insert(rw.to_string(), "write".to_owned());
357 }
358 } else {
359 for rw in rw_perms.split(",") {
360 units.insert(format!("repo.{rw}"), "write".to_owned());
361 }
362 }
363 }
364 units
365 }
366
367 async fn create_team(
368 api: &Forgejo,
369 org: String,
370 name: String,
371 flags: TeamCreateFlags,
372 options: TeamOptions,
373 ) -> eyre::Result<()> {
374 let units = create_unit_map(
375 options.read_permissions.as_deref(),
376 options.write_permissions.as_deref(),
377 );
378 let opt = CreateTeamOption {
379 can_create_org_repo: Some(flags.can_create_repos),
380 description: options.description,
381 includes_all_repositories: Some(flags.include_all_repos),
382 name,
383 permission: flags
384 .admin
385 .then(|| forgejo_api::structs::CreateTeamOptionPermission::Admin),
386 units: None,
387 units_map: Some(units),
388 };
389 let new_team = api.org_create_team(&org, opt).await?;
390 let org = new_team.organization.ok_or_eyre("team doesn't have org")?;
391 let org_name = org
392 .name
393 .or(org.full_name)
394 .ok_or_eyre("org doesn't have name")?;
395 let name = new_team.name.ok_or_eyre("team doesn't have name")?;
396
397 let SpecialRender {
398 bright_blue,
399 bold,
400 reset,
401 ..
402 } = crate::special_render();
403 print!("created new ");
404 if flags.admin {
405 print!("admin ");
406 }
407 println!("team {bright_blue}{bold}{name}{reset} in {bold}{org_name}{reset}");
408 Ok(())
409 }
410
411 async fn edit_team(
412 api: &Forgejo,
413 org: String,
414 name: String,
415 new_name: Option<String>,
416 flags: TeamEditFlags,
417 options: TeamOptions,
418 ) -> eyre::Result<()> {
419 let team = find_team_by_name(api, &org, &name).await?;
420 let id = team.id.ok_or_eyre("team does not have id")?;
421
422 // EditTeamOption's team field is a String rather than Option<String>
423 // That should be fixed, but this gets around it for now.
424 let new_name = new_name.unwrap_or(name);
425 let units = create_unit_map(
426 options.read_permissions.as_deref(),
427 options.write_permissions.as_deref(),
428 );
429
430 let options = EditTeamOption {
431 can_create_org_repo: flags.can_create_repos,
432 description: options.description,
433 includes_all_repositories: flags.include_all_repos,
434 name: new_name,
435 permission: flags
436 .admin
437 .and_then(|b| b.then(|| forgejo_api::structs::EditTeamOptionPermission::Admin)),
438 units: None,
439 units_map: Some(units),
440 };
441 api.org_edit_team(id as u32, options).await?;
442
443 Ok(())
444 }
445
446 async fn delete_team(api: &Forgejo, org: String, name: String) -> eyre::Result<()> {
447 let SpecialRender { bold, reset, .. } = crate::special_render();
448 println!("Are you sure you want to delete {bold}{org}/{name}{reset}?");
449 let confirmation = crate::readline("(y/N) ").await?.to_lowercase();
450 if matches!(confirmation.trim(), "y" | "yes") {
451 let id = find_team_by_name(api, &org, &name)
452 .await?
453 .id
454 .ok_or_eyre("team does not have id")?;
455 api.org_delete_team(id as u64).await?;
456 println!("Team deleted.");
457 } else {
458 println!("Team not deleted.");
459 }
460 Ok(())
461 }
462
463 #[derive(Subcommand, Clone, Debug)]
464 pub enum TeamRepoSubcommand {
465 /// List all the repos this team can access
466 List {
467 /// The name of the organization the team is in.
468 org: String,
469 /// The name of the team to view the repos of.
470 team: String,
471 /// Which page of the results to view
472 #[clap(long, short)]
473 page: Option<u32>,
474 },
475 /// Add access to an existing repo to a team
476 Add {
477 /// The name of the organization the team is in.
478 org: String,
479 /// The name of the team to add a repo to.
480 team: String,
481 /// The name of the repo to add to the team.
482 repo: String,
483 },
484 /// Remove access to a repo from a team
485 ///
486 /// Note that this does NOT delete the repository!
487 Rm {
488 /// The name of the organization the team is in.
489 org: String,
490 /// The name of the team to remove the repo from.
491 team: String,
492 /// The name of the repo to remove from the team.
493 repo: String,
494 },
495 }
496
497 impl TeamRepoSubcommand {
498 async fn run(self, api: &Forgejo) -> eyre::Result<()> {
499 match self {
500 TeamRepoSubcommand::List { org, team, page } => {
501 list_team_repos(&api, org, team, page).await?
502 }
503 TeamRepoSubcommand::Add { org, team, repo } => {
504 add_repo_to_team(&api, org, team, repo).await?
505 }
506 TeamRepoSubcommand::Rm { org, team, repo } => {
507 remove_repo_from_team(&api, org, team, repo).await?
508 }
509 }
510 Ok(())
511 }
512 }
513
514 async fn list_team_repos(
515 api: &Forgejo,
516 org: String,
517 team: String,
518 page: Option<u32>,
519 ) -> eyre::Result<()> {
520 let id = find_team_by_name(api, &org, &team)
521 .await?
522 .id
523 .ok_or_eyre("team does not have id")?;
524 let query = OrgListTeamReposQuery {
525 page,
526 limit: Some(20),
527 };
528 let (headers, repos) = api.org_list_team_repos(id as u64, query).await?;
529
530 let SpecialRender { bullet, .. } = crate::special_render();
531 if repos.is_empty() {
532 println!("No results");
533 } else {
534 for repo in repos {
535 let full_name = repo
536 .full_name
537 .as_deref()
538 .ok_or_eyre("repo does not have full name")?;
539 println!("{bullet} {full_name}");
540 }
541 let count = headers.x_total_count.unwrap_or_default() as u64;
542 println!("Page {} of {}", page.unwrap_or(1), count.div_ceil(20));
543 }
544 Ok(())
545 }
546
547 async fn add_repo_to_team(
548 api: &Forgejo,
549 org: String,
550 team: String,
551 repo: String,
552 ) -> eyre::Result<()> {
553 let id = find_team_by_name(api, &org, &team)
554 .await?
555 .id
556 .ok_or_eyre("team does not have id")?;
557 api.org_add_team_repository(id as u64, &org, &repo).await?;
558 let SpecialRender {
559 bold,
560 reset,
561 bright_blue,
562 ..
563 } = crate::special_render();
564 println!("Added {bold}{org}/{repo}{reset} to team {bright_blue}{bold}{team}{reset}");
565 Ok(())
566 }
567
568 async fn remove_repo_from_team(
569 api: &Forgejo,
570 org: String,
571 team: String,
572 repo: String,
573 ) -> eyre::Result<()> {
574 let id = find_team_by_name(api, &org, &team)
575 .await?
576 .id
577 .ok_or_eyre("team does not have id")?;
578 api.org_remove_team_repository(id as u64, &org, &repo)
579 .await?;
580 let SpecialRender {
581 bold,
582 reset,
583 bright_blue,
584 ..
585 } = crate::special_render();
586 println!("Removed {bold}{org}/{repo}{reset} from team {bright_blue}{bold}{team}{reset}");
587 Ok(())
588 }
589
590 #[derive(Subcommand, Clone, Debug)]
591 pub enum TeamMemberSubcommand {
592 /// List all the members of a team
593 List {
594 /// The name of the organization the team is in.
595 org: String,
596 /// The name of the team to view the members of.
597 team: String,
598 /// Which page of the results to view
599 #[clap(long, short)]
600 page: Option<u32>,
601 },
602 /// Add someone to a team
603 Add {
604 /// The name of the organization the team is in.
605 org: String,
606 /// The name of the team to add a user to.
607 team: String,
608 /// The name of the user to add to the team.
609 user: String,
610 },
611 /// Remove someone from a team
612 Rm {
613 /// The name of the organization the team is in.
614 org: String,
615 /// The name of the team to remove the user from.
616 team: String,
617 /// The name of the user to remove from the team.
618 user: String,
619 },
620 }
621
622 impl TeamMemberSubcommand {
623 async fn run(self, api: &Forgejo) -> eyre::Result<()> {
624 match self {
625 TeamMemberSubcommand::List { org, team, page } => {
626 list_team_members(&api, org, team, page).await?
627 }
628 TeamMemberSubcommand::Add { org, team, user } => {
629 add_user_to_team(&api, org, team, user).await?
630 }
631 TeamMemberSubcommand::Rm { org, team, user } => {
632 remove_user_from_team(&api, org, team, user).await?
633 }
634 }
635 Ok(())
636 }
637 }
638
639 async fn list_team_members(
640 api: &Forgejo,
641 org: String,
642 team: String,
643 page: Option<u32>,
644 ) -> eyre::Result<()> {
645 let id = find_team_by_name(api, &org, &team)
646 .await?
647 .id
648 .ok_or_eyre("team does not have id")?;
649 let query = OrgListTeamMembersQuery {
650 page,
651 limit: Some(20),
652 };
653 let (headers, users) = api.org_list_team_members(id as u64, query).await?;
654
655 let SpecialRender {
656 bullet,
657 light_grey,
658 bright_cyan,
659 reset,
660 ..
661 } = crate::special_render();
662 if users.is_empty() {
663 println!("No results");
664 } else {
665 for user in users {
666 let username = user
667 .login
668 .as_deref()
669 .ok_or_eyre("repo does not have full name")?;
670 match user.full_name.as_deref().filter(|s| !s.is_empty()) {
671 Some(full_name) => println!(
672 "{bullet} {bright_cyan}{full_name}{reset} {light_grey}({username}){reset}"
673 ),
674 None => println!("{bullet} {bright_cyan}{username}{reset}"),
675 }
676 }
677 let count = headers.x_total_count.unwrap_or_default() as u64;
678 println!("Page {} of {}", page.unwrap_or(1), count.div_ceil(20));
679 }
680 Ok(())
681 }
682
683 async fn add_user_to_team(
684 api: &Forgejo,
685 org: String,
686 team: String,
687 user: String,
688 ) -> eyre::Result<()> {
689 let id = find_team_by_name(api, &org, &team)
690 .await?
691 .id
692 .ok_or_eyre("team does not have id")?;
693 api.org_add_team_member(id as u64, &user).await?;
694 let SpecialRender {
695 bold,
696 reset,
697 bright_blue,
698 bright_cyan,
699 ..
700 } = crate::special_render();
701 println!("Added {bright_cyan}{bold}{user}{reset} to team {bright_blue}{bold}{team}{reset}");
702 Ok(())
703 }
704
705 async fn remove_user_from_team(
706 api: &Forgejo,
707 org: String,
708 team: String,
709 user: String,
710 ) -> eyre::Result<()> {
711 let id = find_team_by_name(api, &org, &team)
712 .await?
713 .id
714 .ok_or_eyre("team does not have id")?;
715 api.org_remove_team_member(id as u64, &user).await?;
716 let SpecialRender {
717 bold,
718 reset,
719 bright_blue,
720 bright_cyan,
721 ..
722 } = crate::special_render();
723 println!("Removed {bright_cyan}{bold}{user}{reset} from team {bright_blue}{bold}{team}{reset}");
724 Ok(())
725 }