Fix: persist project folder hierarchy
This commit is contained in:
@@ -10,6 +10,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
@@ -42,6 +43,8 @@ const (
|
||||
var (
|
||||
ErrInstallationNotConfigured = errors.New("bootstrap installation step has not been completed")
|
||||
ErrAdminNotConfigured = errors.New("bootstrap admin step has not been completed")
|
||||
ErrProjectNotFound = errors.New("project not found")
|
||||
ErrProjectFolderNotFound = errors.New("project folder not found")
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
@@ -177,6 +180,30 @@ type namedRecord struct {
|
||||
Slug string `json:"slug"`
|
||||
}
|
||||
|
||||
type ProjectHierarchyFolderRecord struct {
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
Children []ProjectHierarchyFolderRecord `json:"children"`
|
||||
}
|
||||
|
||||
type CreateProjectFolderInput struct {
|
||||
ProjectID string
|
||||
ParentFolderID string
|
||||
Name string
|
||||
}
|
||||
|
||||
type CreateProjectFolderResult struct {
|
||||
ProjectID string `json:"projectId"`
|
||||
CreatedFolder ProjectHierarchyFolderRecord `json:"createdFolder"`
|
||||
Folders []ProjectHierarchyFolderRecord `json:"folders"`
|
||||
}
|
||||
|
||||
type projectHierarchyFolderRow struct {
|
||||
Path string
|
||||
ParentPath string
|
||||
Label string
|
||||
}
|
||||
|
||||
func NewService(db *database.DB, posixRoot string) *Service {
|
||||
return &Service{db: db, posixRoot: strings.TrimSpace(posixRoot)}
|
||||
}
|
||||
@@ -794,6 +821,92 @@ func (service *Service) listProjects(ctx context.Context) ([]ProjectRecord, erro
|
||||
return records, rows.Err()
|
||||
}
|
||||
|
||||
func (service *Service) loadProjectByID(ctx context.Context, projectID string) (*ProjectRecord, error) {
|
||||
var record ProjectRecord
|
||||
err := service.db.Pool.QueryRow(ctx, `
|
||||
SELECT id::text, organization_id::text, department_id::text, team_id::text, name, slug
|
||||
FROM projects
|
||||
WHERE id = $1::uuid
|
||||
LIMIT 1;
|
||||
`, projectID).Scan(&record.ID, &record.OrganizationID, &record.DepartmentID, &record.TeamID, &record.Name, &record.Slug)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrProjectNotFound
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
func (service *Service) GetProjectHierarchyFolders(ctx context.Context, projectID string) ([]ProjectHierarchyFolderRecord, error) {
|
||||
project, err := service.loadProjectByID(ctx, projectID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := service.db.Pool.Query(ctx, `
|
||||
SELECT path, COALESCE(parent_path, ''), COALESCE(resource_name, '')
|
||||
FROM posix_nodes
|
||||
WHERE node_kind = 'directory'::posix_node_kind
|
||||
AND logical_type = 'hierarchy_folder'
|
||||
AND project_slug = $1
|
||||
ORDER BY depth ASC, path ASC;
|
||||
`, project.Slug)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var folderRows []projectHierarchyFolderRow
|
||||
for rows.Next() {
|
||||
var row projectHierarchyFolderRow
|
||||
if err := rows.Scan(&row.Path, &row.ParentPath, &row.Label); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
folderRows = append(folderRows, row)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return buildProjectHierarchyFolderTree(folderRows, projectHierarchyRootPath(project.Slug)), nil
|
||||
}
|
||||
|
||||
func (service *Service) CreateProjectFolder(ctx context.Context, input CreateProjectFolderInput) (CreateProjectFolderResult, error) {
|
||||
project, err := service.loadProjectByID(ctx, strings.TrimSpace(input.ProjectID))
|
||||
if err != nil {
|
||||
return CreateProjectFolderResult{}, err
|
||||
}
|
||||
|
||||
createdPath, _, err := service.createProjectHierarchyFolderOnDisk(project.Slug, strings.TrimSpace(input.ParentFolderID), input.Name)
|
||||
if err != nil {
|
||||
return CreateProjectFolderResult{}, err
|
||||
}
|
||||
|
||||
if err := posixproj.NewProjector(service.db, service.posixRoot).Rebuild(ctx); err != nil {
|
||||
return CreateProjectFolderResult{}, fmt.Errorf("rebuild POSIX projection: %w", err)
|
||||
}
|
||||
|
||||
folders, err := service.GetProjectHierarchyFolders(ctx, project.ID)
|
||||
if err != nil {
|
||||
return CreateProjectFolderResult{}, err
|
||||
}
|
||||
|
||||
createdFolder, ok := findProjectHierarchyFolder(folders, createdPath)
|
||||
if !ok {
|
||||
return CreateProjectFolderResult{}, fmt.Errorf("created project folder missing from projection")
|
||||
}
|
||||
|
||||
return CreateProjectFolderResult{
|
||||
ProjectID: project.ID,
|
||||
CreatedFolder: createdFolder,
|
||||
Folders: folders,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (service *Service) listWorkspaces(ctx context.Context) ([]WorkspaceRecord, error) {
|
||||
rows, err := service.db.Pool.Query(ctx, `
|
||||
SELECT id::text, organization_id::text, name, slug, kind::text, department_id::text, team_id::text, project_id::text
|
||||
@@ -1069,6 +1182,194 @@ func (service *Service) ensureBootstrapPOSIXSkeleton(
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *Service) createProjectHierarchyFolderOnDisk(projectSlug, parentFolderID, name string) (string, string, error) {
|
||||
rootPath := strings.TrimSpace(service.posixRoot)
|
||||
if rootPath == "" {
|
||||
return "", "", fmt.Errorf("POSIX root is not configured")
|
||||
}
|
||||
|
||||
trimmedName := strings.TrimSpace(name)
|
||||
if trimmedName == "" {
|
||||
return "", "", fmt.Errorf("folder name is required")
|
||||
}
|
||||
|
||||
projectRoot := filepath.Join(rootPath, "projects", slugDir("project", projectSlug))
|
||||
childrenRoot := filepath.Join(projectRoot, "children")
|
||||
parentDir := childrenRoot
|
||||
containerProjectionPath := projectHierarchyRootPath(projectSlug)
|
||||
|
||||
if strings.TrimSpace(parentFolderID) != "" {
|
||||
containerProjectionPath = filepath.ToSlash(filepath.Join(strings.TrimSpace(parentFolderID), "children"))
|
||||
parentDir = filepath.Join(rootPath, filepath.FromSlash(containerProjectionPath))
|
||||
info, err := os.Stat(parentDir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return "", "", ErrProjectFolderNotFound
|
||||
}
|
||||
return "", "", fmt.Errorf("stat parent project folder: %w", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return "", "", ErrProjectFolderNotFound
|
||||
}
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(parentDir, 0o755); err != nil {
|
||||
return "", "", fmt.Errorf("create parent project folder path: %w", err)
|
||||
}
|
||||
|
||||
baseSlug := normalizePOSIXSlug(trimmedName)
|
||||
folderName := slugDir("folder", baseSlug)
|
||||
folderDir := filepath.Join(parentDir, folderName)
|
||||
folderSlug := baseSlug
|
||||
|
||||
for attempt := 2; ; attempt += 1 {
|
||||
if _, err := os.Stat(folderDir); os.IsNotExist(err) {
|
||||
break
|
||||
} else if err != nil {
|
||||
return "", "", fmt.Errorf("stat candidate project folder: %w", err)
|
||||
}
|
||||
|
||||
folderSlug = fmt.Sprintf("%s-%d", baseSlug, attempt)
|
||||
folderName = slugDir("folder", folderSlug)
|
||||
folderDir = filepath.Join(parentDir, folderName)
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Join(folderDir, "children"), 0o755); err != nil {
|
||||
return "", "", fmt.Errorf("create project hierarchy folder: %w", err)
|
||||
}
|
||||
|
||||
if err := writeJSONFile(filepath.Join(folderDir, "folder.json"), map[string]any{
|
||||
"name": trimmedName,
|
||||
"slug": folderSlug,
|
||||
"type": "folder",
|
||||
}); err != nil {
|
||||
return "", "", fmt.Errorf("write project folder.json: %w", err)
|
||||
}
|
||||
|
||||
if err := writeJSONFile(filepath.Join(folderDir, "acl.json"), map[string]any{
|
||||
"version": 1,
|
||||
"inherits": true,
|
||||
"rules": []any{},
|
||||
}); err != nil {
|
||||
return "", "", fmt.Errorf("write project acl.json: %w", err)
|
||||
}
|
||||
|
||||
return filepath.ToSlash(filepath.Join(containerProjectionPath, folderName)), folderSlug, nil
|
||||
}
|
||||
|
||||
func buildProjectHierarchyFolderTree(rows []projectHierarchyFolderRow, rootParentPath string) []ProjectHierarchyFolderRecord {
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
nodesByPath := make(map[string]*ProjectHierarchyFolderRecord, len(rows))
|
||||
childrenByParent := make(map[string][]string)
|
||||
|
||||
for _, row := range rows {
|
||||
label := strings.TrimSpace(row.Label)
|
||||
if label == "" {
|
||||
label = fallbackFolderLabel(row.Path)
|
||||
}
|
||||
nodesByPath[row.Path] = &ProjectHierarchyFolderRecord{
|
||||
ID: row.Path,
|
||||
Label: label,
|
||||
Children: []ProjectHierarchyFolderRecord{},
|
||||
}
|
||||
childrenByParent[row.ParentPath] = append(childrenByParent[row.ParentPath], row.Path)
|
||||
}
|
||||
|
||||
var build func(parentPath string) []ProjectHierarchyFolderRecord
|
||||
build = func(parentPath string) []ProjectHierarchyFolderRecord {
|
||||
childPaths := childrenByParent[parentPath]
|
||||
if len(childPaths) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
folders := make([]ProjectHierarchyFolderRecord, 0, len(childPaths))
|
||||
for _, childPath := range childPaths {
|
||||
node := nodesByPath[childPath]
|
||||
if node == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
folder := ProjectHierarchyFolderRecord{
|
||||
ID: node.ID,
|
||||
Label: node.Label,
|
||||
Children: build(filepath.ToSlash(filepath.Join(childPath, "children"))),
|
||||
}
|
||||
folders = append(folders, folder)
|
||||
}
|
||||
|
||||
return folders
|
||||
}
|
||||
|
||||
return build(rootParentPath)
|
||||
}
|
||||
|
||||
func findProjectHierarchyFolder(folders []ProjectHierarchyFolderRecord, folderID string) (ProjectHierarchyFolderRecord, bool) {
|
||||
for _, folder := range folders {
|
||||
if folder.ID == folderID {
|
||||
return folder, true
|
||||
}
|
||||
|
||||
if child, ok := findProjectHierarchyFolder(folder.Children, folderID); ok {
|
||||
return child, true
|
||||
}
|
||||
}
|
||||
|
||||
return ProjectHierarchyFolderRecord{}, false
|
||||
}
|
||||
|
||||
func projectHierarchyRootPath(projectSlug string) string {
|
||||
return filepath.ToSlash(filepath.Join("projects", slugDir("project", projectSlug), "children"))
|
||||
}
|
||||
|
||||
func normalizePOSIXSlug(value string) string {
|
||||
trimmed := strings.TrimSpace(strings.ToLower(value))
|
||||
if trimmed == "" {
|
||||
return "untitled"
|
||||
}
|
||||
|
||||
var builder strings.Builder
|
||||
lastDash := false
|
||||
for _, r := range trimmed {
|
||||
switch {
|
||||
case unicode.IsLetter(r) || unicode.IsDigit(r):
|
||||
builder.WriteRune(r)
|
||||
lastDash = false
|
||||
case r == '-' || r == '_' || unicode.IsSpace(r):
|
||||
if !lastDash && builder.Len() > 0 {
|
||||
builder.WriteByte('-')
|
||||
lastDash = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
slug := strings.Trim(builder.String(), "-")
|
||||
if slug == "" {
|
||||
return "untitled"
|
||||
}
|
||||
|
||||
return slug
|
||||
}
|
||||
|
||||
func fallbackFolderLabel(path string) string {
|
||||
base := filepath.Base(filepath.FromSlash(path))
|
||||
trimmed := strings.TrimPrefix(base, "folder-")
|
||||
parts := strings.FieldsFunc(trimmed, func(r rune) bool { return r == '-' || r == '_' })
|
||||
for index, part := range parts {
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
parts[index] = strings.ToUpper(part[:1]) + part[1:]
|
||||
}
|
||||
label := strings.Join(parts, " ")
|
||||
if label == "" {
|
||||
return base
|
||||
}
|
||||
return label
|
||||
}
|
||||
|
||||
func slugDir(prefix, slug string) string {
|
||||
trimmedSlug := strings.TrimSpace(slug)
|
||||
if trimmedSlug == "" {
|
||||
|
||||
Reference in New Issue
Block a user