-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathGetModuleName.go
More file actions
42 lines (33 loc) · 1 KB
/
GetModuleName.go
File metadata and controls
42 lines (33 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package app
import (
"errors"
"path/filepath"
"strings"
)
// GetModuleName extracts the module name from a path containing a "modules" directory
// Example: "project/modules/user/model.go" -> "user"
func GetModuleName(path string) (string, error) {
if path == "" {
return "", errors.New("empty path")
}
// Replace backslashes with slashes to support Windows paths on any OS
normalized := strings.ReplaceAll(path, "\\", "/")
// Clean the path
cleanPath := filepath.Clean(normalized)
// Split into parts using '/' to be OS-agnostic
parts := strings.Split(cleanPath, "/")
// Find the "modules" directory and return the next part
for i, part := range parts {
if part == "modules" {
if i+1 >= len(parts) {
return "", errors.New("path ends at modules directory")
}
nextPart := parts[i+1]
if nextPart == "" || nextPart == "." || nextPart == ".." {
return "", errors.New("invalid module name")
}
return nextPart, nil
}
}
return "", errors.New("modules directory not found")
}