feat: add deps envs manager
This commit is contained in:
@@ -0,0 +1,174 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"baihu/internal/services/deps_env"
|
||||
"baihu/internal/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type RuntimeController struct {
|
||||
runtimeService *deps_env.RuntimeService
|
||||
}
|
||||
|
||||
func NewRuntimeController() *RuntimeController {
|
||||
return &RuntimeController{
|
||||
runtimeService: deps_env.NewRuntimeService(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetAvailableRuntimes 获取可用的运行时列表
|
||||
func (rc *RuntimeController) GetAvailableRuntimes(c *gin.Context) {
|
||||
runtimes := rc.runtimeService.GetAvailableRuntimes()
|
||||
utils.Success(c, runtimes)
|
||||
}
|
||||
|
||||
// ListEnvs 列出指定运行时的所有环境
|
||||
func (rc *RuntimeController) ListEnvs(c *gin.Context) {
|
||||
runtimeType := c.Param("type")
|
||||
manager := rc.runtimeService.GetManager(runtimeType)
|
||||
if manager == nil {
|
||||
utils.NotFound(c, "运行时类型不存在")
|
||||
return
|
||||
}
|
||||
|
||||
if !manager.IsAvailable() {
|
||||
utils.BadRequest(c, "运行时不可用")
|
||||
return
|
||||
}
|
||||
|
||||
envs, err := manager.ListEnvs()
|
||||
if err != nil {
|
||||
utils.ServerError(c, "获取环境列表失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
utils.Success(c, envs)
|
||||
}
|
||||
|
||||
// CreateEnv 创建环境
|
||||
func (rc *RuntimeController) CreateEnv(c *gin.Context) {
|
||||
runtimeType := c.Param("type")
|
||||
manager := rc.runtimeService.GetManager(runtimeType)
|
||||
if manager == nil {
|
||||
utils.NotFound(c, "运行时类型不存在")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
if err := manager.CreateEnv(req.Name, req.Version); err != nil {
|
||||
utils.ServerError(c, "创建环境失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
utils.SuccessMsg(c, "环境创建成功")
|
||||
}
|
||||
|
||||
// DeleteEnv 删除环境
|
||||
func (rc *RuntimeController) DeleteEnv(c *gin.Context) {
|
||||
runtimeType := c.Param("type")
|
||||
envName := c.Param("name")
|
||||
|
||||
manager := rc.runtimeService.GetManager(runtimeType)
|
||||
if manager == nil {
|
||||
utils.NotFound(c, "运行时类型不存在")
|
||||
return
|
||||
}
|
||||
|
||||
if envName == "base" {
|
||||
utils.BadRequest(c, "不能删除 base 环境")
|
||||
return
|
||||
}
|
||||
|
||||
if err := manager.DeleteEnv(envName); err != nil {
|
||||
utils.ServerError(c, "删除环境失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
utils.SuccessMsg(c, "环境删除成功")
|
||||
}
|
||||
|
||||
// ListPackages 列出环境中的包
|
||||
func (rc *RuntimeController) ListPackages(c *gin.Context) {
|
||||
runtimeType := c.Param("type")
|
||||
envName := c.Param("name")
|
||||
|
||||
manager := rc.runtimeService.GetManager(runtimeType)
|
||||
if manager == nil {
|
||||
utils.NotFound(c, "运行时类型不存在")
|
||||
return
|
||||
}
|
||||
|
||||
packages, err := manager.ListPackages(envName)
|
||||
if err != nil {
|
||||
utils.ServerError(c, "获取包列表失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
utils.Success(c, packages)
|
||||
}
|
||||
|
||||
// InstallPackage 安装包
|
||||
func (rc *RuntimeController) InstallPackage(c *gin.Context) {
|
||||
runtimeType := c.Param("type")
|
||||
envName := c.Param("name")
|
||||
|
||||
manager := rc.runtimeService.GetManager(runtimeType)
|
||||
if manager == nil {
|
||||
utils.NotFound(c, "运行时类型不存在")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Package string `json:"package" binding:"required"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
if err := manager.InstallPackage(envName, req.Package); err != nil {
|
||||
utils.ServerError(c, "安装包失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
utils.SuccessMsg(c, "包安装成功")
|
||||
}
|
||||
|
||||
// UninstallPackage 卸载包
|
||||
func (rc *RuntimeController) UninstallPackage(c *gin.Context) {
|
||||
runtimeType := c.Param("type")
|
||||
envName := c.Param("name")
|
||||
|
||||
manager := rc.runtimeService.GetManager(runtimeType)
|
||||
if manager == nil {
|
||||
utils.NotFound(c, "运行时类型不存在")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Package string `json:"package" binding:"required"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
utils.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
if err := manager.UninstallPackage(envName, req.Package); err != nil {
|
||||
utils.ServerError(c, "卸载包失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
utils.SuccessMsg(c, "包卸载成功")
|
||||
}
|
||||
@@ -38,6 +38,7 @@ func RegisterControllers() *Controllers {
|
||||
Log: controllers.NewLogController(),
|
||||
Terminal: controllers.NewTerminalController(),
|
||||
Settings: controllers.NewSettingsController(userService, loginLogService),
|
||||
Runtime: controllers.NewRuntimeController(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ type Controllers struct {
|
||||
Log *controllers.LogController
|
||||
Terminal *controllers.TerminalController
|
||||
Settings *controllers.SettingsController
|
||||
Runtime *controllers.RuntimeController
|
||||
}
|
||||
|
||||
func mustSubFS(fsys fs.FS, dir string) fs.FS {
|
||||
@@ -177,6 +178,18 @@ func Setup(c *Controllers) *gin.Engine {
|
||||
settings.GET("/about", c.Settings.GetAbout)
|
||||
settings.GET("/loginlogs", c.Settings.GetLoginLogs)
|
||||
}
|
||||
|
||||
// Runtime routes (依赖管理)
|
||||
runtime := authorized.Group("/runtime")
|
||||
{
|
||||
runtime.GET("", c.Runtime.GetAvailableRuntimes)
|
||||
runtime.GET("/:type/envs", c.Runtime.ListEnvs)
|
||||
runtime.POST("/:type/envs", c.Runtime.CreateEnv)
|
||||
runtime.DELETE("/:type/envs/:name", c.Runtime.DeleteEnv)
|
||||
runtime.GET("/:type/envs/:name/packages", c.Runtime.ListPackages)
|
||||
runtime.POST("/:type/envs/:name/packages", c.Runtime.InstallPackage)
|
||||
runtime.DELETE("/:type/envs/:name/packages", c.Runtime.UninstallPackage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
package deps_env
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"baihu/internal/logger"
|
||||
)
|
||||
|
||||
// CondaManager Conda 运行时管理器
|
||||
type CondaManager struct {
|
||||
condaPath string
|
||||
}
|
||||
|
||||
// NewCondaManager 创建 Conda 管理器
|
||||
func NewCondaManager() *CondaManager {
|
||||
return &CondaManager{}
|
||||
}
|
||||
|
||||
// GetType 获取运行时类型
|
||||
func (cm *CondaManager) GetType() string {
|
||||
return "conda"
|
||||
}
|
||||
|
||||
// IsAvailable 检查 Conda 是否可用
|
||||
func (cm *CondaManager) IsAvailable() bool {
|
||||
path, err := cm.findCondaPath()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
cm.condaPath = path
|
||||
return true
|
||||
}
|
||||
|
||||
// findCondaPath 查找 conda 可执行文件路径
|
||||
func (cm *CondaManager) findCondaPath() (string, error) {
|
||||
// 尝试常见的 conda 路径
|
||||
paths := []string{"conda", "micromamba", "/opt/conda/bin/conda", "/root/miniconda3/bin/conda", "/root/anaconda3/bin/conda"}
|
||||
for _, p := range paths {
|
||||
if path, err := exec.LookPath(p); err == nil {
|
||||
return path, nil
|
||||
}
|
||||
}
|
||||
return "", exec.ErrNotFound
|
||||
}
|
||||
|
||||
// getCondaPath 获取 conda 路径
|
||||
func (cm *CondaManager) getCondaPath() string {
|
||||
if cm.condaPath == "" {
|
||||
cm.findCondaPath()
|
||||
}
|
||||
return cm.condaPath
|
||||
}
|
||||
|
||||
// condaEnvJSON conda env list --json 的输出结构
|
||||
type condaEnvJSON struct {
|
||||
Envs []string `json:"envs"`
|
||||
}
|
||||
|
||||
// ListEnvs 列出所有 Conda 环境
|
||||
func (cm *CondaManager) ListEnvs() ([]RuntimeEnv, error) {
|
||||
condaPath := cm.getCondaPath()
|
||||
if condaPath == "" {
|
||||
return nil, exec.ErrNotFound
|
||||
}
|
||||
|
||||
cmd := exec.Command(condaPath, "env", "list", "--json")
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
logger.Errorf("Failed to list conda envs: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var envJSON condaEnvJSON
|
||||
if err := json.Unmarshal(output, &envJSON); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var envs []RuntimeEnv
|
||||
for _, envPath := range envJSON.Envs {
|
||||
name := extractEnvName(envPath)
|
||||
// 过滤以 . 开头的环境
|
||||
if strings.HasPrefix(name, ".") {
|
||||
continue
|
||||
}
|
||||
envs = append(envs, RuntimeEnv{
|
||||
Name: name,
|
||||
Path: envPath,
|
||||
Active: false,
|
||||
})
|
||||
}
|
||||
|
||||
return envs, nil
|
||||
}
|
||||
|
||||
// extractEnvName 从路径中提取环境名称
|
||||
func extractEnvName(envPath string) string {
|
||||
parts := strings.Split(envPath, "/")
|
||||
if len(parts) > 0 {
|
||||
name := parts[len(parts)-1]
|
||||
// 如果是 base 环境,路径可能是 /opt/conda 这样的
|
||||
if name == "conda" || name == "miniconda3" || name == "anaconda3" {
|
||||
return "base"
|
||||
}
|
||||
return name
|
||||
}
|
||||
return envPath
|
||||
}
|
||||
|
||||
// CreateEnv 创建 Conda 环境
|
||||
func (cm *CondaManager) CreateEnv(name string, version string) error {
|
||||
condaPath := cm.getCondaPath()
|
||||
if condaPath == "" {
|
||||
return exec.ErrNotFound
|
||||
}
|
||||
|
||||
args := []string{"create", "-n", name, "-y"}
|
||||
if version != "" {
|
||||
args = append(args, "python="+version)
|
||||
}
|
||||
|
||||
cmd := exec.Command(condaPath, args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
logger.Errorf("Failed to create conda env: %v, output: %s", err, string(output))
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteEnv 删除 Conda 环境
|
||||
func (cm *CondaManager) DeleteEnv(name string) error {
|
||||
condaPath := cm.getCondaPath()
|
||||
if condaPath == "" {
|
||||
return exec.ErrNotFound
|
||||
}
|
||||
|
||||
if name == "base" {
|
||||
return nil // 不允许删除 base 环境
|
||||
}
|
||||
|
||||
cmd := exec.Command(condaPath, "env", "remove", "-n", name, "-y")
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
logger.Errorf("Failed to delete conda env: %v, output: %s", err, string(output))
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListPackages 列出环境中的包
|
||||
func (cm *CondaManager) ListPackages(envName string) ([]RuntimePackage, error) {
|
||||
condaPath := cm.getCondaPath()
|
||||
if condaPath == "" {
|
||||
return nil, exec.ErrNotFound
|
||||
}
|
||||
|
||||
args := []string{"list"}
|
||||
if envName != "" && envName != "base" {
|
||||
args = append(args, "-n", envName)
|
||||
}
|
||||
|
||||
cmd := exec.Command(condaPath, args...)
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
logger.Errorf("Failed to list packages: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return parseCondaList(string(output)), nil
|
||||
}
|
||||
|
||||
// parseCondaList 解析 conda list 输出
|
||||
func parseCondaList(output string) []RuntimePackage {
|
||||
var packages []RuntimePackage
|
||||
scanner := bufio.NewScanner(strings.NewReader(output))
|
||||
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
// 跳过注释和空行
|
||||
if strings.HasPrefix(line, "#") || strings.TrimSpace(line) == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) >= 2 {
|
||||
name := fields[0]
|
||||
|
||||
pkg := RuntimePackage{
|
||||
Name: name,
|
||||
Version: fields[1],
|
||||
}
|
||||
if len(fields) >= 4 {
|
||||
pkg.Channel = fields[3]
|
||||
}
|
||||
packages = append(packages, pkg)
|
||||
}
|
||||
}
|
||||
|
||||
return packages
|
||||
}
|
||||
|
||||
// InstallPackage 安装包
|
||||
func (cm *CondaManager) InstallPackage(envName string, packageName string) error {
|
||||
condaPath := cm.getCondaPath()
|
||||
if condaPath == "" {
|
||||
return exec.ErrNotFound
|
||||
}
|
||||
|
||||
args := []string{"install", "-y"}
|
||||
if envName != "" && envName != "base" {
|
||||
args = append(args, "-n", envName)
|
||||
}
|
||||
args = append(args, packageName)
|
||||
|
||||
cmd := exec.Command(condaPath, args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
logger.Errorf("Failed to install package: %v, output: %s", err, string(output))
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UninstallPackage 卸载包
|
||||
func (cm *CondaManager) UninstallPackage(envName string, packageName string) error {
|
||||
condaPath := cm.getCondaPath()
|
||||
if condaPath == "" {
|
||||
return exec.ErrNotFound
|
||||
}
|
||||
|
||||
args := []string{"remove", "-y"}
|
||||
if envName != "" && envName != "base" {
|
||||
args = append(args, "-n", envName)
|
||||
}
|
||||
args = append(args, packageName)
|
||||
|
||||
cmd := exec.Command(condaPath, args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
logger.Errorf("Failed to uninstall package: %v, output: %s", err, string(output))
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package deps_env
|
||||
|
||||
// RuntimeEnv 运行时环境信息
|
||||
type RuntimeEnv struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
Version string `json:"version"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
// RuntimePackage 包信息
|
||||
type RuntimePackage struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
Channel string `json:"channel,omitempty"`
|
||||
}
|
||||
|
||||
// RuntimeManager 运行时管理器接口
|
||||
type RuntimeManager interface {
|
||||
// GetType 获取运行时类型
|
||||
GetType() string
|
||||
// IsAvailable 检查运行时是否可用
|
||||
IsAvailable() bool
|
||||
// ListEnvs 列出所有环境
|
||||
ListEnvs() ([]RuntimeEnv, error)
|
||||
// CreateEnv 创建环境
|
||||
CreateEnv(name string, version string) error
|
||||
// DeleteEnv 删除环境
|
||||
DeleteEnv(name string) error
|
||||
// ListPackages 列出环境中的包
|
||||
ListPackages(envName string) ([]RuntimePackage, error)
|
||||
// InstallPackage 安装包
|
||||
InstallPackage(envName string, packageName string) error
|
||||
// UninstallPackage 卸载包
|
||||
UninstallPackage(envName string, packageName string) error
|
||||
}
|
||||
|
||||
// RuntimeService 运行时服务
|
||||
type RuntimeService struct {
|
||||
managers map[string]RuntimeManager
|
||||
}
|
||||
|
||||
// NewRuntimeService 创建运行时服务
|
||||
func NewRuntimeService() *RuntimeService {
|
||||
rs := &RuntimeService{
|
||||
managers: make(map[string]RuntimeManager),
|
||||
}
|
||||
// 注册 Conda 管理器
|
||||
rs.RegisterManager(NewCondaManager())
|
||||
return rs
|
||||
}
|
||||
|
||||
// RegisterManager 注册运行时管理器
|
||||
func (rs *RuntimeService) RegisterManager(manager RuntimeManager) {
|
||||
rs.managers[manager.GetType()] = manager
|
||||
}
|
||||
|
||||
// GetManager 获取指定类型的管理器
|
||||
func (rs *RuntimeService) GetManager(runtimeType string) RuntimeManager {
|
||||
return rs.managers[runtimeType]
|
||||
}
|
||||
|
||||
// GetAvailableRuntimes 获取可用的运行时列表
|
||||
func (rs *RuntimeService) GetAvailableRuntimes() []string {
|
||||
var available []string
|
||||
for name, manager := range rs.managers {
|
||||
if manager.IsAvailable() {
|
||||
available = append(available, name)
|
||||
}
|
||||
}
|
||||
return available
|
||||
}
|
||||
@@ -170,6 +170,20 @@ export const api = {
|
||||
}
|
||||
if (json.code !== 200) throw new Error(json.msg || '上传失败')
|
||||
}
|
||||
},
|
||||
runtime: {
|
||||
getAvailable: () => request<string[]>('/runtime'),
|
||||
listEnvs: (type: string) => request<RuntimeEnv[]>(`/runtime/${type}/envs`),
|
||||
createEnv: (type: string, name: string, version?: string) =>
|
||||
request(`/runtime/${type}/envs`, { method: 'POST', body: JSON.stringify({ name, version }) }),
|
||||
deleteEnv: (type: string, name: string) =>
|
||||
request(`/runtime/${type}/envs/${name}`, { method: 'DELETE' }),
|
||||
listPackages: (type: string, envName: string) =>
|
||||
request<RuntimePackage[]>(`/runtime/${type}/envs/${envName}/packages`),
|
||||
installPackage: (type: string, envName: string, packageName: string) =>
|
||||
request(`/runtime/${type}/envs/${envName}/packages`, { method: 'POST', body: JSON.stringify({ package: packageName }) }),
|
||||
uninstallPackage: (type: string, envName: string, packageName: string) =>
|
||||
request(`/runtime/${type}/envs/${envName}/packages`, { method: 'DELETE', body: JSON.stringify({ package: packageName }) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -305,3 +319,16 @@ export interface TaskStatsItem {
|
||||
task_name: string
|
||||
count: number
|
||||
}
|
||||
|
||||
export interface RuntimeEnv {
|
||||
name: string
|
||||
path: string
|
||||
version: string
|
||||
active: boolean
|
||||
}
|
||||
|
||||
export interface RuntimePackage {
|
||||
name: string
|
||||
version: string
|
||||
channel?: string
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { RouterLink, RouterView, useRoute } from 'vue-router'
|
||||
import { LayoutDashboard, ListTodo, FileCode, Settings, LogOut, ScrollText, Terminal, Variable, KeyRound } from 'lucide-vue-next'
|
||||
import { LayoutDashboard, ListTodo, FileCode, Settings, LogOut, ScrollText, Terminal, Variable, KeyRound, Package } from 'lucide-vue-next'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import ThemeToggle from '@/components/ThemeToggle.vue'
|
||||
import { api } from '@/api'
|
||||
@@ -17,6 +17,7 @@ const navItems = [
|
||||
{ to: '/editor', icon: FileCode, label: '脚本编辑', exact: false },
|
||||
{ to: '/history', icon: ScrollText, label: '执行历史', exact: true },
|
||||
{ to: '/environments', icon: Variable, label: '环境变量', exact: true },
|
||||
{ to: '/dependencies', icon: Package, label: '依赖管理', exact: true },
|
||||
{ to: '/terminal', icon: Terminal, label: '终端命令', exact: true },
|
||||
{ to: '/loginlogs', icon: KeyRound, label: '登录日志', exact: true },
|
||||
{ to: '/settings', icon: Settings, label: '系统设置', exact: true },
|
||||
|
||||
@@ -19,6 +19,7 @@ const router = createRouter({
|
||||
{ path: 'tasks', name: 'tasks', component: () => import('@/views/tasks/Tasks.vue') },
|
||||
{ path: 'editor/:path(.*)?', name: 'editor', component: () => import('@/views/editor/Editor.vue') },
|
||||
{ path: 'environments', name: 'environments', component: () => import('@/views/environments/Environments.vue') },
|
||||
{ path: 'dependencies', name: 'dependencies', component: () => import('@/views/dependencies/Dependencies.vue') },
|
||||
{ path: 'history', name: 'history', component: () => import('@/views/history/History.vue') },
|
||||
{ path: 'loginlogs', name: 'loginlogs', component: () => import('@/views/loginlogs/LoginLogs.vue') },
|
||||
{ path: 'terminal', name: 'terminal', component: () => import('@/views/terminal/Terminal.vue') },
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, computed } from 'vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { Plus, Trash2, Package, Search, RefreshCw, Loader2 } from 'lucide-vue-next'
|
||||
import { api, type RuntimeEnv, type RuntimePackage } from '@/api'
|
||||
import { toast } from 'vue-sonner'
|
||||
|
||||
const availableRuntimes = ref<string[]>([])
|
||||
const activeRuntime = ref('conda')
|
||||
const envs = ref<RuntimeEnv[]>([])
|
||||
const selectedEnv = ref<RuntimeEnv | null>(null)
|
||||
const packages = ref<RuntimePackage[]>([])
|
||||
const loading = ref(false)
|
||||
const packagesLoading = ref(false)
|
||||
|
||||
// 创建环境
|
||||
const showCreateDialog = ref(false)
|
||||
const newEnvName = ref('')
|
||||
const newEnvVersion = ref('')
|
||||
const creating = ref(false)
|
||||
|
||||
// 删除环境
|
||||
const showDeleteDialog = ref(false)
|
||||
const envToDelete = ref<RuntimeEnv | null>(null)
|
||||
|
||||
// 安装包
|
||||
const showInstallDialog = ref(false)
|
||||
const packageToInstall = ref('')
|
||||
const installing = ref(false)
|
||||
|
||||
// 搜索
|
||||
const packageSearch = ref('')
|
||||
|
||||
const filteredPackages = computed(() => {
|
||||
if (!packageSearch.value) return packages.value
|
||||
const q = packageSearch.value.toLowerCase()
|
||||
return packages.value.filter(p => p.name.toLowerCase().includes(q))
|
||||
})
|
||||
|
||||
async function loadRuntimes() {
|
||||
try {
|
||||
availableRuntimes.value = await api.runtime.getAvailable()
|
||||
if (availableRuntimes.value.length > 0 && !availableRuntimes.value.includes(activeRuntime.value)) {
|
||||
activeRuntime.value = availableRuntimes.value[0] ?? 'conda'
|
||||
}
|
||||
} catch {
|
||||
availableRuntimes.value = []
|
||||
}
|
||||
}
|
||||
|
||||
async function loadEnvs() {
|
||||
if (!activeRuntime.value) return
|
||||
loading.value = true
|
||||
try {
|
||||
envs.value = await api.runtime.listEnvs(activeRuntime.value)
|
||||
if (envs.value.length > 0 && !selectedEnv.value) {
|
||||
const firstEnv = envs.value[0]
|
||||
if (firstEnv) selectEnv(firstEnv)
|
||||
}
|
||||
} catch {
|
||||
toast.error('加载环境列表失败')
|
||||
envs.value = []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function selectEnv(env: RuntimeEnv) {
|
||||
selectedEnv.value = env
|
||||
await loadPackages()
|
||||
}
|
||||
|
||||
async function loadPackages() {
|
||||
if (!selectedEnv.value) return
|
||||
packagesLoading.value = true
|
||||
try {
|
||||
packages.value = await api.runtime.listPackages(activeRuntime.value, selectedEnv.value.name)
|
||||
} catch {
|
||||
toast.error('加载包列表失败')
|
||||
packages.value = []
|
||||
} finally {
|
||||
packagesLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openCreateDialog() {
|
||||
newEnvName.value = ''
|
||||
newEnvVersion.value = ''
|
||||
showCreateDialog.value = true
|
||||
}
|
||||
|
||||
async function createEnv() {
|
||||
if (!newEnvName.value.trim()) {
|
||||
toast.error('请输入环境名称')
|
||||
return
|
||||
}
|
||||
creating.value = true
|
||||
try {
|
||||
await api.runtime.createEnv(activeRuntime.value, newEnvName.value.trim(), newEnvVersion.value.trim() || undefined)
|
||||
toast.success('环境创建成功')
|
||||
showCreateDialog.value = false
|
||||
await loadEnvs()
|
||||
} catch (e: unknown) {
|
||||
toast.error((e as Error).message || '创建失败')
|
||||
} finally {
|
||||
creating.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function confirmDeleteEnv(env: RuntimeEnv) {
|
||||
if (env.name === 'base') {
|
||||
toast.error('不能删除 base 环境')
|
||||
return
|
||||
}
|
||||
envToDelete.value = env
|
||||
showDeleteDialog.value = true
|
||||
}
|
||||
|
||||
async function deleteEnv() {
|
||||
if (!envToDelete.value) return
|
||||
try {
|
||||
await api.runtime.deleteEnv(activeRuntime.value, envToDelete.value.name)
|
||||
toast.success('环境删除成功')
|
||||
if (selectedEnv.value?.name === envToDelete.value.name) {
|
||||
selectedEnv.value = null
|
||||
packages.value = []
|
||||
}
|
||||
await loadEnvs()
|
||||
} catch (e: unknown) {
|
||||
toast.error((e as Error).message || '删除失败')
|
||||
} finally {
|
||||
showDeleteDialog.value = false
|
||||
envToDelete.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function openInstallDialog() {
|
||||
packageToInstall.value = ''
|
||||
showInstallDialog.value = true
|
||||
}
|
||||
|
||||
async function installPackage() {
|
||||
if (!packageToInstall.value.trim() || !selectedEnv.value) return
|
||||
installing.value = true
|
||||
try {
|
||||
await api.runtime.installPackage(activeRuntime.value, selectedEnv.value.name, packageToInstall.value.trim())
|
||||
toast.success('包安装成功')
|
||||
showInstallDialog.value = false
|
||||
await loadPackages()
|
||||
} catch (e: unknown) {
|
||||
toast.error((e as Error).message || '安装失败')
|
||||
} finally {
|
||||
installing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function uninstallPackage(pkg: RuntimePackage) {
|
||||
if (!selectedEnv.value) return
|
||||
try {
|
||||
await api.runtime.uninstallPackage(activeRuntime.value, selectedEnv.value.name, pkg.name)
|
||||
toast.success('包卸载成功')
|
||||
await loadPackages()
|
||||
} catch (e: unknown) {
|
||||
toast.error((e as Error).message || '卸载失败')
|
||||
}
|
||||
}
|
||||
|
||||
function getRuntimeLabel(type: string) {
|
||||
const labels: Record<string, string> = { conda: 'Conda', node: 'Node.js' }
|
||||
return labels[type] || type
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadRuntimes()
|
||||
if (availableRuntimes.value.includes('conda')) {
|
||||
activeRuntime.value = 'conda'
|
||||
await loadEnvs()
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold tracking-tight">依赖管理</h2>
|
||||
<p class="text-muted-foreground">管理运行时环境和依赖包</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="availableRuntimes.length === 0" class="text-center py-8 text-muted-foreground">
|
||||
<Package class="h-10 w-10 mx-auto mb-3 opacity-50" />
|
||||
<p>未检测到可用的运行时环境</p>
|
||||
<p class="text-sm mt-1">请确保已安装 Conda 或其他支持的运行时</p>
|
||||
</div>
|
||||
|
||||
<Tabs v-else v-model="activeRuntime" @update:model-value="loadEnvs">
|
||||
<TabsList>
|
||||
<TabsTrigger v-for="rt in availableRuntimes" :key="rt" :value="rt">
|
||||
{{ getRuntimeLabel(rt) }}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent :value="activeRuntime" class="mt-4">
|
||||
<div class="flex gap-4 min-h-[480px]">
|
||||
<!-- 环境列表 -->
|
||||
<div class="w-52 shrink-0 border rounded-lg p-3 h-fit">
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<span class="text-sm font-medium">虚拟环境</span>
|
||||
<Button variant="ghost" size="icon" class="h-6 w-6" @click="openCreateDialog">
|
||||
<Plus class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
<div class="space-y-0.5 min-h-[60px]">
|
||||
<div v-if="loading" class="text-sm text-muted-foreground text-center py-3">
|
||||
<Loader2 class="h-4 w-4 animate-spin mx-auto" />
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
v-for="env in envs"
|
||||
:key="env.name"
|
||||
:class="[
|
||||
'group flex items-center justify-between px-2 py-1.5 rounded cursor-pointer text-sm',
|
||||
selectedEnv?.name === env.name ? 'bg-accent text-accent-foreground' : 'hover:bg-muted'
|
||||
]"
|
||||
@click="selectEnv(env)"
|
||||
>
|
||||
<span class="truncate text-xs">{{ env.name }}</span>
|
||||
<Button
|
||||
v-if="env.name !== 'base'"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="h-5 w-5 shrink-0 opacity-0 group-hover:opacity-100"
|
||||
@click.stop="confirmDeleteEnv(env)"
|
||||
>
|
||||
<Trash2 class="h-3 w-3 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 包列表 -->
|
||||
<div class="flex-1 border rounded-lg flex flex-col h-[480px]">
|
||||
<div class="flex items-center justify-between px-3 py-2 border-b bg-muted/30 shrink-0">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-sm font-medium">{{ selectedEnv?.name || '选择环境' }}</span>
|
||||
<Badge v-if="selectedEnv" variant="secondary" class="text-xs">{{ packages.length }} 包</Badge>
|
||||
</div>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<div class="relative">
|
||||
<Search class="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Input v-model="packageSearch" placeholder="搜索..." class="h-7 pl-7 w-36 text-xs" />
|
||||
</div>
|
||||
<Button variant="ghost" size="icon" class="h-7 w-7" @click="loadPackages" :disabled="!selectedEnv">
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button size="sm" class="h-7 text-xs" @click="openInstallDialog" :disabled="!selectedEnv">
|
||||
<Plus class="h-3.5 w-3.5 mr-1" /> 安装
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-1 overflow-y-auto">
|
||||
<div v-if="!selectedEnv" class="text-center py-8 text-muted-foreground text-sm">
|
||||
请选择一个环境
|
||||
</div>
|
||||
<div v-else-if="packagesLoading" class="text-center py-8">
|
||||
<Loader2 class="h-5 w-5 animate-spin mx-auto text-muted-foreground" />
|
||||
</div>
|
||||
<div v-else-if="filteredPackages.length === 0" class="text-center py-8 text-muted-foreground text-sm">
|
||||
{{ packageSearch ? '无匹配结果' : '暂无包' }}
|
||||
</div>
|
||||
<table v-else class="w-full text-sm">
|
||||
<thead class="bg-muted/50 sticky top-0">
|
||||
<tr class="text-xs text-muted-foreground">
|
||||
<th class="text-left px-3 py-1.5 font-medium">包名</th>
|
||||
<th class="text-left px-3 py-1.5 font-medium">版本</th>
|
||||
<th class="text-left px-3 py-1.5 font-medium">来源</th>
|
||||
<th class="text-center px-3 py-1.5 font-medium w-16">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y">
|
||||
<tr v-for="pkg in filteredPackages" :key="pkg.name" class="hover:bg-muted/50">
|
||||
<td class="px-3 py-1.5 text-xs font-mono">{{ pkg.name }}</td>
|
||||
<td class="px-3 py-1.5 text-xs text-muted-foreground">{{ pkg.version }}</td>
|
||||
<td class="px-3 py-1.5 text-xs text-muted-foreground">{{ pkg.channel || '-' }}</td>
|
||||
<td class="px-3 py-1.5 text-center">
|
||||
<Button variant="ghost" size="icon" class="h-6 w-6 text-destructive" @click="uninstallPackage(pkg)">
|
||||
<Trash2 class="h-3 w-3" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<!-- 创建环境对话框 -->
|
||||
<Dialog v-model:open="showCreateDialog">
|
||||
<DialogContent class="sm:max-w-[380px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>创建虚拟环境</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div class="grid gap-3 py-3">
|
||||
<div class="grid grid-cols-4 items-center gap-3">
|
||||
<Label class="text-right text-sm">环境名称</Label>
|
||||
<Input v-model="newEnvName" placeholder="myenv" class="col-span-3 h-8" />
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-center gap-3">
|
||||
<Label class="text-right text-sm">Python</Label>
|
||||
<Input v-model="newEnvVersion" placeholder="3.10 (可选)" class="col-span-3 h-8" />
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" @click="showCreateDialog = false">取消</Button>
|
||||
<Button size="sm" @click="createEnv" :disabled="creating">
|
||||
<Loader2 v-if="creating" class="h-3.5 w-3.5 mr-1.5 animate-spin" />
|
||||
创建
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- 删除环境确认 -->
|
||||
<AlertDialog v-model:open="showDeleteDialog">
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确认删除</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
确定要删除环境 "{{ envToDelete?.name }}" 吗?此操作无法撤销。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||
<AlertDialogAction class="bg-destructive text-white hover:bg-destructive/90" @click="deleteEnv">删除</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<!-- 安装包对话框 -->
|
||||
<Dialog v-model:open="showInstallDialog">
|
||||
<DialogContent class="sm:max-w-[380px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>安装包</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div class="grid gap-3 py-3">
|
||||
<div class="grid grid-cols-4 items-center gap-3">
|
||||
<Label class="text-right text-sm">包名</Label>
|
||||
<Input v-model="packageToInstall" placeholder="numpy" class="col-span-3 h-8" />
|
||||
</div>
|
||||
<p class="text-xs text-muted-foreground ml-auto col-span-4">
|
||||
支持版本指定: numpy==1.24.0
|
||||
</p>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" @click="showInstallDialog = false">取消</Button>
|
||||
<Button size="sm" @click="installPackage" :disabled="installing">
|
||||
<Loader2 v-if="installing" class="h-3.5 w-3.5 mr-1.5 animate-spin" />
|
||||
安装
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
</template>
|
||||
Reference in New Issue
Block a user