Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cli): implement commands to get, list, update, and delete, workspace roles #469

Merged
merged 8 commits into from
Oct 1, 2024

Conversation

Meeran-Tofiq
Copy link
Contributor

@Meeran-Tofiq Meeran-Tofiq commented Sep 29, 2024

User description

Description

Give a summary of the change that you have made

I have made 4 commands that are sub-commands of role. the commands are get, list, update, and delete. Update has the ability to change name, description, color code, authorities, and projects.

Fixes #447

Dependencies

Mention any dependencies/packages used
N/A

Future Improvements

Mention any improvements to be done in future related to any file/feature
The authorities and projects are updated poorly. If a role has a few authorities already, and you need to add a new one, you have to give the command the entire list of all authorities you already have + the authorities you need. Same for projects. This is tedious, arduous, and annoying. If possible and applicable, in the future there should be another sub-command for project and for authorities.

Mentions

Mention and tag the people

Screenshots of relevant screens

Add screenshots of relevant screens

Screenshot from 2024-09-28 15-34-13
Screenshot from 2024-09-28 15-34-22
Screenshot from 2024-09-28 15-34-55
Screenshot from 2024-09-29 14-48-34
Screenshot from 2024-09-28 15-35-56
Screenshot from 2024-09-29 14-40-20

Developer's checklist

  • My PR follows the style guidelines of this project
  • I have performed a self-check on my work

If changes are made in the code:

  • I have followed the coding guidelines
  • My changes in code generate no new warnings
  • My changes are breaking another fix/feature of the project
  • I have added test cases to show that my feature works
  • I have added relevant screenshots in my PR
  • There are no UI/UX issues

Documentation Update

  • This PR requires an update to the documentation at docs.keyshade.xyz
  • I have made the necessary updates to the documentation, or no documentation changes are required.

PR Type

enhancement, documentation


Description

  • Implemented new CLI commands for managing workspace roles, including get, list, update, and delete.
  • Integrated WorkspaceRoleCommand into the existing workspace command structure.
  • Each command provides specific functionalities such as fetching, listing, updating, and deleting workspace roles.
  • Enhanced the CLI tool to support comprehensive role management within a workspace.

Changes walkthrough 📝

Relevant files
Enhancement
workspace.command.ts
Integrate Workspace Role Command into Workspace Commands 

