Skip to content

Commit

Permalink
Support AST parsing with -trimpath flag
Browse files Browse the repository at this point in the history
Checking the trimmed path to see if some suffix is a valid filepath is
probably not a perfect system, but it should be able to work at least
some of the time, which is better than nothing.
  • Loading branch information
rliebz committed Jan 27, 2024
1 parent f7cc441 commit ac5e8b7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
7 changes: 6 additions & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@ permissions:

jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
os:
- ubuntu-latest
- windows-latest
go-version:
- '1.19'
- '1.20'
- '1.21'
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Set up Go ${{ matrix.go-version }}
Expand All @@ -28,6 +31,8 @@ jobs:
run: go build -v ./...
- name: Test
run: go test -v ./...
- name: Test -trimpath
run: go test -trimpath -v ./...

lint:
runs-on: ubuntu-latest
Expand Down
27 changes: 27 additions & 0 deletions ghostlib/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"go/format"
"go/parser"
"go/token"
"os"
"runtime"
"strings"
)
Expand Down Expand Up @@ -54,6 +55,8 @@ func callExprArgs(skip int) ([]ast.Expr, error) {
return nil, errors.New("failed to get file/line")
}

filename = findSystemFilepath(filename)

wantFunc := runtime.FuncForPC(pc)

fset := token.NewFileSet()
Expand All @@ -70,6 +73,30 @@ func callExprArgs(skip int) ([]ast.Expr, error) {
return node.Args, nil
}

// Passing the -trimpath flag will prevent looking up filepaths directly.
// In most cases, some suffix of the path will be a valid relative path, which
// we can use instead.
func findSystemFilepath(filename string) string {
if _, err := os.Stat(filename); err == nil {
return filename
}

cur := filename
for {
parts := strings.SplitN(cur, "/", 2)
if len(parts) < 2 {
break
}

cur = parts[1]
if _, err := os.Stat(cur); err == nil {
return cur
}
}

return filename
}

func callExprForFunc(
wantFunc *runtime.Func,
fset *token.FileSet,
Expand Down

0 comments on commit ac5e8b7

Please sign in to comment.