Skip to content

Conversation

@HarshMN2345
Copy link
Member

@HarshMN2345 HarshMN2345 commented Nov 10, 2025

What does this PR do?

(Provide a description of what this PR does.)

Test Plan

(Write your test plan here. If you changed any code, please provide us with clear instructions on how you verified your changes work.)

Related PRs and Issues

(If this PR is related to any other PR or resolves any issue or related to any issue link all related PR and issues here.)

Have you read the Contributing Guidelines on issues?

(Write your answer here.)

Summary by CodeRabbit

  • New Features

    • Enhanced template source URL generation to include folder-specific paths when available.
    • Added provider-specific URL path formatting for GitHub, GitLab, and Bitbucket.
  • Bug Fixes

    • Improved handling of unsupported providers with explicit null return instead of fallback resolution.

@appwrite
Copy link

appwrite bot commented Nov 10, 2025

Console (appwrite/console)

Project ID: 688b7bf400350cbd60e9

Sites (1)
Site Status Logs Preview QR
 console-stage
688b7cf6003b1842c9dc
Ready Ready View Logs Preview URL QR Code

Tip

Function scopes give you fine-grained control over API permissions

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 10, 2025

Walkthrough

The change modifies the template source helper to handle unsupported providers explicitly by returning null, extracts a folder path from template data (from either providerRootDirectory or frameworks[0].providerRootDirectory), and appends provider-specific tree paths to repository URLs. For GitHub, it appends /tree/main/{normalizedPath}; for GitLab, /-/tree/main/{normalizedPath}; and for Bitbucket, /src/main/{normalizedPath}. The base URL structure remains as https://{host}/{owner}/{repo} when no folder path exists. Documentation examples are updated to reflect the new URL format.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Provider-specific path construction logic should be verified for correctness across GitHub, GitLab, and Bitbucket formats
  • Folder path extraction logic and its fallback behavior (providerRootDirectory vs frameworks[0].providerRootDirectory) warrants confirmation
  • URL normalization and path joining approach should be reviewed for consistency with existing patterns in the codebase

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: modifying the View source button to point to a specific template folder rather than just the repo root.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-SER-483-respect-directory-view-source

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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: 1

🧹 Nitpick comments (2)
src/lib/helpers/templateSource.ts (2)

44-53: Consider URL-encoding the folder path.

The normalizedPath is directly interpolated into the URL without encoding. Folder paths containing special characters (spaces, unicode, etc.) could produce malformed URLs.

Apply this approach:

     if (folderPath) {
         const normalizedPath = folderPath.replace(/^\/+|\/+$/g, '');
         if (normalizedPath) {
+            const encodedPath = encodeURIComponent(normalizedPath).replace(/%2F/g, '/');
             const providerLower = provider.toLowerCase();
             if (providerLower === 'github') {
-                url = `${url}/tree/main/${normalizedPath}`;
+                url = `${url}/tree/main/${encodedPath}`;
             } else if (providerLower === 'gitlab') {
-                url = `${url}/-/tree/main/${normalizedPath}`;
+                url = `${url}/-/tree/main/${encodedPath}`;
             } else if (providerLower === 'bitbucket') {
-                url = `${url}/src/main/${normalizedPath}`;
+                url = `${url}/src/main/${encodedPath}`;
             }
         }
     }

Note: encodeURIComponent encodes slashes too, so we need to restore them for path separators.


11-11: Optional: Cache provider.toLowerCase() result.

The provider string is converted to lowercase three times (lines 22 and 46, with line 11 potentially used later). Consider caching it once:

     const owner = t.providerOwner;
     const repo = t.providerRepositoryId;
-    const provider = t.vcsProvider; // e.g., "github"
+    const provider = t.vcsProvider?.toLowerCase(); // e.g., "github"

     if (!owner || !repo || !provider) return null;

     // Map provider → host (extend if needed)
     const hostMap: Record<string, string> = {
         github: 'github.com',
         gitlab: 'gitlab.com',
         bitbucket: 'bitbucket.org'
     };

-    const host = hostMap[provider.toLowerCase()];
+    const host = hostMap[provider];
     if (!host) return null;
     
     // ... later in the code ...
     