apps/cli/src/commands/workspace.command.ts

  • Imported WorkspaceRoleCommand into workspace sub-commands.
  • Added WorkspaceRoleCommand to the list of sub-commands.
  • +3/-1     
    role.workspace.ts
    Implement Workspace Role Command with Sub-commands             

    apps/cli/src/commands/workspace/role.workspace.ts

  • Created WorkspaceRoleCommand class.
  • Defined sub-commands for managing workspace roles.
  • +24/-0   
    delete.role.ts
    Add Delete Role Command for Workspace Roles                           

    apps/cli/src/commands/workspace/role/delete.role.ts

  • Implemented DeleteRoleCommand class.
  • Added functionality to delete a workspace role.
  • +44/-0   
    get.role.ts
    Add Get Role Command for Workspace Roles                                 

    apps/cli/src/commands/workspace/role/get.role.ts

  • Implemented GetRoleCommand class.
  • Added functionality to fetch a workspace role.
  • +56/-0   
    list.role.ts
    Add List Role Command for Workspace Roles                               

    apps/cli/src/commands/workspace/role/list.role.ts

  • Implemented ListRoleCommand class.
  • Added functionality to list all roles of a workspace.
  • +54/-0   
    update.role.ts
    Add Update Role Command for Workspace Roles                           

    apps/cli/src/commands/workspace/role/update.role.ts

  • Implemented UpdateRoleCommand class.
  • Added functionality to update a workspace role.
  • +97/-0   

    💡 PR-Agent usage: Comment /help "your question" on any pull request to receive relevant information

    Copy link
    Contributor

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Key issues to review

    Input Validation
    The update.role.ts file lacks input validation for the colorCode option. It should be validated to ensure it's a valid hex color code.

    Error Handling
    The update.role.ts file doesn't handle the case where authorities or projectSlugs options are provided but empty. This could lead to unexpected behavior.

    Copy link
    Contributor

    codiumai-pr-agent-free bot commented Sep 29, 2024

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Score
    Input validation
    Add input validation for the color code option to ensure it's a valid hexadecimal color code

    Consider adding input validation for the color code option. Ensure that the provided
    color code is a valid hexadecimal color code before sending the request to the
    server.

    apps/cli/src/commands/workspace/role/update.role.ts [58-76]

     async action({ args, options }: CommandActionData): Promise<void> {
       const [workspaceRoleSlug] = args
       const { name, description, colorCode, authorities, projectSlugs } = options
     
       const authoritiesArray = authorities?.split(',')
       const projectSlugsArray = projectSlugs?.split(',')
    +
    +  if (colorCode && !/^#[0-9A-Fa-f]{6}$/.test(colorCode)) {
    +    Logger.error('Invalid color code. Please provide a valid hexadecimal color code (e.g., #FF0000).')
    +    return
    +  }
     
       const { data, error, success } =
         await ControllerInstance.getInstance().workspaceRoleController.updateWorkspaceRole(
           {
             workspaceRoleSlug,
             name,
             description,
             colorCode,
             authorities: authoritiesArray,
             projectSlugs: projectSlugsArray
           },
           this.headers
         )
    • Apply this suggestion
    Suggestion importance[1-10]: 9

    Why: Input validation is crucial for preventing errors and ensuring data integrity, making this a high-impact improvement.

    9
    Enhancement
    Add a confirmation prompt before deleting a workspace role to prevent accidental deletions

    Consider adding a confirmation prompt before deleting the workspace role. This can
    prevent accidental deletions and improve the user experience. You can use a library
    like inquirer to implement this.

    apps/cli/src/commands/workspace/role/delete.role.ts [27-43]

     async action({ args }: CommandActionData): Promise<void> {
       const [workspaceRoleSlug] = args
    +
    +  const confirm = await inquirer.prompt([
    +    {
    +      type: 'confirm',
    +      name: 'proceed',
    +      message: `Are you sure you want to delete the workspace role "${workspaceRoleSlug}"?`,
    +      default: false
    +    }
    +  ])
    +
    +  if (!confirm.proceed) {
    +    Logger.info('Operation cancelled.')
    +    return
    +  }
     
       const { error, success } =
         await ControllerInstance.getInstance().workspaceRoleController.deleteWorkspaceRole(
           {
             workspaceRoleSlug
           },
           this.headers
         )
     
       if (success) {
         Logger.info(`Workspace role ${workspaceRoleSlug} deleted successfully!`)
       } else {
         Logger.error(`Failed deleting workspace role: ${error.message}`)
       }
     }
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: Adding a confirmation prompt before deletion is a significant improvement for preventing accidental data loss, enhancing user experience and safety.

    8
    Add an option to output the role information in JSON format for easier integration with other tools

    Consider adding an option to output the role information in a machine-readable
    format like JSON. This would make it easier for users to integrate the command
    output with other tools or scripts.

    apps/cli/src/commands/workspace/role/get.role.ts [27-55]

    -async action({ args }: CommandActionData): Promise<void> {
    +async action({ args, options }: CommandActionData): Promise<void> {
       const [workspaceRoleSlug] = args
    +  const { json } = options
     
       const { data, error, success } =
         await ControllerInstance.getInstance().workspaceRoleController.getWorkspaceRole(
           {
             workspaceRoleSlug
           },
           this.headers
         )
     
       if (success) {
    -    Logger.info(`Workspace role fetched successfully!`)
    -    Logger.info(`Workspace role: ${data.name} (${data.slug})`)
    -    Logger.info(`Description: ${data.description || 'N/A'}`)
    -    Logger.info(`Created at ${data.createdAt}`)
    -    Logger.info(`Updated at ${data.updatedAt}`)
    -    Logger.info(`Authorities:`)
    -    for (const authority of data.authorities) {
    -      Logger.info(`- ${authority}`)
    -    }
    -    Logger.info(`Projects:`)
    -    for (const project of data.projects) {
    -      Logger.info(`- ${project.project.name} (${project.project.slug})`)
    +    if (json) {
    +      console.log(JSON.stringify(data, null, 2))
    +    } else {
    +      Logger.info(`Workspace role fetched successfully!`)
    +      Logger.info(`Workspace role: ${data.name} (${data.slug})`)
    +      Logger.info(`Description: ${data.description || 'N/A'}`)
    +      Logger.info(`Created at ${data.createdAt}`)
    +      Logger.info(`Updated at ${data.updatedAt}`)
    +      Logger.info(`Authorities:`)
    +      for (const authority of data.authorities) {
    +        Logger.info(`- ${authority}`)
    +      }
    +      Logger.info(`Projects:`)
    +      for (const project of data.projects) {
    +        Logger.info(`- ${project.project.name} (${project.project.slug})`)
    +      }
         }
       } else {
         Logger.error(`Failed fetching workspace role: ${error.message}`)
       }
     }
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: Providing output in JSON format enhances the command's versatility and integration capabilities, though it is not critical for functionality.

    6
    Performance
    ✅ Implement pagination for the list command to handle large numbers of roles efficiently
    Suggestion Impact:The commit added pagination support by introducing a pagination option to the command, which aligns with the suggestion to handle large numbers of roles efficiently.

    code diff:

    +  getOptions(): CommandOption[] {
    +    return PAGINATION_OPTION
    +  }
    +
    +  async action({ args, options }: CommandActionData): Promise<void> {
         Logger.info("Fetching workspace's roles...")
     
         const [workspaceSlug] = args
    @@ -32,7 +38,8 @@
         const { data, error, success } =
           await ControllerInstance.getInstance().workspaceRoleController.getWorkspaceRolesOfWorkspace(
             {
    -          workspaceSlug
    +          workspaceSlug,
    +          ...options

    Consider adding pagination support for the list command. This will improve
    performance and user experience when dealing with a large number of roles.

    apps/cli/src/commands/workspace/role/list.role.ts [27-53]

     async action({ args }: CommandActionData): Promise<void> {
       Logger.info("Fetching workspace's roles...")
     
       const [workspaceSlug] = args
    +  let page = 1
    +  const pageSize = 10
     
    -  const { data, error, success } =
    -    await ControllerInstance.getInstance().workspaceRoleController.getWorkspaceRolesOfWorkspace(
    -      {
    -        workspaceSlug
    -      },
    -      this.headers
    -    )
    +  while (true) {
    +    const { data, error, success } =
    +      await ControllerInstance.getInstance().workspaceRoleController.getWorkspaceRolesOfWorkspace(
    +        {
    +          workspaceSlug,
    +          page,
    +          pageSize
    +        },
    +        this.headers
    +      )
     
    -  if (success) {
    -    Logger.info('Workspace Roles fetched successfully:')
    -    const roles = data.items
    -    if (roles.length > 0) {
    -      roles.forEach((role: any) => {
    -        Logger.info(`- ${role.name} (${role.slug})`)
    -      })
    +    if (success) {
    +      const roles = data.items
    +      if (roles.length > 0) {
    +        Logger.info(`Page ${page}:`)
    +        roles.forEach((role: any) => {
    +          Logger.info(`- ${role.name} (${role.slug})`)
    +        })
    +        if (roles.length < pageSize) {
    +          break
    +        }
    +        page++
    +      } else {
    +        if (page === 1) {
    +          Logger.info('No roles found')
    +        }
    +        break
    +      }
         } else {
    -      Logger.info('No roles found')
    +      Logger.error(`Failed fetching roles: ${error.message}`)
    +      break
         }
    -  } else {
    -    Logger.error(`Failed fetching roles: ${error.message}`)
       }
     }
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Pagination is a useful feature for handling large datasets, improving performance and user experience by preventing overwhelming output.

    7

    💡 Need additional feedback ? start a PR chat

    Signed-off-by: Meeran Tofiq <101665499+Meeran-Tofiq@users.noreply.github.com>
    Signed-off-by: Meeran Tofiq <101665499+Meeran-Tofiq@users.noreply.github.com>
    Signed-off-by: Meeran Tofiq <101665499+Meeran-Tofiq@users.noreply.github.com>
    Signed-off-by: Meeran Tofiq <101665499+Meeran-Tofiq@users.noreply.github.com>
    Signed-off-by: Meeran Tofiq <101665499+Meeran-Tofiq@users.noreply.github.com>
    Signed-off-by: Meeran Tofiq <101665499+Meeran-Tofiq@users.noreply.github.com>
    Signed-off-by: Meeran Tofiq <101665499+Meeran-Tofiq@users.noreply.github.com>
    Signed-off-by: Meeran Tofiq <101665499+Meeran-Tofiq@users.noreply.github.com>
    @rajdip-b rajdip-b merged commit 957ea8d into keyshade-xyz:develop Oct 1, 2024
    4 checks passed
    Kiranchaudhary537 pushed a commit to Kiranchaudhary537/keyshade that referenced this pull request Oct 13, 2024
    …pace roles (keyshade-xyz#469)
    
    Signed-off-by: Meeran Tofiq <101665499+Meeran-Tofiq@users.noreply.github.com>
    rajdip-b pushed a commit that referenced this pull request Oct 24, 2024
    ## [2.6.0](v2.5.0...v2.6.0) (2024-10-24)
    
    ### 🚀 Features
    
    * **api:**  Add icon and remove description field from workspace ([#435](#435)) ([a99c0db](a99c0db))
    * **api-client:** Added workspace-membership and related tests ([#452](#452)) ([6a1c091](6a1c091))
    * **api-client:** Create controller for User module ([#484](#484)) ([f9d8e83](f9d8e83))
    * **api:** Add prod env schema in env file ([#436](#436)) ([21c3004](21c3004))
    * **api:** Add resend otp implementation ([#445](#445)) ([4dc6aa1](4dc6aa1))
    * **api:** Fetch total count of environments, [secure]s and variables in project ([#434](#434)) ([0c9e50a](0c9e50a))
    * **api:** Replace `projectId` with `name` and `slug` in workspace-role response.  ([#432](#432)) ([af06071](af06071))
    * **cli:** Add functionality to operate on Secrets ([#504](#504)) ([1b4bf2f](1b4bf2f))
    * **cli:** Add project command ([#451](#451)) ([70448e1](70448e1))
    * **cli:** Add workspace operations ([#441](#441)) ([ed38d22](ed38d22))
    * **cli:** implement commands to get, list, update, and delete, workspace roles ([#469](#469)) ([957ea8d](957ea8d))
    * **cli:** Implemented pagination support ([#453](#453)) ([feb1806](feb1806))
    * **cli:** Secret scan ([#438](#438)) ([85cb8ab](85cb8ab))
    * **cli:** Update environment command outputs ([f4af874](f4af874))
    * **platform:** Clearing email field after waitlisting the user email ([#481](#481)) ([256d659](256d659))
    * Remove project IDs from workspace role export data and update tests ([#448](#448)) ([8fdb328](8fdb328))
    * **web:** Configured extra check for waitlisted users already in the list and created toast message for them ([#492](#492)) ([2ddd0ef](2ddd0ef))
    * **web:** show the toast only when email add successfully ([#490](#490)) ([783c411](783c411))
    
    ### 🐛 Bug Fixes
    
    * **api,api-client:** Add environmentSlug in multiple places across the variable module ([#468](#468)) ([d970aff](d970aff))
    * **api:** Replace the id with slug in the global-search service ([#455](#455)) ([74804b1](74804b1))
    * **platform:** Fixed duplicate Google Logo UI fix  ([#450](#450)) ([fb0d6f7](fb0d6f7))
    * resolve footer website name cut-off or overlap issue ([#444](#444)) ([fe03ba2](fe03ba2))
    * **web:** Horizontal Scrolling issue on the website ([#440](#440)) ([655177b](655177b))
    
    ### 📚 Documentation
    
    * Add documentation for environment in CLI ([#462](#462)) ([dad7394](dad7394))
    * Add documentation for project in CLI ([#466](#466)) ([341fb32](341fb32))
    * Add documentation for scan in CLI ([#461](#461)) ([72281e6](72281e6))
    * Add documentation for workspace command ([#464](#464)) ([4aad8a2](4aad8a2))
    * Add instructions for resetting the local Prisma database ([#495](#495)) ([#501](#501)) ([b07ea17](b07ea17))
    * Added docker support documentation ([#465](#465)) ([bc04be4](bc04be4))
    * Added documentation for running the platform ([#473](#473)) ([8b8386b](8b8386b))
    * Added missing mappings to pages ([5de9fd8](5de9fd8))
    * Fix Documentation Hyperlink and update expired Discord invite link ([#496](#496)) ([5a10e39](5a10e39))
    * Updated CLI docs ([#460](#460)) ([c7e0f13](c7e0f13))
    
    ### 🔧 Miscellaneous Chores
    
    * Add more logging to Sentry init ([#470](#470)) ([de4925d](de4925d))
    * **api:** Optimise API docker image size ([#360](#360)) ([ea40dc1](ea40dc1))
    * **api:** Updated lockfile ([a968e78](a968e78))
    * **CI:** Add [secure] scan validation ([f441262](f441262))
    * **cli:** Update controller invocation in environment commands ([#477](#477)) ([596bd1a](596bd1a))
    * Minor changes to variables ([fe01ca6](fe01ca6))
    * **[secure]-scan:** Failing lint issues ([#507](#507)) ([48f45df](48f45df))
    * **[secure]-scan:** Formatted files ([5884833](5884833))
    * Update .env.example ([70ad4f7](70ad4f7))
    * Updated scripts ([9eb76a7](9eb76a7))
    * **web:** email validation ([#487](#487)) ([e8e737a](e8e737a))
    @rajdip-b
    Copy link
    Member

    🎉 This PR is included in version 2.6.0 🎉

    The release is available on GitHub release

    Your semantic-release bot 📦🚀

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    CLI: Add functionality to operate on Workspace Role
    2 participants