-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathgetFileSourceApi.ts
More file actions
107 lines (94 loc) · 4.11 KB
/
getFileSourceApi.ts
File metadata and controls
107 lines (94 loc) · 4.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import { sew } from '@/actions';
import { getBrowsePath } from '@/app/[domain]/browse/hooks/utils';
import { getAuditService } from '@/ee/features/audit/factory';
import { SINGLE_TENANT_ORG_DOMAIN } from '@/lib/constants';
import { parseGitAttributes, resolveLanguageFromGitAttributes } from '@/lib/gitattributes';
import { detectLanguageFromFilename } from '@/lib/languageDetection';
import { ServiceError, notFound, fileNotFound, invalidGitRef, unexpectedError } from '@/lib/serviceError';
import { getCodeHostBrowseFileAtBranchUrl } from '@/lib/utils';
import { withOptionalAuthV2 } from '@/withAuthV2';
import { env, getRepoPath } from '@sourcebot/shared';
import { headers } from 'next/headers';
import simpleGit from 'simple-git';
import type z from 'zod';
import { isGitRefValid, isPathValid } from './utils';
import { fileSourceRequestSchema, fileSourceResponseSchema } from './schemas';
export { fileSourceRequestSchema, fileSourceResponseSchema } from './schemas';
export type FileSourceRequest = z.infer<typeof fileSourceRequestSchema>;
export type FileSourceResponse = z.infer<typeof fileSourceResponseSchema>;
export const getFileSource = async ({ path: filePath, repo: repoName, ref }: FileSourceRequest, { source }: { source?: string } = {}): Promise<FileSourceResponse | ServiceError> => sew(() => withOptionalAuthV2(async ({ org, prisma, user }) => {
if (user) {
const resolvedSource = source ?? (await headers()).get('X-Sourcebot-Client-Source') ?? undefined;
getAuditService().createAudit({
action: 'user.fetched_file_source',
actor: { id: user.id, type: 'user' },
target: { id: org.id.toString(), type: 'org' },
orgId: org.id,
metadata: { source: resolvedSource },
});
}
const repo = await prisma.repo.findFirst({
where: { name: repoName, orgId: org.id },
});
if (!repo) {
return notFound(`Repository "${repoName}" not found.`);
}
if (!isPathValid(filePath)) {
return fileNotFound(filePath, repoName);
}
if (ref !== undefined && !isGitRefValid(ref)) {
return invalidGitRef(ref);
}
const { path: repoPath } = getRepoPath(repo);
const git = simpleGit().cwd(repoPath);
const gitRef = ref ??
repo.defaultBranch ??
'HEAD';
let fileContent: string;
try {
fileContent = await git.raw(['show', `${gitRef}:${filePath}`]);
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error);
if (errorMessage.includes('does not exist') || errorMessage.includes('fatal: path')) {
return fileNotFound(filePath, repoName);
}
if (errorMessage.includes('unknown revision') || errorMessage.includes('bad revision') || errorMessage.includes('invalid object name')) {
return unexpectedError(`Invalid git reference: ${gitRef}`);
}
throw error;
}
let gitattributesContent: string | undefined;
try {
gitattributesContent = await git.raw(['show', `${gitRef}:.gitattributes`]);
} catch {
// No .gitattributes in this repo/ref, that's fine
}
const language = gitattributesContent
? (resolveLanguageFromGitAttributes(filePath, parseGitAttributes(gitattributesContent)) ?? detectLanguageFromFilename(filePath))
: detectLanguageFromFilename(filePath);
const externalWebUrl = getCodeHostBrowseFileAtBranchUrl({
webUrl: repo.webUrl,
codeHostType: repo.external_codeHostType,
branchName: gitRef,
filePath,
});
const baseUrl = env.AUTH_URL;
const webUrl = `${baseUrl}${getBrowsePath({
repoName: repo.name,
revisionName: ref,
path: filePath,
pathType: 'blob',
domain: SINGLE_TENANT_ORG_DOMAIN,
})}`;
return {
source: fileContent,
language,
path: filePath,
repo: repoName,
repoCodeHostType: repo.external_codeHostType,
repoDisplayName: repo.displayName ?? undefined,
repoExternalWebUrl: repo.webUrl ?? undefined,
webUrl,
externalWebUrl,
} satisfies FileSourceResponse;
}));