update: remove docker
This commit is contained in:
+97
-85
@@ -1,7 +1,6 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { writeFileSync, mkdirSync, existsSync, rmSync } from 'fs'
|
||||
import { join, extname, basename } from 'path'
|
||||
import { execSync } from 'child_process'
|
||||
import { Octokit } from '@octokit/rest'
|
||||
import { extname, basename } from 'path'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
export const dynamic = 'force-dynamic'
|
||||
@@ -10,8 +9,6 @@ const MODEL_EXTENSIONS = new Set(['.glb', '.gltf'])
|
||||
const TEXTURE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp'])
|
||||
const ALL_ALLOWED_EXTENSIONS = new Set([...MODEL_EXTENSIONS, ...TEXTURE_EXTENSIONS])
|
||||
|
||||
const ASSETS_DIR = join(process.cwd(), 'public', 'assets')
|
||||
|
||||
function sanitizeFilename(name: string): string {
|
||||
return basename(name)
|
||||
.replace(/[^a-zA-Z0-9._-]/g, '_')
|
||||
@@ -19,7 +16,28 @@ function sanitizeFilename(name: string): string {
|
||||
.toLowerCase()
|
||||
}
|
||||
|
||||
async function parseUpload(req: NextRequest): Promise<{ filename: string; savedPath: string; relPath: string; folderName: string }> {
|
||||
function getOctokit(): Octokit {
|
||||
const token = process.env.GITHUB_TOKEN
|
||||
if (!token) throw new Error('GITHUB_TOKEN non configuré')
|
||||
return new Octokit({ auth: token })
|
||||
}
|
||||
|
||||
function parseRepoUrl(): { owner: string; repo: string } {
|
||||
const url = process.env.GIT_REPO_URL
|
||||
if (!url) throw new Error('GIT_REPO_URL non configuré')
|
||||
|
||||
// Support formats: https://github.com/owner/repo.git, owner/repo, git@github.com:owner/repo.git
|
||||
const httpsMatch = url.match(/github\.com\/([^/]+)\/([^/.]+)/)
|
||||
const sshMatch = url.match(/github\.com:([^/]+)\/([^/.]+)/)
|
||||
const shortMatch = url.match(/^([^/]+)\/([^/]+)$/)
|
||||
|
||||
const match = httpsMatch || sshMatch || shortMatch
|
||||
if (!match) throw new Error(`Format GIT_REPO_URL invalide: "${url}"`)
|
||||
|
||||
return { owner: match[1], repo: match[2] }
|
||||
}
|
||||
|
||||
async function parseUpload(req: NextRequest) {
|
||||
const formData = await req.formData()
|
||||
const file = formData.get('file') as File | null
|
||||
const folderName = (formData.get('folderName') as string | null)?.trim() || 'assets'
|
||||
@@ -38,8 +56,7 @@ async function parseUpload(req: NextRequest): Promise<{ filename: string; savedP
|
||||
}
|
||||
|
||||
const safeFolderName = sanitizeFilename(folderName).replace(/[^a-zA-Z0-9-_]/g, '-')
|
||||
const destDir = join(ASSETS_DIR, safeFolderName)
|
||||
|
||||
|
||||
let filename: string
|
||||
if (fileType === 'texture' && textureName) {
|
||||
filename = sanitizeFilename(textureName)
|
||||
@@ -47,82 +64,79 @@ async function parseUpload(req: NextRequest): Promise<{ filename: string; savedP
|
||||
filename = originalSafe
|
||||
}
|
||||
|
||||
mkdirSync(destDir, { recursive: true })
|
||||
|
||||
const savedPath = join(destDir, filename)
|
||||
const buffer = Buffer.from(await file.arrayBuffer())
|
||||
writeFileSync(savedPath, buffer)
|
||||
const content = buffer.toString('base64')
|
||||
const path = `public/assets/${safeFolderName}/${filename}`
|
||||
|
||||
const relPath = join('public', 'assets', safeFolderName, filename)
|
||||
|
||||
return { filename, savedPath, relPath, folderName: safeFolderName }
|
||||
return { filename, content, path, folderName: safeFolderName }
|
||||
}
|
||||
|
||||
function runGitPush(folderName: string): { output: string } {
|
||||
async function pushToGitHub(
|
||||
filePath: string,
|
||||
content: string,
|
||||
folderName: string
|
||||
): Promise<{ commitUrl: string }> {
|
||||
const octokit = getOctokit()
|
||||
const { owner, repo } = parseRepoUrl()
|
||||
const branch = process.env.GIT_BRANCH ?? 'main'
|
||||
const repoUrl = process.env.GIT_REPO_URL
|
||||
|
||||
const execOpts = {
|
||||
cwd: process.cwd(),
|
||||
encoding: 'utf-8' as const,
|
||||
timeout: 120_000,
|
||||
env: {
|
||||
...process.env,
|
||||
GIT_SSH_COMMAND: 'ssh -i /root/.ssh/id_rsa -o StrictHostKeyChecking=no -o UserKnownHostsFile=/root/.ssh/known_hosts',
|
||||
GIT_AUTHOR_NAME: 'Asset Bridge 3D',
|
||||
GIT_AUTHOR_EMAIL: 'deploy@assetbridge.local',
|
||||
GIT_COMMITTER_NAME: 'Asset Bridge 3D',
|
||||
GIT_COMMITTER_EMAIL: 'deploy@assetbridge.local',
|
||||
},
|
||||
}
|
||||
// 1. Get the current commit SHA on the branch
|
||||
const { data: ref } = await octokit.git.getRef({
|
||||
owner,
|
||||
repo,
|
||||
ref: `heads/${branch}`,
|
||||
})
|
||||
const latestCommitSha = ref.object.sha
|
||||
|
||||
try {
|
||||
execSync('git rev-parse --git-dir', { cwd: process.cwd(), stdio: 'ignore' })
|
||||
} catch {
|
||||
execSync('git init && git lfs install', { ...execOpts, stdio: 'pipe' })
|
||||
if (repoUrl) {
|
||||
execSync(`git remote add origin "${repoUrl}"`, { ...execOpts, stdio: 'pipe' })
|
||||
}
|
||||
try {
|
||||
execSync(`git fetch origin ${branch}`, { ...execOpts, stdio: 'pipe', timeout: 30_000 })
|
||||
execSync(`git checkout -b ${branch} --track origin/${branch}`, { ...execOpts, stdio: 'pipe' })
|
||||
} catch {
|
||||
execSync(`git checkout -b ${branch}`, { ...execOpts, stdio: 'pipe' })
|
||||
}
|
||||
}
|
||||
// 2. Get the tree of the latest commit
|
||||
const { data: commit } = await octokit.git.getCommit({
|
||||
owner,
|
||||
repo,
|
||||
commit_sha: latestCommitSha,
|
||||
})
|
||||
|
||||
if (repoUrl) {
|
||||
execSync(`git remote set-url origin "${repoUrl}"`, { ...execOpts, stdio: 'pipe' })
|
||||
}
|
||||
// 3. Create a blob for the file
|
||||
const { data: blob } = await octokit.git.createBlob({
|
||||
owner,
|
||||
repo,
|
||||
content,
|
||||
encoding: 'base64',
|
||||
})
|
||||
|
||||
// 4. Create a new tree with the file added
|
||||
const { data: newTree } = await octokit.git.createTree({
|
||||
owner,
|
||||
repo,
|
||||
base_tree: commit.tree.sha,
|
||||
tree: [
|
||||
{
|
||||
path: filePath,
|
||||
mode: '100644',
|
||||
type: 'blob',
|
||||
sha: blob.sha,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
// 5. Create a new commit
|
||||
const timestamp = new Date().toISOString()
|
||||
let output = ''
|
||||
const { data: newCommit } = await octokit.git.createCommit({
|
||||
owner,
|
||||
repo,
|
||||
message: `Design Update: ${folderName} [${timestamp}]`,
|
||||
tree: newTree.sha,
|
||||
parents: [latestCommitSha],
|
||||
})
|
||||
|
||||
output += execSync(`git fetch origin ${branch}`, execOpts)
|
||||
output += execSync(`git reset --hard origin/${branch}`, execOpts)
|
||||
// 6. Update the branch reference
|
||||
await octokit.git.updateRef({
|
||||
owner,
|
||||
repo,
|
||||
ref: `heads/${branch}`,
|
||||
sha: newCommit.sha,
|
||||
})
|
||||
|
||||
const folderPath = join('public', 'assets', folderName)
|
||||
if (existsSync(folderPath)) {
|
||||
output += execSync(`git add "${folderPath}"`, execOpts)
|
||||
}
|
||||
|
||||
try {
|
||||
output += execSync(`git commit -m "Design Update: ${folderName} [${timestamp}]"`, execOpts)
|
||||
} catch (err) {
|
||||
const msg = [
|
||||
err instanceof Error ? err.message : '',
|
||||
(err as NodeJS.ErrnoException & { stdout?: string })?.stdout ?? '',
|
||||
(err as NodeJS.ErrnoException & { stderr?: string })?.stderr ?? '',
|
||||
].join(' ')
|
||||
if (!msg.includes('nothing to commit') && !msg.includes('nothing added to commit')) {
|
||||
throw err
|
||||
}
|
||||
output += '[rien à committer]\n'
|
||||
}
|
||||
|
||||
output += execSync(`git push origin ${branch}`, execOpts)
|
||||
|
||||
return { output }
|
||||
return { commitUrl: newCommit.html_url }
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
@@ -131,46 +145,44 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
if (!expectedSecret) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Configuration serveur incomplète' },
|
||||
{ success: false, error: 'Configuration serveur incomplète (UPLOAD_SECRET_KEY manquant)' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
if (!secret || secret !== expectedSecret) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Clé d\'authentification invalide' },
|
||||
{ success: false, error: "Clé d'authentification invalide" },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
let filename: string
|
||||
let savedPath: string
|
||||
let relPath: string
|
||||
let content: string
|
||||
let path: string
|
||||
let folderName: string
|
||||
|
||||
try {
|
||||
;({ filename, savedPath, relPath, folderName } = await parseUpload(req))
|
||||
;({ filename, content, path, folderName } = await parseUpload(req))
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Erreur inconnue'
|
||||
return NextResponse.json({ success: false, error: message }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
const { output } = runGitPush(folderName)
|
||||
const { commitUrl } = await pushToGitHub(path, content, folderName)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
filename,
|
||||
message: `"${filename}" ajouté au dossier "${folderName}" et poussé sur Git.`,
|
||||
gitOutput: output,
|
||||
message: `"${filename}" ajouté au dossier "${folderName}" et poussé sur GitHub.`,
|
||||
commitUrl,
|
||||
})
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Erreur git inconnue'
|
||||
const stderr = (err as NodeJS.ErrnoException & { stderr?: string })?.stderr ?? ''
|
||||
|
||||
const message = err instanceof Error ? err.message : 'Erreur GitHub inconnue'
|
||||
return NextResponse.json(
|
||||
{ success: false, error: `Fichier sauvegardé mais git push a échoué: ${message}`, gitError: stderr },
|
||||
{ success: false, error: `Push GitHub échoué: ${message}` },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user