2025-05-03 18:33:58 +00:00
|
|
|
import escapeStringRegexp from "escape-string-regexp";
|
|
|
|
|
import { fileNotFound, ServiceError } from "../../lib/serviceError";
|
|
|
|
|
import { FileSourceRequest, FileSourceResponse } from "./types";
|
|
|
|
|
import { isServiceError } from "../../lib/utils";
|
|
|
|
|
import { search } from "./searchApi";
|
2025-05-15 20:42:58 +00:00
|
|
|
import { sew, withAuth, withOrgMembership } from "@/actions";
|
2025-05-03 18:33:58 +00:00
|
|
|
|
|
|
|
|
// @todo (bkellam) : We should really be using `git show <hash>:<path>` to fetch file contents here.
|
|
|
|
|
// This will allow us to support permalinks to files at a specific revision that may not be indexed
|
|
|
|
|
// by zoekt.
|
2025-05-15 20:42:58 +00:00
|
|
|
export const getFileSource = async ({ fileName, repository, branch }: FileSourceRequest, domain: string): Promise<FileSourceResponse | ServiceError> => sew(() =>
|
|
|
|
|
withAuth((session) =>
|
|
|
|
|
withOrgMembership(session, domain, async () => {
|
|
|
|
|
const escapedFileName = escapeStringRegexp(fileName);
|
|
|
|
|
const escapedRepository = escapeStringRegexp(repository);
|
2025-05-03 18:33:58 +00:00
|
|
|
|
2025-05-15 20:42:58 +00:00
|
|
|
let query = `file:${escapedFileName} repo:^${escapedRepository}$`;
|
|
|
|
|
if (branch) {
|
|
|
|
|
query = query.concat(` branch:${branch}`);
|
|
|
|
|
}
|
2025-05-03 18:33:58 +00:00
|
|
|
|
2025-05-15 20:42:58 +00:00
|
|
|
const searchResponse = await search({
|
|
|
|
|
query,
|
|
|
|
|
matches: 1,
|
|
|
|
|
whole: true,
|
|
|
|
|
}, domain);
|
2025-05-03 18:33:58 +00:00
|
|
|
|
2025-05-15 20:42:58 +00:00
|
|
|
if (isServiceError(searchResponse)) {
|
|
|
|
|
return searchResponse;
|
|
|
|
|
}
|
2025-05-03 18:33:58 +00:00
|
|
|
|
2025-05-15 20:42:58 +00:00
|
|
|
const files = searchResponse.files;
|
2025-05-03 18:33:58 +00:00
|
|
|
|
2025-05-15 20:42:58 +00:00
|
|
|
if (!files || files.length === 0) {
|
|
|
|
|
return fileNotFound(fileName, repository);
|
|
|
|
|
}
|
2025-05-03 18:33:58 +00:00
|
|
|
|
2025-05-15 20:42:58 +00:00
|
|
|
const file = files[0];
|
|
|
|
|
const source = file.content ?? '';
|
|
|
|
|
const language = file.language;
|
|
|
|
|
return {
|
|
|
|
|
source,
|
|
|
|
|
language,
|
|
|
|
|
} satisfies FileSourceResponse;
|
|
|
|
|
}), /* allowSingleTenantUnauthedAccess = */ true)
|
|
|
|
|
);
|