From ef0818595134ae86e4ec2daea3c2f73a67b37c90 Mon Sep 17 00:00:00 2001 From: Paul Duffin Date: Thu, 13 May 2021 11:11:15 +0100 Subject: [PATCH] Add support for converting OptionalPath to Paths Appending a Path or Paths to a slice of Paths is simple but appending an OptionalPath requires conditional logic which makes OptionalPaths harder to use. This change makes it easy to append the embedded Path, if any, to a slice of Paths. Bug: 179354495 Test: m nothing Change-Id: Ibf80a23043c846162e17c3a98b2590bca653b170 --- android/paths.go | 11 +++++++++++ android/paths_test.go | 22 ++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/android/paths.go b/android/paths.go index 5d458cbb1..fb751175e 100644 --- a/android/paths.go +++ b/android/paths.go @@ -287,6 +287,17 @@ func (p OptionalPath) Path() Path { return p.path } +// AsPaths converts the OptionalPath into Paths. +// +// It returns nil if this is not valid, or a single length slice containing the Path embedded in +// this OptionalPath. +func (p OptionalPath) AsPaths() Paths { + if !p.valid { + return nil + } + return Paths{p.path} +} + // RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the // result of calling Path.RelativeToTop on it. func (p OptionalPath) RelativeToTop() OptionalPath { diff --git a/android/paths_test.go b/android/paths_test.go index f8ccc7789..6f5d79e7e 100644 --- a/android/paths_test.go +++ b/android/paths_test.go @@ -141,6 +141,9 @@ func TestOptionalPath(t *testing.T) { path = OptionalPathForPath(nil) checkInvalidOptionalPath(t, path) + + path = OptionalPathForPath(PathForTesting("path")) + checkValidOptionalPath(t, path, "path") } func checkInvalidOptionalPath(t *testing.T, path OptionalPath) { @@ -151,6 +154,10 @@ func checkInvalidOptionalPath(t *testing.T, path OptionalPath) { if path.String() != "" { t.Errorf("Uninitialized OptionalPath String() should return \"\", not %q", path.String()) } + paths := path.AsPaths() + if len(paths) != 0 { + t.Errorf("Uninitialized OptionalPath AsPaths() should return empty Paths, not %q", paths) + } defer func() { if r := recover(); r == nil { t.Errorf("Expected a panic when calling Path() on an uninitialized OptionalPath") @@ -159,6 +166,21 @@ func checkInvalidOptionalPath(t *testing.T, path OptionalPath) { path.Path() } +func checkValidOptionalPath(t *testing.T, path OptionalPath, expectedString string) { + t.Helper() + if !path.Valid() { + t.Errorf("Initialized OptionalPath should not be invalid") + } + if path.String() != expectedString { + t.Errorf("Initialized OptionalPath String() should return %q, not %q", expectedString, path.String()) + } + paths := path.AsPaths() + if len(paths) != 1 { + t.Errorf("Initialized OptionalPath AsPaths() should return Paths with length 1, not %q", paths) + } + path.Path() +} + func check(t *testing.T, testType, testString string, got interface{}, err []error, expected interface{}, expectedErr []error) {