internal/testing/sample: add AddPackage

For golang/go#39629

Change-Id: I9dcf43ec3ec245ef1514b6bdb64afd1e8266a425
Reviewed-on: https://go-review.googlesource.com/c/pkgsite/+/258561
Trust: Julie Qiu <julie@golang.org>
Run-TryBot: Julie Qiu <julie@golang.org>
TryBot-Result: kokoro <noreply+kokoro@google.com>
Reviewed-by: Jonathan Amsterdam <jba@google.com>
diff --git a/internal/testing/sample/sample.go b/internal/testing/sample/sample.go
index 1d024bb..969ce87 100644
--- a/internal/testing/sample/sample.go
+++ b/internal/testing/sample/sample.go
@@ -93,6 +93,41 @@
 	return time.Now().Truncate(time.Microsecond)
 }
 
+func AddPackage(m *internal.Module, fullPath string) *internal.Module {
+	if m.ModulePath != stdlib.ModulePath && !strings.HasPrefix(fullPath, m.ModulePath) {
+		panic(fmt.Sprintf("package path %q not a prefix of module path %q",
+			fullPath, m.ModulePath))
+	}
+	AddUnit(m, &internal.Unit{
+		UnitMeta:        *UnitMeta(fullPath, m.ModulePath, m.Version, path.Base(fullPath), true),
+		Imports:         Imports,
+		LicenseContents: Licenses,
+		Documentation: &internal.Documentation{
+			Synopsis: Synopsis,
+			HTML:     DocumentationHTML,
+			GOOS:     GOOS,
+			GOARCH:   GOARCH,
+		},
+	})
+	minLen := len(m.ModulePath)
+	if m.ModulePath == stdlib.ModulePath {
+		minLen = 1
+	}
+	for pth := fullPath; len(pth) > minLen; pth = path.Dir(pth) {
+		found := false
+		for _, u := range m.Units {
+			if u.Path == pth {
+				found = true
+				break
+			}
+		}
+		if !found {
+			AddUnit(m, UnitEmpty(pth, m.ModulePath, m.Version))
+		}
+	}
+	return m
+}
+
 func PackageMeta(fullPath string) *internal.PackageMeta {
 	return &internal.PackageMeta{
 		Path:              fullPath,