Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(storage): parse out project number if available #6671

Merged
merged 3 commits into from Sep 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions storage/bucket.go
Expand Up @@ -775,6 +775,7 @@ func newBucketFromProto(b *storagepb.Bucket) *BucketAttrs {
LocationType: b.GetLocationType(),
RPO: toRPOFromProto(b),
CustomPlacementConfig: customPlacementFromProto(b.GetCustomPlacementConfig()),
ProjectNumber: parseProjectNumber(b.GetProject()), // this can return 0 the project resource name is ID based
}
}

Expand Down
19 changes: 19 additions & 0 deletions storage/storage.go
Expand Up @@ -33,6 +33,7 @@ import (
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode/utf8"
Expand Down Expand Up @@ -2002,6 +2003,24 @@ func parseBucketName(b string) string {
return b[sep+1:]
}

// parseProjectNumber consume the given resource name and parses out the project
// number if one is present i.e. it is not a project ID.
func parseProjectNumber(r string) uint64 {
projectID := regexp.MustCompile(`projects\/([0-9]+)\/?`)
if matches := projectID.FindStringSubmatch(r); len(matches) > 0 {
// Capture group follows the matched segment. For example:
// input: projects/123/bars/456
// output: [projects/123/, 123]
number, err := strconv.ParseUint(matches[1], 10, 64)
if err != nil {
return 0
}
return number
}

return 0
}

// toProjectResource accepts a project ID and formats it as a Project resource
// name.
func toProjectResource(project string) string {
Expand Down
18 changes: 18 additions & 0 deletions storage/storage_test.go
Expand Up @@ -2341,6 +2341,24 @@ func TestSignedURLOptionsClone(t *testing.T) {
}
}

func TestParseProjectNumber(t *testing.T) {
for _, tst := range []struct {
input string
want uint64
}{
{"projects/123", 123},
{"projects/123/foos/456", 123},
{"projects/abc-123/foos/456", 0},
{"projects/abc-123", 0},
{"projects/abc", 0},
{"projects/abc/foos", 0},
} {
if got := parseProjectNumber(tst.input); got != tst.want {
t.Errorf("For %q: got %v, expected %v", tst.input, got, tst.want)
}
}
}

// isZeroValue reports whether v is the zero value for its type
// It errors if the argument is unknown
func isZeroValue(v reflect.Value) (bool, error) {
Expand Down