Skip to content

include projects api #2006

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

Merged
merged 1 commit into from
Jul 4, 2025
Merged

include projects api #2006

merged 1 commit into from
Jul 4, 2025

Conversation

motatoes
Copy link
Contributor

@motatoes motatoes commented Jul 4, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new API endpoint to list projects for an organization.
    • Project data now includes a "directory" field.
  • Improvements

    • Project listing responses are more concise, with updated JSON structure.
    • Enhanced database logging and debug information for GitHub integration.
    • Updated dependency for improved logging performance.
  • Bug Fixes

    • Project directory information is now correctly handled during creation and updates.
  • Database

    • Added a "directory" column and removed the "configuration_yaml" column from the projects table.
  • Tests

    • Adjusted tests to accommodate changes in project creation parameters.

Copy link
Contributor

coderabbitai bot commented Jul 4, 2025

Walkthrough

A new /api/projects/ GET endpoint was added, handled by a refactored controller that now returns a simplified project JSON structure with a new directory field. The database schema was updated to add a directory column and remove configuration_yaml. Related method signatures and test calls were updated to support the new field.

Changes

File(s) Change Summary
backend/bootstrap/main.go Added /api/projects/ GET endpoint, handled by ListProjectsApi.
backend/controllers/projects.go Renamed and reimplemented ListProjects as ListProjectsApi; updated project creation to omit ConfigurationYaml.
backend/models/orgs.go Removed ConfigurationYaml field, added Directory field to Project struct and JSON mapping.
backend/models/storage.go Updated CreateProject to accept and set directory; updated project refresh logic to handle directory.
backend/migrations/20250704024948.sql
backend/migrations/20250704025208.sql
Added directory column and dropped configuration_yaml from projects table.
backend/controllers/github_test.go
backend/models/scheduler_test.go
backend/tasks/runs_test.go
Updated test calls to CreateProject to include new directory parameter.
backend/models/setup.go
backend/go.mod
Switched GORM logger dependency and configuration to imdatngo/slog-gorm/v2.
backend/services/repos.go Updated imports and logging; changed GitHub client provider type and usage.
ee/drift/utils/github.go Added debug-level logging to GitHub client/service functions.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant Controller
    participant DB

    Client->>API: GET /api/projects/
    API->>Controller: ListProjectsApi(c)
    Controller->>DB: Find organisation by external_id/source
    alt Org not found
        Controller-->>Client: 404 Not Found
    else Org found
        Controller->>DB: Query projects by organisation_id
        alt DB error
            Controller-->>Client: 500 Error
        else Success
            Controller->>Client: JSON { result: [projects with directory] }
        end
    end
Loading

Possibly related PRs

  • diggerhq/digger#1887: Removes the old /api/projects endpoints and introduces /api/repos and GitHub linking endpoints, closely related as both PRs modify project-related API routing and endpoints.

Poem

A hop and a skip, a directory appears,
Projects now simpler, with fewer old fears.
The API’s fresh, the schema’s just right,
Logging more clever, and tests kept tight.
With every new endpoint, the garden grows bright—
Hooray for the code, and to all a good byte!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in a Comment
  • Commit Unit Tests in branch feat/projects-api

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 auto-generate unit tests to generate unit tests for 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.

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

Major updates to project management and logging infrastructure, focusing on API enhancements and data model refinements.

  • Removed configuration_yaml column from projects table and added new directory field for better project path management
  • Switched logging from orandin/slog-gorm to imdatngo/slog-gorm/v2 with enhanced logging configuration and slow query monitoring
  • Added new /api/projects GET endpoint with improved organization-level project listing
  • Added comprehensive debug logging with structured slog.Debug across GitHub client utilities
  • Improved error handling in projects API with better HTTP status codes and organization access validation

14 files reviewed, 8 comments
Edit PR Review Bot Settings | Greptile

@@ -0,0 +1,2 @@
-- Modify "projects" table
ALTER TABLE "public"."projects" DROP COLUMN "configuration_yaml";
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Consider using IF EXISTS clause to prevent errors if column was already dropped in some environments

Suggested change
ALTER TABLE "public"."projects" DROP COLUMN "configuration_yaml";
ALTER TABLE "public"."projects" DROP COLUMN IF EXISTS "configuration_yaml";

Comment on lines +232 to +233
projectsApiGroup := apiGroup.Group("/projects")
projectsApiGroup.GET("/", controllers.ListProjectsApi)
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Log debug context when handling projects API requests to improve traceability

"log/slog"
"strconv"
"strings"
)

