80 lines
2.0 KiB
TypeScript
80 lines
2.0 KiB
TypeScript
export function getGiteaToken(env: NodeJS.ProcessEnv): string | undefined {
|
|
return firstValue(env.WPOP_GITEA_TOKEN, env.WEBSIMPLE_GITEA_API_TOKEN, env.GITEA_TOKEN);
|
|
}
|
|
|
|
export function getGiteaBaseUrl(env: NodeJS.ProcessEnv): string {
|
|
return firstValue(env.WPOP_GITEA_BASE_URL, env.GITEA_BASE_URL) ?? "https://gitea.websimple.com";
|
|
}
|
|
|
|
export async function giteaRepoExists(
|
|
baseUrl: string,
|
|
token: string,
|
|
owner: string,
|
|
repo: string,
|
|
): Promise<boolean> {
|
|
const url = new URL(
|
|
`/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`,
|
|
baseUrl,
|
|
);
|
|
|
|
const response = await fetch(url, {
|
|
headers: {
|
|
Accept: "application/json",
|
|
Authorization: `token ${token}`,
|
|
},
|
|
});
|
|
|
|
if (response.status === 200) {
|
|
return true;
|
|
}
|
|
|
|
if (response.status === 404) {
|
|
return false;
|
|
}
|
|
|
|
throw new Error(`Gitea API request failed (${response.status}) while checking ${owner}/${repo}`);
|
|
}
|
|
|
|
export async function generateGiteaRepo(
|
|
baseUrl: string,
|
|
token: string,
|
|
options: { templateOwner: string; templateRepo: string; owner: string; name: string },
|
|
): Promise<void> {
|
|
const url = new URL(
|
|
`/api/v1/repos/${encodeURIComponent(options.templateOwner)}/${encodeURIComponent(options.templateRepo)}/generate`,
|
|
baseUrl,
|
|
);
|
|
|
|
const response = await fetch(url, {
|
|
method: "POST",
|
|
headers: {
|
|
Accept: "application/json",
|
|
Authorization: `token ${token}`,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
owner: options.owner,
|
|
name: options.name,
|
|
git_content: true,
|
|
private: true,
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(
|
|
`Gitea API request failed (${response.status}) while generating ${options.owner}/${options.name} from ${options.templateOwner}/${options.templateRepo}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
function firstValue(...values: (string | undefined)[]): string | undefined {
|
|
for (const value of values) {
|
|
const trimmed = value?.trim();
|
|
if (trimmed) {
|
|
return trimmed;
|
|
}
|
|
}
|
|
|
|
return undefined;
|
|
}
|