mirror of
https://gitbruv.vercel.app/api/git/bruv/gitbruv.git
synced 2025-12-20 23:24:09 +01:00
mvp
This commit is contained in:
parent
8f672d012c
commit
46cab693db
49 changed files with 4725 additions and 118 deletions
16
lib/auth-client.ts
Normal file
16
lib/auth-client.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { createAuthClient } from "better-auth/react";
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000",
|
||||
});
|
||||
|
||||
export const { signIn, signOut, useSession } = authClient;
|
||||
|
||||
export async function signUpWithUsername(data: {
|
||||
email: string;
|
||||
password: string;
|
||||
name: string;
|
||||
username: string;
|
||||
}) {
|
||||
return authClient.signUp.email(data as Parameters<typeof authClient.signUp.email>[0]);
|
||||
}
|
||||
33
lib/auth.ts
Normal file
33
lib/auth.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { betterAuth } from "better-auth";
|
||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||
import { db } from "@/db";
|
||||
import * as schema from "@/db/schema";
|
||||
import { nextCookies } from "better-auth/next-js";
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: drizzleAdapter(db, {
|
||||
provider: "pg",
|
||||
schema: {
|
||||
user: schema.users,
|
||||
session: schema.sessions,
|
||||
account: schema.accounts,
|
||||
verification: schema.verifications,
|
||||
},
|
||||
}),
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
requireEmailVerification: false,
|
||||
},
|
||||
user: {
|
||||
additionalFields: {
|
||||
username: {
|
||||
type: "string",
|
||||
required: true,
|
||||
input: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [nextCookies()],
|
||||
});
|
||||
|
||||
export type Session = typeof auth.$Infer.Session;
|
||||
23
lib/query-client.tsx
Normal file
23
lib/query-client.tsx
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
"use client";
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
|
||||
export function QueryProvider({ children }: { children: React.ReactNode }) {
|
||||
const [queryClient] = useState(
|
||||
() =>
|
||||
new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 60 * 1000,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
155
lib/r2-fs.ts
Normal file
155
lib/r2-fs.ts
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
import { r2Get, r2Put, r2Delete, r2Exists, r2List, r2DeletePrefix } from "./r2";
|
||||
|
||||
function normalizePath(path: string): string {
|
||||
return path.replace(/\/+/g, "/").replace(/^\//, "").replace(/\/$/, "");
|
||||
}
|
||||
|
||||
function createStatResult(type: "file" | "dir", size: number) {
|
||||
const now = Date.now();
|
||||
return {
|
||||
type,
|
||||
mode: type === "dir" ? 0o40755 : 0o100644,
|
||||
size,
|
||||
ino: 0,
|
||||
mtimeMs: now,
|
||||
ctimeMs: now,
|
||||
uid: 1000,
|
||||
gid: 1000,
|
||||
dev: 0,
|
||||
isFile: () => type === "file",
|
||||
isDirectory: () => type === "dir",
|
||||
isSymbolicLink: () => false,
|
||||
};
|
||||
}
|
||||
|
||||
export function createR2Fs(repoPrefix: string) {
|
||||
const dirMarkerCache = new Set<string>();
|
||||
|
||||
const getKey = (filepath: string) => {
|
||||
const normalized = normalizePath(filepath);
|
||||
if (normalized.startsWith(repoPrefix)) {
|
||||
return normalized;
|
||||
}
|
||||
if (!normalized) {
|
||||
return repoPrefix;
|
||||
}
|
||||
return `${repoPrefix}/${normalized}`.replace(/\/+/g, "/");
|
||||
};
|
||||
|
||||
const readFile = async (filepath: string, options?: { encoding?: string }): Promise<Buffer | string> => {
|
||||
const key = getKey(filepath);
|
||||
const data = await r2Get(key);
|
||||
if (!data) {
|
||||
const err = new Error(`ENOENT: no such file or directory, open '${filepath}'`) as NodeJS.ErrnoException;
|
||||
err.code = "ENOENT";
|
||||
throw err;
|
||||
}
|
||||
if (options?.encoding === "utf8" || options?.encoding === "utf-8") {
|
||||
return data.toString("utf-8");
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
const writeFile = async (filepath: string, data: Buffer | string): Promise<void> => {
|
||||
const key = getKey(filepath);
|
||||
await r2Put(key, typeof data === "string" ? Buffer.from(data) : data);
|
||||
};
|
||||
|
||||
const unlink = async (filepath: string): Promise<void> => {
|
||||
const key = getKey(filepath);
|
||||
await r2Delete(key);
|
||||
};
|
||||
|
||||
const readdir = async (filepath: string): Promise<string[]> => {
|
||||
const prefix = getKey(filepath);
|
||||
const fullPrefix = prefix.endsWith("/") ? prefix : `${prefix}/`;
|
||||
const keys = await r2List(fullPrefix);
|
||||
|
||||
const entries = new Set<string>();
|
||||
for (const key of keys) {
|
||||
const relative = key.slice(fullPrefix.length);
|
||||
if (!relative) continue;
|
||||
const firstPart = relative.split("/")[0];
|
||||
if (firstPart) entries.add(firstPart);
|
||||
}
|
||||
|
||||
return Array.from(entries);
|
||||
};
|
||||
|
||||
const mkdir = async (filepath: string): Promise<void> => {
|
||||
const key = getKey(filepath);
|
||||
dirMarkerCache.add(key);
|
||||
};
|
||||
|
||||
const rmdir = async (filepath: string, options?: { recursive?: boolean }): Promise<void> => {
|
||||
if (options?.recursive) {
|
||||
const prefix = getKey(filepath);
|
||||
await r2DeletePrefix(prefix.endsWith("/") ? prefix : `${prefix}/`);
|
||||
}
|
||||
const key = getKey(filepath);
|
||||
dirMarkerCache.delete(key);
|
||||
};
|
||||
|
||||
const stat = async (filepath: string) => {
|
||||
const key = getKey(filepath);
|
||||
|
||||
if (dirMarkerCache.has(key)) {
|
||||
return createStatResult("dir", 0);
|
||||
}
|
||||
|
||||
const exists = await r2Exists(key);
|
||||
if (exists) {
|
||||
const data = await r2Get(key);
|
||||
return createStatResult("file", data?.length || 0);
|
||||
}
|
||||
|
||||
const prefix = key.endsWith("/") ? key : `${key}/`;
|
||||
const children = await r2List(prefix);
|
||||
if (children.length > 0) {
|
||||
return createStatResult("dir", 0);
|
||||
}
|
||||
|
||||
const err = new Error(`ENOENT: no such file or directory, stat '${filepath}'`) as NodeJS.ErrnoException;
|
||||
err.code = "ENOENT";
|
||||
throw err;
|
||||
};
|
||||
|
||||
const lstat = stat;
|
||||
|
||||
const readlink = async (filepath: string): Promise<string> => {
|
||||
const err = new Error(`ENOENT: no such file or directory, readlink '${filepath}'`) as NodeJS.ErrnoException;
|
||||
err.code = "ENOENT";
|
||||
throw err;
|
||||
};
|
||||
|
||||
const symlink = async (): Promise<void> => {};
|
||||
|
||||
return {
|
||||
promises: {
|
||||
readFile,
|
||||
writeFile,
|
||||
unlink,
|
||||
readdir,
|
||||
mkdir,
|
||||
rmdir,
|
||||
stat,
|
||||
lstat,
|
||||
readlink,
|
||||
symlink,
|
||||
},
|
||||
readFile,
|
||||
writeFile,
|
||||
unlink,
|
||||
readdir,
|
||||
mkdir,
|
||||
rmdir,
|
||||
stat,
|
||||
lstat,
|
||||
readlink,
|
||||
symlink,
|
||||
};
|
||||
}
|
||||
|
||||
export function getRepoPrefix(userId: string, repoName: string): string {
|
||||
return `repos/${userId}/${repoName}`;
|
||||
}
|
||||
116
lib/r2-git-sync.ts
Normal file
116
lib/r2-git-sync.ts
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
import { r2Get, r2Put, r2List, r2Delete } from "./r2";
|
||||
import { getRepoPrefix } from "./r2-fs";
|
||||
import fs from "fs/promises";
|
||||
import path from "path";
|
||||
import os from "os";
|
||||
|
||||
export async function syncR2ToLocal(userId: string, repoName: string): Promise<string> {
|
||||
const repoPrefix = getRepoPrefix(userId, `${repoName}.git`);
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "gitbruv-"));
|
||||
|
||||
const keys = await r2List(repoPrefix);
|
||||
|
||||
for (const key of keys) {
|
||||
const relativePath = key.slice(repoPrefix.length + 1);
|
||||
if (!relativePath) continue;
|
||||
|
||||
const localPath = path.join(tempDir, relativePath);
|
||||
const localDir = path.dirname(localPath);
|
||||
|
||||
await fs.mkdir(localDir, { recursive: true });
|
||||
|
||||
const data = await r2Get(key);
|
||||
if (data) {
|
||||
await fs.writeFile(localPath, data);
|
||||
}
|
||||
}
|
||||
|
||||
await fs.mkdir(path.join(tempDir, "objects"), { recursive: true });
|
||||
await fs.mkdir(path.join(tempDir, "objects/info"), { recursive: true });
|
||||
await fs.mkdir(path.join(tempDir, "objects/pack"), { recursive: true });
|
||||
await fs.mkdir(path.join(tempDir, "refs"), { recursive: true });
|
||||
await fs.mkdir(path.join(tempDir, "refs/heads"), { recursive: true });
|
||||
await fs.mkdir(path.join(tempDir, "refs/tags"), { recursive: true });
|
||||
|
||||
const headPath = path.join(tempDir, "HEAD");
|
||||
try {
|
||||
await fs.access(headPath);
|
||||
} catch {
|
||||
await fs.writeFile(headPath, "ref: refs/heads/main\n");
|
||||
}
|
||||
|
||||
const configPath = path.join(tempDir, "config");
|
||||
try {
|
||||
await fs.access(configPath);
|
||||
} catch {
|
||||
await fs.writeFile(configPath, `[core]
|
||||
\trepositoryformatversion = 0
|
||||
\tfilemode = true
|
||||
\tbare = true
|
||||
`);
|
||||
}
|
||||
|
||||
return tempDir;
|
||||
}
|
||||
|
||||
export async function syncLocalToR2(localDir: string, userId: string, repoName: string): Promise<void> {
|
||||
const repoPrefix = getRepoPrefix(userId, `${repoName}.git`);
|
||||
|
||||
const existingKeys = await r2List(repoPrefix);
|
||||
const existingSet = new Set(existingKeys);
|
||||
const newKeys = new Set<string>();
|
||||
|
||||
async function uploadDir(dirPath: string, r2Prefix: string) {
|
||||
const entries = await fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const localPath = path.join(dirPath, entry.name);
|
||||
const r2Key = `${r2Prefix}/${entry.name}`;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
await uploadDir(localPath, r2Key);
|
||||
} else if (entry.isFile()) {
|
||||
const data = await fs.readFile(localPath);
|
||||
await r2Put(r2Key, data);
|
||||
newKeys.add(r2Key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await uploadDir(localDir, repoPrefix);
|
||||
|
||||
for (const key of existingSet) {
|
||||
if (!newKeys.has(key)) {
|
||||
await r2Delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function cleanupTempDir(tempDir: string): Promise<void> {
|
||||
try {
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
|
||||
export async function withTempRepo<T>(
|
||||
userId: string,
|
||||
repoName: string,
|
||||
operation: (tempDir: string) => Promise<T>,
|
||||
syncBack: boolean = false
|
||||
): Promise<T> {
|
||||
const tempDir = await syncR2ToLocal(userId, repoName);
|
||||
|
||||
try {
|
||||
const result = await operation(tempDir);
|
||||
|
||||
if (syncBack) {
|
||||
await syncLocalToR2(tempDir, userId, repoName);
|
||||
}
|
||||
|
||||
return result;
|
||||
} finally {
|
||||
await cleanupTempDir(tempDir);
|
||||
}
|
||||
}
|
||||
|
||||
98
lib/r2.ts
Normal file
98
lib/r2.ts
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
import { S3Client, GetObjectCommand, PutObjectCommand, DeleteObjectCommand, ListObjectsV2Command, HeadObjectCommand } from "@aws-sdk/client-s3";
|
||||
|
||||
const R2_ACCOUNT_ID = process.env.R2_ACCOUNT_ID!;
|
||||
const R2_ACCESS_KEY_ID = process.env.R2_ACCESS_KEY_ID!;
|
||||
const R2_SECRET_ACCESS_KEY = process.env.R2_SECRET_ACCESS_KEY!;
|
||||
export const R2_BUCKET_NAME = process.env.R2_BUCKET_NAME || "gitbruv-repos";
|
||||
|
||||
export const r2Client = new S3Client({
|
||||
region: "auto",
|
||||
endpoint: `https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
|
||||
credentials: {
|
||||
accessKeyId: R2_ACCESS_KEY_ID,
|
||||
secretAccessKey: R2_SECRET_ACCESS_KEY,
|
||||
},
|
||||
});
|
||||
|
||||
export async function r2Get(key: string): Promise<Buffer | null> {
|
||||
try {
|
||||
const response = await r2Client.send(
|
||||
new GetObjectCommand({
|
||||
Bucket: R2_BUCKET_NAME,
|
||||
Key: key,
|
||||
})
|
||||
);
|
||||
if (!response.Body) return null;
|
||||
const bytes = await response.Body.transformToByteArray();
|
||||
return Buffer.from(bytes);
|
||||
} catch (err: unknown) {
|
||||
if ((err as { name?: string })?.name === "NoSuchKey") return null;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function r2Put(key: string, data: Buffer | Uint8Array | string): Promise<void> {
|
||||
await r2Client.send(
|
||||
new PutObjectCommand({
|
||||
Bucket: R2_BUCKET_NAME,
|
||||
Key: key,
|
||||
Body: data instanceof Buffer ? data : Buffer.from(data),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function r2Delete(key: string): Promise<void> {
|
||||
await r2Client.send(
|
||||
new DeleteObjectCommand({
|
||||
Bucket: R2_BUCKET_NAME,
|
||||
Key: key,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function r2Exists(key: string): Promise<boolean> {
|
||||
try {
|
||||
await r2Client.send(
|
||||
new HeadObjectCommand({
|
||||
Bucket: R2_BUCKET_NAME,
|
||||
Key: key,
|
||||
})
|
||||
);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function r2List(prefix: string): Promise<string[]> {
|
||||
const keys: string[] = [];
|
||||
let continuationToken: string | undefined;
|
||||
|
||||
do {
|
||||
const response = await r2Client.send(
|
||||
new ListObjectsV2Command({
|
||||
Bucket: R2_BUCKET_NAME,
|
||||
Prefix: prefix,
|
||||
ContinuationToken: continuationToken,
|
||||
})
|
||||
);
|
||||
|
||||
if (response.Contents) {
|
||||
for (const obj of response.Contents) {
|
||||
if (obj.Key) keys.push(obj.Key);
|
||||
}
|
||||
}
|
||||
|
||||
continuationToken = response.NextContinuationToken;
|
||||
} while (continuationToken);
|
||||
|
||||
return keys;
|
||||
}
|
||||
|
||||
export async function r2DeletePrefix(prefix: string): Promise<void> {
|
||||
const keys = await r2List(prefix);
|
||||
for (const key of keys) {
|
||||
await r2Delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
9
lib/session.ts
Normal file
9
lib/session.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { auth } from "@/lib/auth";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
export async function getSession() {
|
||||
const session = await auth.api.getSession({
|
||||
headers: await headers(),
|
||||
});
|
||||
return session;
|
||||
}
|
||||
6
lib/utils.ts
Normal file
6
lib/utils.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue