Skip to content

Commit

Permalink
Fix Package stringer to handle bad inputs
Browse files Browse the repository at this point in the history
If users are constructing modules programatically they may accidentally
construct package paths with illegal values. Before this change, calling
.String() on the package would result in a panic. With these changes the
.String() function will no longer panic, instead it will return a string
representation that does not parse and indicates the source of the
issue.

Signed-off-by: Torin Sandall <torinsandall@gmail.com>
  • Loading branch information
tsandall committed Sep 13, 2018
1 parent 1b82a8c commit 5f2bba0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
5 changes: 5 additions & 0 deletions ast/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,11 @@ func (pkg *Package) SetLoc(loc *Location) {
}

func (pkg *Package) String() string {
if pkg == nil {
return "<illegal nil package>"
} else if len(pkg.Path) <= 1 {
return fmt.Sprintf("package <illegal path %q>", pkg.Path)
}
// Omit head as all packages have the DefaultRootDocument prepended at parse time.
path := make(Ref, len(pkg.Path)-1)
path[0] = VarTerm(string(pkg.Path[1].Value.(String)))
Expand Down
17 changes: 17 additions & 0 deletions ast/policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,23 @@ func TestPackageString(t *testing.T) {
if result1 != expected1 {
t.Errorf("Expected %v but got %v", expected1, result1)
}

var nilPkg *Package

expNil := "<illegal nil package>"
if nilPkg.String() != expNil {
t.Fatal("Unexpected package repr:", nilPkg.String())
}

badPathPkg := &Package{
Path: RefTerm(VarTerm("x")).Value.(Ref),
}

expBadPath := "package <illegal path \"x\">"
if badPathPkg.String() != expBadPath {
t.Fatal("Unexpected package repr:", badPathPkg.String())
}

}

func TestImportEquals(t *testing.T) {
Expand Down

0 comments on commit 5f2bba0

Please sign in to comment.