diff --git a/cmd/frontend/auth/BUILD.bazel b/cmd/frontend/auth/BUILD.bazel index bbc5351d62f..9ccea35f9a1 100644 --- a/cmd/frontend/auth/BUILD.bazel +++ b/cmd/frontend/auth/BUILD.bazel @@ -59,6 +59,7 @@ go_test( "//internal/search/job/jobutil", "//internal/types", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_derision_test_go_mockgen//testutil/require", "@com_github_google_go_cmp//cmp", diff --git a/cmd/frontend/auth/non_public_test.go b/cmd/frontend/auth/non_public_test.go index 9bb9f0d3145..962187c125a 100644 --- a/cmd/frontend/auth/non_public_test.go +++ b/cmd/frontend/auth/non_public_test.go @@ -15,6 +15,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/conf" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/search/job/jobutil" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -71,8 +72,6 @@ func TestAllowAnonymousRequestWithAdditionalConfig(t *testing.T) { return r } - boolPtr := func(b bool) *bool { return &b } - tests := []struct { req *http.Request confAuthPublic bool @@ -81,25 +80,25 @@ func TestAllowAnonymousRequestWithAdditionalConfig(t *testing.T) { }{ {req: req("GET", "/"), confAuthPublic: false, allowAnonymousContextKey: nil, want: false}, {req: req("GET", "/"), confAuthPublic: true, allowAnonymousContextKey: nil, want: false}, - {req: req("GET", "/"), confAuthPublic: false, allowAnonymousContextKey: boolPtr(false), want: false}, - {req: req("GET", "/"), confAuthPublic: true, allowAnonymousContextKey: boolPtr(false), want: false}, - {req: req("GET", "/"), confAuthPublic: false, allowAnonymousContextKey: boolPtr(true), want: false}, - {req: req("GET", "/"), confAuthPublic: true, allowAnonymousContextKey: boolPtr(true), want: true}, + {req: req("GET", "/"), confAuthPublic: false, allowAnonymousContextKey: pointers.Ptr(false), want: false}, + {req: req("GET", "/"), confAuthPublic: true, allowAnonymousContextKey: pointers.Ptr(false), want: false}, + {req: req("GET", "/"), confAuthPublic: false, allowAnonymousContextKey: pointers.Ptr(true), want: false}, + {req: req("GET", "/"), confAuthPublic: true, allowAnonymousContextKey: pointers.Ptr(true), want: true}, {req: req("POST", "/"), confAuthPublic: false, allowAnonymousContextKey: nil, want: false}, {req: req("POST", "/"), confAuthPublic: true, allowAnonymousContextKey: nil, want: false}, - {req: req("POST", "/"), confAuthPublic: false, allowAnonymousContextKey: boolPtr(false), want: false}, - {req: req("POST", "/"), confAuthPublic: true, allowAnonymousContextKey: boolPtr(false), want: false}, - {req: req("POST", "/"), confAuthPublic: false, allowAnonymousContextKey: boolPtr(true), want: false}, - {req: req("POST", "/"), confAuthPublic: true, allowAnonymousContextKey: boolPtr(true), want: true}, + {req: req("POST", "/"), confAuthPublic: false, allowAnonymousContextKey: pointers.Ptr(false), want: false}, + {req: req("POST", "/"), confAuthPublic: true, allowAnonymousContextKey: pointers.Ptr(false), want: false}, + {req: req("POST", "/"), confAuthPublic: false, allowAnonymousContextKey: pointers.Ptr(true), want: false}, + {req: req("POST", "/"), confAuthPublic: true, allowAnonymousContextKey: pointers.Ptr(true), want: true}, {req: req("POST", "/-/sign-in"), confAuthPublic: false, allowAnonymousContextKey: nil, want: true}, {req: req("POST", "/-/sign-in"), confAuthPublic: true, allowAnonymousContextKey: nil, want: true}, - {req: req("POST", "/-/sign-in"), confAuthPublic: false, allowAnonymousContextKey: boolPtr(true), want: true}, - {req: req("POST", "/-/sign-in"), confAuthPublic: true, allowAnonymousContextKey: boolPtr(true), want: true}, + {req: req("POST", "/-/sign-in"), confAuthPublic: false, allowAnonymousContextKey: pointers.Ptr(true), want: true}, + {req: req("POST", "/-/sign-in"), confAuthPublic: true, allowAnonymousContextKey: pointers.Ptr(true), want: true}, {req: req("GET", "/sign-in"), confAuthPublic: false, allowAnonymousContextKey: nil, want: true}, {req: req("GET", "/sign-in"), confAuthPublic: true, allowAnonymousContextKey: nil, want: true}, - {req: req("GET", "/sign-in"), confAuthPublic: false, allowAnonymousContextKey: boolPtr(true), want: true}, - {req: req("GET", "/sign-in"), confAuthPublic: true, allowAnonymousContextKey: boolPtr(true), want: true}, + {req: req("GET", "/sign-in"), confAuthPublic: false, allowAnonymousContextKey: pointers.Ptr(true), want: true}, + {req: req("GET", "/sign-in"), confAuthPublic: true, allowAnonymousContextKey: pointers.Ptr(true), want: true}, } for _, test := range tests { t.Run(fmt.Sprintf("%s %s + auth.public=%v, allowAnonymousContext=%v", test.req.Method, test.req.URL, test.confAuthPublic, test.allowAnonymousContextKey), func(t *testing.T) { diff --git a/cmd/frontend/graphqlbackend/BUILD.bazel b/cmd/frontend/graphqlbackend/BUILD.bazel index 0fe08920975..81142c8dcff 100644 --- a/cmd/frontend/graphqlbackend/BUILD.bazel +++ b/cmd/frontend/graphqlbackend/BUILD.bazel @@ -504,6 +504,7 @@ go_test( "//internal/version", "//internal/webhooks/outbound", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_davecgh_go_spew//spew", "@com_github_derision_test_go_mockgen//testutil/assert", diff --git a/cmd/frontend/graphqlbackend/executor_secrets_test.go b/cmd/frontend/graphqlbackend/executor_secrets_test.go index 57e2803fb4d..26537965d79 100644 --- a/cmd/frontend/graphqlbackend/executor_secrets_test.go +++ b/cmd/frontend/graphqlbackend/executor_secrets_test.go @@ -17,6 +17,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/encryption" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestSchemaResolver_CreateExecutorSecret(t *testing.T) { @@ -33,8 +34,6 @@ func TestSchemaResolver_CreateExecutorSecret(t *testing.T) { t.Fatal(err) } - gqlIDPtr := func(id graphql.ID) *graphql.ID { return &id } - tts := []struct { name string args CreateExecutorSecretArgs @@ -86,7 +85,7 @@ func TestSchemaResolver_CreateExecutorSecret(t *testing.T) { Key: "GITHUB_TOKEN", Value: "1234", Scope: ExecutorSecretScopeBatches, - Namespace: gqlIDPtr(MarshalUserID(user.ID)), + Namespace: pointers.Ptr(MarshalUserID(user.ID)), }, actor: actor.FromUser(user.ID), }, diff --git a/cmd/frontend/graphqlbackend/org_invitations_test.go b/cmd/frontend/graphqlbackend/org_invitations_test.go index be8423fe18e..f1853580068 100644 --- a/cmd/frontend/graphqlbackend/org_invitations_test.go +++ b/cmd/frontend/graphqlbackend/org_invitations_test.go @@ -22,6 +22,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/txemail" "github.com/sourcegraph/sourcegraph/internal/types" stderrors "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -106,7 +107,7 @@ func TestOrgInvitationURL(t *testing.T) { OrgID: 1, ID: 2, SenderUserID: 3, - ExpiresAt: timePtr(timeNow().Add(DefaultExpiryDuration)), + ExpiresAt: pointers.Ptr(timeNow().Add(DefaultExpiryDuration)), } t.Run("Fails if site config is not defined", func(t *testing.T) { @@ -186,7 +187,7 @@ func TestInviteUserToOrganization(t *testing.T) { orgs.GetByIDFunc.SetDefaultReturn(&mockedOrg, nil) orgInvitations := database.NewMockOrgInvitationStore() - orgInvitations.CreateFunc.SetDefaultReturn(&database.OrgInvitation{ID: 1, ExpiresAt: timePtr(timeNow().Add(DefaultExpiryDuration))}, nil) + orgInvitations.CreateFunc.SetDefaultReturn(&database.OrgInvitation{ID: 1, ExpiresAt: pointers.Ptr(timeNow().Add(DefaultExpiryDuration))}, nil) featureFlags := database.NewMockFeatureFlagStore() featureFlags.GetOrgFeatureFlagFunc.SetDefaultReturn(false, nil) diff --git a/cmd/frontend/graphqlbackend/repository_metadata_test.go b/cmd/frontend/graphqlbackend/repository_metadata_test.go index 0a3a5f96871..8a5ab979844 100644 --- a/cmd/frontend/graphqlbackend/repository_metadata_test.go +++ b/cmd/frontend/graphqlbackend/repository_metadata_test.go @@ -16,6 +16,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/rbac" "github.com/sourcegraph/sourcegraph/internal/search/job/jobutil" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/log/logtest" @@ -51,8 +52,6 @@ func TestRepositoryMetadata(t *testing.T) { schema := newSchemaResolver(db, gitserver.NewClient(), jobutil.NewUnimplementedEnterpriseJobs()) gqlID := MarshalRepositoryID(repo.ID) - strPtr := func(s string) *string { return &s } - t.Run("add", func(t *testing.T) { _, err = schema.AddRepoMetadata(ctx, struct { Repo graphql.ID @@ -61,7 +60,7 @@ func TestRepositoryMetadata(t *testing.T) { }{ Repo: gqlID, Key: "key1", - Value: strPtr("val1"), + Value: pointers.Ptr("val1"), }) require.NoError(t, err) @@ -72,7 +71,7 @@ func TestRepositoryMetadata(t *testing.T) { }{ Repo: gqlID, Key: "tag1", - Value: strPtr(" "), + Value: pointers.Ptr(" "), }) require.Error(t, err) require.Equal(t, emptyNonNilValueError{value: " "}, err) @@ -98,7 +97,7 @@ func TestRepositoryMetadata(t *testing.T) { }) require.Equal(t, []KeyValuePair{{ key: "key1", - value: strPtr("val1"), + value: pointers.Ptr("val1"), }, { key: "tag1", value: nil, @@ -113,7 +112,7 @@ func TestRepositoryMetadata(t *testing.T) { }{ Repo: gqlID, Key: "key1", - Value: strPtr("val2"), + Value: pointers.Ptr("val2"), }) require.NoError(t, err) @@ -124,7 +123,7 @@ func TestRepositoryMetadata(t *testing.T) { }{ Repo: gqlID, Key: "tag1", - Value: strPtr("val3"), + Value: pointers.Ptr("val3"), }) require.NoError(t, err) @@ -135,7 +134,7 @@ func TestRepositoryMetadata(t *testing.T) { }{ Repo: gqlID, Key: "tag1", - Value: strPtr(" "), + Value: pointers.Ptr(" "), }) require.Error(t, err) require.Equal(t, emptyNonNilValueError{value: " "}, err) @@ -150,10 +149,10 @@ func TestRepositoryMetadata(t *testing.T) { }) require.Equal(t, []KeyValuePair{{ key: "key1", - value: strPtr("val2"), + value: pointers.Ptr("val2"), }, { key: "tag1", - value: strPtr("val3"), + value: pointers.Ptr("val3"), }}, kvps) }) @@ -197,7 +196,7 @@ func TestRepositoryMetadata(t *testing.T) { }{ Repo: gqlID, Key: "key1", - Value: strPtr("val1"), + Value: pointers.Ptr("val1"), }) require.Error(t, err) require.Equal(t, featureDisabledError, err) @@ -209,7 +208,7 @@ func TestRepositoryMetadata(t *testing.T) { }{ Repo: gqlID, Key: "key1", - Value: strPtr("val2"), + Value: pointers.Ptr("val2"), }) require.Error(t, err) require.Equal(t, featureDisabledError, err) @@ -236,7 +235,7 @@ func TestRepositoryMetadata(t *testing.T) { }{ Repo: gqlID, Key: "key1", - Value: strPtr("val1"), + Value: pointers.Ptr("val1"), }) require.Error(t, err) require.Equal(t, err, &rbac.ErrNotAuthorized{Permission: string(rbac.RepoMetadataWritePermission)}) @@ -249,7 +248,7 @@ func TestRepositoryMetadata(t *testing.T) { }{ Repo: gqlID, Key: "key1", - Value: strPtr("val2"), + Value: pointers.Ptr("val2"), }) require.Error(t, err) require.Equal(t, err, &rbac.ErrNotAuthorized{Permission: string(rbac.RepoMetadataWritePermission)}) diff --git a/cmd/frontend/graphqlbackend/site_config_change_connection_test.go b/cmd/frontend/graphqlbackend/site_config_change_connection_test.go index 4353c4aac73..830e1a24e3b 100644 --- a/cmd/frontend/graphqlbackend/site_config_change_connection_test.go +++ b/cmd/frontend/graphqlbackend/site_config_change_connection_test.go @@ -8,10 +8,12 @@ import ( "github.com/google/go-cmp/cmp" "github.com/sourcegraph/log" + "github.com/sourcegraph/sourcegraph/internal/actor" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) type siteConfigStubs struct { @@ -102,7 +104,7 @@ func setupSiteConfigStubs(t *testing.T) *siteConfigStubs { // This will create 5 entries, because the first time conf.SiteCreateIfupToDate is called it // will create two entries in the DB. for _, input := range siteConfigsToCreate { - siteConfig, err := conf.SiteCreateIfUpToDate(ctx, int32Ptr(lastID), input.AuthorUserID, input.Contents, false) + siteConfig, err := conf.SiteCreateIfUpToDate(ctx, pointers.Ptr(lastID), input.AuthorUserID, input.Contents, false) if err != nil { t.Fatal(err) } @@ -529,7 +531,7 @@ func TestSiteConfigurationChangeConnectionStoreComputeNodes(t *testing.T) { { name: "first: 2", paginationArgs: &database.PaginationArgs{ - First: intPtr(2), + First: pointers.Ptr(2), }, // 5 is skipped because it is the same as 4. expectedSiteConfigIDs: []int32{6, 4}, @@ -538,7 +540,7 @@ func TestSiteConfigurationChangeConnectionStoreComputeNodes(t *testing.T) { { name: "first: 6 (exact number of items that exist in the database)", paginationArgs: &database.PaginationArgs{ - First: intPtr(6), + First: pointers.Ptr(6), }, expectedSiteConfigIDs: []int32{6, 4, 3, 2, 1}, expectedPreviousSiteConfigIDs: []int32{4, 3, 2, 1, 0}, @@ -546,7 +548,7 @@ func TestSiteConfigurationChangeConnectionStoreComputeNodes(t *testing.T) { { name: "first: 20 (more items than what exists in the database)", paginationArgs: &database.PaginationArgs{ - First: intPtr(20), + First: pointers.Ptr(20), }, expectedSiteConfigIDs: []int32{6, 4, 3, 2, 1}, expectedPreviousSiteConfigIDs: []int32{4, 3, 2, 1, 0}, @@ -554,7 +556,7 @@ func TestSiteConfigurationChangeConnectionStoreComputeNodes(t *testing.T) { { name: "last: 2", paginationArgs: &database.PaginationArgs{ - Last: intPtr(2), + Last: pointers.Ptr(2), }, expectedSiteConfigIDs: []int32{1, 2}, expectedPreviousSiteConfigIDs: []int32{0, 1}, @@ -562,7 +564,7 @@ func TestSiteConfigurationChangeConnectionStoreComputeNodes(t *testing.T) { { name: "last: 6 (exact number of items that exist in the database)", paginationArgs: &database.PaginationArgs{ - Last: intPtr(6), + Last: pointers.Ptr(6), }, expectedSiteConfigIDs: []int32{1, 2, 3, 4, 6}, expectedPreviousSiteConfigIDs: []int32{0, 1, 2, 3, 4}, @@ -570,7 +572,7 @@ func TestSiteConfigurationChangeConnectionStoreComputeNodes(t *testing.T) { { name: "last: 20 (more items than what exists in the database)", paginationArgs: &database.PaginationArgs{ - Last: intPtr(20), + Last: pointers.Ptr(20), }, expectedSiteConfigIDs: []int32{1, 2, 3, 4, 6}, expectedPreviousSiteConfigIDs: []int32{0, 1, 2, 3, 4}, @@ -578,7 +580,7 @@ func TestSiteConfigurationChangeConnectionStoreComputeNodes(t *testing.T) { { name: "first: 2, after: 6", paginationArgs: &database.PaginationArgs{ - First: intPtr(2), + First: pointers.Ptr(2), After: toStringPtr(6), }, expectedSiteConfigIDs: []int32{4, 3}, @@ -587,7 +589,7 @@ func TestSiteConfigurationChangeConnectionStoreComputeNodes(t *testing.T) { { name: "first: 10, after: 6", paginationArgs: &database.PaginationArgs{ - First: intPtr(10), + First: pointers.Ptr(10), After: toStringPtr(6), }, expectedSiteConfigIDs: []int32{4, 3, 2, 1}, @@ -596,7 +598,7 @@ func TestSiteConfigurationChangeConnectionStoreComputeNodes(t *testing.T) { { name: "first: 2, after: 1", paginationArgs: &database.PaginationArgs{ - First: intPtr(2), + First: pointers.Ptr(2), After: toStringPtr(1), }, expectedSiteConfigIDs: []int32{}, @@ -605,7 +607,7 @@ func TestSiteConfigurationChangeConnectionStoreComputeNodes(t *testing.T) { { name: "last: 2, before: 2", paginationArgs: &database.PaginationArgs{ - Last: intPtr(2), + Last: pointers.Ptr(2), Before: toStringPtr(2), }, expectedSiteConfigIDs: []int32{3, 4}, @@ -614,7 +616,7 @@ func TestSiteConfigurationChangeConnectionStoreComputeNodes(t *testing.T) { { name: "last: 10, before: 2", paginationArgs: &database.PaginationArgs{ - Last: intPtr(10), + Last: pointers.Ptr(10), Before: toStringPtr(2), }, expectedSiteConfigIDs: []int32{3, 4, 6}, @@ -623,7 +625,7 @@ func TestSiteConfigurationChangeConnectionStoreComputeNodes(t *testing.T) { { name: "last: 2, before: 6", paginationArgs: &database.PaginationArgs{ - Last: intPtr(2), + Last: pointers.Ptr(2), Before: toStringPtr(6), }, expectedSiteConfigIDs: []int32{}, @@ -682,38 +684,38 @@ func TestModifyArgs(t *testing.T) { }{ { name: "first: 5 (first page)", - args: &database.PaginationArgs{First: intPtr(5)}, - expectedArgs: &database.PaginationArgs{First: intPtr(6)}, + args: &database.PaginationArgs{First: pointers.Ptr(5)}, + expectedArgs: &database.PaginationArgs{First: pointers.Ptr(6)}, expectedModified: true, }, { name: "first: 5, after: 10 (next page)", - args: &database.PaginationArgs{First: intPtr(5), After: toStringPtr(10)}, - expectedArgs: &database.PaginationArgs{First: intPtr(6), After: toStringPtr(10)}, + args: &database.PaginationArgs{First: pointers.Ptr(5), After: toStringPtr(10)}, + expectedArgs: &database.PaginationArgs{First: pointers.Ptr(6), After: toStringPtr(10)}, expectedModified: true, }, { name: "last: 5 (last page)", - args: &database.PaginationArgs{Last: intPtr(5)}, - expectedArgs: &database.PaginationArgs{Last: intPtr(5)}, + args: &database.PaginationArgs{Last: pointers.Ptr(5)}, + expectedArgs: &database.PaginationArgs{Last: pointers.Ptr(5)}, expectedModified: false, }, { name: "last: 5, before: 10 (previous page)", - args: &database.PaginationArgs{Last: intPtr(5), Before: toStringPtr(10)}, - expectedArgs: &database.PaginationArgs{Last: intPtr(6), Before: toStringPtr(9)}, + args: &database.PaginationArgs{Last: pointers.Ptr(5), Before: toStringPtr(10)}, + expectedArgs: &database.PaginationArgs{Last: pointers.Ptr(6), Before: toStringPtr(9)}, expectedModified: true, }, { name: "last: 5, before: 1 (edge case)", - args: &database.PaginationArgs{Last: intPtr(5), Before: toStringPtr(1)}, - expectedArgs: &database.PaginationArgs{Last: intPtr(6), Before: toStringPtr(0)}, + args: &database.PaginationArgs{Last: pointers.Ptr(5), Before: toStringPtr(1)}, + expectedArgs: &database.PaginationArgs{Last: pointers.Ptr(6), Before: toStringPtr(0)}, expectedModified: true, }, { name: "last: 5, before: 0 (same as last page but a mathematical edge case)", - args: &database.PaginationArgs{Last: intPtr(5), Before: toStringPtr(0)}, - expectedArgs: &database.PaginationArgs{Last: intPtr(5), Before: toStringPtr(0)}, + args: &database.PaginationArgs{Last: pointers.Ptr(5), Before: toStringPtr(0)}, + expectedArgs: &database.PaginationArgs{Last: pointers.Ptr(5), Before: toStringPtr(0)}, expectedModified: false, }, } diff --git a/cmd/frontend/graphqlbackend/site_config_change_test.go b/cmd/frontend/graphqlbackend/site_config_change_test.go index ba52886e1eb..aedf17f43f2 100644 --- a/cmd/frontend/graphqlbackend/site_config_change_test.go +++ b/cmd/frontend/graphqlbackend/site_config_change_test.go @@ -10,6 +10,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/actor" "github.com/sourcegraph/sourcegraph/internal/gitserver" "github.com/sourcegraph/sourcegraph/internal/search/job/jobutil" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestSiteConfigurationDiff(t *testing.T) { @@ -63,11 +64,11 @@ func TestSiteConfigurationDiff(t *testing.T) { // the nodes in both the directions. { name: "first: 10", - args: &graphqlutil.ConnectionResolverArgs{First: int32Ptr(10)}, + args: &graphqlutil.ConnectionResolverArgs{First: pointers.Ptr(int32(10))}, }, { name: "last: 10", - args: &graphqlutil.ConnectionResolverArgs{Last: int32Ptr(10)}, + args: &graphqlutil.ConnectionResolverArgs{Last: pointers.Ptr(int32(10))}, }, } diff --git a/cmd/frontend/graphqlbackend/site_test.go b/cmd/frontend/graphqlbackend/site_test.go index ae61cf52957..b0431773a8f 100644 --- a/cmd/frontend/graphqlbackend/site_test.go +++ b/cmd/frontend/graphqlbackend/site_test.go @@ -16,6 +16,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/search/job/jobutil" "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestSiteConfiguration(t *testing.T) { @@ -50,95 +51,95 @@ func TestSiteConfigurationHistory(t *testing.T) { }{ { name: "first: 2", - args: &graphqlutil.ConnectionResolverArgs{First: int32Ptr(2)}, + args: &graphqlutil.ConnectionResolverArgs{First: pointers.Ptr(int32(2))}, expectedSiteConfigIDs: []int32{6, 4}, }, { name: "first: 6 (exact number of items that exist in the database)", - args: &graphqlutil.ConnectionResolverArgs{First: int32Ptr(6)}, + args: &graphqlutil.ConnectionResolverArgs{First: pointers.Ptr(int32(6))}, expectedSiteConfigIDs: []int32{6, 4, 3, 2, 1}, }, { name: "first: 20 (more items than what exists in the database)", - args: &graphqlutil.ConnectionResolverArgs{First: int32Ptr(20)}, + args: &graphqlutil.ConnectionResolverArgs{First: pointers.Ptr(int32(20))}, expectedSiteConfigIDs: []int32{6, 4, 3, 2, 1}, }, { name: "last: 2", - args: &graphqlutil.ConnectionResolverArgs{Last: int32Ptr(2)}, + args: &graphqlutil.ConnectionResolverArgs{Last: pointers.Ptr(int32(2))}, expectedSiteConfigIDs: []int32{2, 1}, }, { name: "last: 6 (exact number of items that exist in the database)", - args: &graphqlutil.ConnectionResolverArgs{Last: int32Ptr(6)}, + args: &graphqlutil.ConnectionResolverArgs{Last: pointers.Ptr(int32(6))}, expectedSiteConfigIDs: []int32{6, 4, 3, 2, 1}, }, { name: "last: 20 (more items than what exists in the database)", - args: &graphqlutil.ConnectionResolverArgs{Last: int32Ptr(20)}, + args: &graphqlutil.ConnectionResolverArgs{Last: pointers.Ptr(int32(20))}, expectedSiteConfigIDs: []int32{6, 4, 3, 2, 1}, }, { name: "first: 2, after: 4", args: &graphqlutil.ConnectionResolverArgs{ - First: int32Ptr(2), - After: stringPtr(string(marshalSiteConfigurationChangeID(4))), + First: pointers.Ptr(int32(2)), + After: pointers.Ptr(string(marshalSiteConfigurationChangeID(4))), }, expectedSiteConfigIDs: []int32{3, 2}, }, { name: "first: 10, after: 4 (overflow)", args: &graphqlutil.ConnectionResolverArgs{ - First: int32Ptr(10), - After: stringPtr(string(marshalSiteConfigurationChangeID(4))), + First: pointers.Ptr(int32(10)), + After: pointers.Ptr(string(marshalSiteConfigurationChangeID(4))), }, expectedSiteConfigIDs: []int32{3, 2, 1}, }, { name: "first: 10, after: 7 (same as get all items, but latest ID in DB is 6)", args: &graphqlutil.ConnectionResolverArgs{ - First: int32Ptr(10), - After: stringPtr(string(marshalSiteConfigurationChangeID(7))), + First: pointers.Ptr(int32(10)), + After: pointers.Ptr(string(marshalSiteConfigurationChangeID(7))), }, expectedSiteConfigIDs: []int32{6, 4, 3, 2, 1}, }, { name: "first: 10, after: 1 (beyond the last cursor in DB which is 1)", args: &graphqlutil.ConnectionResolverArgs{ - First: int32Ptr(10), - After: stringPtr(string(marshalSiteConfigurationChangeID(1))), + First: pointers.Ptr(int32(10)), + After: pointers.Ptr(string(marshalSiteConfigurationChangeID(1))), }, expectedSiteConfigIDs: []int32{}, }, { name: "last: 2, before: 1", args: &graphqlutil.ConnectionResolverArgs{ - Last: int32Ptr(2), - Before: stringPtr(string(marshalSiteConfigurationChangeID(1))), + Last: pointers.Ptr(int32(2)), + Before: pointers.Ptr(string(marshalSiteConfigurationChangeID(1))), }, expectedSiteConfigIDs: []int32{3, 2}, }, { name: "last: 10, before: 1 (overflow)", args: &graphqlutil.ConnectionResolverArgs{ - Last: int32Ptr(10), - Before: stringPtr(string(marshalSiteConfigurationChangeID(1))), + Last: pointers.Ptr(int32(10)), + Before: pointers.Ptr(string(marshalSiteConfigurationChangeID(1))), }, expectedSiteConfigIDs: []int32{6, 4, 3, 2}, }, { name: "last: 10, before: 0 (same as get all items, but oldest ID in DB is 1)", args: &graphqlutil.ConnectionResolverArgs{ - Last: int32Ptr(10), - Before: stringPtr(string(marshalSiteConfigurationChangeID(0))), + Last: pointers.Ptr(int32(10)), + Before: pointers.Ptr(string(marshalSiteConfigurationChangeID(0))), }, expectedSiteConfigIDs: []int32{6, 4, 3, 2, 1}, }, { name: "last: 10, before: 7 (beyond the latest cursor in DB which is 6)", args: &graphqlutil.ConnectionResolverArgs{ - Last: int32Ptr(10), - Before: stringPtr(string(marshalSiteConfigurationChangeID(7))), + Last: pointers.Ptr(int32(10)), + Before: pointers.Ptr(string(marshalSiteConfigurationChangeID(7))), }, expectedSiteConfigIDs: []int32{}, }, diff --git a/cmd/frontend/graphqlbackend/webhook_logs_test.go b/cmd/frontend/graphqlbackend/webhook_logs_test.go index d68381d3f01..053cf5e22c6 100644 --- a/cmd/frontend/graphqlbackend/webhook_logs_test.go +++ b/cmd/frontend/graphqlbackend/webhook_logs_test.go @@ -6,10 +6,11 @@ import ( "time" mockassert "github.com/derision-test/go-mockgen/testutil/assert" - "github.com/graph-gophers/graphql-go" - "github.com/sourcegraph/sourcegraph/internal/actor" "github.com/stretchr/testify/assert" + "github.com/sourcegraph/sourcegraph/internal/actor" + "github.com/sourcegraph/sourcegraph/lib/pointers" + "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" "github.com/sourcegraph/sourcegraph/internal/auth" "github.com/sourcegraph/sourcegraph/internal/database" @@ -41,11 +42,11 @@ func TestWebhookLogsArgs(t *testing.T) { "OnlyErrors false": { id: WebhookLogsUnmatchedExternalService, input: WebhookLogsArgs{ - OnlyErrors: boolPtr(false), + OnlyErrors: pointers.Ptr(false), }, want: database.WebhookLogListOpts{ Limit: 50, - ExternalServiceID: int64Ptr(0), + ExternalServiceID: pointers.Ptr(int64(0)), OnlyErrors: false, }, }, @@ -53,22 +54,22 @@ func TestWebhookLogsArgs(t *testing.T) { id: webhookLogsExternalServiceID(1), input: WebhookLogsArgs{ ConnectionArgs: graphqlutil.ConnectionArgs{ - First: int32Ptr(25), + First: pointers.Ptr(int32(25)), }, - After: stringPtr("40"), - OnlyErrors: boolPtr(true), - Since: timePtr(now), - Until: timePtr(later), - WebhookID: gqlIDPtr(webhookID), + After: pointers.Ptr("40"), + OnlyErrors: pointers.Ptr(true), + Since: pointers.Ptr(now), + Until: pointers.Ptr(later), + WebhookID: pointers.Ptr(webhookID), }, want: database.WebhookLogListOpts{ Limit: 25, Cursor: 40, - ExternalServiceID: int64Ptr(1), + ExternalServiceID: pointers.Ptr(int64(1)), OnlyErrors: true, - Since: timePtr(now), - Until: timePtr(later), - WebhookID: int32Ptr(123), + Since: pointers.Ptr(now), + Until: pointers.Ptr(later), + WebhookID: pointers.Ptr(int32(123)), }, }, } { @@ -155,7 +156,7 @@ func TestWebhookLogConnectionResolver(t *testing.T) { r := &WebhookLogConnectionResolver{ args: &WebhookLogsArgs{ ConnectionArgs: graphqlutil.ConnectionArgs{ - First: int32Ptr(20), + First: pointers.Ptr(int32(20)), }, }, externalServiceID: webhookLogsExternalServiceID(1), @@ -175,7 +176,7 @@ func TestWebhookLogConnectionResolver(t *testing.T) { mockassert.Values( mockassert.Skip, database.WebhookLogListOpts{ - ExternalServiceID: int64Ptr(1), + ExternalServiceID: pointers.Ptr(int64(1)), Limit: 20, }, ), @@ -188,7 +189,7 @@ func TestWebhookLogConnectionResolver(t *testing.T) { r := &WebhookLogConnectionResolver{ args: &WebhookLogsArgs{ ConnectionArgs: graphqlutil.ConnectionArgs{ - First: int32Ptr(20), + First: pointers.Ptr(int32(20)), }, }, externalServiceID: webhookLogsExternalServiceID(1), @@ -210,7 +211,7 @@ func TestWebhookLogConnectionResolver(t *testing.T) { mockassert.Values( mockassert.Skip, database.WebhookLogListOpts{ - ExternalServiceID: int64Ptr(1), + ExternalServiceID: pointers.Ptr(int64(1)), Limit: 20, }, ), @@ -224,7 +225,7 @@ func TestWebhookLogConnectionResolver(t *testing.T) { r := &WebhookLogConnectionResolver{ args: &WebhookLogsArgs{ ConnectionArgs: graphqlutil.ConnectionArgs{ - First: int32Ptr(20), + First: pointers.Ptr(int32(20)), }, }, externalServiceID: webhookLogsExternalServiceID(1), @@ -243,7 +244,7 @@ func TestWebhookLogConnectionResolver_TotalCount(t *testing.T) { r := &WebhookLogConnectionResolver{ args: &WebhookLogsArgs{ - OnlyErrors: boolPtr(true), + OnlyErrors: pointers.Ptr(true), }, externalServiceID: webhookLogsExternalServiceID(1), store: store, @@ -258,7 +259,7 @@ func TestWebhookLogConnectionResolver_TotalCount(t *testing.T) { mockassert.Values( mockassert.Skip, database.WebhookLogListOpts{ - ExternalServiceID: int64Ptr(1), + ExternalServiceID: pointers.Ptr(int64(1)), Limit: 50, OnlyErrors: true, }, @@ -273,7 +274,7 @@ func TestWebhookLogConnectionResolver_TotalCount(t *testing.T) { r := &WebhookLogConnectionResolver{ args: &WebhookLogsArgs{ - OnlyErrors: boolPtr(true), + OnlyErrors: pointers.Ptr(true), }, externalServiceID: webhookLogsExternalServiceID(1), store: store, @@ -291,14 +292,14 @@ func TestListWebhookLogs(t *testing.T) { ctx := actor.WithActor(context.Background(), &actor.Actor{UID: 1}) webhookLogsStore := database.NewMockWebhookLogStore() webhookLogs := []*types.WebhookLog{ - {ID: 1, WebhookID: int32Ptr(1), StatusCode: 200}, - {ID: 2, WebhookID: int32Ptr(1), StatusCode: 500}, - {ID: 3, WebhookID: int32Ptr(1), StatusCode: 200}, - {ID: 4, WebhookID: int32Ptr(2), StatusCode: 200}, - {ID: 5, WebhookID: int32Ptr(2), StatusCode: 200}, - {ID: 6, WebhookID: int32Ptr(2), StatusCode: 200}, - {ID: 7, WebhookID: int32Ptr(3), StatusCode: 500}, - {ID: 8, WebhookID: int32Ptr(3), StatusCode: 500}, + {ID: 1, WebhookID: pointers.Ptr(int32(1)), StatusCode: 200}, + {ID: 2, WebhookID: pointers.Ptr(int32(1)), StatusCode: 500}, + {ID: 3, WebhookID: pointers.Ptr(int32(1)), StatusCode: 200}, + {ID: 4, WebhookID: pointers.Ptr(int32(2)), StatusCode: 200}, + {ID: 5, WebhookID: pointers.Ptr(int32(2)), StatusCode: 200}, + {ID: 6, WebhookID: pointers.Ptr(int32(2)), StatusCode: 200}, + {ID: 7, WebhookID: pointers.Ptr(int32(3)), StatusCode: 500}, + {ID: 8, WebhookID: pointers.Ptr(int32(3)), StatusCode: 500}, } webhookLogsStore.ListFunc.SetDefaultHook(func(_ context.Context, options database.WebhookLogListOpts) ([]*types.WebhookLog, int64, error) { var logs []*types.WebhookLog @@ -418,11 +419,3 @@ func TestListWebhookLogs(t *testing.T) { }, }) } - -func boolPtr(v bool) *bool { return &v } -func intPtr(v int) *int { return &v } -func int32Ptr(v int32) *int32 { return &v } -func int64Ptr(v int64) *int64 { return &v } -func stringPtr(v string) *string { return &v } -func timePtr(v time.Time) *time.Time { return &v } -func gqlIDPtr(v graphql.ID) *graphql.ID { return &v } diff --git a/cmd/frontend/internal/app/updatecheck/BUILD.bazel b/cmd/frontend/internal/app/updatecheck/BUILD.bazel index 56a8b6c3505..9f4cb77e566 100644 --- a/cmd/frontend/internal/app/updatecheck/BUILD.bazel +++ b/cmd/frontend/internal/app/updatecheck/BUILD.bazel @@ -58,6 +58,7 @@ go_test( deps = [ "//internal/extsvc", "//internal/types", + "//lib/pointers", "//schema", "@com_github_google_go_cmp//cmp", "@com_github_hexops_autogold_v2//:autogold", diff --git a/cmd/frontend/internal/app/updatecheck/handler_test.go b/cmd/frontend/internal/app/updatecheck/handler_test.go index 5cb7433f050..7eb6b4d933d 100644 --- a/cmd/frontend/internal/app/updatecheck/handler_test.go +++ b/cmd/frontend/internal/app/updatecheck/handler_test.go @@ -13,6 +13,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/extsvc" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestLatestDockerVersionPushed(t *testing.T) { @@ -536,9 +537,9 @@ func TestSerializeCodeIntelUsage(t *testing.T) { testUsage, err := json.Marshal(types.NewCodeIntelUsageStatistics{ StartOfWeek: now, - WAUs: int32Ptr(25), - SearchBasedWAUs: int32Ptr(10), - PreciseCrossRepositoryWAUs: int32Ptr(40), + WAUs: pointers.Ptr(int32(25)), + SearchBasedWAUs: pointers.Ptr(int32(10)), + PreciseCrossRepositoryWAUs: pointers.Ptr(int32(40)), EventSummaries: []types.CodeIntelEventSummary{ { Action: types.HoverAction, @@ -589,28 +590,28 @@ func TestSerializeCodeIntelUsage(t *testing.T) { TotalActions: 3, }, }, - NumRepositories: int32Ptr(50 + 85), - NumRepositoriesWithUploadRecords: int32Ptr(50), - NumRepositoriesWithFreshUploadRecords: int32Ptr(40), - NumRepositoriesWithIndexRecords: int32Ptr(30), - NumRepositoriesWithFreshIndexRecords: int32Ptr(20), - NumRepositoriesWithAutoIndexConfigurationRecords: int32Ptr(7), + NumRepositories: pointers.Ptr(int32(50 + 85)), + NumRepositoriesWithUploadRecords: pointers.Ptr(int32(50)), + NumRepositoriesWithFreshUploadRecords: pointers.Ptr(int32(40)), + NumRepositoriesWithIndexRecords: pointers.Ptr(int32(30)), + NumRepositoriesWithFreshIndexRecords: pointers.Ptr(int32(20)), + NumRepositoriesWithAutoIndexConfigurationRecords: pointers.Ptr(int32(7)), CountsByLanguage: map[string]types.CodeIntelRepositoryCountsByLanguage{ "go": { - NumRepositoriesWithUploadRecords: int32Ptr(10), - NumRepositoriesWithFreshUploadRecords: int32Ptr(20), - NumRepositoriesWithIndexRecords: int32Ptr(30), - NumRepositoriesWithFreshIndexRecords: int32Ptr(40), + NumRepositoriesWithUploadRecords: pointers.Ptr(int32(10)), + NumRepositoriesWithFreshUploadRecords: pointers.Ptr(int32(20)), + NumRepositoriesWithIndexRecords: pointers.Ptr(int32(30)), + NumRepositoriesWithFreshIndexRecords: pointers.Ptr(int32(40)), }, "typescript": { - NumRepositoriesWithUploadRecords: int32Ptr(15), - NumRepositoriesWithFreshUploadRecords: int32Ptr(25), - NumRepositoriesWithIndexRecords: int32Ptr(35), - NumRepositoriesWithFreshIndexRecords: int32Ptr(45), + NumRepositoriesWithUploadRecords: pointers.Ptr(int32(15)), + NumRepositoriesWithFreshUploadRecords: pointers.Ptr(int32(25)), + NumRepositoriesWithIndexRecords: pointers.Ptr(int32(35)), + NumRepositoriesWithFreshIndexRecords: pointers.Ptr(int32(45)), }, }, - SettingsPageViewCount: int32Ptr(1489), - UsersWithRefPanelRedesignEnabled: int32Ptr(46), + SettingsPageViewCount: pointers.Ptr(int32(1489)), + UsersWithRefPanelRedesignEnabled: pointers.Ptr(int32(46)), LanguageRequests: []types.LanguageRequest{ { LanguageID: "frob", @@ -799,16 +800,16 @@ func TestSerializeOldCodeIntelUsage(t *testing.T) { testPeriod, err := json.Marshal(&types.OldCodeIntelUsagePeriod{ StartTime: now, Hover: &types.OldCodeIntelEventCategoryStatistics{ - LSIF: &types.OldCodeIntelEventStatistics{UsersCount: 1, EventsCount: int32Ptr(1)}, - Search: &types.OldCodeIntelEventStatistics{UsersCount: 2, EventsCount: int32Ptr(2)}, + LSIF: &types.OldCodeIntelEventStatistics{UsersCount: 1, EventsCount: pointers.Ptr(int32(1))}, + Search: &types.OldCodeIntelEventStatistics{UsersCount: 2, EventsCount: pointers.Ptr(int32(2))}, }, Definitions: &types.OldCodeIntelEventCategoryStatistics{ - LSIF: &types.OldCodeIntelEventStatistics{UsersCount: 3, EventsCount: int32Ptr(3)}, - Search: &types.OldCodeIntelEventStatistics{UsersCount: 4, EventsCount: int32Ptr(4)}, + LSIF: &types.OldCodeIntelEventStatistics{UsersCount: 3, EventsCount: pointers.Ptr(int32(3))}, + Search: &types.OldCodeIntelEventStatistics{UsersCount: 4, EventsCount: pointers.Ptr(int32(4))}, }, References: &types.OldCodeIntelEventCategoryStatistics{ - LSIF: &types.OldCodeIntelEventStatistics{UsersCount: 5, EventsCount: int32Ptr(1)}, - Search: &types.OldCodeIntelEventStatistics{UsersCount: 6, EventsCount: int32Ptr(3)}, + LSIF: &types.OldCodeIntelEventStatistics{UsersCount: 5, EventsCount: pointers.Ptr(int32(1))}, + Search: &types.OldCodeIntelEventStatistics{UsersCount: 6, EventsCount: pointers.Ptr(int32(3))}, }, }) if err != nil { @@ -1243,7 +1244,3 @@ func compareJSON(t *testing.T, actual []byte, expected string) { t.Fatalf("mismatch (-want +got):\n%s", diff) } } - -func int32Ptr(v int32) *int32 { - return &v -} diff --git a/cmd/frontend/internal/search/BUILD.bazel b/cmd/frontend/internal/search/BUILD.bazel index bb7d968220c..c1e0c6d28b0 100644 --- a/cmd/frontend/internal/search/BUILD.bazel +++ b/cmd/frontend/internal/search/BUILD.bazel @@ -34,6 +34,7 @@ go_library( "//internal/trace", "//internal/types", "//lib/errors", + "//lib/pointers", "@com_github_inconshreveable_log15//:log15", "@com_github_prometheus_client_golang//prometheus", "@com_github_prometheus_client_golang//prometheus/promauto", diff --git a/cmd/frontend/internal/search/search.go b/cmd/frontend/internal/search/search.go index 70467ba2f71..19424293a54 100644 --- a/cmd/frontend/internal/search/search.go +++ b/cmd/frontend/internal/search/search.go @@ -36,6 +36,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/trace" "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) // StreamHandler is an http handler which streams back search results. @@ -101,7 +102,7 @@ func (h *streamHandler) serveHTTP(r *http.Request, tr *trace.Trace, eventWriter inputs, err := h.searchClient.Plan( ctx, args.Version, - strPtr(args.PatternType), + pointers.NonZeroPtr(args.PatternType), args.Query, search.Mode(args.SearchMode), search.Streaming, @@ -257,13 +258,6 @@ func parseURLQuery(q url.Values) (*args, error) { return &a, nil } -func strPtr(s string) *string { - if s == "" { - return nil - } - return &s -} - func fromMatch(match result.Match, repoCache map[api.RepoID]*types.SearchedRepo, enableChunkMatches bool) streamhttp.EventMatch { switch v := match.(type) { case *result.FileMatch: diff --git a/cmd/frontend/webhooks/BUILD.bazel b/cmd/frontend/webhooks/BUILD.bazel index 538ea53ecf9..1f3fc3f3633 100644 --- a/cmd/frontend/webhooks/BUILD.bazel +++ b/cmd/frontend/webhooks/BUILD.bazel @@ -63,6 +63,7 @@ go_test( "//internal/extsvc/gitlab/webhooks", "//internal/types", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_derision_test_go_mockgen//testutil/assert", "@com_github_google_go_github_v43//github", diff --git a/cmd/frontend/webhooks/middleware_test.go b/cmd/frontend/webhooks/middleware_test.go index 6f004e9d92c..8487d0ce837 100644 --- a/cmd/frontend/webhooks/middleware_test.go +++ b/cmd/frontend/webhooks/middleware_test.go @@ -13,6 +13,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/conf" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -49,7 +50,7 @@ func TestLogMiddleware(t *testing.T) { t.Run("logging disabled", func(t *testing.T) { conf.Mock(&conf.Unified{SiteConfiguration: schema.SiteConfiguration{ - WebhookLogging: &schema.WebhookLogging{Enabled: boolPtr(false)}, + WebhookLogging: &schema.WebhookLogging{Enabled: pointers.Ptr(false)}, }}) defer conf.Mock(nil) @@ -141,7 +142,7 @@ func TestLoggingEnabled(t *testing.T) { }, }, WebhookLogging: &schema.WebhookLogging{ - Enabled: boolPtr(false), + Enabled: pointers.Ptr(false), }, }}, want: false, @@ -156,7 +157,7 @@ func TestLoggingEnabled(t *testing.T) { }, }, WebhookLogging: &schema.WebhookLogging{ - Enabled: boolPtr(true), + Enabled: pointers.Ptr(true), }, }}, want: true, @@ -164,7 +165,7 @@ func TestLoggingEnabled(t *testing.T) { "no encryption; explicit webhook false": { c: &conf.Unified{SiteConfiguration: schema.SiteConfiguration{ WebhookLogging: &schema.WebhookLogging{ - Enabled: boolPtr(false), + Enabled: pointers.Ptr(false), }, }}, want: false, @@ -172,7 +173,7 @@ func TestLoggingEnabled(t *testing.T) { "no encryption; explicit webhook true": { c: &conf.Unified{SiteConfiguration: schema.SiteConfiguration{ WebhookLogging: &schema.WebhookLogging{ - Enabled: boolPtr(true), + Enabled: pointers.Ptr(true), }, }}, want: true, @@ -183,5 +184,3 @@ func TestLoggingEnabled(t *testing.T) { }) } } - -func boolPtr(v bool) *bool { return &v } diff --git a/dev/internal/cmd/search-plan/BUILD.bazel b/dev/internal/cmd/search-plan/BUILD.bazel index b38aca83125..f1c432b1bd0 100644 --- a/dev/internal/cmd/search-plan/BUILD.bazel +++ b/dev/internal/cmd/search-plan/BUILD.bazel @@ -15,6 +15,7 @@ go_library( "//internal/search/job/jobutil", "//internal/search/job/printer", "//lib/errors", + "//lib/pointers", "@com_github_sourcegraph_log//:log", ], ) diff --git a/dev/internal/cmd/search-plan/search-plan.go b/dev/internal/cmd/search-plan/search-plan.go index 174a26c5d59..c9100ccefb8 100644 --- a/dev/internal/cmd/search-plan/search-plan.go +++ b/dev/internal/cmd/search-plan/search-plan.go @@ -18,6 +18,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/search/job/jobutil" "github.com/sourcegraph/sourcegraph/internal/search/job/printer" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func run(w io.Writer, args []string) error { @@ -50,7 +51,7 @@ func run(w io.Writer, args []string) error { inputs, err := cli.Plan( context.Background(), *version, - strPtr(*patternType), + pointers.NonZeroPtr(*patternType), query, mode, search.Streaming, @@ -81,10 +82,3 @@ func main() { os.Exit(1) } } - -func strPtr(s string) *string { - if s == "" { - return nil - } - return &s -} diff --git a/enterprise/cmd/frontend/internal/authz/resolvers/BUILD.bazel b/enterprise/cmd/frontend/internal/authz/resolvers/BUILD.bazel index 6b5fcfcb2f5..0a5848a4765 100644 --- a/enterprise/cmd/frontend/internal/authz/resolvers/BUILD.bazel +++ b/enterprise/cmd/frontend/internal/authz/resolvers/BUILD.bazel @@ -35,6 +35,7 @@ go_library( "//internal/repoupdater/protocol", "//internal/types", "//lib/errors", + "//lib/pointers", "@com_github_graph_gophers_graphql_go//:graphql-go", "@com_github_graph_gophers_graphql_go//relay", "@com_github_sourcegraph_log//:log", @@ -72,6 +73,7 @@ go_test( "//internal/timeutil", "//internal/types", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_google_go_cmp//cmp", "@com_github_graph_gophers_graphql_go//:graphql-go", diff --git a/enterprise/cmd/frontend/internal/authz/resolvers/permissions_sync_jobs.go b/enterprise/cmd/frontend/internal/authz/resolvers/permissions_sync_jobs.go index d2c18f675c2..225cc8688a7 100644 --- a/enterprise/cmd/frontend/internal/authz/resolvers/permissions_sync_jobs.go +++ b/enterprise/cmd/frontend/internal/authz/resolvers/permissions_sync_jobs.go @@ -6,6 +6,7 @@ import ( "github.com/graph-gophers/graphql-go" "github.com/graph-gophers/graphql-go/relay" + "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" "github.com/sourcegraph/sourcegraph/internal/api" @@ -13,6 +14,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/gitserver" "github.com/sourcegraph/sourcegraph/internal/gqlutil" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) const permissionsSyncJobIDKind = "PermissionsSyncJob" @@ -329,6 +331,5 @@ func unmarshalPermissionsSyncJobID(id graphql.ID) (jobID int, err error) { } func intToInt32Ptr(value int) *int32 { - int32Value := int32(value) - return &int32Value + return pointers.Ptr(int32(value)) } diff --git a/enterprise/cmd/frontend/internal/authz/resolvers/resolver_test.go b/enterprise/cmd/frontend/internal/authz/resolvers/resolver_test.go index 731bc232537..a025d36bcfb 100644 --- a/enterprise/cmd/frontend/internal/authz/resolvers/resolver_test.go +++ b/enterprise/cmd/frontend/internal/authz/resolvers/resolver_test.go @@ -37,6 +37,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/timeutil" "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -1870,16 +1871,16 @@ query { db.UsersFunc.SetDefaultReturn(users) bbProjects := database.NewMockBitbucketProjectPermissionsStore() - entry := executor.ExecutionLogEntry{Key: "key", Command: []string{"command"}, StartTime: mustParseTime("2020-01-06"), ExitCode: intPtr(1), Out: "out", DurationMs: intPtr(1)} + entry := executor.ExecutionLogEntry{Key: "key", Command: []string{"command"}, StartTime: mustParseTime("2020-01-06"), ExitCode: pointers.Ptr(1), Out: "out", DurationMs: pointers.Ptr(1)} bbProjects.ListJobsFunc.SetDefaultReturn([]*types.BitbucketProjectPermissionJob{ { ID: 1, State: "queued", - FailureMessage: stringPtr("failure massage"), + FailureMessage: pointers.Ptr("failure massage"), QueuedAt: mustParseTime("2020-01-01"), - StartedAt: timePtr(mustParseTime("2020-01-01")), - FinishedAt: timePtr(mustParseTime("2020-01-01")), - ProcessAfter: timePtr(mustParseTime("2020-01-01")), + StartedAt: pointers.Ptr(mustParseTime("2020-01-01")), + FinishedAt: pointers.Ptr(mustParseTime("2020-01-01")), + ProcessAfter: pointers.Ptr(mustParseTime("2020-01-01")), NumResets: 1, NumFailures: 2, LastHeartbeatAt: mustParseTime("2020-01-05"), @@ -2598,10 +2599,6 @@ func mustParseTime(v string) time.Time { return t } -func intPtr(v int) *int { return &v } -func timePtr(v time.Time) *time.Time { return &v } -func stringPtr(v string) *string { return &v } - func TestResolver_PermissionsSyncingStats(t *testing.T) { t.Run("authenticated as non-admin", func(t *testing.T) { user := &types.User{ID: 42} diff --git a/enterprise/cmd/frontend/internal/batches/resolvers/BUILD.bazel b/enterprise/cmd/frontend/internal/batches/resolvers/BUILD.bazel index b3939f435dd..607edf52110 100644 --- a/enterprise/cmd/frontend/internal/batches/resolvers/BUILD.bazel +++ b/enterprise/cmd/frontend/internal/batches/resolvers/BUILD.bazel @@ -164,6 +164,7 @@ go_test( "//lib/batches/schema", "//lib/batches/yaml", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_google_go_cmp//cmp", "@com_github_graph_gophers_graphql_go//:graphql-go", diff --git a/enterprise/cmd/frontend/internal/batches/resolvers/batch_spec_workspace_resolution_test.go b/enterprise/cmd/frontend/internal/batches/resolvers/batch_spec_workspace_resolution_test.go index 23919adaac5..4f4e098f7f5 100644 --- a/enterprise/cmd/frontend/internal/batches/resolvers/batch_spec_workspace_resolution_test.go +++ b/enterprise/cmd/frontend/internal/batches/resolvers/batch_spec_workspace_resolution_test.go @@ -9,6 +9,7 @@ import ( "github.com/sourcegraph/sourcegraph/enterprise/internal/batches/search" "github.com/sourcegraph/sourcegraph/enterprise/internal/batches/store" "github.com/sourcegraph/sourcegraph/enterprise/internal/batches/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestWorkspacesListArgsToDBOpts(t *testing.T) { @@ -33,7 +34,7 @@ func TestWorkspacesListArgsToDBOpts(t *testing.T) { { name: "after set", args: &graphqlbackend.ListWorkspacesArgs{ - After: strPtr("10"), + After: pointers.Ptr("10"), }, want: store.ListBatchSpecWorkspacesOpts{ Cursor: 10, @@ -42,7 +43,7 @@ func TestWorkspacesListArgsToDBOpts(t *testing.T) { { name: "search set", args: &graphqlbackend.ListWorkspacesArgs{ - Search: strPtr("sourcegraph"), + Search: pointers.Ptr("sourcegraph"), }, want: store.ListBatchSpecWorkspacesOpts{ TextSearch: []search.TextSearchTerm{{Term: "sourcegraph"}}, @@ -51,7 +52,7 @@ func TestWorkspacesListArgsToDBOpts(t *testing.T) { { name: "state completed", args: &graphqlbackend.ListWorkspacesArgs{ - State: strPtr("COMPLETED"), + State: pointers.Ptr("COMPLETED"), }, want: store.ListBatchSpecWorkspacesOpts{ OnlyCachedOrCompleted: true, @@ -60,7 +61,7 @@ func TestWorkspacesListArgsToDBOpts(t *testing.T) { { name: "state pending", args: &graphqlbackend.ListWorkspacesArgs{ - State: strPtr("PENDING"), + State: pointers.Ptr("PENDING"), }, want: store.ListBatchSpecWorkspacesOpts{ OnlyWithoutExecutionAndNotCached: true, @@ -69,7 +70,7 @@ func TestWorkspacesListArgsToDBOpts(t *testing.T) { { name: "state queued", args: &graphqlbackend.ListWorkspacesArgs{ - State: strPtr("QUEUED"), + State: pointers.Ptr("QUEUED"), }, want: store.ListBatchSpecWorkspacesOpts{ State: types.BatchSpecWorkspaceExecutionJobStateQueued, diff --git a/enterprise/cmd/frontend/internal/batches/resolvers/bulk_operation_test.go b/enterprise/cmd/frontend/internal/batches/resolvers/bulk_operation_test.go index 1dc26fa9072..4868befd128 100644 --- a/enterprise/cmd/frontend/internal/batches/resolvers/bulk_operation_test.go +++ b/enterprise/cmd/frontend/internal/batches/resolvers/bulk_operation_test.go @@ -19,6 +19,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/internal/timeutil" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestBulkOperationResolver(t *testing.T) { @@ -69,7 +70,7 @@ func TestBulkOperationResolver(t *testing.T) { JobType: btypes.ChangesetJobTypeComment, Payload: btypes.ChangesetJobCommentPayload{Message: "test"}, State: btypes.ChangesetJobStateFailed, - FailureMessage: strPtr(errorMsg), + FailureMessage: pointers.Ptr(errorMsg), StartedAt: now, FinishedAt: now, }, @@ -93,7 +94,7 @@ func TestBulkOperationResolver(t *testing.T) { JobType: btypes.ChangesetJobTypeComment, Payload: btypes.ChangesetJobCommentPayload{Message: "test"}, State: btypes.ChangesetJobStateFailed, - FailureMessage: strPtr(errorMsg), + FailureMessage: pointers.Ptr(errorMsg), StartedAt: now, FinishedAt: now, }, @@ -116,7 +117,7 @@ func TestBulkOperationResolver(t *testing.T) { Errors: []*apitest.ChangesetJobError{ { Changeset: &apitest.Changeset{ID: string(bgql.MarshalChangesetID(changeset1.ID))}, - Error: strPtr(errorMsg), + Error: pointers.Ptr(errorMsg), }, { Changeset: &apitest.Changeset{ID: string(bgql.MarshalChangesetID(changeset3.ID))}, diff --git a/enterprise/cmd/frontend/internal/batches/resolvers/changeset_apply_preview_connection_test.go b/enterprise/cmd/frontend/internal/batches/resolvers/changeset_apply_preview_connection_test.go index fa5eda46b5e..34035469bc6 100644 --- a/enterprise/cmd/frontend/internal/batches/resolvers/changeset_apply_preview_connection_test.go +++ b/enterprise/cmd/frontend/internal/batches/resolvers/changeset_apply_preview_connection_test.go @@ -7,9 +7,11 @@ import ( "time" "github.com/google/go-cmp/cmp" - "github.com/sourcegraph/sourcegraph/internal/gitserver" "github.com/stretchr/testify/assert" + "github.com/sourcegraph/sourcegraph/internal/gitserver" + "github.com/sourcegraph/sourcegraph/lib/pointers" + "github.com/sourcegraph/log/logtest" "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" @@ -186,9 +188,6 @@ func TestRewirerMappings(t *testing.T) { rw.resolvers[mapping] = resolver } - opPtr := func(op btypes.ReconcilerOperation) *btypes.ReconcilerOperation { - return &op - } ctx := context.Background() t.Run("Page", func(t *testing.T) { @@ -296,7 +295,7 @@ func TestRewirerMappings(t *testing.T) { }, "non-existent op": { opts: rewirerMappingPageOpts{ - Op: opPtr(btypes.ReconcilerOperationClose), + Op: pointers.Ptr(btypes.ReconcilerOperationClose), }, want: rewirerMappingPage{ Mappings: btypes.RewirerMappings{}, @@ -305,7 +304,7 @@ func TestRewirerMappings(t *testing.T) { }, "extant op, no limit": { opts: rewirerMappingPageOpts{ - Op: opPtr(btypes.ReconcilerOperationPublish), + Op: pointers.Ptr(btypes.ReconcilerOperationPublish), }, want: rewirerMappingPage{ Mappings: btypes.RewirerMappings{publishA, publishB}, @@ -315,7 +314,7 @@ func TestRewirerMappings(t *testing.T) { "extant op, high limit": { opts: rewirerMappingPageOpts{ LimitOffset: &database.LimitOffset{Limit: 5}, - Op: opPtr(btypes.ReconcilerOperationPublish), + Op: pointers.Ptr(btypes.ReconcilerOperationPublish), }, want: rewirerMappingPage{ Mappings: btypes.RewirerMappings{publishA, publishB}, @@ -325,7 +324,7 @@ func TestRewirerMappings(t *testing.T) { "extant op, low limit": { opts: rewirerMappingPageOpts{ LimitOffset: &database.LimitOffset{Limit: 1}, - Op: opPtr(btypes.ReconcilerOperationPublish), + Op: pointers.Ptr(btypes.ReconcilerOperationPublish), }, want: rewirerMappingPage{ Mappings: btypes.RewirerMappings{publishA}, @@ -335,7 +334,7 @@ func TestRewirerMappings(t *testing.T) { "extant op, low limit and offset": { opts: rewirerMappingPageOpts{ LimitOffset: &database.LimitOffset{Limit: 1, Offset: 1}, - Op: opPtr(btypes.ReconcilerOperationPublish), + Op: pointers.Ptr(btypes.ReconcilerOperationPublish), }, want: rewirerMappingPage{ Mappings: btypes.RewirerMappings{publishB}, @@ -374,7 +373,7 @@ func TestRewirerMappings(t *testing.T) { }) if _, err := rmf.Page(ctx, rewirerMappingPageOpts{ - Op: opPtr(btypes.ReconcilerOperationClose), + Op: pointers.Ptr(btypes.ReconcilerOperationClose), }); err == nil { t.Error("unexpected nil error") } diff --git a/enterprise/cmd/frontend/internal/batches/resolvers/main_test.go b/enterprise/cmd/frontend/internal/batches/resolvers/main_test.go index 3179d8ac6d2..03f7dee9b92 100644 --- a/enterprise/cmd/frontend/internal/batches/resolvers/main_test.go +++ b/enterprise/cmd/frontend/internal/batches/resolvers/main_test.go @@ -247,7 +247,3 @@ func pruneSiteCredentials(t *testing.T, bstore *store.Store) { } } } - -func strPtr(s string) *string { - return &s -} diff --git a/enterprise/cmd/frontend/internal/batches/resolvers/resolver_test.go b/enterprise/cmd/frontend/internal/batches/resolvers/resolver_test.go index 04153554ac0..471e8650101 100644 --- a/enterprise/cmd/frontend/internal/batches/resolvers/resolver_test.go +++ b/enterprise/cmd/frontend/internal/batches/resolvers/resolver_test.go @@ -43,6 +43,7 @@ import ( batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/batches/overridable" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestNullIDResilience(t *testing.T) { @@ -1643,7 +1644,7 @@ func TestListChangesetOptsFromArgs(t *testing.T) { haveCheckStates := []string{"PENDING", "INVALID"} wantReviewStates := []btypes.ChangesetReviewState{"APPROVED", "INVALID"} wantCheckStates := []btypes.ChangesetCheckState{"PENDING", "INVALID"} - truePtr := func() *bool { val := true; return &val }() + truePtr := pointers.Ptr(true) wantSearches := []search.TextSearchTerm{{Term: "foo"}, {Term: "bar", Not: true}} var batchChangeID int64 = 1 var repoID api.RepoID = 123 @@ -1674,7 +1675,7 @@ func TestListChangesetOptsFromArgs(t *testing.T) { // Setting state is safe and transferred to opts. { args: &graphqlbackend.ListChangesetsArgs{ - State: stringPtr(string(haveStates[0])), + State: pointers.Ptr(string(haveStates[0])), }, wantSafe: true, wantParsed: store.ListChangesetsOpts{ @@ -1684,7 +1685,7 @@ func TestListChangesetOptsFromArgs(t *testing.T) { // Setting invalid state fails. { args: &graphqlbackend.ListChangesetsArgs{ - State: stringPtr(string(haveStates[1])), + State: pointers.Ptr(string(haveStates[1])), }, wantErr: "changeset state not valid", }, @@ -1732,7 +1733,7 @@ func TestListChangesetOptsFromArgs(t *testing.T) { // Setting a positive search. { args: &graphqlbackend.ListChangesetsArgs{ - Search: stringPtr("foo"), + Search: pointers.Ptr("foo"), }, wantSafe: false, wantParsed: store.ListChangesetsOpts{ @@ -1742,7 +1743,7 @@ func TestListChangesetOptsFromArgs(t *testing.T) { // Setting a negative search. { args: &graphqlbackend.ListChangesetsArgs{ - Search: stringPtr("-bar"), + Search: pointers.Ptr("-bar"), }, wantSafe: false, wantParsed: store.ListChangesetsOpts{ @@ -2888,8 +2889,6 @@ query($includeLocallyExecutedSpecs: Boolean!) { } ` -func stringPtr(s string) *string { return &s } - func assignBatchChangesWritePermissionToUser(ctx context.Context, t *testing.T, db database.DB, userID int32) (*types.Role, *types.Permission) { role := bt.CreateTestRole(ctx, t, db, "TEST-ROLE-1") bt.AssignRoleToUser(ctx, t, db, userID, role.ID) diff --git a/enterprise/cmd/frontend/internal/codemonitors/resolvers/BUILD.bazel b/enterprise/cmd/frontend/internal/codemonitors/resolvers/BUILD.bazel index 4493ad30d4b..93f43f155ae 100644 --- a/enterprise/cmd/frontend/internal/codemonitors/resolvers/BUILD.bazel +++ b/enterprise/cmd/frontend/internal/codemonitors/resolvers/BUILD.bazel @@ -19,6 +19,7 @@ go_library( "//internal/httpcli", "//internal/search/job/jobutil", "//lib/errors", + "//lib/pointers", "@com_github_graph_gophers_graphql_go//:graphql-go", "@com_github_graph_gophers_graphql_go//relay", "@com_github_sourcegraph_log//:log", diff --git a/enterprise/cmd/frontend/internal/codemonitors/resolvers/resolvers.go b/enterprise/cmd/frontend/internal/codemonitors/resolvers/resolvers.go index 225bee73e52..9a410dd6662 100644 --- a/enterprise/cmd/frontend/internal/codemonitors/resolvers/resolvers.go +++ b/enterprise/cmd/frontend/internal/codemonitors/resolvers/resolvers.go @@ -21,6 +21,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/httpcli" "github.com/sourcegraph/sourcegraph/internal/search/job/jobutil" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) // NewResolver returns a new Resolver that uses the given database @@ -71,7 +72,7 @@ func (r *Resolver) Monitors(ctx context.Context, userID int32, args *graphqlback ms, err := r.db.CodeMonitors().ListMonitors(ctx, edb.ListMonitorsOpts{ UserID: &userID, - First: intPtr(int(newArgs.First)), + First: pointers.Ptr(int(newArgs.First)), After: intPtrToInt64Ptr(after), }) if err != nil { @@ -890,7 +891,7 @@ func (q *monitorQuery) Events(ctx context.Context, args *graphqlbackend.ListEven } es, err := q.db.CodeMonitors().ListQueryTriggerJobs(ctx, edb.ListTriggerJobsOpts{ QueryID: &q.QueryTrigger.ID, - First: intPtr(int(args.First)), + First: pointers.Ptr(int(args.First)), After: intPtrToInt64Ptr(after), }) if err != nil { @@ -1063,7 +1064,7 @@ func (m *monitorEmail) Recipients(ctx context.Context, args *graphqlbackend.List } ms, err := m.db.CodeMonitors().ListRecipients(ctx, edb.ListRecipientsOpts{ EmailID: &m.EmailAction.ID, - First: intPtr(int(args.First)), + First: pointers.Ptr(int(args.First)), After: intPtrToInt64Ptr(after), }) if err != nil { @@ -1125,9 +1126,9 @@ func (m *monitorEmail) Events(ctx context.Context, args *graphqlbackend.ListEven } ajs, err := m.db.CodeMonitors().ListActionJobs(ctx, edb.ListActionJobsOpts{ - EmailID: intPtr(int(m.EmailAction.ID)), + EmailID: pointers.Ptr(int(m.EmailAction.ID)), TriggerEventID: m.triggerEventID, - First: intPtr(int(args.First)), + First: pointers.Ptr(int(args.First)), After: after, }) if err != nil { @@ -1135,7 +1136,7 @@ func (m *monitorEmail) Events(ctx context.Context, args *graphqlbackend.ListEven } totalCount, err := m.db.CodeMonitors().CountActionJobs(ctx, edb.ListActionJobsOpts{ - EmailID: intPtr(int(m.EmailAction.ID)), + EmailID: pointers.Ptr(int(m.EmailAction.ID)), TriggerEventID: m.triggerEventID, }) if err != nil { @@ -1181,9 +1182,9 @@ func (m *monitorWebhook) Events(ctx context.Context, args *graphqlbackend.ListEv } ajs, err := m.db.CodeMonitors().ListActionJobs(ctx, edb.ListActionJobsOpts{ - WebhookID: intPtr(int(m.WebhookAction.ID)), + WebhookID: pointers.Ptr(int(m.WebhookAction.ID)), TriggerEventID: m.triggerEventID, - First: intPtr(int(args.First)), + First: pointers.Ptr(int(args.First)), After: after, }) if err != nil { @@ -1191,7 +1192,7 @@ func (m *monitorWebhook) Events(ctx context.Context, args *graphqlbackend.ListEv } totalCount, err := m.db.CodeMonitors().CountActionJobs(ctx, edb.ListActionJobsOpts{ - WebhookID: intPtr(int(m.WebhookAction.ID)), + WebhookID: pointers.Ptr(int(m.WebhookAction.ID)), TriggerEventID: m.triggerEventID, }) if err != nil { @@ -1237,9 +1238,9 @@ func (m *monitorSlackWebhook) Events(ctx context.Context, args *graphqlbackend.L } ajs, err := m.db.CodeMonitors().ListActionJobs(ctx, edb.ListActionJobsOpts{ - SlackWebhookID: intPtr(int(m.SlackWebhookAction.ID)), + SlackWebhookID: pointers.Ptr(int(m.SlackWebhookAction.ID)), TriggerEventID: m.triggerEventID, - First: intPtr(int(args.First)), + First: pointers.Ptr(int(args.First)), After: after, }) if err != nil { @@ -1247,7 +1248,7 @@ func (m *monitorSlackWebhook) Events(ctx context.Context, args *graphqlbackend.L } totalCount, err := m.db.CodeMonitors().CountActionJobs(ctx, edb.ListActionJobsOpts{ - SlackWebhookID: intPtr(int(m.SlackWebhookAction.ID)), + SlackWebhookID: pointers.Ptr(int(m.SlackWebhookAction.ID)), TriggerEventID: m.triggerEventID, }) if err != nil { @@ -1260,7 +1261,6 @@ func (m *monitorSlackWebhook) Events(ctx context.Context, args *graphqlbackend.L return &monitorActionEventConnection{events: events, totalCount: int32(totalCount)}, nil } -func intPtr(i int) *int { return &i } func intPtrToInt64Ptr(i *int) *int64 { if i == nil { return nil diff --git a/enterprise/cmd/frontend/internal/dotcom/productsubscription/BUILD.bazel b/enterprise/cmd/frontend/internal/dotcom/productsubscription/BUILD.bazel index 44ba072f0d6..024f5a7e581 100644 --- a/enterprise/cmd/frontend/internal/dotcom/productsubscription/BUILD.bazel +++ b/enterprise/cmd/frontend/internal/dotcom/productsubscription/BUILD.bazel @@ -45,6 +45,7 @@ go_library( "//internal/slack", "//internal/types", "//lib/errors", + "//lib/pointers", "@com_github_derision_test_glock//:glock", "@com_github_gomodule_redigo//redis", "@com_github_google_uuid//:uuid", @@ -99,6 +100,7 @@ go_test( "//internal/timeutil", "//internal/types", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_derision_test_glock//:glock", "@com_github_gomodule_redigo//redis", diff --git a/enterprise/cmd/frontend/internal/dotcom/productsubscription/codygateway_dotcom_user.go b/enterprise/cmd/frontend/internal/dotcom/productsubscription/codygateway_dotcom_user.go index 8e9d9c62d9a..9b12adb12d1 100644 --- a/enterprise/cmd/frontend/internal/dotcom/productsubscription/codygateway_dotcom_user.go +++ b/enterprise/cmd/frontend/internal/dotcom/productsubscription/codygateway_dotcom_user.go @@ -14,6 +14,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/errcode" dbtypes "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) type ErrDotcomUserNotFound struct { @@ -179,18 +180,18 @@ func getCompletionsRateLimit(ctx context.Context, db database.DB, userID int32, switch scope { case types.CompletionsFeatureChat: if cfg.Completions != nil && cfg.Completions.PerUserDailyLimit > 0 { - limit = iPtr(cfg.Completions.PerUserDailyLimit) + limit = pointers.Ptr(cfg.Completions.PerUserDailyLimit) } case types.CompletionsFeatureCode: if cfg.Completions != nil && cfg.Completions.PerUserCodeCompletionsDailyLimit > 0 { - limit = iPtr(cfg.Completions.PerUserCodeCompletionsDailyLimit) + limit = pointers.Ptr(cfg.Completions.PerUserCodeCompletionsDailyLimit) } default: return licensing.CodyGatewayRateLimit{}, graphqlbackend.CodyGatewayRateLimitSourcePlan, errors.Newf("unknown scope: %s", scope) } } if limit == nil { - limit = iPtr(0) + limit = pointers.Ptr(0) } return licensing.CodyGatewayRateLimit{ AllowedModels: allowedModels(scope), @@ -209,7 +210,3 @@ func allowedModels(scope types.CompletionsFeature) []string { return []string{} } } - -func iPtr(i int) *int { - return &i -} diff --git a/enterprise/cmd/frontend/internal/dotcom/productsubscription/codygateway_dotcom_user_test.go b/enterprise/cmd/frontend/internal/dotcom/productsubscription/codygateway_dotcom_user_test.go index 7afae4e5ff6..69713ed6ca9 100644 --- a/enterprise/cmd/frontend/internal/dotcom/productsubscription/codygateway_dotcom_user_test.go +++ b/enterprise/cmd/frontend/internal/dotcom/productsubscription/codygateway_dotcom_user_test.go @@ -21,6 +21,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/featureflag" "github.com/sourcegraph/sourcegraph/internal/hashutil" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -59,9 +60,9 @@ func TestCodyGatewayDotcomUserResolver(t *testing.T) { // User with rate limit overrides overrideUser, err := db.Users().Create(ctx, database.NewUser{Username: "override", EmailIsVerified: true, Email: "override@test.com"}) require.NoError(t, err) - err = db.Users().SetChatCompletionsQuota(context.Background(), overrideUser.ID, iPtr(chatOverrideLimit)) + err = db.Users().SetChatCompletionsQuota(context.Background(), overrideUser.ID, pointers.Ptr(chatOverrideLimit)) require.NoError(t, err) - err = db.Users().SetCodeCompletionsQuota(context.Background(), overrideUser.ID, iPtr(codeOverrideLimit)) + err = db.Users().SetCodeCompletionsQuota(context.Background(), overrideUser.ID, pointers.Ptr(codeOverrideLimit)) require.NoError(t, err) tests := []struct { @@ -218,10 +219,6 @@ func TestCodyGatewayDotcomUserResolverRequestAccess(t *testing.T) { } } -func iPtr(i int) *int { - return &i -} - func makeGatewayToken(apiToken string) string { tokenBytes, _ := hex.DecodeString(strings.TrimPrefix(apiToken, "sgp_")) return "sgd_" + hex.EncodeToString(hashutil.ToSHA256Bytes(hashutil.ToSHA256Bytes(tokenBytes))) diff --git a/enterprise/cmd/frontend/internal/dotcom/productsubscription/license_anomaly.go b/enterprise/cmd/frontend/internal/dotcom/productsubscription/license_anomaly.go index 1737d8aed8d..6acdd7bbc2b 100644 --- a/enterprise/cmd/frontend/internal/dotcom/productsubscription/license_anomaly.go +++ b/enterprise/cmd/frontend/internal/dotcom/productsubscription/license_anomaly.go @@ -18,6 +18,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/redispool" "github.com/sourcegraph/sourcegraph/internal/slack" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) const licenseAnomalyCheckKey = "license_anomaly_check" @@ -70,10 +71,6 @@ func maybeCheckAnomalies(logger log.Logger, db database.DB, client slackClient, } } -func boolPtr(b bool) *bool { - return &b -} - // checkAnomalies loops through all current subscriptions and triggers a check for each subscription func checkAnomalies(logger log.Logger, db database.DB, clock glock.Clock, client slackClient) { if conf.Get().Dotcom == nil || conf.Get().Dotcom.SlackLicenseAnomallyWebhook == "" { @@ -100,8 +97,8 @@ func checkSubscriptionAnomalies(ctx context.Context, logger log.Logger, db datab licenses, err := dbLicenses{db: db}.List(ctx, dbLicensesListOptions{ ProductSubscriptionID: sub.ID, WithSiteIDsOnly: true, - Expired: boolPtr(false), - Revoked: boolPtr(false), + Expired: pointers.Ptr(false), + Revoked: pointers.Ptr(false), }) if err != nil { logger.Error("error listing licenses", log.String("subscription", sub.ID), log.Error(err)) diff --git a/enterprise/cmd/frontend/internal/dotcom/productsubscription/license_anomaly_test.go b/enterprise/cmd/frontend/internal/dotcom/productsubscription/license_anomaly_test.go index f4264d0f433..17c7920f748 100644 --- a/enterprise/cmd/frontend/internal/dotcom/productsubscription/license_anomaly_test.go +++ b/enterprise/cmd/frontend/internal/dotcom/productsubscription/license_anomaly_test.go @@ -18,13 +18,10 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/redispool" "github.com/sourcegraph/sourcegraph/internal/slack" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) -func int32Ptr(n int32) *int32 { - return &n -} - func TestMaybeCheckAnomalies(t *testing.T) { logger := logtest.Scoped(t) db := database.NewMockDB() @@ -108,7 +105,7 @@ func TestCheckAnomalies(t *testing.T) { } mocks.licenses.List = func(ctx context.Context, opt dbLicensesListOptions) ([]*dbLicense, error) { if opt.ProductSubscriptionID == sub2ID { - return []*dbLicense{{ID: licenseID, LicenseKey: "key", ProductSubscriptionID: opt.ProductSubscriptionID, SiteID: &siteID, LicenseVersion: int32Ptr(2)}}, nil + return []*dbLicense{{ID: licenseID, LicenseKey: "key", ProductSubscriptionID: opt.ProductSubscriptionID, SiteID: &siteID, LicenseVersion: pointers.Ptr(int32(2))}}, nil } return []*dbLicense{}, nil } diff --git a/enterprise/cmd/frontend/internal/dotcom/productsubscription/license_check_handler_test.go b/enterprise/cmd/frontend/internal/dotcom/productsubscription/license_check_handler_test.go index 7b0d5ce6987..cc95b0104fe 100644 --- a/enterprise/cmd/frontend/internal/dotcom/productsubscription/license_check_handler_test.go +++ b/enterprise/cmd/frontend/internal/dotcom/productsubscription/license_check_handler_test.go @@ -16,6 +16,7 @@ import ( "github.com/sourcegraph/sourcegraph/enterprise/internal/licensing" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestNewLicenseCheckHandler(t *testing.T) { @@ -23,7 +24,6 @@ func TestNewLicenseCheckHandler(t *testing.T) { token := licensing.GenerateHashedLicenseKeyAccessToken(licenseKey) return &token } - strPtr := func(s string) *string { return &s } now := time.Now() hourAgo := now.Add(-1 * time.Hour) @@ -44,7 +44,7 @@ func TestNewLicenseCheckHandler(t *testing.T) { assignedLicense := dbLicense{ LicenseKey: "assigned-license-key", LicenseCheckToken: makeToken("assigned-site-id-token"), - SiteID: strPtr("C2582A60-573C-4EBC-BDD4-BC57A73CF010"), // uppercase to test case sensitivity + SiteID: pointers.Ptr("C2582A60-573C-4EBC-BDD4-BC57A73CF010"), // uppercase to test case sensitivity } licenses := []dbLicense{ validLicense, diff --git a/enterprise/cmd/frontend/internal/dotcom/productsubscription/licenses_db_test.go b/enterprise/cmd/frontend/internal/dotcom/productsubscription/licenses_db_test.go index adbbab7f6e1..ae6cfadc514 100644 --- a/enterprise/cmd/frontend/internal/dotcom/productsubscription/licenses_db_test.go +++ b/enterprise/cmd/frontend/internal/dotcom/productsubscription/licenses_db_test.go @@ -17,6 +17,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/timeutil" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestProductLicenses_Create(t *testing.T) { @@ -298,37 +299,37 @@ func TestProductLicenses_List(t *testing.T) { }, { name: "expired only", - opts: dbLicensesListOptions{Expired: boolPtr(true)}, + opts: dbLicensesListOptions{Expired: pointers.Ptr(true)}, expectedCount: 1, }, { name: "non expired only", - opts: dbLicensesListOptions{Expired: boolPtr(false)}, + opts: dbLicensesListOptions{Expired: pointers.Ptr(false)}, expectedCount: len(licenses) - 1, }, { name: "revoked only", - opts: dbLicensesListOptions{Revoked: boolPtr(true)}, + opts: dbLicensesListOptions{Revoked: pointers.Ptr(true)}, expectedCount: 1, }, { name: "non revoked only", - opts: dbLicensesListOptions{Revoked: boolPtr(false)}, + opts: dbLicensesListOptions{Revoked: pointers.Ptr(false)}, expectedCount: len(licenses) - 1, }, { name: "non revoked and non expired", opts: dbLicensesListOptions{ - Revoked: boolPtr(false), - Expired: boolPtr(false), + Revoked: pointers.Ptr(false), + Expired: pointers.Ptr(false), }, expectedCount: len(licenses) - 2, }, { name: "non revoked and non expired with site ID", opts: dbLicensesListOptions{ - Revoked: boolPtr(false), - Expired: boolPtr(false), + Revoked: pointers.Ptr(false), + Expired: pointers.Ptr(false), WithSiteIDsOnly: true, }, expectedCount: 1, diff --git a/enterprise/cmd/frontend/internal/executorqueue/handler/BUILD.bazel b/enterprise/cmd/frontend/internal/executorqueue/handler/BUILD.bazel index 61e63c96c20..46a6a0f5248 100644 --- a/enterprise/cmd/frontend/internal/executorqueue/handler/BUILD.bazel +++ b/enterprise/cmd/frontend/internal/executorqueue/handler/BUILD.bazel @@ -54,6 +54,7 @@ go_test( "//internal/workerutil/dbworker/store", "//internal/workerutil/dbworker/store/mocks", "//lib/errors", + "//lib/pointers", "@com_github_gorilla_mux//:mux", "@com_github_prometheus_client_model//go", "@com_github_prometheus_common//expfmt", diff --git a/enterprise/cmd/frontend/internal/executorqueue/handler/handler_test.go b/enterprise/cmd/frontend/internal/executorqueue/handler/handler_test.go index 3bfcfacba83..8a62a3f6c07 100644 --- a/enterprise/cmd/frontend/internal/executorqueue/handler/handler_test.go +++ b/enterprise/cmd/frontend/internal/executorqueue/handler/handler_test.go @@ -27,6 +27,7 @@ import ( dbworkerstore "github.com/sourcegraph/sourcegraph/internal/workerutil/dbworker/store" dbworkerstoremocks "github.com/sourcegraph/sourcegraph/internal/workerutil/dbworker/store/mocks" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestHandler_Name(t *testing.T) { @@ -296,9 +297,9 @@ func TestHandler_HandleAddExecutionLogEntry(t *testing.T) { Key: "foo", Command: []string{"faz", "baz"}, StartTime: startTime, - ExitCode: newIntPtr(0), + ExitCode: pointers.Ptr(0), Out: "done", - DurationMs: newIntPtr(100), + DurationMs: pointers.Ptr(100), }, mockStore.AddExecutionLogEntryFunc.History()[0].Arg2, ) @@ -405,9 +406,9 @@ func TestHandler_HandleUpdateExecutionLogEntry(t *testing.T) { Key: "foo", Command: []string{"faz", "baz"}, StartTime: startTime, - ExitCode: newIntPtr(0), + ExitCode: pointers.Ptr(0), Out: "done", - DurationMs: newIntPtr(100), + DurationMs: pointers.Ptr(100), }, mockStore.UpdateExecutionLogEntryFunc.History()[0].Arg3, ) @@ -977,7 +978,3 @@ func (r testRecord) RecordID() int { return r.id } func (r testRecord) RecordUID() string { return strconv.Itoa(r.id) } - -func newIntPtr(i int) *int { - return &i -} diff --git a/enterprise/cmd/worker/internal/permissions/BUILD.bazel b/enterprise/cmd/worker/internal/permissions/BUILD.bazel index a5e07fed78b..a88f238e7e6 100644 --- a/enterprise/cmd/worker/internal/permissions/BUILD.bazel +++ b/enterprise/cmd/worker/internal/permissions/BUILD.bazel @@ -76,6 +76,7 @@ go_test( "//internal/observation", "//internal/timeutil", "//internal/types", + "//lib/pointers", "//schema", "@com_github_google_go_cmp//cmp", "@com_github_sourcegraph_log//:log", diff --git a/enterprise/cmd/worker/internal/permissions/perms_syncer_scheduler_test.go b/enterprise/cmd/worker/internal/permissions/perms_syncer_scheduler_test.go index 5a363a3eecb..5c2be4af84b 100644 --- a/enterprise/cmd/worker/internal/permissions/perms_syncer_scheduler_test.go +++ b/enterprise/cmd/worker/internal/permissions/perms_syncer_scheduler_test.go @@ -21,6 +21,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/extsvc" "github.com/sourcegraph/sourcegraph/internal/timeutil" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -238,8 +239,6 @@ func clock() time.Time { return time.Unix(0, atomic.LoadInt64(&now)) } -func toIntPtr(n int) *int { return &n } - func TestOldestUserPermissionsBatchSize(t *testing.T) { t.Cleanup(func() { conf.Mock(nil) }) @@ -254,17 +253,17 @@ func TestOldestUserPermissionsBatchSize(t *testing.T) { }, { name: "uses number from config", - configure: toIntPtr(5), + configure: pointers.Ptr(5), want: 5, }, { name: "can be set to 0", - configure: toIntPtr(0), + configure: pointers.Ptr(0), want: 0, }, { name: "negative numbers result in default", - configure: toIntPtr(-248), + configure: pointers.Ptr(-248), want: 10, }, } @@ -293,17 +292,17 @@ func TestOldestRepoPermissionsBatchSize(t *testing.T) { }, { name: "uses number from config", - configure: toIntPtr(5), + configure: pointers.Ptr(5), want: 5, }, { name: "can be set to 0", - configure: toIntPtr(0), + configure: pointers.Ptr(0), want: 0, }, { name: "negative numbers result in default", - configure: toIntPtr(-248), + configure: pointers.Ptr(-248), want: 10, }, } diff --git a/enterprise/cmd/worker/internal/telemetry/BUILD.bazel b/enterprise/cmd/worker/internal/telemetry/BUILD.bazel index 4d2acf9af03..cc833319471 100644 --- a/enterprise/cmd/worker/internal/telemetry/BUILD.bazel +++ b/enterprise/cmd/worker/internal/telemetry/BUILD.bazel @@ -48,6 +48,7 @@ go_test( "//internal/observation", "//internal/version", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_google_go_cmp//cmp", "@com_github_hexops_autogold_v2//:autogold", diff --git a/enterprise/cmd/worker/internal/telemetry/telemetry_job_test.go b/enterprise/cmd/worker/internal/telemetry/telemetry_job_test.go index b9ec0610b63..76ff1b9fb16 100644 --- a/enterprise/cmd/worker/internal/telemetry/telemetry_job_test.go +++ b/enterprise/cmd/worker/internal/telemetry/telemetry_job_test.go @@ -7,6 +7,7 @@ import ( "time" "github.com/sourcegraph/sourcegraph/internal/featureflag" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/lib/pq" @@ -130,25 +131,21 @@ func TestHandlerLoadsEvents(t *testing.T) { flags := make(map[string]bool) flags["testflag"] = true - ptr := func(s string) *string { - return &s - } - want := []*database.Event{ { Name: "event1", UserID: 1, Source: "test", EvaluatedFlagSet: flags, - DeviceID: ptr("device-1"), - InsertID: ptr("insert-1"), + DeviceID: pointers.Ptr("device-1"), + InsertID: pointers.Ptr("insert-1"), }, { Name: "event2", UserID: 2, Source: "test", - DeviceID: ptr("device-2"), - InsertID: ptr("insert-2"), + DeviceID: pointers.Ptr("device-2"), + InsertID: pointers.Ptr("insert-2"), }, } err := db.EventLogs().BulkInsert(ctx, want) @@ -248,25 +245,21 @@ func TestHandlerLoadsEventsWithBookmarkState(t *testing.T) { ctx := context.Background() db := database.NewDB(logger, dbHandle) - ptr := func(s string) *string { - return &s - } - initAllowedEvents(t, db, []string{"event1", "event2", "event4"}) testData := []*database.Event{ { Name: "event1", UserID: 1, Source: "test", - DeviceID: ptr("device"), - InsertID: ptr("insert"), + DeviceID: pointers.Ptr("device"), + InsertID: pointers.Ptr("insert"), }, { Name: "event2", UserID: 2, Source: "test", - DeviceID: ptr("device"), - InsertID: ptr("insert"), + DeviceID: pointers.Ptr("device"), + InsertID: pointers.Ptr("insert"), }, } err := db.EventLogs().BulkInsert(ctx, testData) @@ -362,32 +355,28 @@ func TestHandlerLoadsEventsWithAllowlist(t *testing.T) { ctx := context.Background() db := database.NewDB(logger, dbHandle) - ptr := func(s string) *string { - return &s - } - initAllowedEvents(t, db, []string{"allowed"}) testData := []*database.Event{ { Name: "allowed", UserID: 1, Source: "test", - DeviceID: ptr("device"), - InsertID: ptr("insert"), + DeviceID: pointers.Ptr("device"), + InsertID: pointers.Ptr("insert"), }, { Name: "not-allowed", UserID: 2, Source: "test", - DeviceID: ptr("device"), - InsertID: ptr("insert"), + DeviceID: pointers.Ptr("device"), + InsertID: pointers.Ptr("insert"), }, { Name: "allowed", UserID: 3, Source: "test", - DeviceID: ptr("device"), - InsertID: ptr("insert"), + DeviceID: pointers.Ptr("device"), + InsertID: pointers.Ptr("insert"), }, } err := db.EventLogs().BulkInsert(ctx, testData) @@ -492,10 +481,6 @@ func TestBuildBigQueryObject(t *testing.T) { flags := make(featureflag.EvaluatedFlagSet) flags["testflag"] = true - ptr := func(s string) *string { - return &s - } - event := &database.Event{ ID: 1, Name: "GREAT_EVENT", @@ -507,12 +492,12 @@ func TestBuildBigQueryObject(t *testing.T) { Version: "1.1.1", Timestamp: atTime, EvaluatedFlagSet: flags, - CohortID: ptr("cohort1"), - FirstSourceURL: ptr("first_source_url"), - LastSourceURL: ptr("last_source_url"), - Referrer: ptr("reff"), - DeviceID: ptr("devid"), - InsertID: ptr("insertid"), + CohortID: pointers.Ptr("cohort1"), + FirstSourceURL: pointers.Ptr("first_source_url"), + LastSourceURL: pointers.Ptr("last_source_url"), + Referrer: pointers.Ptr("reff"), + DeviceID: pointers.Ptr("devid"), + InsertID: pointers.Ptr("insertid"), } metadata := &instanceMetadata{ diff --git a/enterprise/dev/deployment-notifier/BUILD.bazel b/enterprise/dev/deployment-notifier/BUILD.bazel index d6e9576da1a..bb7fa466a25 100644 --- a/enterprise/dev/deployment-notifier/BUILD.bazel +++ b/enterprise/dev/deployment-notifier/BUILD.bazel @@ -44,6 +44,7 @@ go_test( deps = [ "//internal/httptestutil", "//lib/errors", + "//lib/pointers", "@com_github_dnaeon_go_vcr//cassette", "@com_github_google_go_github_v41//github", "@com_github_stretchr_testify//assert", diff --git a/enterprise/dev/deployment-notifier/trace_test.go b/enterprise/dev/deployment-notifier/trace_test.go index e8cb2ca0627..9b5445473b1 100644 --- a/enterprise/dev/deployment-notifier/trace_test.go +++ b/enterprise/dev/deployment-notifier/trace_test.go @@ -7,20 +7,18 @@ import ( "github.com/google/go-github/v41/github" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" -) -func intPtr(v int) *int { - return &v -} + "github.com/sourcegraph/sourcegraph/lib/pointers" +) func TestGenerateDeploymentTrace(t *testing.T) { trace, err := GenerateDeploymentTrace(&DeploymentReport{ Environment: "preprepod", DeployedAt: time.RFC822Z, PullRequests: []*github.PullRequest{ - {Number: intPtr(32996)}, - {Number: intPtr(32871)}, - {Number: intPtr(32767)}, + {Number: pointers.Ptr(32996)}, + {Number: pointers.Ptr(32871)}, + {Number: pointers.Ptr(32767)}, }, ServicesPerPullRequest: map[int][]string{ 32996: {"frontend", "gitserver", "worker"}, diff --git a/enterprise/internal/batches/reconciler/BUILD.bazel b/enterprise/internal/batches/reconciler/BUILD.bazel index 8e2cb062564..6e26d820621 100644 --- a/enterprise/internal/batches/reconciler/BUILD.bazel +++ b/enterprise/internal/batches/reconciler/BUILD.bazel @@ -75,6 +75,7 @@ go_test( "//lib/batches", "//lib/batches/git", "//lib/errors", + "//lib/pointers", "@com_github_google_go_cmp//cmp", "@com_github_sourcegraph_log//logtest", "@com_github_stretchr_testify//assert", diff --git a/enterprise/internal/batches/reconciler/plan_test.go b/enterprise/internal/batches/reconciler/plan_test.go index 11ed10f7131..09f04cef8aa 100644 --- a/enterprise/internal/batches/reconciler/plan_test.go +++ b/enterprise/internal/batches/reconciler/plan_test.go @@ -6,6 +6,7 @@ import ( bt "github.com/sourcegraph/sourcegraph/enterprise/internal/batches/testing" btypes "github.com/sourcegraph/sourcegraph/enterprise/internal/batches/types" "github.com/sourcegraph/sourcegraph/internal/extsvc" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestDetermineReconcilerPlan(t *testing.T) { @@ -86,7 +87,7 @@ func TestDetermineReconcilerPlan(t *testing.T) { currentSpec: &bt.TestSpecOpts{Published: nil}, changeset: bt.TestChangesetOpts{ PublicationState: btypes.ChangesetPublicationStateUnpublished, - UiPublicationState: uiPublicationStatePtr(btypes.ChangesetUiPublicationStateUnpublished), + UiPublicationState: pointers.Ptr(btypes.ChangesetUiPublicationStateUnpublished), }, wantOperations: Operations{}, }, @@ -95,7 +96,7 @@ func TestDetermineReconcilerPlan(t *testing.T) { currentSpec: &bt.TestSpecOpts{Published: nil}, changeset: bt.TestChangesetOpts{ PublicationState: btypes.ChangesetPublicationStateUnpublished, - UiPublicationState: uiPublicationStatePtr(btypes.ChangesetUiPublicationStateDraft), + UiPublicationState: pointers.Ptr(btypes.ChangesetUiPublicationStateDraft), }, wantOperations: Operations{btypes.ReconcilerOperationPush, btypes.ReconcilerOperationPublishDraft}, }, @@ -105,7 +106,7 @@ func TestDetermineReconcilerPlan(t *testing.T) { changeset: bt.TestChangesetOpts{ ExternalServiceType: extsvc.TypeBitbucketServer, PublicationState: btypes.ChangesetPublicationStateUnpublished, - UiPublicationState: uiPublicationStatePtr(btypes.ChangesetUiPublicationStateDraft), + UiPublicationState: pointers.Ptr(btypes.ChangesetUiPublicationStateDraft), }, // Cannot draft on an unsupported code host, so this is a no-op. wantOperations: Operations{}, @@ -115,7 +116,7 @@ func TestDetermineReconcilerPlan(t *testing.T) { currentSpec: &bt.TestSpecOpts{Published: nil}, changeset: bt.TestChangesetOpts{ PublicationState: btypes.ChangesetPublicationStateUnpublished, - UiPublicationState: uiPublicationStatePtr(btypes.ChangesetUiPublicationStatePublished), + UiPublicationState: pointers.Ptr(btypes.ChangesetUiPublicationStatePublished), }, wantOperations: Operations{btypes.ReconcilerOperationPush, btypes.ReconcilerOperationPublish}, }, @@ -125,7 +126,7 @@ func TestDetermineReconcilerPlan(t *testing.T) { currentSpec: &bt.TestSpecOpts{Published: nil}, changeset: bt.TestChangesetOpts{ PublicationState: btypes.ChangesetPublicationStatePublished, - UiPublicationState: uiPublicationStatePtr(btypes.ChangesetUiPublicationStatePublished), + UiPublicationState: pointers.Ptr(btypes.ChangesetUiPublicationStatePublished), }, wantOperations: Operations{btypes.ReconcilerOperationUndraft}, }, @@ -135,7 +136,7 @@ func TestDetermineReconcilerPlan(t *testing.T) { currentSpec: &bt.TestSpecOpts{Published: nil}, changeset: bt.TestChangesetOpts{ PublicationState: btypes.ChangesetPublicationStatePublished, - UiPublicationState: uiPublicationStatePtr(btypes.ChangesetUiPublicationStateDraft), + UiPublicationState: pointers.Ptr(btypes.ChangesetUiPublicationStateDraft), }, // No change to the actual state, so this is a no-op. wantOperations: Operations{}, @@ -146,7 +147,7 @@ func TestDetermineReconcilerPlan(t *testing.T) { currentSpec: &bt.TestSpecOpts{Published: nil}, changeset: bt.TestChangesetOpts{ PublicationState: btypes.ChangesetPublicationStatePublished, - UiPublicationState: uiPublicationStatePtr(btypes.ChangesetUiPublicationStateUnpublished), + UiPublicationState: pointers.Ptr(btypes.ChangesetUiPublicationStateUnpublished), }, // We can't unscramble an egg, nor can we unpublish a published // changeset, so this is a no-op. @@ -459,7 +460,3 @@ func TestDetermineReconcilerPlan(t *testing.T) { }) } } - -func uiPublicationStatePtr(state btypes.ChangesetUiPublicationState) *btypes.ChangesetUiPublicationState { - return &state -} diff --git a/enterprise/internal/batches/reconciler/publication_state_test.go b/enterprise/internal/batches/reconciler/publication_state_test.go index e58b4e3465d..4aae6cbb75d 100644 --- a/enterprise/internal/batches/reconciler/publication_state_test.go +++ b/enterprise/internal/batches/reconciler/publication_state_test.go @@ -5,6 +5,7 @@ import ( btypes "github.com/sourcegraph/sourcegraph/enterprise/internal/batches/types" "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestPublicationStateCalculator(t *testing.T) { @@ -41,17 +42,17 @@ func TestPublicationStateCalculator(t *testing.T) { }, "no published value; unpublished ui": { spec: batches.PublishedValue{Val: nil}, - ui: uiPublicationStatePtr(btypes.ChangesetUiPublicationStateUnpublished), + ui: pointers.Ptr(btypes.ChangesetUiPublicationStateUnpublished), want: want{false, false, true}, }, "no published value; draft ui": { spec: batches.PublishedValue{Val: nil}, - ui: uiPublicationStatePtr(btypes.ChangesetUiPublicationStateDraft), + ui: pointers.Ptr(btypes.ChangesetUiPublicationStateDraft), want: want{false, true, false}, }, "no published value; published ui": { spec: batches.PublishedValue{Val: nil}, - ui: uiPublicationStatePtr(btypes.ChangesetUiPublicationStatePublished), + ui: pointers.Ptr(btypes.ChangesetUiPublicationStatePublished), want: want{true, false, false}, }, } { diff --git a/enterprise/internal/batches/service/BUILD.bazel b/enterprise/internal/batches/service/BUILD.bazel index 68c91939637..175d585d088 100644 --- a/enterprise/internal/batches/service/BUILD.bazel +++ b/enterprise/internal/batches/service/BUILD.bazel @@ -96,6 +96,7 @@ go_test( "//internal/types", "//lib/batches", "//lib/errors", + "//lib/pointers", "@com_github_google_go_cmp//cmp", "@com_github_google_go_cmp//cmp/cmpopts", "@com_github_graph_gophers_graphql_go//relay", diff --git a/enterprise/internal/batches/service/service_test.go b/enterprise/internal/batches/service/service_test.go index 791022de4c2..160c262d7a7 100644 --- a/enterprise/internal/batches/service/service_test.go +++ b/enterprise/internal/batches/service/service_test.go @@ -34,6 +34,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/timeutil" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestServicePermissionLevels(t *testing.T) { @@ -589,7 +590,7 @@ func TestService(t *testing.T) { NumResets: 0, NumFailures: 0, FailureMessage: nil, - PreviousFailureMessage: strPtr(bt.FailedChangesetFailureMessage), + PreviousFailureMessage: pointers.Ptr(bt.FailedChangesetFailureMessage), }) // rs[0] is filtered out @@ -3411,5 +3412,3 @@ func assertNoAuthError(t *testing.T, err error) { t.Fatalf("got auth error") } } - -func strPtr(s string) *string { return &s } diff --git a/enterprise/internal/batches/sources/BUILD.bazel b/enterprise/internal/batches/sources/BUILD.bazel index 850496111f3..804a75fdd7f 100644 --- a/enterprise/internal/batches/sources/BUILD.bazel +++ b/enterprise/internal/batches/sources/BUILD.bazel @@ -90,6 +90,7 @@ go_test( "//internal/testutil", "//internal/types", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_derision_test_go_mockgen//testutil/assert", "@com_github_dnaeon_go_vcr//cassette", diff --git a/enterprise/internal/batches/sources/azuredevops_test.go b/enterprise/internal/batches/sources/azuredevops_test.go index a203375f687..49a97449d5f 100644 --- a/enterprise/internal/batches/sources/azuredevops_test.go +++ b/enterprise/internal/batches/sources/azuredevops_test.go @@ -16,6 +16,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/extsvc/azuredevops" "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) var ( @@ -709,7 +710,7 @@ func TestAzureDevOpsSource_GetFork(t *testing.T) { return azuredevops.Repository{}, want }) - repo, err := s.GetFork(ctx, upstreamRepo, strPtr("fork"), nil) + repo, err := s.GetFork(ctx, upstreamRepo, pointers.Ptr("fork"), nil) assert.Nil(t, repo) assert.NotNil(t, err) assert.ErrorIs(t, err, want) @@ -723,7 +724,7 @@ func TestAzureDevOpsSource_GetFork(t *testing.T) { return fork, nil }) - forkRepo, err := s.GetFork(ctx, upstreamRepo, strPtr("fork"), nil) + forkRepo, err := s.GetFork(ctx, upstreamRepo, pointers.Ptr("fork"), nil) assert.Nil(t, err) assert.NotNil(t, forkRepo) assert.NotEqual(t, forkRepo, upstreamRepo) @@ -745,7 +746,7 @@ func TestAzureDevOpsSource_GetFork(t *testing.T) { return azuredevops.Project{}, want }) - repo, err := s.GetFork(ctx, upstreamRepo, strPtr("fork"), nil) + repo, err := s.GetFork(ctx, upstreamRepo, pointers.Ptr("fork"), nil) assert.Nil(t, repo) assert.NotNil(t, err) assert.ErrorIs(t, err, want) @@ -772,7 +773,7 @@ func TestAzureDevOpsSource_GetFork(t *testing.T) { return azuredevops.Repository{}, want }) - repo, err := s.GetFork(ctx, upstreamRepo, strPtr("fork"), nil) + repo, err := s.GetFork(ctx, upstreamRepo, pointers.Ptr("fork"), nil) assert.Nil(t, repo) assert.NotNil(t, err) assert.ErrorIs(t, err, want) @@ -814,7 +815,7 @@ func TestAzureDevOpsSource_GetFork(t *testing.T) { return fork, nil }) - forkRepo, err := s.GetFork(ctx, upstreamRepo, strPtr("fork"), nil) + forkRepo, err := s.GetFork(ctx, upstreamRepo, pointers.Ptr("fork"), nil) assert.Nil(t, err) assert.NotNil(t, forkRepo) assert.NotEqual(t, forkRepo, upstreamRepo) @@ -846,7 +847,7 @@ func TestAzureDevOpsSource_GetFork(t *testing.T) { return fork, nil }) - forkRepo, err := s.GetFork(ctx, upstreamRepo, strPtr("fork"), strPtr("special-fork-name")) + forkRepo, err := s.GetFork(ctx, upstreamRepo, pointers.Ptr("fork"), pointers.Ptr("special-fork-name")) assert.Nil(t, err) assert.NotNil(t, forkRepo) assert.NotEqual(t, forkRepo, upstreamRepo) diff --git a/enterprise/internal/batches/sources/bitbucketcloud_test.go b/enterprise/internal/batches/sources/bitbucketcloud_test.go index 360db7c403f..853854aeb65 100644 --- a/enterprise/internal/batches/sources/bitbucketcloud_test.go +++ b/enterprise/internal/batches/sources/bitbucketcloud_test.go @@ -19,6 +19,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/extsvc/bitbucketcloud" "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestNewBitbucketCloudSource(t *testing.T) { @@ -609,7 +610,7 @@ func TestBitbucketCloudSource_GetFork(t *testing.T) { return nil, want }) - repo, err := s.GetFork(ctx, upstreamRepo, strPtr("fork"), nil) + repo, err := s.GetFork(ctx, upstreamRepo, pointers.Ptr("fork"), nil) assert.Nil(t, repo) assert.NotNil(t, err) assert.ErrorIs(t, err, want) @@ -624,7 +625,7 @@ func TestBitbucketCloudSource_GetFork(t *testing.T) { return fork, nil }) - forkRepo, err := s.GetFork(ctx, upstreamRepo, strPtr("fork"), nil) + forkRepo, err := s.GetFork(ctx, upstreamRepo, pointers.Ptr("fork"), nil) assert.Nil(t, err) assert.NotNil(t, forkRepo) assert.NotEqual(t, forkRepo, upstreamRepo) @@ -649,7 +650,7 @@ func TestBitbucketCloudSource_GetFork(t *testing.T) { return nil, want }) - repo, err := s.GetFork(ctx, upstreamRepo, strPtr("fork"), nil) + repo, err := s.GetFork(ctx, upstreamRepo, pointers.Ptr("fork"), nil) assert.Nil(t, repo) assert.NotNil(t, err) assert.ErrorIs(t, err, want) @@ -742,7 +743,7 @@ func TestBitbucketCloudSource_GetFork(t *testing.T) { return fork, nil }) - forkRepo, err := s.GetFork(ctx, upstreamRepo, strPtr("fork"), nil) + forkRepo, err := s.GetFork(ctx, upstreamRepo, pointers.Ptr("fork"), nil) assert.Nil(t, err) assert.NotNil(t, forkRepo) assert.NotEqual(t, forkRepo, upstreamRepo) @@ -766,7 +767,7 @@ func TestBitbucketCloudSource_GetFork(t *testing.T) { return fork, nil }) - forkRepo, err := s.GetFork(ctx, upstreamRepo, strPtr("fork"), strPtr("special-fork-name")) + forkRepo, err := s.GetFork(ctx, upstreamRepo, pointers.Ptr("fork"), pointers.Ptr("special-fork-name")) assert.Nil(t, err) assert.NotNil(t, forkRepo) assert.NotEqual(t, forkRepo, upstreamRepo) diff --git a/enterprise/internal/batches/sources/bitbucketserver_test.go b/enterprise/internal/batches/sources/bitbucketserver_test.go index 2877faadb86..c334114a16b 100644 --- a/enterprise/internal/batches/sources/bitbucketserver_test.go +++ b/enterprise/internal/batches/sources/bitbucketserver_test.go @@ -18,6 +18,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/testutil" "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -830,7 +831,7 @@ func TestBitbucketServerSource_GetFork(t *testing.T) { cf, save := newClientFactory(t, testName(t)) defer save(t) - svc := newExternalService(t, strPtr("invalid")) + svc := newExternalService(t, pointers.Ptr("invalid")) ctx := context.Background() bbsSrc, err := NewBitbucketServerSource(ctx, svc, cf) @@ -861,7 +862,7 @@ func TestBitbucketServerSource_GetFork(t *testing.T) { bbsSrc, err := NewBitbucketServerSource(ctx, svc, cf) assert.Nil(t, err) - fork, err := bbsSrc.GetFork(ctx, target, strPtr("~milton"), strPtr("vcr-fork-test-repo")) + fork, err := bbsSrc.GetFork(ctx, target, pointers.Ptr("~milton"), pointers.Ptr("vcr-fork-test-repo")) assert.Nil(t, fork) assert.ErrorContains(t, err, "repo is not a fork") }) @@ -887,7 +888,7 @@ func TestBitbucketServerSource_GetFork(t *testing.T) { bbsSrc, err := NewBitbucketServerSource(ctx, svc, cf) assert.Nil(t, err) - fork, err := bbsSrc.GetFork(ctx, target, strPtr("~milton"), strPtr("BAT-vcr-fork-test-repo-already-forked")) + fork, err := bbsSrc.GetFork(ctx, target, pointers.Ptr("~milton"), pointers.Ptr("BAT-vcr-fork-test-repo-already-forked")) assert.Nil(t, fork) assert.ErrorContains(t, err, "repo was not forked from the given parent") }) @@ -995,7 +996,7 @@ func TestBitbucketServerSource_GetFork(t *testing.T) { username, err := bbsSrc.client.AuthenticatedUsername(ctx) assert.Nil(t, err) - fork, err := bbsSrc.GetFork(ctx, target, strPtr("~milton"), strPtr("BAT-vcr-fork-test-repo-already-forked")) + fork, err := bbsSrc.GetFork(ctx, target, pointers.Ptr("~milton"), pointers.Ptr("BAT-vcr-fork-test-repo-already-forked")) assert.Nil(t, err) assert.NotNil(t, fork) assert.NotEqual(t, fork, target) @@ -1036,7 +1037,7 @@ func TestBitbucketServerSource_GetFork(t *testing.T) { username, err := bbsSrc.client.AuthenticatedUsername(ctx) assert.Nil(t, err) - fork, err := bbsSrc.GetFork(ctx, target, strPtr("~milton"), strPtr("BAT-vcr-fork-test-repo-not-forked")) + fork, err := bbsSrc.GetFork(ctx, target, pointers.Ptr("~milton"), pointers.Ptr("BAT-vcr-fork-test-repo-not-forked")) assert.Nil(t, err) assert.NotNil(t, fork) assert.NotEqual(t, fork, target) @@ -1046,5 +1047,3 @@ func TestBitbucketServerSource_GetFork(t *testing.T) { testutil.AssertGolden(t, "testdata/golden/"+name, update(name), fork) }) } - -func strPtr(s string) *string { return &s } diff --git a/enterprise/internal/batches/sources/github_test.go b/enterprise/internal/batches/sources/github_test.go index 2ffde7c1d7f..1ac698baac1 100644 --- a/enterprise/internal/batches/sources/github_test.go +++ b/enterprise/internal/batches/sources/github_test.go @@ -25,6 +25,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/testutil" "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -558,7 +559,7 @@ func TestGithubSource_GetFork(t *testing.T) { defer save(t) target := newGitHubRepo(urn, tc.target.namespace+"/"+tc.target.name, "123") - fork, err := src.GetFork(ctx, target, strPtr(tc.fork.namespace), strPtr(tc.fork.name)) + fork, err := src.GetFork(ctx, target, pointers.Ptr(tc.fork.namespace), pointers.Ptr(tc.fork.name)) assert.Nil(t, fork) assert.ErrorContains(t, err, tc.err) @@ -664,7 +665,7 @@ func TestGithubSource_GetFork(t *testing.T) { var fork *types.Repo var err error if tc.externalNameAndNamespace { - fork, err = src.GetFork(ctx, target, strPtr(tc.fork.namespace), strPtr(tc.fork.name)) + fork, err = src.GetFork(ctx, target, pointers.Ptr(tc.fork.namespace), pointers.Ptr(tc.fork.name)) } else { fork, err = src.GetFork(ctx, target, nil, nil) } @@ -778,7 +779,7 @@ func TestGithubSource_GetFork(t *testing.T) { forkRepo: &github.Repository{NameWithOwner: org + "/custom-bar", IsFork: true}, namespace: &org, wantNamespace: org, - name: strPtr("custom-bar"), + name: pointers.Ptr("custom-bar"), wantName: "custom-bar", client: &mockGithubClientFork{ fork: &github.Repository{NameWithOwner: org + "/custom-bar", IsFork: true}, diff --git a/enterprise/internal/batches/sources/gitlab_test.go b/enterprise/internal/batches/sources/gitlab_test.go index 3757e879e02..864c2ad2ede 100644 --- a/enterprise/internal/batches/sources/gitlab_test.go +++ b/enterprise/internal/batches/sources/gitlab_test.go @@ -23,6 +23,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/testutil" "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -1507,7 +1508,7 @@ func TestGitlabSource_GetFork(t *testing.T) { ProjectCommon: gitlab.ProjectCommon{ID: 2, PathWithNamespace: org + "/custom-bar"}}, namespace: &org, wantNamespace: org, - name: strPtr("custom-bar"), + name: pointers.Ptr("custom-bar"), wantName: "custom-bar", client: &mockGitlabClientFork{ fork: &gitlab.Project{ diff --git a/enterprise/internal/batches/store/BUILD.bazel b/enterprise/internal/batches/store/BUILD.bazel index 6ceed3cbb98..03dc7133773 100644 --- a/enterprise/internal/batches/store/BUILD.bazel +++ b/enterprise/internal/batches/store/BUILD.bazel @@ -124,6 +124,7 @@ go_test( "//lib/batches/execution", "//lib/batches/overridable", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_google_go_cmp//cmp", "@com_github_keegancsmith_sqlf//:sqlf", diff --git a/enterprise/internal/batches/store/changeset_specs_test.go b/enterprise/internal/batches/store/changeset_specs_test.go index 2c2e1473286..f2af5fa5f25 100644 --- a/enterprise/internal/batches/store/changeset_specs_test.go +++ b/enterprise/internal/batches/store/changeset_specs_test.go @@ -25,6 +25,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/internal/types/typestest" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) // Comparing the IDs is good enough, no need to bloat the tests here. @@ -1151,10 +1152,6 @@ func testStoreChangesetSpecsCurrentStateAndTextSearch(t *testing.T, ctx context. }, }) - statePtr := func(state btypes.ChangesetState) *btypes.ChangesetState { - return &state - } - for name, tc := range map[string]struct { opts GetRewirerMappingsOpts want []*btypes.Changeset @@ -1162,28 +1159,28 @@ func testStoreChangesetSpecsCurrentStateAndTextSearch(t *testing.T, ctx context. "state and text": { opts: GetRewirerMappingsOpts{ TextSearch: []search.TextSearchTerm{{Term: "foo"}}, - CurrentState: statePtr(btypes.ChangesetStateOpen), + CurrentState: pointers.Ptr(btypes.ChangesetStateOpen), }, want: []*btypes.Changeset{openFoo}, }, "state and not text": { opts: GetRewirerMappingsOpts{ TextSearch: []search.TextSearchTerm{{Term: "foo", Not: true}}, - CurrentState: statePtr(btypes.ChangesetStateOpen), + CurrentState: pointers.Ptr(btypes.ChangesetStateOpen), }, want: []*btypes.Changeset{openBar}, }, "state match only": { opts: GetRewirerMappingsOpts{ TextSearch: []search.TextSearchTerm{{Term: "bar"}}, - CurrentState: statePtr(btypes.ChangesetStateClosed), + CurrentState: pointers.Ptr(btypes.ChangesetStateClosed), }, want: []*btypes.Changeset{}, }, "text match only": { opts: GetRewirerMappingsOpts{ TextSearch: []search.TextSearchTerm{{Term: "foo"}}, - CurrentState: statePtr(btypes.ChangesetStateMerged), + CurrentState: pointers.Ptr(btypes.ChangesetStateMerged), }, want: []*btypes.Changeset{}, }, diff --git a/enterprise/internal/batches/store/changesets_test.go b/enterprise/internal/batches/store/changesets_test.go index 895c9a0a73a..f020a95f17c 100644 --- a/enterprise/internal/batches/store/changesets_test.go +++ b/enterprise/internal/batches/store/changesets_test.go @@ -29,6 +29,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/extsvc/gitlab" "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func testStoreChangesets(t *testing.T, ctx context.Context, s *Store, clock bt.Clock) { @@ -1216,15 +1217,13 @@ func testStoreChangesets(t *testing.T, ctx context.Context, s *Store, clock bt.C OwnedByBatchChange: 123, Metadata: &github.PullRequest{Title: "Se titel"}, }) - intptr := func(i int32) *int32 { return &i } - strptr := func(i string) *string { return &i } cs.ExternalBranch = "refs/heads/branch-2" cs.ExternalState = btypes.ChangesetExternalStateDeleted cs.ExternalReviewState = btypes.ChangesetReviewStateApproved cs.ExternalCheckState = btypes.ChangesetCheckStateFailed - cs.DiffStatAdded = intptr(100) - cs.DiffStatDeleted = intptr(100) + cs.DiffStatAdded = pointers.Ptr(int32(100)) + cs.DiffStatDeleted = pointers.Ptr(int32(100)) cs.Metadata = &github.PullRequest{Title: "The title"} want := cs.Clone() @@ -1237,7 +1236,7 @@ func testStoreChangesets(t *testing.T, ctx context.Context, s *Store, clock bt.C cs.PublicationState = btypes.ChangesetPublicationStatePublished cs.UiPublicationState = &published cs.ReconcilerState = btypes.ReconcilerStateCompleted - cs.FailureMessage = strptr("very bad for real this time") + cs.FailureMessage = pointers.Ptr("very bad for real this time") cs.NumFailures = 100 cs.OwnedByBatchChangeID = 234 cs.Closing = true @@ -1533,7 +1532,7 @@ func testStoreChangesets(t *testing.T, ctx context.Context, s *Store, clock bt.C NumResets: 0, NumFailures: 0, SyncErrorMessage: nil, - PreviousFailureMessage: strPtr("horse was here"), + PreviousFailureMessage: pointers.Ptr("horse was here"), }) }) @@ -2667,5 +2666,3 @@ func TestCleanDetachedChangesets(t *testing.T) { }) } } - -func strPtr(s string) *string { return &s } diff --git a/enterprise/internal/batches/types/BUILD.bazel b/enterprise/internal/batches/types/BUILD.bazel index 12fe5f6ebb5..559fcad80fc 100644 --- a/enterprise/internal/batches/types/BUILD.bazel +++ b/enterprise/internal/batches/types/BUILD.bazel @@ -87,6 +87,7 @@ go_test( "//internal/timeutil", "//lib/batches", "//lib/errors", + "//lib/pointers", "@com_github_google_go_cmp//cmp", "@com_github_sourcegraph_go_diff//diff", "@com_github_stretchr_testify//assert", diff --git a/enterprise/internal/batches/types/changeset_spec_test.go b/enterprise/internal/batches/types/changeset_spec_test.go index 1380355df9f..1df07a22c29 100644 --- a/enterprise/internal/batches/types/changeset_spec_test.go +++ b/enterprise/internal/batches/types/changeset_spec_test.go @@ -4,6 +4,8 @@ import ( "testing" "github.com/stretchr/testify/assert" + + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestChangesetSpec_ForkGetters(t *testing.T) { @@ -18,14 +20,14 @@ func TestChangesetSpec_ForkGetters(t *testing.T) { namespace: nil, }, "fork to user": { - spec: &ChangesetSpec{ForkNamespace: strPtr(changesetSpecForkNamespaceUser)}, + spec: &ChangesetSpec{ForkNamespace: pointers.Ptr(changesetSpecForkNamespaceUser)}, isFork: true, namespace: nil, }, "fork to namespace": { - spec: &ChangesetSpec{ForkNamespace: strPtr("org")}, + spec: &ChangesetSpec{ForkNamespace: pointers.Ptr("org")}, isFork: true, - namespace: strPtr("org"), + namespace: pointers.Ptr("org"), }, } { t.Run(name, func(t *testing.T) { @@ -47,5 +49,3 @@ func TestChangesetSpec_SetForkToUser(t *testing.T) { assert.NotNil(t, cs.ForkNamespace) assert.Equal(t, changesetSpecForkNamespaceUser, *cs.ForkNamespace) } - -func strPtr(s string) *string { return &s } diff --git a/enterprise/internal/batches/types/scheduler/window/BUILD.bazel b/enterprise/internal/batches/types/scheduler/window/BUILD.bazel index 2cbb391aa9b..971db4f2953 100644 --- a/enterprise/internal/batches/types/scheduler/window/BUILD.bazel +++ b/enterprise/internal/batches/types/scheduler/window/BUILD.bazel @@ -34,6 +34,7 @@ go_test( embed = [":window"], deps = [ "//lib/errors", + "//lib/pointers", "//schema", "@com_github_google_go_cmp//cmp", "@com_github_stretchr_testify//assert", diff --git a/enterprise/internal/batches/types/scheduler/window/config_test.go b/enterprise/internal/batches/types/scheduler/window/config_test.go index 177a9053957..b0a6dd976f9 100644 --- a/enterprise/internal/batches/types/scheduler/window/config_test.go +++ b/enterprise/internal/batches/types/scheduler/window/config_test.go @@ -8,6 +8,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -20,8 +21,7 @@ var ( ) func timeOfDayPtr(hour, minute int8) *timeOfDay { - t := timeOfDayFromParts(hour, minute) - return &t + return pointers.Ptr(timeOfDayFromParts(hour, minute)) } func TestConfiguration_Estimate(t *testing.T) { diff --git a/enterprise/internal/batches/types/step_info_test.go b/enterprise/internal/batches/types/step_info_test.go index 3cc844bca9c..9716e323a27 100644 --- a/enterprise/internal/batches/types/step_info_test.go +++ b/enterprise/internal/batches/types/step_info_test.go @@ -10,6 +10,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/executor" "github.com/sourcegraph/sourcegraph/internal/timeutil" batcheslib "github.com/sourcegraph/sourcegraph/lib/batches" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestParseJSONLogsFromOutput(t *testing.T) { @@ -262,7 +263,7 @@ func TestParseLogLines(t *testing.T) { }, { name: "Started but timeout", - entry: executor.ExecutionLogEntry{StartTime: time1, ExitCode: intPtr(-1), DurationMs: intPtr(500)}, + entry: executor.ExecutionLogEntry{StartTime: time1, ExitCode: pointers.Ptr(-1), DurationMs: pointers.Ptr(500)}, lines: []*batcheslib.LogEvent{ { Timestamp: time1, @@ -287,7 +288,7 @@ func TestParseLogLines(t *testing.T) { 1: { StartedAt: time1, FinishedAt: time1.Add(500 * time.Millisecond), - ExitCode: intPtr(-1), + ExitCode: pointers.Ptr(-1), Environment: map[string]string{"env": "var"}, }, }, @@ -485,5 +486,3 @@ func TestParseLogLines(t *testing.T) { }) } } - -func intPtr(i int) *int { return &i } diff --git a/enterprise/internal/codeintel/autoindexing/transport/graphql/BUILD.bazel b/enterprise/internal/codeintel/autoindexing/transport/graphql/BUILD.bazel index 5edb8dbaf9c..71d8db482c5 100644 --- a/enterprise/internal/codeintel/autoindexing/transport/graphql/BUILD.bazel +++ b/enterprise/internal/codeintel/autoindexing/transport/graphql/BUILD.bazel @@ -26,6 +26,7 @@ go_library( "//internal/observation", "//lib/codeintel/autoindex/config", "//lib/errors", + "//lib/pointers", "@com_github_graph_gophers_graphql_go//:graphql-go", "@io_opentelemetry_go_otel//attribute", ], diff --git a/enterprise/internal/codeintel/autoindexing/transport/graphql/root_resolver_configuration_repository.go b/enterprise/internal/codeintel/autoindexing/transport/graphql/root_resolver_configuration_repository.go index 61e6789941e..b46bbeb8d97 100644 --- a/enterprise/internal/codeintel/autoindexing/transport/graphql/root_resolver_configuration_repository.go +++ b/enterprise/internal/codeintel/autoindexing/transport/graphql/root_resolver_configuration_repository.go @@ -14,6 +14,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/lib/codeintel/autoindex/config" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) // 🚨 SECURITY: Only entrypoint is within the repository resolver so the user is already authenticated @@ -97,7 +98,7 @@ func (r *indexConfigurationResolver) Configuration(ctx context.Context) (_ *stri return nil, nil } - return resolverstubs.NonZeroPtr(string(configuration.Data)), nil + return pointers.NonZeroPtr(string(configuration.Data)), nil } func (r *indexConfigurationResolver) InferredConfiguration(ctx context.Context) (_ resolverstubs.InferredConfigurationResolver, err error) { diff --git a/enterprise/internal/codeintel/autoindexing/transport/graphql/root_resolver_inference.go b/enterprise/internal/codeintel/autoindexing/transport/graphql/root_resolver_inference.go index 15918f3b10a..d778f2ebe90 100644 --- a/enterprise/internal/codeintel/autoindexing/transport/graphql/root_resolver_inference.go +++ b/enterprise/internal/codeintel/autoindexing/transport/graphql/root_resolver_inference.go @@ -15,14 +15,15 @@ import ( resolverstubs "github.com/sourcegraph/sourcegraph/internal/codeintel/resolvers" "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/lib/codeintel/autoindex/config" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) // 🚨 SECURITY: Only site admins may infer auto-index jobs func (r *rootResolver) InferAutoIndexJobsForRepo(ctx context.Context, args *resolverstubs.InferAutoIndexJobsForRepoArgs) (_ resolverstubs.InferAutoIndexJobsResultResolver, err error) { ctx, _, endObservation := r.operations.inferAutoIndexJobsForRepo.WithErrors(ctx, &err, observation.Args{Attrs: []attribute.KeyValue{ attribute.String("repository", string(args.Repository)), - attribute.String("rev", resolverstubs.Deref(args.Rev, "")), - attribute.String("script", resolverstubs.Deref(args.Script, "")), + attribute.String("rev", pointers.Deref(args.Rev, "")), + attribute.String("script", pointers.Deref(args.Script, "")), }}) endObservation.OnCancel(ctx, 1, observation.Args{}) @@ -68,8 +69,8 @@ func (r *rootResolver) InferAutoIndexJobsForRepo(ctx context.Context, args *reso func (r *rootResolver) QueueAutoIndexJobsForRepo(ctx context.Context, args *resolverstubs.QueueAutoIndexJobsForRepoArgs) (_ []resolverstubs.PreciseIndexResolver, err error) { ctx, traceErrs, endObservation := r.operations.queueAutoIndexJobsForRepo.WithErrors(ctx, &err, observation.Args{Attrs: []attribute.KeyValue{ attribute.String("repository", string(args.Repository)), - attribute.String("rev", resolverstubs.Deref(args.Rev, "")), - attribute.String("configuration", resolverstubs.Deref(args.Configuration, "")), + attribute.String("rev", pointers.Deref(args.Rev, "")), + attribute.String("configuration", pointers.Deref(args.Configuration, "")), }}) endObservation.OnCancel(ctx, 1, observation.Args{}) diff --git a/enterprise/internal/codeintel/codenav/transport/graphql/BUILD.bazel b/enterprise/internal/codeintel/codenav/transport/graphql/BUILD.bazel index 755d7400611..8f08aa5e1ff 100644 --- a/enterprise/internal/codeintel/codenav/transport/graphql/BUILD.bazel +++ b/enterprise/internal/codeintel/codenav/transport/graphql/BUILD.bazel @@ -36,6 +36,7 @@ go_library( "//internal/metrics", "//internal/observation", "//lib/errors", + "//lib/pointers", "@com_github_graph_gophers_graphql_go//:graphql-go", "@com_github_sourcegraph_go_lsp//:go-lsp", "@com_github_sourcegraph_log//:log", diff --git a/enterprise/internal/codeintel/codenav/transport/graphql/root_resolver_diagnostics.go b/enterprise/internal/codeintel/codenav/transport/graphql/root_resolver_diagnostics.go index 5494668b59e..7b50ee1c106 100644 --- a/enterprise/internal/codeintel/codenav/transport/graphql/root_resolver_diagnostics.go +++ b/enterprise/internal/codeintel/codenav/transport/graphql/root_resolver_diagnostics.go @@ -9,6 +9,7 @@ import ( "github.com/sourcegraph/sourcegraph/enterprise/internal/codeintel/shared/resolvers/gitresolvers" resolverstubs "github.com/sourcegraph/sourcegraph/internal/codeintel/resolvers" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) // DefaultDiagnosticsPageSize is the diagnostic result page size when no limit is supplied. @@ -16,7 +17,7 @@ const DefaultDiagnosticsPageSize = 100 // Diagnostics returns the diagnostics for documents with the given path prefix. func (r *gitBlobLSIFDataResolver) Diagnostics(ctx context.Context, args *resolverstubs.LSIFDiagnosticsArgs) (_ resolverstubs.DiagnosticConnectionResolver, err error) { - limit := int(resolverstubs.Deref(args.First, DefaultDiagnosticsPageSize)) + limit := int(pointers.Deref(args.First, DefaultDiagnosticsPageSize)) if limit <= 0 { return nil, ErrIllegalLimit } @@ -55,13 +56,13 @@ func newDiagnosticResolver(diagnostic codenav.DiagnosticAtUpload, locationResolv func (r *diagnosticResolver) Severity() (*string, error) { return toSeverity(r.diagnostic.Severity) } func (r *diagnosticResolver) Code() (*string, error) { - return resolverstubs.NonZeroPtr(r.diagnostic.Code), nil + return pointers.NonZeroPtr(r.diagnostic.Code), nil } func (r *diagnosticResolver) Source() (*string, error) { - return resolverstubs.NonZeroPtr(r.diagnostic.Source), nil + return pointers.NonZeroPtr(r.diagnostic.Source), nil } func (r *diagnosticResolver) Message() (*string, error) { - return resolverstubs.NonZeroPtr(r.diagnostic.Message), nil + return pointers.NonZeroPtr(r.diagnostic.Message), nil } func (r *diagnosticResolver) Location(ctx context.Context) (resolverstubs.LocationResolver, error) { diff --git a/enterprise/internal/codeintel/codenav/transport/graphql/root_resolver_implementations.go b/enterprise/internal/codeintel/codenav/transport/graphql/root_resolver_implementations.go index 5c0df9c35ca..6baff6f5eb1 100644 --- a/enterprise/internal/codeintel/codenav/transport/graphql/root_resolver_implementations.go +++ b/enterprise/internal/codeintel/codenav/transport/graphql/root_resolver_implementations.go @@ -11,6 +11,7 @@ import ( "github.com/sourcegraph/sourcegraph/enterprise/internal/codeintel/codenav" resolverstubs "github.com/sourcegraph/sourcegraph/internal/codeintel/resolvers" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) // DefaultReferencesPageSize is the implementation result page size when no limit is supplied. @@ -20,7 +21,7 @@ const DefaultImplementationsPageSize = 100 var ErrIllegalLimit = errors.New("illegal limit") func (r *gitBlobLSIFDataResolver) Implementations(ctx context.Context, args *resolverstubs.LSIFPagedQueryPositionArgs) (_ resolverstubs.LocationConnectionResolver, err error) { - limit := int(resolverstubs.Deref(args.First, DefaultImplementationsPageSize)) + limit := int(pointers.Deref(args.First, DefaultImplementationsPageSize)) if limit <= 0 { return nil, ErrIllegalLimit } @@ -63,11 +64,11 @@ func (r *gitBlobLSIFDataResolver) Implementations(ctx context.Context, args *res impls = filtered } - return newLocationConnectionResolver(impls, resolverstubs.NonZeroPtr(nextCursor), r.locationResolver), nil + return newLocationConnectionResolver(impls, pointers.NonZeroPtr(nextCursor), r.locationResolver), nil } func (r *gitBlobLSIFDataResolver) Prototypes(ctx context.Context, args *resolverstubs.LSIFPagedQueryPositionArgs) (_ resolverstubs.LocationConnectionResolver, err error) { - limit := int(resolverstubs.Deref(args.First, DefaultImplementationsPageSize)) + limit := int(pointers.Deref(args.First, DefaultImplementationsPageSize)) if limit <= 0 { return nil, ErrIllegalLimit } @@ -110,7 +111,7 @@ func (r *gitBlobLSIFDataResolver) Prototypes(ctx context.Context, args *resolver prototypes = filtered } - return newLocationConnectionResolver(prototypes, resolverstubs.NonZeroPtr(nextCursor), r.locationResolver), nil + return newLocationConnectionResolver(prototypes, pointers.NonZeroPtr(nextCursor), r.locationResolver), nil } // diff --git a/enterprise/internal/codeintel/codenav/transport/graphql/root_resolver_references.go b/enterprise/internal/codeintel/codenav/transport/graphql/root_resolver_references.go index d6d6d9a39d1..72bbc6aa151 100644 --- a/enterprise/internal/codeintel/codenav/transport/graphql/root_resolver_references.go +++ b/enterprise/internal/codeintel/codenav/transport/graphql/root_resolver_references.go @@ -11,13 +11,14 @@ import ( "github.com/sourcegraph/sourcegraph/enterprise/internal/codeintel/codenav" resolverstubs "github.com/sourcegraph/sourcegraph/internal/codeintel/resolvers" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) const DefaultReferencesPageSize = 100 // References returns the list of source locations that reference the symbol at the given position. func (r *gitBlobLSIFDataResolver) References(ctx context.Context, args *resolverstubs.LSIFPagedQueryPositionArgs) (_ resolverstubs.LocationConnectionResolver, err error) { - limit := int(resolverstubs.Deref(args.First, DefaultReferencesPageSize)) + limit := int(pointers.Deref(args.First, DefaultReferencesPageSize)) if limit <= 0 { return nil, ErrIllegalLimit } @@ -60,7 +61,7 @@ func (r *gitBlobLSIFDataResolver) References(ctx context.Context, args *resolver refs = filtered } - return newLocationConnectionResolver(refs, resolverstubs.NonZeroPtr(nextCursor), r.locationResolver), nil + return newLocationConnectionResolver(refs, pointers.NonZeroPtr(nextCursor), r.locationResolver), nil } // diff --git a/enterprise/internal/codeintel/policies/BUILD.bazel b/enterprise/internal/codeintel/policies/BUILD.bazel index b4c7138f2f0..f3ccbfe5c93 100644 --- a/enterprise/internal/codeintel/policies/BUILD.bazel +++ b/enterprise/internal/codeintel/policies/BUILD.bazel @@ -58,6 +58,7 @@ go_test( "//internal/observation", "//internal/timeutil", "//internal/types", + "//lib/pointers", "@com_github_derision_test_glock//:glock", "@com_github_google_go_cmp//cmp", ], diff --git a/enterprise/internal/codeintel/policies/internal/store/store_test.go b/enterprise/internal/codeintel/policies/internal/store/store_test.go index 35dc6aee582..9b39e775c8f 100644 --- a/enterprise/internal/codeintel/policies/internal/store/store_test.go +++ b/enterprise/internal/codeintel/policies/internal/store/store_test.go @@ -48,10 +48,6 @@ func insertRepo(t testing.TB, db database.DB, id int, name string, private bool) } } -func boolPtr(value bool) *bool { - return &value -} - // scanPolicyRepositories returns a map of policyIDs that have a slice of their correspondent repoIDs (repoIDs associated with that policyIDs). func scanPolicyRepositories(rows *sql.Rows, queryErr error) (_ map[int][]int, err error) { if queryErr != nil { diff --git a/enterprise/internal/codeintel/policies/service_test.go b/enterprise/internal/codeintel/policies/service_test.go index b12c755ba9c..bd345964091 100644 --- a/enterprise/internal/codeintel/policies/service_test.go +++ b/enterprise/internal/codeintel/policies/service_test.go @@ -17,6 +17,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" "github.com/sourcegraph/sourcegraph/internal/observation" internaltypes "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestGetRetentionPolicyOverview(t *testing.T) { @@ -46,7 +47,7 @@ func TestGetRetentionPolicyOverview(t *testing.T) { mockPolicies: []policiesshared.RetentionPolicyMatchCandidate{ { ConfigurationPolicy: &policiesshared.ConfigurationPolicy{ - RetentionDuration: timePtr(time.Hour * 24), + RetentionDuration: pointers.Ptr(time.Hour * 24), RetainIntermediateCommits: false, Type: policiesshared.GitObjectTypeTag, Pattern: "*", @@ -74,7 +75,7 @@ func TestGetRetentionPolicyOverview(t *testing.T) { mockPolicies: []policiesshared.RetentionPolicyMatchCandidate{ { ConfigurationPolicy: &policiesshared.ConfigurationPolicy{ - RetentionDuration: timePtr(time.Hour * 24), + RetentionDuration: pointers.Ptr(time.Hour * 24), RetainIntermediateCommits: false, Type: policiesshared.GitObjectTypeTag, Pattern: "*", @@ -125,7 +126,7 @@ func TestGetRetentionPolicyOverview(t *testing.T) { mockPolicies: []policiesshared.RetentionPolicyMatchCandidate{ { ConfigurationPolicy: &policiesshared.ConfigurationPolicy{ - RetentionDuration: timePtr(time.Hour * 24), + RetentionDuration: pointers.Ptr(time.Hour * 24), RetainIntermediateCommits: false, Type: policiesshared.GitObjectTypeTag, Pattern: "*", @@ -134,7 +135,7 @@ func TestGetRetentionPolicyOverview(t *testing.T) { }, { ConfigurationPolicy: &policiesshared.ConfigurationPolicy{ - RetentionDuration: timePtr(time.Hour * 24), + RetentionDuration: pointers.Ptr(time.Hour * 24), RetainIntermediateCommits: false, Type: policiesshared.GitObjectTypeTree, Pattern: "*", @@ -162,7 +163,7 @@ func TestGetRetentionPolicyOverview(t *testing.T) { mockPolicies: []policiesshared.RetentionPolicyMatchCandidate{ { ConfigurationPolicy: &policiesshared.ConfigurationPolicy{ - RetentionDuration: timePtr(time.Hour * 24), + RetentionDuration: pointers.Ptr(time.Hour * 24), RetainIntermediateCommits: false, Type: policiesshared.GitObjectTypeTag, Pattern: "*", @@ -252,7 +253,7 @@ func TestRetentionPolicyOverview_ByVisibility(t *testing.T) { mockPolicies: []policiesshared.RetentionPolicyMatchCandidate{ { ConfigurationPolicy: &policiesshared.ConfigurationPolicy{ - RetentionDuration: timePtr(time.Hour * 24), + RetentionDuration: pointers.Ptr(time.Hour * 24), RetainIntermediateCommits: false, Type: policiesshared.GitObjectTypeTag, Pattern: "*", @@ -329,10 +330,6 @@ func TestRetentionPolicyOverview_ByVisibility(t *testing.T) { } } -func timePtr(t time.Duration) *time.Duration { - return &t -} - func mockConfigurationPolicies(policies []policiesshared.RetentionPolicyMatchCandidate) (mockedCandidates []policiesshared.RetentionPolicyMatchCandidate, mockedPolicies []policiesshared.ConfigurationPolicy) { for i, policy := range policies { if policy.ConfigurationPolicy != nil { diff --git a/enterprise/internal/codeintel/policies/transport/graphql/BUILD.bazel b/enterprise/internal/codeintel/policies/transport/graphql/BUILD.bazel index 4477039a00a..343fd33c14a 100644 --- a/enterprise/internal/codeintel/policies/transport/graphql/BUILD.bazel +++ b/enterprise/internal/codeintel/policies/transport/graphql/BUILD.bazel @@ -24,6 +24,7 @@ go_library( "//internal/metrics", "//internal/observation", "//lib/errors", + "//lib/pointers", "@com_github_graph_gophers_graphql_go//:graphql-go", "@io_opentelemetry_go_otel//attribute", ], diff --git a/enterprise/internal/codeintel/policies/transport/graphql/root_resolver_policy_mutations.go b/enterprise/internal/codeintel/policies/transport/graphql/root_resolver_policy_mutations.go index 47061697314..2efd8028877 100644 --- a/enterprise/internal/codeintel/policies/transport/graphql/root_resolver_policy_mutations.go +++ b/enterprise/internal/codeintel/policies/transport/graphql/root_resolver_policy_mutations.go @@ -10,12 +10,13 @@ import ( resolverstubs "github.com/sourcegraph/sourcegraph/internal/codeintel/resolvers" "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) // 🚨 SECURITY: Only site admins may modify code intelligence configuration policies func (r *rootResolver) CreateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *resolverstubs.CreateCodeIntelligenceConfigurationPolicyArgs) (_ resolverstubs.CodeIntelligenceConfigurationPolicyResolver, err error) { ctx, traceErrs, endObservation := r.operations.createConfigurationPolicy.WithErrors(ctx, &err, observation.Args{Attrs: []attribute.KeyValue{ - attribute.String("repository", string(resolverstubs.Deref(args.Repository, ""))), + attribute.String("repository", string(pointers.Deref(args.Repository, ""))), }}) endObservation.OnCancel(ctx, 1, observation.Args{}) diff --git a/enterprise/internal/codeintel/policies/transport/graphql/root_resolver_policy_queries.go b/enterprise/internal/codeintel/policies/transport/graphql/root_resolver_policy_queries.go index 586898a52da..30cee82680f 100644 --- a/enterprise/internal/codeintel/policies/transport/graphql/root_resolver_policy_queries.go +++ b/enterprise/internal/codeintel/policies/transport/graphql/root_resolver_policy_queries.go @@ -9,6 +9,7 @@ import ( policiesshared "github.com/sourcegraph/sourcegraph/enterprise/internal/codeintel/policies/shared" resolverstubs "github.com/sourcegraph/sourcegraph/internal/codeintel/resolvers" "github.com/sourcegraph/sourcegraph/internal/observation" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) const DefaultConfigurationPolicyPageSize = 50 @@ -16,13 +17,13 @@ const DefaultConfigurationPolicyPageSize = 50 // 🚨 SECURITY: dbstore layer handles authz for GetConfigurationPolicies func (r *rootResolver) CodeIntelligenceConfigurationPolicies(ctx context.Context, args *resolverstubs.CodeIntelligenceConfigurationPoliciesArgs) (_ resolverstubs.CodeIntelligenceConfigurationPolicyConnectionResolver, err error) { ctx, traceErrs, endObservation := r.operations.configurationPolicies.WithErrors(ctx, &err, observation.Args{Attrs: []attribute.KeyValue{ - attribute.Int("first", int(resolverstubs.Deref(args.First, 0))), - attribute.String("after", resolverstubs.Deref(args.After, "")), - attribute.String("repository", string(resolverstubs.Deref(args.Repository, ""))), - attribute.String("query", resolverstubs.Deref(args.Query, "")), - attribute.Bool("forDataRetention", resolverstubs.Deref(args.ForDataRetention, false)), - attribute.Bool("forIndexing", resolverstubs.Deref(args.ForIndexing, false)), - attribute.Bool("protected", resolverstubs.Deref(args.Protected, false)), + attribute.Int("first", int(pointers.Deref(args.First, 0))), + attribute.String("after", pointers.Deref(args.After, "")), + attribute.String("repository", string(pointers.Deref(args.Repository, ""))), + attribute.String("query", pointers.Deref(args.Query, "")), + attribute.Bool("forDataRetention", pointers.Deref(args.ForDataRetention, false)), + attribute.Bool("forIndexing", pointers.Deref(args.ForIndexing, false)), + attribute.Bool("protected", pointers.Deref(args.Protected, false)), }}) endObservation.OnCancel(ctx, 1, observation.Args{}) diff --git a/enterprise/internal/codeintel/policies/transport/graphql/root_resolver_previews.go b/enterprise/internal/codeintel/policies/transport/graphql/root_resolver_previews.go index 6743fd1e6ca..69ea5ed1849 100644 --- a/enterprise/internal/codeintel/policies/transport/graphql/root_resolver_previews.go +++ b/enterprise/internal/codeintel/policies/transport/graphql/root_resolver_previews.go @@ -12,6 +12,7 @@ import ( resolverstubs "github.com/sourcegraph/sourcegraph/internal/codeintel/resolvers" "github.com/sourcegraph/sourcegraph/internal/gqlutil" "github.com/sourcegraph/sourcegraph/internal/observation" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) const ( @@ -21,7 +22,7 @@ const ( func (r *rootResolver) PreviewRepositoryFilter(ctx context.Context, args *resolverstubs.PreviewRepositoryFilterArgs) (_ resolverstubs.RepositoryFilterPreviewResolver, err error) { ctx, _, endObservation := r.operations.previewRepoFilter.With(ctx, &err, observation.Args{Attrs: []attribute.KeyValue{ - attribute.Int("first", int(resolverstubs.Deref(args.First, 0))), + attribute.Int("first", int(pointers.Deref(args.First, 0))), attribute.StringSlice("patterns", args.Patterns), }}) defer endObservation(1, observation.Args{}) @@ -56,7 +57,7 @@ func (r *rootResolver) PreviewRepositoryFilter(ctx context.Context, args *resolv func (r *rootResolver) PreviewGitObjectFilter(ctx context.Context, id graphql.ID, args *resolverstubs.PreviewGitObjectFilterArgs) (_ resolverstubs.GitObjectFilterPreviewResolver, err error) { ctx, _, endObservation := r.operations.previewGitObjectFilter.With(ctx, &err, observation.Args{Attrs: []attribute.KeyValue{ - attribute.Int("first", int(resolverstubs.Deref(args.First, 0))), + attribute.Int("first", int(pointers.Deref(args.First, 0))), attribute.String("type", string(args.Type)), attribute.String("pattern", args.Pattern), }}) diff --git a/enterprise/internal/codeintel/sentinel/transport/graphql/BUILD.bazel b/enterprise/internal/codeintel/sentinel/transport/graphql/BUILD.bazel index 340c648148b..f2a268625b6 100644 --- a/enterprise/internal/codeintel/sentinel/transport/graphql/BUILD.bazel +++ b/enterprise/internal/codeintel/sentinel/transport/graphql/BUILD.bazel @@ -19,6 +19,7 @@ go_library( "//internal/gqlutil", "//internal/metrics", "//internal/observation", + "//lib/pointers", "@com_github_graph_gophers_graphql_go//:graphql-go", "@io_opentelemetry_go_otel//attribute", ], diff --git a/enterprise/internal/codeintel/sentinel/transport/graphql/root_resolver.go b/enterprise/internal/codeintel/sentinel/transport/graphql/root_resolver.go index fcd98adbb14..024b9edf7d2 100644 --- a/enterprise/internal/codeintel/sentinel/transport/graphql/root_resolver.go +++ b/enterprise/internal/codeintel/sentinel/transport/graphql/root_resolver.go @@ -12,6 +12,7 @@ import ( resolverstubs "github.com/sourcegraph/sourcegraph/internal/codeintel/resolvers" "github.com/sourcegraph/sourcegraph/internal/gqlutil" "github.com/sourcegraph/sourcegraph/internal/observation" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) type rootResolver struct { @@ -45,8 +46,8 @@ func NewRootResolver( func (r *rootResolver) Vulnerabilities(ctx context.Context, args resolverstubs.GetVulnerabilitiesArgs) (_ resolverstubs.VulnerabilityConnectionResolver, err error) { ctx, _, endObservation := r.operations.getVulnerabilities.WithErrors(ctx, &err, observation.Args{Attrs: []attribute.KeyValue{ - attribute.Int("first", int(resolverstubs.Deref(args.First, 0))), - attribute.String("after", resolverstubs.Deref(args.After, "")), + attribute.Int("first", int(pointers.Deref(args.First, 0))), + attribute.String("after", pointers.Deref(args.After, "")), }}) endObservation.OnCancel(ctx, 1, observation.Args{}) @@ -73,8 +74,8 @@ func (r *rootResolver) Vulnerabilities(ctx context.Context, args resolverstubs.G func (r *rootResolver) VulnerabilityMatches(ctx context.Context, args resolverstubs.GetVulnerabilityMatchesArgs) (_ resolverstubs.VulnerabilityMatchConnectionResolver, err error) { ctx, errTracer, endObservation := r.operations.getMatches.WithErrors(ctx, &err, observation.Args{Attrs: []attribute.KeyValue{ - attribute.Int("first", int(resolverstubs.Deref(args.First, 0))), - attribute.String("after", resolverstubs.Deref(args.After, "")), + attribute.Int("first", int(pointers.Deref(args.First, 0))), + attribute.String("after", pointers.Deref(args.After, "")), }}) endObservation.OnCancel(ctx, 1, observation.Args{}) diff --git a/enterprise/internal/codeintel/uploads/internal/background/expirer/BUILD.bazel b/enterprise/internal/codeintel/uploads/internal/background/expirer/BUILD.bazel index dd1818b4fe8..e3547cdb0da 100644 --- a/enterprise/internal/codeintel/uploads/internal/background/expirer/BUILD.bazel +++ b/enterprise/internal/codeintel/uploads/internal/background/expirer/BUILD.bazel @@ -54,6 +54,7 @@ go_test( "//internal/workerutil", "//internal/workerutil/dbworker/store", "//lib/codeintel/precise", + "//lib/pointers", "@com_github_google_go_cmp//cmp", "@com_github_keegancsmith_sqlf//:sqlf", "@com_github_sourcegraph_scip//bindings/go/scip", diff --git a/enterprise/internal/codeintel/uploads/internal/background/expirer/job_expirer_test.go b/enterprise/internal/codeintel/uploads/internal/background/expirer/job_expirer_test.go index b70c19d9cfb..3f6ff22e8be 100644 --- a/enterprise/internal/codeintel/uploads/internal/background/expirer/job_expirer_test.go +++ b/enterprise/internal/codeintel/uploads/internal/background/expirer/job_expirer_test.go @@ -18,6 +18,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/internal/timeutil" internaltypes "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestUploadExpirer(t *testing.T) { @@ -93,10 +94,10 @@ func TestUploadExpirer(t *testing.T) { func setupMockPolicyService() *MockPolicyService { policies := []policiesshared.ConfigurationPolicy{ {ID: 1, RepositoryID: nil}, - {ID: 2, RepositoryID: intPtr(53)}, + {ID: 2, RepositoryID: pointers.Ptr(53)}, {ID: 3, RepositoryID: nil}, {ID: 4, RepositoryID: nil}, - {ID: 5, RepositoryID: intPtr(50)}, + {ID: 5, RepositoryID: pointers.Ptr(50)}, } getConfigurationPolicies := func(ctx context.Context, opts policiesshared.GetConfigurationPoliciesOptions) (filtered []policiesshared.ConfigurationPolicy, _ int, _ error) { @@ -261,10 +262,6 @@ func testUploadExpirerMockPolicyMatcher() *MockPolicyMatcher { return policyMatcher } -func intPtr(v int) *int { - return &v -} - func days(n int) *time.Duration { t := time.Hour * 24 * time.Duration(n) return &t diff --git a/enterprise/internal/codeintel/uploads/internal/store/BUILD.bazel b/enterprise/internal/codeintel/uploads/internal/store/BUILD.bazel index a442939e387..6f6dbee00a3 100644 --- a/enterprise/internal/codeintel/uploads/internal/store/BUILD.bazel +++ b/enterprise/internal/codeintel/uploads/internal/store/BUILD.bazel @@ -79,6 +79,7 @@ go_test( "//internal/observation", "//lib/codeintel/precise", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_google_go_cmp//cmp", "@com_github_keegancsmith_sqlf//:sqlf", diff --git a/enterprise/internal/codeintel/uploads/internal/store/cleanup_test.go b/enterprise/internal/codeintel/uploads/internal/store/cleanup_test.go index 3d37765c665..f1f953dd823 100644 --- a/enterprise/internal/codeintel/uploads/internal/store/cleanup_test.go +++ b/enterprise/internal/codeintel/uploads/internal/store/cleanup_test.go @@ -17,6 +17,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/observation" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestHardDeleteUploadsByIDs(t *testing.T) { @@ -574,24 +575,24 @@ func TestExpireFailedRecords(t *testing.T) { insertIndexes(t, db, // young failures (none removed) - uploadsshared.Index{ID: 1, RepositoryID: 50, Commit: makeCommit(1), FinishedAt: timePtr(now.Add(-time.Minute * 10)), State: "failed"}, - uploadsshared.Index{ID: 2, RepositoryID: 50, Commit: makeCommit(2), FinishedAt: timePtr(now.Add(-time.Minute * 20)), State: "failed"}, - uploadsshared.Index{ID: 3, RepositoryID: 50, Commit: makeCommit(3), FinishedAt: timePtr(now.Add(-time.Minute * 20)), State: "failed"}, + uploadsshared.Index{ID: 1, RepositoryID: 50, Commit: makeCommit(1), FinishedAt: pointers.Ptr(now.Add(-time.Minute * 10)), State: "failed"}, + uploadsshared.Index{ID: 2, RepositoryID: 50, Commit: makeCommit(2), FinishedAt: pointers.Ptr(now.Add(-time.Minute * 20)), State: "failed"}, + uploadsshared.Index{ID: 3, RepositoryID: 50, Commit: makeCommit(3), FinishedAt: pointers.Ptr(now.Add(-time.Minute * 20)), State: "failed"}, // failures prior to a success (both removed) - uploadsshared.Index{ID: 4, RepositoryID: 50, Commit: makeCommit(4), FinishedAt: timePtr(now.Add(-time.Hour * 10)), Root: "foo", State: "completed"}, - uploadsshared.Index{ID: 5, RepositoryID: 50, Commit: makeCommit(5), FinishedAt: timePtr(now.Add(-time.Hour * 12)), Root: "foo", State: "failed"}, - uploadsshared.Index{ID: 6, RepositoryID: 50, Commit: makeCommit(6), FinishedAt: timePtr(now.Add(-time.Hour * 14)), Root: "foo", State: "failed"}, + uploadsshared.Index{ID: 4, RepositoryID: 50, Commit: makeCommit(4), FinishedAt: pointers.Ptr(now.Add(-time.Hour * 10)), Root: "foo", State: "completed"}, + uploadsshared.Index{ID: 5, RepositoryID: 50, Commit: makeCommit(5), FinishedAt: pointers.Ptr(now.Add(-time.Hour * 12)), Root: "foo", State: "failed"}, + uploadsshared.Index{ID: 6, RepositoryID: 50, Commit: makeCommit(6), FinishedAt: pointers.Ptr(now.Add(-time.Hour * 14)), Root: "foo", State: "failed"}, // old failures (one is left for debugging) - uploadsshared.Index{ID: 7, RepositoryID: 51, Commit: makeCommit(7), FinishedAt: timePtr(now.Add(-time.Hour * 3)), State: "failed"}, - uploadsshared.Index{ID: 8, RepositoryID: 51, Commit: makeCommit(8), FinishedAt: timePtr(now.Add(-time.Hour * 4)), State: "failed"}, - uploadsshared.Index{ID: 9, RepositoryID: 51, Commit: makeCommit(9), FinishedAt: timePtr(now.Add(-time.Hour * 5)), State: "failed"}, + uploadsshared.Index{ID: 7, RepositoryID: 51, Commit: makeCommit(7), FinishedAt: pointers.Ptr(now.Add(-time.Hour * 3)), State: "failed"}, + uploadsshared.Index{ID: 8, RepositoryID: 51, Commit: makeCommit(8), FinishedAt: pointers.Ptr(now.Add(-time.Hour * 4)), State: "failed"}, + uploadsshared.Index{ID: 9, RepositoryID: 51, Commit: makeCommit(9), FinishedAt: pointers.Ptr(now.Add(-time.Hour * 5)), State: "failed"}, // failures prior to queued uploads (one removed; queued does not reset failures) uploadsshared.Index{ID: 10, RepositoryID: 52, Commit: makeCommit(10), Root: "foo", State: "queued"}, - uploadsshared.Index{ID: 11, RepositoryID: 52, Commit: makeCommit(11), FinishedAt: timePtr(now.Add(-time.Hour * 12)), Root: "foo", State: "failed"}, - uploadsshared.Index{ID: 12, RepositoryID: 52, Commit: makeCommit(12), FinishedAt: timePtr(now.Add(-time.Hour * 14)), Root: "foo", State: "failed"}, + uploadsshared.Index{ID: 11, RepositoryID: 52, Commit: makeCommit(11), FinishedAt: pointers.Ptr(now.Add(-time.Hour * 12)), Root: "foo", State: "failed"}, + uploadsshared.Index{ID: 12, RepositoryID: 52, Commit: makeCommit(12), FinishedAt: pointers.Ptr(now.Add(-time.Hour * 14)), Root: "foo", State: "failed"}, ) if _, _, err := store.ExpireFailedRecords(ctx, 100, time.Hour, now); err != nil { @@ -618,10 +619,6 @@ func TestExpireFailedRecords(t *testing.T) { // // -func timePtr(t time.Time) *time.Time { - return &t -} - func getIndexStates(db database.DB, ids ...int) (map[int]string, error) { if len(ids) == 0 { return nil, nil diff --git a/enterprise/internal/codeintel/uploads/transport/graphql/BUILD.bazel b/enterprise/internal/codeintel/uploads/transport/graphql/BUILD.bazel index 0f4dd450ddc..f1946f27c79 100644 --- a/enterprise/internal/codeintel/uploads/transport/graphql/BUILD.bazel +++ b/enterprise/internal/codeintel/uploads/transport/graphql/BUILD.bazel @@ -41,6 +41,7 @@ go_library( "//internal/metrics", "//internal/observation", "//lib/errors", + "//lib/pointers", "@com_github_grafana_regexp//:regexp", "@com_github_graph_gophers_graphql_go//:graphql-go", "@com_github_graph_gophers_graphql_go//relay", diff --git a/enterprise/internal/codeintel/uploads/transport/graphql/index_steps_resolver.go b/enterprise/internal/codeintel/uploads/transport/graphql/index_steps_resolver.go index 8d20d181721..f1722c69804 100644 --- a/enterprise/internal/codeintel/uploads/transport/graphql/index_steps_resolver.go +++ b/enterprise/internal/codeintel/uploads/transport/graphql/index_steps_resolver.go @@ -12,6 +12,7 @@ import ( resolverstubs "github.com/sourcegraph/sourcegraph/internal/codeintel/resolvers" "github.com/sourcegraph/sourcegraph/internal/executor" "github.com/sourcegraph/sourcegraph/internal/gqlutil" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) // indexStepsResolver resolves the steps of an index record. @@ -167,7 +168,7 @@ func newIndexStepResolver(siteAdminChecker sharedresolvers.SiteAdminChecker, ind func (r *indexStepResolver) Commands() []string { return r.index.LocalSteps } func (r *indexStepResolver) IndexerArgs() []string { return r.index.IndexerArgs } -func (r *indexStepResolver) Outfile() *string { return resolverstubs.NonZeroPtr(r.index.Outfile) } +func (r *indexStepResolver) Outfile() *string { return pointers.NonZeroPtr(r.index.Outfile) } func (r *indexStepResolver) RequestedEnvVars() *[]string { if len(r.index.RequestedEnvVars) == 0 { diff --git a/enterprise/internal/codeintel/uploads/transport/graphql/root_resolver_index_mutations.go b/enterprise/internal/codeintel/uploads/transport/graphql/root_resolver_index_mutations.go index a1addf0234f..fde41126d84 100644 --- a/enterprise/internal/codeintel/uploads/transport/graphql/root_resolver_index_mutations.go +++ b/enterprise/internal/codeintel/uploads/transport/graphql/root_resolver_index_mutations.go @@ -8,6 +8,7 @@ import ( uploadsshared "github.com/sourcegraph/sourcegraph/enterprise/internal/codeintel/uploads/shared" resolverstubs "github.com/sourcegraph/sourcegraph/internal/codeintel/resolvers" "github.com/sourcegraph/sourcegraph/internal/observation" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) // 🚨 SECURITY: Only site admins may modify code intelligence upload data @@ -67,7 +68,7 @@ func (r *rootResolver) DeletePreciseIndexes(ctx context.Context, args *resolvers return nil, err } } - term := resolverstubs.Deref(args.Query, "") + term := pointers.Deref(args.Query, "") visibleAtTip := false if args.IsLatestForRepo != nil { @@ -158,7 +159,7 @@ func (r *rootResolver) ReindexPreciseIndexes(ctx context.Context, args *resolver return nil, err } } - term := resolverstubs.Deref(args.Query, "") + term := pointers.Deref(args.Query, "") visibleAtTip := false if args.IsLatestForRepo != nil { diff --git a/enterprise/internal/database/BUILD.bazel b/enterprise/internal/database/BUILD.bazel index ab63c0de714..968bdea8dfc 100644 --- a/enterprise/internal/database/BUILD.bazel +++ b/enterprise/internal/database/BUILD.bazel @@ -110,6 +110,7 @@ go_test( "//internal/timeutil", "//internal/types", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_gitchander_permutation//:permutation", "@com_github_google_go_cmp//cmp", diff --git a/enterprise/internal/database/perms_store_test.go b/enterprise/internal/database/perms_store_test.go index 0800525926f..609b044d485 100644 --- a/enterprise/internal/database/perms_store_test.go +++ b/enterprise/internal/database/perms_store_test.go @@ -37,6 +37,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/timeutil" "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -3999,7 +4000,7 @@ func TestPermsStore_ListUserPermissions(t *testing.T) { Name: "TestPagination", UserID: 555, Args: &ListUserPermissionsArgs{ - PaginationArgs: &database.PaginationArgs{First: toIntPtr(2), After: toStringPtr("'public_repo_5'"), OrderBy: database.OrderBy{{Field: "repo.name"}}}, + PaginationArgs: &database.PaginationArgs{First: pointers.Ptr(2), After: pointers.Ptr("'public_repo_5'"), OrderBy: database.OrderBy{{Field: "repo.name"}}}, }, WantResults: []*listUserPermissionsResult{ { @@ -4184,7 +4185,7 @@ func TestPermsStore_ListRepoPermissions(t *testing.T) { Name: "TestPaginationWithPrivateRepo", RepoID: 1, Args: &ListRepoPermissionsArgs{ - PaginationArgs: &database.PaginationArgs{First: toIntPtr(1), After: toStringPtr("555"), OrderBy: database.OrderBy{{Field: "users.id"}}, Ascending: true}, + PaginationArgs: &database.PaginationArgs{First: pointers.Ptr(1), After: pointers.Ptr("555"), OrderBy: database.OrderBy{{Field: "users.id"}}, Ascending: true}, }, WantResults: []*listRepoPermissionsResult{ { @@ -4364,14 +4365,6 @@ type listRepoPermissionsResult struct { Reason UserRepoPermissionReason } -func toIntPtr(num int) *int { - return &num -} - -func toStringPtr(str string) *string { - return &str -} - type fakeProvider struct { codeHost *extsvc.CodeHost extAcct *extsvc.Account diff --git a/enterprise/internal/insights/store/BUILD.bazel b/enterprise/internal/insights/store/BUILD.bazel index 160caeac577..c1bdc85ac35 100644 --- a/enterprise/internal/insights/store/BUILD.bazel +++ b/enterprise/internal/insights/store/BUILD.bazel @@ -60,6 +60,7 @@ go_test( "//internal/database/dbtest", "//internal/timeutil", "//lib/errors", + "//lib/pointers", "@com_github_google_go_cmp//cmp", "@com_github_hexops_autogold_v2//:autogold", "@com_github_hexops_valast//:valast", diff --git a/enterprise/internal/insights/store/store_benchs_test.go b/enterprise/internal/insights/store/store_benchs_test.go index be8c0cd0037..e80e4d0629c 100644 --- a/enterprise/internal/insights/store/store_benchs_test.go +++ b/enterprise/internal/insights/store/store_benchs_test.go @@ -16,17 +16,15 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/timeutil" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func initializeData(ctx context.Context, store *Store, repos, times int, withCapture int) string { var cv []*string - strPtr := func(s string) *string { - return &s - } if withCapture > 0 { for i := 0; i < withCapture; i++ { - cv = append(cv, strPtr(fmt.Sprintf("%d", i))) + cv = append(cv, pointers.Ptr(fmt.Sprintf("%d", i))) } } else { cv = append(cv, nil) diff --git a/enterprise/internal/insights/store/store_test.go b/enterprise/internal/insights/store/store_test.go index 08bbee8f2f5..2aafcb6e89f 100644 --- a/enterprise/internal/insights/store/store_test.go +++ b/enterprise/internal/insights/store/store_test.go @@ -20,6 +20,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/timeutil" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestSeriesPoints(t *testing.T) { @@ -148,8 +149,7 @@ func TestCountData(t *testing.T) { return v } timePtr := func(s string) *time.Time { - t := timeValue(s) - return &t + return pointers.Ptr(timeValue(s)) } optionalString := func(v string) *string { return &v } optionalRepoID := func(v api.RepoID) *api.RepoID { return &v } diff --git a/enterprise/internal/licensing/BUILD.bazel b/enterprise/internal/licensing/BUILD.bazel index c45a154188a..f21bd44b7e5 100644 --- a/enterprise/internal/licensing/BUILD.bazel +++ b/enterprise/internal/licensing/BUILD.bazel @@ -56,6 +56,7 @@ go_test( deps = [ "//enterprise/internal/license", "//internal/redispool", + "//lib/pointers", "@com_github_derision_test_glock//:glock", "@com_github_gomodule_redigo//redis", "@com_github_google_go_cmp//cmp", diff --git a/enterprise/internal/licensing/codygateway_test.go b/enterprise/internal/licensing/codygateway_test.go index 47d6f056fe0..51cca0cffc7 100644 --- a/enterprise/internal/licensing/codygateway_test.go +++ b/enterprise/internal/licensing/codygateway_test.go @@ -4,6 +4,8 @@ import ( "testing" "github.com/google/go-cmp/cmp" + + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestNewCodyGatewayChatRateLimit(t *testing.T) { @@ -17,7 +19,7 @@ func TestNewCodyGatewayChatRateLimit(t *testing.T) { { name: "Enterprise plan with GPT tag and user count", plan: PlanEnterprise1, - userCount: intPtr(50), + userCount: pointers.Ptr(50), licenseTags: []string{GPTLLMAccessTag}, want: CodyGatewayRateLimit{ AllowedModels: []string{"openai/gpt-4", "openai/gpt-3.5-turbo"}, @@ -28,7 +30,7 @@ func TestNewCodyGatewayChatRateLimit(t *testing.T) { { name: "Enterprise plan with no GPT tag", plan: PlanEnterprise1, - userCount: intPtr(50), + userCount: pointers.Ptr(50), want: CodyGatewayRateLimit{ AllowedModels: []string{"anthropic/claude-v1", "anthropic/claude-instant-v1"}, Limit: 2500, @@ -75,7 +77,7 @@ func TestCodyGatewayCodeRateLimit(t *testing.T) { { name: "Enterprise plan with GPT tag and user count", plan: PlanEnterprise1, - userCount: intPtr(50), + userCount: pointers.Ptr(50), licenseTags: []string{GPTLLMAccessTag}, want: CodyGatewayRateLimit{ AllowedModels: []string{"openai/gpt-3.5-turbo"}, @@ -86,7 +88,7 @@ func TestCodyGatewayCodeRateLimit(t *testing.T) { { name: "Enterprise plan with no GPT tag", plan: PlanEnterprise1, - userCount: intPtr(50), + userCount: pointers.Ptr(50), want: CodyGatewayRateLimit{ AllowedModels: []string{"anthropic/claude-instant-v1"}, Limit: 50000, @@ -133,7 +135,7 @@ func TestCodyGatewayEmbeddingsRateLimit(t *testing.T) { { name: "Enterprise plan", plan: PlanEnterprise1, - userCount: intPtr(50), + userCount: pointers.Ptr(50), want: CodyGatewayRateLimit{ AllowedModels: []string{"openai/text-embedding-ada-002"}, Limit: 20 * 50 * 2_500_000 / 30, @@ -168,5 +170,3 @@ func TestCodyGatewayEmbeddingsRateLimit(t *testing.T) { }) } } - -func intPtr(i int) *int { return &i } diff --git a/enterprise/internal/rockskip/BUILD.bazel b/enterprise/internal/rockskip/BUILD.bazel index 025a2691ab4..96b97474128 100644 --- a/enterprise/internal/rockskip/BUILD.bazel +++ b/enterprise/internal/rockskip/BUILD.bazel @@ -59,6 +59,7 @@ go_test( "//internal/gitserver/gitdomain", "//internal/search", "//lib/errors", + "//lib/pointers", "@com_github_google_go_cmp//cmp", "@com_github_sourcegraph_go_ctags//:go-ctags", "@com_github_sourcegraph_log//logtest", diff --git a/enterprise/internal/rockskip/search_test.go b/enterprise/internal/rockskip/search_test.go index 5443f2afec2..090c9dfbe05 100644 --- a/enterprise/internal/rockskip/search_test.go +++ b/enterprise/internal/rockskip/search_test.go @@ -4,6 +4,8 @@ import ( "testing" "github.com/google/go-cmp/cmp" + + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestIsFileExtensionMatch(t *testing.T) { @@ -37,16 +39,14 @@ func TestIsFileExtensionMatch(t *testing.T) { } func TestIsLiteralPrefix(t *testing.T) { - ptr := func(s string) *string { return &s } - tests := []struct { expr string prefix *string }{ {``, nil}, - {`^`, ptr(``)}, - {`^foo`, ptr(`foo`)}, - {`^foo/bar\.go`, ptr(`foo/bar.go`)}, + {`^`, pointers.Ptr(``)}, + {`^foo`, pointers.Ptr(`foo`)}, + {`^foo/bar\.go`, pointers.Ptr(`foo/bar.go`)}, {`foo/bar\.go`, nil}, } diff --git a/enterprise/internal/scim/BUILD.bazel b/enterprise/internal/scim/BUILD.bazel index e7293457cfc..71ac90aeab7 100644 --- a/enterprise/internal/scim/BUILD.bazel +++ b/enterprise/internal/scim/BUILD.bazel @@ -69,6 +69,7 @@ go_test( "//internal/txemail", "//internal/types", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_elimity_com_scim//:scim", "@com_github_elimity_com_scim//errors", diff --git a/enterprise/internal/scim/user_patch_test.go b/enterprise/internal/scim/user_patch_test.go index c2564f9da38..6ab81040b9c 100644 --- a/enterprise/internal/scim/user_patch_test.go +++ b/enterprise/internal/scim/user_patch_test.go @@ -16,6 +16,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -122,7 +123,7 @@ func Test_UserResourceHandler_PatchRemoveWithFilter(t *testing.T) { userResourceHandler := NewUserResourceHandler(context.Background(), &observation.TestContext, db) operations := []scim.PatchOperation{ {Op: "remove", Path: parseStringPath("emails[type eq \"work\" and primary eq false]")}, - {Op: "remove", Path: createPath(AttrName, strPtr(AttrNameMiddle))}, + {Op: "remove", Path: createPath(AttrName, pointers.Ptr(AttrNameMiddle))}, } userRes, err := userResourceHandler.Patch(createDummyRequest(), "1", operations) @@ -237,7 +238,7 @@ func Test_UserResourceHandler_PatchNoChange(t *testing.T) { db := createMockDB() userResourceHandler := NewUserResourceHandler(context.Background(), &observation.TestContext, db) operations := []scim.PatchOperation{ - {Op: "replace", Path: createPath(AttrName, strPtr(AttrNameGiven)), Value: "Nannie"}, + {Op: "replace", Path: createPath(AttrName, pointers.Ptr(AttrNameGiven)), Value: "Nannie"}, } userRes, err := userResourceHandler.Patch(createDummyRequest(), "1", operations) @@ -303,7 +304,7 @@ func Test_UserResourceHandler_PatchReactiveUser(t *testing.T) { "type": "work", "value": "primary@work.com", "primary": true - }, + }, ], "name": { "givenName": "Nannie", @@ -421,11 +422,6 @@ func parseStringPath(path string) *filter.Path { return &f } -// strPtr returns a pointer to the given string. -func strPtr(s string) *string { - return &s -} - // toInterfaceSlice converts a slice of maps to a slice of interfaces. func toInterfaceSlice(maps ...map[string]interface{}) []interface{} { s := make([]interface{}, 0, len(maps)) diff --git a/internal/codeintel/resolvers/BUILD.bazel b/internal/codeintel/resolvers/BUILD.bazel index 69645ea460b..f4cd66353bd 100644 --- a/internal/codeintel/resolvers/BUILD.bazel +++ b/internal/codeintel/resolvers/BUILD.bazel @@ -22,6 +22,7 @@ go_library( "//internal/markdown", "//internal/types", "//lib/errors", + "//lib/pointers", "@com_github_graph_gophers_graphql_go//:graphql-go", "@com_github_graph_gophers_graphql_go//relay", ], diff --git a/internal/codeintel/resolvers/utils.go b/internal/codeintel/resolvers/utils.go index 77973467b6a..d01d8615e2f 100644 --- a/internal/codeintel/resolvers/utils.go +++ b/internal/codeintel/resolvers/utils.go @@ -6,6 +6,8 @@ import ( "github.com/graph-gophers/graphql-go" "github.com/graph-gophers/graphql-go/relay" + + "github.com/sourcegraph/sourcegraph/lib/pointers" ) type ConnectionResolver[T any] interface { @@ -169,7 +171,7 @@ type ConnectionArgs struct { } func (a *ConnectionArgs) Limit(defaultValue int32) int32 { - return Deref(a.First, defaultValue) + return pointers.Deref(a.First, defaultValue) } type PagedConnectionArgs struct { @@ -199,30 +201,6 @@ func (er *EmptyResponse) AlwaysNil() *string { return nil } -func Ptr[T any](v T) *T { - return &v -} - -func NonZeroPtr[T comparable](v T) *T { - if v != zero[T]() { - return Ptr(v) - } - - return nil -} - -func zero[T any]() (zeroValue T) { - return zeroValue -} - -func Deref[T any](v *T, defaultValue T) T { - if v != nil { - return *v - } - - return defaultValue -} - func UnmarshalID[T any](id graphql.ID) (val T, err error) { err = relay.UnmarshalSpec(id, &val) return diff --git a/internal/conf/BUILD.bazel b/internal/conf/BUILD.bazel index a24a982f3b6..b543b1f03e7 100644 --- a/internal/conf/BUILD.bazel +++ b/internal/conf/BUILD.bazel @@ -62,6 +62,7 @@ go_test( "//internal/api/internalapi", "//internal/conf/conftypes", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_google_go_cmp//cmp", "@com_github_sourcegraph_log//:log", diff --git a/internal/conf/computed_test.go b/internal/conf/computed_test.go index aaef5f64c4d..1fdddc7583c 100644 --- a/internal/conf/computed_test.go +++ b/internal/conf/computed_test.go @@ -7,6 +7,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/assert" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -81,17 +82,17 @@ func TestGitMaxCodehostRequestsPerSecond(t *testing.T) { }, { name: "bad value should return default", - sc: &Unified{SiteConfiguration: schema.SiteConfiguration{GitMaxCodehostRequestsPerSecond: intPtr(-100)}}, + sc: &Unified{SiteConfiguration: schema.SiteConfiguration{GitMaxCodehostRequestsPerSecond: pointers.Ptr(-100)}}, want: -1, }, { name: "set 0 should return 0", - sc: &Unified{SiteConfiguration: schema.SiteConfiguration{GitMaxCodehostRequestsPerSecond: intPtr(0)}}, + sc: &Unified{SiteConfiguration: schema.SiteConfiguration{GitMaxCodehostRequestsPerSecond: pointers.Ptr(0)}}, want: 0, }, { name: "set non-0 should return non-0", - sc: &Unified{SiteConfiguration: schema.SiteConfiguration{GitMaxCodehostRequestsPerSecond: intPtr(100)}}, + sc: &Unified{SiteConfiguration: schema.SiteConfiguration{GitMaxCodehostRequestsPerSecond: pointers.Ptr(100)}}, want: 100, }, } @@ -320,14 +321,6 @@ func TestIsAccessRequestEnabled(t *testing.T) { } } -func boolPtr(b bool) *bool { - return &b -} - -func intPtr(i int) *int { - return &i -} - func TestCodyEnabled(t *testing.T) { tests := []struct { name string @@ -341,22 +334,22 @@ func TestCodyEnabled(t *testing.T) { }, { name: "cody enabled", - sc: schema.SiteConfiguration{CodyEnabled: boolPtr(true)}, + sc: schema.SiteConfiguration{CodyEnabled: pointers.Ptr(true)}, want: true, }, { name: "cody disabled", - sc: schema.SiteConfiguration{CodyEnabled: boolPtr(false)}, + sc: schema.SiteConfiguration{CodyEnabled: pointers.Ptr(false)}, want: false, }, { name: "cody enabled, completions configured", - sc: schema.SiteConfiguration{CodyEnabled: boolPtr(true), Completions: &schema.Completions{Model: "foobar"}}, + sc: schema.SiteConfiguration{CodyEnabled: pointers.Ptr(true), Completions: &schema.Completions{Model: "foobar"}}, want: true, }, { name: "cody disabled, completions configured", - sc: schema.SiteConfiguration{CodyEnabled: boolPtr(false), Completions: &schema.Completions{Model: "foobar"}}, + sc: schema.SiteConfiguration{CodyEnabled: pointers.Ptr(false), Completions: &schema.Completions{Model: "foobar"}}, want: false, }, { diff --git a/internal/database/BUILD.bazel b/internal/database/BUILD.bazel index fe87b2e0ae7..b4b5e6978b8 100644 --- a/internal/database/BUILD.bazel +++ b/internal/database/BUILD.bazel @@ -257,6 +257,7 @@ go_test( "//internal/types/typestest", "//internal/version", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_cockroachdb_errors//errbase", "@com_github_gofrs_uuid//:uuid", diff --git a/internal/database/bitbucket_project_permissions_test.go b/internal/database/bitbucket_project_permissions_test.go index 34efd8535ca..ff28e8d8336 100644 --- a/internal/database/bitbucket_project_permissions_test.go +++ b/internal/database/bitbucket_project_permissions_test.go @@ -13,6 +13,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/executor" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestBitbucketProjectPermissionsEnqueue(t *testing.T) { @@ -162,15 +163,15 @@ func TestScanFirstBitbucketProjectPermissionsJob(t *testing.T) { job, err := ScanBitbucketProjectPermissionJob(rows) require.NoError(t, err) require.NotNil(t, job) - entry := executor.ExecutionLogEntry{Key: "key", Command: []string{"command"}, StartTime: mustParseTime("2020-01-06"), ExitCode: intPtr(1), Out: "out", DurationMs: intPtr(1)} + entry := executor.ExecutionLogEntry{Key: "key", Command: []string{"command"}, StartTime: mustParseTime("2020-01-06"), ExitCode: pointers.Ptr(1), Out: "out", DurationMs: pointers.Ptr(1)} require.Equal(t, &types.BitbucketProjectPermissionJob{ ID: 1, State: "queued", - FailureMessage: stringPtr("failure message"), + FailureMessage: pointers.Ptr("failure message"), QueuedAt: mustParseTime("2020-01-01"), - StartedAt: timePtr(mustParseTime("2020-01-02")), - FinishedAt: timePtr(mustParseTime("2020-01-03")), - ProcessAfter: timePtr(mustParseTime("2020-01-04")), + StartedAt: pointers.Ptr(mustParseTime("2020-01-02")), + FinishedAt: pointers.Ptr(mustParseTime("2020-01-03")), + ProcessAfter: pointers.Ptr(mustParseTime("2020-01-04")), NumResets: 1, NumFailures: 2, LastHeartbeatAt: mustParseTime("2020-01-05"), @@ -310,9 +311,6 @@ func TestListJobs(t *testing.T) { }) } -func intPtr(v int) *int { return &v } -func stringPtr(v string) *string { return &v } - func mustParseTime(v string) time.Time { t, err := time.Parse("2006-01-02", v) if err != nil { diff --git a/internal/database/conf_test.go b/internal/database/conf_test.go index dae8959c801..0b76d642637 100644 --- a/internal/database/conf_test.go +++ b/internal/database/conf_test.go @@ -6,12 +6,14 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "github.com/sourcegraph/sourcegraph/lib/errors" "github.com/stretchr/testify/require" + "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/log/logtest" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestSiteGetLatestDefault(t *testing.T) { @@ -383,9 +385,6 @@ func TestGetSiteConfigCount(t *testing.T) { } func TestListSiteConfigs(t *testing.T) { - toIntPtr := func(n int) *int { return &n } - toStringPtr := func(n string) *string { return &n } - if testing.Short() { t.Skip() } @@ -413,106 +412,106 @@ func TestListSiteConfigs(t *testing.T) { { name: "first: 2 (subset of data)", listOptions: &PaginationArgs{ - First: toIntPtr(2), + First: pointers.Ptr(2), }, expectedIDs: []int32{5, 3}, }, { name: "last: 2 (subset of data)", listOptions: &PaginationArgs{ - Last: toIntPtr(2), + Last: pointers.Ptr(2), }, expectedIDs: []int32{1, 2}, }, { name: "first: 5 (all of data)", listOptions: &PaginationArgs{ - First: toIntPtr(5), + First: pointers.Ptr(5), }, expectedIDs: []int32{5, 3, 2, 1}, }, { name: "last: 5 (all of data)", listOptions: &PaginationArgs{ - Last: toIntPtr(5), + Last: pointers.Ptr(5), }, expectedIDs: []int32{1, 2, 3, 5}, }, { name: "first: 10 (more than data)", listOptions: &PaginationArgs{ - First: toIntPtr(10), + First: pointers.Ptr(10), }, expectedIDs: []int32{5, 3, 2, 1}, }, { name: "last: 10 (more than data)", listOptions: &PaginationArgs{ - Last: toIntPtr(10), + Last: pointers.Ptr(10), }, expectedIDs: []int32{1, 2, 3, 5}, }, { name: "first: 2, after: 5", listOptions: &PaginationArgs{ - First: toIntPtr(2), - After: toStringPtr("5"), + First: pointers.Ptr(2), + After: pointers.Ptr("5"), }, expectedIDs: []int32{3, 2}, }, { name: "first: 6, after: 5 (overflow)", listOptions: &PaginationArgs{ - First: toIntPtr(6), - After: toStringPtr("5"), + First: pointers.Ptr(6), + After: pointers.Ptr("5"), }, expectedIDs: []int32{3, 2, 1}, }, { name: "last: 2, after: 5", listOptions: &PaginationArgs{ - Last: toIntPtr(2), - After: toStringPtr("5"), + Last: pointers.Ptr(2), + After: pointers.Ptr("5"), }, expectedIDs: []int32{1, 2}, }, { name: "last: 6, after: 5 (overflow)", listOptions: &PaginationArgs{ - Last: toIntPtr(6), - After: toStringPtr("5"), + Last: pointers.Ptr(6), + After: pointers.Ptr("5"), }, expectedIDs: []int32{1, 2, 3}, }, { name: "first: 2, before: 1", listOptions: &PaginationArgs{ - First: toIntPtr(2), - Before: toStringPtr("1"), + First: pointers.Ptr(2), + Before: pointers.Ptr("1"), }, expectedIDs: []int32{5, 3}, }, { name: "first: 6, before: 1 (overflow)", listOptions: &PaginationArgs{ - First: toIntPtr(6), - Before: toStringPtr("1"), + First: pointers.Ptr(6), + Before: pointers.Ptr("1"), }, expectedIDs: []int32{5, 3, 2}, }, { name: "last: 2, before: 2", listOptions: &PaginationArgs{ - Last: toIntPtr(2), - Before: toStringPtr("2"), + Last: pointers.Ptr(2), + Before: pointers.Ptr("2"), }, expectedIDs: []int32{3, 5}, }, { name: "last: 6, before: 2 (overflow)", listOptions: &PaginationArgs{ - Last: toIntPtr(6), - Before: toStringPtr("2"), + Last: pointers.Ptr(6), + Before: pointers.Ptr("2"), }, expectedIDs: []int32{3, 5}, }, diff --git a/internal/database/event_logs_test.go b/internal/database/event_logs_test.go index d238c01d947..7729e218bc8 100644 --- a/internal/database/event_logs_test.go +++ b/internal/database/event_logs_test.go @@ -27,6 +27,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/internal/version" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -1446,13 +1447,13 @@ func TestEventLogs_ListAll(t *testing.T) { } t.Run("listed all SearchResultsQueried events", func(t *testing.T) { - have, err := db.EventLogs().ListAll(ctx, EventLogsListOptions{EventName: strptr("SearchResultsQueried")}) + have, err := db.EventLogs().ListAll(ctx, EventLogsListOptions{EventName: pointers.Ptr("SearchResultsQueried")}) require.NoError(t, err) assert.Len(t, have, 2) }) t.Run("listed one ViewRepository event", func(t *testing.T) { - opts := EventLogsListOptions{EventName: strptr("ViewRepository"), LimitOffset: &LimitOffset{Limit: 1}} + opts := EventLogsListOptions{EventName: pointers.Ptr("ViewRepository"), LimitOffset: &LimitOffset{Limit: 1}} have, err := db.EventLogs().ListAll(ctx, opts) require.NoError(t, err) assert.Len(t, have, 1) @@ -1460,14 +1461,14 @@ func TestEventLogs_ListAll(t *testing.T) { }) t.Run("listed zero events because of after parameter", func(t *testing.T) { - opts := EventLogsListOptions{EventName: strptr("ViewRepository"), AfterID: 3} + opts := EventLogsListOptions{EventName: pointers.Ptr("ViewRepository"), AfterID: 3} have, err := db.EventLogs().ListAll(ctx, opts) require.NoError(t, err) require.Empty(t, have) }) t.Run("listed one SearchResultsQueried event because of after parameter", func(t *testing.T) { - opts := EventLogsListOptions{EventName: strptr("SearchResultsQueried"), AfterID: 1} + opts := EventLogsListOptions{EventName: pointers.Ptr("SearchResultsQueried"), AfterID: 1} have, err := db.EventLogs().ListAll(ctx, opts) require.NoError(t, err) assert.Len(t, have, 1) @@ -1494,10 +1495,6 @@ func TestEventLogs_LatestPing(t *testing.T) { } }) - ptr := func(s string) *string { - return &s - } - t.Run("with existing pings in database", func(t *testing.T) { userID := int32(0) timestamp := timeutil.Now() @@ -1513,8 +1510,8 @@ func TestEventLogs_LatestPing(t *testing.T) { Timestamp: timestamp, Argument: json.RawMessage(`{"key": "value1"}`), PublicArgument: json.RawMessage("{}"), - DeviceID: ptr("device-id"), - InsertID: ptr("insert-id"), + DeviceID: pointers.Ptr("device-id"), + InsertID: pointers.Ptr("insert-id"), }, { UserID: 0, Name: "ping", @@ -1524,8 +1521,8 @@ func TestEventLogs_LatestPing(t *testing.T) { Timestamp: timestamp, Argument: json.RawMessage(`{"key": "value2"}`), PublicArgument: json.RawMessage("{}"), - DeviceID: ptr("device-id"), - InsertID: ptr("insert-id"), + DeviceID: pointers.Ptr("device-id"), + InsertID: pointers.Ptr("insert-id"), }, } for _, event := range events { @@ -1550,8 +1547,8 @@ func TestEventLogs_LatestPing(t *testing.T) { Source: events[1].Source, Timestamp: timestamp, } - expectedPing.DeviceID = ptr("device-id") - expectedPing.InsertID = ptr("insert-id") // set these values for test determinism + expectedPing.DeviceID = pointers.Ptr("device-id") + expectedPing.InsertID = pointers.Ptr("insert-id") // set these values for test determinism if diff := cmp.Diff(gotPing, expectedPing); diff != "" { t.Fatal(diff) } @@ -1650,7 +1647,6 @@ func TestEventLogs_OwnershipFeatureActivity(t *testing.T) { t.Skip() } t.Parallel() - ptr := func(i int32) *int32 { return &i } for name, testCase := range map[string]struct { now time.Time events []*Event @@ -1676,9 +1672,9 @@ func TestEventLogs_OwnershipFeatureActivity(t *testing.T) { queryEventNames: []string{"horse"}, stats: map[string]*types.OwnershipUsageStatisticsActiveUsers{ "horse": { - DAU: ptr(2), - WAU: ptr(2), - MAU: ptr(2), + DAU: pointers.Ptr(int32(2)), + WAU: pointers.Ptr(int32(2)), + MAU: pointers.Ptr(int32(2)), }, }, }, @@ -1701,9 +1697,9 @@ func TestEventLogs_OwnershipFeatureActivity(t *testing.T) { queryEventNames: []string{"horse"}, stats: map[string]*types.OwnershipUsageStatisticsActiveUsers{ "horse": { - DAU: ptr(0), - WAU: ptr(2), - MAU: ptr(2), + DAU: pointers.Ptr(int32(0)), + WAU: pointers.Ptr(int32(2)), + MAU: pointers.Ptr(int32(2)), }, }, }, @@ -1726,9 +1722,9 @@ func TestEventLogs_OwnershipFeatureActivity(t *testing.T) { queryEventNames: []string{"horse"}, stats: map[string]*types.OwnershipUsageStatisticsActiveUsers{ "horse": { - DAU: ptr(0), - WAU: ptr(0), - MAU: ptr(2), + DAU: pointers.Ptr(int32(0)), + WAU: pointers.Ptr(int32(0)), + MAU: pointers.Ptr(int32(2)), }, }, }, @@ -1751,9 +1747,9 @@ func TestEventLogs_OwnershipFeatureActivity(t *testing.T) { queryEventNames: []string{"horse"}, stats: map[string]*types.OwnershipUsageStatisticsActiveUsers{ "horse": { - DAU: ptr(0), - WAU: ptr(2), - MAU: ptr(0), + DAU: pointers.Ptr(int32(0)), + WAU: pointers.Ptr(int32(2)), + MAU: pointers.Ptr(int32(0)), }, }, }, @@ -1800,14 +1796,14 @@ func TestEventLogs_OwnershipFeatureActivity(t *testing.T) { queryEventNames: []string{"cat", "dog"}, stats: map[string]*types.OwnershipUsageStatisticsActiveUsers{ "cat": { - DAU: ptr(0), - WAU: ptr(0), - MAU: ptr(0), + DAU: pointers.Ptr(int32(0)), + WAU: pointers.Ptr(int32(0)), + MAU: pointers.Ptr(int32(0)), }, "dog": { - DAU: ptr(0), - WAU: ptr(0), - MAU: ptr(0), + DAU: pointers.Ptr(int32(0)), + WAU: pointers.Ptr(int32(0)), + MAU: pointers.Ptr(int32(0)), }, }, }, @@ -1854,14 +1850,14 @@ func TestEventLogs_OwnershipFeatureActivity(t *testing.T) { queryEventNames: []string{"horse", "ram"}, stats: map[string]*types.OwnershipUsageStatisticsActiveUsers{ "horse": { - DAU: ptr(2), - WAU: ptr(2), - MAU: ptr(2), + DAU: pointers.Ptr(int32(2)), + WAU: pointers.Ptr(int32(2)), + MAU: pointers.Ptr(int32(2)), }, "ram": { - DAU: ptr(2), - WAU: ptr(2), - MAU: ptr(2), + DAU: pointers.Ptr(int32(2)), + WAU: pointers.Ptr(int32(2)), + MAU: pointers.Ptr(int32(2)), }, }, }, @@ -1891,7 +1887,6 @@ func TestEventLogs_AggregatedRepoMetadataStats(t *testing.T) { t.Skip() } t.Parallel() - ptr := func(i int32) *int32 { return &i } now := time.Date(2000, time.January, 20, 12, 0, 0, 0, time.UTC) events := []*Event{ { @@ -1952,20 +1947,20 @@ func TestEventLogs_AggregatedRepoMetadataStats(t *testing.T) { stats: &types.RepoMetadataAggregatedEvents{ StartTime: time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC), CreateRepoMetadata: &types.EventStats{ - UsersCount: ptr(1), - EventsCount: ptr(2), + UsersCount: pointers.Ptr(int32(1)), + EventsCount: pointers.Ptr(int32(2)), }, UpdateRepoMetadata: &types.EventStats{ - UsersCount: ptr(1), - EventsCount: ptr(1), + UsersCount: pointers.Ptr(int32(1)), + EventsCount: pointers.Ptr(int32(1)), }, DeleteRepoMetadata: &types.EventStats{ - UsersCount: ptr(1), - EventsCount: ptr(1), + UsersCount: pointers.Ptr(int32(1)), + EventsCount: pointers.Ptr(int32(1)), }, SearchFilterUsage: &types.EventStats{ - UsersCount: ptr(1), - EventsCount: ptr(1), + UsersCount: pointers.Ptr(int32(1)), + EventsCount: pointers.Ptr(int32(1)), }, }, }, @@ -1975,20 +1970,20 @@ func TestEventLogs_AggregatedRepoMetadataStats(t *testing.T) { stats: &types.RepoMetadataAggregatedEvents{ StartTime: time.Date(now.Year(), now.Month(), now.Day()-int(now.Weekday()), 0, 0, 0, 0, time.UTC), CreateRepoMetadata: &types.EventStats{ - UsersCount: ptr(1), - EventsCount: ptr(3), + UsersCount: pointers.Ptr(int32(1)), + EventsCount: pointers.Ptr(int32(3)), }, UpdateRepoMetadata: &types.EventStats{ - UsersCount: ptr(1), - EventsCount: ptr(1), + UsersCount: pointers.Ptr(int32(1)), + EventsCount: pointers.Ptr(int32(1)), }, DeleteRepoMetadata: &types.EventStats{ - UsersCount: ptr(1), - EventsCount: ptr(1), + UsersCount: pointers.Ptr(int32(1)), + EventsCount: pointers.Ptr(int32(1)), }, SearchFilterUsage: &types.EventStats{ - UsersCount: ptr(1), - EventsCount: ptr(1), + UsersCount: pointers.Ptr(int32(1)), + EventsCount: pointers.Ptr(int32(1)), }, }, }, @@ -1998,20 +1993,20 @@ func TestEventLogs_AggregatedRepoMetadataStats(t *testing.T) { stats: &types.RepoMetadataAggregatedEvents{ StartTime: time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC), CreateRepoMetadata: &types.EventStats{ - UsersCount: ptr(1), - EventsCount: ptr(3), + UsersCount: pointers.Ptr(int32(1)), + EventsCount: pointers.Ptr(int32(3)), }, UpdateRepoMetadata: &types.EventStats{ - UsersCount: ptr(1), - EventsCount: ptr(1), + UsersCount: pointers.Ptr(int32(1)), + EventsCount: pointers.Ptr(int32(1)), }, DeleteRepoMetadata: &types.EventStats{ - UsersCount: ptr(1), - EventsCount: ptr(1), + UsersCount: pointers.Ptr(int32(1)), + EventsCount: pointers.Ptr(int32(1)), }, SearchFilterUsage: &types.EventStats{ - UsersCount: ptr(1), - EventsCount: ptr(1), + UsersCount: pointers.Ptr(int32(1)), + EventsCount: pointers.Ptr(int32(1)), }, }, }, diff --git a/internal/database/external_services_test.go b/internal/database/external_services_test.go index 4312e1e8970..2dd4f3b12fd 100644 --- a/internal/database/external_services_test.go +++ b/internal/database/external_services_test.go @@ -23,6 +23,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/api" "github.com/sourcegraph/sourcegraph/internal/timeutil" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/log/logtest" @@ -471,7 +472,7 @@ func TestExternalServicesStore_Update(t *testing.T) { update: &ExternalServiceUpdate{ DisplayName: strptr("GITHUB (updated) #5"), Config: strptr(`{"url": "https://github.com", "repositoryQuery": ["none"], "token": "def"}`), - TokenExpiresAt: timePtr(time.Now()), + TokenExpiresAt: pointers.Ptr(time.Now()), }, wantCloudDefault: true, wantTokenExpiresAt: true, diff --git a/internal/database/migration/store/BUILD.bazel b/internal/database/migration/store/BUILD.bazel index 5c685b51b58..efe69a781c1 100644 --- a/internal/database/migration/store/BUILD.bazel +++ b/internal/database/migration/store/BUILD.bazel @@ -60,6 +60,7 @@ go_test( "//internal/database/migration/shared", "//internal/observation", "//internal/timeutil", + "//lib/pointers", "@com_github_google_go_cmp//cmp", "@com_github_hexops_autogold_v2//:autogold", "@com_github_keegancsmith_sqlf//:sqlf", diff --git a/internal/database/migration/store/store_test.go b/internal/database/migration/store/store_test.go index a10b4ca3a32..8fa31b6e48b 100644 --- a/internal/database/migration/store/store_test.go +++ b/internal/database/migration/store/store_test.go @@ -22,6 +22,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database/migration/shared" "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/internal/timeutil" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestEnsureSchemaTable(t *testing.T) { @@ -210,9 +211,9 @@ func TestVersions(t *testing.T) { return testCase{t, version, up, nil, nil} } if *failed { - return testCase{t, version, up, boolPtr(false), strPtr("uh-oh")} + return testCase{t, version, up, pointers.Ptr(false), pointers.Ptr("uh-oh")} } - return testCase{t, version, up, boolPtr(true), nil} + return testCase{t, version, up, pointers.Ptr(true), nil} } t3 := timeutil.Now() @@ -221,17 +222,17 @@ func TestVersions(t *testing.T) { for _, migrationLog := range []testCase{ // Historic attempts - makeCase(t1, 1003, true, boolPtr(true)), makeCase(t2, 1003, false, boolPtr(true)), // 1003: successful up, successful down - makeCase(t1, 1004, true, boolPtr(true)), // 1004: successful up - makeCase(t1, 1006, true, boolPtr(false)), makeCase(t2, 1006, true, boolPtr(true)), // 1006: failed up, successful up + makeCase(t1, 1003, true, pointers.Ptr(true)), makeCase(t2, 1003, false, pointers.Ptr(true)), // 1003: successful up, successful down + makeCase(t1, 1004, true, pointers.Ptr(true)), // 1004: successful up + makeCase(t1, 1006, true, pointers.Ptr(false)), makeCase(t2, 1006, true, pointers.Ptr(true)), // 1006: failed up, successful up // Last attempts - makeCase(t3, 1001, true, boolPtr(false)), // successful up - makeCase(t3, 1002, false, boolPtr(false)), // successful down - makeCase(t3, 1003, true, nil), // pending up - makeCase(t3, 1004, false, nil), // pending down - makeCase(t3, 1005, true, boolPtr(true)), // failed up - makeCase(t3, 1006, false, boolPtr(true)), // failed down + makeCase(t3, 1001, true, pointers.Ptr(false)), // successful up + makeCase(t3, 1002, false, pointers.Ptr(false)), // successful down + makeCase(t3, 1003, true, nil), // pending up + makeCase(t3, 1004, false, nil), // pending down + makeCase(t3, 1005, true, pointers.Ptr(true)), // failed up + makeCase(t3, 1006, false, pointers.Ptr(true)), // failed down } { finishedAt := &migrationLog.startedAt if migrationLog.success == nil { @@ -346,19 +347,19 @@ func TestWrappedUp(t *testing.T) { Schema: defaultTestTableName, Version: 13, Up: true, - Success: boolPtr(true), + Success: pointers.Ptr(true), }, { Schema: defaultTestTableName, Version: 14, Up: true, - Success: boolPtr(true), + Success: pointers.Ptr(true), }, { Schema: defaultTestTableName, Version: 15, Up: true, - Success: boolPtr(true), + Success: pointers.Ptr(true), }, } @@ -395,7 +396,7 @@ func TestWrappedUp(t *testing.T) { Schema: defaultTestTableName, Version: 16, Up: true, - Success: boolPtr(true), + Success: pointers.Ptr(true), }) assertLogs(t, ctx, store, logs) assertVersions(t, ctx, store, []int{13, 14, 15, 16}, nil, nil) @@ -427,7 +428,7 @@ func TestWrappedUp(t *testing.T) { Schema: defaultTestTableName, Version: 17, Up: true, - Success: boolPtr(false), + Success: pointers.Ptr(false), }) assertLogs(t, ctx, store, logs) assertVersions(t, ctx, store, []int{13, 14, 15, 16}, nil, []int{17}) @@ -489,19 +490,19 @@ func TestWrappedDown(t *testing.T) { Schema: defaultTestTableName, Version: 12, Up: true, - Success: boolPtr(true), + Success: pointers.Ptr(true), }, { Schema: defaultTestTableName, Version: 13, Up: true, - Success: boolPtr(true), + Success: pointers.Ptr(true), }, { Schema: defaultTestTableName, Version: 14, Up: true, - Success: boolPtr(true), + Success: pointers.Ptr(true), }, } @@ -528,7 +529,7 @@ func TestWrappedDown(t *testing.T) { Schema: defaultTestTableName, Version: 14, Up: false, - Success: boolPtr(true), + Success: pointers.Ptr(true), }) assertLogs(t, ctx, store, logs) assertVersions(t, ctx, store, []int{12, 13}, nil, nil) @@ -555,7 +556,7 @@ func TestWrappedDown(t *testing.T) { Schema: defaultTestTableName, Version: 13, Up: false, - Success: boolPtr(false), + Success: pointers.Ptr(false), }) assertLogs(t, ctx, store, logs) assertVersions(t, ctx, store, []int{12, 13}, nil, nil) @@ -729,14 +730,6 @@ func testStoreWithName(db *sql.DB, name string) *Store { return NewWithDB(&observation.TestContext, db, name) } -func strPtr(v string) *string { - return &v -} - -func boolPtr(value bool) *bool { - return &value -} - func assertLogs(t *testing.T, ctx context.Context, store *Store, expectedLogs []migrationLog) { t.Helper() diff --git a/internal/database/outbound_webhook_jobs_test.go b/internal/database/outbound_webhook_jobs_test.go index 322c468e965..365f9b28e3d 100644 --- a/internal/database/outbound_webhook_jobs_test.go +++ b/internal/database/outbound_webhook_jobs_test.go @@ -16,6 +16,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/errcode" "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestOutboundWebhookJobs(t *testing.T) { @@ -47,7 +48,7 @@ func TestOutboundWebhookJobs(t *testing.T) { target **types.OutboundWebhookJob }{ "scoped": { - scope: stringPtr("scope"), + scope: pointers.Ptr("scope"), target: &scopedJob, }, "unscoped": { diff --git a/internal/database/outbound_webhooks_test.go b/internal/database/outbound_webhooks_test.go index fcf8e65f80c..d5917d188ee 100644 --- a/internal/database/outbound_webhooks_test.go +++ b/internal/database/outbound_webhooks_test.go @@ -17,6 +17,7 @@ import ( et "github.com/sourcegraph/sourcegraph/internal/encryption/testing" "github.com/sourcegraph/sourcegraph/internal/errcode" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestOutboundWebhooks(t *testing.T) { @@ -52,7 +53,7 @@ func TestOutboundWebhooks(t *testing.T) { t, user, ScopedEventType{EventType: "foo"}, ScopedEventType{EventType: "bar"}, - ScopedEventType{EventType: "quux", Scope: stringPtr("123")}, + ScopedEventType{EventType: "quux", Scope: pointers.Ptr("123")}, ) err := store.Create(ctx, createdWebhook) assert.NoError(t, err) @@ -95,11 +96,11 @@ func TestOutboundWebhooks(t *testing.T) { barOnlyWebhook := newSavedTestWebhook(t, user, ScopedEventType{EventType: "bar"}) quuxWithSameScopeWebhook := newSavedTestWebhook( t, user, - ScopedEventType{EventType: "quux", Scope: stringPtr("123")}, + ScopedEventType{EventType: "quux", Scope: pointers.Ptr("123")}, ) quuxWithDifferentScopeWebhook := newSavedTestWebhook( t, user, - ScopedEventType{EventType: "quux", Scope: stringPtr("456")}, + ScopedEventType{EventType: "quux", Scope: pointers.Ptr("456")}, ) allWebhooks := []*types.OutboundWebhook{ @@ -127,7 +128,7 @@ func TestOutboundWebhooks(t *testing.T) { opts: OutboundWebhookListOpts{ OutboundWebhookCountOpts: OutboundWebhookCountOpts{ EventTypes: []FilterEventType{ - {EventType: "not found", Scope: stringPtr(FilterEventTypeNoScope)}, + {EventType: "not found", Scope: pointers.Ptr(FilterEventTypeNoScope)}, }, }, }, @@ -137,7 +138,7 @@ func TestOutboundWebhooks(t *testing.T) { opts: OutboundWebhookListOpts{ OutboundWebhookCountOpts: OutboundWebhookCountOpts{ EventTypes: []FilterEventType{ - {EventType: "foo", Scope: stringPtr("bar")}, + {EventType: "foo", Scope: pointers.Ptr("bar")}, }, }, }, @@ -147,7 +148,7 @@ func TestOutboundWebhooks(t *testing.T) { opts: OutboundWebhookListOpts{ OutboundWebhookCountOpts: OutboundWebhookCountOpts{ EventTypes: []FilterEventType{ - {EventType: "quux", Scope: stringPtr("789")}, + {EventType: "quux", Scope: pointers.Ptr("789")}, }, }, }, @@ -173,8 +174,8 @@ func TestOutboundWebhooks(t *testing.T) { opts: OutboundWebhookListOpts{ OutboundWebhookCountOpts: OutboundWebhookCountOpts{ EventTypes: []FilterEventType{ - {EventType: "foo", Scope: stringPtr(FilterEventTypeNoScope)}, - {EventType: "quux", Scope: stringPtr(FilterEventTypeNoScope)}, + {EventType: "foo", Scope: pointers.Ptr(FilterEventTypeNoScope)}, + {EventType: "quux", Scope: pointers.Ptr(FilterEventTypeNoScope)}, }, }, }, @@ -188,10 +189,10 @@ func TestOutboundWebhooks(t *testing.T) { opts: OutboundWebhookListOpts{ OutboundWebhookCountOpts: OutboundWebhookCountOpts{ EventTypes: []FilterEventType{ - {EventType: "foo", Scope: stringPtr("no match")}, - {EventType: "quux", Scope: stringPtr("123")}, - {EventType: "quux", Scope: stringPtr("456")}, - {EventType: "quux", Scope: stringPtr("789")}, + {EventType: "foo", Scope: pointers.Ptr("no match")}, + {EventType: "quux", Scope: pointers.Ptr("123")}, + {EventType: "quux", Scope: pointers.Ptr("456")}, + {EventType: "quux", Scope: pointers.Ptr("789")}, }, }, }, @@ -205,7 +206,7 @@ func TestOutboundWebhooks(t *testing.T) { opts: OutboundWebhookListOpts{ OutboundWebhookCountOpts: OutboundWebhookCountOpts{ EventTypes: []FilterEventType{ - {EventType: "quux", Scope: stringPtr("123")}, + {EventType: "quux", Scope: pointers.Ptr("123")}, }, }, }, @@ -218,7 +219,7 @@ func TestOutboundWebhooks(t *testing.T) { opts: OutboundWebhookListOpts{ OutboundWebhookCountOpts: OutboundWebhookCountOpts{ EventTypes: []FilterEventType{{EventType: "bar"}, - {EventType: "quux", Scope: stringPtr("123")}, + {EventType: "quux", Scope: pointers.Ptr("123")}, }, }, }, @@ -287,7 +288,7 @@ func TestOutboundWebhooks(t *testing.T) { t.Run("append to the current event types", func(t *testing.T) { createdWebhook.EventTypes = append( createdWebhook.EventTypes, - types.OutboundWebhookEventType{EventType: "newer", Scope: stringPtr("abc")}, + types.OutboundWebhookEventType{EventType: "newer", Scope: pointers.Ptr("abc")}, ) err := store.Update(ctx, createdWebhook) assert.NoError(t, err) diff --git a/internal/database/permission_sync_jobs_test.go b/internal/database/permission_sync_jobs_test.go index 9b49d4572cf..0a87e07af19 100644 --- a/internal/database/permission_sync_jobs_test.go +++ b/internal/database/permission_sync_jobs_test.go @@ -10,12 +10,14 @@ import ( "github.com/google/go-cmp/cmp/cmpopts" "github.com/keegancsmith/sqlf" "github.com/sourcegraph/log/logtest" + "github.com/stretchr/testify/require" + "github.com/sourcegraph/sourcegraph/internal/api" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/errcode" "github.com/sourcegraph/sourcegraph/internal/timeutil" "github.com/sourcegraph/sourcegraph/internal/types" - "github.com/stretchr/testify/require" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestPermissionSyncJobs_CreateAndList(t *testing.T) { @@ -258,7 +260,7 @@ func TestPermissionSyncJobs_CreateAndList(t *testing.T) { }, { name: "User name search with pagination", - opts: ListPermissionSyncJobOpts{Query: "user-2", SearchType: PermissionsSyncSearchTypeUser, PaginationArgs: &PaginationArgs{First: intPtr(1)}}, + opts: ListPermissionSyncJobOpts{Query: "user-2", SearchType: PermissionsSyncSearchTypeUser, PaginationArgs: &PaginationArgs{First: pointers.Ptr(1)}}, wantJobs: jobs[2:3], }, { @@ -762,7 +764,7 @@ func TestPermissionSyncJobs_Pagination(t *testing.T) { }, { name: "First", - paginationArgs: PaginationArgs{Ascending: true, First: intPtr(5)}, + paginationArgs: PaginationArgs{Ascending: true, First: pointers.Ptr(5)}, wantJobs: jobs[:5], }, { diff --git a/internal/database/repo_kvps_test.go b/internal/database/repo_kvps_test.go index 25ad5406b7c..dc20686f72c 100644 --- a/internal/database/repo_kvps_test.go +++ b/internal/database/repo_kvps_test.go @@ -10,6 +10,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestRepoKVPs(t *testing.T) { @@ -26,13 +27,11 @@ func TestRepoKVPs(t *testing.T) { repo, err := db.Repos().GetByName(ctx, "repo") require.NoError(t, err) - strPtr := func(s string) *string { return &s } - t.Run("Create", func(t *testing.T) { t.Run("non-nil value", func(t *testing.T) { err := kvps.Create(ctx, repo.ID, KeyValuePair{ Key: "key1", - Value: strPtr("value1"), + Value: pointers.Ptr("value1"), }) require.NoError(t, err) }) @@ -50,7 +49,7 @@ func TestRepoKVPs(t *testing.T) { t.Run("exists", func(t *testing.T) { kvp, err := kvps.Get(ctx, repo.ID, "key1") require.NoError(t, err) - require.Equal(t, kvp, KeyValuePair{Key: "key1", Value: strPtr("value1")}) + require.Equal(t, kvp, KeyValuePair{Key: "key1", Value: pointers.Ptr("value1")}) }) t.Run("exists with nil value", func(t *testing.T) { @@ -73,7 +72,7 @@ func TestRepoKVPs(t *testing.T) { t.Run("ListKeys", func(t *testing.T) { t.Run("returns all", func(t *testing.T) { keys, err := kvps.ListKeys(ctx, RepoKVPListKeysOptions{}, PaginationArgs{ - First: intPtr(10), + First: pointers.Ptr(10), OrderBy: OrderBy{{Field: string(RepoKVPListKeyColumn)}}, }) require.NoError(t, err) @@ -82,8 +81,8 @@ func TestRepoKVPs(t *testing.T) { }) t.Run("returns when found match by query", func(t *testing.T) { - keys, err := kvps.ListKeys(ctx, RepoKVPListKeysOptions{Query: strPtr("tag")}, PaginationArgs{ - First: intPtr(10), + keys, err := kvps.ListKeys(ctx, RepoKVPListKeysOptions{Query: pointers.Ptr("tag")}, PaginationArgs{ + First: pointers.Ptr(10), OrderBy: OrderBy{{Field: string(RepoKVPListKeyColumn)}}, }) require.NoError(t, err) @@ -91,8 +90,8 @@ func TestRepoKVPs(t *testing.T) { }) t.Run("returns empty when found no match by query", func(t *testing.T) { - keys, err := kvps.ListKeys(ctx, RepoKVPListKeysOptions{Query: strPtr("nonexisting")}, PaginationArgs{ - First: intPtr(10), OrderBy: OrderBy{{Field: string(RepoKVPListKeyColumn)}}, + keys, err := kvps.ListKeys(ctx, RepoKVPListKeysOptions{Query: pointers.Ptr("nonexisting")}, PaginationArgs{ + First: pointers.Ptr(10), OrderBy: OrderBy{{Field: string(RepoKVPListKeyColumn)}}, }) require.NoError(t, err) require.Empty(t, keys) @@ -107,17 +106,17 @@ func TestRepoKVPs(t *testing.T) { }) t.Run("returns when found match by query", func(t *testing.T) { - count, err := kvps.CountKeys(ctx, RepoKVPListKeysOptions{Query: strPtr("ey")}) + count, err := kvps.CountKeys(ctx, RepoKVPListKeysOptions{Query: pointers.Ptr("ey")}) require.NoError(t, err) require.Equal(t, 1, count) - count, err = kvps.CountKeys(ctx, RepoKVPListKeysOptions{Query: strPtr("1")}) + count, err = kvps.CountKeys(ctx, RepoKVPListKeysOptions{Query: pointers.Ptr("1")}) require.NoError(t, err) require.Equal(t, 2, count) }) t.Run("returns empty when found no match by query", func(t *testing.T) { - count, err := kvps.CountKeys(ctx, RepoKVPListKeysOptions{Query: strPtr("nonexisting")}) + count, err := kvps.CountKeys(ctx, RepoKVPListKeysOptions{Query: pointers.Ptr("nonexisting")}) require.NoError(t, err) require.Empty(t, count) }) @@ -126,7 +125,7 @@ func TestRepoKVPs(t *testing.T) { t.Run("ListValues", func(t *testing.T) { t.Run("returns all", func(t *testing.T) { values, err := kvps.ListValues(ctx, RepoKVPListValuesOptions{Key: "key1"}, PaginationArgs{ - First: intPtr(10), + First: pointers.Ptr(10), OrderBy: OrderBy{{Field: string(RepoKVPListValueColumn)}}, }) require.NoError(t, err) @@ -134,8 +133,8 @@ func TestRepoKVPs(t *testing.T) { }) t.Run("returns when found match by query", func(t *testing.T) { - keys, err := kvps.ListValues(ctx, RepoKVPListValuesOptions{Key: "key1", Query: strPtr("val")}, PaginationArgs{ - First: intPtr(10), + keys, err := kvps.ListValues(ctx, RepoKVPListValuesOptions{Key: "key1", Query: pointers.Ptr("val")}, PaginationArgs{ + First: pointers.Ptr(10), OrderBy: OrderBy{{Field: string(RepoKVPListValueColumn)}}, }) require.NoError(t, err) @@ -143,8 +142,8 @@ func TestRepoKVPs(t *testing.T) { }) t.Run("returns empty when found no match by query", func(t *testing.T) { - keys, err := kvps.ListValues(ctx, RepoKVPListValuesOptions{Key: "key1", Query: strPtr("nonexisting")}, PaginationArgs{ - First: intPtr(10), OrderBy: OrderBy{{Field: string(RepoKVPListValueColumn)}}, + keys, err := kvps.ListValues(ctx, RepoKVPListValuesOptions{Key: "key1", Query: pointers.Ptr("nonexisting")}, PaginationArgs{ + First: pointers.Ptr(10), OrderBy: OrderBy{{Field: string(RepoKVPListValueColumn)}}, }) require.NoError(t, err) require.Empty(t, keys) @@ -159,13 +158,13 @@ func TestRepoKVPs(t *testing.T) { }) t.Run("returns when found match by query", func(t *testing.T) { - count, err := kvps.CountValues(ctx, RepoKVPListValuesOptions{Key: "key1", Query: strPtr("value")}) + count, err := kvps.CountValues(ctx, RepoKVPListValuesOptions{Key: "key1", Query: pointers.Ptr("value")}) require.NoError(t, err) require.Equal(t, 1, count) }) t.Run("returns empty when found no match by query", func(t *testing.T) { - count, err := kvps.CountValues(ctx, RepoKVPListValuesOptions{Key: "key1", Query: strPtr("nonexisting")}) + count, err := kvps.CountValues(ctx, RepoKVPListValuesOptions{Key: "key1", Query: pointers.Ptr("nonexisting")}) require.NoError(t, err) require.Empty(t, count) }) @@ -175,10 +174,10 @@ func TestRepoKVPs(t *testing.T) { t.Run("normal", func(t *testing.T) { kvp, err := kvps.Update(ctx, repo.ID, KeyValuePair{ Key: "key1", - Value: strPtr("value2"), + Value: pointers.Ptr("value2"), }) require.NoError(t, err) - require.Equal(t, kvp, KeyValuePair{Key: "key1", Value: strPtr("value2")}) + require.Equal(t, kvp, KeyValuePair{Key: "key1", Value: pointers.Ptr("value2")}) }) t.Run("into tag", func(t *testing.T) { @@ -193,16 +192,16 @@ func TestRepoKVPs(t *testing.T) { t.Run("from tag", func(t *testing.T) { kvp, err := kvps.Update(ctx, repo.ID, KeyValuePair{ Key: "key1", - Value: strPtr("value3"), + Value: pointers.Ptr("value3"), }) require.NoError(t, err) - require.Equal(t, kvp, KeyValuePair{Key: "key1", Value: strPtr("value3")}) + require.Equal(t, kvp, KeyValuePair{Key: "key1", Value: pointers.Ptr("value3")}) }) t.Run("does not exist", func(t *testing.T) { _, err := kvps.Update(ctx, repo.ID, KeyValuePair{ Key: "noexist", - Value: strPtr("value3"), + Value: pointers.Ptr("value3"), }) require.Error(t, err) }) diff --git a/internal/database/user_emails_test.go b/internal/database/user_emails_test.go index e5c4e4b82c4..e472b34b661 100644 --- a/internal/database/user_emails_test.go +++ b/internal/database/user_emails_test.go @@ -14,13 +14,10 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/errcode" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestUserEmail_NeedsVerificationCoolDown(t *testing.T) { - timePtr := func(t time.Time) *time.Time { - return &t - } - tests := []struct { name string lastVerificationSentAt *time.Time @@ -33,12 +30,12 @@ func TestUserEmail_NeedsVerificationCoolDown(t *testing.T) { }, { name: "needs cool down", - lastVerificationSentAt: timePtr(time.Now().Add(time.Minute)), + lastVerificationSentAt: pointers.Ptr(time.Now().Add(time.Minute)), needsCoolDown: true, }, { name: "does not need cool down", - lastVerificationSentAt: timePtr(time.Now().Add(-1 * time.Minute)), + lastVerificationSentAt: pointers.Ptr(time.Now().Add(-1 * time.Minute)), needsCoolDown: false, }, } diff --git a/internal/database/webhook_logs_test.go b/internal/database/webhook_logs_test.go index 5f06359fc9d..d967e29125c 100644 --- a/internal/database/webhook_logs_test.go +++ b/internal/database/webhook_logs_test.go @@ -18,6 +18,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/extsvc" "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestWebhookLogStore(t *testing.T) { @@ -197,61 +198,61 @@ func TestWebhookLogStore(t *testing.T) { want: []*types.WebhookLog{errLog}, }, "specific external service": { - opts: WebhookLogListOpts{ExternalServiceID: int64Ptr(es.ID)}, + opts: WebhookLogListOpts{ExternalServiceID: pointers.Ptr(es.ID)}, want: []*types.WebhookLog{okLog}, }, "no external service": { - opts: WebhookLogListOpts{ExternalServiceID: int64Ptr(0)}, + opts: WebhookLogListOpts{ExternalServiceID: pointers.Ptr(int64(0))}, want: []*types.WebhookLog{errLog}, }, "external service without results": { - opts: WebhookLogListOpts{ExternalServiceID: int64Ptr(es.ID + 1)}, + opts: WebhookLogListOpts{ExternalServiceID: pointers.Ptr(es.ID + 1)}, want: []*types.WebhookLog{}, }, "specific webhook id": { - opts: WebhookLogListOpts{WebhookID: int32Ptr(wh.ID)}, + opts: WebhookLogListOpts{WebhookID: pointers.Ptr(wh.ID)}, want: []*types.WebhookLog{okLog}, }, "no webhook id": { - opts: WebhookLogListOpts{WebhookID: int32Ptr(0)}, + opts: WebhookLogListOpts{WebhookID: pointers.Ptr(int32(0))}, want: []*types.WebhookLog{errLog}, }, "webhook id without results": { - opts: WebhookLogListOpts{WebhookID: int32Ptr(wh.ID + 1)}, + opts: WebhookLogListOpts{WebhookID: pointers.Ptr(wh.ID + 1)}, want: []*types.WebhookLog{}, }, "both within time range": { opts: WebhookLogListOpts{ - Since: timePtr(okTime.Add(-1 * time.Minute)), - Until: timePtr(errTime.Add(1 * time.Minute)), + Since: pointers.Ptr(okTime.Add(-1 * time.Minute)), + Until: pointers.Ptr(errTime.Add(1 * time.Minute)), }, want: []*types.WebhookLog{errLog, okLog}, }, "neither within time range": { opts: WebhookLogListOpts{ - Since: timePtr(okTime.Add(-3 * time.Minute)), - Until: timePtr(okTime.Add(-2 * time.Minute)), + Since: pointers.Ptr(okTime.Add(-3 * time.Minute)), + Until: pointers.Ptr(okTime.Add(-2 * time.Minute)), }, want: []*types.WebhookLog{}, }, "one before": { opts: WebhookLogListOpts{ - Until: timePtr(okTime.Add(30 * time.Second)), + Until: pointers.Ptr(okTime.Add(30 * time.Second)), }, want: []*types.WebhookLog{okLog}, }, "one after": { opts: WebhookLogListOpts{ - Since: timePtr(okTime.Add(30 * time.Second)), + Since: pointers.Ptr(okTime.Add(30 * time.Second)), }, want: []*types.WebhookLog{errLog}, }, "all options given": { opts: WebhookLogListOpts{ - ExternalServiceID: int64Ptr(0), + ExternalServiceID: pointers.Ptr(int64(0)), OnlyErrors: true, - Since: timePtr(okTime.Add(-1 * time.Minute)), - Until: timePtr(errTime.Add(1 * time.Minute)), + Since: pointers.Ptr(okTime.Add(-1 * time.Minute)), + Until: pointers.Ptr(errTime.Add(1 * time.Minute)), }, want: []*types.WebhookLog{errLog}, }, @@ -354,7 +355,3 @@ func createWebhookLog(externalServiceID int64, webhookID int32, statusCode int, }), } } - -func int64Ptr(v int64) *int64 { return &v } -func int32Ptr(v int32) *int32 { return &v } -func timePtr(v time.Time) *time.Time { return &v } diff --git a/internal/endpoint/BUILD.bazel b/internal/endpoint/BUILD.bazel index 219a0a0523a..9e3a962b82a 100644 --- a/internal/endpoint/BUILD.bazel +++ b/internal/endpoint/BUILD.bazel @@ -39,6 +39,7 @@ go_test( embed = [":endpoint"], deps = [ "//lib/errors", + "//lib/pointers", "@com_github_google_go_cmp//cmp", "@com_github_google_go_cmp//cmp/cmpopts", "@com_github_sourcegraph_log//logtest", diff --git a/internal/endpoint/k8s_test.go b/internal/endpoint/k8s_test.go index 1419d2b116b..26df28c8c8e 100644 --- a/internal/endpoint/k8s_test.go +++ b/internal/endpoint/k8s_test.go @@ -16,6 +16,8 @@ import ( _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/homedir" + + "github.com/sourcegraph/sourcegraph/lib/pointers" ) // Tests that even with publishNotReadyAddresses: true in the headless services, @@ -159,7 +161,7 @@ func TestK8sEndpoints(t *testing.T) { Name: "indexed-search", }, Spec: appsv1.StatefulSetSpec{ - Replicas: int32Ptr(2), + Replicas: pointers.Ptr(int32(2)), ServiceName: "indexed-search-svc", // normally same as sts name, but testing when different }, }, @@ -181,10 +183,6 @@ func TestK8sEndpoints(t *testing.T) { } } -func int32Ptr(v int32) *int32 { - return &v -} - func localClient() (*kubernetes.Clientset, error) { kubeconfig := filepath.Join(homedir.HomeDir(), ".kube", "config") config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) diff --git a/internal/extsvc/github/BUILD.bazel b/internal/extsvc/github/BUILD.bazel index b2c87e0f3a6..21a1beeca70 100644 --- a/internal/extsvc/github/BUILD.bazel +++ b/internal/extsvc/github/BUILD.bazel @@ -58,6 +58,7 @@ go_test( "//internal/rcache", "//internal/testutil", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_google_go_cmp//cmp", "@com_github_google_go_cmp//cmp/cmpopts", diff --git a/internal/extsvc/github/v3_test.go b/internal/extsvc/github/v3_test.go index 33da9685c0f..a9e911f0a7a 100644 --- a/internal/extsvc/github/v3_test.go +++ b/internal/extsvc/github/v3_test.go @@ -27,6 +27,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/rcache" "github.com/sourcegraph/sourcegraph/internal/testutil" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func newTestClient(t *testing.T, cli httpcli.Doer) *V3Client { @@ -745,7 +746,7 @@ func TestV3Client_Fork(t *testing.T) { // We'll use github.com/sourcegraph/automation-testing as our guinea pig. for name, org := range map[string]*string{ "user": nil, - "sourcegraph-testing": strPtr("sourcegraph-testing"), + "sourcegraph-testing": pointers.Ptr("sourcegraph-testing"), } { t.Run(name, func(t *testing.T) { testName := testName(t) @@ -815,8 +816,6 @@ func newV3TestEnterpriseClient(t testing.TB, name string) (*V3Client, func()) { return NewV3Client(logtest.Scoped(t), "Test", uri, gheToken, doer), save } -func strPtr(s string) *string { return &s } - func TestClient_ListRepositoriesForSearch(t *testing.T) { cli, save := newV3TestClient(t, "ListRepositoriesForSearch") defer save() diff --git a/internal/oobmigration/BUILD.bazel b/internal/oobmigration/BUILD.bazel index d74678cbdac..96a5bd401de 100644 --- a/internal/oobmigration/BUILD.bazel +++ b/internal/oobmigration/BUILD.bazel @@ -66,6 +66,7 @@ go_test( "//internal/database/dbtest", "//internal/observation", "//lib/errors", + "//lib/pointers", "@com_github_derision_test_glock//:glock", "@com_github_google_go_cmp//cmp", "@com_github_keegancsmith_sqlf//:sqlf", diff --git a/internal/oobmigration/store_test.go b/internal/oobmigration/store_test.go index f54909ab7fa..484ffa02475 100644 --- a/internal/oobmigration/store_test.go +++ b/internal/oobmigration/store_test.go @@ -15,6 +15,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestSynchronizeMetadata(t *testing.T) { @@ -291,7 +292,7 @@ func TestUpdateProgress(t *testing.T) { expectedMigration := testMigrations[2] // ID = 3 expectedMigration.Progress = 0.7 - expectedMigration.LastUpdated = timePtr(now) + expectedMigration.LastUpdated = pointers.Ptr(now) if diff := cmp.Diff(expectedMigration, migration); diff != "" { t.Errorf("unexpected migration (-want +got):\n%s", diff) @@ -330,7 +331,7 @@ func TestUpdateMetadata(t *testing.T) { // Formatting can change so we just use the value returned and confirm // unmarshalled value is the same lower down expectedMigration.Metadata = migration.Metadata - expectedMigration.LastUpdated = timePtr(now) + expectedMigration.LastUpdated = pointers.Ptr(now) if diff := cmp.Diff(expectedMigration, migration); diff != "" { t.Errorf("unexpected migration (-want +got):\n%s", diff) @@ -367,7 +368,7 @@ func TestAddError(t *testing.T) { } expectedMigration := testMigrations[1] // ID = 2 - expectedMigration.LastUpdated = timePtr(now) + expectedMigration.LastUpdated = pointers.Ptr(now) expectedMigration.Errors = []MigrationError{ {Message: "oops", Created: now}, {Message: "uh-oh 1", Created: testTime.Add(time.Hour*5 + time.Second*2)}, @@ -415,7 +416,7 @@ func TestAddErrorBounded(t *testing.T) { } expectedMigration := testMigrations[1] // ID = 2 - expectedMigration.LastUpdated = timePtr(now) + expectedMigration.LastUpdated = pointers.Ptr(now) expectedMigration.Errors = expectedErrors[:MaxMigrationErrors] if diff := cmp.Diff(expectedMigration, migration); diff != "" { @@ -454,7 +455,7 @@ var testMigrations = []Migration{ Deprecated: newVersionPtr(3, 28), Progress: 0.5, Created: testTime.Add(time.Hour * 1), - LastUpdated: timePtr(testTime.Add(time.Hour * 2)), + LastUpdated: pointers.Ptr(testTime.Add(time.Hour * 2)), NonDestructive: true, IsEnterprise: false, ApplyReverse: false, @@ -473,7 +474,7 @@ var testMigrations = []Migration{ Deprecated: nil, Progress: 0.4, Created: testTime.Add(time.Hour * 3), - LastUpdated: timePtr(testTime.Add(time.Hour * 4)), + LastUpdated: pointers.Ptr(testTime.Add(time.Hour * 4)), NonDestructive: false, IsEnterprise: false, ApplyReverse: true, @@ -511,7 +512,7 @@ var testEnterpriseMigrations = []Migration{ Deprecated: newVersionPtr(3, 28), Progress: 0.5, Created: testTime.Add(time.Hour * 1), - LastUpdated: timePtr(testTime.Add(time.Hour * 2)), + LastUpdated: pointers.Ptr(testTime.Add(time.Hour * 2)), NonDestructive: true, IsEnterprise: true, ApplyReverse: false, @@ -520,11 +521,8 @@ var testEnterpriseMigrations = []Migration{ }, } -func timePtr(t time.Time) *time.Time { return &t } - func newVersionPtr(major, minor int) *Version { - v := NewVersion(major, minor) - return &v + return pointers.Ptr(NewVersion(major, minor)) } func testEnterprise(t *testing.T) { diff --git a/internal/repos/BUILD.bazel b/internal/repos/BUILD.bazel index 3dc030b4890..8473af7fdce 100644 --- a/internal/repos/BUILD.bazel +++ b/internal/repos/BUILD.bazel @@ -192,6 +192,7 @@ go_test( "//internal/types", "//internal/types/typestest", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_davecgh_go_spew//spew", "@com_github_dnaeon_go_vcr//cassette", diff --git a/internal/repos/scheduler_test.go b/internal/repos/scheduler_test.go index 653fb19a05e..06eca895e0f 100644 --- a/internal/repos/scheduler_test.go +++ b/internal/repos/scheduler_test.go @@ -18,6 +18,7 @@ import ( gitserverprotocol "github.com/sourcegraph/sourcegraph/internal/gitserver/protocol" "github.com/sourcegraph/sourcegraph/internal/limiter" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -1382,15 +1383,15 @@ func TestUpdateScheduler_runUpdateLoop(t *testing.T) { { repo: a, resp: &gitserverprotocol.RepoUpdateResponse{ - LastFetched: timePtr(defaultTime.Add(2 * time.Minute)), - LastChanged: timePtr(defaultTime), + LastFetched: pointers.Ptr(defaultTime.Add(2 * time.Minute)), + LastChanged: pointers.Ptr(defaultTime), }, }, { repo: b, resp: &gitserverprotocol.RepoUpdateResponse{ - LastFetched: timePtr(defaultTime.Add(2 * time.Minute)), - LastChanged: timePtr(defaultTime), + LastFetched: pointers.Ptr(defaultTime.Add(2 * time.Minute)), + LastChanged: pointers.Ptr(defaultTime), }, }, }, @@ -1496,10 +1497,6 @@ func verifyRecording(t *testing.T, s *UpdateScheduler, timeAfterFuncDelays []tim } } -func timePtr(t time.Time) *time.Time { - return &t -} - func Test_updateQueue_Less(t *testing.T) { q := &updateQueue{} tests := []struct { diff --git a/internal/search/backend/BUILD.bazel b/internal/search/backend/BUILD.bazel index 5a0ac958f9f..77d0e1288c9 100644 --- a/internal/search/backend/BUILD.bazel +++ b/internal/search/backend/BUILD.bazel @@ -69,6 +69,7 @@ go_test( "//internal/conf", "//internal/types", "//lib/errors", + "//lib/pointers", "//schema", "@com_github_google_go_cmp//cmp", "@com_github_google_go_cmp//cmp/cmpopts", diff --git a/internal/search/backend/index_options_test.go b/internal/search/backend/index_options_test.go index 0cf6ed2677c..f4dba634cd4 100644 --- a/internal/search/backend/index_options_test.go +++ b/internal/search/backend/index_options_test.go @@ -10,6 +10,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/api" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -121,7 +122,7 @@ func TestGetIndexOptions(t *testing.T) { }, { name: "nosymbols", conf: schema.SiteConfiguration{ - SearchIndexSymbolsEnabled: boolPtr(false), + SearchIndexSymbolsEnabled: pointers.Ptr(false), }, repo: REPO, want: ZoektIndexOptions{ @@ -424,7 +425,3 @@ func TestGetIndexOptions_batch(t *testing.T) { t.Fatal("mismatch (-want, +got):\n", diff) } } - -func boolPtr(b bool) *bool { - return &b -} diff --git a/internal/search/query/BUILD.bazel b/internal/search/query/BUILD.bazel index a36d001abbd..29f6cdc474b 100644 --- a/internal/search/query/BUILD.bazel +++ b/internal/search/query/BUILD.bazel @@ -56,6 +56,7 @@ go_test( embed = [":query"], deps = [ "//lib/errors", + "//lib/pointers", "@com_github_google_go_cmp//cmp", "@com_github_grafana_regexp//syntax", "@com_github_hexops_autogold_v2//:autogold", diff --git a/internal/search/query/predicate_test.go b/internal/search/query/predicate_test.go index 61367b6013e..8024966adf6 100644 --- a/internal/search/query/predicate_test.go +++ b/internal/search/query/predicate_test.go @@ -5,6 +5,8 @@ import ( "testing" "github.com/stretchr/testify/require" + + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestRepoContainsFilePredicate(t *testing.T) { @@ -146,8 +148,6 @@ func TestRepoHasTopicPredicate(t *testing.T) { } func TestRepoHasKVPMetaPredicate(t *testing.T) { - strPtr := func(s string) *string { return &s } - t.Run("Unmarshal", func(t *testing.T) { type test struct { name string @@ -156,11 +156,11 @@ func TestRepoHasKVPMetaPredicate(t *testing.T) { } valid := []test{ - {`key:value`, `key:value`, &RepoHasMetaPredicate{Key: "key", Value: strPtr("value"), Negated: false, KeyOnly: false}}, - {`double quoted special characters`, `"key:colon":"value:colon"`, &RepoHasMetaPredicate{Key: "key:colon", Value: strPtr("value:colon"), Negated: false, KeyOnly: false}}, - {`single quoted special characters`, `' key:':'value : '`, &RepoHasMetaPredicate{Key: ` key:`, Value: strPtr(`value : `), Negated: false, KeyOnly: false}}, - {`escaped quotes`, `"key\"quote":"value\"quote"`, &RepoHasMetaPredicate{Key: `key"quote`, Value: strPtr(`value"quote`), Negated: false, KeyOnly: false}}, - {`space padding`, ` key:value `, &RepoHasMetaPredicate{Key: `key`, Value: strPtr(`value`), Negated: false, KeyOnly: false}}, + {`key:value`, `key:value`, &RepoHasMetaPredicate{Key: "key", Value: pointers.Ptr("value"), Negated: false, KeyOnly: false}}, + {`double quoted special characters`, `"key:colon":"value:colon"`, &RepoHasMetaPredicate{Key: "key:colon", Value: pointers.Ptr("value:colon"), Negated: false, KeyOnly: false}}, + {`single quoted special characters`, `' key:':'value : '`, &RepoHasMetaPredicate{Key: ` key:`, Value: pointers.Ptr(`value : `), Negated: false, KeyOnly: false}}, + {`escaped quotes`, `"key\"quote":"value\"quote"`, &RepoHasMetaPredicate{Key: `key"quote`, Value: pointers.Ptr(`value"quote`), Negated: false, KeyOnly: false}}, + {`space padding`, ` key:value `, &RepoHasMetaPredicate{Key: `key`, Value: pointers.Ptr(`value`), Negated: false, KeyOnly: false}}, {`only key`, `key`, &RepoHasMetaPredicate{Key: `key`, Value: nil, Negated: false, KeyOnly: true}}, {`key tag`, `key:`, &RepoHasMetaPredicate{Key: "key", Value: nil, Negated: false, KeyOnly: false}}, } diff --git a/internal/search/streaming/api/BUILD.bazel b/internal/search/streaming/api/BUILD.bazel index 574c5111802..cf0cd54f99b 100644 --- a/internal/search/streaming/api/BUILD.bazel +++ b/internal/search/streaming/api/BUILD.bazel @@ -21,5 +21,6 @@ go_test( deps = [ "//internal/api", "//internal/testutil", + "//lib/pointers", ], ) diff --git a/internal/search/streaming/api/progress_test.go b/internal/search/streaming/api/progress_test.go index e06156bd21f..885fdc67f34 100644 --- a/internal/search/streaming/api/progress_test.go +++ b/internal/search/streaming/api/progress_test.go @@ -8,6 +8,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/api" "github.com/sourcegraph/sourcegraph/internal/testutil" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) var updateGolden = flag.Bool("update", false, "Updastdata goldens") @@ -27,12 +28,12 @@ func TestSearchProgress(t *testing.T) { cases := map[string]ProgressStats{ "empty": {}, "zeroresults": { - RepositoriesCount: intPtr(0), + RepositoriesCount: pointers.Ptr(0), }, "timedout100": { MatchCount: 0, ElapsedMilliseconds: 0, - RepositoriesCount: intPtr(100), + RepositoriesCount: pointers.Ptr(100), ExcludedArchived: 0, ExcludedForks: 0, Timedout: timedout100, @@ -44,7 +45,7 @@ func TestSearchProgress(t *testing.T) { "all": { MatchCount: 1, ElapsedMilliseconds: 0, - RepositoriesCount: intPtr(5), + RepositoriesCount: pointers.Ptr(5), BackendsMissing: 1, ExcludedArchived: 1, ExcludedForks: 5, @@ -92,7 +93,3 @@ func TestNumber(t *testing.T) { } } } - -func intPtr(i int) *int { - return &i -} diff --git a/internal/settings/BUILD.bazel b/internal/settings/BUILD.bazel index ff2d48e6a4d..6c474295d21 100644 --- a/internal/settings/BUILD.bazel +++ b/internal/settings/BUILD.bazel @@ -31,6 +31,7 @@ go_test( "//internal/database", "//internal/database/dbtest", "//internal/types", + "//lib/pointers", "//schema", "@com_github_sourcegraph_log//logtest", "@com_github_stretchr_testify//require", diff --git a/internal/settings/settings_test.go b/internal/settings/settings_test.go index 2bbee18ee60..76f1cfc2b4d 100644 --- a/internal/settings/settings_test.go +++ b/internal/settings/settings_test.go @@ -7,10 +7,12 @@ import ( "github.com/stretchr/testify/require" "github.com/sourcegraph/log/logtest" + "github.com/sourcegraph/sourcegraph/internal/api" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/schema" ) @@ -104,10 +106,6 @@ func TestRelevantSettings(t *testing.T) { } func TestMergeSettings(t *testing.T) { - boolPtr := func(b bool) *bool { - return &b - } - cases := []struct { name string left *schema.Settings @@ -130,14 +128,14 @@ func TestMergeSettings(t *testing.T) { }, { name: "merge bool ptr", left: &schema.Settings{ - AlertsHideObservabilitySiteAlerts: boolPtr(true), + AlertsHideObservabilitySiteAlerts: pointers.Ptr(true), }, right: &schema.Settings{ SearchDefaultMode: "test", }, expected: &schema.Settings{ SearchDefaultMode: "test", - AlertsHideObservabilitySiteAlerts: boolPtr(true), + AlertsHideObservabilitySiteAlerts: pointers.Ptr(true), }, }, { name: "merge bool", @@ -171,30 +169,30 @@ func TestMergeSettings(t *testing.T) { name: "deep merge struct pointer", left: &schema.Settings{ ExperimentalFeatures: &schema.SettingsExperimentalFeatures{ - CodeMonitoringWebHooks: boolPtr(true), + CodeMonitoringWebHooks: pointers.Ptr(true), }, }, right: &schema.Settings{ ExperimentalFeatures: &schema.SettingsExperimentalFeatures{ - ShowMultilineSearchConsole: boolPtr(false), + ShowMultilineSearchConsole: pointers.Ptr(false), }, }, expected: &schema.Settings{ ExperimentalFeatures: &schema.SettingsExperimentalFeatures{ - CodeMonitoringWebHooks: boolPtr(true), - ShowMultilineSearchConsole: boolPtr(false), + CodeMonitoringWebHooks: pointers.Ptr(true), + ShowMultilineSearchConsole: pointers.Ptr(false), }, }, }, { name: "overwriting merge", left: &schema.Settings{ - AlertsHideObservabilitySiteAlerts: boolPtr(true), + AlertsHideObservabilitySiteAlerts: pointers.Ptr(true), }, right: &schema.Settings{ - AlertsHideObservabilitySiteAlerts: boolPtr(false), + AlertsHideObservabilitySiteAlerts: pointers.Ptr(false), }, expected: &schema.Settings{ - AlertsHideObservabilitySiteAlerts: boolPtr(false), + AlertsHideObservabilitySiteAlerts: pointers.Ptr(false), }, }, { name: "deep merge slice", diff --git a/internal/usagestats/BUILD.bazel b/internal/usagestats/BUILD.bazel index 5b789b80cbe..fcb3098f1ec 100644 --- a/internal/usagestats/BUILD.bazel +++ b/internal/usagestats/BUILD.bazel @@ -49,6 +49,7 @@ go_library( "//internal/types", "//internal/version", "//lib/errors", + "//lib/pointers", "@com_github_gomodule_redigo//redis", "@com_github_google_uuid//:uuid", "@com_github_inconshreveable_log15//:log15", @@ -93,6 +94,7 @@ go_test( "//internal/extsvc", "//internal/types", "//lib/errors", + "//lib/pointers", "@com_github_derision_test_glock//:glock", "@com_github_google_go_cmp//cmp", "@com_github_inconshreveable_log15//:log15", diff --git a/internal/usagestats/aggregated_search_test.go b/internal/usagestats/aggregated_search_test.go index 667e533049f..5409ca18275 100644 --- a/internal/usagestats/aggregated_search_test.go +++ b/internal/usagestats/aggregated_search_test.go @@ -7,6 +7,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestGroupAggregateSearchStats(t *testing.T) { @@ -65,13 +66,9 @@ func TestGroupAggregateSearchStats(t *testing.T) { } func newSearchTestEvent(eventCount, userCount int32, p50, p90, p99 float64) *types.SearchEventStatistics { - intptr := func(i int32) *int32 { - return &i - } - return &types.SearchEventStatistics{ - EventsCount: intptr(eventCount), - UserCount: intptr(userCount), + EventsCount: pointers.Ptr(eventCount), + UserCount: pointers.Ptr(userCount), EventLatencies: &types.SearchEventLatencies{P50: p50, P90: p90, P99: p99}, } } diff --git a/internal/usagestats/own_test.go b/internal/usagestats/own_test.go index 7172e6f58dd..05437d68ed3 100644 --- a/internal/usagestats/own_test.go +++ b/internal/usagestats/own_test.go @@ -14,6 +14,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestGetOwnershipUsageStatsReposCount(t *testing.T) { @@ -44,10 +45,9 @@ func TestGetOwnershipUsageStatsReposCount(t *testing.T) { if err != nil { t.Fatalf("GetOwnershipUsageStats err: %s", err) } - iptr := func(i int32) *int32 { return &i } want := &types.OwnershipUsageReposCounts{ - Total: iptr(2), - WithIngestedOwnership: iptr(1), + Total: pointers.Ptr(int32(2)), + WithIngestedOwnership: pointers.Ptr(int32(1)), } if diff := cmp.Diff(want, stats.ReposCount); diff != "" { t.Errorf("GetOwnershipUsageStates.ReposCount, +want,-got:\n%s", diff) @@ -69,10 +69,9 @@ func TestGetOwnershipUsageStatsReposCountNoCodeowners(t *testing.T) { if err != nil { t.Fatalf("GetOwnershipUsageStats err: %s", err) } - iptr := func(i int32) *int32 { return &i } want := &types.OwnershipUsageReposCounts{ - Total: iptr(1), - WithIngestedOwnership: iptr(0), + Total: pointers.Ptr(int32(1)), + WithIngestedOwnership: pointers.Ptr(int32(0)), } if diff := cmp.Diff(want, stats.ReposCount); diff != "" { t.Errorf("GetOwnershipUsageStates.ReposCount, +want,-got:\n%s", diff) @@ -94,10 +93,9 @@ func TestGetOwnershipUsageStatsReposCountNoRepos(t *testing.T) { if err != nil { t.Fatalf("GetOwnershipUsageStats err: %s", err) } - iptr := func(i int32) *int32 { return &i } want := &types.OwnershipUsageReposCounts{ - Total: iptr(0), - WithIngestedOwnership: iptr(0), + Total: pointers.Ptr(int32(0)), + WithIngestedOwnership: pointers.Ptr(int32(0)), } if diff := cmp.Diff(want, stats.ReposCount); diff != "" { t.Errorf("GetOwnershipUsageStates.ReposCount, -want+got:\n%s", diff) @@ -130,11 +128,10 @@ func TestGetOwnershipUsageStatsReposCountStatsNotCompacted(t *testing.T) { if err != nil { t.Fatalf("GetOwnershipUsageStats err: %s", err) } - iptr := func(i int32) *int32 { return &i } want := &types.OwnershipUsageReposCounts{ // Can have zero repos and one ingested ownership then. - Total: iptr(2), - WithIngestedOwnership: iptr(1), + Total: pointers.Ptr(int32(2)), + WithIngestedOwnership: pointers.Ptr(int32(1)), } if diff := cmp.Diff(want, stats.ReposCount); diff != "" { t.Errorf("GetOwnershipUsageStates.ReposCount, -want,+got:\n%s", diff) @@ -237,11 +234,10 @@ func TestGetOwnershipUsageStatsAggregatedStats(t *testing.T) { if err != nil { t.Fatalf("GetOwnershipUsageStats err: %s", err) } - ptr := func(i int32) *int32 { return &i } want := &types.OwnershipUsageStatisticsActiveUsers{ - MAU: ptr(2), - WAU: ptr(1), - DAU: ptr(0), + MAU: pointers.Ptr(int32(2)), + WAU: pointers.Ptr(int32(1)), + DAU: pointers.Ptr(int32(0)), } if diff := cmp.Diff(want, lens(stats)); diff != "" { t.Errorf("GetOwnershipUsageStats().%s -want+got: %s", eventName, diff) diff --git a/internal/usagestats/util.go b/internal/usagestats/util.go index 7abc49d4a65..87c2637aa79 100644 --- a/internal/usagestats/util.go +++ b/internal/usagestats/util.go @@ -1,6 +1,7 @@ package usagestats +import "github.com/sourcegraph/sourcegraph/lib/pointers" + func int32Ptr(v int) *int32 { - v32 := int32(v) - return &v32 + return pointers.Ptr(int32(v)) } diff --git a/lib/batches/env/BUILD.bazel b/lib/batches/env/BUILD.bazel index f0c0f8cf38d..5b6b626917e 100644 --- a/lib/batches/env/BUILD.bazel +++ b/lib/batches/env/BUILD.bazel @@ -24,6 +24,7 @@ go_test( ], embed = [":env"], deps = [ + "//lib/pointers", "@com_github_google_go_cmp//cmp", "@in_gopkg_yaml_v2//:yaml_v2", ], diff --git a/lib/batches/env/env_test.go b/lib/batches/env/env_test.go index 9d3a898816d..23abc2e6e77 100644 --- a/lib/batches/env/env_test.go +++ b/lib/batches/env/env_test.go @@ -6,6 +6,8 @@ import ( "github.com/google/go-cmp/cmp" "gopkg.in/yaml.v2" + + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestEnvironment_MarshalJSON(t *testing.T) { @@ -19,14 +21,14 @@ func TestEnvironment_MarshalJSON(t *testing.T) { }, "only static variables": { in: Environment{vars: []variable{ - {name: "foo", value: stringPtr("bar")}, - {name: "quux", value: stringPtr("baz")}, + {name: "foo", value: pointers.Ptr("bar")}, + {name: "quux", value: pointers.Ptr("baz")}, }}, want: `{"foo":"bar","quux":"baz"}`, }, "with variables": { in: Environment{vars: []variable{ - {name: "foo", value: stringPtr("bar")}, + {name: "foo", value: pointers.Ptr("bar")}, {name: "quux", value: nil}, }}, want: `[{"foo":"bar"},"quux"]`, @@ -58,7 +60,7 @@ func TestEnvironment_UnmarshalJSON(t *testing.T) { "set array": { in: `[{"foo":"bar"},"quux"]`, want: Environment{vars: []variable{ - {name: "foo", value: stringPtr("bar")}, + {name: "foo", value: pointers.Ptr("bar")}, {name: "quux"}, }}, }, @@ -69,8 +71,8 @@ func TestEnvironment_UnmarshalJSON(t *testing.T) { "set object": { in: `{"foo":"bar","quux":"baz"}`, want: Environment{vars: []variable{ - {name: "foo", value: stringPtr("bar")}, - {name: "quux", value: stringPtr("baz")}, + {name: "foo", value: pointers.Ptr("bar")}, + {name: "quux", value: pointers.Ptr("baz")}, }}, }, } { @@ -117,7 +119,7 @@ func TestEnvironment_UnmarshalYAML(t *testing.T) { "set array": { in: "- foo: bar\n- quux", want: Environment{vars: []variable{ - {name: "foo", value: stringPtr("bar")}, + {name: "foo", value: pointers.Ptr("bar")}, {name: "quux"}, }}, }, @@ -128,8 +130,8 @@ func TestEnvironment_UnmarshalYAML(t *testing.T) { "set object": { in: "foo: bar\nquux: baz", want: Environment{vars: []variable{ - {name: "foo", value: stringPtr("bar")}, - {name: "quux", value: stringPtr("baz")}, + {name: "foo", value: pointers.Ptr("bar")}, + {name: "quux", value: pointers.Ptr("baz")}, }}, }, } { @@ -174,14 +176,14 @@ func TestEnvironment_IsStatic(t *testing.T) { }, "static": { env: Environment{vars: []variable{ - {name: "foo", value: stringPtr("bar")}, - {name: "quux", value: stringPtr("baz")}, + {name: "foo", value: pointers.Ptr("bar")}, + {name: "quux", value: pointers.Ptr("baz")}, }}, want: true, }, "not static": { env: Environment{vars: []variable{ - {name: "foo", value: stringPtr("bar")}, + {name: "foo", value: pointers.Ptr("bar")}, {name: "quux", value: nil}, }}, want: false, @@ -198,7 +200,7 @@ func TestEnvironment_IsStatic(t *testing.T) { func TestEnvironment_Resolve(t *testing.T) { env := Environment{vars: []variable{ {name: "nil"}, - {name: "foo", value: stringPtr("bar")}, + {name: "foo", value: pointers.Ptr("bar")}, }} t.Run("invalid outer", func(t *testing.T) { @@ -267,14 +269,14 @@ func TestEnvironment_OuterVars(t *testing.T) { }, "static variables": { in: Environment{vars: []variable{ - {name: "foo", value: stringPtr("bar")}, - {name: "quux", value: stringPtr("baz")}, + {name: "foo", value: pointers.Ptr("bar")}, + {name: "quux", value: pointers.Ptr("baz")}, }}, want: []string{}, }, "dynamic variables and static mixed": { in: Environment{vars: []variable{ - {name: "foo", value: stringPtr("bar")}, + {name: "foo", value: pointers.Ptr("bar")}, {name: "quux", value: nil}, }}, want: []string{"quux"}, diff --git a/lib/batches/env/var_test.go b/lib/batches/env/var_test.go index 214cda003bc..39aa05ee4ed 100644 --- a/lib/batches/env/var_test.go +++ b/lib/batches/env/var_test.go @@ -6,6 +6,8 @@ import ( "github.com/google/go-cmp/cmp" "gopkg.in/yaml.v2" + + "github.com/sourcegraph/sourcegraph/lib/pointers" ) func TestVariable_MarshalJSON(t *testing.T) { @@ -18,7 +20,7 @@ func TestVariable_MarshalJSON(t *testing.T) { want: `"foo"`, }, "with value": { - in: variable{name: "foo", value: stringPtr("bar")}, + in: variable{name: "foo", value: pointers.Ptr("bar")}, want: `{"foo":"bar"}`, }, } { @@ -47,7 +49,7 @@ func TestVariable_UnmarshalJSON(t *testing.T) { }, "with value": { in: `{"foo":"bar"}`, - want: variable{name: "foo", value: stringPtr("bar")}, + want: variable{name: "foo", value: pointers.Ptr("bar")}, }, } { t.Run(name, func(t *testing.T) { @@ -123,7 +125,7 @@ func TestVariable_UnmarshalYAML(t *testing.T) { }, "with value": { in: `foo: bar`, - want: variable{name: "foo", value: stringPtr("bar")}, + want: variable{name: "foo", value: pointers.Ptr("bar")}, }, } { t.Run(name, func(t *testing.T) { @@ -186,5 +188,3 @@ func TestVariable_UnmarshalYAML(t *testing.T) { }) }) } - -func stringPtr(s string) *string { return &s } diff --git a/lib/pointers/BUILD.bazel b/lib/pointers/BUILD.bazel new file mode 100644 index 00000000000..d7a7783f209 --- /dev/null +++ b/lib/pointers/BUILD.bazel @@ -0,0 +1,19 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") +load("//dev:go_defs.bzl", "go_test") + +go_library( + name = "pointers", + srcs = ["ptr.go"], + importpath = "github.com/sourcegraph/sourcegraph/lib/pointers", + visibility = ["//visibility:public"], +) + +go_test( + name = "pointers_test", + srcs = ["ptr_test.go"], + embed = [":pointers"], + deps = [ + "@com_github_stretchr_testify//require", + "@tools_gotest//assert", + ], +) diff --git a/lib/pointers/ptr.go b/lib/pointers/ptr.go new file mode 100644 index 00000000000..cf6bd092a0f --- /dev/null +++ b/lib/pointers/ptr.go @@ -0,0 +1,26 @@ +package pointers + +// Ptr returns a pointer to any value. +// Useful in tests or when pointer without a variable is needed. +func Ptr[T any](val T) *T { + return &val +} + +// NonZeroPtr returns nil for zero value, otherwise pointer to value +func NonZeroPtr[T comparable](val T) *T { + var zero T + if val == zero { + return nil + } + return Ptr(val) +} + +// Deref safely dereferences a pointer. If pointer is nil, returns zero value, +// otherwise returns dereferenced value. +func Deref[T any](v *T, defaultValue T) T { + if v != nil { + return *v + } + + return defaultValue +} diff --git a/lib/pointers/ptr_test.go b/lib/pointers/ptr_test.go new file mode 100644 index 00000000000..ce9b54a3c43 --- /dev/null +++ b/lib/pointers/ptr_test.go @@ -0,0 +1,205 @@ +package pointers + +import ( + "testing" + + "github.com/stretchr/testify/require" + "gotest.tools/assert" +) + +func TestPtr(t *testing.T) { + tests := []struct { + name string + val interface{} + }{ + { + name: "int", + val: 1, + }, + { + name: "string", + val: "hello", + }, + { + name: "bool", + val: true, + }, + { + name: "struct", + val: struct{ Foo int }{42}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := Ptr(tt.val) + assert.Equal(t, tt.val, *got) + }) + } +} + +type nonZeroTestCase[T comparable] struct { + name string + val T + wantNil bool +} + +func runNonZeroPtrTest[T comparable](t *testing.T, tc nonZeroTestCase[T]) { + t.Helper() + + t.Run(tc.name, func(t *testing.T) { + got := NonZeroPtr(tc.val) + if tc.wantNil { + require.Nil(t, got) + } else { + assert.Equal(t, tc.val, *got) + } + }) +} + +func TestNonZeroPtr(t *testing.T) { + intTests := []nonZeroTestCase[int]{ + { + name: "int", + val: 1, + }, + { + name: "zero int", + val: 0, + wantNil: true, + }, + } + stringTests := []nonZeroTestCase[string]{ + { + name: "string", + val: "hello", + }, + { + name: "zero string", + val: "", + wantNil: true, + }, + } + boolTests := []nonZeroTestCase[bool]{ + { + name: "bool", + val: true, + }, + { + name: "zero bool", + val: false, + wantNil: true, + }, + } + structTests := []nonZeroTestCase[struct{ Foo int }]{ + { + name: "struct", + val: struct{ Foo int }{42}, + }, + { + name: "zero struct", + val: struct{ Foo int }{}, + wantNil: true, + }, + } + + for _, tc := range intTests { + runNonZeroPtrTest(t, tc) + } + for _, tc := range stringTests { + runNonZeroPtrTest(t, tc) + } + for _, tc := range boolTests { + runNonZeroPtrTest(t, tc) + } + for _, tc := range structTests { + runNonZeroPtrTest(t, tc) + } +} + +type derefTestCase[T comparable] struct { + name string + val *T + defaultVal T + want T +} + +func runDerefTest[T comparable](t *testing.T, tc derefTestCase[T]) { + t.Helper() + + t.Run(tc.name, func(t *testing.T) { + got := Deref(tc.val, tc.defaultVal) + assert.Equal(t, tc.want, got) + }) +} + +func TestDeref(t *testing.T) { + intTests := []derefTestCase[int]{ + { + name: "int", + val: Ptr(1), + defaultVal: 0, + want: 1, + }, + { + name: "zero int", + val: nil, + defaultVal: 0, + want: 0, + }, + } + stringTests := []derefTestCase[string]{ + { + name: "string", + val: Ptr("hello"), + defaultVal: "", + want: "hello", + }, + { + name: "zero string", + val: nil, + defaultVal: "", + want: "", + }, + } + boolTests := []derefTestCase[bool]{ + { + name: "bool", + val: Ptr(true), + defaultVal: false, + want: true, + }, + { + name: "zero bool", + val: nil, + defaultVal: false, + want: false, + }, + } + structTests := []derefTestCase[struct{ Foo int }]{ + { + name: "struct", + val: Ptr(struct{ Foo int }{42}), + defaultVal: struct{ Foo int }{}, + want: struct{ Foo int }{42}, + }, + { + name: "zero struct", + val: nil, + defaultVal: struct{ Foo int }{}, + want: struct{ Foo int }{}, + }, + } + + for _, tc := range intTests { + runDerefTest(t, tc) + } + for _, tc := range stringTests { + runDerefTest(t, tc) + } + for _, tc := range boolTests { + runDerefTest(t, tc) + } + for _, tc := range structTests { + runDerefTest(t, tc) + } +} diff --git a/monitoring/monitoring/BUILD.bazel b/monitoring/monitoring/BUILD.bazel index 9a6cab43ba5..d63ce71d0f2 100644 --- a/monitoring/monitoring/BUILD.bazel +++ b/monitoring/monitoring/BUILD.bazel @@ -22,6 +22,7 @@ go_library( visibility = ["//visibility:public"], deps = [ "//lib/errors", + "//lib/pointers", "//monitoring/grafanaclient", "//monitoring/monitoring/internal/grafana", "//monitoring/monitoring/internal/promql", diff --git a/monitoring/monitoring/monitoring.go b/monitoring/monitoring/monitoring.go index fa769dfbc9a..f3125716219 100644 --- a/monitoring/monitoring/monitoring.go +++ b/monitoring/monitoring/monitoring.go @@ -12,6 +12,7 @@ import ( "github.com/prometheus/prometheus/model/labels" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/monitoring/monitoring/internal/grafana" "github.com/sourcegraph/sourcegraph/monitoring/monitoring/internal/promql" ) @@ -141,7 +142,7 @@ func (c *Dashboard) renderDashboard(injectLabelMatchers []*labels.Matcher, folde board.Annotations.List = []sdk.Annotation{{ Name: "Alert events", - Datasource: StringPtr("Prometheus"), + Datasource: pointers.Ptr("Prometheus"), Expr: expr, Step: "60s", TitleFormat: "{{ description }} ({{ name }})", @@ -168,7 +169,7 @@ func (c *Dashboard) renderDashboard(injectLabelMatchers []*labels.Matcher, folde board.Annotations.List = append(board.Annotations.List, sdk.Annotation{ Name: "Version changes", - Datasource: StringPtr("Prometheus"), + Datasource: pointers.Ptr("Prometheus"), Expr: expr, Step: "60s", TitleFormat: "v{{ version }}", @@ -256,7 +257,7 @@ func (c *Dashboard) renderDashboard(injectLabelMatchers []*labels.Matcher, folde alertsFiring.GraphPanel.FieldConfig = &sdk.FieldConfig{} alertsFiring.GraphPanel.FieldConfig.Defaults.Links = []sdk.Link{{ Title: "Graph panel", - URL: StringPtr("/-/debug/grafana/d/${__field.labels.service_name}/${__field.labels.service_name}?viewPanel=${__field.labels.grafana_panel_id}"), + URL: pointers.Ptr("/-/debug/grafana/d/${__field.labels.service_name}/${__field.labels.service_name}?viewPanel=${__field.labels.grafana_panel_id}"), }} board.Panels = append(board.Panels, alertsFiring) } @@ -830,14 +831,14 @@ func (o Observable) renderPanel(c *Dashboard, manipulations panelManipulationOpt // Add reference links panel.Links = []sdk.Link{{ Title: "Panel reference", - URL: StringPtr(fmt.Sprintf("%s#%s", canonicalDashboardsDocsURL, observableDocAnchor(c, o))), - TargetBlank: boolPtr(true), + URL: pointers.Ptr(fmt.Sprintf("%s#%s", canonicalDashboardsDocsURL, observableDocAnchor(c, o))), + TargetBlank: pointers.Ptr(true), }} if !o.NoAlert { panel.Links = append(panel.Links, sdk.Link{ Title: "Alerts reference", - URL: StringPtr(fmt.Sprintf("%s#%s", canonicalAlertDocsURL, observableDocAnchor(c, o))), - TargetBlank: boolPtr(true), + URL: pointers.Ptr(fmt.Sprintf("%s#%s", canonicalAlertDocsURL, observableDocAnchor(c, o))), + TargetBlank: pointers.Ptr(true), }) } diff --git a/monitoring/monitoring/util.go b/monitoring/monitoring/util.go index 3ef0c18bb6b..4af86b9df74 100644 --- a/monitoring/monitoring/util.go +++ b/monitoring/monitoring/util.go @@ -4,9 +4,10 @@ import ( "fmt" "strings" - "github.com/sourcegraph/sourcegraph/lib/errors" "golang.org/x/text/cases" "golang.org/x/text/language" + + "github.com/sourcegraph/sourcegraph/lib/errors" ) // upperFirst returns s with an uppercase first rune. @@ -29,15 +30,6 @@ func pluralize(noun string, count int) string { return fmt.Sprintf("%d %s", count, noun) } -// StringPtr converts a string value to a pointer, useful for setting fields in some APIs. -func StringPtr(s string) *string { return &s } - -// boolPtr converts a boolean value to a pointer, useful for setting fields in some APIs. -func boolPtr(b bool) *bool { return &b } - -// IntPtr converts an int64 value to a pointer, useful for setting fields in some APIs. -func Int64Ptr(i int64) *int64 { return &i } - // toMarkdown converts a Go string to Markdown, and optionally converts it to a list item if requested by forceList. func toMarkdown(m string, forceList bool) (string, error) { m = strings.TrimPrefix(m, "\n") diff --git a/monitoring/monitoring/variables.go b/monitoring/monitoring/variables.go index 8ae408de287..850d3c8359a 100644 --- a/monitoring/monitoring/variables.go +++ b/monitoring/monitoring/variables.go @@ -10,6 +10,7 @@ import ( "github.com/prometheus/prometheus/model/labels" "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/lib/pointers" "github.com/sourcegraph/sourcegraph/monitoring/monitoring/internal/promql" ) @@ -102,7 +103,7 @@ func (c *ContainerVariable) toGrafanaTemplateVar(injectLabelMatchers []*labels.M Label: c.Label, Multi: c.Multi, - Datasource: StringPtr("Prometheus"), + Datasource: pointers.Ptr("Prometheus"), IncludeAll: true, // Apply the AllValue to a template variable by default @@ -130,7 +131,7 @@ func (c *ContainerVariable) toGrafanaTemplateVar(injectLabelMatchers []*labels.M variable.Query = fmt.Sprintf("label_values(%s, %s)", expr, c.OptionsLabelValues.LabelName) variable.Refresh = sdk.BoolInt{ Flag: true, - Value: Int64Ptr(2), // Refresh on time range change + Value: pointers.Ptr(int64(2)), // Refresh on time range change } variable.Sort = 3 variable.Options = []sdk.Option{} // Cannot be null in later versions of Grafana