-            const providerLower = provider.toLowerCase();
-            if (providerLower === 'github') {
+            if (provider === 'github') {

Also applies to: 22-22, 46-46

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 73552e5 and 3dd1e39.

📒 Files selected for processing (1)
  • src/lib/helpers/templateSource.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: e2e
  • GitHub Check: build
🔇 Additional comments (3)
src/lib/helpers/templateSource.ts (3)

4-4: Documentation example looks good.

The updated example clearly demonstrates the new URL format with the tree path.


22-23: LGTM: Explicit null return for unsupported providers.

Returning null explicitly when the provider is unsupported is the correct approach, avoiding potentially incorrect URL construction.


25-39: Well-structured folderPath extraction.

The type narrowing with in operator and explicit type checks is solid. Edge cases like empty frameworks arrays are properly handled with optional chaining.

Comment on lines +47 to +53
if (providerLower === 'github') {
url = `${url}/tree/main/${normalizedPath}`;
} else if (providerLower === 'gitlab') {
url = `${url}/-/tree/main/${normalizedPath}`;
} else if (providerLower === 'bitbucket') {
url = `${url}/src/main/${normalizedPath}`;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Hardcoded branch name may cause broken links.

The branch name "main" is hardcoded across all providers. Repositories using different default branches (e.g., "master", "develop", or custom branches) will result in 404 errors when users click "View source".

Consider one of these approaches:

  • Add a providerBranch field to the template data and use it here with "main" as fallback
  • Query the repository's default branch via the provider's API
  • Make the branch name configurable

Run this script to check if template data contains branch information:


🏁 Script executed:

#!/bin/bash
# Search for branch-related fields in Models definitions or template data structures
rg -n -C3 --type=ts "branch|Branch|defaultBranch" | head -50

Length of output: 4229


Need to verify the broader context. Let me examine the templateSource.ts file and check for related branch-fetching infrastructure.

Now let me examine the templateSource.ts file to understand its context and whether it uses the existing branch-fetching infrastructure.

[/run_scripts]


🏁 Script executed:

#!/bin/bash
# View templateSource.ts to understand context and check for branch handling
cat src/lib/helpers/templateSource.ts | head -100

Length of output: 1841


🏁 Script executed:

#!/bin/bash
# Search for getDefaultBranch usage across codebase
rg -n "getDefaultBranch" --type=ts

Length of output: 122


🏁 Script executed:

#!/bin/bash
# Search for GitLab and Bitbucket equivalent functions
rg -n "getDefault|defaultBranch" src/lib/helpers/ --type=ts -A2

Length of output: 281


🏁 Script executed:

#!/bin/bash
# Check Models.ProviderRepository structure
rg -n "ProviderRepository" --type=ts -A10 | head -80

Length of output: 1963


🏁 Script executed:

#!/bin/bash
# Check what data is passed into the templateSource function
rg -n "templateSource" --type=ts -B2 -A2 | head -100

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Find where getTemplateSourceUrl is imported/called
rg -n "getTemplateSourceUrl" --type=ts -B3 -A3

Length of output: 501


🏁 Script executed:

#!/bin/bash
# Check for any URL encoding utilities in the codebase
rg -n "encodeURI|URLSearchParams|encodeComponent" --type=ts | head -20

Length of output: 696


🏁 Script executed:

#!/bin/bash
# Look for Models.TemplateSite and TemplateFunction definitions to check for branch field
rg -n "Models\.(TemplateSite|TemplateFunction)" src/lib/ --type=ts -B5 -A5 | head -100

Length of output: 745


[/run_scripts]


🏁 Script executed:

#!/bin/bash
# Search for imports of getTemplateSourceUrl (try different patterns)
rg -n "import.*getTemplateSourceUrl|from.*templateSource" --type=ts

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Check for exports in lib/helpers/index files
fd -n "index.ts" src/lib/helpers/ --exec cat {} \;

Length of output: 230


🏁 Script executed:

#!/bin/bash
# Search for template URL usage (links, hrefs, etc.)
rg -n "getTemplateSourceUrl\|templateUrl\|template.*url" --type=ts --type=svelte | head -50

Length of output: 30


🏁 Script executed:

#!/bin/bash
# Look at what pages/components use template data
rg -n "TemplateSite|TemplateFunction" src/lib/components --type=ts --type=svelte -l

Length of output: 30


[/run_scripts]


🏁 Script executed:

#!/bin/bash
# List helpers/index files correctly
find src/lib/helpers -name "index.ts" -exec cat {} \;

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Search for getTemplateSourceUrl without type restrictions
rg -n "getTemplateSourceUrl" --no-type-list

Length of output: 443


🏁 Script executed:

#!/bin/bash
# Search for component/page files using template data (wider search)
rg -n "TemplateSite\|TemplateFunction" src/lib/components -A3 -B3 2>/dev/null | head -80

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Check git log to see if this is new code
git log --oneline -20 -- src/lib/helpers/templateSource.ts 2>/dev/null || echo "No git history available"

Length of output: 277


🏁 Script executed:

#!/bin/bash
# Search all files (any extension) for usage of this function
rg "getTemplateSourceUrl" -A2 -B2 --max-count=20

Length of output: 1962


Hardcoded branch causes broken links for non-standard repositories.

This generates user-visible links from the "View source" button in templates. Repositories using default branches other than "main" (e.g., "master", "develop", or custom names) will result in 404 errors when users click the link.

Additionally, normalizedPath is inserted directly into the URL without encoding, which will break URLs containing special characters (spaces, #, ?, etc.).

Suggested fixes:

  • Add a branch field to template metadata and pass it through
  • Query the repository's default branch via provider APIs (infrastructure exists for GitHub but isn't used)
  • Make branch configurable per template

Consider also applying encodeURIComponent to the path segment (which is already used elsewhere in the codebase).

🤖 Prompt for AI Agents
In src/lib/helpers/templateSource.ts around lines 47 to 53, the URL builder
hardcodes the "main" branch and inserts normalizedPath unencoded, causing 404s
for repos with non-standard default branches and breaking on special characters;
update the logic to accept a branch value (prefer a branch field in template
metadata, falling back to a passed-in branch or to querying the provider
API/default branch if available), use that branch variable instead of the
literal "main" in provider-specific URL formats, and wrap the path segment with
encodeURIComponent (or the existing encoding helper) before interpolating into
the URL so spaces and special characters are safe. Ensure the branch is optional
and falls back gracefully to existing behavior when not supplied and provider
lookup fails.

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.

2 participants