Skip to content

Batch Repo addition to a team(Backend) #672

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

thesujai
Copy link
Contributor

@thesujai thesujai commented Jun 16, 2025

Linked Issue(s)

Fixes part of #664

Proposed changes (including videos or screenshots)

  1. Adds an api endpoint /api/internal/[org_id[/git_org_repos that fetched all the repos of an organisation/group from github/gitlab
  2. Adds test for the endpoint mentioned above
  3. Refactor some logic of git_provider_org so that they can be re-used for the new api endpoint

Further comments

There was a minor issue with the github utils test, that is fixed with this PR

Summary by CodeRabbit

  • New Features

    • Introduced a new API endpoint to fetch repositories from GitHub or GitLab organizations, supporting pagination and the option to retrieve all repositories at once.
  • Bug Fixes

    • Improved handling of custom domain URLs in GitHub API tests to ensure correct URL formatting.
  • Tests

    • Added comprehensive tests for fetching repositories from GitHub and GitLab, including pagination and data extraction scenarios.
  • Chores

    • Updated project configuration to specify the package manager and its version.
    • Refactored token retrieval logic for GitHub and GitLab integrations to a shared utility for better maintainability.

Copy link

coderabbitai bot commented Jun 16, 2025

Walkthrough

A new API endpoint is introduced to fetch repositories from GitHub or GitLab organizations, supporting pagination and selecting all repositories. Token retrieval logic is centralized into utility functions. Tests are added for the new endpoint and updated for GitHub URL utilities. Minor configuration and export adjustments are also included.

Changes

File(s) Change Summary
web-server/pages/api/internal/[org_id]/git_org_repos.ts Added new API endpoint to fetch repositories from GitHub/GitLab, including pagination and select-all logic.
web-server/pages/api/internal/[org_id]/utils.ts Exported replaceURL; added exported getGithubToken and getGitlabToken for token retrieval and decryption.
web-server/pages/api/internal/[org_id]/git_provider_org.ts Refactored to use imported token retrieval functions from utils; removed local definitions.
web-server/pages/api/internal/[org_id]/tests/git_org_repos.test.ts Added test suite for the new git_org_repos API, covering fetchRepos and selectAllRepos with mocks.
web-server/pages/api/internal/[org_id]/tests/github.test.ts Updated mocks for custom GitHub domains to use fully qualified URLs with "https://" scheme.
web-server/package.json Added "packageManager": "yarn@1.22.22" field.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API_Handler
    participant Utils
    participant GitHub_API
    participant GitLab_API
    participant DB

    Client->>API_Handler: GET /api/internal/[org_id]/git_org_repos
    API_Handler->>Utils: getGithubToken/org_id or getGitlabToken/org_id
    Utils->>DB: Query Integration table
    DB-->>Utils: Return encrypted token
    Utils->>Utils: Decrypt token
    Utils-->>API_Handler: Return token

    alt provider is GitHub
        API_Handler->>GitHub_API: GraphQL query for repos (with pagination)
        GitHub_API-->>API_Handler: Repo data
    else provider is GitLab
        API_Handler->>GitLab_API: GraphQL query for repos (with pagination)
        GitLab_API-->>API_Handler: Repo data
    end

    API_Handler-->>Client: Return repos (paginated or all)
Loading

Poem

In the warren of code, a new path we compose,
Fetching repos from clouds where the digital wind blows.
Tokens now gathered from a single, safe place,
With tests that ensure all the bugs we erase.
Hop, skip, and jump—new features in tow,
The rabbit approves—let the repositories flow!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@thesujai thesujai changed the title Batch Repo addition to a team Batch Repo addition to a team(Backend) Jun 16, 2025
@thesujai thesujai force-pushed the repos-import-bulk branch from ce98b9d to eac96ef Compare June 17, 2025 10:36
@thesujai thesujai marked this pull request as ready for review June 17, 2025 13:56
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🔭 Outside diff range comments (2)
web-server/pages/api/internal/[org_id]/git_provider_org.ts (1)

30-36: tokens.shift() inside map obscures intent and can mis-align provider/token pairs

Promise.all(providerMap.map(item => item.search(tokens.shift(), …))) relies on mutation and positional coupling.
If any earlier getToken resolves to undefined (integration missing, decrypt failure), the shift will silently slide the array, pairing the wrong token with the next provider.

-const repos = await Promise.all(
-  providerMap.map((item) => item.search(tokens.shift(), search_text))
-);
+const repos = await Promise.all(
+  providerMap.map((item, idx) => item.search(tokens[idx], search_text))
+);

Clearer, O(1), and robust to sparse elements.

web-server/pages/api/internal/[org_id]/utils.ts (1)

291-307: replaceURL ignores org_id – custom domain might clash across orgs

The query filters only by name = GITLAB, so if multiple orgs store different custom_domain values the first row wins.
Either add org_id to the where clause or document that the GitLab domain is global.

-const provider_meta = await db('Integration')
-  .where('name', Integration.GITLAB)
+const provider_meta = await db('Integration')
+  .where({ name: Integration.GITLAB, org_id })

(Requires passing org_id into the helper.)

🧹 Nitpick comments (3)
web-server/package.json (1)

132-135: Node 22 × Yarn 1 combo – double-check CI image and local dev setup

Declaring "engines": { "node": "^22.x" } while locking the project to Yarn 1 ("packageManager": "yarn@1.22.22") is fine syntactically, but Node 22 is still experimental in many standard build images and some Yarn 1 plugins (esp. node-gyp consumers) lag behind new major Node versions.
Make sure the CI/Prod containers actually ship Node 22, or relax the engine range to the latest LTS (e.g. ^20.0.0) to avoid accidental install failures (npm ERR! Unsupported engine).

web-server/pages/api/internal/[org_id]/__tests__/github.test.ts (1)

78-82: Minor nit – duplicate https:// stripped twice

getGitHubGraphQLUrl already normalises slashes; no action needed, but future tests could drop the trailing /api repetition (https://api.github.local/api/graphql) to focus on the important part.

web-server/pages/api/internal/[org_id]/__tests__/git_org_repos.test.ts (1)

16-18: Prefer resetting global.fetch with assignment over delete

Static analysis rightly flags delete (global as any).fetch; it slows objects on V8 and is unnecessary in test code.

-// @ts-ignore
-delete (global as any).fetch
+// @ts-expect-error – test shim
+(global as any).fetch = undefined
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 15d36fd and eac96ef.

📒 Files selected for processing (6)
  • web-server/package.json (1 hunks)
  • web-server/pages/api/internal/[org_id]/__tests__/git_org_repos.test.ts (1 hunks)
  • web-server/pages/api/internal/[org_id]/__tests__/github.test.ts (2 hunks)
  • web-server/pages/api/internal/[org_id]/git_org_repos.ts (1 hunks)
  • web-server/pages/api/internal/[org_id]/git_provider_org.ts (1 hunks)
  • web-server/pages/api/internal/[org_id]/utils.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
web-server/pages/api/internal/[org_id]/__tests__/git_org_repos.test.ts (2)
web-server/pages/api/internal/[org_id]/git_org_repos.ts (2)
  • fetchRepos (31-199)
  • selectAllRepos (201-220)
backend/analytics_server/mhq/store/models/integrations/integrations.py (1)
  • Integration (10-28)
web-server/pages/api/internal/[org_id]/utils.ts (2)
backend/analytics_server/mhq/store/models/integrations/integrations.py (1)
  • Integration (10-28)
web-server/src/utils/auth-supplementary.ts (1)
  • dec (20-25)
web-server/pages/api/internal/[org_id]/git_org_repos.ts (3)
web-server/src/api-helpers/global.ts (1)
  • Endpoint (26-106)
web-server/pages/api/internal/[org_id]/utils.ts (4)
  • getGitHubGraphQLUrl (335-338)
  • replaceURL (291-308)
  • getGithubToken (340-350)
  • getGitlabToken (352-362)
web-server/src/types/resources.ts (1)
  • BaseRepo (242-254)
🪛 Biome (1.9.4)
web-server/pages/api/internal/[org_id]/__tests__/git_org_repos.test.ts

[error] 16-16: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 126-126: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (5)
web-server/pages/api/internal/[org_id]/git_provider_org.ts (1)

45-56: Great improvement – token retrieval logic is now fully centralised
Importing getGithubToken / getGitlabToken from the utils module removes duplication from this handler and keeps secrets logic in one place.

web-server/pages/api/internal/[org_id]/__tests__/github.test.ts (1)

58-68: 👍 Scheme-prefixed custom domain mocks align with production helper

The tests now use full URLs (https://git.sujai.com) which mirrors the format expected by getGitHubCustomDomain(). Assertions remain correct.

web-server/pages/api/internal/[org_id]/__tests__/git_org_repos.test.ts (1)

129-145: Nice coverage – confirms pagination loop terminates correctly
The two-page mock and expect(fetchMock).toHaveBeenCalledTimes(2) accurately guard against infinite loops or premature exits in selectAllRepos().

web-server/pages/api/internal/[org_id]/utils.ts (1)

323-333: Good: URL de-duplication helper keeps consumer code clean
The negative-look-behind regex for double slashes is concise and safe.

web-server/pages/api/internal/[org_id]/git_org_repos.ts (1)

81-84: Use proper “Bearer” scheme in Authorization header

OAuth2 spec (and GitHub examples) capitalise the scheme:
Authorization: Bearer <token>

Some servers are case-sensitive; using lower-case “bearer” risks 401s.

-Authorization: `bearer ${token}`,
+Authorization: `Bearer ${token}`,

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
web-server/pages/api/internal/[org_id]/__tests__/git_org_repos.test.ts (1)

125-127: Duplicate: avoid delete global.fetch

Same recommendation as on lines 15-17—assign undefined instead of using delete.

🧹 Nitpick comments (3)
web-server/pages/api/internal/[org_id]/__tests__/git_org_repos.test.ts (3)

15-17: Replace delete global.fetch with assignment

Deleting a property on global is slower and triggers the noDelete lint rule. You can achieve the same reset with a simple assignment.

-// @ts-ignore
-delete (global as any).fetch
+// @ts-expect-error – reset the polyfill between tests
+(global as any).fetch = undefined

6-9: Align import indentation

The extra left-padding makes these top-level imports look nested inside the previous block. Align them to column 0 for consistency.

-  import { fetchRepos, selectAllRepos } from '@/api/internal/[org_id]/git_org_repos'
-  import { Integration } from '@/constants/integrations'
-  import * as utils from '@/api/internal/[org_id]/utils'
+import { fetchRepos, selectAllRepos } from '@/api/internal/[org_id]/git_org_repos'
+import { Integration } from '@/constants/integrations'
+import * as utils from '@/api/internal/[org_id]/utils'

12-18: Add negative-path tests for complete coverage

fetchRepos throws when res.ok is false or when a GraphQL errors array is present, but the suite only covers the happy path. A couple of extra test cases with:

  1. global.fetch resolving to { ok: false, status: 500 }
  2. global.fetch resolving to { ok: true, json: () => ({ errors: [{ message: 'boom' }] }) }

would lock in the error-handling behaviour and protect against regressions.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eac96ef and a6764e0.

📒 Files selected for processing (1)
  • web-server/pages/api/internal/[org_id]/__tests__/git_org_repos.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
web-server/pages/api/internal/[org_id]/__tests__/git_org_repos.test.ts (1)
web-server/pages/api/internal/[org_id]/git_org_repos.ts (2)
  • fetchRepos (31-199)
  • selectAllRepos (201-220)
🪛 Biome (1.9.4)
web-server/pages/api/internal/[org_id]/__tests__/git_org_repos.test.ts

[error] 16-16: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 126-126: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: All file linting
🔇 Additional comments (1)
web-server/pages/api/internal/[org_id]/__tests__/git_org_repos.test.ts (1)

115-119: 👍 GitLab matcher now reflects the real object shape

The assertion has been updated to use slug, web_url, and parent, matching what fetchRepos actually returns for GitLab repos. This addresses the previous review’s concern and prevents false negatives.

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

Successfully merging this pull request may close these issues.

1 participant