ai_scheduler/pkg/func.go

74 lines
1.6 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package pkg
import (
"fmt"
"os"
"path/filepath"
)
func GetModuleDir() (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", err
}
for {
modPath := filepath.Join(dir, "go.mod")
if _, err := os.Stat(modPath); err == nil {
return dir, nil // 找到 go.mod
}
// 向上查找父目录
parent := filepath.Dir(dir)
if parent == dir {
break // 到达根目录,未找到
}
dir = parent
}
return "", fmt.Errorf("go.mod not found in current directory or parents")
}
// GetCacheDir 用于获取缓存目录路径
// 如果缓存目录不存在,则会自动创建
// 返回值:
// - string: 缓存目录的路径
// - error: 如果获取模块目录失败或创建缓存目录失败,则返回错误信息
func GetCacheDir() (string, error) {
// 获取模块目录
modDir, err := GetModuleDir()
if err != nil {
return "", err
}
// 拼接缓存目录路径
path := fmt.Sprintf("%s/cache", modDir)
// 创建目录包括所有必要的父目录权限设置为0755
err = os.MkdirAll(path, 0755)
if err != nil {
return "", fmt.Errorf("创建目录失败: %w", err)
}
// 返回成功创建的缓存目录路径
return path, nil
}
func GetTmplDir() (string, error) {
modDir, err := GetModuleDir()
if err != nil {
return "", err
}
path := fmt.Sprintf("%s/tmpl", modDir)
err = os.MkdirAll(path, 0755)
if err != nil {
return "", fmt.Errorf("创建目录失败: %w", err)
}
return path, nil
}
func ReverseSliceNew[T any](s []T) []T {
result := make([]T, len(s))
for i := 0; i < len(s); i++ {
result[i] = s[len(s)-1-i]
}
return result
}