@@ -17,10 +17,13 @@ package python
1717import (
1818 "fmt"
1919 "os"
20+ "os/exec"
2021 "path/filepath"
2122 "regexp"
23+ "sort"
2224 "strings"
2325
26+ "github.com/cloudwego/abcoder/lang/log"
2427 lsp "github.com/cloudwego/abcoder/lang/lsp"
2528 "github.com/cloudwego/abcoder/lang/uniast"
2629)
@@ -29,10 +32,23 @@ type PythonSpec struct {
2932 repo string
3033 topModuleName string
3134 topModulePath string
35+ sysPaths []string
3236}
3337
3438func NewPythonSpec () * PythonSpec {
35- return & PythonSpec {}
39+ cmd := exec .Command ("python" , "-c" , "import sys ; print('\\ n'.join(sys.path))" )
40+ output , err := cmd .Output ()
41+ if err != nil {
42+ log .Error ("Failed to get sys.path: %v\n " , err )
43+ return nil
44+ }
45+ sysPaths := strings .Split (string (output ), "\n " )
46+ // Match more specific paths first
47+ sort .Slice (sysPaths , func (i , j int ) bool {
48+ return len (sysPaths [i ]) > len (sysPaths [j ])
49+ })
50+ log .Info ("PythonSpec: using sysPaths %+v\n " , sysPaths )
51+ return & PythonSpec {sysPaths : sysPaths }
3652}
3753
3854func (c * PythonSpec ) WorkSpace (root string ) (map [string ]string , error ) {
@@ -83,18 +99,11 @@ func (c *PythonSpec) NameSpace(path string) (string, string, error) {
8399 return modName , pkgPath , nil
84100 }
85101
86- // XXX: hardcode
87- if strings .HasSuffix (path , "stdlib/3/builtins.pyi" ) {
88- // builtin module
89- return "builtins" , "builtins" , nil
90- }
91-
92- // XXX: hardcoded python path
93- condaPrefix := "/home/zhenyang/anaconda3/envs/abcoder/lib/python3.11"
94- if strings .HasPrefix (path , condaPrefix ) {
95- if strings .HasPrefix (path , condaPrefix + "/site-packages" ) {
96- // external module
97- relPath , err := filepath .Rel (condaPrefix + "/site-packages" , path )
102+ for _ , sysPath := range c .sysPaths {
103+ log .Error ("PythonSpec: path %s sysPath %s\n " , path , sysPath )
104+ if strings .HasPrefix (path , sysPath ) {
105+ relPath , err := filepath .Rel (sysPath , path )
106+ log .Error ("PythonSpec: matched relPath %s, sysPath %s\n " , relPath , sysPath )
98107 if err != nil {
99108 return "" , "" , err
100109 }
@@ -107,18 +116,9 @@ func (c *PythonSpec) NameSpace(path string) (string, string, error) {
107116 }
108117 panic (fmt .Sprintf ("Malformed Namespace %s, pkgPath %s" , path , pkgPath ))
109118 }
110- // builtin module
111- modName := "builtins"
112- relPath , err := filepath .Rel (condaPrefix , path )
113- if err != nil {
114- return "" , "" , err
115- }
116- relPath = strings .TrimSuffix (relPath , ".py" )
117- pkgPath := strings .ReplaceAll (relPath , string (os .PathSeparator ), "." )
118- return modName , pkgPath , nil
119119 }
120-
121- panic ( fmt .Sprintf ( "Unhandled Namespace %s" , path ) )
120+ log . Error ( "Namespace not found for path: %s \n " , path )
121+ return "" , "" , fmt .Errorf ( "namespace not found for path: %s" , path )
122122}
123123
124124func (c * PythonSpec ) ShouldSkip (path string ) bool {
0 commit comments