Skip to content

Commit 2629ce6

Browse files
committed
Fix: Grab Default Branch instead of main/master.
1 parent 919b040 commit 2629ce6

File tree

3 files changed

+123
-15
lines changed

3 files changed

+123
-15
lines changed

api/data_pipeline.py

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -524,8 +524,25 @@ def get_gitlab_file_content(repo_url: str, file_path: str, access_token: str = N
524524
# Encode file path
525525
encoded_file_path = quote(file_path, safe='')
526526

527-
# Default to 'main' branch if not specified
528-
default_branch = 'main'
527+
# Try to get the default branch from the project info
528+
default_branch = None
529+
try:
530+
project_info_url = f"{gitlab_domain}/api/v4/projects/{encoded_project_path}"
531+
project_headers = {}
532+
if access_token:
533+
project_headers["PRIVATE-TOKEN"] = access_token
534+
535+
project_response = requests.get(project_info_url, headers=project_headers)
536+
if project_response.status_code == 200:
537+
project_data = project_response.json()
538+
default_branch = project_data.get('default_branch', 'main')
539+
logger.info(f"Found default branch: {default_branch}")
540+
else:
541+
logger.warning(f"Could not fetch project info, using 'main' as default branch")
542+
default_branch = 'main'
543+
except Exception as e:
544+
logger.warning(f"Error fetching project info: {e}, using 'main' as default branch")
545+
default_branch = 'main'
529546

530547
api_url = f"{gitlab_domain}/api/v4/projects/{encoded_project_path}/repository/files/{encoded_file_path}/raw?ref={default_branch}"
531548
# Fetch file content from GitLab API
@@ -578,9 +595,29 @@ def get_bitbucket_file_content(repo_url: str, file_path: str, access_token: str
578595
owner = parts[-2]
579596
repo = parts[-1].replace(".git", "")
580597

598+
# Try to get the default branch from the repository info
599+
default_branch = None
600+
try:
601+
repo_info_url = f"https://api.bitbucket.org/2.0/repositories/{owner}/{repo}"
602+
repo_headers = {}
603+
if access_token:
604+
repo_headers["Authorization"] = f"Bearer {access_token}"
605+
606+
repo_response = requests.get(repo_info_url, headers=repo_headers)
607+
if repo_response.status_code == 200:
608+
repo_data = repo_response.json()
609+
default_branch = repo_data.get('mainbranch', {}).get('name', 'main')
610+
logger.info(f"Found default branch: {default_branch}")
611+
else:
612+
logger.warning(f"Could not fetch repository info, using 'main' as default branch")
613+
default_branch = 'main'
614+
except Exception as e:
615+
logger.warning(f"Error fetching repository info: {e}, using 'main' as default branch")
616+
default_branch = 'main'
617+
581618
# Use Bitbucket API to get file content
582619
# The API endpoint for getting file content is: /2.0/repositories/{owner}/{repo}/src/{branch}/{path}
583-
api_url = f"https://api.bitbucket.org/2.0/repositories/{owner}/{repo}/src/main/{file_path}"
620+
api_url = f"https://api.bitbucket.org/2.0/repositories/{owner}/{repo}/src/{default_branch}/{file_path}"
584621

585622
# Fetch file content from Bitbucket API
586623
headers = {}

src/app/[owner]/[repo]/page.tsx

Lines changed: 81 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,43 @@ export default function RepoWikiPage() {
251251
const [authCode, setAuthCode] = useState<string>('');
252252
const [isAuthLoading, setIsAuthLoading] = useState<boolean>(true);
253253

254+
// Default branch state
255+
const [defaultBranch, setDefaultBranch] = useState<string>('main');
256+
257+
// Helper function to generate proper repository file URLs
258+
const generateFileUrl = useCallback((filePath: string): string => {
259+
if (effectiveRepoInfo.type === 'local') {
260+
// For local repositories, we can't generate web URLs
261+
return filePath;
262+
}
263+
264+
const repoUrl = effectiveRepoInfo.repoUrl;
265+
if (!repoUrl) {
266+
return filePath;
267+
}
268+
269+
try {
270+
const url = new URL(repoUrl);
271+
const hostname = url.hostname;
272+
273+
if (hostname === 'github.com' || hostname.includes('github')) {
274+
// GitHub URL format: https://github.com/owner/repo/blob/branch/path
275+
return `${repoUrl}/blob/${defaultBranch}/${filePath}`;
276+
} else if (hostname === 'gitlab.com' || hostname.includes('gitlab')) {
277+
// GitLab URL format: https://gitlab.com/owner/repo/-/blob/branch/path
278+
return `${repoUrl}/-/blob/${defaultBranch}/${filePath}`;
279+
} else if (hostname === 'bitbucket.org' || hostname.includes('bitbucket')) {
280+
// Bitbucket URL format: https://bitbucket.org/owner/repo/src/branch/path
281+
return `${repoUrl}/src/${defaultBranch}/${filePath}`;
282+
}
283+
} catch (error) {
284+
console.warn('Error generating file URL:', error);
285+
}
286+
287+
// Fallback to just the file path
288+
return filePath;
289+
}, [effectiveRepoInfo, defaultBranch]);
290+
254291
// Memoize repo info to avoid triggering updates in callbacks
255292

256293
// Add useEffect to handle scroll reset
@@ -367,7 +404,7 @@ Format it exactly like this:
367404
Remember, do not provide any acknowledgements, disclaimers, apologies, or any other preface before the \`<details>\` block. JUST START with the \`<details>\` block.
368405
The following files were used as context for generating this wiki page:
369406
370-
${filePaths.map(path => `- [${path}](${path})`).join('\n')}
407+
${filePaths.map(path => `- [${path}](${generateFileUrl(path)})`).join('\n')}
371408
<!-- Add additional relevant files if fewer than 5 were provided -->
372409
</details>
373410
@@ -407,7 +444,7 @@ Based ONLY on the content of the \`[RELEVANT_SOURCE_FILES]\`:
407444
* Configuration options, their types, and default values.
408445
* Data model fields, types, constraints, and descriptions.
409446
410-
5. **Code Snippets:**
447+
5. **Code Snippets (ENTIRELY OPTIONAL):**
411448
* Include short, relevant code snippets (e.g., Python, Java, JavaScript, SQL, JSON, YAML) directly from the \`[RELEVANT_SOURCE_FILES]\` to illustrate key implementation details, data structures, or configurations.
412449
* Ensure snippets are well-formatted within Markdown code blocks with appropriate language identifiers.
413450
@@ -591,7 +628,7 @@ Remember:
591628
setLoadingMessage(undefined); // Clear specific loading message
592629
}
593630
});
594-
}, [generatedPages, currentToken, effectiveRepoInfo, selectedProviderState, selectedModelState, isCustomSelectedModelState, customSelectedModelState, modelExcludedDirs, modelExcludedFiles, language, activeContentRequests]);
631+
}, [generatedPages, currentToken, effectiveRepoInfo, selectedProviderState, selectedModelState, isCustomSelectedModelState, customSelectedModelState, modelExcludedDirs, modelExcludedFiles, language, activeContentRequests, generateFileUrl]);
595632

596633
// Determine the wiki structure from repository data
597634
const determineWikiStructure = useCallback(async (fileTree: string, readme: string, owner: string, repo: string) => {
@@ -1111,6 +1148,8 @@ IMPORTANT:
11111148
const data = await response.json();
11121149
fileTreeData = data.file_tree;
11131150
readmeContent = data.readme;
1151+
// For local repos, we can't determine the actual branch, so use 'main' as default
1152+
setDefaultBranch('main');
11141153
} catch (err) {
11151154
throw err;
11161155
}
@@ -1145,7 +1184,30 @@ IMPORTANT:
11451184

11461185
const githubApiBaseUrl = getGithubApiUrl(effectiveRepoInfo.repoUrl);
11471186

1148-
for (const branch of ['main', 'master']) {
1187+
// First, try to get the default branch from the repository info
1188+
let defaultBranchLocal = null;
1189+
try {
1190+
const repoInfoResponse = await fetch(`${githubApiBaseUrl}/repos/${owner}/${repo}`, {
1191+
headers: createGithubHeaders(currentToken)
1192+
});
1193+
1194+
if (repoInfoResponse.ok) {
1195+
const repoData = await repoInfoResponse.json();
1196+
defaultBranchLocal = repoData.default_branch;
1197+
console.log(`Found default branch: ${defaultBranchLocal}`);
1198+
// Store the default branch in state
1199+
setDefaultBranch(defaultBranchLocal || 'main');
1200+
}
1201+
} catch (err) {
1202+
console.warn('Could not fetch repository info for default branch:', err);
1203+
}
1204+
1205+
// Create list of branches to try, prioritizing the actual default branch
1206+
const branchesToTry = defaultBranchLocal
1207+
? [defaultBranchLocal, 'main', 'master'].filter((branch, index, arr) => arr.indexOf(branch) === index)
1208+
: ['main', 'master'];
1209+
1210+
for (const branch of branchesToTry) {
11491211
const apiUrl = `${githubApiBaseUrl}/repos/${owner}/${repo}/git/trees/${branch}?recursive=1`;
11501212
const headers = createGithubHeaders(currentToken);
11511213

@@ -1215,6 +1277,7 @@ IMPORTANT:
12151277
try {
12161278
// Step 1: Get project info to determine default branch
12171279
let projectInfoUrl: string;
1280+
let defaultBranchLocal = 'main'; // fallback
12181281
try {
12191282
const validatedUrl = new URL(projectDomain ?? ''); // Validate domain
12201283
projectInfoUrl = `${validatedUrl.origin}/api/v4/projects/${encodedProjectPath}`;
@@ -1228,10 +1291,16 @@ IMPORTANT:
12281291
throw new Error(`GitLab project info error: Status ${projectInfoRes.status}, Response: ${errorData}`);
12291292
}
12301293

1294+
const projectInfo = await projectInfoRes.json();
1295+
defaultBranchLocal = projectInfo.default_branch || 'main';
1296+
console.log(`Found GitLab default branch: ${defaultBranchLocal}`);
1297+
// Store the default branch in state
1298+
setDefaultBranch(defaultBranchLocal);
1299+
12311300
// Step 2: Paginate to fetch full file tree
12321301
let page = 1;
12331302
let morePages = true;
1234-
1303+
12351304
while (morePages) {
12361305
const apiUrl = `${projectInfoUrl}/repository/tree?recursive=true&per_page=100&page=${page}`;
12371306
const response = await fetch(apiUrl, { headers });
@@ -1285,7 +1354,7 @@ IMPORTANT:
12851354
// Try to get the file tree for common branch names
12861355
let filesData = null;
12871356
let apiErrorDetails = '';
1288-
let defaultBranch = '';
1357+
let defaultBranchLocal = '';
12891358
const headers = createBitbucketHeaders(currentToken);
12901359

12911360
// First get project info to determine default branch
@@ -1297,9 +1366,11 @@ IMPORTANT:
12971366

12981367
if (response.ok) {
12991368
const projectData = JSON.parse(responseText);
1300-
defaultBranch = projectData.mainbranch.name;
1369+
defaultBranchLocal = projectData.mainbranch.name;
1370+
// Store the default branch in state
1371+
setDefaultBranch(defaultBranchLocal);
13011372

1302-
const apiUrl = `https://api.bitbucket.org/2.0/repositories/${encodedRepoPath}/src/${defaultBranch}/?recursive=true&per_page=100`;
1373+
const apiUrl = `https://api.bitbucket.org/2.0/repositories/${encodedRepoPath}/src/${defaultBranchLocal}/?recursive=true&per_page=100`;
13031374
try {
13041375
const response = await fetch(apiUrl, {
13051376
headers
@@ -1314,7 +1385,7 @@ IMPORTANT:
13141385
apiErrorDetails = `Status: ${response.status}, Response: ${errorData}`;
13151386
}
13161387
} catch (err) {
1317-
console.error(`Network error fetching Bitbucket branch ${defaultBranch}:`, err);
1388+
console.error(`Network error fetching Bitbucket branch ${defaultBranchLocal}:`, err);
13181389
}
13191390
} else {
13201391
const errorData = responseText;
@@ -1342,7 +1413,7 @@ IMPORTANT:
13421413
try {
13431414
const headers = createBitbucketHeaders(currentToken);
13441415

1345-
const readmeResponse = await fetch(`https://api.bitbucket.org/2.0/repositories/${encodedRepoPath}/src/${defaultBranch}/README.md`, {
1416+
const readmeResponse = await fetch(`https://api.bitbucket.org/2.0/repositories/${encodedRepoPath}/src/${defaultBranchLocal}/README.md`, {
13461417
headers
13471418
});
13481419

src/app/api/auth/status/route.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import { NextRequest, NextResponse } from "next/server";
1+
import { NextResponse } from "next/server";
22

33
const TARGET_SERVER_BASE_URL = process.env.SERVER_BASE_URL || 'http://localhost:8001';
44

5-
export async function GET(request: NextRequest) {
5+
export async function GET() {
66
try {
77
// Forward the request to the backend API
88
const response = await fetch(`${TARGET_SERVER_BASE_URL}/auth/status`, {

0 commit comments

Comments
 (0)