// PodFileBrowser.tsx — Pod 容器文件浏览器组件 // 作者: Logan import { useState, useEffect, useCallback, useRef } from 'react'; import { kubernetesApi } from '@/api'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { Loader2, X, Folder, File, ChevronRight, Download, Upload, RefreshCw, ArrowLeft, HardDrive, } from 'lucide-react'; import type { JsonData } from '@/types/common'; export interface PodFileBrowserProps { open: boolean; onOpenChange: (open: boolean) => void; clusterCode: string; namespace: string; podName: string; containers?: string[]; initialContainer?: string; } interface FileEntry { name: string; isDir: boolean; size?: number; modTime?: string; } export function PodFileBrowser({ open, onOpenChange, clusterCode, namespace, podName, containers = [], initialContainer, }: PodFileBrowserProps) { const [container, setContainer] = useState(initialContainer || containers[0] || ''); const [currentPath, setCurrentPath] = useState('/'); const [entries, setEntries] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); const [preview, setPreview] = useState<{ file: string; content: string } | null>(null); const [uploading, setUploading] = useState(false); const fileInputRef = useRef(null); const workdirDetected = useRef(false); const loadFiles = useCallback(async (path: string) => { setLoading(true); setError(''); setPreview(null); try { const res: JsonData = await kubernetesApi.listPodFiles(clusterCode, namespace, podName, path, container || undefined); // 兼容后端 {files: [...]} 和 {entries: [...]} 两种返回格式 const raw: JsonData[] = res?.entries || res?.files || res?.data?.entries || res?.data?.files || (Array.isArray(res) ? res : []); const list: FileEntry[] = raw.map((it: JsonData) => ({ name: it.name ?? it.Name ?? '', isDir: Boolean(it.isDir ?? it.is_dir ?? it.IsDir ?? it.dir ?? it.directory), size: typeof it.size === 'number' ? it.size : (it.Size ? Number(it.Size) : undefined), modTime: it.modTime ?? it.mod_time ?? it.ModTime ?? it.mtime ?? it.modified, })).filter(e => e.name && e.name !== '.'); setEntries(list); setCurrentPath(path); } catch (e) { setError((e as JsonData).message || '加载文件列表失败'); setEntries([]); } finally { setLoading(false); } }, [clusterCode, namespace, podName, container]); useEffect(() => { if (open) { // 检测容器 WORKDIR 作为初始路径(执行 pwd 命令) const detectWorkdir = async () => { if (workdirDetected.current) { loadFiles(currentPath); return; } setLoading(true); try { const res: JsonData = await kubernetesApi.execPod(clusterCode, namespace, podName, ['pwd'], container || undefined); const stdout = (res?.stdout || res?.data?.stdout || '').trim(); const workdir = stdout && stdout.startsWith('/') ? stdout : '/'; workdirDetected.current = true; setCurrentPath(workdir); loadFiles(workdir); } catch { // pwd 失败则默认 / workdirDetected.current = true; loadFiles('/'); } }; detectWorkdir(); } else { workdirDetected.current = false; } }, [open, container]); const handleClick = (entry: FileEntry) => { if (entry.isDir) { const newPath = currentPath === '/' ? `/${entry.name}` : `${currentPath}/${entry.name}`; loadFiles(newPath); } else { handlePreview(entry.name); } }; const handlePreview = async (fileName: string) => { const filePath = currentPath === '/' ? `/${fileName}` : `${currentPath}/${fileName}`; try { const text = await kubernetesApi.readPodFileText(clusterCode, namespace, podName, filePath, container || undefined); setPreview({ file: fileName, content: text }); } catch (e) { setPreview({ file: fileName, content: `读取失败: ${(e as JsonData).message}` }); } }; const handleDownload = (fileName: string) => { const filePath = currentPath === '/' ? `/${fileName}` : `${currentPath}/${fileName}`; const url = kubernetesApi.buildPodFileDownloadUrl(clusterCode, namespace, podName, filePath, container || undefined); window.open(url, '_blank'); }; const handleUpload = async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; setUploading(true); try { await kubernetesApi.uploadPodFile(clusterCode, namespace, podName, currentPath, file, container || undefined); loadFiles(currentPath); } catch (err) { setError(`上传失败: ${(err as JsonData).message}`); } finally { setUploading(false); if (fileInputRef.current) fileInputRef.current.value = ''; } }; const handleGoUp = () => { if (currentPath === '/') return; const parts = currentPath.split('/').filter(Boolean); parts.pop(); loadFiles(parts.length === 0 ? '/' : `/${parts.join('/')}`); }; const formatSize = (bytes?: number) => { if (bytes == null) return '-'; if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; }; const pathSegments = currentPath.split('/').filter(Boolean); if (!open) return null; return (
onOpenChange(false)}>
e.stopPropagation()} > {/* Header */}
文件: {podName} {namespace}
{containers.length > 0 && ( )}
{/* Breadcrumb + Actions */}
{pathSegments.map((seg, i) => { const path = `/${pathSegments.slice(0, i + 1).join('/')}`; return ( ); })}
{/* Content */}
{/* File list */}
{error &&

{error}

} {loading ? (
) : entries.length === 0 ? (

空目录

) : (
{entries.sort((a, b) => (a.isDir === b.isDir ? a.name.localeCompare(b.name) : a.isDir ? -1 : 1)).map((entry) => (
handleClick(entry)} > {entry.isDir ? ( ) : ( )} {entry.name} {!entry.isDir && ( {formatSize(entry.size)} )} {!entry.isDir && ( )}
))}
)}
{/* Preview */} {preview && (
{preview.file}
                  {preview.content || '(空文件)'}
                
)}
); }