Debian Codegraph @

src/org/team.rs

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