func LoadProjectsFromGithubRepo(gh utils2.GithubClientProvider, installationId string, repoFullName string, repoOwner string, repoName string, cloneUrl string, branch string) error {
func LoadProjectsFromGithubRepo(gh utils3.GithubClientProvider, installationId string, repoFullName string, repoOwner string, repoName string, cloneUrl string, branch string) error {
installationId64, err := strconv.ParseInt(installationId, 10, 64)
if err != nil {
slog.Error("failed to convert installation id %v to int64", "insallationId", installationId)
Copy link
Contributor

Choose a reason for hiding this comment

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

syntax: Typo in error log parameter name 'insallationId'

Suggested change
slog.Error("failed to convert installation id %v to int64", "insallationId", installationId)
slog.Error("failed to convert installation id %v to int64", "installationId", installationId)

@@ -140,7 +140,7 @@ func TestThatRunQueueItemMovesFromQueuedToPlanningAfterPickup(t *testing.T) {
for i, testParam := range testParameters {
ciService := github2.MockCiService{}
batch, _ := models.DB.CreateDiggerBatch(models.DiggerVCSGithub, 123, "", "", "", 22, "", "", "", nil, 0, "", false, true, nil)
project, _ := models.DB.CreateProject(fmt.Sprintf("test%v", i), nil, "", false, false)
project, _ := models.DB.CreateProject(fmt.Sprintf("test%v", i), "", nil, "", false, false)
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: Missing error handling for CreateProject - ignoring error could mask test failures

Suggested change
project, _ := models.DB.CreateProject(fmt.Sprintf("test%v", i), "", nil, "", false, false)
project, err := models.DB.CreateProject(fmt.Sprintf("test%v", i), "", nil, "", false, false)
assert.NoError(t, err)

@@ -20,8 +20,19 @@ var DEFAULT_ORG_NAME = "digger"
var DB *Database

func ConnectDatabase() {
slogger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: Set log level based on DIGGER_LOG_LEVEL environment variable instead of hardcoding to LevelInfo

Suggested change
slogger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
logLevel := slog.LevelInfo
if os.Getenv("DIGGER_LOG_LEVEL") == "DEBUG" {
logLevel = slog.LevelDebug
}
slogger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: logLevel}))

net "net/http"
"os"
"path"
"strconv"
)

func GetGithubClient(gh utils.GithubClientProvider, installationId int64, repoFullName string) (*github.Client, *string, error) {
slog.Debug("Getting GitHub client",
"installationId", installationId,
"repoFullName", repoFullName)
repo, err := dbmodels.DB.GetRepoByInstllationIdAndRepoFullName(strconv.FormatInt(installationId, 10), repoFullName)
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: Method name contains typo: 'Instllation' is missing an 'a'

Suggested change
repo, err := dbmodels.DB.GetRepoByInstllationIdAndRepoFullName(strconv.FormatInt(installationId, 10), repoFullName)
repo, err := dbmodels.DB.GetRepoByInstallationIdAndRepoFullName(strconv.FormatInt(installationId, 10), repoFullName)

Comment on lines 15 to +16
"log"
"log/slog"
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Using both log and slog packages - consider standardizing on slog throughout

Comment on lines 397 to 402
project := models.Project{
Name: request.Name,
ConfigurationYaml: request.ConfigurationYaml,
OrganisationID: org.ID,
RepoFullName: repo.RepoFullName,
Organisation: org,
Name: request.Name,
OrganisationID: org.ID,
RepoFullName: repo.RepoFullName,
Organisation: org,
}
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: ConfigurationYaml field has been removed from project creation. Ensure this doesn't break any existing code that expects this field.

Copy link

delve-auditor bot commented Jul 4, 2025

No security or compliance issues detected. Reviewed everything up to fd3af41.

Security Overview
  • 🔎 Scanned files: 15 changed file(s)
Detected Code Changes
Change Type Relevant files
Enhancement ► main.go
    Add projects API routes
► projects.go
    Implement ListProjectsApi endpoint
► models/orgs.go
    Update Project model structure
► migrations/20250704024948.sql, migrations/20250704025208.sql
    Add directory column and remove configuration_yaml
Refactor ► models/setup.go
    Update logging configuration
► services/repos.go
    Update GitHub client implementation

Reply to this PR with @delve-auditor followed by a description of what change you want and we'll auto-submit a change to this PR to implement it.

Copy link
Contributor

@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: 2

🧹 Nitpick comments (1)
ee/drift/utils/github.go (1)

38-38: Fix inconsistent capitalization in log message.

The log message capitalization is inconsistent with the similar message above (line 24).

-	slog.Debug("getting github client", "installationId", installationId, "repoFullName", repoFullName)
+	slog.Debug("Getting GitHub client", "installationId", installationId, "repoFullName", repoFullName)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f6cd6a7 and fd3af41.

⛔ Files ignored due to path filters (2)
  • backend/go.sum is excluded by !**/*.sum
  • backend/migrations/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (13)
  • backend/bootstrap/main.go (1 hunks)
  • backend/controllers/github_test.go (1 hunks)
  • backend/controllers/projects.go (2 hunks)
  • backend/go.mod (1 hunks)
  • backend/migrations/20250704024948.sql (1 hunks)
  • backend/migrations/20250704025208.sql (1 hunks)
  • backend/models/orgs.go (2 hunks)
  • backend/models/scheduler_test.go (1 hunks)
  • backend/models/setup.go (2 hunks)
  • backend/models/storage.go (3 hunks)
  • backend/services/repos.go (2 hunks)
  • backend/tasks/runs_test.go (2 hunks)
  • ee/drift/utils/github.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
backend/bootstrap/main.go (1)
backend/controllers/projects.go (1)
  • ListProjectsApi (28-72)
ee/drift/utils/github.go (2)
backend/utils/github.go (2)
  • GetGithubClient (183-196)
  • GithubClientProvider (89-93)
next/utils/github.go (2)
  • GetGithubClient (109-118)
  • GithubClientProvider (44-48)
backend/models/storage.go (3)
backend/models/setup.go (1)
  • Database (13-15)
backend/models/orgs.go (2)
  • Organisation (9-14)
  • Project (74-84)
libs/digger_config/config.go (1)
  • Project (44-62)
backend/controllers/projects.go (3)
backend/middleware/jwt.go (2)
  • ORGANISATION_ID_KEY (326-326)
  • ORGANISATION_SOURCE_KEY (327-327)
backend/models/orgs.go (2)
  • Organisation (9-14)
  • Project (74-84)
backend/models/setup.go (1)
  • DB (20-20)
backend/services/repos.go (1)
ee/drift/utils/github.go (1)
  • GetGithubService (37-52)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Build
  • GitHub Check: Build
  • GitHub Check: Build
  • GitHub Check: Build
  • GitHub Check: Build
  • GitHub Check: Build
  • GitHub Check: Build
  • GitHub Check: Security Check
  • GitHub Check: Build
  • GitHub Check: Build
  • GitHub Check: Build
🔇 Additional comments (17)
backend/go.mod (1)

23-23: Dependency Verified: slog-gorm updated to v2.0.0
The github.com/imdatngo/slog-gorm/v2 module v2.0.0 (released May 7, 2024) exists and has no known security advisories. Please run your integration tests to confirm compatibility with this new major version.

backend/migrations/20250704024948.sql (1)

1-2: LGTM! Migration follows best practices.

The migration safely adds a nullable column, which won't break existing data. The SQL syntax is correct for PostgreSQL.

ee/drift/utils/github.go (2)

16-16: LGTM! Good addition for observability.

Adding structured logging with slog improves debugging capabilities.


24-26: LGTM! Structured logging with relevant parameters.

The debug log provides good context for troubleshooting GitHub client issues.

backend/bootstrap/main.go (1)

232-234: LGTM! API route follows established patterns.

The new projects API endpoint is properly configured with appropriate middleware and follows the existing routing structure. The controller function ListProjectsApi correctly handles the endpoint logic as shown in the relevant code snippets.

backend/controllers/github_test.go (1)

617-617: LGTM: Correctly updated CreateProject call for new signature.

The addition of an empty string as the second argument properly aligns with the updated CreateProject method signature that now includes a directory parameter.

backend/tasks/runs_test.go (1)

77-77: LGTM: CreateProject calls properly updated for new signature.

Both instances correctly add the empty string directory parameter to align with the updated CreateProject method signature.

Also applies to: 143-143

backend/models/scheduler_test.go (1)

57-57: LGTM: CreateProject call correctly updated.

The addition of the empty string directory parameter properly aligns with the updated method signature.

backend/models/orgs.go (2)

77-77: LGTM: Directory field properly added to Project struct.

The new Directory string field is correctly positioned and will support the enhanced project structure.


108-108: LGTM: JSON mapping updated to include Directory field.

The MapToJsonStruct method correctly includes the new Directory field in the JSON output, maintaining consistency with the struct changes.

backend/models/setup.go (1)

23-36: LGTM: Database logging upgraded with structured logging.

The migration to slog-gorm v2 with proper configuration enhances observability. The logger setup includes appropriate settings for grouping, slow query detection, and conditional debug tracing.

backend/services/repos.go (1)

13-13: LGTM! Package refactoring looks correct.

The function signature update to use utils3.GithubClientProvider and the corresponding change to call utils3.GetGithubService along with the added debug logging are all consistent with the package reorganization.

Also applies to: 37-38

backend/models/storage.go (3)

381-381: LGTM! Clear logging message improvement.

The updated log message clarifies that this method fetches by full name rather than just name.


1405-1408: LGTM! Directory field addition is consistent with schema changes.

The new directory parameter and its assignment to the Directory field aligns well with the schema migration that adds this field.


1646-1652: LGTM! Directory handling implementation is correct.

The extraction of projectDirectory from the configuration and its use in both project creation and updates is properly implemented and consistent with the schema changes.

backend/controllers/projects.go (2)

28-72: LGTM! Well-implemented API endpoint with proper error handling.

The new ListProjectsApi function demonstrates good practices:

  • Proper error handling with appropriate HTTP status codes
  • Comprehensive logging for both success and error cases
  • Clean separation of concerns between organization lookup and project querying
  • Consistent response structure

The implementation correctly relies on middleware validation for organization context and handles all error scenarios appropriately.


397-402: LGTM! ConfigurationYaml field removal is consistent with schema changes.

The removal of the ConfigurationYaml field assignment aligns with the database schema migration that drops this column and the model changes that remove this field from the Project struct.

Comment on lines +1 to +2
-- Modify "projects" table
ALTER TABLE "public"."projects" DROP COLUMN "configuration_yaml";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify that all references to configuration_yaml have been removed.

This migration drops the configuration_yaml column, which is a destructive operation. Ensure that:

  1. All code references to ConfigurationYaml field have been removed or updated
  2. Any data migration from configuration_yaml to directory has been completed
  3. This migration is safe to run in production

🏁 Script executed:

#!/bin/bash
# Search for any remaining references to configuration_yaml or ConfigurationYaml
echo "Searching for configuration_yaml references..."
rg -i "configuration_yaml|configurationyaml" --type go --type sql

echo "Searching for ConfigurationYaml field references..."
rg "ConfigurationYaml" --type go -A 3 -B 3

Length of output: 9506


Ensure Complete Removal of configuration_yaml References and Safe Data Migration

Please address the following before merging this destructive migration:

  • Remove all code references to the dropped configuration_yaml column and replace them with the new directory field (or appropriate substitute):
    • next/model/projects.gen.go & next/models_generated/projects.gen.go: eliminate the ConfigurationYaml field, regenerate models.
    • backend/controllers/projects.go: remove ConfigurationYaml from CreateProjectRequest and any handlers (e.g., ReportProjectsForRepo).
    • libs/backendapi/diggerapi.go: drop the configurationYaml parameter and JSON payload, update client calls to use directory.
  • Add a pre-migration step (in an earlier migration) to copy existing configuration_yaml data into directory (or the new storage) for all rows.
  • Delete or update the older migration (20231227132525.sql) that initially created configuration_yaml, if it’s no longer needed.
  • Regenerate and commit any affected codegen artifacts (models, clients) so the codebase compiles without the old field.
  • Verify in a staging environment that:
    1. Data is correctly migrated.
    2. No runtime errors occur in endpoints or background jobs.
    3. The new field behaves as expected.
🤖 Prompt for AI Agents
In backend/migrations/20250704025208.sql at lines 1-2, the migration drops the
configuration_yaml column but does not handle related code or data migration. To
fix this, remove all references to configuration_yaml in the codebase including
the specified Go model files, controller, and API client, replacing them with
the directory field. Add a prior migration that copies data from
configuration_yaml to directory for all existing rows. Also, delete or update
the older migration that created configuration_yaml if obsolete. Regenerate all
affected codegen artifacts to reflect these changes and verify in staging that
data migration is successful and no runtime errors occur.

Comment on lines +1656 to 1659
} else {
p.Directory = projectDirectory
db.GormDB.Save(p)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for the database save operation.

The direct save operation on line 1658 lacks error handling, which could lead to silent failures when updating the project directory.

 } else {
   p.Directory = projectDirectory
-  db.GormDB.Save(p)
+  err := db.GormDB.Save(p).Error
+  if err != nil {
+    return fmt.Errorf("error updating project directory: %v", err)
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} else {
p.Directory = projectDirectory
db.GormDB.Save(p)
}
} else {
p.Directory = projectDirectory
err := db.GormDB.Save(p).Error
if err != nil {
return fmt.Errorf("error updating project directory: %v", err)
}
}
🤖 Prompt for AI Agents
In backend/models/storage.go around lines 1656 to 1659, the call to
db.GormDB.Save(p) does not handle potential errors, risking silent failures.
Modify the code to capture the error returned by the Save operation, check if an
error occurred, and handle it appropriately, such as logging the error or
returning it to the caller to ensure failures are not ignored.

@motatoes motatoes merged commit 5cf11a5 into develop Jul 4, 2025
13 checks passed
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