From 9ff8ace27fe2c3776d049ed26c08a1cf9084e256 Mon Sep 17 00:00:00 2001 From: Cesar Jimenez Date: Wed, 28 Sep 2022 15:55:34 -0400 Subject: [PATCH] [code-nav]: Moving graphql transport layer to individual service layers (#41596) --- .../src/codeintel/ReferencesPanel.mocks.ts | 6 +- .../src/codeintel/ReferencesPanelQueries.ts | 2 +- cmd/frontend/graphqlbackend/codeintel.go | 470 +-- cmd/frontend/graphqlbackend/codeintel.graphql | 8 +- cmd/frontend/graphqlbackend/git_tree_entry.go | 16 +- cmd/frontend/graphqlbackend/graphqlbackend.go | 2 +- cmd/frontend/graphqlbackend/node.go | 14 +- cmd/frontend/graphqlbackend/repository.go | 35 +- cmd/frontend/graphqlbackend/schema.graphql | 111 +- cmd/frontend/internal/app/editor.go | 2 +- .../cmd/frontend/internal/codeintel/init.go | 14 +- .../codeintel/resolvers/graphql/audit_logs.go | 60 - .../graphql/codeintel_tree_info_resolver.go | 145 - .../graphql/configuration_connection.go | 45 - .../resolvers/graphql/cursors_test.go | 85 - .../codeintel/resolvers/graphql/diagnostic.go | 54 - .../graphql/diagnostic_connection.go | 38 - .../resolvers/graphql/documents_connection.go | 17 - .../resolvers/graphql/frankenresolver.go | 110 - .../codeintel/resolvers/graphql/hover.go | 22 - .../codeintel/resolvers/graphql/ids.go | 53 - .../codeintel/resolvers/graphql/ids_test.go | 42 - .../codeintel/resolvers/graphql/iface.go | 20 - .../codeintel/resolvers/graphql/index.go | 112 - .../resolvers/graphql/index_connection.go | 67 - .../resolvers/graphql/index_steps.go | 86 - .../resolvers/graphql/index_steps_index.go | 27 - .../resolvers/graphql/index_steps_preindex.go | 28 - .../resolvers/graphql/location_connection.go | 30 - .../resolvers/graphql/observability.go | 77 - .../codeintel/resolvers/graphql/ranges.go | 32 - .../resolvers/graphql/ranges_connection.go | 24 - .../graphql/repository_filter_preview.go | 41 - .../codeintel/resolvers/graphql/resolver.go | 828 +---- .../resolvers/graphql/resolver_test.go | 201 - .../retention_policy_matcher_connection.go | 47 - .../graphql/retention_policy_matches.go | 32 - .../codeintel/resolvers/graphql/summary.go | 145 - .../codeintel/resolvers/graphql/support.go | 113 - .../codeintel/resolvers/graphql/upload.go | 176 - .../resolvers/graphql/upload_connection.go | 69 - .../codeintel/resolvers/graphql/util.go | 407 -- .../codeintel/resolvers/graphql/util_test.go | 54 - .../internal/codeintel/resolvers/iface.go | 59 - .../codeintel/resolvers/mocks/mocks_temp.go | 618 ---- .../resolvers/mocks/transport/mocks_temp.go | 1093 ------ .../resolvers/mocks/transport/mocks_temps.go | 1462 -------- .../mocks/transport/uploads/mocks_uploads.go | 1203 ------ .../codeintel/resolvers/mocks_test.go | 291 -- .../internal/codeintel/resolvers/resolver.go | 54 +- .../frontend/internal/codeintel/services.go | 7 +- .../internal/codeintel/indexing/iface.go | 4 +- .../internal/codeintel/indexing/mocks_test.go | 56 +- .../cloneurls/clone_urls.go | 0 .../cloneurls/clone_urls_test.go | 0 .../background/scheduler/iface.go | 6 +- .../background/scheduler/mocks_test.go | 24 +- .../background/scheduler/scheduler.go | 4 +- internal/codeintel/autoindexing/init.go | 4 +- .../internal/store/observability.go | 8 + .../autoindexing/internal/store/scan.go | 9 +- .../autoindexing/internal/store/store.go | 27 +- .../internal/store/store_indexes.go | 19 +- .../internal/store/store_indexes_test.go | 127 +- .../internal/store/store_language_support.go | 39 + .../store/store_language_support_test.go} | 0 .../store/store_sourced_commits_test.go | 35 +- internal/codeintel/autoindexing/mocks_test.go | 763 +++- .../codeintel/autoindexing/observability.go | 20 + internal/codeintel/autoindexing/service.go | 132 +- .../codeintel/autoindexing/service_test.go | 55 +- .../codeintel/autoindexing/shared/iface.go | 8 +- .../codeintel/autoindexing/shared/types.go | 134 +- .../graphql/codeintel_support_resolver.go | 34 +- .../graphql/codeintel_tree_info_resolver.go | 115 + ...odeintel_tree_precise_coverage_resolver.go | 23 + ...ntel_tree_searchbased_coverage_resolver.go | 19 + .../autoindexing/transport/graphql/iface.go | 53 + .../graphql/index_configuration_resolver.go | 31 +- .../transport/graphql/mocks_temp.go | 3266 +++++++++++++++++ .../transport/graphql/observability.go | 50 +- .../graphql/precise_based_support_resolver.go | 58 + .../transport/graphql/resolver.go | 161 - .../transport/graphql/root_resolver.go | 464 +++ .../transport/graphql/root_resolver_test.go | 64 + .../graphql/search_based_support_resolver.go | 32 + .../autoindexing/transport/graphql/utils.go | 222 ++ .../transport/graphql/utils_test.go | 174 + .../codeintel/codenav/gittree_translator.go | 35 +- .../codenav/gittree_translator_test.go | 60 +- internal/codeintel/codenav/iface.go | 8 +- internal/codeintel/codenav/init.go | 5 +- .../codenav/internal/lsifstore/lsifstore.go | 5 +- .../internal/lsifstore/lsifstore_hover.go | 8 +- .../internal/lsifstore/lsifstore_locations.go | 11 +- .../internal/lsifstore/lsifstore_stencil.go | 6 +- .../codenav/internal/store/observability.go | 7 +- .../codeintel/codenav/internal/store/store.go | 40 +- internal/codeintel/codenav/mocks_test.go | 417 +-- internal/codeintel/codenav/observability.go | 4 - internal/codeintel/codenav/request_state.go | 29 +- internal/codeintel/codenav/service.go | 167 +- .../codenav/service_definitions_test.go | 126 +- .../codenav/service_diagnostics_test.go | 15 +- .../codeintel/codenav/service_hover_test.go | 38 +- .../codenav/service_implementations_test.go | 44 +- .../codeintel/codenav/service_ranges_test.go | 35 +- .../codenav/service_references_test.go | 54 +- .../codeintel/codenav/service_stencil_test.go | 31 +- internal/codeintel/codenav/shared/types.go | 70 +- .../codenav/transport/graphql/diagnostic.go | 64 + .../graphql/diagnostic_connection.go | 44 + .../graphql/gitblob_lsif_data_resolver.go | 157 +- .../gitblob_lsif_data_resolver_test.go | 202 +- .../transport/graphql/gitblob_resolver.go | 41 +- .../gitblob_tree_lsif_data_resolver.go | 12 + .../codenav/transport/graphql/hover.go | 25 + .../codenav/transport/graphql/iface.go | 46 +- .../transport/graphql/location_resolver.go | 60 + .../graphql/location_resolver_connection.go | 35 + .../codenav/transport/graphql/markdown.go | 41 + .../codenav/transport/graphql/mocks_test.go | 3038 +++++++++++++++ .../transport/graphql/observability.go | 10 +- .../transport/graphql/position_resolver.go | 29 + .../transport/graphql/range_resolver.go | 30 + .../transport/graphql/ranges_resolver.go | 48 + .../graphql/ranges_resolver_connection.go | 36 + .../codenav/transport/graphql/resolver.go | 110 - .../transport/graphql/root_resolver.go | 65 + .../codenav/transport}/graphql/types.go | 39 +- .../codenav/transport/graphql/utils.go | 171 + .../codenav/transport/graphql/utils_test.go | 113 + internal/codeintel/codenav/types.go | 6 +- internal/codeintel/codenav/utils.go | 7 +- .../policies/background/repomatcher/iface.go | 4 +- .../codeintel/policies/enterprise/matcher.go | 4 +- .../codeintel/policies/internal/store/scan.go | 3 +- .../policies/internal/store/store.go | 21 +- .../internal/store/store_configuration.go | 14 +- .../store/store_configuration_test.go | 12 +- .../internal/store/store_repo_test.go | 4 +- .../policies/internal/store/store_repos.go | 12 +- internal/codeintel/policies/mocks_test.go | 247 +- internal/codeintel/policies/service.go | 71 +- internal/codeintel/policies/service_test.go | 64 +- internal/codeintel/policies/shared/types.go | 82 - .../graphql/configuration_policy_resolver.go | 142 + ...onfiguration_policy_resolver_connection.go | 54 + .../git_object_filter_preview_resolver.go | 9 +- .../policies/transport/graphql/iface.go | 14 +- .../transport/graphql/observability.go | 71 +- .../transport/graphql/policy_resolver.go | 94 - .../repository_filter_preview_resolver.go | 56 + .../policies/transport/graphql/resolver.go | 33 - .../transport/graphql/root_resolver.go | 338 ++ .../policies/transport/graphql/utils.go | 156 + .../audit_log_column_resolver.go | 27 + .../sharedresolvers/audit_log_resolver.go | 67 + .../cached_location_resolver.go | 63 +- .../cached_location_resolver_test.go | 70 +- .../configuration_policy_resolver.go | 54 +- .../sharedresolvers/empty_resolver.go | 11 + .../execution_log_entry_resolver.go | 65 + .../sharedresolvers/git_commit_resolver.go | 84 + .../codeintel/sharedresolvers/git_object.go | 32 + .../git_tree_entry_resolver.go | 143 + .../git_tree_submodule_resolver.go | 31 + internal/codeintel/sharedresolvers/iface.go | 40 + .../index_resolver_connection.go | 68 + .../sharedresolvers/index_resolvers.go | 127 + .../index_step_pre_resolver.go | 36 + .../sharedresolvers/index_step_resolver.go | 34 + .../sharedresolvers/index_steps_resolver.go | 93 + .../indexes_repository_namespace_resolver.go | 43 + .../indexes_resolver.go | 13 +- .../codeintel/sharedresolvers/mocks_temp.go | 1379 +++++++ .../codeintel/sharedresolvers}/prefetcher.go | 41 +- .../sharedresolvers}/prefetcher_test.go | 58 +- .../sharedresolvers/repository_resolver.go | 138 + .../retention_policy_matcher_connection.go | 48 + .../retention_policy_matcher_resolver.go | 44 + internal/codeintel/sharedresolvers/summary.go | 70 + .../upload_document_path_connection.go | 34 + .../sharedresolvers/upload_resolver.go | 197 + .../upload_resolver_connection.go | 69 + .../uploads_repository_namespace_resolver.go | 42 + .../uploads_resolver.go | 16 +- internal/codeintel/sharedresolvers/utils.go | 228 ++ internal/codeintel/types/index.go | 92 + .../codeintel/types}/indexers.go | 17 +- internal/codeintel/types/types.go | 167 +- .../uploads/background/expiration/iface.go | 7 +- .../background/expiration/mocks_test.go | 59 +- .../background/expiration/upload_expirer.go | 15 +- .../expiration/upload_expirer_test.go | 13 +- .../codeintel/uploads/internal/store/scan.go | 11 +- .../codeintel/uploads/internal/store/store.go | 17 +- .../internal/store/store_audit_logs.go | 4 +- .../internal/store/store_audit_logs_test.go | 6 +- .../internal/store/store_commits_test.go | 59 +- .../uploads/internal/store/store_dumps.go | 10 +- .../internal/store/store_dumps_test.go | 40 +- .../internal/store/store_packages_test.go | 3 +- .../internal/store/store_references_test.go | 4 +- .../internal/store/store_repositories_test.go | 18 +- .../uploads/internal/store/store_uploads.go | 13 +- .../internal/store/store_uploads_test.go | 202 +- internal/codeintel/uploads/mocks_test.go | 346 +- internal/codeintel/uploads/observability.go | 6 + internal/codeintel/uploads/service.go | 55 +- internal/codeintel/uploads/shared/iface.go | 2 + internal/codeintel/uploads/shared/types.go | 131 +- .../transport/graphql/commitgraph_resolver.go | 13 +- .../uploads/transport/graphql/iface.go | 33 + .../uploads/transport/graphql/mocks_temp.go | 1811 +++++++++ .../transport/graphql/observability.go | 28 +- .../uploads/transport/graphql/resolver.go | 119 - .../transport/graphql/root_resolver.go | 147 + .../transport/graphql/root_resolver_test.go | 61 + .../uploads/transport/graphql/utils.go | 261 ++ .../uploads/transport/graphql/utils_test.go | 178 + mockgen.temp.yaml | 27 +- mockgen.test.yaml | 4 - 223 files changed, 18259 insertions(+), 11328 deletions(-) delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/audit_logs.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/codeintel_tree_info_resolver.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/configuration_connection.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/cursors_test.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/diagnostic.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/diagnostic_connection.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/documents_connection.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/frankenresolver.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/hover.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ids.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ids_test.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/iface.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_connection.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_steps.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_steps_index.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_steps_preindex.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/location_connection.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/observability.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ranges.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ranges_connection.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/repository_filter_preview.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/resolver_test.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/retention_policy_matcher_connection.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/retention_policy_matches.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/summary.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/support.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/upload.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/upload_connection.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/util.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/util_test.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/iface.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/mocks_temp.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/mocks_temp.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/mocks_temps.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/uploads/mocks_uploads.go delete mode 100644 enterprise/cmd/frontend/internal/codeintel/resolvers/mocks_test.go rename {cmd/frontend/internal => internal}/cloneurls/clone_urls.go (100%) rename {cmd/frontend/internal => internal}/cloneurls/clone_urls_test.go (100%) create mode 100644 internal/codeintel/autoindexing/internal/store/store_language_support.go rename internal/codeintel/{codenav/internal/store/store_test.go => autoindexing/internal/store/store_language_support_test.go} (100%) rename enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/codeintel_blob_info_resolver.go => internal/codeintel/autoindexing/transport/graphql/codeintel_support_resolver.go (54%) create mode 100644 internal/codeintel/autoindexing/transport/graphql/codeintel_tree_info_resolver.go create mode 100644 internal/codeintel/autoindexing/transport/graphql/codeintel_tree_precise_coverage_resolver.go create mode 100644 internal/codeintel/autoindexing/transport/graphql/codeintel_tree_searchbased_coverage_resolver.go create mode 100644 internal/codeintel/autoindexing/transport/graphql/iface.go rename enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/configuration.go => internal/codeintel/autoindexing/transport/graphql/index_configuration_resolver.go (50%) create mode 100644 internal/codeintel/autoindexing/transport/graphql/mocks_temp.go create mode 100644 internal/codeintel/autoindexing/transport/graphql/precise_based_support_resolver.go delete mode 100644 internal/codeintel/autoindexing/transport/graphql/resolver.go create mode 100644 internal/codeintel/autoindexing/transport/graphql/root_resolver.go create mode 100644 internal/codeintel/autoindexing/transport/graphql/root_resolver_test.go create mode 100644 internal/codeintel/autoindexing/transport/graphql/search_based_support_resolver.go create mode 100644 internal/codeintel/autoindexing/transport/graphql/utils.go create mode 100644 internal/codeintel/autoindexing/transport/graphql/utils_test.go create mode 100644 internal/codeintel/codenav/transport/graphql/diagnostic.go create mode 100644 internal/codeintel/codenav/transport/graphql/diagnostic_connection.go rename enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/query.go => internal/codeintel/codenav/transport/graphql/gitblob_lsif_data_resolver.go (51%) rename enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/query_test.go => internal/codeintel/codenav/transport/graphql/gitblob_lsif_data_resolver_test.go (50%) create mode 100644 internal/codeintel/codenav/transport/graphql/gitblob_tree_lsif_data_resolver.go create mode 100644 internal/codeintel/codenav/transport/graphql/hover.go create mode 100644 internal/codeintel/codenav/transport/graphql/location_resolver.go create mode 100644 internal/codeintel/codenav/transport/graphql/location_resolver_connection.go create mode 100644 internal/codeintel/codenav/transport/graphql/markdown.go create mode 100644 internal/codeintel/codenav/transport/graphql/mocks_test.go create mode 100644 internal/codeintel/codenav/transport/graphql/position_resolver.go create mode 100644 internal/codeintel/codenav/transport/graphql/range_resolver.go create mode 100644 internal/codeintel/codenav/transport/graphql/ranges_resolver.go create mode 100644 internal/codeintel/codenav/transport/graphql/ranges_resolver_connection.go delete mode 100644 internal/codeintel/codenav/transport/graphql/resolver.go create mode 100644 internal/codeintel/codenav/transport/graphql/root_resolver.go rename {enterprise/cmd/frontend/internal/codeintel/resolvers => internal/codeintel/codenav/transport}/graphql/types.go (57%) create mode 100644 internal/codeintel/codenav/transport/graphql/utils.go create mode 100644 internal/codeintel/codenav/transport/graphql/utils_test.go create mode 100644 internal/codeintel/policies/transport/graphql/configuration_policy_resolver.go create mode 100644 internal/codeintel/policies/transport/graphql/configuration_policy_resolver_connection.go rename enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/git_object_filter_preview.go => internal/codeintel/policies/transport/graphql/git_object_filter_preview_resolver.go (50%) delete mode 100644 internal/codeintel/policies/transport/graphql/policy_resolver.go create mode 100644 internal/codeintel/policies/transport/graphql/repository_filter_preview_resolver.go delete mode 100644 internal/codeintel/policies/transport/graphql/resolver.go create mode 100644 internal/codeintel/policies/transport/graphql/root_resolver.go create mode 100644 internal/codeintel/policies/transport/graphql/utils.go create mode 100644 internal/codeintel/sharedresolvers/audit_log_column_resolver.go create mode 100644 internal/codeintel/sharedresolvers/audit_log_resolver.go rename enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/locations.go => internal/codeintel/sharedresolvers/cached_location_resolver.go (77%) rename enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/locations_test.go => internal/codeintel/sharedresolvers/cached_location_resolver_test.go (66%) rename enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/configuration_policy.go => internal/codeintel/sharedresolvers/configuration_policy_resolver.go (65%) create mode 100644 internal/codeintel/sharedresolvers/empty_resolver.go create mode 100644 internal/codeintel/sharedresolvers/execution_log_entry_resolver.go create mode 100644 internal/codeintel/sharedresolvers/git_commit_resolver.go create mode 100644 internal/codeintel/sharedresolvers/git_object.go create mode 100644 internal/codeintel/sharedresolvers/git_tree_entry_resolver.go create mode 100644 internal/codeintel/sharedresolvers/git_tree_submodule_resolver.go create mode 100644 internal/codeintel/sharedresolvers/iface.go create mode 100644 internal/codeintel/sharedresolvers/index_resolver_connection.go create mode 100644 internal/codeintel/sharedresolvers/index_resolvers.go create mode 100644 internal/codeintel/sharedresolvers/index_step_pre_resolver.go create mode 100644 internal/codeintel/sharedresolvers/index_step_resolver.go create mode 100644 internal/codeintel/sharedresolvers/index_steps_resolver.go create mode 100644 internal/codeintel/sharedresolvers/indexes_repository_namespace_resolver.go rename internal/codeintel/{autoindexing/transport/graphql => sharedresolvers}/indexes_resolver.go (76%) create mode 100644 internal/codeintel/sharedresolvers/mocks_temp.go rename {enterprise/cmd/frontend/internal/codeintel/resolvers/graphql => internal/codeintel/sharedresolvers}/prefetcher.go (77%) rename {enterprise/cmd/frontend/internal/codeintel/resolvers/graphql => internal/codeintel/sharedresolvers}/prefetcher_test.go (73%) create mode 100644 internal/codeintel/sharedresolvers/repository_resolver.go create mode 100644 internal/codeintel/sharedresolvers/retention_policy_matcher_connection.go create mode 100644 internal/codeintel/sharedresolvers/retention_policy_matcher_resolver.go create mode 100644 internal/codeintel/sharedresolvers/summary.go create mode 100644 internal/codeintel/sharedresolvers/upload_document_path_connection.go create mode 100644 internal/codeintel/sharedresolvers/upload_resolver.go create mode 100644 internal/codeintel/sharedresolvers/upload_resolver_connection.go create mode 100644 internal/codeintel/sharedresolvers/uploads_repository_namespace_resolver.go rename internal/codeintel/{uploads/transport/graphql => sharedresolvers}/uploads_resolver.go (67%) create mode 100644 internal/codeintel/sharedresolvers/utils.go create mode 100644 internal/codeintel/types/index.go rename {enterprise/cmd/frontend/internal/codeintel/resolvers/graphql => internal/codeintel/types}/indexers.go (90%) create mode 100644 internal/codeintel/uploads/transport/graphql/iface.go create mode 100644 internal/codeintel/uploads/transport/graphql/mocks_temp.go delete mode 100644 internal/codeintel/uploads/transport/graphql/resolver.go create mode 100644 internal/codeintel/uploads/transport/graphql/root_resolver.go create mode 100644 internal/codeintel/uploads/transport/graphql/root_resolver_test.go create mode 100644 internal/codeintel/uploads/transport/graphql/utils.go create mode 100644 internal/codeintel/uploads/transport/graphql/utils_test.go diff --git a/client/web/src/codeintel/ReferencesPanel.mocks.ts b/client/web/src/codeintel/ReferencesPanel.mocks.ts index 8e6b476a88d..4d520a1fe16 100644 --- a/client/web/src/codeintel/ReferencesPanel.mocks.ts +++ b/client/web/src/codeintel/ReferencesPanel.mocks.ts @@ -153,13 +153,13 @@ function buildMockLocation({ content, repository: { name: repo, - __typename: 'Repository', + __typename: 'CodeIntelRepository', }, commit: { oid: commit, - __typename: 'GitCommit', + __typename: 'CodeIntelCommit', }, - __typename: 'GitBlob', + __typename: 'CodeIntelGitBlob', }, range: { start: { ...start, __typename: 'Position' }, diff --git a/client/web/src/codeintel/ReferencesPanelQueries.ts b/client/web/src/codeintel/ReferencesPanelQueries.ts index 3aeb4371e6a..c93eee921a7 100644 --- a/client/web/src/codeintel/ReferencesPanelQueries.ts +++ b/client/web/src/codeintel/ReferencesPanelQueries.ts @@ -20,7 +20,7 @@ const codeIntelFragments = gql` } } - fragment GitBlobFields on GitBlob { + fragment GitBlobFields on CodeIntelGitBlob { path content repository { diff --git a/cmd/frontend/graphqlbackend/codeintel.go b/cmd/frontend/graphqlbackend/codeintel.go index 53d6c84d0b3..886d91f2aac 100644 --- a/cmd/frontend/graphqlbackend/codeintel.go +++ b/cmd/frontend/graphqlbackend/codeintel.go @@ -5,462 +5,58 @@ import ( "github.com/graph-gophers/graphql-go" - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" - "github.com/sourcegraph/sourcegraph/internal/api" - codenav "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql" + autoindexinggraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/transport/graphql" + codenavgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql" + policiesgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/transport/graphql" + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" + resolvers "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" + uploadsgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/transport/graphql" executor "github.com/sourcegraph/sourcegraph/internal/services/executors/transport/graphql" - "github.com/sourcegraph/sourcegraph/internal/types" ) type CodeIntelResolver interface { - GitBlobLSIFData(ctx context.Context, args *GitBlobLSIFDataArgs) (GitBlobLSIFDataResolver, error) - GitBlobCodeIntelInfo(ctx context.Context, args *GitTreeEntryCodeIntelInfoArgs) (GitBlobCodeIntelSupportResolver, error) - GitTreeCodeIntelInfo(ctx context.Context, args *GitTreeEntryCodeIntelInfoArgs) (GitTreeCodeIntelSupportResolver, error) - - RepositorySummary(ctx context.Context, id graphql.ID) (CodeIntelRepositorySummaryResolver, error) - NodeResolvers() map[string]NodeByIDFunc - - RequestLanguageSupport(ctx context.Context, args *RequestLanguageSupportArgs) (*EmptyResponse, error) + GitBlobLSIFData(ctx context.Context, args *codenavgraphql.GitBlobLSIFDataArgs) (codenavgraphql.GitBlobLSIFDataResolver, error) + GitBlobCodeIntelInfo(ctx context.Context, args *autoindexinggraphql.GitTreeEntryCodeIntelInfoArgs) (_ autoindexinggraphql.GitBlobCodeIntelSupportResolver, err error) + GitTreeCodeIntelInfo(ctx context.Context, args *autoindexinggraphql.GitTreeEntryCodeIntelInfoArgs) (resolver autoindexinggraphql.GitTreeCodeIntelSupportResolver, err error) + RequestLanguageSupport(ctx context.Context, args *autoindexinggraphql.RequestLanguageSupportArgs) (*resolvers.EmptyResponse, error) RequestedLanguageSupport(ctx context.Context) ([]string, error) + NodeResolvers() map[string]NodeByIDFunc + AutoindexingServiceResolver ExecutorResolver UploadsServiceResolver PoliciesServiceResolver } -type AutoindexingServiceResolver interface { - DeleteLSIFIndex(ctx context.Context, args *struct{ ID graphql.ID }) (*EmptyResponse, error) - IndexConfiguration(ctx context.Context, id graphql.ID) (IndexConfigurationResolver, error) // TODO - rename ...ForRepo - LSIFIndexByID(ctx context.Context, id graphql.ID) (LSIFIndexResolver, error) - LSIFIndexes(ctx context.Context, args *LSIFIndexesQueryArgs) (LSIFIndexConnectionResolver, error) - LSIFIndexesByRepo(ctx context.Context, args *LSIFRepositoryIndexesQueryArgs) (LSIFIndexConnectionResolver, error) - QueueAutoIndexJobsForRepo(ctx context.Context, args *QueueAutoIndexJobsForRepoArgs) ([]LSIFIndexResolver, error) - UpdateRepositoryIndexConfiguration(ctx context.Context, args *UpdateRepositoryIndexConfigurationArgs) (*EmptyResponse, error) -} - type ExecutorResolver interface { ExecutorResolver() executor.Resolver } -type CodeNavResolver interface { - CodeNavResolver() codenav.Resolver +type AutoindexingServiceResolver interface { + IndexConfiguration(ctx context.Context, id graphql.ID) (autoindexinggraphql.IndexConfigurationResolver, error) // TODO - rename ...ForRepo + DeleteLSIFIndex(ctx context.Context, args *struct{ ID graphql.ID }) (*resolvers.EmptyResponse, error) + LSIFIndexByID(ctx context.Context, id graphql.ID) (_ resolvers.LSIFIndexResolver, err error) + LSIFIndexes(ctx context.Context, args *autoindexinggraphql.LSIFIndexesQueryArgs) (resolvers.LSIFIndexConnectionResolver, error) + LSIFIndexesByRepo(ctx context.Context, args *autoindexinggraphql.LSIFRepositoryIndexesQueryArgs) (resolvers.LSIFIndexConnectionResolver, error) + QueueAutoIndexJobsForRepo(ctx context.Context, args *autoindexinggraphql.QueueAutoIndexJobsForRepoArgs) ([]resolvers.LSIFIndexResolver, error) + UpdateRepositoryIndexConfiguration(ctx context.Context, args *autoindexinggraphql.UpdateRepositoryIndexConfigurationArgs) (*resolvers.EmptyResponse, error) + RepositorySummary(ctx context.Context, id graphql.ID) (resolvers.CodeIntelRepositorySummaryResolver, error) } type UploadsServiceResolver interface { - CommitGraph(ctx context.Context, id graphql.ID) (CodeIntelligenceCommitGraphResolver, error) - LSIFUploadByID(ctx context.Context, id graphql.ID) (LSIFUploadResolver, error) - LSIFUploads(ctx context.Context, args *LSIFUploadsQueryArgs) (LSIFUploadConnectionResolver, error) - LSIFUploadsByRepo(ctx context.Context, args *LSIFRepositoryUploadsQueryArgs) (LSIFUploadConnectionResolver, error) - DeleteLSIFUpload(ctx context.Context, args *struct{ ID graphql.ID }) (*EmptyResponse, error) + CommitGraph(ctx context.Context, id graphql.ID) (uploadsgraphql.CodeIntelligenceCommitGraphResolver, error) + LSIFUploadByID(ctx context.Context, id graphql.ID) (resolvers.LSIFUploadResolver, error) + LSIFUploads(ctx context.Context, args *uploadsgraphql.LSIFUploadsQueryArgs) (resolvers.LSIFUploadConnectionResolver, error) + LSIFUploadsByRepo(ctx context.Context, args *uploadsgraphql.LSIFRepositoryUploadsQueryArgs) (resolvers.LSIFUploadConnectionResolver, error) + DeleteLSIFUpload(ctx context.Context, args *struct{ ID graphql.ID }) (*resolvers.EmptyResponse, error) } type PoliciesServiceResolver interface { - CodeIntelligenceConfigurationPolicies(ctx context.Context, args *CodeIntelligenceConfigurationPoliciesArgs) (CodeIntelligenceConfigurationPolicyConnectionResolver, error) - ConfigurationPolicyByID(ctx context.Context, id graphql.ID) (CodeIntelligenceConfigurationPolicyResolver, error) - CreateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *CreateCodeIntelligenceConfigurationPolicyArgs) (CodeIntelligenceConfigurationPolicyResolver, error) - DeleteCodeIntelligenceConfigurationPolicy(ctx context.Context, args *DeleteCodeIntelligenceConfigurationPolicyArgs) (*EmptyResponse, error) - PreviewGitObjectFilter(ctx context.Context, id graphql.ID, args *PreviewGitObjectFilterArgs) ([]GitObjectFilterPreviewResolver, error) - PreviewRepositoryFilter(ctx context.Context, args *PreviewRepositoryFilterArgs) (RepositoryFilterPreviewResolver, error) - UpdateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *UpdateCodeIntelligenceConfigurationPolicyArgs) (*EmptyResponse, error) -} - -type LSIFUploadsQueryArgs struct { - graphqlutil.ConnectionArgs - Query *string - State *string - IsLatestForRepo *bool - DependencyOf *graphql.ID - DependentOf *graphql.ID - After *string - IncludeDeleted *bool -} - -type LSIFRepositoryUploadsQueryArgs struct { - *LSIFUploadsQueryArgs - RepositoryID graphql.ID -} - -type LSIFUploadRetentionPolicyMatchesArgs struct { - MatchesOnly bool - First *int32 - After *string - Query *string -} - -type LSIFUploadResolver interface { - ID() graphql.ID - InputCommit() string - Tags(ctx context.Context) ([]string, error) - InputRoot() string - IsLatestForRepo() bool - UploadedAt() DateTime - State() string - Failure() *string - StartedAt() *DateTime - FinishedAt() *DateTime - InputIndexer() string - Indexer() CodeIntelIndexerResolver - PlaceInQueue() *int32 - AssociatedIndex(ctx context.Context) (LSIFIndexResolver, error) - ProjectRoot(ctx context.Context) (*GitTreeEntryResolver, error) - RetentionPolicyOverview(ctx context.Context, args *LSIFUploadRetentionPolicyMatchesArgs) (CodeIntelligenceRetentionPolicyMatchesConnectionResolver, error) - DocumentPaths(ctx context.Context, args *LSIFUploadDocumentPathsQueryArgs) (LSIFUploadDocumentPathsConnectionResolver, error) - AuditLogs(ctx context.Context) (*[]LSIFUploadsAuditLogsResolver, error) -} - -type LSIFUploadConnectionResolver interface { - Nodes(ctx context.Context) ([]LSIFUploadResolver, error) - TotalCount(ctx context.Context) (*int32, error) - PageInfo(ctx context.Context) (*graphqlutil.PageInfo, error) -} - -type LSIFUploadDocumentPathsQueryArgs struct { - Pattern string -} - -type LSIFUploadDocumentPathsConnectionResolver interface { - Nodes(ctx context.Context) ([]string, error) - TotalCount(ctx context.Context) (*int32, error) -} - -type LSIFUploadsAuditLogsResolver interface { - LogTimestamp() DateTime - UploadDeletedAt() *DateTime - Reason() *string - ChangedColumns() []AuditLogColumnChange - UploadID() graphql.ID - InputCommit() string - InputRoot() string - InputIndexer() string - UploadedAt() DateTime - Operation() string - // AssociatedIndex(ctx context.Context) (LSIFIndexResolver, error) -} - -type AuditLogColumnChange interface { - Column() string - Old() *string - New() *string -} - -type LSIFIndexesQueryArgs struct { - graphqlutil.ConnectionArgs - Query *string - State *string - After *string -} - -type LSIFRepositoryIndexesQueryArgs struct { - *LSIFIndexesQueryArgs - RepositoryID graphql.ID -} - -type LSIFIndexResolver interface { - ID() graphql.ID - InputCommit() string - Tags(ctx context.Context) ([]string, error) - InputRoot() string - InputIndexer() string - Indexer() CodeIntelIndexerResolver - QueuedAt() DateTime - State() string - Failure() *string - StartedAt() *DateTime - FinishedAt() *DateTime - Steps() IndexStepsResolver - PlaceInQueue() *int32 - AssociatedUpload(ctx context.Context) (LSIFUploadResolver, error) - ProjectRoot(ctx context.Context) (*GitTreeEntryResolver, error) -} - -type IndexStepsResolver interface { - Setup() []ExecutionLogEntryResolver - PreIndex() []PreIndexStepResolver - Index() IndexStepResolver - Upload() ExecutionLogEntryResolver - Teardown() []ExecutionLogEntryResolver -} - -type PreIndexStepResolver interface { - Root() string - Image() string - Commands() []string - LogEntry() ExecutionLogEntryResolver -} - -type IndexStepResolver interface { - IndexerArgs() []string - Outfile() *string - LogEntry() ExecutionLogEntryResolver -} - -type LSIFIndexConnectionResolver interface { - Nodes(ctx context.Context) ([]LSIFIndexResolver, error) - TotalCount(ctx context.Context) (*int32, error) - PageInfo(ctx context.Context) (*graphqlutil.PageInfo, error) -} - -type QueueAutoIndexJobsForRepoArgs struct { - Repository graphql.ID - Rev *string - Configuration *string -} - -type GitTreeLSIFDataResolver interface { - LSIFUploads(ctx context.Context) ([]LSIFUploadResolver, error) - Diagnostics(ctx context.Context, args *LSIFDiagnosticsArgs) (DiagnosticConnectionResolver, error) -} - -type CodeIntelligenceCommitGraphResolver interface { - Stale(ctx context.Context) (bool, error) - UpdatedAt(ctx context.Context) (*DateTime, error) -} - -type GitBlobLSIFDataResolver interface { - GitTreeLSIFDataResolver - ToGitTreeLSIFData() (GitTreeLSIFDataResolver, bool) - ToGitBlobLSIFData() (GitBlobLSIFDataResolver, bool) - - Stencil(ctx context.Context) ([]RangeResolver, error) - Ranges(ctx context.Context, args *LSIFRangesArgs) (CodeIntelligenceRangeConnectionResolver, error) - Definitions(ctx context.Context, args *LSIFQueryPositionArgs) (LocationConnectionResolver, error) - References(ctx context.Context, args *LSIFPagedQueryPositionArgs) (LocationConnectionResolver, error) - Implementations(ctx context.Context, args *LSIFPagedQueryPositionArgs) (LocationConnectionResolver, error) - Hover(ctx context.Context, args *LSIFQueryPositionArgs) (HoverResolver, error) -} - -type GitBlobLSIFDataArgs struct { - Repo *types.Repo - Commit api.CommitID - Path string - ExactPath bool - ToolName string -} - -type LSIFRangesArgs struct { - StartLine int32 - EndLine int32 -} - -type LSIFQueryPositionArgs struct { - Line int32 - Character int32 - Filter *string -} - -type LSIFPagedQueryPositionArgs struct { - LSIFQueryPositionArgs - graphqlutil.ConnectionArgs - After *string - Filter *string -} - -type LSIFDiagnosticsArgs struct { - graphqlutil.ConnectionArgs -} - -type CodeIntelligenceRangeConnectionResolver interface { - Nodes(ctx context.Context) ([]CodeIntelligenceRangeResolver, error) -} - -type CodeIntelligenceRangeResolver interface { - Range(ctx context.Context) (RangeResolver, error) - Definitions(ctx context.Context) (LocationConnectionResolver, error) - References(ctx context.Context) (LocationConnectionResolver, error) - Implementations(ctx context.Context) (LocationConnectionResolver, error) - Hover(ctx context.Context) (HoverResolver, error) -} - -type LocationConnectionResolver interface { - Nodes(ctx context.Context) ([]LocationResolver, error) - PageInfo(ctx context.Context) (*graphqlutil.PageInfo, error) -} - -type HoverResolver interface { - Markdown() Markdown - Range() RangeResolver -} - -type DiagnosticConnectionResolver interface { - Nodes(ctx context.Context) ([]DiagnosticResolver, error) - TotalCount(ctx context.Context) (int32, error) - PageInfo(ctx context.Context) (*graphqlutil.PageInfo, error) -} - -type DiagnosticResolver interface { - Severity() (*string, error) - Code() (*string, error) - Source() (*string, error) - Message() (*string, error) - Location(ctx context.Context) (LocationResolver, error) -} - -type CodeIntelConfigurationPolicy struct { - Name string - RepositoryID *int32 - RepositoryPatterns *[]string - Type GitObjectType - Pattern string - RetentionEnabled bool - RetentionDurationHours *int32 - RetainIntermediateCommits bool - IndexingEnabled bool - IndexCommitMaxAgeHours *int32 - IndexIntermediateCommits bool -} - -type CodeIntelligenceConfigurationPoliciesArgs struct { - graphqlutil.ConnectionArgs - Repository *graphql.ID - Query *string - ForDataRetention *bool - ForIndexing *bool - After *string -} - -type CreateCodeIntelligenceConfigurationPolicyArgs struct { - Repository *graphql.ID - CodeIntelConfigurationPolicy -} - -type UpdateCodeIntelligenceConfigurationPolicyArgs struct { - ID graphql.ID - Repository *graphql.ID - CodeIntelConfigurationPolicy -} - -type DeleteCodeIntelligenceConfigurationPolicyArgs struct { - Policy graphql.ID -} - -type CodeIntelRepositorySummaryResolver interface { - RecentUploads() []LSIFUploadsWithRepositoryNamespaceResolver - RecentIndexes() []LSIFIndexesWithRepositoryNamespaceResolver - LastUploadRetentionScan() *DateTime - LastIndexScan() *DateTime -} - -type LSIFUploadsWithRepositoryNamespaceResolver interface { - Root() string - Indexer() CodeIntelIndexerResolver - Uploads() []LSIFUploadResolver -} - -type LSIFIndexesWithRepositoryNamespaceResolver interface { - Root() string - Indexer() CodeIntelIndexerResolver - Indexes() []LSIFIndexResolver -} - -type IndexConfigurationResolver interface { - Configuration(ctx context.Context) (*string, error) - InferredConfiguration(ctx context.Context) (*string, error) -} - -type UpdateRepositoryIndexConfigurationArgs struct { - Repository graphql.ID - Configuration string -} - -type PreviewRepositoryFilterArgs struct { - graphqlutil.ConnectionArgs - Patterns []string - After *string -} - -type RepositoryFilterPreviewResolver interface { - Nodes() []*RepositoryResolver - TotalCount() int32 - Limit() *int32 - TotalMatches() int32 - PageInfo() *graphqlutil.PageInfo -} - -type PreviewGitObjectFilterArgs struct { - Type GitObjectType - Pattern string -} - -type GitObjectFilterPreviewResolver interface { - Name() string - Rev() string -} - -type CodeIntelligenceConfigurationPolicyConnectionResolver interface { - Nodes(ctx context.Context) ([]CodeIntelligenceConfigurationPolicyResolver, error) - TotalCount(ctx context.Context) (*int32, error) - PageInfo(ctx context.Context) (*graphqlutil.PageInfo, error) -} - -type CodeIntelligenceConfigurationPolicyResolver interface { - ID() graphql.ID - Repository(ctx context.Context) (*RepositoryResolver, error) - RepositoryPatterns() *[]string - Name() string - Type() (GitObjectType, error) - Pattern() string - Protected() bool - RetentionEnabled() bool - RetentionDurationHours() *int32 - RetainIntermediateCommits() bool - IndexingEnabled() bool - IndexCommitMaxAgeHours() *int32 - IndexIntermediateCommits() bool -} - -type CodeIntelligenceRetentionPolicyMatchesConnectionResolver interface { - Nodes(ctx context.Context) ([]CodeIntelligenceRetentionPolicyMatchResolver, error) - TotalCount(ctx context.Context) (*int32, error) - PageInfo(ctx context.Context) (*graphqlutil.PageInfo, error) -} - -type CodeIntelligenceRetentionPolicyMatchResolver interface { - ConfigurationPolicy() CodeIntelligenceConfigurationPolicyResolver - Matches() bool - ProtectingCommits() *[]string -} - -type GitTreeEntryCodeIntelInfoArgs struct { - Repo *types.Repo - Path string - Commit string -} - -type GitTreeCodeIntelSupportResolver interface { - SearchBasedSupport(context.Context) (*[]GitTreeSearchBasedCoverage, error) - PreciseSupport(context.Context) (*[]GitTreePreciseCoverage, error) -} - -type GitTreeSearchBasedCoverage interface { - CoveredPaths() []string - Support() SearchBasedSupportResolver -} - -type GitTreePreciseCoverage interface { - Support() PreciseSupportResolver - Confidence() string -} - -type GitBlobCodeIntelSupportResolver interface { - SearchBasedSupport(context.Context) (SearchBasedSupportResolver, error) - PreciseSupport(context.Context) (PreciseSupportResolver, error) -} - -type PreciseSupportResolver interface { - SupportLevel() string - Indexers() *[]CodeIntelIndexerResolver -} - -type CodeIntelIndexerResolver interface { - Name() string - URL() string -} - -type SearchBasedSupportResolver interface { - SupportLevel() string - Language() string -} - -type RequestLanguageSupportArgs struct { - Language string + CodeIntelligenceConfigurationPolicies(ctx context.Context, args *policiesgraphql.CodeIntelligenceConfigurationPoliciesArgs) (policiesgraphql.CodeIntelligenceConfigurationPolicyConnectionResolver, error) + ConfigurationPolicyByID(ctx context.Context, id graphql.ID) (policiesgraphql.CodeIntelligenceConfigurationPolicyResolver, error) + CreateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *policiesgraphql.CreateCodeIntelligenceConfigurationPolicyArgs) (policiesgraphql.CodeIntelligenceConfigurationPolicyResolver, error) + DeleteCodeIntelligenceConfigurationPolicy(ctx context.Context, args *policiesgraphql.DeleteCodeIntelligenceConfigurationPolicyArgs) (*sharedresolvers.EmptyResponse, error) + PreviewGitObjectFilter(ctx context.Context, id graphql.ID, args *policiesgraphql.PreviewGitObjectFilterArgs) ([]policiesgraphql.GitObjectFilterPreviewResolver, error) + PreviewRepositoryFilter(ctx context.Context, args *policiesgraphql.PreviewRepositoryFilterArgs) (policiesgraphql.RepositoryFilterPreviewResolver, error) + UpdateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *policiesgraphql.UpdateCodeIntelligenceConfigurationPolicyArgs) (*sharedresolvers.EmptyResponse, error) } diff --git a/cmd/frontend/graphqlbackend/codeintel.graphql b/cmd/frontend/graphqlbackend/codeintel.graphql index ade7ff5b46b..001aa7c7c31 100644 --- a/cmd/frontend/graphqlbackend/codeintel.graphql +++ b/cmd/frontend/graphqlbackend/codeintel.graphql @@ -252,7 +252,7 @@ type RepositoryFilterPreview { """ A list of repositories composing the current page. """ - nodes: [Repository!]! + nodes: [CodeIntelRepository!]! """ The total number of repositories in this result set. @@ -315,7 +315,7 @@ type CodeIntelligenceConfigurationPolicy implements Node { """ The repository to which this configuration policy applies. """ - repository: Repository + repository: CodeIntelRepository """ The set of name patterns matching repositories to which this configuration policy applies. @@ -973,7 +973,7 @@ type LSIFUpload implements Node { """ The project for which this upload provides code intelligence. """ - projectRoot: GitTree + projectRoot: CodeIntelGitTree """ The original 40-character commit commit supplied at upload time. @@ -1244,7 +1244,7 @@ type LSIFIndex implements Node { """ The project for which this upload provides code intelligence. """ - projectRoot: GitTree + projectRoot: CodeIntelGitTree """ The original 40-character commit commit supplied at index time. diff --git a/cmd/frontend/graphqlbackend/git_tree_entry.go b/cmd/frontend/graphqlbackend/git_tree_entry.go index 3287a997d6f..b41253fa315 100644 --- a/cmd/frontend/graphqlbackend/git_tree_entry.go +++ b/cmd/frontend/graphqlbackend/git_tree_entry.go @@ -17,10 +17,12 @@ import ( "github.com/sourcegraph/sourcegraph/cmd/frontend/globals" "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/externallink" - "github.com/sourcegraph/sourcegraph/cmd/frontend/internal/cloneurls" "github.com/sourcegraph/sourcegraph/cmd/frontend/internal/highlight" "github.com/sourcegraph/sourcegraph/internal/api" "github.com/sourcegraph/sourcegraph/internal/authz" + "github.com/sourcegraph/sourcegraph/internal/cloneurls" + autoindexinggraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/transport/graphql" + codenavgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/gitserver" "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" @@ -233,7 +235,7 @@ func (r *GitTreeEntryResolver) IsSingleChild(ctx context.Context, args *gitTreeE return len(entries) == 1, nil } -func (r *GitTreeEntryResolver) LSIF(ctx context.Context, args *struct{ ToolName *string }) (GitBlobLSIFDataResolver, error) { +func (r *GitTreeEntryResolver) LSIF(ctx context.Context, args *struct{ ToolName *string }) (codenavgraphql.GitBlobLSIFDataResolver, error) { codeIntelRequests.WithLabelValues(trace.RequestOrigin(ctx)).Inc() var toolName string @@ -246,7 +248,7 @@ func (r *GitTreeEntryResolver) LSIF(ctx context.Context, args *struct{ ToolName return nil, err } - return EnterpriseResolvers.codeIntelResolver.GitBlobLSIFData(ctx, &GitBlobLSIFDataArgs{ + return EnterpriseResolvers.codeIntelResolver.GitBlobLSIFData(ctx, &codenavgraphql.GitBlobLSIFDataArgs{ Repo: repo, Commit: api.CommitID(r.Commit().OID()), Path: r.Path(), @@ -255,25 +257,25 @@ func (r *GitTreeEntryResolver) LSIF(ctx context.Context, args *struct{ ToolName }) } -func (r *GitTreeEntryResolver) CodeIntelSupport(ctx context.Context) (GitBlobCodeIntelSupportResolver, error) { +func (r *GitTreeEntryResolver) CodeIntelSupport(ctx context.Context) (autoindexinggraphql.GitBlobCodeIntelSupportResolver, error) { repo, err := r.commit.repoResolver.repo(ctx) if err != nil { return nil, err } - return EnterpriseResolvers.codeIntelResolver.GitBlobCodeIntelInfo(ctx, &GitTreeEntryCodeIntelInfoArgs{ + return EnterpriseResolvers.codeIntelResolver.GitBlobCodeIntelInfo(ctx, &autoindexinggraphql.GitTreeEntryCodeIntelInfoArgs{ Repo: repo, Path: r.Path(), }) } -func (r *GitTreeEntryResolver) CodeIntelInfo(ctx context.Context) (GitTreeCodeIntelSupportResolver, error) { +func (r *GitTreeEntryResolver) CodeIntelInfo(ctx context.Context) (autoindexinggraphql.GitTreeCodeIntelSupportResolver, error) { repo, err := r.commit.repoResolver.repo(ctx) if err != nil { return nil, err } - return EnterpriseResolvers.codeIntelResolver.GitTreeCodeIntelInfo(ctx, &GitTreeEntryCodeIntelInfoArgs{ + return EnterpriseResolvers.codeIntelResolver.GitTreeCodeIntelInfo(ctx, &autoindexinggraphql.GitTreeEntryCodeIntelInfoArgs{ Repo: repo, Commit: string(r.Commit().OID()), Path: r.Path(), diff --git a/cmd/frontend/graphqlbackend/graphqlbackend.go b/cmd/frontend/graphqlbackend/graphqlbackend.go index 61d4dc158ef..a040a37555f 100644 --- a/cmd/frontend/graphqlbackend/graphqlbackend.go +++ b/cmd/frontend/graphqlbackend/graphqlbackend.go @@ -22,9 +22,9 @@ import ( sglog "github.com/sourcegraph/log" "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" - "github.com/sourcegraph/sourcegraph/cmd/frontend/internal/cloneurls" "github.com/sourcegraph/sourcegraph/internal/actor" "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/cloneurls" "github.com/sourcegraph/sourcegraph/internal/conf" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/errcode" diff --git a/cmd/frontend/graphqlbackend/node.go b/cmd/frontend/graphqlbackend/node.go index be9650d4e8f..3895e64ecd0 100644 --- a/cmd/frontend/graphqlbackend/node.go +++ b/cmd/frontend/graphqlbackend/node.go @@ -6,6 +6,8 @@ import ( "github.com/graph-gophers/graphql-go" "github.com/graph-gophers/graphql-go/relay" + policiesgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/transport/graphql" + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" executor "github.com/sourcegraph/sourcegraph/internal/services/executors/transport/graphql" "github.com/sourcegraph/sourcegraph/lib/errors" ) @@ -218,18 +220,18 @@ func (r *NodeResolver) ToSite() (*siteResolver, bool) { return n, ok } -func (r *NodeResolver) ToLSIFUpload() (LSIFUploadResolver, bool) { - n, ok := r.Node.(LSIFUploadResolver) +func (r *NodeResolver) ToLSIFUpload() (sharedresolvers.LSIFUploadResolver, bool) { + n, ok := r.Node.(sharedresolvers.LSIFUploadResolver) return n, ok } -func (r *NodeResolver) ToLSIFIndex() (LSIFIndexResolver, bool) { - n, ok := r.Node.(LSIFIndexResolver) +func (r *NodeResolver) ToLSIFIndex() (sharedresolvers.LSIFIndexResolver, bool) { + n, ok := r.Node.(sharedresolvers.LSIFIndexResolver) return n, ok } -func (r *NodeResolver) ToCodeIntelligenceConfigurationPolicy() (CodeIntelligenceConfigurationPolicyResolver, bool) { - n, ok := r.Node.(CodeIntelligenceConfigurationPolicyResolver) +func (r *NodeResolver) ToCodeIntelligenceConfigurationPolicy() (policiesgraphql.CodeIntelligenceConfigurationPolicyResolver, bool) { + n, ok := r.Node.(policiesgraphql.CodeIntelligenceConfigurationPolicyResolver) return n, ok } diff --git a/cmd/frontend/graphqlbackend/repository.go b/cmd/frontend/graphqlbackend/repository.go index 4d3b124ef2d..08e4ea81e54 100644 --- a/cmd/frontend/graphqlbackend/repository.go +++ b/cmd/frontend/graphqlbackend/repository.go @@ -15,6 +15,10 @@ import ( "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/externallink" "github.com/sourcegraph/sourcegraph/internal/api" + autoindex "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/transport/graphql" + policies "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/transport/graphql" + resolvers "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" + uploads "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/transport/graphql" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/extsvc" "github.com/sourcegraph/sourcegraph/internal/extsvc/phabricator" @@ -356,33 +360,33 @@ func (r *RepositoryResolver) hydrate(ctx context.Context) error { return r.err } -func (r *RepositoryResolver) LSIFUploads(ctx context.Context, args *LSIFUploadsQueryArgs) (LSIFUploadConnectionResolver, error) { - return EnterpriseResolvers.codeIntelResolver.LSIFUploadsByRepo(ctx, &LSIFRepositoryUploadsQueryArgs{ +func (r *RepositoryResolver) LSIFUploads(ctx context.Context, args *uploads.LSIFUploadsQueryArgs) (resolvers.LSIFUploadConnectionResolver, error) { + return EnterpriseResolvers.codeIntelResolver.LSIFUploadsByRepo(ctx, &uploads.LSIFRepositoryUploadsQueryArgs{ LSIFUploadsQueryArgs: args, RepositoryID: r.ID(), }) } -func (r *RepositoryResolver) LSIFIndexes(ctx context.Context, args *LSIFIndexesQueryArgs) (LSIFIndexConnectionResolver, error) { - return EnterpriseResolvers.codeIntelResolver.LSIFIndexesByRepo(ctx, &LSIFRepositoryIndexesQueryArgs{ +func (r *RepositoryResolver) LSIFIndexes(ctx context.Context, args *autoindex.LSIFIndexesQueryArgs) (resolvers.LSIFIndexConnectionResolver, error) { + return EnterpriseResolvers.codeIntelResolver.LSIFIndexesByRepo(ctx, &autoindex.LSIFRepositoryIndexesQueryArgs{ LSIFIndexesQueryArgs: args, RepositoryID: r.ID(), }) } -func (r *RepositoryResolver) IndexConfiguration(ctx context.Context) (IndexConfigurationResolver, error) { +func (r *RepositoryResolver) IndexConfiguration(ctx context.Context) (autoindex.IndexConfigurationResolver, error) { return EnterpriseResolvers.codeIntelResolver.IndexConfiguration(ctx, r.ID()) } -func (r *RepositoryResolver) CodeIntelligenceCommitGraph(ctx context.Context) (CodeIntelligenceCommitGraphResolver, error) { +func (r *RepositoryResolver) CodeIntelligenceCommitGraph(ctx context.Context) (uploads.CodeIntelligenceCommitGraphResolver, error) { return EnterpriseResolvers.codeIntelResolver.CommitGraph(ctx, r.ID()) } -func (r *RepositoryResolver) CodeIntelSummary(ctx context.Context) (CodeIntelRepositorySummaryResolver, error) { +func (r *RepositoryResolver) CodeIntelSummary(ctx context.Context) (resolvers.CodeIntelRepositorySummaryResolver, error) { return EnterpriseResolvers.codeIntelResolver.RepositorySummary(ctx, r.ID()) } -func (r *RepositoryResolver) PreviewGitObjectFilter(ctx context.Context, args *PreviewGitObjectFilterArgs) ([]GitObjectFilterPreviewResolver, error) { +func (r *RepositoryResolver) PreviewGitObjectFilter(ctx context.Context, args *policies.PreviewGitObjectFilterArgs) ([]policies.GitObjectFilterPreviewResolver, error) { return EnterpriseResolvers.codeIntelResolver.PreviewGitObjectFilter(ctx, r.ID(), args) } @@ -415,7 +419,8 @@ func (r *schemaResolver) AddPhabricatorRepo(ctx context.Context, args *struct { // TODO(chris): Remove URI in favor of Name. URI *string URL string -}) (*EmptyResponse, error) { +}, +) (*EmptyResponse, error) { if args.Name != nil { args.URI = args.Name } @@ -436,7 +441,8 @@ func (r *schemaResolver) ResolvePhabricatorDiff(ctx context.Context, args *struc AuthorEmail *string Description *string Date *string -}) (*GitCommitResolver, error) { +}, +) (*GitCommitResolver, error) { db := r.db repo, err := db.Repos().GetByName(ctx, api.RepoName(args.RepoName)) if err != nil { @@ -609,7 +615,8 @@ func (r *schemaResolver) AddRepoKeyValuePair(ctx context.Context, args struct { Repo graphql.ID Key string Value *string -}) (*EmptyResponse, error) { +}, +) (*EmptyResponse, error) { if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.db); err != nil { return &EmptyResponse{}, err } @@ -626,7 +633,8 @@ func (r *schemaResolver) UpdateRepoKeyValuePair(ctx context.Context, args struct Repo graphql.ID Key string Value *string -}) (*EmptyResponse, error) { +}, +) (*EmptyResponse, error) { if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.db); err != nil { return &EmptyResponse{}, err } @@ -643,7 +651,8 @@ func (r *schemaResolver) UpdateRepoKeyValuePair(ctx context.Context, args struct func (r *schemaResolver) DeleteRepoKeyValuePair(ctx context.Context, args struct { Repo graphql.ID Key string -}) (*EmptyResponse, error) { +}, +) (*EmptyResponse, error) { if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.db); err != nil { return &EmptyResponse{}, err } diff --git a/cmd/frontend/graphqlbackend/schema.graphql b/cmd/frontend/graphqlbackend/schema.graphql index 4706741d77e..2e51b547dfb 100755 --- a/cmd/frontend/graphqlbackend/schema.graphql +++ b/cmd/frontend/graphqlbackend/schema.graphql @@ -3648,6 +3648,85 @@ type Symbol { fileLocal: Boolean! } +""" +A gitblob resolver specific to code intel. +""" +type CodeIntelGitBlob { + """ + The full path (relative to the root) of this tree. + """ + path: String! + """ + The base name (i.e., last path component only) of this tree. + """ + name: String! + """ + The Git commit containing this tree. + """ + commit: CodeIntelCommit! + """ + The URL to this tree (using the input revision specifier, which may not be immutable). + """ + url: String! + """ + The repository containing this tree. + """ + repository: CodeIntelRepository! + """ + The content of this blob. + """ + content: String! +} + +""" +A codeintel repository is a Git source control repository that is mirrored from some origin code host and it is specific to code intel. +""" +type CodeIntelRepository { + """ + The globally addressable ID for this commit. + """ + id: ID! + """ + The repository's name, as a path with one or more components. It conventionally consists of + the repository's hostname and path (joined by "/"), minus any suffixes (such as ".git"). + Examples: + - github.com/foo/bar + - my-code-host.example.com/myrepo + - myrepo + """ + name: String! + """ + The URL to this repository. + """ + url: String! +} + +""" +A Code Intel Commit. +""" +type CodeIntelCommit { + """ + The globally addressable ID for this commit. + """ + id: ID! + """ + This commit's Git object ID (OID), a 40-character SHA-1 hash. + """ + oid: GitObjectID! + """ + The abbreviated form of this commit's OID. + """ + abbreviatedOID: String! + """ + The URL to this commit (using the input revision specifier, which may not be immutable). + """ + url: String! + """ + The repository that contains this commit. + """ + repository: CodeIntelRepository! +} + """ A location inside a resource (in a repository at a specific commit). """ @@ -3655,7 +3734,7 @@ type Location { """ The file that this location refers to. """ - resource: GitBlob! + resource: CodeIntelGitBlob! """ The range inside the file that this location refers to. """ @@ -4359,6 +4438,36 @@ interface TreeEntry { ): Boolean! } +""" +A Code Intel Git Tree. +""" +type CodeIntelGitTree { + """ + The full path (relative to the root) of this tree. + """ + path: String! + """ + The base name (i.e., last path component only) of this tree. + """ + name: String! + """ + The Git commit containing this tree. + """ + commit: CodeIntelCommit! + """ + The URL to this tree (using the input revision specifier, which may not be immutable). + """ + url: String! + """ + The repository containing this tree. + """ + repository: CodeIntelRepository! + """ + The content of this blob. + """ + content: String! +} + """ A Git tree in a repository. """ diff --git a/cmd/frontend/internal/app/editor.go b/cmd/frontend/internal/app/editor.go index d79ace8fba9..c0740d235b1 100644 --- a/cmd/frontend/internal/app/editor.go +++ b/cmd/frontend/internal/app/editor.go @@ -15,8 +15,8 @@ import ( "github.com/sourcegraph/log" "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" - "github.com/sourcegraph/sourcegraph/cmd/frontend/internal/cloneurls" "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/cloneurls" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/lib/errors" ) diff --git a/enterprise/cmd/frontend/internal/codeintel/init.go b/enterprise/cmd/frontend/internal/codeintel/init.go index e4e62f597d2..2e815ddf3a3 100644 --- a/enterprise/cmd/frontend/internal/codeintel/init.go +++ b/enterprise/cmd/frontend/internal/codeintel/init.go @@ -16,7 +16,6 @@ import ( policiesgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/transport/graphql" uploadgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/transport/graphql" "github.com/sourcegraph/sourcegraph/internal/database" - "github.com/sourcegraph/sourcegraph/internal/honey" "github.com/sourcegraph/sourcegraph/internal/observation" executorgraphql "github.com/sourcegraph/sourcegraph/internal/services/executors/transport/graphql" "github.com/sourcegraph/sourcegraph/internal/trace" @@ -32,16 +31,15 @@ func Init(ctx context.Context, db database.DB, config *Config, enterpriseService } executorResolver := executorgraphql.New(db) - codenavResolver := codenavgraphql.New(services.CodeNavSvc, services.gitserverClient, services.AutoIndexingSvc, config.MaximumIndexesPerMonikerSearch, config.HunkCacheSize, oc("codenav")) - policyResolver := policiesgraphql.New(services.PoliciesSvc, oc("policies")) - autoindexingResolver := autoindexinggraphql.New(services.AutoIndexingSvc, oc("autoindexing")) - uploadResolver := uploadgraphql.New(services.UploadSvc, oc("upload")) - innerResolver := codeintelresolvers.NewResolver(codenavResolver, executorResolver, policyResolver, autoindexingResolver, uploadResolver) + codenavRootResolver := codenavgraphql.NewRootResolver(services.CodeNavSvc, services.AutoIndexingSvc, services.UploadSvc, services.PoliciesSvc, services.gitserverClient, config.MaximumIndexesPerMonikerSearch, config.HunkCacheSize, oc("codenav")) + policyRootResolver := policiesgraphql.NewRootResolver(services.PoliciesSvc, oc("policies")) + autoindexingRootResolver := autoindexinggraphql.NewRootResolver(services.AutoIndexingSvc, services.UploadSvc, services.PoliciesSvc, oc("autoindexing")) + uploadRootResolver := uploadgraphql.NewRootResolver(services.UploadSvc, services.AutoIndexingSvc, services.PoliciesSvc, oc("upload")) - observationCtx := &observation.Context{Logger: nil, Tracer: &trace.Tracer{}, Registerer: nil, HoneyDataset: &honey.Dataset{}} + resolvers := codeintelresolvers.NewResolver(codenavRootResolver, executorResolver, policyRootResolver, autoindexingRootResolver, uploadRootResolver) - enterpriseServices.CodeIntelResolver = codeintelgqlresolvers.NewResolver(db, services.gitserverClient, innerResolver, observationCtx) + enterpriseServices.CodeIntelResolver = codeintelgqlresolvers.NewResolver(resolvers) enterpriseServices.NewCodeIntelUploadHandler = newUploadHandler(services) return nil diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/audit_logs.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/audit_logs.go deleted file mode 100644 index 2e20a036835..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/audit_logs.go +++ /dev/null @@ -1,60 +0,0 @@ -package graphql - -import ( - "strings" - - "github.com/graph-gophers/graphql-go" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - uploadsShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" -) - -type auditLogColumnChangeResolver struct { - columnTransition map[string]*string -} - -func (r *auditLogColumnChangeResolver) Column() string { - return *r.columnTransition["column"] -} - -func (r *auditLogColumnChangeResolver) Old() *string { - return r.columnTransition["old"] -} - -func (r *auditLogColumnChangeResolver) New() *string { - return r.columnTransition["new"] -} - -type lsifUploadsAuditLogResolver struct { - log uploadsShared.UploadLog -} - -func (r *lsifUploadsAuditLogResolver) Reason() *string { return r.log.Reason } -func (r *lsifUploadsAuditLogResolver) ChangedColumns() (values []gql.AuditLogColumnChange) { - for _, transition := range r.log.TransitionColumns { - values = append(values, &auditLogColumnChangeResolver{transition}) - } - return -} - -func (r *lsifUploadsAuditLogResolver) LogTimestamp() gql.DateTime { - return gql.DateTime{Time: r.log.LogTimestamp} -} - -func (r *lsifUploadsAuditLogResolver) UploadDeletedAt() *gql.DateTime { - return gql.DateTimeOrNil(r.log.RecordDeletedAt) -} - -func (r *lsifUploadsAuditLogResolver) UploadID() graphql.ID { - return marshalLSIFUploadGQLID(int64(r.log.UploadID)) -} -func (r *lsifUploadsAuditLogResolver) InputCommit() string { return r.log.Commit } -func (r *lsifUploadsAuditLogResolver) InputRoot() string { return r.log.Root } -func (r *lsifUploadsAuditLogResolver) InputIndexer() string { return r.log.Indexer } -func (r *lsifUploadsAuditLogResolver) UploadedAt() gql.DateTime { - return gql.DateTime{Time: r.log.UploadedAt} -} - -func (r *lsifUploadsAuditLogResolver) Operation() string { - return strings.ToUpper(r.log.Operation) -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/codeintel_tree_info_resolver.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/codeintel_tree_info_resolver.go deleted file mode 100644 index 835bafe9363..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/codeintel_tree_info_resolver.go +++ /dev/null @@ -1,145 +0,0 @@ -package graphql - -import ( - "context" - "strings" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers" - "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/internal/types" - "github.com/sourcegraph/sourcegraph/lib/codeintel/autoindex/config" -) - -type preciseSupportInferenceConfidence string - -const ( - languageSupport preciseSupportInferenceConfidence = "LANGUAGE_SUPPORTED" - projectStructureSupported preciseSupportInferenceConfidence = "PROJECT_STRUCTURE_SUPPORTED" - indexJobInfered preciseSupportInferenceConfidence = "INDEX_JOB_INFERED" -) - -type codeIntelTreeInfoResolver struct { - resolver resolvers.Resolver - commit string - path string - files []string - repo *types.Repo - errTracer *observation.ErrCollector -} - -func NewCodeIntelTreeInfoResolver( - resolver resolvers.Resolver, - repo *types.Repo, - commit, path string, - files []string, - errTracer *observation.ErrCollector, -) gql.GitTreeCodeIntelSupportResolver { - return &codeIntelTreeInfoResolver{ - resolver: resolver, - repo: repo, - commit: commit, - path: path, - files: files, - errTracer: errTracer, - } -} - -func (r *codeIntelTreeInfoResolver) SearchBasedSupport(ctx context.Context) (*[]gql.GitTreeSearchBasedCoverage, error) { - langMapping := make(map[string][]string) - codeNavResolver := r.resolver.CodeNavResolver() - for _, file := range r.files { - ok, lang, err := codeNavResolver.GetSupportedByCtags(ctx, file, r.repo.Name) - if err != nil { - return nil, err - } - if ok { - langMapping[lang] = append(langMapping[lang], file) - } - } - - resolvers := make([]gql.GitTreeSearchBasedCoverage, 0, len(langMapping)) - - for lang, files := range langMapping { - resolvers = append(resolvers, &codeIntelTreeSearchBasedCoverageResolver{ - paths: files, - language: lang, - }) - } - - return &resolvers, nil -} - -func (r *codeIntelTreeInfoResolver) PreciseSupport(ctx context.Context) (*[]gql.GitTreePreciseCoverage, error) { - autoIndexingResolver := r.resolver.AutoIndexingResolver() - configurations, ok, err := autoIndexingResolver.InferedIndexConfiguration(ctx, int(r.repo.ID), r.commit) - if err != nil { - return nil, err - } - - var resolvers []gql.GitTreePreciseCoverage - - if ok { - for _, job := range configurations.IndexJobs { - if job.Root == r.path { - resolvers = append(resolvers, &codeIntelTreePreciseCoverageResolver{ - confidence: indexJobInfered, - // drop the tag if it exists - indexer: imageToIndexer[strings.Split(job.Indexer, ":")[0]], - }) - } - } - } - - hints, err := autoIndexingResolver.InferedIndexConfigurationHints(ctx, int(r.repo.ID), r.commit) - if err != nil { - return nil, err - } - - for _, hint := range hints { - if hint.Root == r.path { - var confidence preciseSupportInferenceConfidence - switch hint.HintConfidence { - case config.HintConfidenceLanguageSupport: - confidence = languageSupport - case config.HintConfidenceProjectStructureSupported: - confidence = projectStructureSupported - default: - continue - } - resolvers = append(resolvers, &codeIntelTreePreciseCoverageResolver{ - confidence: confidence, - // expected that job hints don't include a tag in the indexer name - indexer: imageToIndexer[hint.Indexer], - }) - } - } - - return &resolvers, nil -} - -type codeIntelTreePreciseCoverageResolver struct { - confidence preciseSupportInferenceConfidence - indexer gql.CodeIntelIndexerResolver -} - -func (r *codeIntelTreePreciseCoverageResolver) Support() gql.PreciseSupportResolver { - return NewPreciseCodeIntelSupportResolverFromIndexers([]gql.CodeIntelIndexerResolver{r.indexer}) -} - -func (r *codeIntelTreePreciseCoverageResolver) Confidence() string { - return string(r.confidence) -} - -type codeIntelTreeSearchBasedCoverageResolver struct { - paths []string - language string -} - -func (r *codeIntelTreeSearchBasedCoverageResolver) CoveredPaths() []string { - return r.paths -} - -func (r *codeIntelTreeSearchBasedCoverageResolver) Support() gql.SearchBasedSupportResolver { - return NewSearchBasedCodeIntelResolver(r.language) -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/configuration_connection.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/configuration_connection.go deleted file mode 100644 index ea78346549a..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/configuration_connection.go +++ /dev/null @@ -1,45 +0,0 @@ -package graphql - -import ( - "context" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" - "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - "github.com/sourcegraph/sourcegraph/internal/database" - "github.com/sourcegraph/sourcegraph/internal/observation" -) - -type codeIntelligenceConfigurationPolicyConnectionResolver struct { - db database.DB - policies []dbstore.ConfigurationPolicy - totalCount int - errTracer *observation.ErrCollector -} - -func NewCodeIntelligenceConfigurationPolicyConnectionResolver(db database.DB, policies []dbstore.ConfigurationPolicy, totalCount int, errTracer *observation.ErrCollector) gql.CodeIntelligenceConfigurationPolicyConnectionResolver { - return &codeIntelligenceConfigurationPolicyConnectionResolver{ - db: db, - policies: policies, - totalCount: totalCount, - errTracer: errTracer, - } -} - -func (r *codeIntelligenceConfigurationPolicyConnectionResolver) Nodes(ctx context.Context) ([]gql.CodeIntelligenceConfigurationPolicyResolver, error) { - resolvers := make([]gql.CodeIntelligenceConfigurationPolicyResolver, 0, len(r.policies)) - for _, policy := range r.policies { - resolvers = append(resolvers, NewConfigurationPolicyResolver(r.db, policy, r.errTracer)) - } - - return resolvers, nil -} - -func (r *codeIntelligenceConfigurationPolicyConnectionResolver) TotalCount(ctx context.Context) (*int32, error) { - v := int32(r.totalCount) - return &v, nil -} - -func (r *codeIntelligenceConfigurationPolicyConnectionResolver) PageInfo(ctx context.Context) (*graphqlutil.PageInfo, error) { - return graphqlutil.HasNextPage(len(r.policies) < r.totalCount), nil -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/cursors_test.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/cursors_test.go deleted file mode 100644 index 2bc35c92a0d..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/cursors_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package graphql - -import ( - "testing" - - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" -) - -func TestCursor(t *testing.T) { - expected := "test" - pageInfo := graphqlutil.EncodeCursor(&expected) - - if !pageInfo.HasNextPage() { - t.Fatalf("expected next page") - } - if pageInfo.EndCursor() == nil { - t.Fatalf("unexpected nil cursor") - } - - value, err := graphqlutil.DecodeCursor(pageInfo.EndCursor()) - if err != nil { - t.Fatalf("unexpected error decoding cursor: %s", err) - } - if value != expected { - t.Errorf("unexpected decoded cursor. want=%s have=%s", expected, value) - } -} - -func TestCursorEmpty(t *testing.T) { - pageInfo := graphqlutil.EncodeCursor(nil) - - if pageInfo.HasNextPage() { - t.Errorf("unexpected next page") - } - if pageInfo.EndCursor() != nil { - t.Errorf("unexpected encoded cursor: %s", *pageInfo.EndCursor()) - } - - value, err := graphqlutil.DecodeCursor(nil) - if err != nil { - t.Fatalf("unexpected error decoding cursor: %s", err) - } - if value != "" { - t.Errorf("unexpected decoded cursor: %s", value) - } -} - -func TestIntCursor(t *testing.T) { - expected := 42 - pageInfo := graphqlutil.EncodeIntCursor(toInt32(&expected)) - - if !pageInfo.HasNextPage() { - t.Fatalf("expected next page") - } - if pageInfo.EndCursor() == nil { - t.Fatalf("unexpected nil cursor") - } - - value, err := graphqlutil.DecodeIntCursor(pageInfo.EndCursor()) - if err != nil { - t.Fatalf("unexpected error decoding cursor: %s", err) - } - if value != expected { - t.Errorf("unexpected decoded cursor. want=%d have=%d", expected, value) - } -} - -func TestIntCursorEmpty(t *testing.T) { - pageInfo := graphqlutil.EncodeIntCursor(nil) - - if pageInfo.HasNextPage() { - t.Errorf("unexpected next page") - } - if pageInfo.EndCursor() != nil { - t.Errorf("unexpected encoded cursor: %s", *pageInfo.EndCursor()) - } - - value, err := graphqlutil.DecodeIntCursor(nil) - if err != nil { - t.Fatalf("unexpected error decoding cursor: %s", err) - } - if value != 0 { - t.Errorf("unexpected decoded cursor: %d", value) - } -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/diagnostic.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/diagnostic.go deleted file mode 100644 index ef39b8a90ea..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/diagnostic.go +++ /dev/null @@ -1,54 +0,0 @@ -package graphql - -import ( - "context" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -type DiagnosticResolver struct { - diagnostic AdjustedDiagnostic - locationResolver *CachedLocationResolver -} - -func NewDiagnosticResolver(diagnostic AdjustedDiagnostic, locationResolver *CachedLocationResolver) gql.DiagnosticResolver { - return &DiagnosticResolver{ - diagnostic: diagnostic, - locationResolver: locationResolver, - } -} - -func (r *DiagnosticResolver) Severity() (*string, error) { return toSeverity(r.diagnostic.Severity) } -func (r *DiagnosticResolver) Code() (*string, error) { return strPtr(r.diagnostic.Code), nil } -func (r *DiagnosticResolver) Source() (*string, error) { return strPtr(r.diagnostic.Source), nil } -func (r *DiagnosticResolver) Message() (*string, error) { return strPtr(r.diagnostic.Message), nil } - -func (r *DiagnosticResolver) Location(ctx context.Context) (gql.LocationResolver, error) { - return resolveLocation( - ctx, - r.locationResolver, - AdjustedLocation{ - Dump: r.diagnostic.Dump, - Path: r.diagnostic.Path, - AdjustedCommit: r.diagnostic.AdjustedCommit, - AdjustedRange: r.diagnostic.AdjustedRange, - }, - ) -} - -var severities = map[int]string{ - 1: "ERROR", - 2: "WARNING", - 3: "INFORMATION", - 4: "HINT", -} - -func toSeverity(val int) (*string, error) { - severity, ok := severities[val] - if !ok { - return nil, errors.Errorf("unknown diagnostic severity %d", val) - } - - return &severity, nil -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/diagnostic_connection.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/diagnostic_connection.go deleted file mode 100644 index e6345dd5a7e..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/diagnostic_connection.go +++ /dev/null @@ -1,38 +0,0 @@ -package graphql - -import ( - "context" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" -) - -type DiagnosticConnectionResolver struct { - diagnostics []AdjustedDiagnostic - totalCount int - locationResolver *CachedLocationResolver -} - -func NewDiagnosticConnectionResolver(diagnostics []AdjustedDiagnostic, totalCount int, locationResolver *CachedLocationResolver) gql.DiagnosticConnectionResolver { - return &DiagnosticConnectionResolver{ - diagnostics: diagnostics, - totalCount: totalCount, - locationResolver: locationResolver, - } -} - -func (r *DiagnosticConnectionResolver) Nodes(ctx context.Context) ([]gql.DiagnosticResolver, error) { - resolvers := make([]gql.DiagnosticResolver, 0, len(r.diagnostics)) - for i := range r.diagnostics { - resolvers = append(resolvers, NewDiagnosticResolver(r.diagnostics[i], r.locationResolver)) - } - return resolvers, nil -} - -func (r *DiagnosticConnectionResolver) TotalCount(ctx context.Context) (int32, error) { - return int32(r.totalCount), nil -} - -func (r *DiagnosticConnectionResolver) PageInfo(ctx context.Context) (*graphqlutil.PageInfo, error) { - return graphqlutil.HasNextPage(len(r.diagnostics) < r.totalCount), nil -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/documents_connection.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/documents_connection.go deleted file mode 100644 index 1b3fc595dff..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/documents_connection.go +++ /dev/null @@ -1,17 +0,0 @@ -package graphql - -import "context" - -type uploadDocumentPathsConnectionResolver struct { - totalCount int - documents []string -} - -func (r *uploadDocumentPathsConnectionResolver) Nodes(ctx context.Context) ([]string, error) { - return r.documents, nil -} - -func (r *uploadDocumentPathsConnectionResolver) TotalCount(ctx context.Context) (*int32, error) { - count := int32(r.totalCount) - return &count, nil -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/frankenresolver.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/frankenresolver.go deleted file mode 100644 index 6fe0cc17f23..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/frankenresolver.go +++ /dev/null @@ -1,110 +0,0 @@ -package graphql - -import ( - "context" - - "github.com/graph-gophers/graphql-go" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" -) - -type frankenResolver struct { - *Resolver - gql.AutoindexingServiceResolver - gql.UploadsServiceResolver - gql.PoliciesServiceResolver -} - -func (r *frankenResolver) getAutoindexingServiceResolver() gql.AutoindexingServiceResolver { - return r.Resolver -} - -func (r *frankenResolver) LSIFIndexByID(ctx context.Context, id graphql.ID) (_ gql.LSIFIndexResolver, err error) { - return r.getAutoindexingServiceResolver().LSIFIndexByID(ctx, id) -} - -func (r *frankenResolver) LSIFIndexes(ctx context.Context, args *gql.LSIFIndexesQueryArgs) (_ gql.LSIFIndexConnectionResolver, err error) { - return r.getAutoindexingServiceResolver().LSIFIndexes(ctx, args) -} - -func (r *frankenResolver) LSIFIndexesByRepo(ctx context.Context, args *gql.LSIFRepositoryIndexesQueryArgs) (_ gql.LSIFIndexConnectionResolver, err error) { - return r.getAutoindexingServiceResolver().LSIFIndexesByRepo(ctx, args) -} - -func (r *frankenResolver) DeleteLSIFIndex(ctx context.Context, args *struct{ ID graphql.ID }) (_ *gql.EmptyResponse, err error) { - return r.getAutoindexingServiceResolver().DeleteLSIFIndex(ctx, args) -} - -func (r *frankenResolver) QueueAutoIndexJobsForRepo(ctx context.Context, args *gql.QueueAutoIndexJobsForRepoArgs) (_ []gql.LSIFIndexResolver, err error) { - return r.getAutoindexingServiceResolver().QueueAutoIndexJobsForRepo(ctx, args) -} - -func (r *frankenResolver) IndexConfiguration(ctx context.Context, id graphql.ID) (_ gql.IndexConfigurationResolver, err error) { - return r.getAutoindexingServiceResolver().IndexConfiguration(ctx, id) -} - -func (r *frankenResolver) UpdateRepositoryIndexConfiguration(ctx context.Context, args *gql.UpdateRepositoryIndexConfigurationArgs) (_ *gql.EmptyResponse, err error) { - return r.getAutoindexingServiceResolver().UpdateRepositoryIndexConfiguration(ctx, args) -} - -func (r *frankenResolver) getUploadsServiceResolver() gql.UploadsServiceResolver { - return r.Resolver - - // Uncomment after https://github.com/sourcegraph/sourcegraph/issues/33375 - // return r.UploadsServiceResolver -} - -func (r *frankenResolver) LSIFUploadByID(ctx context.Context, id graphql.ID) (_ gql.LSIFUploadResolver, err error) { - return r.getUploadsServiceResolver().LSIFUploadByID(ctx, id) -} - -func (r *frankenResolver) LSIFUploads(ctx context.Context, args *gql.LSIFUploadsQueryArgs) (_ gql.LSIFUploadConnectionResolver, err error) { - return r.getUploadsServiceResolver().LSIFUploads(ctx, args) -} - -func (r *frankenResolver) LSIFUploadsByRepo(ctx context.Context, args *gql.LSIFRepositoryUploadsQueryArgs) (_ gql.LSIFUploadConnectionResolver, err error) { - return r.getUploadsServiceResolver().LSIFUploadsByRepo(ctx, args) -} - -func (r *frankenResolver) DeleteLSIFUpload(ctx context.Context, args *struct{ ID graphql.ID }) (_ *gql.EmptyResponse, err error) { - return r.getUploadsServiceResolver().DeleteLSIFUpload(ctx, args) -} - -func (r *frankenResolver) CommitGraph(ctx context.Context, id graphql.ID) (_ gql.CodeIntelligenceCommitGraphResolver, err error) { - return r.getUploadsServiceResolver().CommitGraph(ctx, id) -} - -func (r *frankenResolver) getPoliciesServiceResolver() gql.PoliciesServiceResolver { - return r.Resolver - - // Uncomment after https://github.com/sourcegraph/sourcegraph/issues/33376 - // return r.PoliciesServiceResolver -} - -func (r *frankenResolver) ConfigurationPolicyByID(ctx context.Context, id graphql.ID) (_ gql.CodeIntelligenceConfigurationPolicyResolver, err error) { - return r.getPoliciesServiceResolver().ConfigurationPolicyByID(ctx, id) -} - -func (r *frankenResolver) CodeIntelligenceConfigurationPolicies(ctx context.Context, args *gql.CodeIntelligenceConfigurationPoliciesArgs) (_ gql.CodeIntelligenceConfigurationPolicyConnectionResolver, err error) { - return r.getPoliciesServiceResolver().CodeIntelligenceConfigurationPolicies(ctx, args) -} - -func (r *frankenResolver) CreateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *gql.CreateCodeIntelligenceConfigurationPolicyArgs) (_ gql.CodeIntelligenceConfigurationPolicyResolver, err error) { - return r.getPoliciesServiceResolver().CreateCodeIntelligenceConfigurationPolicy(ctx, args) -} - -func (r *frankenResolver) UpdateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *gql.UpdateCodeIntelligenceConfigurationPolicyArgs) (_ *gql.EmptyResponse, err error) { - return r.getPoliciesServiceResolver().UpdateCodeIntelligenceConfigurationPolicy(ctx, args) -} - -func (r *frankenResolver) DeleteCodeIntelligenceConfigurationPolicy(ctx context.Context, args *gql.DeleteCodeIntelligenceConfigurationPolicyArgs) (_ *gql.EmptyResponse, err error) { - return r.getPoliciesServiceResolver().DeleteCodeIntelligenceConfigurationPolicy(ctx, args) -} - -func (r *frankenResolver) PreviewRepositoryFilter(ctx context.Context, args *gql.PreviewRepositoryFilterArgs) (_ gql.RepositoryFilterPreviewResolver, err error) { - return r.getPoliciesServiceResolver().PreviewRepositoryFilter(ctx, args) -} - -func (r *frankenResolver) PreviewGitObjectFilter(ctx context.Context, id graphql.ID, args *gql.PreviewGitObjectFilterArgs) (_ []gql.GitObjectFilterPreviewResolver, err error) { - return r.getPoliciesServiceResolver().PreviewGitObjectFilter(ctx, id, args) -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/hover.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/hover.go deleted file mode 100644 index 16b44871879..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/hover.go +++ /dev/null @@ -1,22 +0,0 @@ -package graphql - -import ( - "github.com/sourcegraph/go-lsp" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" -) - -type HoverResolver struct { - text string - lspRange lsp.Range -} - -func NewHoverResolver(text string, lspRange lsp.Range) gql.HoverResolver { - return &HoverResolver{ - text: text, - lspRange: lspRange, - } -} - -func (r *HoverResolver) Markdown() gql.Markdown { return gql.Markdown(r.text) } -func (r *HoverResolver) Range() gql.RangeResolver { return gql.NewRangeResolver(r.lspRange) } diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ids.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ids.go deleted file mode 100644 index 79464c19d34..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ids.go +++ /dev/null @@ -1,53 +0,0 @@ -package graphql - -import ( - "strconv" - - "github.com/graph-gophers/graphql-go" - "github.com/graph-gophers/graphql-go/relay" -) - -func marshalLSIFUploadGQLID(uploadID int64) graphql.ID { - return relay.MarshalID("LSIFUpload", uploadID) -} - -func unmarshalLSIFUploadGQLID(id graphql.ID) (uploadID int64, err error) { - // First, try to unmarshal the ID as a string and then convert it to an - // integer. This is here to maintain backwards compatibility with the - // src-cli lsif upload command, which constructs its own relay identifier - // from a the string payload returned by the upload proxy. - - var idString string - err = relay.UnmarshalSpec(id, &idString) - if err == nil { - uploadID, err = strconv.ParseInt(idString, 10, 64) - return - } - - // If it wasn't unmarshal-able as a string, it's a new-style int identifier - err = relay.UnmarshalSpec(id, &uploadID) - return uploadID, err -} - -func marshalLSIFIndexGQLID(indexID int64) graphql.ID { - return relay.MarshalID("LSIFIndex", indexID) -} - -func unmarshalLSIFIndexGQLID(id graphql.ID) (indexID int64, err error) { - err = relay.UnmarshalSpec(id, &indexID) - return indexID, err -} - -func marshalConfigurationPolicyGQLID(configurationPolicyID int64) graphql.ID { - return relay.MarshalID("CodeIntelligenceConfigurationPolicy", configurationPolicyID) -} - -func unmarshalConfigurationPolicyGQLID(id graphql.ID) (configurationPolicyID int64, err error) { - err = relay.UnmarshalSpec(id, &configurationPolicyID) - return configurationPolicyID, err -} - -func unmarshalRepositoryID(id graphql.ID) (repositoryID int64, err error) { - err = relay.UnmarshalSpec(id, &repositoryID) - return repositoryID, err -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ids_test.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ids_test.go deleted file mode 100644 index cb6830a253a..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ids_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package graphql - -import ( - "encoding/base64" - "testing" - - "github.com/graph-gophers/graphql-go" -) - -func TestUploadID(t *testing.T) { - expected := int64(42) - value, err := unmarshalLSIFUploadGQLID(marshalLSIFUploadGQLID(expected)) - if err != nil { - t.Fatalf("unexpected error marshalling id: %s", err) - } - if value != expected { - t.Errorf("unexpected id. have=%d want=%d", expected, value) - } -} - -func TestUnmarshalUploadIDString(t *testing.T) { - expected := int64(42) - id := graphql.ID(base64.StdEncoding.EncodeToString([]byte(`LSIFUpload:"42"`))) - value, err := unmarshalLSIFUploadGQLID(id) - if err != nil { - t.Fatalf("unexpected error marshalling id: %s", err) - } - if value != expected { - t.Errorf("unexpected id. have=%d want=%d", expected, value) - } -} - -func TestIndexID(t *testing.T) { - expected := int64(42) - value, err := unmarshalLSIFIndexGQLID(marshalLSIFIndexGQLID(expected)) - if err != nil { - t.Fatalf("unexpected error marshalling id: %s", err) - } - if value != expected { - t.Errorf("unexpected id. have=%d want=%d", expected, value) - } -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/iface.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/iface.go deleted file mode 100644 index f903cc8b486..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/iface.go +++ /dev/null @@ -1,20 +0,0 @@ -package graphql - -import ( - "context" - - "github.com/grafana/regexp" - - "github.com/sourcegraph/sourcegraph/internal/api" - policies "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/enterprise" - "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" - "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" -) - -type GitserverClient interface { - policies.GitserverClient - shared.GitserverClient - - ListFiles(ctx context.Context, repositoryID int, commit string, pattern *regexp.Regexp) ([]string, error) - ListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) ([]*gitdomain.Tag, error) -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index.go deleted file mode 100644 index e1be2ef202e..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index.go +++ /dev/null @@ -1,112 +0,0 @@ -package graphql - -import ( - "context" - "strings" - - "github.com/graph-gophers/graphql-go" - "github.com/opentracing/opentracing-go/log" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers" - "github.com/sourcegraph/sourcegraph/internal/api" - store "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - "github.com/sourcegraph/sourcegraph/internal/database" - "github.com/sourcegraph/sourcegraph/internal/observation" -) - -type IndexResolver struct { - db database.DB - gitserver GitserverClient - resolver resolvers.Resolver - index store.Index - prefetcher *Prefetcher - locationResolver *CachedLocationResolver - traceErrs *observation.ErrCollector -} - -func NewIndexResolver(db database.DB, gitserver GitserverClient, resolver resolvers.Resolver, index store.Index, prefetcher *Prefetcher, locationResolver *CachedLocationResolver, errTrace *observation.ErrCollector) gql.LSIFIndexResolver { - if index.AssociatedUploadID != nil { - // Request the next batch of upload fetches to contain the record's associated - // upload id, if one exists it exists. This allows the prefetcher.GetUploadByID - // invocation in the AssociatedUpload method to batch its work with sibling - // resolvers, which share the same prefetcher instance. - prefetcher.MarkUpload(*index.AssociatedUploadID) - } - - return &IndexResolver{ - db: db, - gitserver: gitserver, - resolver: resolver, - index: index, - prefetcher: prefetcher, - locationResolver: locationResolver, - traceErrs: errTrace, - } -} - -func (r *IndexResolver) ID() graphql.ID { return marshalLSIFIndexGQLID(int64(r.index.ID)) } -func (r *IndexResolver) InputCommit() string { return r.index.Commit } -func (r *IndexResolver) InputRoot() string { return r.index.Root } -func (r *IndexResolver) InputIndexer() string { return r.index.Indexer } -func (r *IndexResolver) QueuedAt() gql.DateTime { return gql.DateTime{Time: r.index.QueuedAt} } -func (r *IndexResolver) Failure() *string { return r.index.FailureMessage } -func (r *IndexResolver) StartedAt() *gql.DateTime { return gql.DateTimeOrNil(r.index.StartedAt) } -func (r *IndexResolver) FinishedAt() *gql.DateTime { return gql.DateTimeOrNil(r.index.FinishedAt) } -func (r *IndexResolver) Steps() gql.IndexStepsResolver { - return &indexStepsResolver{db: r.db, index: r.index} -} -func (r *IndexResolver) PlaceInQueue() *int32 { return toInt32(r.index.Rank) } - -func (r *IndexResolver) Tags(ctx context.Context) (tagsNames []string, err error) { - tags, err := r.gitserver.ListTags(ctx, api.RepoName(r.index.RepositoryName), r.index.Commit) - if err != nil { - return nil, err - } - for _, tag := range tags { - tagsNames = append(tagsNames, tag.Name) - } - return -} - -func (r *IndexResolver) State() string { - state := strings.ToUpper(r.index.State) - if state == "FAILED" { - state = "ERRORED" - } - - return state -} - -func (r *IndexResolver) AssociatedUpload(ctx context.Context) (_ gql.LSIFUploadResolver, err error) { - if r.index.AssociatedUploadID == nil { - return nil, nil - } - - defer r.traceErrs.Collect(&err, - log.String("indexResolver.field", "associatedUpload"), - log.Int("associatedUpload", *r.index.AssociatedUploadID), - ) - - upload, exists, err := r.prefetcher.GetUploadByID(ctx, *r.index.AssociatedUploadID) - if err != nil || !exists { - return nil, err - } - - return NewUploadResolver(r.db, r.gitserver, r.resolver, upload, r.prefetcher, r.locationResolver, r.traceErrs), nil -} - -func (r *IndexResolver) ProjectRoot(ctx context.Context) (_ *gql.GitTreeEntryResolver, err error) { - defer r.traceErrs.Collect(&err, log.String("indexResolver.field", "projectRoot")) - - return r.locationResolver.Path(ctx, api.RepoID(r.index.RepositoryID), r.index.Commit, r.index.Root) -} - -func (r *IndexResolver) Indexer() gql.CodeIntelIndexerResolver { - // drop the tag if it exists - if idx, ok := imageToIndexer[strings.Split(r.index.Indexer, ":")[0]]; ok { - return idx - } - - return &codeIntelIndexerResolver{name: r.index.Indexer} -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_connection.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_connection.go deleted file mode 100644 index cad65ac99f9..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_connection.go +++ /dev/null @@ -1,67 +0,0 @@ -package graphql - -import ( - "context" - - "github.com/opentracing/opentracing-go/log" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" - "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers" - autoindexinggraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/transport/graphql" - "github.com/sourcegraph/sourcegraph/internal/database" - "github.com/sourcegraph/sourcegraph/internal/observation" -) - -type IndexConnectionResolver struct { - db database.DB - gitserver GitserverClient - resolver resolvers.Resolver - indexesResolver *autoindexinggraphql.IndexesResolver - prefetcher *Prefetcher - locationResolver *CachedLocationResolver - errTracer *observation.ErrCollector -} - -func NewIndexConnectionResolver(db database.DB, gitserver GitserverClient, resolver resolvers.Resolver, indexesResolver *autoindexinggraphql.IndexesResolver, prefetcher *Prefetcher, locationResolver *CachedLocationResolver, errTracer *observation.ErrCollector) gql.LSIFIndexConnectionResolver { - return &IndexConnectionResolver{ - db: db, - gitserver: gitserver, - resolver: resolver, - indexesResolver: indexesResolver, - prefetcher: prefetcher, - locationResolver: locationResolver, - errTracer: errTracer, - } -} - -func (r *IndexConnectionResolver) Nodes(ctx context.Context) ([]gql.LSIFIndexResolver, error) { - if err := r.indexesResolver.Resolve(ctx); err != nil { - return nil, err - } - - resolvers := make([]gql.LSIFIndexResolver, 0, len(r.indexesResolver.Indexes)) - for i := range r.indexesResolver.Indexes { - index := convertSharedIndexToDBStoreIndex(r.indexesResolver.Indexes[i]) - resolvers = append(resolvers, NewIndexResolver(r.db, r.gitserver, r.resolver, index, r.prefetcher, r.locationResolver, r.errTracer)) - } - return resolvers, nil -} - -func (r *IndexConnectionResolver) TotalCount(ctx context.Context) (_ *int32, err error) { - defer r.errTracer.Collect(&err, log.String("indexConnectionResolver.field", "totalCount")) - - if err := r.indexesResolver.Resolve(ctx); err != nil { - return nil, err - } - return toInt32(&r.indexesResolver.TotalCount), nil -} - -func (r *IndexConnectionResolver) PageInfo(ctx context.Context) (_ *graphqlutil.PageInfo, err error) { - defer r.errTracer.Collect(&err, log.String("indexConnectionResolver.field", "pageInfo")) - - if err := r.indexesResolver.Resolve(ctx); err != nil { - return nil, err - } - return graphqlutil.EncodeIntCursor(toInt32(r.indexesResolver.NextOffset)), nil -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_steps.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_steps.go deleted file mode 100644 index dd76b3cd923..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_steps.go +++ /dev/null @@ -1,86 +0,0 @@ -package graphql - -import ( - "fmt" - "strings" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - store "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - "github.com/sourcegraph/sourcegraph/internal/database" - "github.com/sourcegraph/sourcegraph/internal/workerutil" -) - -// indexStepsResolver resolves the steps of an index record. -// -// Index jobs are broken into three parts: -// - pre-index steps; all but the last docker step -// - index step; the last docker step -// - upload step; the only src-cli step -// -// The setup and teardown steps match the executor setup and teardown. -type indexStepsResolver struct { - db database.DB - index store.Index -} - -var _ gql.IndexStepsResolver = &indexStepsResolver{} - -func (r *indexStepsResolver) Setup() []gql.ExecutionLogEntryResolver { - return r.executionLogEntryResolversWithPrefix("setup.") -} - -func (r *indexStepsResolver) PreIndex() []gql.PreIndexStepResolver { - var resolvers []gql.PreIndexStepResolver - for i, step := range r.index.DockerSteps { - if entry, ok := r.findExecutionLogEntry(fmt.Sprintf("step.docker.%d", i)); ok { - resolvers = append(resolvers, &preIndexStepResolver{db: r.db, step: step, entry: &entry}) - } else { - resolvers = append(resolvers, &preIndexStepResolver{db: r.db, step: step, entry: nil}) - } - } - - return resolvers -} - -func (r *indexStepsResolver) Index() gql.IndexStepResolver { - if entry, ok := r.findExecutionLogEntry(fmt.Sprintf("step.docker.%d", len(r.index.DockerSteps))); ok { - return &indexStepResolver{db: r.db, index: r.index, entry: &entry} - } - - return &indexStepResolver{db: r.db, index: r.index, entry: nil} -} - -func (r *indexStepsResolver) Upload() gql.ExecutionLogEntryResolver { - if entry, ok := r.findExecutionLogEntry("step.src.0"); ok { - return gql.NewExecutionLogEntryResolver(r.db, entry) - } - - return nil -} - -func (r *indexStepsResolver) Teardown() []gql.ExecutionLogEntryResolver { - return r.executionLogEntryResolversWithPrefix("teardown.") -} - -func (r *indexStepsResolver) findExecutionLogEntry(key string) (workerutil.ExecutionLogEntry, bool) { - for _, entry := range r.index.ExecutionLogs { - if entry.Key == key { - return entry, true - } - } - - return workerutil.ExecutionLogEntry{}, false -} - -func (r *indexStepsResolver) executionLogEntryResolversWithPrefix(prefix string) []gql.ExecutionLogEntryResolver { - var resolvers []gql.ExecutionLogEntryResolver - for _, entry := range r.index.ExecutionLogs { - if !strings.HasPrefix(entry.Key, prefix) { - continue - } - r := gql.NewExecutionLogEntryResolver(r.db, entry) - resolvers = append(resolvers, r) - } - - return resolvers -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_steps_index.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_steps_index.go deleted file mode 100644 index b71343f83d8..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_steps_index.go +++ /dev/null @@ -1,27 +0,0 @@ -package graphql - -import ( - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - store "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - "github.com/sourcegraph/sourcegraph/internal/database" - "github.com/sourcegraph/sourcegraph/internal/workerutil" -) - -type indexStepResolver struct { - db database.DB - index store.Index - entry *workerutil.ExecutionLogEntry -} - -var _ gql.IndexStepResolver = &indexStepResolver{} - -func (r *indexStepResolver) IndexerArgs() []string { return r.index.IndexerArgs } -func (r *indexStepResolver) Outfile() *string { return strPtr(r.index.Outfile) } - -func (r *indexStepResolver) LogEntry() gql.ExecutionLogEntryResolver { - if r.entry != nil { - return gql.NewExecutionLogEntryResolver(r.db, *r.entry) - } - - return nil -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_steps_preindex.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_steps_preindex.go deleted file mode 100644 index 42462a02123..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/index_steps_preindex.go +++ /dev/null @@ -1,28 +0,0 @@ -package graphql - -import ( - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - store "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - "github.com/sourcegraph/sourcegraph/internal/database" - "github.com/sourcegraph/sourcegraph/internal/workerutil" -) - -type preIndexStepResolver struct { - db database.DB - step store.DockerStep - entry *workerutil.ExecutionLogEntry -} - -var _ gql.PreIndexStepResolver = &preIndexStepResolver{} - -func (r *preIndexStepResolver) Root() string { return r.step.Root } -func (r *preIndexStepResolver) Image() string { return r.step.Image } -func (r *preIndexStepResolver) Commands() []string { return r.step.Commands } - -func (r *preIndexStepResolver) LogEntry() gql.ExecutionLogEntryResolver { - if r.entry != nil { - return gql.NewExecutionLogEntryResolver(r.db, *r.entry) - } - - return nil -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/location_connection.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/location_connection.go deleted file mode 100644 index d74f8b9892a..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/location_connection.go +++ /dev/null @@ -1,30 +0,0 @@ -package graphql - -import ( - "context" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" -) - -type LocationConnectionResolver struct { - locations []AdjustedLocation - cursor *string - locationResolver *CachedLocationResolver -} - -func NewLocationConnectionResolver(locations []AdjustedLocation, cursor *string, locationResolver *CachedLocationResolver) gql.LocationConnectionResolver { - return &LocationConnectionResolver{ - locations: locations, - cursor: cursor, - locationResolver: locationResolver, - } -} - -func (r *LocationConnectionResolver) Nodes(ctx context.Context) ([]gql.LocationResolver, error) { - return resolveLocations(ctx, r.locationResolver, r.locations) -} - -func (r *LocationConnectionResolver) PageInfo(ctx context.Context) (*graphqlutil.PageInfo, error) { - return graphqlutil.EncodeCursor(r.cursor), nil -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/observability.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/observability.go deleted file mode 100644 index 0fc72e545ea..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/observability.go +++ /dev/null @@ -1,77 +0,0 @@ -package graphql - -import ( - "fmt" - - "github.com/sourcegraph/sourcegraph/internal/observation" -) - -type operations struct { - commitGraph *observation.Operation - configurationPolicies *observation.Operation - configurationPolicyByID *observation.Operation - createConfigurationPolicy *observation.Operation - deleteConfigurationPolicy *observation.Operation - deleteLsifIndexes *observation.Operation - deleteLsifUpload *observation.Operation - gitBlobCodeIntelInfo *observation.Operation - gitBlobLsifData *observation.Operation - gitTreeCodeIntelInfo *observation.Operation - indexConfiguration *observation.Operation - lsifIndexByID *observation.Operation - lsifIndexes *observation.Operation - lsifIndexesByRepo *observation.Operation - lsifUploadByID *observation.Operation - lsifUploads *observation.Operation - lsifUploadsByRepo *observation.Operation - previewGitObjectFilter *observation.Operation - previewRepoFilter *observation.Operation - queueAutoIndexJobsForRepo *observation.Operation - repositorySummary *observation.Operation - requestedLanguageSupport *observation.Operation - requestLanguageSupport *observation.Operation - updateConfigurationPolicy *observation.Operation - updateIndexConfiguration *observation.Operation -} - -func newOperations(observationContext *observation.Context) *operations { - op := func(name string) *observation.Operation { - return observationContext.Operation(observation.Op{ - Name: fmt.Sprintf("codeintel.resolver.%s", name), - ErrorFilter: func(err error) observation.ErrorFilterBehaviour { - if err == ErrIllegalBounds || err == ErrIllegalLimit { - return observation.EmitForNone - } - return observation.EmitForLogs - }, - }) - } - - return &operations{ - commitGraph: op("CommitGraph"), - configurationPolicies: op("ConfigurationPolicies"), - configurationPolicyByID: op("ConfigurationPolicyByID"), - createConfigurationPolicy: op("CreateConfigurationPolicy"), - deleteConfigurationPolicy: op("DeleteConfigurationPolicy"), - deleteLsifIndexes: op("DeleteLSIFIndexes"), - deleteLsifUpload: op("DeleteLSIFUpload"), - gitBlobCodeIntelInfo: op("GitBlobCodeIntelInfo"), - gitBlobLsifData: op("GitBlobLSIFData"), - gitTreeCodeIntelInfo: op("GitTreeCodeIntelInfo"), - indexConfiguration: op("IndexConfiguration"), - lsifIndexByID: op("LSIFIndexByID"), - lsifIndexes: op("LSIFIndexes"), - lsifIndexesByRepo: op("LSIFIndexesByRepo"), - lsifUploadByID: op("LSIFUploadByID"), - lsifUploads: op("LSIFUploads"), - lsifUploadsByRepo: op("LSIFUploadsByRepo"), - previewGitObjectFilter: op("PreviewGitObjectFilter"), - previewRepoFilter: op("PreviewRepoFilter"), - queueAutoIndexJobsForRepo: op("QueueAutoIndexJobsForRepo"), - repositorySummary: op("RepositorySummary"), - requestedLanguageSupport: op("RequestedLanguageSupport"), - requestLanguageSupport: op("RequestLanguageSupport"), - updateConfigurationPolicy: op("UpdateConfigurationPolicy"), - updateIndexConfiguration: op("UpdateIndexConfiguration"), - } -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ranges.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ranges.go deleted file mode 100644 index 8cd44006184..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ranges.go +++ /dev/null @@ -1,32 +0,0 @@ -package graphql - -import ( - "context" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" -) - -type CodeIntelligenceRangeResolver struct { - r AdjustedCodeIntelligenceRange - locationResolver *CachedLocationResolver -} - -func (r *CodeIntelligenceRangeResolver) Range(ctx context.Context) (gql.RangeResolver, error) { - return gql.NewRangeResolver(convertRange(r.r.Range)), nil -} - -func (r *CodeIntelligenceRangeResolver) Definitions(ctx context.Context) (gql.LocationConnectionResolver, error) { - return NewLocationConnectionResolver(r.r.Definitions, nil, r.locationResolver), nil -} - -func (r *CodeIntelligenceRangeResolver) References(ctx context.Context) (gql.LocationConnectionResolver, error) { - return NewLocationConnectionResolver(r.r.References, nil, r.locationResolver), nil -} - -func (r *CodeIntelligenceRangeResolver) Implementations(ctx context.Context) (gql.LocationConnectionResolver, error) { - return NewLocationConnectionResolver(r.r.Implementations, nil, r.locationResolver), nil -} - -func (r *CodeIntelligenceRangeResolver) Hover(ctx context.Context) (gql.HoverResolver, error) { - return NewHoverResolver(r.r.HoverText, convertRange(r.r.Range)), nil -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ranges_connection.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ranges_connection.go deleted file mode 100644 index 5257a1ce1e1..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/ranges_connection.go +++ /dev/null @@ -1,24 +0,0 @@ -package graphql - -import ( - "context" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" -) - -type CodeIntelligenceRangeConnectionResolver struct { - ranges []AdjustedCodeIntelligenceRange - locationResolver *CachedLocationResolver -} - -func (r *CodeIntelligenceRangeConnectionResolver) Nodes(ctx context.Context) ([]gql.CodeIntelligenceRangeResolver, error) { - var resolvers []gql.CodeIntelligenceRangeResolver - for _, rn := range r.ranges { - resolvers = append(resolvers, &CodeIntelligenceRangeResolver{ - r: rn, - locationResolver: r.locationResolver, - }) - } - - return resolvers, nil -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/repository_filter_preview.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/repository_filter_preview.go deleted file mode 100644 index a31c6057dfc..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/repository_filter_preview.go +++ /dev/null @@ -1,41 +0,0 @@ -package graphql - -import ( - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" -) - -type repositoryFilterPreviewResolver struct { - repositoryResolvers []*gql.RepositoryResolver - totalCount int - offset int - totalMatches int - limit *int -} - -var _ gql.RepositoryFilterPreviewResolver = &repositoryFilterPreviewResolver{} - -func (r *repositoryFilterPreviewResolver) Nodes() []*gql.RepositoryResolver { - return r.repositoryResolvers -} - -func (r *repositoryFilterPreviewResolver) TotalCount() int32 { - return int32(r.totalCount) -} - -func (r *repositoryFilterPreviewResolver) TotalMatches() int32 { - return int32(r.totalMatches) -} - -func (r *repositoryFilterPreviewResolver) Limit() *int32 { - if r.limit == nil { - return nil - } - - v := int32(*r.limit) - return &v -} - -func (r *repositoryFilterPreviewResolver) PageInfo() *graphqlutil.PageInfo { - return graphqlutil.EncodeIntCursor(toInt32(graphqlutil.NextOffset(r.offset, len(r.repositoryResolvers), r.totalCount))) -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/resolver.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/resolver.go index aa66aed1862..0b932657af6 100644 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/resolver.go +++ b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/resolver.go @@ -2,67 +2,37 @@ package graphql import ( "context" - "sort" - "strings" - "time" - "github.com/grafana/regexp" "github.com/graph-gophers/graphql-go" - "github.com/opentracing/opentracing-go/log" - "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers" - "github.com/sourcegraph/sourcegraph/internal/api" - autoindexingShared "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" - "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" - uploadsShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" - "github.com/sourcegraph/sourcegraph/internal/conf" - "github.com/sourcegraph/sourcegraph/internal/database" - "github.com/sourcegraph/sourcegraph/internal/observation" + autoindexinggraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/transport/graphql" + codenavgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql" + policiesgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/transport/graphql" + sharedresolvers "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" + uploadsgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/transport/graphql" executor "github.com/sourcegraph/sourcegraph/internal/services/executors/transport/graphql" - "github.com/sourcegraph/sourcegraph/lib/errors" ) -const ( - DefaultUploadPageSize = 50 - DefaultIndexPageSize = 50 - DefaultConfigurationPolicyPageSize = 50 - DefaultRepositoryFilterPreviewPageSize = 50 - DefaultRetentionPolicyMatchesPageSize = 50 -) - -var errAutoIndexingNotEnabled = errors.New("precise code intelligence auto-indexing is not enabled") - // Resolver is the main interface to code intel-related operations exposed to the GraphQL API. This // resolver concerns itself with GraphQL/API-specific behaviors (auth, validation, marshaling, etc.). // All code intel-specific behavior is delegated to the underlying resolver instance, which is defined // in the parent package. type Resolver struct { - db database.DB - gitserver GitserverClient - resolver resolvers.Resolver - locationResolver *CachedLocationResolver - observationContext *operations + resolver resolvers.Resolver } // NewResolver creates a new Resolver with the given resolver that defines all code intel-specific behavior. -func NewResolver(db database.DB, gitserver GitserverClient, resolver resolvers.Resolver, observationContext *observation.Context) gql.CodeIntelResolver { +func NewResolver(resolver resolvers.Resolver) gql.CodeIntelResolver { baseResolver := &Resolver{ - db: db, - gitserver: gitserver, - resolver: resolver, - locationResolver: NewCachedLocationResolver(db), - observationContext: newOperations(observationContext), + resolver: resolver, } - return &frankenResolver{ - Resolver: baseResolver, - } + return baseResolver } -func (r *frankenResolver) NodeResolvers() map[string]gql.NodeByIDFunc { +func (r *Resolver) NodeResolvers() map[string]gql.NodeByIDFunc { return map[string]gql.NodeByIDFunc{ "LSIFUpload": func(ctx context.Context, id graphql.ID) (gql.Node, error) { return r.LSIFUploadByID(ctx, id) @@ -80,794 +50,120 @@ func (r *Resolver) ExecutorResolver() executor.Resolver { return r.resolver.ExecutorResolver() } -func (r *Resolver) CodeNavResolver() resolvers.CodeNavResolver { - return r.resolver.CodeNavResolver() -} - -func (r *Resolver) PoliciesResolver() resolvers.PoliciesResolver { - return r.resolver.PoliciesResolver() -} - -func (r *Resolver) AutoIndexingResolver() resolvers.AutoIndexingResolver { - return r.resolver.AutoIndexingResolver() -} - // 🚨 SECURITY: dbstore layer handles authz for GetUploadByID -func (r *Resolver) LSIFUploadByID(ctx context.Context, id graphql.ID) (_ gql.LSIFUploadResolver, err error) { - ctx, traceErrs, endObservation := r.observationContext.lsifUploadByID.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ - log.String("uploadID", string(id)), - }}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - uploadID, err := unmarshalLSIFUploadGQLID(id) - if err != nil { - return nil, err - } - - // Create a new prefetcher here as we only want to cache upload and index records in - // the same graphQL request, not across different request. - prefetcher := NewPrefetcher(r.resolver) - - upload, exists, err := prefetcher.GetUploadByID(ctx, int(uploadID)) - if err != nil || !exists { - return nil, err - } - - return NewUploadResolver(r.db, r.gitserver, r.resolver, upload, prefetcher, r.locationResolver, traceErrs), nil +func (r *Resolver) LSIFUploadByID(ctx context.Context, id graphql.ID) (_ sharedresolvers.LSIFUploadResolver, err error) { + return r.resolver.UploadRootResolver().LSIFUploadByID(ctx, id) } // 🚨 SECURITY: dbstore layer handles authz for GetUploads -func (r *Resolver) LSIFUploads(ctx context.Context, args *gql.LSIFUploadsQueryArgs) (_ gql.LSIFUploadConnectionResolver, err error) { - // ctx, _, endObservation := r.observationContext.lsifUploads.With(ctx, &err, observation.Args{}) - // endObservation.EndOnCancel(ctx, 1, observation.Args{}) - - // Delegate behavior to LSIFUploadsByRepo with no specified repository identifier - return r.LSIFUploadsByRepo(ctx, &gql.LSIFRepositoryUploadsQueryArgs{LSIFUploadsQueryArgs: args}) +func (r *Resolver) LSIFUploads(ctx context.Context, args *uploadsgraphql.LSIFUploadsQueryArgs) (_ sharedresolvers.LSIFUploadConnectionResolver, err error) { + return r.resolver.UploadRootResolver().LSIFUploads(ctx, args) } // 🚨 SECURITY: dbstore layer handles authz for GetUploads -func (r *Resolver) LSIFUploadsByRepo(ctx context.Context, args *gql.LSIFRepositoryUploadsQueryArgs) (_ gql.LSIFUploadConnectionResolver, err error) { - ctx, traceErrs, endObservation := r.observationContext.lsifUploadsByRepo.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ - log.String("repoID", string(args.RepositoryID)), - }}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - opts, err := makeGetUploadsOptions(args) - if err != nil { - return nil, err - } - - // Create a new prefetcher here as we only want to cache upload and index records in - // the same graphQL request, not across different request. - prefetcher := NewPrefetcher(r.resolver) - uploadConnectionResolver := r.resolver.UploadsResolver().UploadsConnectionResolverFromFactory(opts) - - return NewUploadConnectionResolver(r.db, r.gitserver, r.resolver, uploadConnectionResolver, prefetcher, r.locationResolver, traceErrs), nil +func (r *Resolver) LSIFUploadsByRepo(ctx context.Context, args *uploadsgraphql.LSIFRepositoryUploadsQueryArgs) (_ sharedresolvers.LSIFUploadConnectionResolver, err error) { + return r.resolver.UploadRootResolver().LSIFUploadsByRepo(ctx, args) } // 🚨 SECURITY: Only site admins may modify code intelligence upload data -func (r *Resolver) DeleteLSIFUpload(ctx context.Context, args *struct{ ID graphql.ID }) (_ *gql.EmptyResponse, err error) { - ctx, _, endObservation := r.observationContext.deleteLsifUpload.With(ctx, &err, observation.Args{LogFields: []log.Field{ - log.String("uploadID", string(args.ID)), - }}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.db); err != nil { - return nil, err - } - - uploadID, err := unmarshalLSIFUploadGQLID(args.ID) - if err != nil { - return nil, err - } - - if _, err := r.resolver.UploadsResolver().DeleteUploadByID(ctx, int(uploadID)); err != nil { - return nil, err - } - - return &gql.EmptyResponse{}, nil +func (r *Resolver) DeleteLSIFUpload(ctx context.Context, args *struct{ ID graphql.ID }) (_ *sharedresolvers.EmptyResponse, err error) { + return r.resolver.UploadRootResolver().DeleteLSIFUpload(ctx, args) } -var autoIndexingEnabled = conf.CodeIntelAutoIndexingEnabled - // 🚨 SECURITY: dbstore layer handles authz for GetIndexByID -func (r *Resolver) LSIFIndexByID(ctx context.Context, id graphql.ID) (_ gql.LSIFIndexResolver, err error) { - if !autoIndexingEnabled() { - return nil, errAutoIndexingNotEnabled - } - - ctx, traceErrs, endObservation := r.observationContext.lsifIndexByID.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ - log.String("indexID", string(id)), - }}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - indexID, err := unmarshalLSIFIndexGQLID(id) - if err != nil { - return nil, err - } - - // Create a new prefetcher here as we only want to cache upload and index records in - // the same graphQL request, not across different request. - prefetcher := NewPrefetcher(r.resolver) - - index, exists, err := prefetcher.GetIndexByID(ctx, int(indexID)) - if err != nil || !exists { - return nil, err - } - - return NewIndexResolver(r.db, r.gitserver, r.resolver, index, prefetcher, r.locationResolver, traceErrs), nil +func (r *Resolver) LSIFIndexByID(ctx context.Context, id graphql.ID) (_ sharedresolvers.LSIFIndexResolver, err error) { + return r.resolver.AutoIndexingRootResolver().LSIFIndexByID(ctx, id) } // 🚨 SECURITY: dbstore layer handles authz for GetIndexes -func (r *Resolver) LSIFIndexes(ctx context.Context, args *gql.LSIFIndexesQueryArgs) (_ gql.LSIFIndexConnectionResolver, err error) { - if !autoIndexingEnabled() { - return nil, errAutoIndexingNotEnabled - } - - ctx, _, endObservation := r.observationContext.lsifIndexes.With(ctx, &err, observation.Args{}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - // Delegate behavior to LSIFIndexesByRepo with no specified repository identifier - return r.LSIFIndexesByRepo(ctx, &gql.LSIFRepositoryIndexesQueryArgs{LSIFIndexesQueryArgs: args}) +func (r *Resolver) LSIFIndexes(ctx context.Context, args *autoindexinggraphql.LSIFIndexesQueryArgs) (_ sharedresolvers.LSIFIndexConnectionResolver, err error) { + return r.resolver.AutoIndexingRootResolver().LSIFIndexes(ctx, args) } // 🚨 SECURITY: dbstore layer handles authz for GetIndexes -func (r *Resolver) LSIFIndexesByRepo(ctx context.Context, args *gql.LSIFRepositoryIndexesQueryArgs) (_ gql.LSIFIndexConnectionResolver, err error) { - if !autoIndexingEnabled() { - return nil, errAutoIndexingNotEnabled - } - - ctx, traceErrs, endObservation := r.observationContext.lsifIndexesByRepo.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ - log.String("repoID", string(args.RepositoryID)), - }}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - opts, err := makeGetIndexesOptions(args) - if err != nil { - return nil, err - } - - // Create a new prefetcher here as we only want to cache upload and index records in - // the same graphQL request, not across different request. - prefetcher := NewPrefetcher(r.resolver) - - // Create a new indexConnectionResolver here as we only want to index records in - // the same graphQL request, not across different request. - indexConnectionResolver := r.resolver.AutoIndexingResolver().IndexConnectionResolverFromFactory(opts) - - return NewIndexConnectionResolver(r.db, r.gitserver, r.resolver, indexConnectionResolver, prefetcher, r.locationResolver, traceErrs), nil +func (r *Resolver) LSIFIndexesByRepo(ctx context.Context, args *autoindexinggraphql.LSIFRepositoryIndexesQueryArgs) (_ sharedresolvers.LSIFIndexConnectionResolver, err error) { + return r.resolver.AutoIndexingRootResolver().LSIFIndexesByRepo(ctx, args) } // 🚨 SECURITY: Only site admins may modify code intelligence index data -func (r *Resolver) DeleteLSIFIndex(ctx context.Context, args *struct{ ID graphql.ID }) (_ *gql.EmptyResponse, err error) { - ctx, _, endObservation := r.observationContext.deleteLsifIndexes.With(ctx, &err, observation.Args{LogFields: []log.Field{ - log.String("indexID", string(args.ID)), - }}) - defer endObservation(1, observation.Args{}) - - if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.db); err != nil { - return nil, err - } - if !autoIndexingEnabled() { - return nil, errAutoIndexingNotEnabled - } - - indexID, err := unmarshalLSIFIndexGQLID(args.ID) - if err != nil { - return nil, err - } - - autoIndexingResolver := r.resolver.AutoIndexingResolver() - if err := autoIndexingResolver.DeleteIndexByID(ctx, int(indexID)); err != nil { - return nil, err - } - - return &gql.EmptyResponse{}, nil +func (r *Resolver) DeleteLSIFIndex(ctx context.Context, args *struct{ ID graphql.ID }) (_ *sharedresolvers.EmptyResponse, err error) { + return r.resolver.AutoIndexingRootResolver().DeleteLSIFIndex(ctx, args) } // 🚨 SECURITY: Only entrypoint is within the repository resolver so the user is already authenticated -func (r *Resolver) CommitGraph(ctx context.Context, id graphql.ID) (_ gql.CodeIntelligenceCommitGraphResolver, err error) { - ctx, _, endObservation := r.observationContext.commitGraph.With(ctx, &err, observation.Args{LogFields: []log.Field{ - log.String("repoID", string(id)), - }}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - repositoryID, err := gql.UnmarshalRepositoryID(id) - if err != nil { - return nil, err - } - - commitGraphResolver := r.resolver.UploadsResolver().CommitGraphResolverFromFactory(ctx, int(repositoryID)) - - return commitGraphResolver, nil +func (r *Resolver) CommitGraph(ctx context.Context, id graphql.ID) (_ uploadsgraphql.CodeIntelligenceCommitGraphResolver, err error) { + return r.resolver.UploadRootResolver().CommitGraph(ctx, id) } // 🚨 SECURITY: Only site admins may queue auto-index jobs -func (r *Resolver) QueueAutoIndexJobsForRepo(ctx context.Context, args *gql.QueueAutoIndexJobsForRepoArgs) (_ []gql.LSIFIndexResolver, err error) { - ctx, traceErrs, endObservation := r.observationContext.queueAutoIndexJobsForRepo.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ - log.String("repoID", string(args.Repository)), - }}) - endObservation.OnCancel(ctx, 1, observation.Args{}) +func (r *Resolver) QueueAutoIndexJobsForRepo(ctx context.Context, args *autoindexinggraphql.QueueAutoIndexJobsForRepoArgs) (_ []sharedresolvers.LSIFIndexResolver, err error) { + return r.resolver.AutoIndexingRootResolver().QueueAutoIndexJobsForRepo(ctx, args) +} - if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.db); err != nil { - return nil, err - } - if !autoIndexingEnabled() { - return nil, errAutoIndexingNotEnabled - } +func (r *Resolver) RequestLanguageSupport(ctx context.Context, args *autoindexinggraphql.RequestLanguageSupportArgs) (_ *sharedresolvers.EmptyResponse, err error) { + return r.resolver.AutoIndexingRootResolver().RequestLanguageSupport(ctx, args) +} - repositoryID, err := gql.UnmarshalRepositoryID(args.Repository) - if err != nil { - return nil, err - } - - rev := "HEAD" - if args.Rev != nil { - rev = *args.Rev - } - - configuration := "" - if args.Configuration != nil { - configuration = *args.Configuration - } - - autoindexingResolver := r.resolver.AutoIndexingResolver() - indexes, err := autoindexingResolver.QueueAutoIndexJobsForRepo(ctx, int(repositoryID), rev, configuration) - if err != nil { - return nil, err - } - - // Create a new prefetcher here as we only want to cache upload and index records in - // the same graphQL request, not across different request. - prefetcher := NewPrefetcher(r.resolver) - - resolvers := make([]gql.LSIFIndexResolver, 0, len(indexes)) - for i := range indexes { - index := convertSharedIndexToDBStoreIndex(indexes[i]) - resolvers = append(resolvers, NewIndexResolver(r.db, r.gitserver, r.resolver, index, prefetcher, r.locationResolver, traceErrs)) - } - return resolvers, nil +func (r *Resolver) RequestedLanguageSupport(ctx context.Context) (_ []string, err error) { + return r.resolver.AutoIndexingRootResolver().RequestedLanguageSupport(ctx) } // 🚨 SECURITY: dbstore layer handles authz for query resolution -func (r *Resolver) GitBlobLSIFData(ctx context.Context, args *gql.GitBlobLSIFDataArgs) (_ gql.GitBlobLSIFDataResolver, err error) { - ctx, errTracer, endObservation := r.observationContext.gitBlobLsifData.WithErrors(ctx, &err, observation.Args{}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - codenav := r.resolver.CodeNavResolver() - gitBlobResolver, err := codenav.GitBlobLSIFDataResolverFactory(ctx, args.Repo, string(args.Commit), args.Path, args.ToolName, args.ExactPath) - if err != nil || gitBlobResolver == nil { - return nil, err - } - - return NewQueryResolver(r.gitserver, gitBlobResolver, r.resolver, r.locationResolver, errTracer), nil +func (r *Resolver) GitBlobLSIFData(ctx context.Context, args *codenavgraphql.GitBlobLSIFDataArgs) (_ codenavgraphql.GitBlobLSIFDataResolver, err error) { + return r.resolver.CodeNavResolver().GitBlobLSIFData(ctx, args) } -func (r *Resolver) GitBlobCodeIntelInfo(ctx context.Context, args *gql.GitTreeEntryCodeIntelInfoArgs) (_ gql.GitBlobCodeIntelSupportResolver, err error) { - ctx, errTracer, endObservation := r.observationContext.gitBlobCodeIntelInfo.WithErrors(ctx, &err, observation.Args{}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - return NewCodeIntelSupportResolver(r.resolver, args.Repo.Name, args.Path, errTracer), nil +func (r *Resolver) GitBlobCodeIntelInfo(ctx context.Context, args *autoindexinggraphql.GitTreeEntryCodeIntelInfoArgs) (_ autoindexinggraphql.GitBlobCodeIntelSupportResolver, err error) { + return r.resolver.AutoIndexingRootResolver().GitBlobCodeIntelInfo(ctx, args) } -func (r *Resolver) GitTreeCodeIntelInfo(ctx context.Context, args *gql.GitTreeEntryCodeIntelInfoArgs) (resolver gql.GitTreeCodeIntelSupportResolver, err error) { - ctx, errTracer, endObservation := r.observationContext.gitBlobCodeIntelInfo.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ - log.Int("repoID", int(args.Repo.ID)), - log.String("path", args.Path), - log.String("commit", args.Commit), - }}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - filesRegex, err := regexp.Compile("^" + regexp.QuoteMeta(args.Path) + "[^.]{1}[^/]*$") - if err != nil { - return nil, errors.Wrapf(err, "path '%s' caused invalid regex", args.Path) - } - - files, err := r.gitserver.ListFiles(ctx, int(args.Repo.ID), args.Commit, filesRegex) - if err != nil { - return nil, errors.Wrapf(err, "gitserver.ListFiles: error listing files at %s for repo %d", args.Path, args.Repo.ID) - } - - return NewCodeIntelTreeInfoResolver(r.resolver, args.Repo, args.Commit, args.Path, files, errTracer), nil +func (r *Resolver) GitTreeCodeIntelInfo(ctx context.Context, args *autoindexinggraphql.GitTreeEntryCodeIntelInfoArgs) (resolver autoindexinggraphql.GitTreeCodeIntelSupportResolver, err error) { + return r.resolver.AutoIndexingRootResolver().GitTreeCodeIntelInfo(ctx, args) } // 🚨 SECURITY: dbstore layer handles authz for GetConfigurationPolicyByID -func (r *Resolver) ConfigurationPolicyByID(ctx context.Context, id graphql.ID) (_ gql.CodeIntelligenceConfigurationPolicyResolver, err error) { - ctx, traceErrs, endObservation := r.observationContext.configurationPolicyByID.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ - log.String("configPolicyID", string(id)), - }}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - configurationPolicyID, err := unmarshalConfigurationPolicyGQLID(id) - if err != nil { - return nil, err - } - - policyResolver, err := r.resolver.PoliciesResolver().PolicyResolverFactory(ctx) - if err != nil { - return nil, err - } - configurationPolicy, exists, err := policyResolver.GetConfigurationPolicyByID(ctx, int(configurationPolicyID)) - if err != nil || !exists { - return nil, err - } - cp := sharedConfigurationPoliciesToStoreConfigurationPolicies(configurationPolicy) - - return NewConfigurationPolicyResolver(r.db, cp, traceErrs), nil +func (r *Resolver) ConfigurationPolicyByID(ctx context.Context, id graphql.ID) (_ policiesgraphql.CodeIntelligenceConfigurationPolicyResolver, err error) { + return r.resolver.PoliciesRootResolver().ConfigurationPolicyByID(ctx, id) } // 🚨 SECURITY: dbstore layer handles authz for GetConfigurationPolicies -func (r *Resolver) CodeIntelligenceConfigurationPolicies(ctx context.Context, args *gql.CodeIntelligenceConfigurationPoliciesArgs) (_ gql.CodeIntelligenceConfigurationPolicyConnectionResolver, err error) { - fields := []log.Field{} - if args.Repository != nil { - fields = append(fields, log.String("repoID", string(*args.Repository))) - } - ctx, traceErrs, endObservation := r.observationContext.configurationPolicies.WithErrors(ctx, &err, observation.Args{LogFields: fields}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - offset, err := graphqlutil.DecodeIntCursor(args.After) - if err != nil { - return nil, err - } - - pageSize := DefaultConfigurationPolicyPageSize - if args.First != nil { - pageSize = int(*args.First) - } - - opts := shared.GetConfigurationPoliciesOptions{ - Limit: pageSize, - Offset: offset, - } - if args.Repository != nil { - id64, err := unmarshalRepositoryID(*args.Repository) - if err != nil { - return nil, err - } - opts.RepositoryID = int(id64) - } - if args.Query != nil { - opts.Term = *args.Query - } - if args.ForDataRetention != nil { - opts.ForDataRetention = *args.ForDataRetention - } - if args.ForIndexing != nil { - opts.ForIndexing = *args.ForIndexing - } - - policyResolver, err := r.resolver.PoliciesResolver().PolicyResolverFactory(ctx) - if err != nil { - return nil, err - } - policies, totalCount, err := policyResolver.GetConfigurationPolicies(ctx, opts) - if err != nil { - return nil, err - } - - p := sharedConfigurationPoliciesListToStoreConfigurationPoliciesList(policies) - return NewCodeIntelligenceConfigurationPolicyConnectionResolver(r.db, p, totalCount, traceErrs), nil +func (r *Resolver) CodeIntelligenceConfigurationPolicies(ctx context.Context, args *policiesgraphql.CodeIntelligenceConfigurationPoliciesArgs) (_ policiesgraphql.CodeIntelligenceConfigurationPolicyConnectionResolver, err error) { + return r.resolver.PoliciesRootResolver().CodeIntelligenceConfigurationPolicies(ctx, args) } // 🚨 SECURITY: Only site admins may modify code intelligence configuration policies -func (r *Resolver) CreateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *gql.CreateCodeIntelligenceConfigurationPolicyArgs) (_ gql.CodeIntelligenceConfigurationPolicyResolver, err error) { - ctx, traceErrs, endObservation := r.observationContext.createConfigurationPolicy.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{}}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.db); err != nil { - return nil, err - } - - if err := validateConfigurationPolicy(args.CodeIntelConfigurationPolicy); err != nil { - return nil, err - } - - var repositoryID *int - if args.Repository != nil { - id64, err := unmarshalRepositoryID(*args.Repository) - if err != nil { - return nil, err - } - - id := int(id64) - repositoryID = &id - } - - policyResolver, err := r.resolver.PoliciesResolver().PolicyResolverFactory(ctx) - if err != nil { - return nil, err - } - - opts := shared.ConfigurationPolicy{ - RepositoryID: repositoryID, - Name: args.Name, - RepositoryPatterns: args.RepositoryPatterns, - Type: shared.GitObjectType(args.Type), - Pattern: args.Pattern, - RetentionEnabled: args.RetentionEnabled, - RetentionDuration: toDuration(args.RetentionDurationHours), - RetainIntermediateCommits: args.RetainIntermediateCommits, - IndexingEnabled: args.IndexingEnabled, - IndexCommitMaxAge: toDuration(args.IndexCommitMaxAgeHours), - IndexIntermediateCommits: args.IndexIntermediateCommits, - } - configurationPolicy, err := policyResolver.CreateConfigurationPolicy(ctx, opts) - if err != nil { - return nil, err - } - - cp := sharedConfigurationPoliciesToStoreConfigurationPolicies(configurationPolicy) - return NewConfigurationPolicyResolver(r.db, cp, traceErrs), nil +func (r *Resolver) CreateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *policiesgraphql.CreateCodeIntelligenceConfigurationPolicyArgs) (_ policiesgraphql.CodeIntelligenceConfigurationPolicyResolver, err error) { + return r.resolver.PoliciesRootResolver().CreateCodeIntelligenceConfigurationPolicy(ctx, args) } // 🚨 SECURITY: Only site admins may modify code intelligence configuration policies -func (r *Resolver) UpdateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *gql.UpdateCodeIntelligenceConfigurationPolicyArgs) (_ *gql.EmptyResponse, err error) { - ctx, _, endObservation := r.observationContext.updateConfigurationPolicy.With(ctx, &err, observation.Args{LogFields: []log.Field{ - log.String("configPolicyID", string(args.ID)), - }}) - defer endObservation(1, observation.Args{}) - - if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.db); err != nil { - return nil, err - } - - if err := validateConfigurationPolicy(args.CodeIntelConfigurationPolicy); err != nil { - return nil, err - } - - id, err := unmarshalConfigurationPolicyGQLID(args.ID) - if err != nil { - return nil, err - } - - policyResolver, err := r.resolver.PoliciesResolver().PolicyResolverFactory(ctx) - if err != nil { - return nil, err - } - opts := shared.ConfigurationPolicy{ - ID: int(id), - Name: args.Name, - RepositoryPatterns: args.RepositoryPatterns, - Type: shared.GitObjectType(args.Type), - Pattern: args.Pattern, - RetentionEnabled: args.RetentionEnabled, - RetentionDuration: toDuration(args.RetentionDurationHours), - RetainIntermediateCommits: args.RetainIntermediateCommits, - IndexingEnabled: args.IndexingEnabled, - IndexCommitMaxAge: toDuration(args.IndexCommitMaxAgeHours), - IndexIntermediateCommits: args.IndexIntermediateCommits, - } - if err := policyResolver.UpdateConfigurationPolicy(ctx, opts); err != nil { - return nil, err - } - - return &gql.EmptyResponse{}, nil +func (r *Resolver) UpdateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *policiesgraphql.UpdateCodeIntelligenceConfigurationPolicyArgs) (_ *sharedresolvers.EmptyResponse, err error) { + return r.resolver.PoliciesRootResolver().UpdateCodeIntelligenceConfigurationPolicy(ctx, args) } // 🚨 SECURITY: Only site admins may modify code intelligence configuration policies -func (r *Resolver) DeleteCodeIntelligenceConfigurationPolicy(ctx context.Context, args *gql.DeleteCodeIntelligenceConfigurationPolicyArgs) (_ *gql.EmptyResponse, err error) { - ctx, _, endObservation := r.observationContext.deleteConfigurationPolicy.With(ctx, &err, observation.Args{LogFields: []log.Field{ - log.String("configPolicyID", string(args.Policy)), - }}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.db); err != nil { - return nil, err - } - - id, err := unmarshalConfigurationPolicyGQLID(args.Policy) - if err != nil { - return nil, err - } - - policyResolver, err := r.resolver.PoliciesResolver().PolicyResolverFactory(ctx) - if err != nil { - return nil, err - } - if err := policyResolver.DeleteConfigurationPolicyByID(ctx, int(id)); err != nil { - return nil, err - } - - return &gql.EmptyResponse{}, nil +func (r *Resolver) DeleteCodeIntelligenceConfigurationPolicy(ctx context.Context, args *policiesgraphql.DeleteCodeIntelligenceConfigurationPolicyArgs) (_ *sharedresolvers.EmptyResponse, err error) { + return r.resolver.PoliciesRootResolver().DeleteCodeIntelligenceConfigurationPolicy(ctx, args) } -func (r *Resolver) RepositorySummary(ctx context.Context, id graphql.ID) (_ gql.CodeIntelRepositorySummaryResolver, err error) { - ctx, errTracer, endObservation := r.observationContext.repositorySummary.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ - log.String("repoID", string(id)), - }}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - repositoryID, err := gql.UnmarshalRepositoryID(id) - if err != nil { - return nil, err - } - repoID := int(repositoryID) - - uploadResolver := r.resolver.UploadsResolver() - recentUploads, err := uploadResolver.GetRecentUploadsSummary(ctx, repoID) - if err != nil { - return nil, err - } - - lastUploadRetentionScan, err := uploadResolver.GetLastUploadRetentionScanForRepository(ctx, repoID) - if err != nil { - return nil, err - } - - autoindexingResolver := r.resolver.AutoIndexingResolver() - recentIndexes, err := autoindexingResolver.GetRecentIndexesSummary(ctx, repoID) - if err != nil { - return nil, err - } - - lastIndexScan, err := autoindexingResolver.GetLastIndexScanForRepository(ctx, repoID) - if err != nil { - return nil, err - } - - summary := RepositorySummary{ - RecentUploads: recentUploads, - RecentIndexes: recentIndexes, - LastUploadRetentionScan: lastUploadRetentionScan, - LastIndexScan: lastIndexScan, - } - - // Create a new prefetcher here as we only want to cache upload and index records in - // the same graphQL request, not across different request. - prefetcher := NewPrefetcher(r.resolver) - - return NewRepositorySummaryResolver( - r.db, - r.resolver, - r.gitserver, - summary, - prefetcher, - r.locationResolver, - errTracer, - ), nil +func (r *Resolver) RepositorySummary(ctx context.Context, id graphql.ID) (_ sharedresolvers.CodeIntelRepositorySummaryResolver, err error) { + return r.resolver.AutoIndexingRootResolver().RepositorySummary(ctx, id) } // 🚨 SECURITY: Only entrypoint is within the repository resolver so the user is already authenticated -func (r *Resolver) IndexConfiguration(ctx context.Context, id graphql.ID) (_ gql.IndexConfigurationResolver, err error) { - _, traceErrs, endObservation := r.observationContext.indexConfiguration.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ - log.String("repoID", string(id)), - }}) - endObservation.OnCancel(ctx, 1, observation.Args{}) - - if !autoIndexingEnabled() { - return nil, errAutoIndexingNotEnabled - } - - repositoryID, err := gql.UnmarshalRepositoryID(id) - if err != nil { - return nil, err - } - - return NewIndexConfigurationResolver(r.resolver, int(repositoryID), traceErrs), nil +func (r *Resolver) IndexConfiguration(ctx context.Context, id graphql.ID) (_ autoindexinggraphql.IndexConfigurationResolver, err error) { + return r.resolver.AutoIndexingRootResolver().IndexConfiguration(ctx, id) } // 🚨 SECURITY: Only site admins may modify code intelligence indexing configuration -func (r *Resolver) UpdateRepositoryIndexConfiguration(ctx context.Context, args *gql.UpdateRepositoryIndexConfigurationArgs) (_ *gql.EmptyResponse, err error) { - ctx, _, endObservation := r.observationContext.updateIndexConfiguration.With(ctx, &err, observation.Args{LogFields: []log.Field{ - log.String("repoID", string(args.Repository)), - }}) - defer endObservation(1, observation.Args{}) - - if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.db); err != nil { - return nil, err - } - if !autoIndexingEnabled() { - return nil, errAutoIndexingNotEnabled - } - - repositoryID, err := unmarshalLSIFIndexGQLID(args.Repository) - if err != nil { - return nil, err - } - autoIndexingResolver := r.resolver.AutoIndexingResolver() - if err := autoIndexingResolver.UpdateIndexConfigurationByRepositoryID(ctx, int(repositoryID), args.Configuration); err != nil { - return nil, err - } - - return &gql.EmptyResponse{}, nil +func (r *Resolver) UpdateRepositoryIndexConfiguration(ctx context.Context, args *autoindexinggraphql.UpdateRepositoryIndexConfigurationArgs) (_ *sharedresolvers.EmptyResponse, err error) { + return r.resolver.AutoIndexingRootResolver().UpdateRepositoryIndexConfiguration(ctx, args) } -func (r *Resolver) PreviewRepositoryFilter(ctx context.Context, args *gql.PreviewRepositoryFilterArgs) (_ gql.RepositoryFilterPreviewResolver, err error) { - ctx, _, endObservation := r.observationContext.previewRepoFilter.With(ctx, &err, observation.Args{}) - defer endObservation(1, observation.Args{}) - - offset, err := graphqlutil.DecodeIntCursor(args.After) - if err != nil { - return nil, err - } - - pageSize := DefaultRepositoryFilterPreviewPageSize - if args.First != nil { - pageSize = int(*args.First) - } - - policyResolver, err := r.resolver.PoliciesResolver().PolicyResolverFactory(ctx) - if err != nil { - return nil, err - } - - ids, totalCount, repositoryMatchLimit, err := policyResolver.GetPreviewRepositoryFilter(ctx, args.Patterns, pageSize, offset) - if err != nil { - return nil, err - } - - resv := make([]*gql.RepositoryResolver, 0, len(ids)) - for _, id := range ids { - repo, err := backend.NewRepos(r.locationResolver.logger, r.db).Get(ctx, api.RepoID(id)) - if err != nil { - return nil, err - } - - resv = append(resv, gql.NewRepositoryResolver(r.db, repo)) - } - - limitedCount := totalCount - if repositoryMatchLimit != nil && *repositoryMatchLimit < limitedCount { - limitedCount = *repositoryMatchLimit - } - - return &repositoryFilterPreviewResolver{ - repositoryResolvers: resv, - totalCount: limitedCount, - offset: offset, - totalMatches: totalCount, - limit: repositoryMatchLimit, - }, nil +func (r *Resolver) PreviewRepositoryFilter(ctx context.Context, args *policiesgraphql.PreviewRepositoryFilterArgs) (_ policiesgraphql.RepositoryFilterPreviewResolver, err error) { + return r.resolver.PoliciesRootResolver().PreviewRepositoryFilter(ctx, args) } -func (r *Resolver) PreviewGitObjectFilter(ctx context.Context, id graphql.ID, args *gql.PreviewGitObjectFilterArgs) (_ []gql.GitObjectFilterPreviewResolver, err error) { - ctx, _, endObservation := r.observationContext.previewGitObjectFilter.With(ctx, &err, observation.Args{}) - defer endObservation(1, observation.Args{}) - - repositoryID, err := unmarshalLSIFIndexGQLID(id) - if err != nil { - return nil, err - } - - policyResolver, err := r.resolver.PoliciesResolver().PolicyResolverFactory(ctx) - if err != nil { - return nil, err - } - - namesByRev, err := policyResolver.GetPreviewGitObjectFilter(ctx, int(repositoryID), shared.GitObjectType(args.Type), args.Pattern) - if err != nil { - return nil, err - } - - var previews []gql.GitObjectFilterPreviewResolver - for rev, names := range namesByRev { - for _, name := range names { - previews = append(previews, &gitObjectFilterPreviewResolver{ - name: name, - rev: rev, - }) - } - } - - sort.Slice(previews, func(i, j int) bool { - return previews[i].Name() < previews[j].Name() || (previews[i].Name() == previews[j].Name() && previews[i].Rev() < previews[j].Rev()) - }) - - return previews, nil -} - -// makeGetUploadsOptions translates the given GraphQL arguments into options defined by the -// store.GetUploads operations. -func makeGetUploadsOptions(args *gql.LSIFRepositoryUploadsQueryArgs) (uploadsShared.GetUploadsOptions, error) { - repositoryID, err := resolveRepositoryID(args.RepositoryID) - if err != nil { - return uploadsShared.GetUploadsOptions{}, err - } - - var dependencyOf int64 - if args.DependencyOf != nil { - dependencyOf, err = unmarshalLSIFUploadGQLID(*args.DependencyOf) - if err != nil { - return uploadsShared.GetUploadsOptions{}, err - } - } - - var dependentOf int64 - if args.DependentOf != nil { - dependentOf, err = unmarshalLSIFUploadGQLID(*args.DependentOf) - if err != nil { - return uploadsShared.GetUploadsOptions{}, err - } - } - - offset, err := graphqlutil.DecodeIntCursor(args.After) - if err != nil { - return uploadsShared.GetUploadsOptions{}, err - } - - return uploadsShared.GetUploadsOptions{ - RepositoryID: repositoryID, - State: strings.ToLower(derefString(args.State, "")), - Term: derefString(args.Query, ""), - VisibleAtTip: derefBool(args.IsLatestForRepo, false), - DependencyOf: int(dependencyOf), - DependentOf: int(dependentOf), - Limit: derefInt32(args.First, DefaultUploadPageSize), - Offset: offset, - AllowExpired: true, - AllowDeletedUpload: derefBool(args.IncludeDeleted, false), - }, nil -} - -// makeGetIndexesOptions translates the given GraphQL arguments into options defined by the -// store.GetIndexes operations. -func makeGetIndexesOptions(args *gql.LSIFRepositoryIndexesQueryArgs) (autoindexingShared.GetIndexesOptions, error) { - repositoryID, err := resolveRepositoryID(args.RepositoryID) - if err != nil { - return autoindexingShared.GetIndexesOptions{}, err - } - - offset, err := graphqlutil.DecodeIntCursor(args.After) - if err != nil { - return autoindexingShared.GetIndexesOptions{}, err - } - - return autoindexingShared.GetIndexesOptions{ - RepositoryID: repositoryID, - State: strings.ToLower(derefString(args.State, "")), - Term: derefString(args.Query, ""), - Limit: derefInt32(args.First, DefaultIndexPageSize), - Offset: offset, - }, nil -} - -// resolveRepositoryByID gets a repository's internal identifier from a GraphQL identifier. -func resolveRepositoryID(id graphql.ID) (int, error) { - if id == "" { - return 0, nil - } - - repoID, err := gql.UnmarshalRepositoryID(id) - if err != nil { - return 0, err - } - - return int(repoID), nil -} - -func validateConfigurationPolicy(policy gql.CodeIntelConfigurationPolicy) error { - switch policy.Type { - case gql.GitObjectTypeCommit: - case gql.GitObjectTypeTag: - case gql.GitObjectTypeTree: - default: - return errors.Errorf("illegal git object type '%s', expected 'GIT_COMMIT', 'GIT_TAG', or 'GIT_TREE'", policy.Type) - } - - if policy.Name == "" { - return errors.Errorf("no name supplied") - } - if policy.Pattern == "" { - return errors.Errorf("no pattern supplied") - } - if policy.Type == gql.GitObjectTypeCommit && policy.Pattern != "HEAD" { - return errors.Errorf("pattern must be HEAD for policy type 'GIT_COMMIT'") - } - if policy.RetentionDurationHours != nil && *policy.RetentionDurationHours <= 0 { - return errors.Errorf("illegal retention duration '%d'", *policy.RetentionDurationHours) - } - if policy.IndexCommitMaxAgeHours != nil && *policy.IndexCommitMaxAgeHours <= 0 { - return errors.Errorf("illegal index commit max age '%d'", *policy.IndexCommitMaxAgeHours) - } - - return nil -} - -func toDuration(hours *int32) *time.Duration { - if hours == nil { - return nil - } - - v := time.Duration(*hours) * time.Hour - return &v +func (r *Resolver) PreviewGitObjectFilter(ctx context.Context, id graphql.ID, args *policiesgraphql.PreviewGitObjectFilterArgs) (_ []policiesgraphql.GitObjectFilterPreviewResolver, err error) { + return r.resolver.PoliciesRootResolver().PreviewGitObjectFilter(ctx, id, args) } diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/resolver_test.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/resolver_test.go deleted file mode 100644 index bd41dc30a73..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/resolver_test.go +++ /dev/null @@ -1,201 +0,0 @@ -package graphql - -import ( - "context" - "encoding/base64" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/graph-gophers/graphql-go" - - "github.com/sourcegraph/log/logtest" - - "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" - resolvermocks "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks" - transportmocks "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport" - uploadmocks "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/uploads" - autoindexingShared "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" - uploadsShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" - "github.com/sourcegraph/sourcegraph/internal/database" - "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/internal/types" -) - -func init() { - autoIndexingEnabled = func() bool { return true } -} - -func TestDeleteLSIFUpload(t *testing.T) { - users := database.NewStrictMockUserStore() - users.GetByCurrentAuthUserFunc.SetDefaultReturn(&types.User{SiteAdmin: true}, nil) - - db := database.NewMockDB() - db.UsersFunc.SetDefaultReturn(users) - - id := graphql.ID(base64.StdEncoding.EncodeToString([]byte("LSIFUpload:42"))) - mockUploadResolver := uploadmocks.NewMockResolver() - mockResolver := resolvermocks.NewMockResolver() - mockResolver.UploadsResolverFunc.SetDefaultReturn(mockUploadResolver) - - if _, err := NewResolver(db, nil, mockResolver, &observation.TestContext).DeleteLSIFUpload(context.Background(), &struct{ ID graphql.ID }{id}); err != nil { - t.Fatalf("unexpected error: %s", err) - } - - if len(mockUploadResolver.DeleteUploadByIDFunc.History()) != 1 { - t.Fatalf("unexpected call count. want=%d have=%d", 1, len(mockUploadResolver.DeleteUploadByIDFunc.History())) - } - if val := mockUploadResolver.DeleteUploadByIDFunc.History()[0].Arg1; val != 42 { - t.Fatalf("unexpected upload id. want=%d have=%d", 42, val) - } -} - -func TestDeleteLSIFUploadUnauthenticated(t *testing.T) { - logger := logtest.Scoped(t) - db := database.NewDB(logger, nil) - - id := graphql.ID(base64.StdEncoding.EncodeToString([]byte("LSIFUpload:42"))) - mockResolver := resolvermocks.NewMockResolver() - - if _, err := NewResolver(db, nil, mockResolver, &observation.TestContext).DeleteLSIFUpload(context.Background(), &struct{ ID graphql.ID }{id}); err != backend.ErrNotAuthenticated { - t.Errorf("unexpected error. want=%q have=%q", backend.ErrNotAuthenticated, err) - } -} - -func TestDeleteLSIFIndex(t *testing.T) { - users := database.NewStrictMockUserStore() - users.GetByCurrentAuthUserFunc.SetDefaultReturn(&types.User{SiteAdmin: true}, nil) - - db := database.NewStrictMockDB() - db.UsersFunc.SetDefaultReturn(users) - - id := graphql.ID(base64.StdEncoding.EncodeToString([]byte("LSIFIndex:42"))) - mockResolver := resolvermocks.NewMockResolver() - mockAutoIndexingResolver := transportmocks.NewMockResolver() - mockResolver.AutoIndexingResolverFunc.PushReturn(mockAutoIndexingResolver) - - if _, err := NewResolver(db, nil, mockResolver, &observation.TestContext).DeleteLSIFIndex(context.Background(), &struct{ ID graphql.ID }{id}); err != nil { - t.Fatalf("unexpected error: %s", err) - } - - if len(mockAutoIndexingResolver.DeleteIndexByIDFunc.History()) != 1 { - t.Fatalf("unexpected call count. want=%d have=%d", 1, len(mockAutoIndexingResolver.DeleteIndexByIDFunc.History())) - } - if val := mockAutoIndexingResolver.DeleteIndexByIDFunc.History()[0].Arg1; val != 42 { - t.Fatalf("unexpected index id. want=%d have=%d", 42, val) - } -} - -func TestDeleteLSIFIndexUnauthenticated(t *testing.T) { - logger := logtest.Scoped(t) - db := database.NewDB(logger, nil) - - id := graphql.ID(base64.StdEncoding.EncodeToString([]byte("LSIFIndex:42"))) - mockResolver := resolvermocks.NewMockResolver() - - if _, err := NewResolver(db, nil, mockResolver, &observation.TestContext).DeleteLSIFIndex(context.Background(), &struct{ ID graphql.ID }{id}); err != backend.ErrNotAuthenticated { - t.Errorf("unexpected error. want=%q have=%q", backend.ErrNotAuthenticated, err) - } -} - -func TestMakeGetUploadsOptions(t *testing.T) { - opts, err := makeGetUploadsOptions(&gql.LSIFRepositoryUploadsQueryArgs{ - LSIFUploadsQueryArgs: &gql.LSIFUploadsQueryArgs{ - ConnectionArgs: graphqlutil.ConnectionArgs{ - First: intPtr(5), - }, - Query: strPtr("q"), - State: strPtr("s"), - IsLatestForRepo: boolPtr(true), - After: graphqlutil.EncodeIntCursor(intPtr(25)).EndCursor(), - }, - RepositoryID: graphql.ID(base64.StdEncoding.EncodeToString([]byte("Repo:50"))), - }) - if err != nil { - t.Fatalf("unexpected error making options: %s", err) - } - - expected := uploadsShared.GetUploadsOptions{ - RepositoryID: 50, - State: "s", - Term: "q", - VisibleAtTip: true, - Limit: 5, - Offset: 25, - AllowExpired: true, - } - if diff := cmp.Diff(expected, opts); diff != "" { - t.Errorf("unexpected opts (-want +got):\n%s", diff) - } -} - -func TestMakeGetUploadsOptionsDefaults(t *testing.T) { - opts, err := makeGetUploadsOptions(&gql.LSIFRepositoryUploadsQueryArgs{ - LSIFUploadsQueryArgs: &gql.LSIFUploadsQueryArgs{}, - }) - if err != nil { - t.Fatalf("unexpected error making options: %s", err) - } - - expected := uploadsShared.GetUploadsOptions{ - RepositoryID: 0, - State: "", - Term: "", - VisibleAtTip: false, - Limit: DefaultUploadPageSize, - Offset: 0, - AllowExpired: true, - } - if diff := cmp.Diff(expected, opts); diff != "" { - t.Errorf("unexpected opts (-want +got):\n%s", diff) - } -} - -func TestMakeGetIndexesOptions(t *testing.T) { - opts, err := makeGetIndexesOptions(&gql.LSIFRepositoryIndexesQueryArgs{ - LSIFIndexesQueryArgs: &gql.LSIFIndexesQueryArgs{ - ConnectionArgs: graphqlutil.ConnectionArgs{ - First: intPtr(5), - }, - Query: strPtr("q"), - State: strPtr("s"), - After: graphqlutil.EncodeIntCursor(intPtr(25)).EndCursor(), - }, - RepositoryID: graphql.ID(base64.StdEncoding.EncodeToString([]byte("Repo:50"))), - }) - if err != nil { - t.Fatalf("unexpected error making options: %s", err) - } - - expected := autoindexingShared.GetIndexesOptions{ - RepositoryID: 50, - State: "s", - Term: "q", - Limit: 5, - Offset: 25, - } - if diff := cmp.Diff(expected, opts); diff != "" { - t.Errorf("unexpected opts (-want +got):\n%s", diff) - } -} - -func TestMakeGetIndexesOptionsDefaults(t *testing.T) { - opts, err := makeGetIndexesOptions(&gql.LSIFRepositoryIndexesQueryArgs{ - LSIFIndexesQueryArgs: &gql.LSIFIndexesQueryArgs{}, - }) - if err != nil { - t.Fatalf("unexpected error making options: %s", err) - } - - expected := autoindexingShared.GetIndexesOptions{ - RepositoryID: 0, - State: "", - Term: "", - Limit: DefaultIndexPageSize, - Offset: 0, - } - if diff := cmp.Diff(expected, opts); diff != "" { - t.Errorf("unexpected opts (-want +got):\n%s", diff) - } -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/retention_policy_matcher_connection.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/retention_policy_matcher_connection.go deleted file mode 100644 index fae517d8ee4..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/retention_policy_matcher_connection.go +++ /dev/null @@ -1,47 +0,0 @@ -package graphql - -import ( - "context" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" - "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers" - "github.com/sourcegraph/sourcegraph/internal/database" - "github.com/sourcegraph/sourcegraph/internal/observation" -) - -type codeIntelligenceRetentionPolicyMatcherConnectionResolver struct { - db database.DB - resolver resolvers.Resolver - policies []RetentionPolicyMatchCandidate - totalCount int - errTracer *observation.ErrCollector -} - -func NewCodeIntelligenceRetentionPolicyMatcherConnectionResolver(db database.DB, resolver resolvers.Resolver, policies []RetentionPolicyMatchCandidate, totalCount int, errTracer *observation.ErrCollector) *codeIntelligenceRetentionPolicyMatcherConnectionResolver { - return &codeIntelligenceRetentionPolicyMatcherConnectionResolver{ - db: db, - resolver: resolver, - policies: policies, - totalCount: totalCount, - errTracer: errTracer, - } -} - -func (r *codeIntelligenceRetentionPolicyMatcherConnectionResolver) Nodes(ctx context.Context) ([]gql.CodeIntelligenceRetentionPolicyMatchResolver, error) { - resolvers := make([]gql.CodeIntelligenceRetentionPolicyMatchResolver, 0, len(r.policies)) - for _, policy := range r.policies { - resolvers = append(resolvers, NewRetentionPolicyMatcherResolver(r.db, policy)) - } - - return resolvers, nil -} - -func (r *codeIntelligenceRetentionPolicyMatcherConnectionResolver) TotalCount(ctx context.Context) (*int32, error) { - v := int32(r.totalCount) - return &v, nil -} - -func (r *codeIntelligenceRetentionPolicyMatcherConnectionResolver) PageInfo(ctx context.Context) (*graphqlutil.PageInfo, error) { - return graphqlutil.HasNextPage(len(r.policies) < r.totalCount), nil -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/retention_policy_matches.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/retention_policy_matches.go deleted file mode 100644 index 6df3ccaaf4f..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/retention_policy_matches.go +++ /dev/null @@ -1,32 +0,0 @@ -package graphql - -import ( - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/internal/database" - "github.com/sourcegraph/sourcegraph/internal/observation" -) - -type RetentionPolicyMatcherResolver struct { - db database.DB - policy RetentionPolicyMatchCandidate - errCollector *observation.ErrCollector -} - -func NewRetentionPolicyMatcherResolver(db database.DB, policy RetentionPolicyMatchCandidate) *RetentionPolicyMatcherResolver { - return &RetentionPolicyMatcherResolver{db: db, policy: policy} -} - -func (r *RetentionPolicyMatcherResolver) ConfigurationPolicy() gql.CodeIntelligenceConfigurationPolicyResolver { - if r.policy.ConfigurationPolicy == nil { - return nil - } - return NewConfigurationPolicyResolver(r.db, *r.policy.ConfigurationPolicy, r.errCollector) -} - -func (r *RetentionPolicyMatcherResolver) Matches() bool { - return r.policy.Matched -} - -func (r *RetentionPolicyMatcherResolver) ProtectingCommits() *[]string { - return &r.policy.ProtectingCommits -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/summary.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/summary.go deleted file mode 100644 index 37f92c5187f..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/summary.go +++ /dev/null @@ -1,145 +0,0 @@ -package graphql - -import ( - "strings" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers" - "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - uploadsShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" - "github.com/sourcegraph/sourcegraph/internal/database" - "github.com/sourcegraph/sourcegraph/internal/observation" -) - -type repositorySummaryResolver struct { - db database.DB - resolver resolvers.Resolver - gitserver GitserverClient - summary RepositorySummary - prefetcher *Prefetcher - locationResolver *CachedLocationResolver - errTracer *observation.ErrCollector -} - -func NewRepositorySummaryResolver( - db database.DB, - resolver resolvers.Resolver, - gitserver GitserverClient, - summary RepositorySummary, - prefetcher *Prefetcher, - locationResolver *CachedLocationResolver, - errTracer *observation.ErrCollector, -) gql.CodeIntelRepositorySummaryResolver { - return &repositorySummaryResolver{ - db: db, - resolver: resolver, - gitserver: gitserver, - summary: summary, - prefetcher: prefetcher, - locationResolver: locationResolver, - errTracer: errTracer, - } -} - -func (r *repositorySummaryResolver) RecentUploads() []gql.LSIFUploadsWithRepositoryNamespaceResolver { - resolvers := make([]gql.LSIFUploadsWithRepositoryNamespaceResolver, 0, len(r.summary.RecentUploads)) - for _, upload := range r.summary.RecentUploads { - uploadResolvers := make([]gql.LSIFUploadResolver, 0, len(upload.Uploads)) - for _, u := range upload.Uploads { - upload := convertSharedUploadsToDBStoreUploads(u) - uploadResolvers = append(uploadResolvers, NewUploadResolver(r.db, r.gitserver, r.resolver, upload, r.prefetcher, r.locationResolver, r.errTracer)) - } - - resolvers = append(resolvers, NewLSIFUploadsWithRepositoryNamespaceResolver(upload, uploadResolvers)) - } - - return resolvers -} - -func (r *repositorySummaryResolver) RecentIndexes() []gql.LSIFIndexesWithRepositoryNamespaceResolver { - resolvers := make([]gql.LSIFIndexesWithRepositoryNamespaceResolver, 0, len(r.summary.RecentIndexes)) - for _, index := range r.summary.RecentIndexes { - indexResolvers := make([]gql.LSIFIndexResolver, 0, len(index.Indexes)) - for _, u := range index.Indexes { - upload := convertSharedIndexToDBStoreIndex(u) - indexResolvers = append(indexResolvers, NewIndexResolver(r.db, r.gitserver, r.resolver, upload, r.prefetcher, r.locationResolver, r.errTracer)) - } - dbstoreIndex := convertSharedIndexesWithRepositoryNamespaceToDBStoreIndexesWithRepositoryNamespace(index) - resolvers = append(resolvers, NewLSIFIndexesWithRepositoryNamespaceResolver(dbstoreIndex, indexResolvers)) - } - - return resolvers -} - -func (r *repositorySummaryResolver) LastUploadRetentionScan() *gql.DateTime { - return gql.DateTimeOrNil(r.summary.LastUploadRetentionScan) -} - -func (r *repositorySummaryResolver) LastIndexScan() *gql.DateTime { - return gql.DateTimeOrNil(r.summary.LastIndexScan) -} - -type LSIFUploadsWithRepositoryNamespaceResolver struct { - uploadsSummary uploadsShared.UploadsWithRepositoryNamespace - uploadResolvers []gql.LSIFUploadResolver -} - -func NewLSIFUploadsWithRepositoryNamespaceResolver( - uploadsSummary uploadsShared.UploadsWithRepositoryNamespace, - uploadResolvers []gql.LSIFUploadResolver, -) gql.LSIFUploadsWithRepositoryNamespaceResolver { - return &LSIFUploadsWithRepositoryNamespaceResolver{ - uploadsSummary: uploadsSummary, - uploadResolvers: uploadResolvers, - } -} - -func (r *LSIFUploadsWithRepositoryNamespaceResolver) Root() string { - return r.uploadsSummary.Root -} - -func (r *LSIFUploadsWithRepositoryNamespaceResolver) Indexer() gql.CodeIntelIndexerResolver { - for _, indexer := range allIndexers { - if indexer.Name() == r.uploadsSummary.Indexer { - return indexer - } - } - - return &codeIntelIndexerResolver{name: r.uploadsSummary.Indexer} -} - -func (r *LSIFUploadsWithRepositoryNamespaceResolver) Uploads() []gql.LSIFUploadResolver { - return r.uploadResolvers -} - -type LSIFIndexesWithRepositoryNamespaceResolver struct { - indexesSummary dbstore.IndexesWithRepositoryNamespace - indexResolvers []gql.LSIFIndexResolver -} - -func NewLSIFIndexesWithRepositoryNamespaceResolver( - indexesSummary dbstore.IndexesWithRepositoryNamespace, - indexResolvers []gql.LSIFIndexResolver, -) gql.LSIFIndexesWithRepositoryNamespaceResolver { - return &LSIFIndexesWithRepositoryNamespaceResolver{ - indexesSummary: indexesSummary, - indexResolvers: indexResolvers, - } -} - -func (r *LSIFIndexesWithRepositoryNamespaceResolver) Root() string { - return r.indexesSummary.Root -} - -func (r *LSIFIndexesWithRepositoryNamespaceResolver) Indexer() gql.CodeIntelIndexerResolver { - // drop the tag if it exists - if idx, ok := imageToIndexer[strings.Split(r.indexesSummary.Indexer, ":")[0]]; ok { - return idx - } - - return &codeIntelIndexerResolver{name: r.indexesSummary.Indexer} -} - -func (r *LSIFIndexesWithRepositoryNamespaceResolver) Indexes() []gql.LSIFIndexResolver { - return r.indexResolvers -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/support.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/support.go deleted file mode 100644 index cb763e11593..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/support.go +++ /dev/null @@ -1,113 +0,0 @@ -package graphql - -import ( - "context" - "path" - "strings" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/internal/actor" - "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/lib/errors" -) - -type searchBasedCodeIntelSupportType string - -const ( - unsupported searchBasedCodeIntelSupportType = "UNSUPPORTED" - basic searchBasedCodeIntelSupportType = "BASIC" -) - -type preciseCodeIntelSupportType string - -const ( - native preciseCodeIntelSupportType = "NATIVE" - thirdParty preciseCodeIntelSupportType = "THIRD_PARTY" - unknown preciseCodeIntelSupportType = "UNKNOWN" -) - -type searchBasedSupportResolver struct { - language string -} - -func NewSearchBasedCodeIntelResolver(language string) gql.SearchBasedSupportResolver { - return &searchBasedSupportResolver{language} -} - -func (r *searchBasedSupportResolver) SupportLevel() string { - if r.language != "" { - return string(basic) - } - return string(unsupported) -} - -func (r *searchBasedSupportResolver) Language() string { - return r.language -} - -type preciseCodeIntelSupportResolver struct { - indexers []gql.CodeIntelIndexerResolver -} - -func NewPreciseCodeIntelSupportResolver(filepath string) gql.PreciseSupportResolver { - return &preciseCodeIntelSupportResolver{ - indexers: languageToIndexer[path.Ext(filepath)], - } -} - -func NewPreciseCodeIntelSupportResolverFromIndexers(indexers []gql.CodeIntelIndexerResolver) gql.PreciseSupportResolver { - return &preciseCodeIntelSupportResolver{ - indexers: indexers, - } -} - -func (r *preciseCodeIntelSupportResolver) SupportLevel() string { - // if the first indexer in a list is from us, consider native support - nativeRecommendation := len(r.indexers) > 0 && - strings.HasPrefix(r.indexers[0].URL(), "https://github.com/sourcegraph") - - if nativeRecommendation { - return string(native) - } else if len(r.indexers) > 0 { - return string(thirdParty) - } else { - return string(unknown) - } -} - -func (r *preciseCodeIntelSupportResolver) Indexers() *[]gql.CodeIntelIndexerResolver { - if len(r.indexers) == 0 { - return nil - } - return &r.indexers -} - -func (r *Resolver) RequestLanguageSupport(ctx context.Context, args *gql.RequestLanguageSupportArgs) (_ *gql.EmptyResponse, err error) { - ctx, _, endObservation := r.observationContext.requestLanguageSupport.With(ctx, &err, observation.Args{}) - defer endObservation(1, observation.Args{}) - - userID := int(actor.FromContext(ctx).UID) - if userID == 0 { - return nil, errors.Newf("language support requests only logged for authenticated users") - } - - codeNavResolver := r.resolver.CodeNavResolver() - if err := codeNavResolver.SetRequestLanguageSupport(ctx, userID, args.Language); err != nil { - return nil, err - } - - return &gql.EmptyResponse{}, nil -} - -func (r *Resolver) RequestedLanguageSupport(ctx context.Context) (_ []string, err error) { - ctx, _, endObservation := r.observationContext.requestedLanguageSupport.With(ctx, &err, observation.Args{}) - defer endObservation(1, observation.Args{}) - - userID := int(actor.FromContext(ctx).UID) - if userID == 0 { - return nil, errors.Newf("language support requests only logged for authenticated users") - } - - codeNavResolver := r.resolver.CodeNavResolver() - return codeNavResolver.GetLanguagesRequestedBy(ctx, userID) -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/upload.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/upload.go deleted file mode 100644 index b5e969cfb43..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/upload.go +++ /dev/null @@ -1,176 +0,0 @@ -package graphql - -import ( - "context" - "strings" - "time" - - "github.com/graph-gophers/graphql-go" - "github.com/opentracing/opentracing-go/log" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers" - "github.com/sourcegraph/sourcegraph/internal/api" - "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - "github.com/sourcegraph/sourcegraph/internal/database" - "github.com/sourcegraph/sourcegraph/internal/observation" -) - -type UploadResolver struct { - db database.DB - gitserver GitserverClient - resolver resolvers.Resolver - upload dbstore.Upload - prefetcher *Prefetcher - locationResolver *CachedLocationResolver - traceErrs *observation.ErrCollector -} - -func NewUploadResolver(db database.DB, gitserver GitserverClient, resolver resolvers.Resolver, upload dbstore.Upload, prefetcher *Prefetcher, locationResolver *CachedLocationResolver, traceErrs *observation.ErrCollector) gql.LSIFUploadResolver { - if upload.AssociatedIndexID != nil { - // Request the next batch of index fetches to contain the record's associated - // index id, if one exists it exists. This allows the prefetcher.GetIndexByID - // invocation in the AssociatedIndex method to batch its work with sibling - // resolvers, which share the same prefetcher instance. - prefetcher.MarkIndex(*upload.AssociatedIndexID) - } - - return &UploadResolver{ - db: db, - gitserver: gitserver, - resolver: resolver, - upload: upload, - prefetcher: prefetcher, - locationResolver: locationResolver, - traceErrs: traceErrs, - } -} - -func (r *UploadResolver) ID() graphql.ID { return marshalLSIFUploadGQLID(int64(r.upload.ID)) } -func (r *UploadResolver) InputCommit() string { return r.upload.Commit } -func (r *UploadResolver) InputRoot() string { return r.upload.Root } -func (r *UploadResolver) IsLatestForRepo() bool { return r.upload.VisibleAtTip } -func (r *UploadResolver) UploadedAt() gql.DateTime { return gql.DateTime{Time: r.upload.UploadedAt} } -func (r *UploadResolver) Failure() *string { return r.upload.FailureMessage } -func (r *UploadResolver) StartedAt() *gql.DateTime { return gql.DateTimeOrNil(r.upload.StartedAt) } -func (r *UploadResolver) FinishedAt() *gql.DateTime { return gql.DateTimeOrNil(r.upload.FinishedAt) } -func (r *UploadResolver) InputIndexer() string { return r.upload.Indexer } -func (r *UploadResolver) PlaceInQueue() *int32 { return toInt32(r.upload.Rank) } - -func (r *UploadResolver) Tags(ctx context.Context) (tagsNames []string, err error) { - tags, err := r.gitserver.ListTags(ctx, api.RepoName(r.upload.RepositoryName), r.upload.Commit) - if err != nil { - return nil, err - } - for _, tag := range tags { - tagsNames = append(tagsNames, tag.Name) - } - return -} - -func (r *UploadResolver) State() string { - state := strings.ToUpper(r.upload.State) - if state == "FAILED" { - state = "ERRORED" - } - - return state -} - -func (r *UploadResolver) AssociatedIndex(ctx context.Context) (_ gql.LSIFIndexResolver, err error) { - // TODO - why are a bunch of them zero? - if r.upload.AssociatedIndexID == nil || *r.upload.AssociatedIndexID == 0 { - return nil, nil - } - - defer r.traceErrs.Collect(&err, - log.String("uploadResolver.field", "associatedIndex"), - log.Int("associatedIndex", *r.upload.AssociatedIndexID), - ) - - index, exists, err := r.prefetcher.GetIndexByID(ctx, *r.upload.AssociatedIndexID) - if err != nil || !exists { - return nil, err - } - - return NewIndexResolver(r.db, r.gitserver, r.resolver, index, r.prefetcher, r.locationResolver, r.traceErrs), nil -} - -func (r *UploadResolver) ProjectRoot(ctx context.Context) (*gql.GitTreeEntryResolver, error) { - return r.locationResolver.Path(ctx, api.RepoID(r.upload.RepositoryID), r.upload.Commit, r.upload.Root) -} - -func (r *UploadResolver) RetentionPolicyOverview(ctx context.Context, args *gql.LSIFUploadRetentionPolicyMatchesArgs) (_ gql.CodeIntelligenceRetentionPolicyMatchesConnectionResolver, err error) { - var afterID int64 - if args.After != nil { - afterID, err = unmarshalConfigurationPolicyGQLID(graphql.ID(*args.After)) - if err != nil { - return nil, err - } - } - - pageSize := DefaultRetentionPolicyMatchesPageSize - if args.First != nil { - pageSize = int(*args.First) - } - - var term string - if args.Query != nil { - term = *args.Query - } - - policyResolver, err := r.resolver.PoliciesResolver().PolicyResolverFactory(ctx) - if err != nil { - return nil, err - } - - upload := sharedPoliciesUploadsToStoreUpload(r.upload) - m, totalCount, err := policyResolver.GetRetentionPolicyOverview(ctx, upload, args.MatchesOnly, pageSize, afterID, term, time.Now()) - if err != nil { - return nil, err - } - matches := sharedRetentionPolicyToStoreRetentionPolicy(m) - - return NewCodeIntelligenceRetentionPolicyMatcherConnectionResolver(r.db, r.resolver, matches, totalCount, r.traceErrs), nil -} - -func (r *UploadResolver) Indexer() gql.CodeIntelIndexerResolver { - for _, indexer := range allIndexers { - if indexer.Name() == r.upload.Indexer { - return indexer - } - } - - return &codeIntelIndexerResolver{name: r.upload.Indexer} -} - -func (r *UploadResolver) DocumentPaths(ctx context.Context, args *gql.LSIFUploadDocumentPathsQueryArgs) (gql.LSIFUploadDocumentPathsConnectionResolver, error) { - pattern := "%%" - if args.Pattern != "" { - pattern = args.Pattern - } - - documents, totalCount, err := r.resolver.UploadsResolver().GetUploadDocumentsForPath(ctx, r.upload.ID, pattern) - if err != nil { - return nil, err - } - - return &uploadDocumentPathsConnectionResolver{ - totalCount: totalCount, - documents: documents, - }, nil -} - -func (r *UploadResolver) AuditLogs(ctx context.Context) (*[]gql.LSIFUploadsAuditLogsResolver, error) { - logs, err := r.resolver.UploadsResolver().GetAuditLogsForUpload(ctx, r.upload.ID) - if err != nil { - return nil, err - } - - resolvers := make([]gql.LSIFUploadsAuditLogsResolver, 0, len(logs)) - for _, log := range logs { - resolvers = append(resolvers, &lsifUploadsAuditLogResolver{log}) - } - - return &resolvers, nil -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/upload_connection.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/upload_connection.go deleted file mode 100644 index 2a754b71821..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/upload_connection.go +++ /dev/null @@ -1,69 +0,0 @@ -package graphql - -import ( - "context" - - "github.com/opentracing/opentracing-go/log" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" - "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers" - uploadsgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/transport/graphql" - "github.com/sourcegraph/sourcegraph/internal/database" - "github.com/sourcegraph/sourcegraph/internal/observation" -) - -type UploadConnectionResolver struct { - db database.DB - gitserver GitserverClient - resolver resolvers.Resolver - uploadsResolver *uploadsgraphql.UploadsResolver - prefetcher *Prefetcher - locationResolver *CachedLocationResolver - errTracer *observation.ErrCollector -} - -func NewUploadConnectionResolver(db database.DB, gitserver GitserverClient, resolver resolvers.Resolver, uploadsResolver *uploadsgraphql.UploadsResolver, prefetcher *Prefetcher, locationResolver *CachedLocationResolver, errTracer *observation.ErrCollector) gql.LSIFUploadConnectionResolver { - return &UploadConnectionResolver{ - resolver: resolver, - db: db, - gitserver: gitserver, - uploadsResolver: uploadsResolver, - prefetcher: prefetcher, - locationResolver: locationResolver, - errTracer: errTracer, - } -} - -func (r *UploadConnectionResolver) Nodes(ctx context.Context) (_ []gql.LSIFUploadResolver, err error) { - defer r.errTracer.Collect(&err, log.String("uploadConnectionResolver.field", "nodes")) - - if err := r.uploadsResolver.Resolve(ctx); err != nil { - return nil, err - } - - resolvers := make([]gql.LSIFUploadResolver, 0, len(r.uploadsResolver.Uploads)) - for i := range r.uploadsResolver.Uploads { - upload := convertSharedUploadsToDBStoreUploads(r.uploadsResolver.Uploads[i]) - resolvers = append(resolvers, NewUploadResolver(r.db, r.gitserver, r.resolver, upload, r.prefetcher, r.locationResolver, r.errTracer)) - } - return resolvers, nil -} - -func (r *UploadConnectionResolver) TotalCount(ctx context.Context) (_ *int32, err error) { - defer r.errTracer.Collect(&err, log.String("uploadConnectionResolver.field", "totalCount")) - - if err := r.uploadsResolver.Resolve(ctx); err != nil { - return nil, err - } - return toInt32(&r.uploadsResolver.TotalCount), nil -} - -func (r *UploadConnectionResolver) PageInfo(ctx context.Context) (_ *graphqlutil.PageInfo, err error) { - defer r.errTracer.Collect(&err, log.String("uploadConnectionResolver.field", "pageInfo")) - - if err := r.uploadsResolver.Resolve(ctx); err != nil { - return nil, err - } - return graphqlutil.EncodeIntCursor(toInt32(r.uploadsResolver.NextOffset)), nil -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/util.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/util.go deleted file mode 100644 index 4df71183e72..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/util.go +++ /dev/null @@ -1,407 +0,0 @@ -package graphql - -import ( - "github.com/sourcegraph/go-lsp" - - autoindexingShared "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" - "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" - policiesShared "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" - "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - store "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/lsifstore" - uploadsShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" - "github.com/sourcegraph/sourcegraph/internal/workerutil" - "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" -) - -// strPtr creates a pointer to the given value. If the value is an -// empty string, a nil pointer is returned. -func strPtr(val string) *string { - if val == "" { - return nil - } - - return &val -} - -// intPtr creates a pointer to the given value. -func intPtr(val int32) *int32 { - return &val -} - -// intPtr creates a pointer to the given value. -func boolPtr(val bool) *bool { - return &val -} - -// toInt32 translates the given int pointer into an int32 pointer. -func toInt32(val *int) *int32 { - if val == nil { - return nil - } - - v := int32(*val) - return &v -} - -// derefString returns the underlying value in the given pointer. -// If the pointer is nil, the default value is returned. -func derefString(val *string, defaultValue string) string { - if val != nil { - return *val - } - return defaultValue -} - -// derefInt32 returns the underlying value in the given pointer. -// If the pointer is nil, the default value is returned. -func derefInt32(val *int32, defaultValue int) int { - if val != nil { - return int(*val) - } - return defaultValue -} - -// derefBool returns the underlying value in the given pointer. -// If the pointer is nil, the default value is returned. -func derefBool(val *bool, defaultValue bool) bool { - if val != nil { - return *val - } - return defaultValue -} - -// convertRange creates an LSP range from a bundle range. -func convertRange(r lsifstore.Range) lsp.Range { - return lsp.Range{Start: convertPosition(r.Start.Line, r.Start.Character), End: convertPosition(r.End.Line, r.End.Character)} -} - -// convertPosition creates an LSP position from a line and character pair. -func convertPosition(line, character int) lsp.Position { - return lsp.Position{Line: line, Character: character} -} - -func sharedConfigurationPoliciesListToStoreConfigurationPoliciesList(policies []policiesShared.ConfigurationPolicy) []store.ConfigurationPolicy { - storePolicies := make([]store.ConfigurationPolicy, 0, len(policies)) - for _, p := range policies { - storePolicies = append(storePolicies, sharedConfigurationPoliciesToStoreConfigurationPolicies(p)) - } - return storePolicies -} - -func sharedConfigurationPoliciesToStoreConfigurationPolicies(p policiesShared.ConfigurationPolicy) store.ConfigurationPolicy { - return store.ConfigurationPolicy{ - ID: p.ID, - RepositoryID: p.RepositoryID, - RepositoryPatterns: p.RepositoryPatterns, - Name: p.Name, - Type: store.GitObjectType(p.Type), - Pattern: p.Pattern, - Protected: p.Protected, - RetentionEnabled: p.RetentionEnabled, - RetentionDuration: p.RetentionDuration, - RetainIntermediateCommits: p.RetainIntermediateCommits, - IndexingEnabled: p.IndexingEnabled, - IndexCommitMaxAge: p.IndexCommitMaxAge, - IndexIntermediateCommits: p.IndexIntermediateCommits, - } -} - -func sharedRangeTolsifstoreRange(r shared.Range) lsifstore.Range { - return lsifstore.Range{ - Start: lsifstore.Position(r.Start), - End: lsifstore.Position(r.End), - } -} - -func sharedRangeTolspRange(r shared.Range) lsp.Range { - return lsp.Range{Start: convertPosition(r.Start.Line, r.Start.Character), End: convertPosition(r.End.Line, r.End.Character)} -} - -func sharedRangeToAdjustedRange(rng []shared.AdjustedCodeIntelligenceRange) []AdjustedCodeIntelligenceRange { - adjustedRange := make([]AdjustedCodeIntelligenceRange, 0, len(rng)) - for _, r := range rng { - - definitions := make([]AdjustedLocation, 0, len(r.Definitions)) - for _, d := range r.Definitions { - def := AdjustedLocation{ - Dump: store.Dump(d.Dump), - Path: d.Path, - AdjustedCommit: d.TargetCommit, - AdjustedRange: lsifstore.Range{ - Start: lsifstore.Position(d.TargetRange.Start), - End: lsifstore.Position(d.TargetRange.End), - }, - } - definitions = append(definitions, def) - } - - references := make([]AdjustedLocation, 0, len(r.References)) - for _, d := range r.References { - ref := AdjustedLocation{ - Dump: store.Dump(d.Dump), - Path: d.Path, - AdjustedCommit: d.TargetCommit, - AdjustedRange: lsifstore.Range{ - Start: lsifstore.Position(d.TargetRange.Start), - End: lsifstore.Position(d.TargetRange.End), - }, - } - references = append(references, ref) - } - - implementations := make([]AdjustedLocation, 0, len(r.Implementations)) - for _, d := range r.Implementations { - impl := AdjustedLocation{ - Dump: store.Dump(d.Dump), - Path: d.Path, - AdjustedCommit: d.TargetCommit, - AdjustedRange: lsifstore.Range{ - Start: lsifstore.Position(d.TargetRange.Start), - End: lsifstore.Position(d.TargetRange.End), - }, - } - implementations = append(implementations, impl) - } - - adj := AdjustedCodeIntelligenceRange{ - Range: lsifstore.Range{ - Start: lsifstore.Position(r.Range.Start), - End: lsifstore.Position(r.Range.End), - }, - Definitions: definitions, - References: references, - Implementations: implementations, - HoverText: r.HoverText, - } - - adjustedRange = append(adjustedRange, adj) - } - - return adjustedRange -} - -func uploadLocationToAdjustedLocations(location []shared.UploadLocation) []AdjustedLocation { - uploadLocation := make([]AdjustedLocation, 0, len(location)) - for _, loc := range location { - dump := store.Dump(loc.Dump) - adjustedRange := lsifstore.Range{ - Start: lsifstore.Position{ - Line: loc.TargetRange.Start.Line, - Character: loc.TargetRange.Start.Character, - }, - End: lsifstore.Position{ - Line: loc.TargetRange.End.Line, - Character: loc.TargetRange.End.Character, - }, - } - - uploadLocation = append(uploadLocation, AdjustedLocation{ - Dump: dump, - Path: loc.Path, - AdjustedCommit: loc.TargetCommit, - AdjustedRange: adjustedRange, - }) - } - - return uploadLocation -} - -func sharedPoliciesUploadsToStoreUpload(dump store.Upload) policiesShared.Upload { - return policiesShared.Upload{ - ID: dump.ID, - Commit: dump.Commit, - Root: dump.Root, - VisibleAtTip: dump.VisibleAtTip, - UploadedAt: dump.UploadedAt, - State: dump.State, - FailureMessage: dump.FailureMessage, - StartedAt: dump.StartedAt, - FinishedAt: dump.FinishedAt, - ProcessAfter: dump.ProcessAfter, - NumResets: dump.NumResets, - NumFailures: dump.NumFailures, - RepositoryID: dump.RepositoryID, - RepositoryName: dump.RepositoryName, - Indexer: dump.Indexer, - IndexerVersion: dump.IndexerVersion, - NumParts: 0, - UploadedParts: []int{}, - UploadSize: nil, - Rank: nil, - AssociatedIndexID: dump.AssociatedIndexID, - } -} - -func sharedRetentionPolicyToStoreRetentionPolicy(policy []policiesShared.RetentionPolicyMatchCandidate) []RetentionPolicyMatchCandidate { - retentionPolicy := make([]RetentionPolicyMatchCandidate, 0, len(policy)) - for _, p := range policy { - r := RetentionPolicyMatchCandidate{ - Matched: p.Matched, - ProtectingCommits: p.ProtectingCommits, - } - if p.ConfigurationPolicy != nil { - r.ConfigurationPolicy = &store.ConfigurationPolicy{ - ID: p.ID, - RepositoryID: p.RepositoryID, - RepositoryPatterns: p.RepositoryPatterns, - Name: p.Name, - Type: store.GitObjectType(p.Type), - Pattern: p.Pattern, - Protected: p.Protected, - RetentionEnabled: p.RetentionEnabled, - RetentionDuration: p.RetentionDuration, - RetainIntermediateCommits: p.RetainIntermediateCommits, - IndexingEnabled: p.IndexingEnabled, - IndexCommitMaxAge: p.IndexCommitMaxAge, - IndexIntermediateCommits: p.IndexIntermediateCommits, - } - } - retentionPolicy = append(retentionPolicy, r) - } - - return retentionPolicy -} - -func sharedDumpToDbstoreUpload(dump shared.Dump) store.Upload { - return store.Upload{ - ID: dump.ID, - Commit: dump.Commit, - Root: dump.Root, - VisibleAtTip: dump.VisibleAtTip, - UploadedAt: dump.UploadedAt, - State: dump.State, - FailureMessage: dump.FailureMessage, - StartedAt: dump.StartedAt, - FinishedAt: dump.FinishedAt, - ProcessAfter: dump.ProcessAfter, - NumResets: dump.NumResets, - NumFailures: dump.NumFailures, - RepositoryID: dump.RepositoryID, - RepositoryName: dump.RepositoryName, - Indexer: dump.Indexer, - IndexerVersion: dump.IndexerVersion, - NumParts: 0, - UploadedParts: []int{}, - UploadSize: nil, - Rank: nil, - AssociatedIndexID: dump.AssociatedIndexID, - } -} - -func sharedDiagnosticAtUploadToAdjustedDiagnostic(shared []shared.DiagnosticAtUpload) []AdjustedDiagnostic { - adjustedDiagnostics := make([]AdjustedDiagnostic, 0, len(shared)) - for _, diag := range shared { - diagnosticData := precise.DiagnosticData{ - Severity: diag.Severity, - Code: diag.Code, - Message: diag.Message, - Source: diag.Source, - StartLine: diag.StartLine, - StartCharacter: diag.StartCharacter, - EndLine: diag.EndLine, - EndCharacter: diag.EndCharacter, - } - lsifDiag := lsifstore.Diagnostic{ - DiagnosticData: diagnosticData, - DumpID: diag.DumpID, - Path: diag.Path, - } - - adjusted := AdjustedDiagnostic{ - Diagnostic: lsifDiag, - Dump: store.Dump(diag.Dump), - AdjustedCommit: diag.AdjustedCommit, - AdjustedRange: lsifstore.Range{ - Start: lsifstore.Position(diag.AdjustedRange.Start), - End: lsifstore.Position(diag.AdjustedRange.End), - }, - } - adjustedDiagnostics = append(adjustedDiagnostics, adjusted) - } - return adjustedDiagnostics -} - -func convertSharedIndexToDBStoreIndex(index autoindexingShared.Index) store.Index { - dockerSteps := make([]store.DockerStep, 0, len(index.DockerSteps)) - for _, step := range index.DockerSteps { - dockerSteps = append(dockerSteps, store.DockerStep(step)) - } - - executionLogs := make([]workerutil.ExecutionLogEntry, 0, len(index.ExecutionLogs)) - for _, log := range index.ExecutionLogs { - executionLogs = append(executionLogs, workerutil.ExecutionLogEntry(log)) - } - - return store.Index{ - ID: index.ID, - Commit: index.Commit, - QueuedAt: index.QueuedAt, - State: index.State, - FailureMessage: index.FailureMessage, - StartedAt: index.StartedAt, - FinishedAt: index.FinishedAt, - ProcessAfter: index.ProcessAfter, - NumResets: index.NumResets, - NumFailures: index.NumFailures, - RepositoryID: index.RepositoryID, - LocalSteps: index.LocalSteps, - RepositoryName: index.RepositoryName, - DockerSteps: dockerSteps, - Root: index.Root, - Indexer: index.Indexer, - IndexerArgs: index.IndexerArgs, - Outfile: index.Outfile, - ExecutionLogs: executionLogs, - Rank: index.Rank, - AssociatedUploadID: index.AssociatedUploadID, - } -} - -func convertSharedIndexesWithRepositoryNamespaceToDBStoreIndexesWithRepositoryNamespace(shared autoindexingShared.IndexesWithRepositoryNamespace) dbstore.IndexesWithRepositoryNamespace { - indexes := make([]dbstore.Index, 0, len(shared.Indexes)) - for _, index := range shared.Indexes { - indexes = append(indexes, convertSharedIndexToDBStoreIndex(index)) - } - - return dbstore.IndexesWithRepositoryNamespace{ - Root: shared.Root, - Indexer: shared.Indexer, - Indexes: indexes, - } -} - -func convertSharedUploadsToDBStoreUploads(u uploadsShared.Upload) store.Upload { - return store.Upload{ - ID: u.ID, - Commit: u.Commit, - Root: u.Root, - VisibleAtTip: u.VisibleAtTip, - UploadedAt: u.UploadedAt, - State: u.State, - FailureMessage: u.FailureMessage, - StartedAt: u.StartedAt, - FinishedAt: u.FinishedAt, - ProcessAfter: u.ProcessAfter, - NumResets: u.NumResets, - NumFailures: u.NumFailures, - RepositoryID: u.RepositoryID, - RepositoryName: u.RepositoryName, - Indexer: u.Indexer, - IndexerVersion: u.IndexerVersion, - NumParts: u.NumParts, - UploadedParts: u.UploadedParts, - UploadSize: u.UploadSize, - UncompressedSize: u.UncompressedSize, - Rank: u.Rank, - AssociatedIndexID: u.AssociatedIndexID, - } -} - -func convertSharedUploadsListToDBStoreUploadsList(u []uploadsShared.Upload) []store.Upload { - uploads := make([]store.Upload, 0, len(u)) - for _, upload := range u { - uploads = append(uploads, convertSharedUploadsToDBStoreUploads(upload)) - } - return uploads -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/util_test.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/util_test.go deleted file mode 100644 index 47272fd4e76..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/util_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package graphql - -import "testing" - -func TestDerefString(t *testing.T) { - expected := "foo" - - if val := derefString(nil, expected); val != expected { - t.Errorf("unexpected value. want=%s have=%s", expected, val) - } - if val := derefString(&expected, ""); val != expected { - t.Errorf("unexpected value. want=%s have=%s", expected, val) - } - if val := derefString(&expected, expected); val != expected { - t.Errorf("unexpected value. want=%s have=%s", expected, val) - } -} - -func TestDerefInt32(t *testing.T) { - expected := 42 - expected32 := int32(expected) - - if val := derefInt32(nil, expected); val != expected { - t.Errorf("unexpected value. want=%d have=%d", expected, val) - } - if val := derefInt32(&expected32, expected); val != expected { - t.Errorf("unexpected value. want=%d have=%d", expected, val) - } -} - -func TestDerefBool(t *testing.T) { - if val := derefBool(nil, true); !val { - t.Errorf("unexpected value. want=%v have=%v", true, val) - } - if val := derefBool(nil, false); val { - t.Errorf("unexpected value. want=%v have=%v", false, val) - } - - pVal := true - if val := derefBool(&pVal, true); !val { - t.Errorf("unexpected value. want=%v have=%v", true, val) - } - if val := derefBool(&pVal, false); !val { - t.Errorf("unexpected value. want=%v have=%v", false, val) - } - - pVal = false - if val := derefBool(&pVal, true); val { - t.Errorf("unexpected value. want=%v have=%v", true, val) - } - if val := derefBool(&pVal, false); val { - t.Errorf("unexpected value. want=%v have=%v", false, val) - } -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/iface.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/iface.go deleted file mode 100644 index a81b3a27816..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/iface.go +++ /dev/null @@ -1,59 +0,0 @@ -package resolvers - -import ( - "context" - "time" - - "github.com/sourcegraph/sourcegraph/internal/api" - autoindexingShared "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" - autoindexinggraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/transport/graphql" - codenavgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql" - policiesgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/transport/graphql" - uploadsShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" - uploadsgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/transport/graphql" - "github.com/sourcegraph/sourcegraph/internal/types" - "github.com/sourcegraph/sourcegraph/lib/codeintel/autoindex/config" -) - -type DBStore interface { - RequestLanguageSupport(ctx context.Context, userID int, language string) error - LanguagesRequestedBy(ctx context.Context, userID int) ([]string, error) -} - -type CodeNavResolver interface { - GetSupportedByCtags(ctx context.Context, filepath string, repoName api.RepoName) (bool, string, error) - SetRequestLanguageSupport(ctx context.Context, userID int, language string) (err error) - GetLanguagesRequestedBy(ctx context.Context, userID int) (_ []string, err error) - GitBlobLSIFDataResolverFactory(ctx context.Context, repo *types.Repo, commit, path, toolName string, exactPath bool) (_ codenavgraphql.GitBlobLSIFDataResolver, err error) -} - -type PoliciesResolver interface { - PolicyResolverFactory(ctx context.Context) (_ policiesgraphql.PolicyResolver, err error) -} - -type AutoIndexingResolver interface { - GetIndexByID(ctx context.Context, id int) (_ autoindexingShared.Index, _ bool, err error) - GetIndexesByIDs(ctx context.Context, ids ...int) (_ []autoindexingShared.Index, err error) - GetRecentIndexesSummary(ctx context.Context, repositoryID int) (summaries []autoindexingShared.IndexesWithRepositoryNamespace, err error) - GetLastIndexScanForRepository(ctx context.Context, repositoryID int) (_ *time.Time, err error) - DeleteIndexByID(ctx context.Context, id int) (err error) - QueueAutoIndexJobsForRepo(ctx context.Context, repositoryID int, rev, configuration string) ([]autoindexingShared.Index, error) - - GetIndexConfiguration(ctx context.Context, repositoryID int) ([]byte, bool, error) // GetIndexConfigurationByRepositoryID - InferedIndexConfiguration(ctx context.Context, repositoryID int, commit string) (*config.IndexConfiguration, bool, error) // in the service InferIndexConfiguration first return - InferedIndexConfigurationHints(ctx context.Context, repositoryID int, commit string) ([]config.IndexJobHint, error) // in the service InferIndexConfiguration second return - UpdateIndexConfigurationByRepositoryID(ctx context.Context, repositoryID int, configuration string) error // simple dbstore - - IndexConnectionResolverFromFactory(opts autoindexingShared.GetIndexesOptions) *autoindexinggraphql.IndexesResolver -} - -type UploadsResolver interface { - GetUploadsByIDs(ctx context.Context, ids ...int) (_ []uploadsShared.Upload, err error) - GetUploadDocumentsForPath(ctx context.Context, bundleID int, pathPattern string) ([]string, int, error) - GetRecentUploadsSummary(ctx context.Context, repositoryID int) (upload []uploadsShared.UploadsWithRepositoryNamespace, err error) - GetLastUploadRetentionScanForRepository(ctx context.Context, repositoryID int) (_ *time.Time, err error) - DeleteUploadByID(ctx context.Context, id int) (_ bool, err error) - GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []uploadsShared.UploadLog, err error) - UploadsConnectionResolverFromFactory(opts uploadsShared.GetUploadsOptions) *uploadsgraphql.UploadsResolver - CommitGraphResolverFromFactory(ctx context.Context, repositoryID int) *uploadsgraphql.CommitGraphResolver -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/mocks_temp.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/mocks_temp.go deleted file mode 100644 index e6a29631c5f..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/mocks_temp.go +++ /dev/null @@ -1,618 +0,0 @@ -// Code generated by go-mockgen 1.3.4; DO NOT EDIT. -// -// This file was generated by running `sg generate` (or `go-mockgen`) at the root of -// this repository. To add additional mocks to this or another package, add a new entry -// to the mockgen.yaml file in the root of this repository. - -package mocks - -import ( - "sync" - - resolvers "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers" - graphql "github.com/sourcegraph/sourcegraph/internal/services/executors/transport/graphql" -) - -// MockResolver is a mock implementation of the Resolver interface (from the -// package -// github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers) -// used for unit testing. -type MockResolver struct { - // AutoIndexingResolverFunc is an instance of a mock function object - // controlling the behavior of the method AutoIndexingResolver. - AutoIndexingResolverFunc *ResolverAutoIndexingResolverFunc - // CodeNavResolverFunc is an instance of a mock function object - // controlling the behavior of the method CodeNavResolver. - CodeNavResolverFunc *ResolverCodeNavResolverFunc - // ExecutorResolverFunc is an instance of a mock function object - // controlling the behavior of the method ExecutorResolver. - ExecutorResolverFunc *ResolverExecutorResolverFunc - // PoliciesResolverFunc is an instance of a mock function object - // controlling the behavior of the method PoliciesResolver. - PoliciesResolverFunc *ResolverPoliciesResolverFunc - // UploadsResolverFunc is an instance of a mock function object - // controlling the behavior of the method UploadsResolver. - UploadsResolverFunc *ResolverUploadsResolverFunc -} - -// NewMockResolver creates a new mock of the Resolver interface. All methods -// return zero values for all results, unless overwritten. -func NewMockResolver() *MockResolver { - return &MockResolver{ - AutoIndexingResolverFunc: &ResolverAutoIndexingResolverFunc{ - defaultHook: func() (r0 resolvers.AutoIndexingResolver) { - return - }, - }, - CodeNavResolverFunc: &ResolverCodeNavResolverFunc{ - defaultHook: func() (r0 resolvers.CodeNavResolver) { - return - }, - }, - ExecutorResolverFunc: &ResolverExecutorResolverFunc{ - defaultHook: func() (r0 graphql.Resolver) { - return - }, - }, - PoliciesResolverFunc: &ResolverPoliciesResolverFunc{ - defaultHook: func() (r0 resolvers.PoliciesResolver) { - return - }, - }, - UploadsResolverFunc: &ResolverUploadsResolverFunc{ - defaultHook: func() (r0 resolvers.UploadsResolver) { - return - }, - }, - } -} - -// NewStrictMockResolver creates a new mock of the Resolver interface. All -// methods panic on invocation, unless overwritten. -func NewStrictMockResolver() *MockResolver { - return &MockResolver{ - AutoIndexingResolverFunc: &ResolverAutoIndexingResolverFunc{ - defaultHook: func() resolvers.AutoIndexingResolver { - panic("unexpected invocation of MockResolver.AutoIndexingResolver") - }, - }, - CodeNavResolverFunc: &ResolverCodeNavResolverFunc{ - defaultHook: func() resolvers.CodeNavResolver { - panic("unexpected invocation of MockResolver.CodeNavResolver") - }, - }, - ExecutorResolverFunc: &ResolverExecutorResolverFunc{ - defaultHook: func() graphql.Resolver { - panic("unexpected invocation of MockResolver.ExecutorResolver") - }, - }, - PoliciesResolverFunc: &ResolverPoliciesResolverFunc{ - defaultHook: func() resolvers.PoliciesResolver { - panic("unexpected invocation of MockResolver.PoliciesResolver") - }, - }, - UploadsResolverFunc: &ResolverUploadsResolverFunc{ - defaultHook: func() resolvers.UploadsResolver { - panic("unexpected invocation of MockResolver.UploadsResolver") - }, - }, - } -} - -// NewMockResolverFrom creates a new mock of the MockResolver interface. All -// methods delegate to the given implementation, unless overwritten. -func NewMockResolverFrom(i resolvers.Resolver) *MockResolver { - return &MockResolver{ - AutoIndexingResolverFunc: &ResolverAutoIndexingResolverFunc{ - defaultHook: i.AutoIndexingResolver, - }, - CodeNavResolverFunc: &ResolverCodeNavResolverFunc{ - defaultHook: i.CodeNavResolver, - }, - ExecutorResolverFunc: &ResolverExecutorResolverFunc{ - defaultHook: i.ExecutorResolver, - }, - PoliciesResolverFunc: &ResolverPoliciesResolverFunc{ - defaultHook: i.PoliciesResolver, - }, - UploadsResolverFunc: &ResolverUploadsResolverFunc{ - defaultHook: i.UploadsResolver, - }, - } -} - -// ResolverAutoIndexingResolverFunc describes the behavior when the -// AutoIndexingResolver method of the parent MockResolver instance is -// invoked. -type ResolverAutoIndexingResolverFunc struct { - defaultHook func() resolvers.AutoIndexingResolver - hooks []func() resolvers.AutoIndexingResolver - history []ResolverAutoIndexingResolverFuncCall - mutex sync.Mutex -} - -// AutoIndexingResolver delegates to the next hook function in the queue and -// stores the parameter and result values of this invocation. -func (m *MockResolver) AutoIndexingResolver() resolvers.AutoIndexingResolver { - r0 := m.AutoIndexingResolverFunc.nextHook()() - m.AutoIndexingResolverFunc.appendCall(ResolverAutoIndexingResolverFuncCall{r0}) - return r0 -} - -// SetDefaultHook sets function that is called when the AutoIndexingResolver -// method of the parent MockResolver instance is invoked and the hook queue -// is empty. -func (f *ResolverAutoIndexingResolverFunc) SetDefaultHook(hook func() resolvers.AutoIndexingResolver) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// AutoIndexingResolver method of the parent MockResolver instance invokes -// the hook at the front of the queue and discards it. After the queue is -// empty, the default hook function is invoked for any future action. -func (f *ResolverAutoIndexingResolverFunc) PushHook(hook func() resolvers.AutoIndexingResolver) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverAutoIndexingResolverFunc) SetDefaultReturn(r0 resolvers.AutoIndexingResolver) { - f.SetDefaultHook(func() resolvers.AutoIndexingResolver { - return r0 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverAutoIndexingResolverFunc) PushReturn(r0 resolvers.AutoIndexingResolver) { - f.PushHook(func() resolvers.AutoIndexingResolver { - return r0 - }) -} - -func (f *ResolverAutoIndexingResolverFunc) nextHook() func() resolvers.AutoIndexingResolver { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverAutoIndexingResolverFunc) appendCall(r0 ResolverAutoIndexingResolverFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverAutoIndexingResolverFuncCall -// objects describing the invocations of this function. -func (f *ResolverAutoIndexingResolverFunc) History() []ResolverAutoIndexingResolverFuncCall { - f.mutex.Lock() - history := make([]ResolverAutoIndexingResolverFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverAutoIndexingResolverFuncCall is an object that describes an -// invocation of method AutoIndexingResolver on an instance of MockResolver. -type ResolverAutoIndexingResolverFuncCall struct { - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 resolvers.AutoIndexingResolver -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverAutoIndexingResolverFuncCall) Args() []interface{} { - return []interface{}{} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverAutoIndexingResolverFuncCall) Results() []interface{} { - return []interface{}{c.Result0} -} - -// ResolverCodeNavResolverFunc describes the behavior when the -// CodeNavResolver method of the parent MockResolver instance is invoked. -type ResolverCodeNavResolverFunc struct { - defaultHook func() resolvers.CodeNavResolver - hooks []func() resolvers.CodeNavResolver - history []ResolverCodeNavResolverFuncCall - mutex sync.Mutex -} - -// CodeNavResolver delegates to the next hook function in the queue and -// stores the parameter and result values of this invocation. -func (m *MockResolver) CodeNavResolver() resolvers.CodeNavResolver { - r0 := m.CodeNavResolverFunc.nextHook()() - m.CodeNavResolverFunc.appendCall(ResolverCodeNavResolverFuncCall{r0}) - return r0 -} - -// SetDefaultHook sets function that is called when the CodeNavResolver -// method of the parent MockResolver instance is invoked and the hook queue -// is empty. -func (f *ResolverCodeNavResolverFunc) SetDefaultHook(hook func() resolvers.CodeNavResolver) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// CodeNavResolver method of the parent MockResolver instance invokes the -// hook at the front of the queue and discards it. After the queue is empty, -// the default hook function is invoked for any future action. -func (f *ResolverCodeNavResolverFunc) PushHook(hook func() resolvers.CodeNavResolver) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverCodeNavResolverFunc) SetDefaultReturn(r0 resolvers.CodeNavResolver) { - f.SetDefaultHook(func() resolvers.CodeNavResolver { - return r0 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverCodeNavResolverFunc) PushReturn(r0 resolvers.CodeNavResolver) { - f.PushHook(func() resolvers.CodeNavResolver { - return r0 - }) -} - -func (f *ResolverCodeNavResolverFunc) nextHook() func() resolvers.CodeNavResolver { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverCodeNavResolverFunc) appendCall(r0 ResolverCodeNavResolverFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverCodeNavResolverFuncCall objects -// describing the invocations of this function. -func (f *ResolverCodeNavResolverFunc) History() []ResolverCodeNavResolverFuncCall { - f.mutex.Lock() - history := make([]ResolverCodeNavResolverFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverCodeNavResolverFuncCall is an object that describes an invocation -// of method CodeNavResolver on an instance of MockResolver. -type ResolverCodeNavResolverFuncCall struct { - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 resolvers.CodeNavResolver -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverCodeNavResolverFuncCall) Args() []interface{} { - return []interface{}{} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverCodeNavResolverFuncCall) Results() []interface{} { - return []interface{}{c.Result0} -} - -// ResolverExecutorResolverFunc describes the behavior when the -// ExecutorResolver method of the parent MockResolver instance is invoked. -type ResolverExecutorResolverFunc struct { - defaultHook func() graphql.Resolver - hooks []func() graphql.Resolver - history []ResolverExecutorResolverFuncCall - mutex sync.Mutex -} - -// ExecutorResolver delegates to the next hook function in the queue and -// stores the parameter and result values of this invocation. -func (m *MockResolver) ExecutorResolver() graphql.Resolver { - r0 := m.ExecutorResolverFunc.nextHook()() - m.ExecutorResolverFunc.appendCall(ResolverExecutorResolverFuncCall{r0}) - return r0 -} - -// SetDefaultHook sets function that is called when the ExecutorResolver -// method of the parent MockResolver instance is invoked and the hook queue -// is empty. -func (f *ResolverExecutorResolverFunc) SetDefaultHook(hook func() graphql.Resolver) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// ExecutorResolver method of the parent MockResolver instance invokes the -// hook at the front of the queue and discards it. After the queue is empty, -// the default hook function is invoked for any future action. -func (f *ResolverExecutorResolverFunc) PushHook(hook func() graphql.Resolver) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverExecutorResolverFunc) SetDefaultReturn(r0 graphql.Resolver) { - f.SetDefaultHook(func() graphql.Resolver { - return r0 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverExecutorResolverFunc) PushReturn(r0 graphql.Resolver) { - f.PushHook(func() graphql.Resolver { - return r0 - }) -} - -func (f *ResolverExecutorResolverFunc) nextHook() func() graphql.Resolver { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverExecutorResolverFunc) appendCall(r0 ResolverExecutorResolverFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverExecutorResolverFuncCall objects -// describing the invocations of this function. -func (f *ResolverExecutorResolverFunc) History() []ResolverExecutorResolverFuncCall { - f.mutex.Lock() - history := make([]ResolverExecutorResolverFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverExecutorResolverFuncCall is an object that describes an -// invocation of method ExecutorResolver on an instance of MockResolver. -type ResolverExecutorResolverFuncCall struct { - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 graphql.Resolver -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverExecutorResolverFuncCall) Args() []interface{} { - return []interface{}{} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverExecutorResolverFuncCall) Results() []interface{} { - return []interface{}{c.Result0} -} - -// ResolverPoliciesResolverFunc describes the behavior when the -// PoliciesResolver method of the parent MockResolver instance is invoked. -type ResolverPoliciesResolverFunc struct { - defaultHook func() resolvers.PoliciesResolver - hooks []func() resolvers.PoliciesResolver - history []ResolverPoliciesResolverFuncCall - mutex sync.Mutex -} - -// PoliciesResolver delegates to the next hook function in the queue and -// stores the parameter and result values of this invocation. -func (m *MockResolver) PoliciesResolver() resolvers.PoliciesResolver { - r0 := m.PoliciesResolverFunc.nextHook()() - m.PoliciesResolverFunc.appendCall(ResolverPoliciesResolverFuncCall{r0}) - return r0 -} - -// SetDefaultHook sets function that is called when the PoliciesResolver -// method of the parent MockResolver instance is invoked and the hook queue -// is empty. -func (f *ResolverPoliciesResolverFunc) SetDefaultHook(hook func() resolvers.PoliciesResolver) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// PoliciesResolver method of the parent MockResolver instance invokes the -// hook at the front of the queue and discards it. After the queue is empty, -// the default hook function is invoked for any future action. -func (f *ResolverPoliciesResolverFunc) PushHook(hook func() resolvers.PoliciesResolver) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverPoliciesResolverFunc) SetDefaultReturn(r0 resolvers.PoliciesResolver) { - f.SetDefaultHook(func() resolvers.PoliciesResolver { - return r0 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverPoliciesResolverFunc) PushReturn(r0 resolvers.PoliciesResolver) { - f.PushHook(func() resolvers.PoliciesResolver { - return r0 - }) -} - -func (f *ResolverPoliciesResolverFunc) nextHook() func() resolvers.PoliciesResolver { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverPoliciesResolverFunc) appendCall(r0 ResolverPoliciesResolverFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverPoliciesResolverFuncCall objects -// describing the invocations of this function. -func (f *ResolverPoliciesResolverFunc) History() []ResolverPoliciesResolverFuncCall { - f.mutex.Lock() - history := make([]ResolverPoliciesResolverFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverPoliciesResolverFuncCall is an object that describes an -// invocation of method PoliciesResolver on an instance of MockResolver. -type ResolverPoliciesResolverFuncCall struct { - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 resolvers.PoliciesResolver -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverPoliciesResolverFuncCall) Args() []interface{} { - return []interface{}{} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverPoliciesResolverFuncCall) Results() []interface{} { - return []interface{}{c.Result0} -} - -// ResolverUploadsResolverFunc describes the behavior when the -// UploadsResolver method of the parent MockResolver instance is invoked. -type ResolverUploadsResolverFunc struct { - defaultHook func() resolvers.UploadsResolver - hooks []func() resolvers.UploadsResolver - history []ResolverUploadsResolverFuncCall - mutex sync.Mutex -} - -// UploadsResolver delegates to the next hook function in the queue and -// stores the parameter and result values of this invocation. -func (m *MockResolver) UploadsResolver() resolvers.UploadsResolver { - r0 := m.UploadsResolverFunc.nextHook()() - m.UploadsResolverFunc.appendCall(ResolverUploadsResolverFuncCall{r0}) - return r0 -} - -// SetDefaultHook sets function that is called when the UploadsResolver -// method of the parent MockResolver instance is invoked and the hook queue -// is empty. -func (f *ResolverUploadsResolverFunc) SetDefaultHook(hook func() resolvers.UploadsResolver) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// UploadsResolver method of the parent MockResolver instance invokes the -// hook at the front of the queue and discards it. After the queue is empty, -// the default hook function is invoked for any future action. -func (f *ResolverUploadsResolverFunc) PushHook(hook func() resolvers.UploadsResolver) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverUploadsResolverFunc) SetDefaultReturn(r0 resolvers.UploadsResolver) { - f.SetDefaultHook(func() resolvers.UploadsResolver { - return r0 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverUploadsResolverFunc) PushReturn(r0 resolvers.UploadsResolver) { - f.PushHook(func() resolvers.UploadsResolver { - return r0 - }) -} - -func (f *ResolverUploadsResolverFunc) nextHook() func() resolvers.UploadsResolver { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverUploadsResolverFunc) appendCall(r0 ResolverUploadsResolverFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverUploadsResolverFuncCall objects -// describing the invocations of this function. -func (f *ResolverUploadsResolverFunc) History() []ResolverUploadsResolverFuncCall { - f.mutex.Lock() - history := make([]ResolverUploadsResolverFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverUploadsResolverFuncCall is an object that describes an invocation -// of method UploadsResolver on an instance of MockResolver. -type ResolverUploadsResolverFuncCall struct { - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 resolvers.UploadsResolver -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverUploadsResolverFuncCall) Args() []interface{} { - return []interface{}{} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverUploadsResolverFuncCall) Results() []interface{} { - return []interface{}{c.Result0} -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/mocks_temp.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/mocks_temp.go deleted file mode 100644 index 405e6cc7f65..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/mocks_temp.go +++ /dev/null @@ -1,1093 +0,0 @@ -// Code generated by go-mockgen 1.3.4; DO NOT EDIT. -// -// This file was generated by running `sg generate` (or `go-mockgen`) at the root of -// this repository. To add additional mocks to this or another package, add a new entry -// to the mockgen.yaml file in the root of this repository. - -package transport - -import ( - "context" - "sync" - - shared "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" - graphql "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql" -) - -// MockGitBlobLSIFDataResolver is a mock implementation of the -// GitBlobLSIFDataResolver interface (from the package -// github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql) -// used for unit testing. -type MockGitBlobLSIFDataResolver struct { - // DefinitionsFunc is an instance of a mock function object controlling - // the behavior of the method Definitions. - DefinitionsFunc *GitBlobLSIFDataResolverDefinitionsFunc - // DiagnosticsFunc is an instance of a mock function object controlling - // the behavior of the method Diagnostics. - DiagnosticsFunc *GitBlobLSIFDataResolverDiagnosticsFunc - // HoverFunc is an instance of a mock function object controlling the - // behavior of the method Hover. - HoverFunc *GitBlobLSIFDataResolverHoverFunc - // ImplementationsFunc is an instance of a mock function object - // controlling the behavior of the method Implementations. - ImplementationsFunc *GitBlobLSIFDataResolverImplementationsFunc - // LSIFUploadsFunc is an instance of a mock function object controlling - // the behavior of the method LSIFUploads. - LSIFUploadsFunc *GitBlobLSIFDataResolverLSIFUploadsFunc - // RangesFunc is an instance of a mock function object controlling the - // behavior of the method Ranges. - RangesFunc *GitBlobLSIFDataResolverRangesFunc - // ReferencesFunc is an instance of a mock function object controlling - // the behavior of the method References. - ReferencesFunc *GitBlobLSIFDataResolverReferencesFunc - // StencilFunc is an instance of a mock function object controlling the - // behavior of the method Stencil. - StencilFunc *GitBlobLSIFDataResolverStencilFunc -} - -// NewMockGitBlobLSIFDataResolver creates a new mock of the -// GitBlobLSIFDataResolver interface. All methods return zero values for all -// results, unless overwritten. -func NewMockGitBlobLSIFDataResolver() *MockGitBlobLSIFDataResolver { - return &MockGitBlobLSIFDataResolver{ - DefinitionsFunc: &GitBlobLSIFDataResolverDefinitionsFunc{ - defaultHook: func(context.Context, int, int) (r0 []shared.UploadLocation, r1 error) { - return - }, - }, - DiagnosticsFunc: &GitBlobLSIFDataResolverDiagnosticsFunc{ - defaultHook: func(context.Context, int) (r0 []shared.DiagnosticAtUpload, r1 int, r2 error) { - return - }, - }, - HoverFunc: &GitBlobLSIFDataResolverHoverFunc{ - defaultHook: func(context.Context, int, int) (r0 string, r1 shared.Range, r2 bool, r3 error) { - return - }, - }, - ImplementationsFunc: &GitBlobLSIFDataResolverImplementationsFunc{ - defaultHook: func(context.Context, int, int, int, string) (r0 []shared.UploadLocation, r1 string, r2 error) { - return - }, - }, - LSIFUploadsFunc: &GitBlobLSIFDataResolverLSIFUploadsFunc{ - defaultHook: func(context.Context) (r0 []shared.Dump, r1 error) { - return - }, - }, - RangesFunc: &GitBlobLSIFDataResolverRangesFunc{ - defaultHook: func(context.Context, int, int) (r0 []shared.AdjustedCodeIntelligenceRange, r1 error) { - return - }, - }, - ReferencesFunc: &GitBlobLSIFDataResolverReferencesFunc{ - defaultHook: func(context.Context, int, int, int, string) (r0 []shared.UploadLocation, r1 string, r2 error) { - return - }, - }, - StencilFunc: &GitBlobLSIFDataResolverStencilFunc{ - defaultHook: func(context.Context) (r0 []shared.Range, r1 error) { - return - }, - }, - } -} - -// NewStrictMockGitBlobLSIFDataResolver creates a new mock of the -// GitBlobLSIFDataResolver interface. All methods panic on invocation, -// unless overwritten. -func NewStrictMockGitBlobLSIFDataResolver() *MockGitBlobLSIFDataResolver { - return &MockGitBlobLSIFDataResolver{ - DefinitionsFunc: &GitBlobLSIFDataResolverDefinitionsFunc{ - defaultHook: func(context.Context, int, int) ([]shared.UploadLocation, error) { - panic("unexpected invocation of MockGitBlobLSIFDataResolver.Definitions") - }, - }, - DiagnosticsFunc: &GitBlobLSIFDataResolverDiagnosticsFunc{ - defaultHook: func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error) { - panic("unexpected invocation of MockGitBlobLSIFDataResolver.Diagnostics") - }, - }, - HoverFunc: &GitBlobLSIFDataResolverHoverFunc{ - defaultHook: func(context.Context, int, int) (string, shared.Range, bool, error) { - panic("unexpected invocation of MockGitBlobLSIFDataResolver.Hover") - }, - }, - ImplementationsFunc: &GitBlobLSIFDataResolverImplementationsFunc{ - defaultHook: func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error) { - panic("unexpected invocation of MockGitBlobLSIFDataResolver.Implementations") - }, - }, - LSIFUploadsFunc: &GitBlobLSIFDataResolverLSIFUploadsFunc{ - defaultHook: func(context.Context) ([]shared.Dump, error) { - panic("unexpected invocation of MockGitBlobLSIFDataResolver.LSIFUploads") - }, - }, - RangesFunc: &GitBlobLSIFDataResolverRangesFunc{ - defaultHook: func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error) { - panic("unexpected invocation of MockGitBlobLSIFDataResolver.Ranges") - }, - }, - ReferencesFunc: &GitBlobLSIFDataResolverReferencesFunc{ - defaultHook: func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error) { - panic("unexpected invocation of MockGitBlobLSIFDataResolver.References") - }, - }, - StencilFunc: &GitBlobLSIFDataResolverStencilFunc{ - defaultHook: func(context.Context) ([]shared.Range, error) { - panic("unexpected invocation of MockGitBlobLSIFDataResolver.Stencil") - }, - }, - } -} - -// NewMockGitBlobLSIFDataResolverFrom creates a new mock of the -// MockGitBlobLSIFDataResolver interface. All methods delegate to the given -// implementation, unless overwritten. -func NewMockGitBlobLSIFDataResolverFrom(i graphql.GitBlobLSIFDataResolver) *MockGitBlobLSIFDataResolver { - return &MockGitBlobLSIFDataResolver{ - DefinitionsFunc: &GitBlobLSIFDataResolverDefinitionsFunc{ - defaultHook: i.Definitions, - }, - DiagnosticsFunc: &GitBlobLSIFDataResolverDiagnosticsFunc{ - defaultHook: i.Diagnostics, - }, - HoverFunc: &GitBlobLSIFDataResolverHoverFunc{ - defaultHook: i.Hover, - }, - ImplementationsFunc: &GitBlobLSIFDataResolverImplementationsFunc{ - defaultHook: i.Implementations, - }, - LSIFUploadsFunc: &GitBlobLSIFDataResolverLSIFUploadsFunc{ - defaultHook: i.LSIFUploads, - }, - RangesFunc: &GitBlobLSIFDataResolverRangesFunc{ - defaultHook: i.Ranges, - }, - ReferencesFunc: &GitBlobLSIFDataResolverReferencesFunc{ - defaultHook: i.References, - }, - StencilFunc: &GitBlobLSIFDataResolverStencilFunc{ - defaultHook: i.Stencil, - }, - } -} - -// GitBlobLSIFDataResolverDefinitionsFunc describes the behavior when the -// Definitions method of the parent MockGitBlobLSIFDataResolver instance is -// invoked. -type GitBlobLSIFDataResolverDefinitionsFunc struct { - defaultHook func(context.Context, int, int) ([]shared.UploadLocation, error) - hooks []func(context.Context, int, int) ([]shared.UploadLocation, error) - history []GitBlobLSIFDataResolverDefinitionsFuncCall - mutex sync.Mutex -} - -// Definitions delegates to the next hook function in the queue and stores -// the parameter and result values of this invocation. -func (m *MockGitBlobLSIFDataResolver) Definitions(v0 context.Context, v1 int, v2 int) ([]shared.UploadLocation, error) { - r0, r1 := m.DefinitionsFunc.nextHook()(v0, v1, v2) - m.DefinitionsFunc.appendCall(GitBlobLSIFDataResolverDefinitionsFuncCall{v0, v1, v2, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the Definitions method -// of the parent MockGitBlobLSIFDataResolver instance is invoked and the -// hook queue is empty. -func (f *GitBlobLSIFDataResolverDefinitionsFunc) SetDefaultHook(hook func(context.Context, int, int) ([]shared.UploadLocation, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// Definitions method of the parent MockGitBlobLSIFDataResolver instance -// invokes the hook at the front of the queue and discards it. After the -// queue is empty, the default hook function is invoked for any future -// action. -func (f *GitBlobLSIFDataResolverDefinitionsFunc) PushHook(hook func(context.Context, int, int) ([]shared.UploadLocation, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *GitBlobLSIFDataResolverDefinitionsFunc) SetDefaultReturn(r0 []shared.UploadLocation, r1 error) { - f.SetDefaultHook(func(context.Context, int, int) ([]shared.UploadLocation, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *GitBlobLSIFDataResolverDefinitionsFunc) PushReturn(r0 []shared.UploadLocation, r1 error) { - f.PushHook(func(context.Context, int, int) ([]shared.UploadLocation, error) { - return r0, r1 - }) -} - -func (f *GitBlobLSIFDataResolverDefinitionsFunc) nextHook() func(context.Context, int, int) ([]shared.UploadLocation, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *GitBlobLSIFDataResolverDefinitionsFunc) appendCall(r0 GitBlobLSIFDataResolverDefinitionsFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of GitBlobLSIFDataResolverDefinitionsFuncCall -// objects describing the invocations of this function. -func (f *GitBlobLSIFDataResolverDefinitionsFunc) History() []GitBlobLSIFDataResolverDefinitionsFuncCall { - f.mutex.Lock() - history := make([]GitBlobLSIFDataResolverDefinitionsFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// GitBlobLSIFDataResolverDefinitionsFuncCall is an object that describes an -// invocation of method Definitions on an instance of -// MockGitBlobLSIFDataResolver. -type GitBlobLSIFDataResolverDefinitionsFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Arg2 is the value of the 3rd argument passed to this method - // invocation. - Arg2 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []shared.UploadLocation - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c GitBlobLSIFDataResolverDefinitionsFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1, c.Arg2} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c GitBlobLSIFDataResolverDefinitionsFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// GitBlobLSIFDataResolverDiagnosticsFunc describes the behavior when the -// Diagnostics method of the parent MockGitBlobLSIFDataResolver instance is -// invoked. -type GitBlobLSIFDataResolverDiagnosticsFunc struct { - defaultHook func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error) - hooks []func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error) - history []GitBlobLSIFDataResolverDiagnosticsFuncCall - mutex sync.Mutex -} - -// Diagnostics delegates to the next hook function in the queue and stores -// the parameter and result values of this invocation. -func (m *MockGitBlobLSIFDataResolver) Diagnostics(v0 context.Context, v1 int) ([]shared.DiagnosticAtUpload, int, error) { - r0, r1, r2 := m.DiagnosticsFunc.nextHook()(v0, v1) - m.DiagnosticsFunc.appendCall(GitBlobLSIFDataResolverDiagnosticsFuncCall{v0, v1, r0, r1, r2}) - return r0, r1, r2 -} - -// SetDefaultHook sets function that is called when the Diagnostics method -// of the parent MockGitBlobLSIFDataResolver instance is invoked and the -// hook queue is empty. -func (f *GitBlobLSIFDataResolverDiagnosticsFunc) SetDefaultHook(hook func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// Diagnostics method of the parent MockGitBlobLSIFDataResolver instance -// invokes the hook at the front of the queue and discards it. After the -// queue is empty, the default hook function is invoked for any future -// action. -func (f *GitBlobLSIFDataResolverDiagnosticsFunc) PushHook(hook func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *GitBlobLSIFDataResolverDiagnosticsFunc) SetDefaultReturn(r0 []shared.DiagnosticAtUpload, r1 int, r2 error) { - f.SetDefaultHook(func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error) { - return r0, r1, r2 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *GitBlobLSIFDataResolverDiagnosticsFunc) PushReturn(r0 []shared.DiagnosticAtUpload, r1 int, r2 error) { - f.PushHook(func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error) { - return r0, r1, r2 - }) -} - -func (f *GitBlobLSIFDataResolverDiagnosticsFunc) nextHook() func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *GitBlobLSIFDataResolverDiagnosticsFunc) appendCall(r0 GitBlobLSIFDataResolverDiagnosticsFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of GitBlobLSIFDataResolverDiagnosticsFuncCall -// objects describing the invocations of this function. -func (f *GitBlobLSIFDataResolverDiagnosticsFunc) History() []GitBlobLSIFDataResolverDiagnosticsFuncCall { - f.mutex.Lock() - history := make([]GitBlobLSIFDataResolverDiagnosticsFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// GitBlobLSIFDataResolverDiagnosticsFuncCall is an object that describes an -// invocation of method Diagnostics on an instance of -// MockGitBlobLSIFDataResolver. -type GitBlobLSIFDataResolverDiagnosticsFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []shared.DiagnosticAtUpload - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 int - // Result2 is the value of the 3rd result returned from this method - // invocation. - Result2 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c GitBlobLSIFDataResolverDiagnosticsFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c GitBlobLSIFDataResolverDiagnosticsFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1, c.Result2} -} - -// GitBlobLSIFDataResolverHoverFunc describes the behavior when the Hover -// method of the parent MockGitBlobLSIFDataResolver instance is invoked. -type GitBlobLSIFDataResolverHoverFunc struct { - defaultHook func(context.Context, int, int) (string, shared.Range, bool, error) - hooks []func(context.Context, int, int) (string, shared.Range, bool, error) - history []GitBlobLSIFDataResolverHoverFuncCall - mutex sync.Mutex -} - -// Hover delegates to the next hook function in the queue and stores the -// parameter and result values of this invocation. -func (m *MockGitBlobLSIFDataResolver) Hover(v0 context.Context, v1 int, v2 int) (string, shared.Range, bool, error) { - r0, r1, r2, r3 := m.HoverFunc.nextHook()(v0, v1, v2) - m.HoverFunc.appendCall(GitBlobLSIFDataResolverHoverFuncCall{v0, v1, v2, r0, r1, r2, r3}) - return r0, r1, r2, r3 -} - -// SetDefaultHook sets function that is called when the Hover method of the -// parent MockGitBlobLSIFDataResolver instance is invoked and the hook queue -// is empty. -func (f *GitBlobLSIFDataResolverHoverFunc) SetDefaultHook(hook func(context.Context, int, int) (string, shared.Range, bool, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// Hover method of the parent MockGitBlobLSIFDataResolver instance invokes -// the hook at the front of the queue and discards it. After the queue is -// empty, the default hook function is invoked for any future action. -func (f *GitBlobLSIFDataResolverHoverFunc) PushHook(hook func(context.Context, int, int) (string, shared.Range, bool, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *GitBlobLSIFDataResolverHoverFunc) SetDefaultReturn(r0 string, r1 shared.Range, r2 bool, r3 error) { - f.SetDefaultHook(func(context.Context, int, int) (string, shared.Range, bool, error) { - return r0, r1, r2, r3 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *GitBlobLSIFDataResolverHoverFunc) PushReturn(r0 string, r1 shared.Range, r2 bool, r3 error) { - f.PushHook(func(context.Context, int, int) (string, shared.Range, bool, error) { - return r0, r1, r2, r3 - }) -} - -func (f *GitBlobLSIFDataResolverHoverFunc) nextHook() func(context.Context, int, int) (string, shared.Range, bool, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *GitBlobLSIFDataResolverHoverFunc) appendCall(r0 GitBlobLSIFDataResolverHoverFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of GitBlobLSIFDataResolverHoverFuncCall -// objects describing the invocations of this function. -func (f *GitBlobLSIFDataResolverHoverFunc) History() []GitBlobLSIFDataResolverHoverFuncCall { - f.mutex.Lock() - history := make([]GitBlobLSIFDataResolverHoverFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// GitBlobLSIFDataResolverHoverFuncCall is an object that describes an -// invocation of method Hover on an instance of MockGitBlobLSIFDataResolver. -type GitBlobLSIFDataResolverHoverFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Arg2 is the value of the 3rd argument passed to this method - // invocation. - Arg2 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 string - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 shared.Range - // Result2 is the value of the 3rd result returned from this method - // invocation. - Result2 bool - // Result3 is the value of the 4th result returned from this method - // invocation. - Result3 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c GitBlobLSIFDataResolverHoverFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1, c.Arg2} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c GitBlobLSIFDataResolverHoverFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1, c.Result2, c.Result3} -} - -// GitBlobLSIFDataResolverImplementationsFunc describes the behavior when -// the Implementations method of the parent MockGitBlobLSIFDataResolver -// instance is invoked. -type GitBlobLSIFDataResolverImplementationsFunc struct { - defaultHook func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error) - hooks []func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error) - history []GitBlobLSIFDataResolverImplementationsFuncCall - mutex sync.Mutex -} - -// Implementations delegates to the next hook function in the queue and -// stores the parameter and result values of this invocation. -func (m *MockGitBlobLSIFDataResolver) Implementations(v0 context.Context, v1 int, v2 int, v3 int, v4 string) ([]shared.UploadLocation, string, error) { - r0, r1, r2 := m.ImplementationsFunc.nextHook()(v0, v1, v2, v3, v4) - m.ImplementationsFunc.appendCall(GitBlobLSIFDataResolverImplementationsFuncCall{v0, v1, v2, v3, v4, r0, r1, r2}) - return r0, r1, r2 -} - -// SetDefaultHook sets function that is called when the Implementations -// method of the parent MockGitBlobLSIFDataResolver instance is invoked and -// the hook queue is empty. -func (f *GitBlobLSIFDataResolverImplementationsFunc) SetDefaultHook(hook func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// Implementations method of the parent MockGitBlobLSIFDataResolver instance -// invokes the hook at the front of the queue and discards it. After the -// queue is empty, the default hook function is invoked for any future -// action. -func (f *GitBlobLSIFDataResolverImplementationsFunc) PushHook(hook func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *GitBlobLSIFDataResolverImplementationsFunc) SetDefaultReturn(r0 []shared.UploadLocation, r1 string, r2 error) { - f.SetDefaultHook(func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error) { - return r0, r1, r2 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *GitBlobLSIFDataResolverImplementationsFunc) PushReturn(r0 []shared.UploadLocation, r1 string, r2 error) { - f.PushHook(func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error) { - return r0, r1, r2 - }) -} - -func (f *GitBlobLSIFDataResolverImplementationsFunc) nextHook() func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *GitBlobLSIFDataResolverImplementationsFunc) appendCall(r0 GitBlobLSIFDataResolverImplementationsFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of -// GitBlobLSIFDataResolverImplementationsFuncCall objects describing the -// invocations of this function. -func (f *GitBlobLSIFDataResolverImplementationsFunc) History() []GitBlobLSIFDataResolverImplementationsFuncCall { - f.mutex.Lock() - history := make([]GitBlobLSIFDataResolverImplementationsFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// GitBlobLSIFDataResolverImplementationsFuncCall is an object that -// describes an invocation of method Implementations on an instance of -// MockGitBlobLSIFDataResolver. -type GitBlobLSIFDataResolverImplementationsFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Arg2 is the value of the 3rd argument passed to this method - // invocation. - Arg2 int - // Arg3 is the value of the 4th argument passed to this method - // invocation. - Arg3 int - // Arg4 is the value of the 5th argument passed to this method - // invocation. - Arg4 string - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []shared.UploadLocation - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 string - // Result2 is the value of the 3rd result returned from this method - // invocation. - Result2 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c GitBlobLSIFDataResolverImplementationsFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3, c.Arg4} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c GitBlobLSIFDataResolverImplementationsFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1, c.Result2} -} - -// GitBlobLSIFDataResolverLSIFUploadsFunc describes the behavior when the -// LSIFUploads method of the parent MockGitBlobLSIFDataResolver instance is -// invoked. -type GitBlobLSIFDataResolverLSIFUploadsFunc struct { - defaultHook func(context.Context) ([]shared.Dump, error) - hooks []func(context.Context) ([]shared.Dump, error) - history []GitBlobLSIFDataResolverLSIFUploadsFuncCall - mutex sync.Mutex -} - -// LSIFUploads delegates to the next hook function in the queue and stores -// the parameter and result values of this invocation. -func (m *MockGitBlobLSIFDataResolver) LSIFUploads(v0 context.Context) ([]shared.Dump, error) { - r0, r1 := m.LSIFUploadsFunc.nextHook()(v0) - m.LSIFUploadsFunc.appendCall(GitBlobLSIFDataResolverLSIFUploadsFuncCall{v0, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the LSIFUploads method -// of the parent MockGitBlobLSIFDataResolver instance is invoked and the -// hook queue is empty. -func (f *GitBlobLSIFDataResolverLSIFUploadsFunc) SetDefaultHook(hook func(context.Context) ([]shared.Dump, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// LSIFUploads method of the parent MockGitBlobLSIFDataResolver instance -// invokes the hook at the front of the queue and discards it. After the -// queue is empty, the default hook function is invoked for any future -// action. -func (f *GitBlobLSIFDataResolverLSIFUploadsFunc) PushHook(hook func(context.Context) ([]shared.Dump, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *GitBlobLSIFDataResolverLSIFUploadsFunc) SetDefaultReturn(r0 []shared.Dump, r1 error) { - f.SetDefaultHook(func(context.Context) ([]shared.Dump, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *GitBlobLSIFDataResolverLSIFUploadsFunc) PushReturn(r0 []shared.Dump, r1 error) { - f.PushHook(func(context.Context) ([]shared.Dump, error) { - return r0, r1 - }) -} - -func (f *GitBlobLSIFDataResolverLSIFUploadsFunc) nextHook() func(context.Context) ([]shared.Dump, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *GitBlobLSIFDataResolverLSIFUploadsFunc) appendCall(r0 GitBlobLSIFDataResolverLSIFUploadsFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of GitBlobLSIFDataResolverLSIFUploadsFuncCall -// objects describing the invocations of this function. -func (f *GitBlobLSIFDataResolverLSIFUploadsFunc) History() []GitBlobLSIFDataResolverLSIFUploadsFuncCall { - f.mutex.Lock() - history := make([]GitBlobLSIFDataResolverLSIFUploadsFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// GitBlobLSIFDataResolverLSIFUploadsFuncCall is an object that describes an -// invocation of method LSIFUploads on an instance of -// MockGitBlobLSIFDataResolver. -type GitBlobLSIFDataResolverLSIFUploadsFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []shared.Dump - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c GitBlobLSIFDataResolverLSIFUploadsFuncCall) Args() []interface{} { - return []interface{}{c.Arg0} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c GitBlobLSIFDataResolverLSIFUploadsFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// GitBlobLSIFDataResolverRangesFunc describes the behavior when the Ranges -// method of the parent MockGitBlobLSIFDataResolver instance is invoked. -type GitBlobLSIFDataResolverRangesFunc struct { - defaultHook func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error) - hooks []func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error) - history []GitBlobLSIFDataResolverRangesFuncCall - mutex sync.Mutex -} - -// Ranges delegates to the next hook function in the queue and stores the -// parameter and result values of this invocation. -func (m *MockGitBlobLSIFDataResolver) Ranges(v0 context.Context, v1 int, v2 int) ([]shared.AdjustedCodeIntelligenceRange, error) { - r0, r1 := m.RangesFunc.nextHook()(v0, v1, v2) - m.RangesFunc.appendCall(GitBlobLSIFDataResolverRangesFuncCall{v0, v1, v2, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the Ranges method of the -// parent MockGitBlobLSIFDataResolver instance is invoked and the hook queue -// is empty. -func (f *GitBlobLSIFDataResolverRangesFunc) SetDefaultHook(hook func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// Ranges method of the parent MockGitBlobLSIFDataResolver instance invokes -// the hook at the front of the queue and discards it. After the queue is -// empty, the default hook function is invoked for any future action. -func (f *GitBlobLSIFDataResolverRangesFunc) PushHook(hook func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *GitBlobLSIFDataResolverRangesFunc) SetDefaultReturn(r0 []shared.AdjustedCodeIntelligenceRange, r1 error) { - f.SetDefaultHook(func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *GitBlobLSIFDataResolverRangesFunc) PushReturn(r0 []shared.AdjustedCodeIntelligenceRange, r1 error) { - f.PushHook(func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error) { - return r0, r1 - }) -} - -func (f *GitBlobLSIFDataResolverRangesFunc) nextHook() func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *GitBlobLSIFDataResolverRangesFunc) appendCall(r0 GitBlobLSIFDataResolverRangesFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of GitBlobLSIFDataResolverRangesFuncCall -// objects describing the invocations of this function. -func (f *GitBlobLSIFDataResolverRangesFunc) History() []GitBlobLSIFDataResolverRangesFuncCall { - f.mutex.Lock() - history := make([]GitBlobLSIFDataResolverRangesFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// GitBlobLSIFDataResolverRangesFuncCall is an object that describes an -// invocation of method Ranges on an instance of -// MockGitBlobLSIFDataResolver. -type GitBlobLSIFDataResolverRangesFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Arg2 is the value of the 3rd argument passed to this method - // invocation. - Arg2 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []shared.AdjustedCodeIntelligenceRange - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c GitBlobLSIFDataResolverRangesFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1, c.Arg2} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c GitBlobLSIFDataResolverRangesFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// GitBlobLSIFDataResolverReferencesFunc describes the behavior when the -// References method of the parent MockGitBlobLSIFDataResolver instance is -// invoked. -type GitBlobLSIFDataResolverReferencesFunc struct { - defaultHook func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error) - hooks []func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error) - history []GitBlobLSIFDataResolverReferencesFuncCall - mutex sync.Mutex -} - -// References delegates to the next hook function in the queue and stores -// the parameter and result values of this invocation. -func (m *MockGitBlobLSIFDataResolver) References(v0 context.Context, v1 int, v2 int, v3 int, v4 string) ([]shared.UploadLocation, string, error) { - r0, r1, r2 := m.ReferencesFunc.nextHook()(v0, v1, v2, v3, v4) - m.ReferencesFunc.appendCall(GitBlobLSIFDataResolverReferencesFuncCall{v0, v1, v2, v3, v4, r0, r1, r2}) - return r0, r1, r2 -} - -// SetDefaultHook sets function that is called when the References method of -// the parent MockGitBlobLSIFDataResolver instance is invoked and the hook -// queue is empty. -func (f *GitBlobLSIFDataResolverReferencesFunc) SetDefaultHook(hook func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// References method of the parent MockGitBlobLSIFDataResolver instance -// invokes the hook at the front of the queue and discards it. After the -// queue is empty, the default hook function is invoked for any future -// action. -func (f *GitBlobLSIFDataResolverReferencesFunc) PushHook(hook func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *GitBlobLSIFDataResolverReferencesFunc) SetDefaultReturn(r0 []shared.UploadLocation, r1 string, r2 error) { - f.SetDefaultHook(func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error) { - return r0, r1, r2 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *GitBlobLSIFDataResolverReferencesFunc) PushReturn(r0 []shared.UploadLocation, r1 string, r2 error) { - f.PushHook(func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error) { - return r0, r1, r2 - }) -} - -func (f *GitBlobLSIFDataResolverReferencesFunc) nextHook() func(context.Context, int, int, int, string) ([]shared.UploadLocation, string, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *GitBlobLSIFDataResolverReferencesFunc) appendCall(r0 GitBlobLSIFDataResolverReferencesFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of GitBlobLSIFDataResolverReferencesFuncCall -// objects describing the invocations of this function. -func (f *GitBlobLSIFDataResolverReferencesFunc) History() []GitBlobLSIFDataResolverReferencesFuncCall { - f.mutex.Lock() - history := make([]GitBlobLSIFDataResolverReferencesFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// GitBlobLSIFDataResolverReferencesFuncCall is an object that describes an -// invocation of method References on an instance of -// MockGitBlobLSIFDataResolver. -type GitBlobLSIFDataResolverReferencesFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Arg2 is the value of the 3rd argument passed to this method - // invocation. - Arg2 int - // Arg3 is the value of the 4th argument passed to this method - // invocation. - Arg3 int - // Arg4 is the value of the 5th argument passed to this method - // invocation. - Arg4 string - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []shared.UploadLocation - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 string - // Result2 is the value of the 3rd result returned from this method - // invocation. - Result2 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c GitBlobLSIFDataResolverReferencesFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3, c.Arg4} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c GitBlobLSIFDataResolverReferencesFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1, c.Result2} -} - -// GitBlobLSIFDataResolverStencilFunc describes the behavior when the -// Stencil method of the parent MockGitBlobLSIFDataResolver instance is -// invoked. -type GitBlobLSIFDataResolverStencilFunc struct { - defaultHook func(context.Context) ([]shared.Range, error) - hooks []func(context.Context) ([]shared.Range, error) - history []GitBlobLSIFDataResolverStencilFuncCall - mutex sync.Mutex -} - -// Stencil delegates to the next hook function in the queue and stores the -// parameter and result values of this invocation. -func (m *MockGitBlobLSIFDataResolver) Stencil(v0 context.Context) ([]shared.Range, error) { - r0, r1 := m.StencilFunc.nextHook()(v0) - m.StencilFunc.appendCall(GitBlobLSIFDataResolverStencilFuncCall{v0, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the Stencil method of -// the parent MockGitBlobLSIFDataResolver instance is invoked and the hook -// queue is empty. -func (f *GitBlobLSIFDataResolverStencilFunc) SetDefaultHook(hook func(context.Context) ([]shared.Range, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// Stencil method of the parent MockGitBlobLSIFDataResolver instance invokes -// the hook at the front of the queue and discards it. After the queue is -// empty, the default hook function is invoked for any future action. -func (f *GitBlobLSIFDataResolverStencilFunc) PushHook(hook func(context.Context) ([]shared.Range, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *GitBlobLSIFDataResolverStencilFunc) SetDefaultReturn(r0 []shared.Range, r1 error) { - f.SetDefaultHook(func(context.Context) ([]shared.Range, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *GitBlobLSIFDataResolverStencilFunc) PushReturn(r0 []shared.Range, r1 error) { - f.PushHook(func(context.Context) ([]shared.Range, error) { - return r0, r1 - }) -} - -func (f *GitBlobLSIFDataResolverStencilFunc) nextHook() func(context.Context) ([]shared.Range, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *GitBlobLSIFDataResolverStencilFunc) appendCall(r0 GitBlobLSIFDataResolverStencilFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of GitBlobLSIFDataResolverStencilFuncCall -// objects describing the invocations of this function. -func (f *GitBlobLSIFDataResolverStencilFunc) History() []GitBlobLSIFDataResolverStencilFuncCall { - f.mutex.Lock() - history := make([]GitBlobLSIFDataResolverStencilFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// GitBlobLSIFDataResolverStencilFuncCall is an object that describes an -// invocation of method Stencil on an instance of -// MockGitBlobLSIFDataResolver. -type GitBlobLSIFDataResolverStencilFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []shared.Range - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c GitBlobLSIFDataResolverStencilFuncCall) Args() []interface{} { - return []interface{}{c.Arg0} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c GitBlobLSIFDataResolverStencilFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/mocks_temps.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/mocks_temps.go deleted file mode 100644 index 680efb0827d..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/mocks_temps.go +++ /dev/null @@ -1,1462 +0,0 @@ -// Code generated by go-mockgen 1.3.4; DO NOT EDIT. -// -// This file was generated by running `sg generate` (or `go-mockgen`) at the root of -// this repository. To add additional mocks to this or another package, add a new entry -// to the mockgen.yaml file in the root of this repository. - -package transport - -import ( - "context" - "sync" - "time" - - shared "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" - graphql "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/transport/graphql" - config "github.com/sourcegraph/sourcegraph/lib/codeintel/autoindex/config" -) - -// MockResolver is a mock implementation of the Resolver interface (from the -// package -// github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/transport/graphql) -// used for unit testing. -type MockResolver struct { - // DeleteIndexByIDFunc is an instance of a mock function object - // controlling the behavior of the method DeleteIndexByID. - DeleteIndexByIDFunc *ResolverDeleteIndexByIDFunc - // GetIndexByIDFunc is an instance of a mock function object controlling - // the behavior of the method GetIndexByID. - GetIndexByIDFunc *ResolverGetIndexByIDFunc - // GetIndexConfigurationFunc is an instance of a mock function object - // controlling the behavior of the method GetIndexConfiguration. - GetIndexConfigurationFunc *ResolverGetIndexConfigurationFunc - // GetIndexesByIDsFunc is an instance of a mock function object - // controlling the behavior of the method GetIndexesByIDs. - GetIndexesByIDsFunc *ResolverGetIndexesByIDsFunc - // GetLastIndexScanForRepositoryFunc is an instance of a mock function - // object controlling the behavior of the method - // GetLastIndexScanForRepository. - GetLastIndexScanForRepositoryFunc *ResolverGetLastIndexScanForRepositoryFunc - // GetRecentIndexesSummaryFunc is an instance of a mock function object - // controlling the behavior of the method GetRecentIndexesSummary. - GetRecentIndexesSummaryFunc *ResolverGetRecentIndexesSummaryFunc - // IndexConnectionResolverFromFactoryFunc is an instance of a mock - // function object controlling the behavior of the method - // IndexConnectionResolverFromFactory. - IndexConnectionResolverFromFactoryFunc *ResolverIndexConnectionResolverFromFactoryFunc - // InferedIndexConfigurationFunc is an instance of a mock function - // object controlling the behavior of the method - // InferedIndexConfiguration. - InferedIndexConfigurationFunc *ResolverInferedIndexConfigurationFunc - // InferedIndexConfigurationHintsFunc is an instance of a mock function - // object controlling the behavior of the method - // InferedIndexConfigurationHints. - InferedIndexConfigurationHintsFunc *ResolverInferedIndexConfigurationHintsFunc - // QueueAutoIndexJobsForRepoFunc is an instance of a mock function - // object controlling the behavior of the method - // QueueAutoIndexJobsForRepo. - QueueAutoIndexJobsForRepoFunc *ResolverQueueAutoIndexJobsForRepoFunc - // UpdateIndexConfigurationByRepositoryIDFunc is an instance of a mock - // function object controlling the behavior of the method - // UpdateIndexConfigurationByRepositoryID. - UpdateIndexConfigurationByRepositoryIDFunc *ResolverUpdateIndexConfigurationByRepositoryIDFunc -} - -// NewMockResolver creates a new mock of the Resolver interface. All methods -// return zero values for all results, unless overwritten. -func NewMockResolver() *MockResolver { - return &MockResolver{ - DeleteIndexByIDFunc: &ResolverDeleteIndexByIDFunc{ - defaultHook: func(context.Context, int) (r0 error) { - return - }, - }, - GetIndexByIDFunc: &ResolverGetIndexByIDFunc{ - defaultHook: func(context.Context, int) (r0 shared.Index, r1 bool, r2 error) { - return - }, - }, - GetIndexConfigurationFunc: &ResolverGetIndexConfigurationFunc{ - defaultHook: func(context.Context, int) (r0 []byte, r1 bool, r2 error) { - return - }, - }, - GetIndexesByIDsFunc: &ResolverGetIndexesByIDsFunc{ - defaultHook: func(context.Context, ...int) (r0 []shared.Index, r1 error) { - return - }, - }, - GetLastIndexScanForRepositoryFunc: &ResolverGetLastIndexScanForRepositoryFunc{ - defaultHook: func(context.Context, int) (r0 *time.Time, r1 error) { - return - }, - }, - GetRecentIndexesSummaryFunc: &ResolverGetRecentIndexesSummaryFunc{ - defaultHook: func(context.Context, int) (r0 []shared.IndexesWithRepositoryNamespace, r1 error) { - return - }, - }, - IndexConnectionResolverFromFactoryFunc: &ResolverIndexConnectionResolverFromFactoryFunc{ - defaultHook: func(shared.GetIndexesOptions) (r0 *graphql.IndexesResolver) { - return - }, - }, - InferedIndexConfigurationFunc: &ResolverInferedIndexConfigurationFunc{ - defaultHook: func(context.Context, int, string) (r0 *config.IndexConfiguration, r1 bool, r2 error) { - return - }, - }, - InferedIndexConfigurationHintsFunc: &ResolverInferedIndexConfigurationHintsFunc{ - defaultHook: func(context.Context, int, string) (r0 []config.IndexJobHint, r1 error) { - return - }, - }, - QueueAutoIndexJobsForRepoFunc: &ResolverQueueAutoIndexJobsForRepoFunc{ - defaultHook: func(context.Context, int, string, string) (r0 []shared.Index, r1 error) { - return - }, - }, - UpdateIndexConfigurationByRepositoryIDFunc: &ResolverUpdateIndexConfigurationByRepositoryIDFunc{ - defaultHook: func(context.Context, int, string) (r0 error) { - return - }, - }, - } -} - -// NewStrictMockResolver creates a new mock of the Resolver interface. All -// methods panic on invocation, unless overwritten. -func NewStrictMockResolver() *MockResolver { - return &MockResolver{ - DeleteIndexByIDFunc: &ResolverDeleteIndexByIDFunc{ - defaultHook: func(context.Context, int) error { - panic("unexpected invocation of MockResolver.DeleteIndexByID") - }, - }, - GetIndexByIDFunc: &ResolverGetIndexByIDFunc{ - defaultHook: func(context.Context, int) (shared.Index, bool, error) { - panic("unexpected invocation of MockResolver.GetIndexByID") - }, - }, - GetIndexConfigurationFunc: &ResolverGetIndexConfigurationFunc{ - defaultHook: func(context.Context, int) ([]byte, bool, error) { - panic("unexpected invocation of MockResolver.GetIndexConfiguration") - }, - }, - GetIndexesByIDsFunc: &ResolverGetIndexesByIDsFunc{ - defaultHook: func(context.Context, ...int) ([]shared.Index, error) { - panic("unexpected invocation of MockResolver.GetIndexesByIDs") - }, - }, - GetLastIndexScanForRepositoryFunc: &ResolverGetLastIndexScanForRepositoryFunc{ - defaultHook: func(context.Context, int) (*time.Time, error) { - panic("unexpected invocation of MockResolver.GetLastIndexScanForRepository") - }, - }, - GetRecentIndexesSummaryFunc: &ResolverGetRecentIndexesSummaryFunc{ - defaultHook: func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error) { - panic("unexpected invocation of MockResolver.GetRecentIndexesSummary") - }, - }, - IndexConnectionResolverFromFactoryFunc: &ResolverIndexConnectionResolverFromFactoryFunc{ - defaultHook: func(shared.GetIndexesOptions) *graphql.IndexesResolver { - panic("unexpected invocation of MockResolver.IndexConnectionResolverFromFactory") - }, - }, - InferedIndexConfigurationFunc: &ResolverInferedIndexConfigurationFunc{ - defaultHook: func(context.Context, int, string) (*config.IndexConfiguration, bool, error) { - panic("unexpected invocation of MockResolver.InferedIndexConfiguration") - }, - }, - InferedIndexConfigurationHintsFunc: &ResolverInferedIndexConfigurationHintsFunc{ - defaultHook: func(context.Context, int, string) ([]config.IndexJobHint, error) { - panic("unexpected invocation of MockResolver.InferedIndexConfigurationHints") - }, - }, - QueueAutoIndexJobsForRepoFunc: &ResolverQueueAutoIndexJobsForRepoFunc{ - defaultHook: func(context.Context, int, string, string) ([]shared.Index, error) { - panic("unexpected invocation of MockResolver.QueueAutoIndexJobsForRepo") - }, - }, - UpdateIndexConfigurationByRepositoryIDFunc: &ResolverUpdateIndexConfigurationByRepositoryIDFunc{ - defaultHook: func(context.Context, int, string) error { - panic("unexpected invocation of MockResolver.UpdateIndexConfigurationByRepositoryID") - }, - }, - } -} - -// NewMockResolverFrom creates a new mock of the MockResolver interface. All -// methods delegate to the given implementation, unless overwritten. -func NewMockResolverFrom(i graphql.Resolver) *MockResolver { - return &MockResolver{ - DeleteIndexByIDFunc: &ResolverDeleteIndexByIDFunc{ - defaultHook: i.DeleteIndexByID, - }, - GetIndexByIDFunc: &ResolverGetIndexByIDFunc{ - defaultHook: i.GetIndexByID, - }, - GetIndexConfigurationFunc: &ResolverGetIndexConfigurationFunc{ - defaultHook: i.GetIndexConfiguration, - }, - GetIndexesByIDsFunc: &ResolverGetIndexesByIDsFunc{ - defaultHook: i.GetIndexesByIDs, - }, - GetLastIndexScanForRepositoryFunc: &ResolverGetLastIndexScanForRepositoryFunc{ - defaultHook: i.GetLastIndexScanForRepository, - }, - GetRecentIndexesSummaryFunc: &ResolverGetRecentIndexesSummaryFunc{ - defaultHook: i.GetRecentIndexesSummary, - }, - IndexConnectionResolverFromFactoryFunc: &ResolverIndexConnectionResolverFromFactoryFunc{ - defaultHook: i.IndexConnectionResolverFromFactory, - }, - InferedIndexConfigurationFunc: &ResolverInferedIndexConfigurationFunc{ - defaultHook: i.InferedIndexConfiguration, - }, - InferedIndexConfigurationHintsFunc: &ResolverInferedIndexConfigurationHintsFunc{ - defaultHook: i.InferedIndexConfigurationHints, - }, - QueueAutoIndexJobsForRepoFunc: &ResolverQueueAutoIndexJobsForRepoFunc{ - defaultHook: i.QueueAutoIndexJobsForRepo, - }, - UpdateIndexConfigurationByRepositoryIDFunc: &ResolverUpdateIndexConfigurationByRepositoryIDFunc{ - defaultHook: i.UpdateIndexConfigurationByRepositoryID, - }, - } -} - -// ResolverDeleteIndexByIDFunc describes the behavior when the -// DeleteIndexByID method of the parent MockResolver instance is invoked. -type ResolverDeleteIndexByIDFunc struct { - defaultHook func(context.Context, int) error - hooks []func(context.Context, int) error - history []ResolverDeleteIndexByIDFuncCall - mutex sync.Mutex -} - -// DeleteIndexByID delegates to the next hook function in the queue and -// stores the parameter and result values of this invocation. -func (m *MockResolver) DeleteIndexByID(v0 context.Context, v1 int) error { - r0 := m.DeleteIndexByIDFunc.nextHook()(v0, v1) - m.DeleteIndexByIDFunc.appendCall(ResolverDeleteIndexByIDFuncCall{v0, v1, r0}) - return r0 -} - -// SetDefaultHook sets function that is called when the DeleteIndexByID -// method of the parent MockResolver instance is invoked and the hook queue -// is empty. -func (f *ResolverDeleteIndexByIDFunc) SetDefaultHook(hook func(context.Context, int) error) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// DeleteIndexByID method of the parent MockResolver instance invokes the -// hook at the front of the queue and discards it. After the queue is empty, -// the default hook function is invoked for any future action. -func (f *ResolverDeleteIndexByIDFunc) PushHook(hook func(context.Context, int) error) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverDeleteIndexByIDFunc) SetDefaultReturn(r0 error) { - f.SetDefaultHook(func(context.Context, int) error { - return r0 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverDeleteIndexByIDFunc) PushReturn(r0 error) { - f.PushHook(func(context.Context, int) error { - return r0 - }) -} - -func (f *ResolverDeleteIndexByIDFunc) nextHook() func(context.Context, int) error { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverDeleteIndexByIDFunc) appendCall(r0 ResolverDeleteIndexByIDFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverDeleteIndexByIDFuncCall objects -// describing the invocations of this function. -func (f *ResolverDeleteIndexByIDFunc) History() []ResolverDeleteIndexByIDFuncCall { - f.mutex.Lock() - history := make([]ResolverDeleteIndexByIDFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverDeleteIndexByIDFuncCall is an object that describes an invocation -// of method DeleteIndexByID on an instance of MockResolver. -type ResolverDeleteIndexByIDFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverDeleteIndexByIDFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverDeleteIndexByIDFuncCall) Results() []interface{} { - return []interface{}{c.Result0} -} - -// ResolverGetIndexByIDFunc describes the behavior when the GetIndexByID -// method of the parent MockResolver instance is invoked. -type ResolverGetIndexByIDFunc struct { - defaultHook func(context.Context, int) (shared.Index, bool, error) - hooks []func(context.Context, int) (shared.Index, bool, error) - history []ResolverGetIndexByIDFuncCall - mutex sync.Mutex -} - -// GetIndexByID delegates to the next hook function in the queue and stores -// the parameter and result values of this invocation. -func (m *MockResolver) GetIndexByID(v0 context.Context, v1 int) (shared.Index, bool, error) { - r0, r1, r2 := m.GetIndexByIDFunc.nextHook()(v0, v1) - m.GetIndexByIDFunc.appendCall(ResolverGetIndexByIDFuncCall{v0, v1, r0, r1, r2}) - return r0, r1, r2 -} - -// SetDefaultHook sets function that is called when the GetIndexByID method -// of the parent MockResolver instance is invoked and the hook queue is -// empty. -func (f *ResolverGetIndexByIDFunc) SetDefaultHook(hook func(context.Context, int) (shared.Index, bool, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// GetIndexByID method of the parent MockResolver instance invokes the hook -// at the front of the queue and discards it. After the queue is empty, the -// default hook function is invoked for any future action. -func (f *ResolverGetIndexByIDFunc) PushHook(hook func(context.Context, int) (shared.Index, bool, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverGetIndexByIDFunc) SetDefaultReturn(r0 shared.Index, r1 bool, r2 error) { - f.SetDefaultHook(func(context.Context, int) (shared.Index, bool, error) { - return r0, r1, r2 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverGetIndexByIDFunc) PushReturn(r0 shared.Index, r1 bool, r2 error) { - f.PushHook(func(context.Context, int) (shared.Index, bool, error) { - return r0, r1, r2 - }) -} - -func (f *ResolverGetIndexByIDFunc) nextHook() func(context.Context, int) (shared.Index, bool, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverGetIndexByIDFunc) appendCall(r0 ResolverGetIndexByIDFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverGetIndexByIDFuncCall objects -// describing the invocations of this function. -func (f *ResolverGetIndexByIDFunc) History() []ResolverGetIndexByIDFuncCall { - f.mutex.Lock() - history := make([]ResolverGetIndexByIDFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverGetIndexByIDFuncCall is an object that describes an invocation of -// method GetIndexByID on an instance of MockResolver. -type ResolverGetIndexByIDFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 shared.Index - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 bool - // Result2 is the value of the 3rd result returned from this method - // invocation. - Result2 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverGetIndexByIDFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverGetIndexByIDFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1, c.Result2} -} - -// ResolverGetIndexConfigurationFunc describes the behavior when the -// GetIndexConfiguration method of the parent MockResolver instance is -// invoked. -type ResolverGetIndexConfigurationFunc struct { - defaultHook func(context.Context, int) ([]byte, bool, error) - hooks []func(context.Context, int) ([]byte, bool, error) - history []ResolverGetIndexConfigurationFuncCall - mutex sync.Mutex -} - -// GetIndexConfiguration delegates to the next hook function in the queue -// and stores the parameter and result values of this invocation. -func (m *MockResolver) GetIndexConfiguration(v0 context.Context, v1 int) ([]byte, bool, error) { - r0, r1, r2 := m.GetIndexConfigurationFunc.nextHook()(v0, v1) - m.GetIndexConfigurationFunc.appendCall(ResolverGetIndexConfigurationFuncCall{v0, v1, r0, r1, r2}) - return r0, r1, r2 -} - -// SetDefaultHook sets function that is called when the -// GetIndexConfiguration method of the parent MockResolver instance is -// invoked and the hook queue is empty. -func (f *ResolverGetIndexConfigurationFunc) SetDefaultHook(hook func(context.Context, int) ([]byte, bool, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// GetIndexConfiguration method of the parent MockResolver instance invokes -// the hook at the front of the queue and discards it. After the queue is -// empty, the default hook function is invoked for any future action. -func (f *ResolverGetIndexConfigurationFunc) PushHook(hook func(context.Context, int) ([]byte, bool, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverGetIndexConfigurationFunc) SetDefaultReturn(r0 []byte, r1 bool, r2 error) { - f.SetDefaultHook(func(context.Context, int) ([]byte, bool, error) { - return r0, r1, r2 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverGetIndexConfigurationFunc) PushReturn(r0 []byte, r1 bool, r2 error) { - f.PushHook(func(context.Context, int) ([]byte, bool, error) { - return r0, r1, r2 - }) -} - -func (f *ResolverGetIndexConfigurationFunc) nextHook() func(context.Context, int) ([]byte, bool, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverGetIndexConfigurationFunc) appendCall(r0 ResolverGetIndexConfigurationFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverGetIndexConfigurationFuncCall -// objects describing the invocations of this function. -func (f *ResolverGetIndexConfigurationFunc) History() []ResolverGetIndexConfigurationFuncCall { - f.mutex.Lock() - history := make([]ResolverGetIndexConfigurationFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverGetIndexConfigurationFuncCall is an object that describes an -// invocation of method GetIndexConfiguration on an instance of -// MockResolver. -type ResolverGetIndexConfigurationFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []byte - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 bool - // Result2 is the value of the 3rd result returned from this method - // invocation. - Result2 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverGetIndexConfigurationFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverGetIndexConfigurationFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1, c.Result2} -} - -// ResolverGetIndexesByIDsFunc describes the behavior when the -// GetIndexesByIDs method of the parent MockResolver instance is invoked. -type ResolverGetIndexesByIDsFunc struct { - defaultHook func(context.Context, ...int) ([]shared.Index, error) - hooks []func(context.Context, ...int) ([]shared.Index, error) - history []ResolverGetIndexesByIDsFuncCall - mutex sync.Mutex -} - -// GetIndexesByIDs delegates to the next hook function in the queue and -// stores the parameter and result values of this invocation. -func (m *MockResolver) GetIndexesByIDs(v0 context.Context, v1 ...int) ([]shared.Index, error) { - r0, r1 := m.GetIndexesByIDsFunc.nextHook()(v0, v1...) - m.GetIndexesByIDsFunc.appendCall(ResolverGetIndexesByIDsFuncCall{v0, v1, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the GetIndexesByIDs -// method of the parent MockResolver instance is invoked and the hook queue -// is empty. -func (f *ResolverGetIndexesByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]shared.Index, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// GetIndexesByIDs method of the parent MockResolver instance invokes the -// hook at the front of the queue and discards it. After the queue is empty, -// the default hook function is invoked for any future action. -func (f *ResolverGetIndexesByIDsFunc) PushHook(hook func(context.Context, ...int) ([]shared.Index, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverGetIndexesByIDsFunc) SetDefaultReturn(r0 []shared.Index, r1 error) { - f.SetDefaultHook(func(context.Context, ...int) ([]shared.Index, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverGetIndexesByIDsFunc) PushReturn(r0 []shared.Index, r1 error) { - f.PushHook(func(context.Context, ...int) ([]shared.Index, error) { - return r0, r1 - }) -} - -func (f *ResolverGetIndexesByIDsFunc) nextHook() func(context.Context, ...int) ([]shared.Index, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverGetIndexesByIDsFunc) appendCall(r0 ResolverGetIndexesByIDsFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverGetIndexesByIDsFuncCall objects -// describing the invocations of this function. -func (f *ResolverGetIndexesByIDsFunc) History() []ResolverGetIndexesByIDsFuncCall { - f.mutex.Lock() - history := make([]ResolverGetIndexesByIDsFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverGetIndexesByIDsFuncCall is an object that describes an invocation -// of method GetIndexesByIDs on an instance of MockResolver. -type ResolverGetIndexesByIDsFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is a slice containing the values of the variadic arguments - // passed to this method invocation. - Arg1 []int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []shared.Index - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. The variadic slice argument is flattened in this array such -// that one positional argument and three variadic arguments would result in -// a slice of four, not two. -func (c ResolverGetIndexesByIDsFuncCall) Args() []interface{} { - trailing := []interface{}{} - for _, val := range c.Arg1 { - trailing = append(trailing, val) - } - - return append([]interface{}{c.Arg0}, trailing...) -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverGetIndexesByIDsFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// ResolverGetLastIndexScanForRepositoryFunc describes the behavior when the -// GetLastIndexScanForRepository method of the parent MockResolver instance -// is invoked. -type ResolverGetLastIndexScanForRepositoryFunc struct { - defaultHook func(context.Context, int) (*time.Time, error) - hooks []func(context.Context, int) (*time.Time, error) - history []ResolverGetLastIndexScanForRepositoryFuncCall - mutex sync.Mutex -} - -// GetLastIndexScanForRepository delegates to the next hook function in the -// queue and stores the parameter and result values of this invocation. -func (m *MockResolver) GetLastIndexScanForRepository(v0 context.Context, v1 int) (*time.Time, error) { - r0, r1 := m.GetLastIndexScanForRepositoryFunc.nextHook()(v0, v1) - m.GetLastIndexScanForRepositoryFunc.appendCall(ResolverGetLastIndexScanForRepositoryFuncCall{v0, v1, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the -// GetLastIndexScanForRepository method of the parent MockResolver instance -// is invoked and the hook queue is empty. -func (f *ResolverGetLastIndexScanForRepositoryFunc) SetDefaultHook(hook func(context.Context, int) (*time.Time, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// GetLastIndexScanForRepository method of the parent MockResolver instance -// invokes the hook at the front of the queue and discards it. After the -// queue is empty, the default hook function is invoked for any future -// action. -func (f *ResolverGetLastIndexScanForRepositoryFunc) PushHook(hook func(context.Context, int) (*time.Time, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverGetLastIndexScanForRepositoryFunc) SetDefaultReturn(r0 *time.Time, r1 error) { - f.SetDefaultHook(func(context.Context, int) (*time.Time, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverGetLastIndexScanForRepositoryFunc) PushReturn(r0 *time.Time, r1 error) { - f.PushHook(func(context.Context, int) (*time.Time, error) { - return r0, r1 - }) -} - -func (f *ResolverGetLastIndexScanForRepositoryFunc) nextHook() func(context.Context, int) (*time.Time, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverGetLastIndexScanForRepositoryFunc) appendCall(r0 ResolverGetLastIndexScanForRepositoryFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of -// ResolverGetLastIndexScanForRepositoryFuncCall objects describing the -// invocations of this function. -func (f *ResolverGetLastIndexScanForRepositoryFunc) History() []ResolverGetLastIndexScanForRepositoryFuncCall { - f.mutex.Lock() - history := make([]ResolverGetLastIndexScanForRepositoryFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverGetLastIndexScanForRepositoryFuncCall is an object that describes -// an invocation of method GetLastIndexScanForRepository on an instance of -// MockResolver. -type ResolverGetLastIndexScanForRepositoryFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 *time.Time - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverGetLastIndexScanForRepositoryFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverGetLastIndexScanForRepositoryFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// ResolverGetRecentIndexesSummaryFunc describes the behavior when the -// GetRecentIndexesSummary method of the parent MockResolver instance is -// invoked. -type ResolverGetRecentIndexesSummaryFunc struct { - defaultHook func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error) - hooks []func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error) - history []ResolverGetRecentIndexesSummaryFuncCall - mutex sync.Mutex -} - -// GetRecentIndexesSummary delegates to the next hook function in the queue -// and stores the parameter and result values of this invocation. -func (m *MockResolver) GetRecentIndexesSummary(v0 context.Context, v1 int) ([]shared.IndexesWithRepositoryNamespace, error) { - r0, r1 := m.GetRecentIndexesSummaryFunc.nextHook()(v0, v1) - m.GetRecentIndexesSummaryFunc.appendCall(ResolverGetRecentIndexesSummaryFuncCall{v0, v1, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the -// GetRecentIndexesSummary method of the parent MockResolver instance is -// invoked and the hook queue is empty. -func (f *ResolverGetRecentIndexesSummaryFunc) SetDefaultHook(hook func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// GetRecentIndexesSummary method of the parent MockResolver instance -// invokes the hook at the front of the queue and discards it. After the -// queue is empty, the default hook function is invoked for any future -// action. -func (f *ResolverGetRecentIndexesSummaryFunc) PushHook(hook func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverGetRecentIndexesSummaryFunc) SetDefaultReturn(r0 []shared.IndexesWithRepositoryNamespace, r1 error) { - f.SetDefaultHook(func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverGetRecentIndexesSummaryFunc) PushReturn(r0 []shared.IndexesWithRepositoryNamespace, r1 error) { - f.PushHook(func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error) { - return r0, r1 - }) -} - -func (f *ResolverGetRecentIndexesSummaryFunc) nextHook() func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverGetRecentIndexesSummaryFunc) appendCall(r0 ResolverGetRecentIndexesSummaryFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverGetRecentIndexesSummaryFuncCall -// objects describing the invocations of this function. -func (f *ResolverGetRecentIndexesSummaryFunc) History() []ResolverGetRecentIndexesSummaryFuncCall { - f.mutex.Lock() - history := make([]ResolverGetRecentIndexesSummaryFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverGetRecentIndexesSummaryFuncCall is an object that describes an -// invocation of method GetRecentIndexesSummary on an instance of -// MockResolver. -type ResolverGetRecentIndexesSummaryFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []shared.IndexesWithRepositoryNamespace - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverGetRecentIndexesSummaryFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverGetRecentIndexesSummaryFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// ResolverIndexConnectionResolverFromFactoryFunc describes the behavior -// when the IndexConnectionResolverFromFactory method of the parent -// MockResolver instance is invoked. -type ResolverIndexConnectionResolverFromFactoryFunc struct { - defaultHook func(shared.GetIndexesOptions) *graphql.IndexesResolver - hooks []func(shared.GetIndexesOptions) *graphql.IndexesResolver - history []ResolverIndexConnectionResolverFromFactoryFuncCall - mutex sync.Mutex -} - -// IndexConnectionResolverFromFactory delegates to the next hook function in -// the queue and stores the parameter and result values of this invocation. -func (m *MockResolver) IndexConnectionResolverFromFactory(v0 shared.GetIndexesOptions) *graphql.IndexesResolver { - r0 := m.IndexConnectionResolverFromFactoryFunc.nextHook()(v0) - m.IndexConnectionResolverFromFactoryFunc.appendCall(ResolverIndexConnectionResolverFromFactoryFuncCall{v0, r0}) - return r0 -} - -// SetDefaultHook sets function that is called when the -// IndexConnectionResolverFromFactory method of the parent MockResolver -// instance is invoked and the hook queue is empty. -func (f *ResolverIndexConnectionResolverFromFactoryFunc) SetDefaultHook(hook func(shared.GetIndexesOptions) *graphql.IndexesResolver) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// IndexConnectionResolverFromFactory method of the parent MockResolver -// instance invokes the hook at the front of the queue and discards it. -// After the queue is empty, the default hook function is invoked for any -// future action. -func (f *ResolverIndexConnectionResolverFromFactoryFunc) PushHook(hook func(shared.GetIndexesOptions) *graphql.IndexesResolver) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverIndexConnectionResolverFromFactoryFunc) SetDefaultReturn(r0 *graphql.IndexesResolver) { - f.SetDefaultHook(func(shared.GetIndexesOptions) *graphql.IndexesResolver { - return r0 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverIndexConnectionResolverFromFactoryFunc) PushReturn(r0 *graphql.IndexesResolver) { - f.PushHook(func(shared.GetIndexesOptions) *graphql.IndexesResolver { - return r0 - }) -} - -func (f *ResolverIndexConnectionResolverFromFactoryFunc) nextHook() func(shared.GetIndexesOptions) *graphql.IndexesResolver { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverIndexConnectionResolverFromFactoryFunc) appendCall(r0 ResolverIndexConnectionResolverFromFactoryFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of -// ResolverIndexConnectionResolverFromFactoryFuncCall objects describing the -// invocations of this function. -func (f *ResolverIndexConnectionResolverFromFactoryFunc) History() []ResolverIndexConnectionResolverFromFactoryFuncCall { - f.mutex.Lock() - history := make([]ResolverIndexConnectionResolverFromFactoryFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverIndexConnectionResolverFromFactoryFuncCall is an object that -// describes an invocation of method IndexConnectionResolverFromFactory on -// an instance of MockResolver. -type ResolverIndexConnectionResolverFromFactoryFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 shared.GetIndexesOptions - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 *graphql.IndexesResolver -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverIndexConnectionResolverFromFactoryFuncCall) Args() []interface{} { - return []interface{}{c.Arg0} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverIndexConnectionResolverFromFactoryFuncCall) Results() []interface{} { - return []interface{}{c.Result0} -} - -// ResolverInferedIndexConfigurationFunc describes the behavior when the -// InferedIndexConfiguration method of the parent MockResolver instance is -// invoked. -type ResolverInferedIndexConfigurationFunc struct { - defaultHook func(context.Context, int, string) (*config.IndexConfiguration, bool, error) - hooks []func(context.Context, int, string) (*config.IndexConfiguration, bool, error) - history []ResolverInferedIndexConfigurationFuncCall - mutex sync.Mutex -} - -// InferedIndexConfiguration delegates to the next hook function in the -// queue and stores the parameter and result values of this invocation. -func (m *MockResolver) InferedIndexConfiguration(v0 context.Context, v1 int, v2 string) (*config.IndexConfiguration, bool, error) { - r0, r1, r2 := m.InferedIndexConfigurationFunc.nextHook()(v0, v1, v2) - m.InferedIndexConfigurationFunc.appendCall(ResolverInferedIndexConfigurationFuncCall{v0, v1, v2, r0, r1, r2}) - return r0, r1, r2 -} - -// SetDefaultHook sets function that is called when the -// InferedIndexConfiguration method of the parent MockResolver instance is -// invoked and the hook queue is empty. -func (f *ResolverInferedIndexConfigurationFunc) SetDefaultHook(hook func(context.Context, int, string) (*config.IndexConfiguration, bool, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// InferedIndexConfiguration method of the parent MockResolver instance -// invokes the hook at the front of the queue and discards it. After the -// queue is empty, the default hook function is invoked for any future -// action. -func (f *ResolverInferedIndexConfigurationFunc) PushHook(hook func(context.Context, int, string) (*config.IndexConfiguration, bool, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverInferedIndexConfigurationFunc) SetDefaultReturn(r0 *config.IndexConfiguration, r1 bool, r2 error) { - f.SetDefaultHook(func(context.Context, int, string) (*config.IndexConfiguration, bool, error) { - return r0, r1, r2 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverInferedIndexConfigurationFunc) PushReturn(r0 *config.IndexConfiguration, r1 bool, r2 error) { - f.PushHook(func(context.Context, int, string) (*config.IndexConfiguration, bool, error) { - return r0, r1, r2 - }) -} - -func (f *ResolverInferedIndexConfigurationFunc) nextHook() func(context.Context, int, string) (*config.IndexConfiguration, bool, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverInferedIndexConfigurationFunc) appendCall(r0 ResolverInferedIndexConfigurationFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverInferedIndexConfigurationFuncCall -// objects describing the invocations of this function. -func (f *ResolverInferedIndexConfigurationFunc) History() []ResolverInferedIndexConfigurationFuncCall { - f.mutex.Lock() - history := make([]ResolverInferedIndexConfigurationFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverInferedIndexConfigurationFuncCall is an object that describes an -// invocation of method InferedIndexConfiguration on an instance of -// MockResolver. -type ResolverInferedIndexConfigurationFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Arg2 is the value of the 3rd argument passed to this method - // invocation. - Arg2 string - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 *config.IndexConfiguration - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 bool - // Result2 is the value of the 3rd result returned from this method - // invocation. - Result2 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverInferedIndexConfigurationFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1, c.Arg2} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverInferedIndexConfigurationFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1, c.Result2} -} - -// ResolverInferedIndexConfigurationHintsFunc describes the behavior when -// the InferedIndexConfigurationHints method of the parent MockResolver -// instance is invoked. -type ResolverInferedIndexConfigurationHintsFunc struct { - defaultHook func(context.Context, int, string) ([]config.IndexJobHint, error) - hooks []func(context.Context, int, string) ([]config.IndexJobHint, error) - history []ResolverInferedIndexConfigurationHintsFuncCall - mutex sync.Mutex -} - -// InferedIndexConfigurationHints delegates to the next hook function in the -// queue and stores the parameter and result values of this invocation. -func (m *MockResolver) InferedIndexConfigurationHints(v0 context.Context, v1 int, v2 string) ([]config.IndexJobHint, error) { - r0, r1 := m.InferedIndexConfigurationHintsFunc.nextHook()(v0, v1, v2) - m.InferedIndexConfigurationHintsFunc.appendCall(ResolverInferedIndexConfigurationHintsFuncCall{v0, v1, v2, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the -// InferedIndexConfigurationHints method of the parent MockResolver instance -// is invoked and the hook queue is empty. -func (f *ResolverInferedIndexConfigurationHintsFunc) SetDefaultHook(hook func(context.Context, int, string) ([]config.IndexJobHint, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// InferedIndexConfigurationHints method of the parent MockResolver instance -// invokes the hook at the front of the queue and discards it. After the -// queue is empty, the default hook function is invoked for any future -// action. -func (f *ResolverInferedIndexConfigurationHintsFunc) PushHook(hook func(context.Context, int, string) ([]config.IndexJobHint, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverInferedIndexConfigurationHintsFunc) SetDefaultReturn(r0 []config.IndexJobHint, r1 error) { - f.SetDefaultHook(func(context.Context, int, string) ([]config.IndexJobHint, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverInferedIndexConfigurationHintsFunc) PushReturn(r0 []config.IndexJobHint, r1 error) { - f.PushHook(func(context.Context, int, string) ([]config.IndexJobHint, error) { - return r0, r1 - }) -} - -func (f *ResolverInferedIndexConfigurationHintsFunc) nextHook() func(context.Context, int, string) ([]config.IndexJobHint, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverInferedIndexConfigurationHintsFunc) appendCall(r0 ResolverInferedIndexConfigurationHintsFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of -// ResolverInferedIndexConfigurationHintsFuncCall objects describing the -// invocations of this function. -func (f *ResolverInferedIndexConfigurationHintsFunc) History() []ResolverInferedIndexConfigurationHintsFuncCall { - f.mutex.Lock() - history := make([]ResolverInferedIndexConfigurationHintsFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverInferedIndexConfigurationHintsFuncCall is an object that -// describes an invocation of method InferedIndexConfigurationHints on an -// instance of MockResolver. -type ResolverInferedIndexConfigurationHintsFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Arg2 is the value of the 3rd argument passed to this method - // invocation. - Arg2 string - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []config.IndexJobHint - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverInferedIndexConfigurationHintsFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1, c.Arg2} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverInferedIndexConfigurationHintsFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// ResolverQueueAutoIndexJobsForRepoFunc describes the behavior when the -// QueueAutoIndexJobsForRepo method of the parent MockResolver instance is -// invoked. -type ResolverQueueAutoIndexJobsForRepoFunc struct { - defaultHook func(context.Context, int, string, string) ([]shared.Index, error) - hooks []func(context.Context, int, string, string) ([]shared.Index, error) - history []ResolverQueueAutoIndexJobsForRepoFuncCall - mutex sync.Mutex -} - -// QueueAutoIndexJobsForRepo delegates to the next hook function in the -// queue and stores the parameter and result values of this invocation. -func (m *MockResolver) QueueAutoIndexJobsForRepo(v0 context.Context, v1 int, v2 string, v3 string) ([]shared.Index, error) { - r0, r1 := m.QueueAutoIndexJobsForRepoFunc.nextHook()(v0, v1, v2, v3) - m.QueueAutoIndexJobsForRepoFunc.appendCall(ResolverQueueAutoIndexJobsForRepoFuncCall{v0, v1, v2, v3, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the -// QueueAutoIndexJobsForRepo method of the parent MockResolver instance is -// invoked and the hook queue is empty. -func (f *ResolverQueueAutoIndexJobsForRepoFunc) SetDefaultHook(hook func(context.Context, int, string, string) ([]shared.Index, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// QueueAutoIndexJobsForRepo method of the parent MockResolver instance -// invokes the hook at the front of the queue and discards it. After the -// queue is empty, the default hook function is invoked for any future -// action. -func (f *ResolverQueueAutoIndexJobsForRepoFunc) PushHook(hook func(context.Context, int, string, string) ([]shared.Index, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverQueueAutoIndexJobsForRepoFunc) SetDefaultReturn(r0 []shared.Index, r1 error) { - f.SetDefaultHook(func(context.Context, int, string, string) ([]shared.Index, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverQueueAutoIndexJobsForRepoFunc) PushReturn(r0 []shared.Index, r1 error) { - f.PushHook(func(context.Context, int, string, string) ([]shared.Index, error) { - return r0, r1 - }) -} - -func (f *ResolverQueueAutoIndexJobsForRepoFunc) nextHook() func(context.Context, int, string, string) ([]shared.Index, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverQueueAutoIndexJobsForRepoFunc) appendCall(r0 ResolverQueueAutoIndexJobsForRepoFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverQueueAutoIndexJobsForRepoFuncCall -// objects describing the invocations of this function. -func (f *ResolverQueueAutoIndexJobsForRepoFunc) History() []ResolverQueueAutoIndexJobsForRepoFuncCall { - f.mutex.Lock() - history := make([]ResolverQueueAutoIndexJobsForRepoFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverQueueAutoIndexJobsForRepoFuncCall is an object that describes an -// invocation of method QueueAutoIndexJobsForRepo on an instance of -// MockResolver. -type ResolverQueueAutoIndexJobsForRepoFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Arg2 is the value of the 3rd argument passed to this method - // invocation. - Arg2 string - // Arg3 is the value of the 4th argument passed to this method - // invocation. - Arg3 string - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []shared.Index - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverQueueAutoIndexJobsForRepoFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverQueueAutoIndexJobsForRepoFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// ResolverUpdateIndexConfigurationByRepositoryIDFunc describes the behavior -// when the UpdateIndexConfigurationByRepositoryID method of the parent -// MockResolver instance is invoked. -type ResolverUpdateIndexConfigurationByRepositoryIDFunc struct { - defaultHook func(context.Context, int, string) error - hooks []func(context.Context, int, string) error - history []ResolverUpdateIndexConfigurationByRepositoryIDFuncCall - mutex sync.Mutex -} - -// UpdateIndexConfigurationByRepositoryID delegates to the next hook -// function in the queue and stores the parameter and result values of this -// invocation. -func (m *MockResolver) UpdateIndexConfigurationByRepositoryID(v0 context.Context, v1 int, v2 string) error { - r0 := m.UpdateIndexConfigurationByRepositoryIDFunc.nextHook()(v0, v1, v2) - m.UpdateIndexConfigurationByRepositoryIDFunc.appendCall(ResolverUpdateIndexConfigurationByRepositoryIDFuncCall{v0, v1, v2, r0}) - return r0 -} - -// SetDefaultHook sets function that is called when the -// UpdateIndexConfigurationByRepositoryID method of the parent MockResolver -// instance is invoked and the hook queue is empty. -func (f *ResolverUpdateIndexConfigurationByRepositoryIDFunc) SetDefaultHook(hook func(context.Context, int, string) error) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// UpdateIndexConfigurationByRepositoryID method of the parent MockResolver -// instance invokes the hook at the front of the queue and discards it. -// After the queue is empty, the default hook function is invoked for any -// future action. -func (f *ResolverUpdateIndexConfigurationByRepositoryIDFunc) PushHook(hook func(context.Context, int, string) error) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverUpdateIndexConfigurationByRepositoryIDFunc) SetDefaultReturn(r0 error) { - f.SetDefaultHook(func(context.Context, int, string) error { - return r0 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverUpdateIndexConfigurationByRepositoryIDFunc) PushReturn(r0 error) { - f.PushHook(func(context.Context, int, string) error { - return r0 - }) -} - -func (f *ResolverUpdateIndexConfigurationByRepositoryIDFunc) nextHook() func(context.Context, int, string) error { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverUpdateIndexConfigurationByRepositoryIDFunc) appendCall(r0 ResolverUpdateIndexConfigurationByRepositoryIDFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of -// ResolverUpdateIndexConfigurationByRepositoryIDFuncCall objects describing -// the invocations of this function. -func (f *ResolverUpdateIndexConfigurationByRepositoryIDFunc) History() []ResolverUpdateIndexConfigurationByRepositoryIDFuncCall { - f.mutex.Lock() - history := make([]ResolverUpdateIndexConfigurationByRepositoryIDFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverUpdateIndexConfigurationByRepositoryIDFuncCall is an object that -// describes an invocation of method UpdateIndexConfigurationByRepositoryID -// on an instance of MockResolver. -type ResolverUpdateIndexConfigurationByRepositoryIDFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Arg2 is the value of the 3rd argument passed to this method - // invocation. - Arg2 string - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverUpdateIndexConfigurationByRepositoryIDFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1, c.Arg2} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverUpdateIndexConfigurationByRepositoryIDFuncCall) Results() []interface{} { - return []interface{}{c.Result0} -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/uploads/mocks_uploads.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/uploads/mocks_uploads.go deleted file mode 100644 index f00c47ed567..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/uploads/mocks_uploads.go +++ /dev/null @@ -1,1203 +0,0 @@ -// Code generated by go-mockgen 1.3.4; DO NOT EDIT. -// -// This file was generated by running `sg generate` (or `go-mockgen`) at the root of -// this repository. To add additional mocks to this or another package, add a new entry -// to the mockgen.yaml file in the root of this repository. - -package uploads - -import ( - "context" - "sync" - "time" - - shared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" - graphql "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/transport/graphql" -) - -// MockResolver is a mock implementation of the Resolver interface (from the -// package -// github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/transport/graphql) -// used for unit testing. -type MockResolver struct { - // CommitGraphResolverFromFactoryFunc is an instance of a mock function - // object controlling the behavior of the method - // CommitGraphResolverFromFactory. - CommitGraphResolverFromFactoryFunc *ResolverCommitGraphResolverFromFactoryFunc - // DeleteUploadByIDFunc is an instance of a mock function object - // controlling the behavior of the method DeleteUploadByID. - DeleteUploadByIDFunc *ResolverDeleteUploadByIDFunc - // GetAuditLogsForUploadFunc is an instance of a mock function object - // controlling the behavior of the method GetAuditLogsForUpload. - GetAuditLogsForUploadFunc *ResolverGetAuditLogsForUploadFunc - // GetCommitsVisibleToUploadFunc is an instance of a mock function - // object controlling the behavior of the method - // GetCommitsVisibleToUpload. - GetCommitsVisibleToUploadFunc *ResolverGetCommitsVisibleToUploadFunc - // GetLastUploadRetentionScanForRepositoryFunc is an instance of a mock - // function object controlling the behavior of the method - // GetLastUploadRetentionScanForRepository. - GetLastUploadRetentionScanForRepositoryFunc *ResolverGetLastUploadRetentionScanForRepositoryFunc - // GetRecentUploadsSummaryFunc is an instance of a mock function object - // controlling the behavior of the method GetRecentUploadsSummary. - GetRecentUploadsSummaryFunc *ResolverGetRecentUploadsSummaryFunc - // GetUploadDocumentsForPathFunc is an instance of a mock function - // object controlling the behavior of the method - // GetUploadDocumentsForPath. - GetUploadDocumentsForPathFunc *ResolverGetUploadDocumentsForPathFunc - // GetUploadsByIDsFunc is an instance of a mock function object - // controlling the behavior of the method GetUploadsByIDs. - GetUploadsByIDsFunc *ResolverGetUploadsByIDsFunc - // UploadsConnectionResolverFromFactoryFunc is an instance of a mock - // function object controlling the behavior of the method - // UploadsConnectionResolverFromFactory. - UploadsConnectionResolverFromFactoryFunc *ResolverUploadsConnectionResolverFromFactoryFunc -} - -// NewMockResolver creates a new mock of the Resolver interface. All methods -// return zero values for all results, unless overwritten. -func NewMockResolver() *MockResolver { - return &MockResolver{ - CommitGraphResolverFromFactoryFunc: &ResolverCommitGraphResolverFromFactoryFunc{ - defaultHook: func(context.Context, int) (r0 *graphql.CommitGraphResolver) { - return - }, - }, - DeleteUploadByIDFunc: &ResolverDeleteUploadByIDFunc{ - defaultHook: func(context.Context, int) (r0 bool, r1 error) { - return - }, - }, - GetAuditLogsForUploadFunc: &ResolverGetAuditLogsForUploadFunc{ - defaultHook: func(context.Context, int) (r0 []shared.UploadLog, r1 error) { - return - }, - }, - GetCommitsVisibleToUploadFunc: &ResolverGetCommitsVisibleToUploadFunc{ - defaultHook: func(context.Context, int, int, *string) (r0 []string, r1 *string, r2 error) { - return - }, - }, - GetLastUploadRetentionScanForRepositoryFunc: &ResolverGetLastUploadRetentionScanForRepositoryFunc{ - defaultHook: func(context.Context, int) (r0 *time.Time, r1 error) { - return - }, - }, - GetRecentUploadsSummaryFunc: &ResolverGetRecentUploadsSummaryFunc{ - defaultHook: func(context.Context, int) (r0 []shared.UploadsWithRepositoryNamespace, r1 error) { - return - }, - }, - GetUploadDocumentsForPathFunc: &ResolverGetUploadDocumentsForPathFunc{ - defaultHook: func(context.Context, int, string) (r0 []string, r1 int, r2 error) { - return - }, - }, - GetUploadsByIDsFunc: &ResolverGetUploadsByIDsFunc{ - defaultHook: func(context.Context, ...int) (r0 []shared.Upload, r1 error) { - return - }, - }, - UploadsConnectionResolverFromFactoryFunc: &ResolverUploadsConnectionResolverFromFactoryFunc{ - defaultHook: func(shared.GetUploadsOptions) (r0 *graphql.UploadsResolver) { - return - }, - }, - } -} - -// NewStrictMockResolver creates a new mock of the Resolver interface. All -// methods panic on invocation, unless overwritten. -func NewStrictMockResolver() *MockResolver { - return &MockResolver{ - CommitGraphResolverFromFactoryFunc: &ResolverCommitGraphResolverFromFactoryFunc{ - defaultHook: func(context.Context, int) *graphql.CommitGraphResolver { - panic("unexpected invocation of MockResolver.CommitGraphResolverFromFactory") - }, - }, - DeleteUploadByIDFunc: &ResolverDeleteUploadByIDFunc{ - defaultHook: func(context.Context, int) (bool, error) { - panic("unexpected invocation of MockResolver.DeleteUploadByID") - }, - }, - GetAuditLogsForUploadFunc: &ResolverGetAuditLogsForUploadFunc{ - defaultHook: func(context.Context, int) ([]shared.UploadLog, error) { - panic("unexpected invocation of MockResolver.GetAuditLogsForUpload") - }, - }, - GetCommitsVisibleToUploadFunc: &ResolverGetCommitsVisibleToUploadFunc{ - defaultHook: func(context.Context, int, int, *string) ([]string, *string, error) { - panic("unexpected invocation of MockResolver.GetCommitsVisibleToUpload") - }, - }, - GetLastUploadRetentionScanForRepositoryFunc: &ResolverGetLastUploadRetentionScanForRepositoryFunc{ - defaultHook: func(context.Context, int) (*time.Time, error) { - panic("unexpected invocation of MockResolver.GetLastUploadRetentionScanForRepository") - }, - }, - GetRecentUploadsSummaryFunc: &ResolverGetRecentUploadsSummaryFunc{ - defaultHook: func(context.Context, int) ([]shared.UploadsWithRepositoryNamespace, error) { - panic("unexpected invocation of MockResolver.GetRecentUploadsSummary") - }, - }, - GetUploadDocumentsForPathFunc: &ResolverGetUploadDocumentsForPathFunc{ - defaultHook: func(context.Context, int, string) ([]string, int, error) { - panic("unexpected invocation of MockResolver.GetUploadDocumentsForPath") - }, - }, - GetUploadsByIDsFunc: &ResolverGetUploadsByIDsFunc{ - defaultHook: func(context.Context, ...int) ([]shared.Upload, error) { - panic("unexpected invocation of MockResolver.GetUploadsByIDs") - }, - }, - UploadsConnectionResolverFromFactoryFunc: &ResolverUploadsConnectionResolverFromFactoryFunc{ - defaultHook: func(shared.GetUploadsOptions) *graphql.UploadsResolver { - panic("unexpected invocation of MockResolver.UploadsConnectionResolverFromFactory") - }, - }, - } -} - -// NewMockResolverFrom creates a new mock of the MockResolver interface. All -// methods delegate to the given implementation, unless overwritten. -func NewMockResolverFrom(i graphql.Resolver) *MockResolver { - return &MockResolver{ - CommitGraphResolverFromFactoryFunc: &ResolverCommitGraphResolverFromFactoryFunc{ - defaultHook: i.CommitGraphResolverFromFactory, - }, - DeleteUploadByIDFunc: &ResolverDeleteUploadByIDFunc{ - defaultHook: i.DeleteUploadByID, - }, - GetAuditLogsForUploadFunc: &ResolverGetAuditLogsForUploadFunc{ - defaultHook: i.GetAuditLogsForUpload, - }, - GetCommitsVisibleToUploadFunc: &ResolverGetCommitsVisibleToUploadFunc{ - defaultHook: i.GetCommitsVisibleToUpload, - }, - GetLastUploadRetentionScanForRepositoryFunc: &ResolverGetLastUploadRetentionScanForRepositoryFunc{ - defaultHook: i.GetLastUploadRetentionScanForRepository, - }, - GetRecentUploadsSummaryFunc: &ResolverGetRecentUploadsSummaryFunc{ - defaultHook: i.GetRecentUploadsSummary, - }, - GetUploadDocumentsForPathFunc: &ResolverGetUploadDocumentsForPathFunc{ - defaultHook: i.GetUploadDocumentsForPath, - }, - GetUploadsByIDsFunc: &ResolverGetUploadsByIDsFunc{ - defaultHook: i.GetUploadsByIDs, - }, - UploadsConnectionResolverFromFactoryFunc: &ResolverUploadsConnectionResolverFromFactoryFunc{ - defaultHook: i.UploadsConnectionResolverFromFactory, - }, - } -} - -// ResolverCommitGraphResolverFromFactoryFunc describes the behavior when -// the CommitGraphResolverFromFactory method of the parent MockResolver -// instance is invoked. -type ResolverCommitGraphResolverFromFactoryFunc struct { - defaultHook func(context.Context, int) *graphql.CommitGraphResolver - hooks []func(context.Context, int) *graphql.CommitGraphResolver - history []ResolverCommitGraphResolverFromFactoryFuncCall - mutex sync.Mutex -} - -// CommitGraphResolverFromFactory delegates to the next hook function in the -// queue and stores the parameter and result values of this invocation. -func (m *MockResolver) CommitGraphResolverFromFactory(v0 context.Context, v1 int) *graphql.CommitGraphResolver { - r0 := m.CommitGraphResolverFromFactoryFunc.nextHook()(v0, v1) - m.CommitGraphResolverFromFactoryFunc.appendCall(ResolverCommitGraphResolverFromFactoryFuncCall{v0, v1, r0}) - return r0 -} - -// SetDefaultHook sets function that is called when the -// CommitGraphResolverFromFactory method of the parent MockResolver instance -// is invoked and the hook queue is empty. -func (f *ResolverCommitGraphResolverFromFactoryFunc) SetDefaultHook(hook func(context.Context, int) *graphql.CommitGraphResolver) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// CommitGraphResolverFromFactory method of the parent MockResolver instance -// invokes the hook at the front of the queue and discards it. After the -// queue is empty, the default hook function is invoked for any future -// action. -func (f *ResolverCommitGraphResolverFromFactoryFunc) PushHook(hook func(context.Context, int) *graphql.CommitGraphResolver) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverCommitGraphResolverFromFactoryFunc) SetDefaultReturn(r0 *graphql.CommitGraphResolver) { - f.SetDefaultHook(func(context.Context, int) *graphql.CommitGraphResolver { - return r0 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverCommitGraphResolverFromFactoryFunc) PushReturn(r0 *graphql.CommitGraphResolver) { - f.PushHook(func(context.Context, int) *graphql.CommitGraphResolver { - return r0 - }) -} - -func (f *ResolverCommitGraphResolverFromFactoryFunc) nextHook() func(context.Context, int) *graphql.CommitGraphResolver { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverCommitGraphResolverFromFactoryFunc) appendCall(r0 ResolverCommitGraphResolverFromFactoryFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of -// ResolverCommitGraphResolverFromFactoryFuncCall objects describing the -// invocations of this function. -func (f *ResolverCommitGraphResolverFromFactoryFunc) History() []ResolverCommitGraphResolverFromFactoryFuncCall { - f.mutex.Lock() - history := make([]ResolverCommitGraphResolverFromFactoryFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverCommitGraphResolverFromFactoryFuncCall is an object that -// describes an invocation of method CommitGraphResolverFromFactory on an -// instance of MockResolver. -type ResolverCommitGraphResolverFromFactoryFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 *graphql.CommitGraphResolver -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverCommitGraphResolverFromFactoryFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverCommitGraphResolverFromFactoryFuncCall) Results() []interface{} { - return []interface{}{c.Result0} -} - -// ResolverDeleteUploadByIDFunc describes the behavior when the -// DeleteUploadByID method of the parent MockResolver instance is invoked. -type ResolverDeleteUploadByIDFunc struct { - defaultHook func(context.Context, int) (bool, error) - hooks []func(context.Context, int) (bool, error) - history []ResolverDeleteUploadByIDFuncCall - mutex sync.Mutex -} - -// DeleteUploadByID delegates to the next hook function in the queue and -// stores the parameter and result values of this invocation. -func (m *MockResolver) DeleteUploadByID(v0 context.Context, v1 int) (bool, error) { - r0, r1 := m.DeleteUploadByIDFunc.nextHook()(v0, v1) - m.DeleteUploadByIDFunc.appendCall(ResolverDeleteUploadByIDFuncCall{v0, v1, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the DeleteUploadByID -// method of the parent MockResolver instance is invoked and the hook queue -// is empty. -func (f *ResolverDeleteUploadByIDFunc) SetDefaultHook(hook func(context.Context, int) (bool, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// DeleteUploadByID method of the parent MockResolver instance invokes the -// hook at the front of the queue and discards it. After the queue is empty, -// the default hook function is invoked for any future action. -func (f *ResolverDeleteUploadByIDFunc) PushHook(hook func(context.Context, int) (bool, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverDeleteUploadByIDFunc) SetDefaultReturn(r0 bool, r1 error) { - f.SetDefaultHook(func(context.Context, int) (bool, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverDeleteUploadByIDFunc) PushReturn(r0 bool, r1 error) { - f.PushHook(func(context.Context, int) (bool, error) { - return r0, r1 - }) -} - -func (f *ResolverDeleteUploadByIDFunc) nextHook() func(context.Context, int) (bool, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverDeleteUploadByIDFunc) appendCall(r0 ResolverDeleteUploadByIDFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverDeleteUploadByIDFuncCall objects -// describing the invocations of this function. -func (f *ResolverDeleteUploadByIDFunc) History() []ResolverDeleteUploadByIDFuncCall { - f.mutex.Lock() - history := make([]ResolverDeleteUploadByIDFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverDeleteUploadByIDFuncCall is an object that describes an -// invocation of method DeleteUploadByID on an instance of MockResolver. -type ResolverDeleteUploadByIDFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 bool - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverDeleteUploadByIDFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverDeleteUploadByIDFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// ResolverGetAuditLogsForUploadFunc describes the behavior when the -// GetAuditLogsForUpload method of the parent MockResolver instance is -// invoked. -type ResolverGetAuditLogsForUploadFunc struct { - defaultHook func(context.Context, int) ([]shared.UploadLog, error) - hooks []func(context.Context, int) ([]shared.UploadLog, error) - history []ResolverGetAuditLogsForUploadFuncCall - mutex sync.Mutex -} - -// GetAuditLogsForUpload delegates to the next hook function in the queue -// and stores the parameter and result values of this invocation. -func (m *MockResolver) GetAuditLogsForUpload(v0 context.Context, v1 int) ([]shared.UploadLog, error) { - r0, r1 := m.GetAuditLogsForUploadFunc.nextHook()(v0, v1) - m.GetAuditLogsForUploadFunc.appendCall(ResolverGetAuditLogsForUploadFuncCall{v0, v1, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the -// GetAuditLogsForUpload method of the parent MockResolver instance is -// invoked and the hook queue is empty. -func (f *ResolverGetAuditLogsForUploadFunc) SetDefaultHook(hook func(context.Context, int) ([]shared.UploadLog, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// GetAuditLogsForUpload method of the parent MockResolver instance invokes -// the hook at the front of the queue and discards it. After the queue is -// empty, the default hook function is invoked for any future action. -func (f *ResolverGetAuditLogsForUploadFunc) PushHook(hook func(context.Context, int) ([]shared.UploadLog, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverGetAuditLogsForUploadFunc) SetDefaultReturn(r0 []shared.UploadLog, r1 error) { - f.SetDefaultHook(func(context.Context, int) ([]shared.UploadLog, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverGetAuditLogsForUploadFunc) PushReturn(r0 []shared.UploadLog, r1 error) { - f.PushHook(func(context.Context, int) ([]shared.UploadLog, error) { - return r0, r1 - }) -} - -func (f *ResolverGetAuditLogsForUploadFunc) nextHook() func(context.Context, int) ([]shared.UploadLog, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverGetAuditLogsForUploadFunc) appendCall(r0 ResolverGetAuditLogsForUploadFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverGetAuditLogsForUploadFuncCall -// objects describing the invocations of this function. -func (f *ResolverGetAuditLogsForUploadFunc) History() []ResolverGetAuditLogsForUploadFuncCall { - f.mutex.Lock() - history := make([]ResolverGetAuditLogsForUploadFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverGetAuditLogsForUploadFuncCall is an object that describes an -// invocation of method GetAuditLogsForUpload on an instance of -// MockResolver. -type ResolverGetAuditLogsForUploadFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []shared.UploadLog - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverGetAuditLogsForUploadFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverGetAuditLogsForUploadFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// ResolverGetCommitsVisibleToUploadFunc describes the behavior when the -// GetCommitsVisibleToUpload method of the parent MockResolver instance is -// invoked. -type ResolverGetCommitsVisibleToUploadFunc struct { - defaultHook func(context.Context, int, int, *string) ([]string, *string, error) - hooks []func(context.Context, int, int, *string) ([]string, *string, error) - history []ResolverGetCommitsVisibleToUploadFuncCall - mutex sync.Mutex -} - -// GetCommitsVisibleToUpload delegates to the next hook function in the -// queue and stores the parameter and result values of this invocation. -func (m *MockResolver) GetCommitsVisibleToUpload(v0 context.Context, v1 int, v2 int, v3 *string) ([]string, *string, error) { - r0, r1, r2 := m.GetCommitsVisibleToUploadFunc.nextHook()(v0, v1, v2, v3) - m.GetCommitsVisibleToUploadFunc.appendCall(ResolverGetCommitsVisibleToUploadFuncCall{v0, v1, v2, v3, r0, r1, r2}) - return r0, r1, r2 -} - -// SetDefaultHook sets function that is called when the -// GetCommitsVisibleToUpload method of the parent MockResolver instance is -// invoked and the hook queue is empty. -func (f *ResolverGetCommitsVisibleToUploadFunc) SetDefaultHook(hook func(context.Context, int, int, *string) ([]string, *string, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// GetCommitsVisibleToUpload method of the parent MockResolver instance -// invokes the hook at the front of the queue and discards it. After the -// queue is empty, the default hook function is invoked for any future -// action. -func (f *ResolverGetCommitsVisibleToUploadFunc) PushHook(hook func(context.Context, int, int, *string) ([]string, *string, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverGetCommitsVisibleToUploadFunc) SetDefaultReturn(r0 []string, r1 *string, r2 error) { - f.SetDefaultHook(func(context.Context, int, int, *string) ([]string, *string, error) { - return r0, r1, r2 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverGetCommitsVisibleToUploadFunc) PushReturn(r0 []string, r1 *string, r2 error) { - f.PushHook(func(context.Context, int, int, *string) ([]string, *string, error) { - return r0, r1, r2 - }) -} - -func (f *ResolverGetCommitsVisibleToUploadFunc) nextHook() func(context.Context, int, int, *string) ([]string, *string, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverGetCommitsVisibleToUploadFunc) appendCall(r0 ResolverGetCommitsVisibleToUploadFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverGetCommitsVisibleToUploadFuncCall -// objects describing the invocations of this function. -func (f *ResolverGetCommitsVisibleToUploadFunc) History() []ResolverGetCommitsVisibleToUploadFuncCall { - f.mutex.Lock() - history := make([]ResolverGetCommitsVisibleToUploadFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverGetCommitsVisibleToUploadFuncCall is an object that describes an -// invocation of method GetCommitsVisibleToUpload on an instance of -// MockResolver. -type ResolverGetCommitsVisibleToUploadFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Arg2 is the value of the 3rd argument passed to this method - // invocation. - Arg2 int - // Arg3 is the value of the 4th argument passed to this method - // invocation. - Arg3 *string - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []string - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 *string - // Result2 is the value of the 3rd result returned from this method - // invocation. - Result2 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverGetCommitsVisibleToUploadFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverGetCommitsVisibleToUploadFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1, c.Result2} -} - -// ResolverGetLastUploadRetentionScanForRepositoryFunc describes the -// behavior when the GetLastUploadRetentionScanForRepository method of the -// parent MockResolver instance is invoked. -type ResolverGetLastUploadRetentionScanForRepositoryFunc struct { - defaultHook func(context.Context, int) (*time.Time, error) - hooks []func(context.Context, int) (*time.Time, error) - history []ResolverGetLastUploadRetentionScanForRepositoryFuncCall - mutex sync.Mutex -} - -// GetLastUploadRetentionScanForRepository delegates to the next hook -// function in the queue and stores the parameter and result values of this -// invocation. -func (m *MockResolver) GetLastUploadRetentionScanForRepository(v0 context.Context, v1 int) (*time.Time, error) { - r0, r1 := m.GetLastUploadRetentionScanForRepositoryFunc.nextHook()(v0, v1) - m.GetLastUploadRetentionScanForRepositoryFunc.appendCall(ResolverGetLastUploadRetentionScanForRepositoryFuncCall{v0, v1, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the -// GetLastUploadRetentionScanForRepository method of the parent MockResolver -// instance is invoked and the hook queue is empty. -func (f *ResolverGetLastUploadRetentionScanForRepositoryFunc) SetDefaultHook(hook func(context.Context, int) (*time.Time, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// GetLastUploadRetentionScanForRepository method of the parent MockResolver -// instance invokes the hook at the front of the queue and discards it. -// After the queue is empty, the default hook function is invoked for any -// future action. -func (f *ResolverGetLastUploadRetentionScanForRepositoryFunc) PushHook(hook func(context.Context, int) (*time.Time, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverGetLastUploadRetentionScanForRepositoryFunc) SetDefaultReturn(r0 *time.Time, r1 error) { - f.SetDefaultHook(func(context.Context, int) (*time.Time, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverGetLastUploadRetentionScanForRepositoryFunc) PushReturn(r0 *time.Time, r1 error) { - f.PushHook(func(context.Context, int) (*time.Time, error) { - return r0, r1 - }) -} - -func (f *ResolverGetLastUploadRetentionScanForRepositoryFunc) nextHook() func(context.Context, int) (*time.Time, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverGetLastUploadRetentionScanForRepositoryFunc) appendCall(r0 ResolverGetLastUploadRetentionScanForRepositoryFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of -// ResolverGetLastUploadRetentionScanForRepositoryFuncCall objects -// describing the invocations of this function. -func (f *ResolverGetLastUploadRetentionScanForRepositoryFunc) History() []ResolverGetLastUploadRetentionScanForRepositoryFuncCall { - f.mutex.Lock() - history := make([]ResolverGetLastUploadRetentionScanForRepositoryFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverGetLastUploadRetentionScanForRepositoryFuncCall is an object that -// describes an invocation of method GetLastUploadRetentionScanForRepository -// on an instance of MockResolver. -type ResolverGetLastUploadRetentionScanForRepositoryFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 *time.Time - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverGetLastUploadRetentionScanForRepositoryFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverGetLastUploadRetentionScanForRepositoryFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// ResolverGetRecentUploadsSummaryFunc describes the behavior when the -// GetRecentUploadsSummary method of the parent MockResolver instance is -// invoked. -type ResolverGetRecentUploadsSummaryFunc struct { - defaultHook func(context.Context, int) ([]shared.UploadsWithRepositoryNamespace, error) - hooks []func(context.Context, int) ([]shared.UploadsWithRepositoryNamespace, error) - history []ResolverGetRecentUploadsSummaryFuncCall - mutex sync.Mutex -} - -// GetRecentUploadsSummary delegates to the next hook function in the queue -// and stores the parameter and result values of this invocation. -func (m *MockResolver) GetRecentUploadsSummary(v0 context.Context, v1 int) ([]shared.UploadsWithRepositoryNamespace, error) { - r0, r1 := m.GetRecentUploadsSummaryFunc.nextHook()(v0, v1) - m.GetRecentUploadsSummaryFunc.appendCall(ResolverGetRecentUploadsSummaryFuncCall{v0, v1, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the -// GetRecentUploadsSummary method of the parent MockResolver instance is -// invoked and the hook queue is empty. -func (f *ResolverGetRecentUploadsSummaryFunc) SetDefaultHook(hook func(context.Context, int) ([]shared.UploadsWithRepositoryNamespace, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// GetRecentUploadsSummary method of the parent MockResolver instance -// invokes the hook at the front of the queue and discards it. After the -// queue is empty, the default hook function is invoked for any future -// action. -func (f *ResolverGetRecentUploadsSummaryFunc) PushHook(hook func(context.Context, int) ([]shared.UploadsWithRepositoryNamespace, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverGetRecentUploadsSummaryFunc) SetDefaultReturn(r0 []shared.UploadsWithRepositoryNamespace, r1 error) { - f.SetDefaultHook(func(context.Context, int) ([]shared.UploadsWithRepositoryNamespace, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverGetRecentUploadsSummaryFunc) PushReturn(r0 []shared.UploadsWithRepositoryNamespace, r1 error) { - f.PushHook(func(context.Context, int) ([]shared.UploadsWithRepositoryNamespace, error) { - return r0, r1 - }) -} - -func (f *ResolverGetRecentUploadsSummaryFunc) nextHook() func(context.Context, int) ([]shared.UploadsWithRepositoryNamespace, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverGetRecentUploadsSummaryFunc) appendCall(r0 ResolverGetRecentUploadsSummaryFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverGetRecentUploadsSummaryFuncCall -// objects describing the invocations of this function. -func (f *ResolverGetRecentUploadsSummaryFunc) History() []ResolverGetRecentUploadsSummaryFuncCall { - f.mutex.Lock() - history := make([]ResolverGetRecentUploadsSummaryFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverGetRecentUploadsSummaryFuncCall is an object that describes an -// invocation of method GetRecentUploadsSummary on an instance of -// MockResolver. -type ResolverGetRecentUploadsSummaryFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []shared.UploadsWithRepositoryNamespace - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverGetRecentUploadsSummaryFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverGetRecentUploadsSummaryFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// ResolverGetUploadDocumentsForPathFunc describes the behavior when the -// GetUploadDocumentsForPath method of the parent MockResolver instance is -// invoked. -type ResolverGetUploadDocumentsForPathFunc struct { - defaultHook func(context.Context, int, string) ([]string, int, error) - hooks []func(context.Context, int, string) ([]string, int, error) - history []ResolverGetUploadDocumentsForPathFuncCall - mutex sync.Mutex -} - -// GetUploadDocumentsForPath delegates to the next hook function in the -// queue and stores the parameter and result values of this invocation. -func (m *MockResolver) GetUploadDocumentsForPath(v0 context.Context, v1 int, v2 string) ([]string, int, error) { - r0, r1, r2 := m.GetUploadDocumentsForPathFunc.nextHook()(v0, v1, v2) - m.GetUploadDocumentsForPathFunc.appendCall(ResolverGetUploadDocumentsForPathFuncCall{v0, v1, v2, r0, r1, r2}) - return r0, r1, r2 -} - -// SetDefaultHook sets function that is called when the -// GetUploadDocumentsForPath method of the parent MockResolver instance is -// invoked and the hook queue is empty. -func (f *ResolverGetUploadDocumentsForPathFunc) SetDefaultHook(hook func(context.Context, int, string) ([]string, int, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// GetUploadDocumentsForPath method of the parent MockResolver instance -// invokes the hook at the front of the queue and discards it. After the -// queue is empty, the default hook function is invoked for any future -// action. -func (f *ResolverGetUploadDocumentsForPathFunc) PushHook(hook func(context.Context, int, string) ([]string, int, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverGetUploadDocumentsForPathFunc) SetDefaultReturn(r0 []string, r1 int, r2 error) { - f.SetDefaultHook(func(context.Context, int, string) ([]string, int, error) { - return r0, r1, r2 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverGetUploadDocumentsForPathFunc) PushReturn(r0 []string, r1 int, r2 error) { - f.PushHook(func(context.Context, int, string) ([]string, int, error) { - return r0, r1, r2 - }) -} - -func (f *ResolverGetUploadDocumentsForPathFunc) nextHook() func(context.Context, int, string) ([]string, int, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverGetUploadDocumentsForPathFunc) appendCall(r0 ResolverGetUploadDocumentsForPathFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverGetUploadDocumentsForPathFuncCall -// objects describing the invocations of this function. -func (f *ResolverGetUploadDocumentsForPathFunc) History() []ResolverGetUploadDocumentsForPathFuncCall { - f.mutex.Lock() - history := make([]ResolverGetUploadDocumentsForPathFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverGetUploadDocumentsForPathFuncCall is an object that describes an -// invocation of method GetUploadDocumentsForPath on an instance of -// MockResolver. -type ResolverGetUploadDocumentsForPathFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Arg2 is the value of the 3rd argument passed to this method - // invocation. - Arg2 string - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []string - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 int - // Result2 is the value of the 3rd result returned from this method - // invocation. - Result2 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverGetUploadDocumentsForPathFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1, c.Arg2} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverGetUploadDocumentsForPathFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1, c.Result2} -} - -// ResolverGetUploadsByIDsFunc describes the behavior when the -// GetUploadsByIDs method of the parent MockResolver instance is invoked. -type ResolverGetUploadsByIDsFunc struct { - defaultHook func(context.Context, ...int) ([]shared.Upload, error) - hooks []func(context.Context, ...int) ([]shared.Upload, error) - history []ResolverGetUploadsByIDsFuncCall - mutex sync.Mutex -} - -// GetUploadsByIDs delegates to the next hook function in the queue and -// stores the parameter and result values of this invocation. -func (m *MockResolver) GetUploadsByIDs(v0 context.Context, v1 ...int) ([]shared.Upload, error) { - r0, r1 := m.GetUploadsByIDsFunc.nextHook()(v0, v1...) - m.GetUploadsByIDsFunc.appendCall(ResolverGetUploadsByIDsFuncCall{v0, v1, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the GetUploadsByIDs -// method of the parent MockResolver instance is invoked and the hook queue -// is empty. -func (f *ResolverGetUploadsByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]shared.Upload, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// GetUploadsByIDs method of the parent MockResolver instance invokes the -// hook at the front of the queue and discards it. After the queue is empty, -// the default hook function is invoked for any future action. -func (f *ResolverGetUploadsByIDsFunc) PushHook(hook func(context.Context, ...int) ([]shared.Upload, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverGetUploadsByIDsFunc) SetDefaultReturn(r0 []shared.Upload, r1 error) { - f.SetDefaultHook(func(context.Context, ...int) ([]shared.Upload, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverGetUploadsByIDsFunc) PushReturn(r0 []shared.Upload, r1 error) { - f.PushHook(func(context.Context, ...int) ([]shared.Upload, error) { - return r0, r1 - }) -} - -func (f *ResolverGetUploadsByIDsFunc) nextHook() func(context.Context, ...int) ([]shared.Upload, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverGetUploadsByIDsFunc) appendCall(r0 ResolverGetUploadsByIDsFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of ResolverGetUploadsByIDsFuncCall objects -// describing the invocations of this function. -func (f *ResolverGetUploadsByIDsFunc) History() []ResolverGetUploadsByIDsFuncCall { - f.mutex.Lock() - history := make([]ResolverGetUploadsByIDsFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverGetUploadsByIDsFuncCall is an object that describes an invocation -// of method GetUploadsByIDs on an instance of MockResolver. -type ResolverGetUploadsByIDsFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is a slice containing the values of the variadic arguments - // passed to this method invocation. - Arg1 []int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []shared.Upload - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. The variadic slice argument is flattened in this array such -// that one positional argument and three variadic arguments would result in -// a slice of four, not two. -func (c ResolverGetUploadsByIDsFuncCall) Args() []interface{} { - trailing := []interface{}{} - for _, val := range c.Arg1 { - trailing = append(trailing, val) - } - - return append([]interface{}{c.Arg0}, trailing...) -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverGetUploadsByIDsFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// ResolverUploadsConnectionResolverFromFactoryFunc describes the behavior -// when the UploadsConnectionResolverFromFactory method of the parent -// MockResolver instance is invoked. -type ResolverUploadsConnectionResolverFromFactoryFunc struct { - defaultHook func(shared.GetUploadsOptions) *graphql.UploadsResolver - hooks []func(shared.GetUploadsOptions) *graphql.UploadsResolver - history []ResolverUploadsConnectionResolverFromFactoryFuncCall - mutex sync.Mutex -} - -// UploadsConnectionResolverFromFactory delegates to the next hook function -// in the queue and stores the parameter and result values of this -// invocation. -func (m *MockResolver) UploadsConnectionResolverFromFactory(v0 shared.GetUploadsOptions) *graphql.UploadsResolver { - r0 := m.UploadsConnectionResolverFromFactoryFunc.nextHook()(v0) - m.UploadsConnectionResolverFromFactoryFunc.appendCall(ResolverUploadsConnectionResolverFromFactoryFuncCall{v0, r0}) - return r0 -} - -// SetDefaultHook sets function that is called when the -// UploadsConnectionResolverFromFactory method of the parent MockResolver -// instance is invoked and the hook queue is empty. -func (f *ResolverUploadsConnectionResolverFromFactoryFunc) SetDefaultHook(hook func(shared.GetUploadsOptions) *graphql.UploadsResolver) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// UploadsConnectionResolverFromFactory method of the parent MockResolver -// instance invokes the hook at the front of the queue and discards it. -// After the queue is empty, the default hook function is invoked for any -// future action. -func (f *ResolverUploadsConnectionResolverFromFactoryFunc) PushHook(hook func(shared.GetUploadsOptions) *graphql.UploadsResolver) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *ResolverUploadsConnectionResolverFromFactoryFunc) SetDefaultReturn(r0 *graphql.UploadsResolver) { - f.SetDefaultHook(func(shared.GetUploadsOptions) *graphql.UploadsResolver { - return r0 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *ResolverUploadsConnectionResolverFromFactoryFunc) PushReturn(r0 *graphql.UploadsResolver) { - f.PushHook(func(shared.GetUploadsOptions) *graphql.UploadsResolver { - return r0 - }) -} - -func (f *ResolverUploadsConnectionResolverFromFactoryFunc) nextHook() func(shared.GetUploadsOptions) *graphql.UploadsResolver { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *ResolverUploadsConnectionResolverFromFactoryFunc) appendCall(r0 ResolverUploadsConnectionResolverFromFactoryFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of -// ResolverUploadsConnectionResolverFromFactoryFuncCall objects describing -// the invocations of this function. -func (f *ResolverUploadsConnectionResolverFromFactoryFunc) History() []ResolverUploadsConnectionResolverFromFactoryFuncCall { - f.mutex.Lock() - history := make([]ResolverUploadsConnectionResolverFromFactoryFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// ResolverUploadsConnectionResolverFromFactoryFuncCall is an object that -// describes an invocation of method UploadsConnectionResolverFromFactory on -// an instance of MockResolver. -type ResolverUploadsConnectionResolverFromFactoryFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 shared.GetUploadsOptions - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 *graphql.UploadsResolver -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c ResolverUploadsConnectionResolverFromFactoryFuncCall) Args() []interface{} { - return []interface{}{c.Arg0} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c ResolverUploadsConnectionResolverFromFactoryFuncCall) Results() []interface{} { - return []interface{}{c.Result0} -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks_test.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks_test.go deleted file mode 100644 index e05135bffa1..00000000000 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks_test.go +++ /dev/null @@ -1,291 +0,0 @@ -// Code generated by go-mockgen 1.3.4; DO NOT EDIT. -// -// This file was generated by running `sg generate` (or `go-mockgen`) at the root of -// this repository. To add additional mocks to this or another package, add a new entry -// to the mockgen.yaml file in the root of this repository. - -package resolvers - -import ( - "context" - "sync" -) - -// MockDBStore is a mock implementation of the DBStore interface (from the -// package -// github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers) -// used for unit testing. -type MockDBStore struct { - // LanguagesRequestedByFunc is an instance of a mock function object - // controlling the behavior of the method LanguagesRequestedBy. - LanguagesRequestedByFunc *DBStoreLanguagesRequestedByFunc - // RequestLanguageSupportFunc is an instance of a mock function object - // controlling the behavior of the method RequestLanguageSupport. - RequestLanguageSupportFunc *DBStoreRequestLanguageSupportFunc -} - -// NewMockDBStore creates a new mock of the DBStore interface. All methods -// return zero values for all results, unless overwritten. -func NewMockDBStore() *MockDBStore { - return &MockDBStore{ - LanguagesRequestedByFunc: &DBStoreLanguagesRequestedByFunc{ - defaultHook: func(context.Context, int) (r0 []string, r1 error) { - return - }, - }, - RequestLanguageSupportFunc: &DBStoreRequestLanguageSupportFunc{ - defaultHook: func(context.Context, int, string) (r0 error) { - return - }, - }, - } -} - -// NewStrictMockDBStore creates a new mock of the DBStore interface. All -// methods panic on invocation, unless overwritten. -func NewStrictMockDBStore() *MockDBStore { - return &MockDBStore{ - LanguagesRequestedByFunc: &DBStoreLanguagesRequestedByFunc{ - defaultHook: func(context.Context, int) ([]string, error) { - panic("unexpected invocation of MockDBStore.LanguagesRequestedBy") - }, - }, - RequestLanguageSupportFunc: &DBStoreRequestLanguageSupportFunc{ - defaultHook: func(context.Context, int, string) error { - panic("unexpected invocation of MockDBStore.RequestLanguageSupport") - }, - }, - } -} - -// NewMockDBStoreFrom creates a new mock of the MockDBStore interface. All -// methods delegate to the given implementation, unless overwritten. -func NewMockDBStoreFrom(i DBStore) *MockDBStore { - return &MockDBStore{ - LanguagesRequestedByFunc: &DBStoreLanguagesRequestedByFunc{ - defaultHook: i.LanguagesRequestedBy, - }, - RequestLanguageSupportFunc: &DBStoreRequestLanguageSupportFunc{ - defaultHook: i.RequestLanguageSupport, - }, - } -} - -// DBStoreLanguagesRequestedByFunc describes the behavior when the -// LanguagesRequestedBy method of the parent MockDBStore instance is -// invoked. -type DBStoreLanguagesRequestedByFunc struct { - defaultHook func(context.Context, int) ([]string, error) - hooks []func(context.Context, int) ([]string, error) - history []DBStoreLanguagesRequestedByFuncCall - mutex sync.Mutex -} - -// LanguagesRequestedBy delegates to the next hook function in the queue and -// stores the parameter and result values of this invocation. -func (m *MockDBStore) LanguagesRequestedBy(v0 context.Context, v1 int) ([]string, error) { - r0, r1 := m.LanguagesRequestedByFunc.nextHook()(v0, v1) - m.LanguagesRequestedByFunc.appendCall(DBStoreLanguagesRequestedByFuncCall{v0, v1, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the LanguagesRequestedBy -// method of the parent MockDBStore instance is invoked and the hook queue -// is empty. -func (f *DBStoreLanguagesRequestedByFunc) SetDefaultHook(hook func(context.Context, int) ([]string, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// LanguagesRequestedBy method of the parent MockDBStore instance invokes -// the hook at the front of the queue and discards it. After the queue is -// empty, the default hook function is invoked for any future action. -func (f *DBStoreLanguagesRequestedByFunc) PushHook(hook func(context.Context, int) ([]string, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *DBStoreLanguagesRequestedByFunc) SetDefaultReturn(r0 []string, r1 error) { - f.SetDefaultHook(func(context.Context, int) ([]string, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *DBStoreLanguagesRequestedByFunc) PushReturn(r0 []string, r1 error) { - f.PushHook(func(context.Context, int) ([]string, error) { - return r0, r1 - }) -} - -func (f *DBStoreLanguagesRequestedByFunc) nextHook() func(context.Context, int) ([]string, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *DBStoreLanguagesRequestedByFunc) appendCall(r0 DBStoreLanguagesRequestedByFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of DBStoreLanguagesRequestedByFuncCall objects -// describing the invocations of this function. -func (f *DBStoreLanguagesRequestedByFunc) History() []DBStoreLanguagesRequestedByFuncCall { - f.mutex.Lock() - history := make([]DBStoreLanguagesRequestedByFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// DBStoreLanguagesRequestedByFuncCall is an object that describes an -// invocation of method LanguagesRequestedBy on an instance of MockDBStore. -type DBStoreLanguagesRequestedByFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []string - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c DBStoreLanguagesRequestedByFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c DBStoreLanguagesRequestedByFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// DBStoreRequestLanguageSupportFunc describes the behavior when the -// RequestLanguageSupport method of the parent MockDBStore instance is -// invoked. -type DBStoreRequestLanguageSupportFunc struct { - defaultHook func(context.Context, int, string) error - hooks []func(context.Context, int, string) error - history []DBStoreRequestLanguageSupportFuncCall - mutex sync.Mutex -} - -// RequestLanguageSupport delegates to the next hook function in the queue -// and stores the parameter and result values of this invocation. -func (m *MockDBStore) RequestLanguageSupport(v0 context.Context, v1 int, v2 string) error { - r0 := m.RequestLanguageSupportFunc.nextHook()(v0, v1, v2) - m.RequestLanguageSupportFunc.appendCall(DBStoreRequestLanguageSupportFuncCall{v0, v1, v2, r0}) - return r0 -} - -// SetDefaultHook sets function that is called when the -// RequestLanguageSupport method of the parent MockDBStore instance is -// invoked and the hook queue is empty. -func (f *DBStoreRequestLanguageSupportFunc) SetDefaultHook(hook func(context.Context, int, string) error) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// RequestLanguageSupport method of the parent MockDBStore instance invokes -// the hook at the front of the queue and discards it. After the queue is -// empty, the default hook function is invoked for any future action. -func (f *DBStoreRequestLanguageSupportFunc) PushHook(hook func(context.Context, int, string) error) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *DBStoreRequestLanguageSupportFunc) SetDefaultReturn(r0 error) { - f.SetDefaultHook(func(context.Context, int, string) error { - return r0 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *DBStoreRequestLanguageSupportFunc) PushReturn(r0 error) { - f.PushHook(func(context.Context, int, string) error { - return r0 - }) -} - -func (f *DBStoreRequestLanguageSupportFunc) nextHook() func(context.Context, int, string) error { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *DBStoreRequestLanguageSupportFunc) appendCall(r0 DBStoreRequestLanguageSupportFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of DBStoreRequestLanguageSupportFuncCall -// objects describing the invocations of this function. -func (f *DBStoreRequestLanguageSupportFunc) History() []DBStoreRequestLanguageSupportFuncCall { - f.mutex.Lock() - history := make([]DBStoreRequestLanguageSupportFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// DBStoreRequestLanguageSupportFuncCall is an object that describes an -// invocation of method RequestLanguageSupport on an instance of -// MockDBStore. -type DBStoreRequestLanguageSupportFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Arg2 is the value of the 3rd argument passed to this method - // invocation. - Arg2 string - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c DBStoreRequestLanguageSupportFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1, c.Arg2} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c DBStoreRequestLanguageSupportFuncCall) Results() []interface{} { - return []interface{}{c.Result0} -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/resolver.go b/enterprise/cmd/frontend/internal/codeintel/resolvers/resolver.go index fbefdc30222..216edde1988 100644 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/resolver.go +++ b/enterprise/cmd/frontend/internal/codeintel/resolvers/resolver.go @@ -1,6 +1,10 @@ package resolvers import ( + autoindexinggraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/transport/graphql" + codenavgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql" + policiesgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/transport/graphql" + uploadsgraphql "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/transport/graphql" executor "github.com/sourcegraph/sourcegraph/internal/services/executors/transport/graphql" ) @@ -11,51 +15,51 @@ import ( // by the API. type Resolver interface { ExecutorResolver() executor.Resolver - CodeNavResolver() CodeNavResolver - PoliciesResolver() PoliciesResolver - AutoIndexingResolver() AutoIndexingResolver - UploadsResolver() UploadsResolver + CodeNavResolver() codenavgraphql.RootResolver + PoliciesRootResolver() policiesgraphql.RootResolver + AutoIndexingRootResolver() autoindexinggraphql.RootResolver + UploadRootResolver() uploadsgraphql.RootResolver } type resolver struct { - executorResolver executor.Resolver - codenavResolver CodeNavResolver - policiesResolver PoliciesResolver - autoIndexingResolver AutoIndexingResolver - uploadsResolver UploadsResolver + executorResolver executor.Resolver + codenavResolver codenavgraphql.RootResolver + policiesRootResolver policiesgraphql.RootResolver + autoIndexingRootResolver autoindexinggraphql.RootResolver + uploadsRootResolver uploadsgraphql.RootResolver } // NewResolver creates a new resolver with the given services. func NewResolver( - codenavResolver CodeNavResolver, + codenavResolver codenavgraphql.RootResolver, executorResolver executor.Resolver, - policiesResolver PoliciesResolver, - autoIndexingResolver AutoIndexingResolver, - uploadsResolver UploadsResolver, + policiesRootResolver policiesgraphql.RootResolver, + autoIndexingRootResolver autoindexinggraphql.RootResolver, + uploadsRootResolver uploadsgraphql.RootResolver, ) Resolver { return &resolver{ - executorResolver: executorResolver, - codenavResolver: codenavResolver, - policiesResolver: policiesResolver, - autoIndexingResolver: autoIndexingResolver, - uploadsResolver: uploadsResolver, + executorResolver: executorResolver, + codenavResolver: codenavResolver, + policiesRootResolver: policiesRootResolver, + autoIndexingRootResolver: autoIndexingRootResolver, + uploadsRootResolver: uploadsRootResolver, } } -func (r *resolver) CodeNavResolver() CodeNavResolver { +func (r *resolver) CodeNavResolver() codenavgraphql.RootResolver { return r.codenavResolver } -func (r *resolver) PoliciesResolver() PoliciesResolver { - return r.policiesResolver +func (r *resolver) PoliciesRootResolver() policiesgraphql.RootResolver { + return r.policiesRootResolver } -func (r *resolver) AutoIndexingResolver() AutoIndexingResolver { - return r.autoIndexingResolver +func (r *resolver) AutoIndexingRootResolver() autoindexinggraphql.RootResolver { + return r.autoIndexingRootResolver } -func (r *resolver) UploadsResolver() UploadsResolver { - return r.uploadsResolver +func (r *resolver) UploadRootResolver() uploadsgraphql.RootResolver { + return r.uploadsRootResolver } func (r *resolver) ExecutorResolver() executor.Resolver { diff --git a/enterprise/cmd/frontend/internal/codeintel/services.go b/enterprise/cmd/frontend/internal/codeintel/services.go index 4e7f027688e..490086d81da 100644 --- a/enterprise/cmd/frontend/internal/codeintel/services.go +++ b/enterprise/cmd/frontend/internal/codeintel/services.go @@ -24,13 +24,10 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database" connections "github.com/sourcegraph/sourcegraph/internal/database/connections/live" "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/internal/symbols" "github.com/sourcegraph/sourcegraph/internal/trace" ) type Services struct { - dbStore *store.Store - // shared with executor queue InternalUploadHandler http.Handler ExternalUploadHandler http.Handler @@ -73,7 +70,7 @@ func NewServices(ctx context.Context, config *Config, siteConfig conftypes.Watch // Initialize services uploadSvc := uploads.GetService(db, codeIntelLsifStore, gitserverClient) - codenavSvc := codenav.GetService(db, codeIntelLsifStore, uploadSvc, gitserverClient, symbols.DefaultClient) + codenavSvc := codenav.GetService(db, codeIntelLsifStore, uploadSvc, gitserverClient) policySvc := policies.GetService(db, uploadSvc, gitserverClient) autoindexingSvc := autoindexing.GetService(db, uploadSvc, gitserverClient, repoUpdaterClient) @@ -85,8 +82,6 @@ func NewServices(ctx context.Context, config *Config, siteConfig conftypes.Watch externalUploadHandler := newUploadHandler(true) return &Services{ - dbStore: dbStore, - InternalUploadHandler: internalUploadHandler, ExternalUploadHandler: externalUploadHandler, diff --git a/enterprise/cmd/worker/internal/codeintel/indexing/iface.go b/enterprise/cmd/worker/internal/codeintel/indexing/iface.go index eb915df1895..5f74ea035d6 100644 --- a/enterprise/cmd/worker/internal/codeintel/indexing/iface.go +++ b/enterprise/cmd/worker/internal/codeintel/indexing/iface.go @@ -7,9 +7,9 @@ import ( "github.com/grafana/regexp" "github.com/sourcegraph/sourcegraph/internal/api" - autoindexingShared "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" policies "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/enterprise" "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" + codeinteltypes "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/conf" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" @@ -70,7 +70,7 @@ type GitserverClient interface { } type IndexEnqueuer interface { - QueueIndexes(ctx context.Context, repositoryID int, rev, configuration string, force, bypassLimit bool) ([]autoindexingShared.Index, error) + QueueIndexes(ctx context.Context, repositoryID int, rev, configuration string, force, bypassLimit bool) ([]codeinteltypes.Index, error) QueueIndexesForPackage(ctx context.Context, pkg precise.Package) error } diff --git a/enterprise/cmd/worker/internal/codeintel/indexing/mocks_test.go b/enterprise/cmd/worker/internal/codeintel/indexing/mocks_test.go index 8e487a79936..b7fec769877 100644 --- a/enterprise/cmd/worker/internal/codeintel/indexing/mocks_test.go +++ b/enterprise/cmd/worker/internal/codeintel/indexing/mocks_test.go @@ -14,10 +14,10 @@ import ( regexp "github.com/grafana/regexp" sqlf "github.com/keegancsmith/sqlf" api "github.com/sourcegraph/sourcegraph/internal/api" - shared "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" enterprise "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/enterprise" dbstore "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - shared1 "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/shared" + shared "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/shared" + types1 "github.com/sourcegraph/sourcegraph/internal/codeintel/types" database "github.com/sourcegraph/sourcegraph/internal/database" basestore "github.com/sourcegraph/sourcegraph/internal/database/basestore" protocol "github.com/sourcegraph/sourcegraph/internal/repoupdater/protocol" @@ -1827,7 +1827,7 @@ type MockIndexEnqueuer struct { func NewMockIndexEnqueuer() *MockIndexEnqueuer { return &MockIndexEnqueuer{ QueueIndexesFunc: &IndexEnqueuerQueueIndexesFunc{ - defaultHook: func(context.Context, int, string, string, bool, bool) (r0 []shared.Index, r1 error) { + defaultHook: func(context.Context, int, string, string, bool, bool) (r0 []types1.Index, r1 error) { return }, }, @@ -1844,7 +1844,7 @@ func NewMockIndexEnqueuer() *MockIndexEnqueuer { func NewStrictMockIndexEnqueuer() *MockIndexEnqueuer { return &MockIndexEnqueuer{ QueueIndexesFunc: &IndexEnqueuerQueueIndexesFunc{ - defaultHook: func(context.Context, int, string, string, bool, bool) ([]shared.Index, error) { + defaultHook: func(context.Context, int, string, string, bool, bool) ([]types1.Index, error) { panic("unexpected invocation of MockIndexEnqueuer.QueueIndexes") }, }, @@ -1873,15 +1873,15 @@ func NewMockIndexEnqueuerFrom(i IndexEnqueuer) *MockIndexEnqueuer { // IndexEnqueuerQueueIndexesFunc describes the behavior when the // QueueIndexes method of the parent MockIndexEnqueuer instance is invoked. type IndexEnqueuerQueueIndexesFunc struct { - defaultHook func(context.Context, int, string, string, bool, bool) ([]shared.Index, error) - hooks []func(context.Context, int, string, string, bool, bool) ([]shared.Index, error) + defaultHook func(context.Context, int, string, string, bool, bool) ([]types1.Index, error) + hooks []func(context.Context, int, string, string, bool, bool) ([]types1.Index, error) history []IndexEnqueuerQueueIndexesFuncCall mutex sync.Mutex } // QueueIndexes delegates to the next hook function in the queue and stores // the parameter and result values of this invocation. -func (m *MockIndexEnqueuer) QueueIndexes(v0 context.Context, v1 int, v2 string, v3 string, v4 bool, v5 bool) ([]shared.Index, error) { +func (m *MockIndexEnqueuer) QueueIndexes(v0 context.Context, v1 int, v2 string, v3 string, v4 bool, v5 bool) ([]types1.Index, error) { r0, r1 := m.QueueIndexesFunc.nextHook()(v0, v1, v2, v3, v4, v5) m.QueueIndexesFunc.appendCall(IndexEnqueuerQueueIndexesFuncCall{v0, v1, v2, v3, v4, v5, r0, r1}) return r0, r1 @@ -1890,7 +1890,7 @@ func (m *MockIndexEnqueuer) QueueIndexes(v0 context.Context, v1 int, v2 string, // SetDefaultHook sets function that is called when the QueueIndexes method // of the parent MockIndexEnqueuer instance is invoked and the hook queue is // empty. -func (f *IndexEnqueuerQueueIndexesFunc) SetDefaultHook(hook func(context.Context, int, string, string, bool, bool) ([]shared.Index, error)) { +func (f *IndexEnqueuerQueueIndexesFunc) SetDefaultHook(hook func(context.Context, int, string, string, bool, bool) ([]types1.Index, error)) { f.defaultHook = hook } @@ -1898,7 +1898,7 @@ func (f *IndexEnqueuerQueueIndexesFunc) SetDefaultHook(hook func(context.Context // QueueIndexes method of the parent MockIndexEnqueuer instance invokes the // hook at the front of the queue and discards it. After the queue is empty, // the default hook function is invoked for any future action. -func (f *IndexEnqueuerQueueIndexesFunc) PushHook(hook func(context.Context, int, string, string, bool, bool) ([]shared.Index, error)) { +func (f *IndexEnqueuerQueueIndexesFunc) PushHook(hook func(context.Context, int, string, string, bool, bool) ([]types1.Index, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -1906,20 +1906,20 @@ func (f *IndexEnqueuerQueueIndexesFunc) PushHook(hook func(context.Context, int, // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *IndexEnqueuerQueueIndexesFunc) SetDefaultReturn(r0 []shared.Index, r1 error) { - f.SetDefaultHook(func(context.Context, int, string, string, bool, bool) ([]shared.Index, error) { +func (f *IndexEnqueuerQueueIndexesFunc) SetDefaultReturn(r0 []types1.Index, r1 error) { + f.SetDefaultHook(func(context.Context, int, string, string, bool, bool) ([]types1.Index, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *IndexEnqueuerQueueIndexesFunc) PushReturn(r0 []shared.Index, r1 error) { - f.PushHook(func(context.Context, int, string, string, bool, bool) ([]shared.Index, error) { +func (f *IndexEnqueuerQueueIndexesFunc) PushReturn(r0 []types1.Index, r1 error) { + f.PushHook(func(context.Context, int, string, string, bool, bool) ([]types1.Index, error) { return r0, r1 }) } -func (f *IndexEnqueuerQueueIndexesFunc) nextHook() func(context.Context, int, string, string, bool, bool) ([]shared.Index, error) { +func (f *IndexEnqueuerQueueIndexesFunc) nextHook() func(context.Context, int, string, string, bool, bool) ([]types1.Index, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -1972,7 +1972,7 @@ type IndexEnqueuerQueueIndexesFuncCall struct { Arg5 bool // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.Index + Result0 []types1.Index // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error @@ -3047,7 +3047,7 @@ func NewMockPackageReferenceScanner() *MockPackageReferenceScanner { }, }, NextFunc: &PackageReferenceScannerNextFunc{ - defaultHook: func() (r0 shared1.PackageReference, r1 bool, r2 error) { + defaultHook: func() (r0 shared.PackageReference, r1 bool, r2 error) { return }, }, @@ -3065,7 +3065,7 @@ func NewStrictMockPackageReferenceScanner() *MockPackageReferenceScanner { }, }, NextFunc: &PackageReferenceScannerNextFunc{ - defaultHook: func() (shared1.PackageReference, bool, error) { + defaultHook: func() (shared.PackageReference, bool, error) { panic("unexpected invocation of MockPackageReferenceScanner.Next") }, }, @@ -3188,15 +3188,15 @@ func (c PackageReferenceScannerCloseFuncCall) Results() []interface{} { // PackageReferenceScannerNextFunc describes the behavior when the Next // method of the parent MockPackageReferenceScanner instance is invoked. type PackageReferenceScannerNextFunc struct { - defaultHook func() (shared1.PackageReference, bool, error) - hooks []func() (shared1.PackageReference, bool, error) + defaultHook func() (shared.PackageReference, bool, error) + hooks []func() (shared.PackageReference, bool, error) history []PackageReferenceScannerNextFuncCall mutex sync.Mutex } // Next delegates to the next hook function in the queue and stores the // parameter and result values of this invocation. -func (m *MockPackageReferenceScanner) Next() (shared1.PackageReference, bool, error) { +func (m *MockPackageReferenceScanner) Next() (shared.PackageReference, bool, error) { r0, r1, r2 := m.NextFunc.nextHook()() m.NextFunc.appendCall(PackageReferenceScannerNextFuncCall{r0, r1, r2}) return r0, r1, r2 @@ -3205,7 +3205,7 @@ func (m *MockPackageReferenceScanner) Next() (shared1.PackageReference, bool, er // SetDefaultHook sets function that is called when the Next method of the // parent MockPackageReferenceScanner instance is invoked and the hook queue // is empty. -func (f *PackageReferenceScannerNextFunc) SetDefaultHook(hook func() (shared1.PackageReference, bool, error)) { +func (f *PackageReferenceScannerNextFunc) SetDefaultHook(hook func() (shared.PackageReference, bool, error)) { f.defaultHook = hook } @@ -3213,7 +3213,7 @@ func (f *PackageReferenceScannerNextFunc) SetDefaultHook(hook func() (shared1.Pa // Next method of the parent MockPackageReferenceScanner instance invokes // the hook at the front of the queue and discards it. After the queue is // empty, the default hook function is invoked for any future action. -func (f *PackageReferenceScannerNextFunc) PushHook(hook func() (shared1.PackageReference, bool, error)) { +func (f *PackageReferenceScannerNextFunc) PushHook(hook func() (shared.PackageReference, bool, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -3221,20 +3221,20 @@ func (f *PackageReferenceScannerNextFunc) PushHook(hook func() (shared1.PackageR // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *PackageReferenceScannerNextFunc) SetDefaultReturn(r0 shared1.PackageReference, r1 bool, r2 error) { - f.SetDefaultHook(func() (shared1.PackageReference, bool, error) { +func (f *PackageReferenceScannerNextFunc) SetDefaultReturn(r0 shared.PackageReference, r1 bool, r2 error) { + f.SetDefaultHook(func() (shared.PackageReference, bool, error) { return r0, r1, r2 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *PackageReferenceScannerNextFunc) PushReturn(r0 shared1.PackageReference, r1 bool, r2 error) { - f.PushHook(func() (shared1.PackageReference, bool, error) { +func (f *PackageReferenceScannerNextFunc) PushReturn(r0 shared.PackageReference, r1 bool, r2 error) { + f.PushHook(func() (shared.PackageReference, bool, error) { return r0, r1, r2 }) } -func (f *PackageReferenceScannerNextFunc) nextHook() func() (shared1.PackageReference, bool, error) { +func (f *PackageReferenceScannerNextFunc) nextHook() func() (shared.PackageReference, bool, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -3269,7 +3269,7 @@ func (f *PackageReferenceScannerNextFunc) History() []PackageReferenceScannerNex type PackageReferenceScannerNextFuncCall struct { // Result0 is the value of the 1st result returned from this method // invocation. - Result0 shared1.PackageReference + Result0 shared.PackageReference // Result1 is the value of the 2nd result returned from this method // invocation. Result1 bool diff --git a/cmd/frontend/internal/cloneurls/clone_urls.go b/internal/cloneurls/clone_urls.go similarity index 100% rename from cmd/frontend/internal/cloneurls/clone_urls.go rename to internal/cloneurls/clone_urls.go diff --git a/cmd/frontend/internal/cloneurls/clone_urls_test.go b/internal/cloneurls/clone_urls_test.go similarity index 100% rename from cmd/frontend/internal/cloneurls/clone_urls_test.go rename to internal/cloneurls/clone_urls_test.go diff --git a/internal/codeintel/autoindexing/background/scheduler/iface.go b/internal/codeintel/autoindexing/background/scheduler/iface.go index 5d15afe7337..6e61a407e5e 100644 --- a/internal/codeintel/autoindexing/background/scheduler/iface.go +++ b/internal/codeintel/autoindexing/background/scheduler/iface.go @@ -5,15 +5,15 @@ import ( "time" policies "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/enterprise" - "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" ) type PolicyMatcher interface { - CommitsDescribedByPolicyInternal(ctx context.Context, repositoryID int, policies []shared.ConfigurationPolicy, now time.Time, filterCommits ...string) (map[string][]policies.PolicyMatch, error) + CommitsDescribedByPolicyInternal(ctx context.Context, repositoryID int, policies []types.ConfigurationPolicy, now time.Time, filterCommits ...string) (map[string][]policies.PolicyMatch, error) } type PolicyService interface { - GetConfigurationPolicies(ctx context.Context, opts shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) + GetConfigurationPolicies(ctx context.Context, opts types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) } type UploadService interface { diff --git a/internal/codeintel/autoindexing/background/scheduler/mocks_test.go b/internal/codeintel/autoindexing/background/scheduler/mocks_test.go index 6918787e574..9c075520aa6 100644 --- a/internal/codeintel/autoindexing/background/scheduler/mocks_test.go +++ b/internal/codeintel/autoindexing/background/scheduler/mocks_test.go @@ -12,7 +12,7 @@ import ( "time" enterprise "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/enterprise" - shared "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" + types "github.com/sourcegraph/sourcegraph/internal/codeintel/types" ) // MockPolicyMatcher is a mock implementation of the PolicyMatcher interface @@ -31,7 +31,7 @@ type MockPolicyMatcher struct { func NewMockPolicyMatcher() *MockPolicyMatcher { return &MockPolicyMatcher{ CommitsDescribedByPolicyInternalFunc: &PolicyMatcherCommitsDescribedByPolicyInternalFunc{ - defaultHook: func(context.Context, int, []shared.ConfigurationPolicy, time.Time, ...string) (r0 map[string][]enterprise.PolicyMatch, r1 error) { + defaultHook: func(context.Context, int, []types.ConfigurationPolicy, time.Time, ...string) (r0 map[string][]enterprise.PolicyMatch, r1 error) { return }, }, @@ -43,7 +43,7 @@ func NewMockPolicyMatcher() *MockPolicyMatcher { func NewStrictMockPolicyMatcher() *MockPolicyMatcher { return &MockPolicyMatcher{ CommitsDescribedByPolicyInternalFunc: &PolicyMatcherCommitsDescribedByPolicyInternalFunc{ - defaultHook: func(context.Context, int, []shared.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error) { + defaultHook: func(context.Context, int, []types.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error) { panic("unexpected invocation of MockPolicyMatcher.CommitsDescribedByPolicyInternal") }, }, @@ -65,15 +65,15 @@ func NewMockPolicyMatcherFrom(i PolicyMatcher) *MockPolicyMatcher { // when the CommitsDescribedByPolicyInternal method of the parent // MockPolicyMatcher instance is invoked. type PolicyMatcherCommitsDescribedByPolicyInternalFunc struct { - defaultHook func(context.Context, int, []shared.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error) - hooks []func(context.Context, int, []shared.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error) + defaultHook func(context.Context, int, []types.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error) + hooks []func(context.Context, int, []types.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error) history []PolicyMatcherCommitsDescribedByPolicyInternalFuncCall mutex sync.Mutex } // CommitsDescribedByPolicyInternal delegates to the next hook function in // the queue and stores the parameter and result values of this invocation. -func (m *MockPolicyMatcher) CommitsDescribedByPolicyInternal(v0 context.Context, v1 int, v2 []shared.ConfigurationPolicy, v3 time.Time, v4 ...string) (map[string][]enterprise.PolicyMatch, error) { +func (m *MockPolicyMatcher) CommitsDescribedByPolicyInternal(v0 context.Context, v1 int, v2 []types.ConfigurationPolicy, v3 time.Time, v4 ...string) (map[string][]enterprise.PolicyMatch, error) { r0, r1 := m.CommitsDescribedByPolicyInternalFunc.nextHook()(v0, v1, v2, v3, v4...) m.CommitsDescribedByPolicyInternalFunc.appendCall(PolicyMatcherCommitsDescribedByPolicyInternalFuncCall{v0, v1, v2, v3, v4, r0, r1}) return r0, r1 @@ -82,7 +82,7 @@ func (m *MockPolicyMatcher) CommitsDescribedByPolicyInternal(v0 context.Context, // SetDefaultHook sets function that is called when the // CommitsDescribedByPolicyInternal method of the parent MockPolicyMatcher // instance is invoked and the hook queue is empty. -func (f *PolicyMatcherCommitsDescribedByPolicyInternalFunc) SetDefaultHook(hook func(context.Context, int, []shared.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error)) { +func (f *PolicyMatcherCommitsDescribedByPolicyInternalFunc) SetDefaultHook(hook func(context.Context, int, []types.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error)) { f.defaultHook = hook } @@ -91,7 +91,7 @@ func (f *PolicyMatcherCommitsDescribedByPolicyInternalFunc) SetDefaultHook(hook // instance invokes the hook at the front of the queue and discards it. // After the queue is empty, the default hook function is invoked for any // future action. -func (f *PolicyMatcherCommitsDescribedByPolicyInternalFunc) PushHook(hook func(context.Context, int, []shared.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error)) { +func (f *PolicyMatcherCommitsDescribedByPolicyInternalFunc) PushHook(hook func(context.Context, int, []types.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -100,19 +100,19 @@ func (f *PolicyMatcherCommitsDescribedByPolicyInternalFunc) PushHook(hook func(c // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. func (f *PolicyMatcherCommitsDescribedByPolicyInternalFunc) SetDefaultReturn(r0 map[string][]enterprise.PolicyMatch, r1 error) { - f.SetDefaultHook(func(context.Context, int, []shared.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error) { + f.SetDefaultHook(func(context.Context, int, []types.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. func (f *PolicyMatcherCommitsDescribedByPolicyInternalFunc) PushReturn(r0 map[string][]enterprise.PolicyMatch, r1 error) { - f.PushHook(func(context.Context, int, []shared.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error) { + f.PushHook(func(context.Context, int, []types.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error) { return r0, r1 }) } -func (f *PolicyMatcherCommitsDescribedByPolicyInternalFunc) nextHook() func(context.Context, int, []shared.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error) { +func (f *PolicyMatcherCommitsDescribedByPolicyInternalFunc) nextHook() func(context.Context, int, []types.ConfigurationPolicy, time.Time, ...string) (map[string][]enterprise.PolicyMatch, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -155,7 +155,7 @@ type PolicyMatcherCommitsDescribedByPolicyInternalFuncCall struct { Arg1 int // Arg2 is the value of the 3rd argument passed to this method // invocation. - Arg2 []shared.ConfigurationPolicy + Arg2 []types.ConfigurationPolicy // Arg3 is the value of the 4th argument passed to this method // invocation. Arg3 time.Time diff --git a/internal/codeintel/autoindexing/background/scheduler/scheduler.go b/internal/codeintel/autoindexing/background/scheduler/scheduler.go index 1a6b725dee0..9f0db2110e8 100644 --- a/internal/codeintel/autoindexing/background/scheduler/scheduler.go +++ b/internal/codeintel/autoindexing/background/scheduler/scheduler.go @@ -7,7 +7,7 @@ import ( "github.com/sourcegraph/log" "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing" - "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/conf" "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" "github.com/sourcegraph/sourcegraph/internal/goroutine" @@ -83,7 +83,7 @@ func (s *scheduler) handleRepository(ctx context.Context, repositoryID int, now for { // Retrieve the set of configuration policies that affect indexing for this repository. - policies, totalCount, err := s.policySvc.GetConfigurationPolicies(ctx, shared.GetConfigurationPoliciesOptions{ + policies, totalCount, err := s.policySvc.GetConfigurationPolicies(ctx, types.GetConfigurationPoliciesOptions{ RepositoryID: repositoryID, ForIndexing: true, Limit: ConfigInst.PolicyBatchSize, diff --git a/internal/codeintel/autoindexing/init.go b/internal/codeintel/autoindexing/init.go index a0945329a61..52005421091 100644 --- a/internal/codeintel/autoindexing/init.go +++ b/internal/codeintel/autoindexing/init.go @@ -15,6 +15,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/env" "github.com/sourcegraph/sourcegraph/internal/observation" + "github.com/sourcegraph/sourcegraph/internal/symbols" "github.com/sourcegraph/sourcegraph/internal/trace" ) @@ -43,8 +44,9 @@ func GetService(db database.DB, uploadSvc shared.UploadService, gitserver shared s := store.New(db, oc("store")) inf := inference.GetService(db) + sclient := symbols.DefaultClient - svc = newService(s, uploadSvc, gitserver, repoUpdater, inf, oc("service")) + svc = newService(s, uploadSvc, gitserver, sclient, repoUpdater, inf, oc("service")) }) return svc diff --git a/internal/codeintel/autoindexing/internal/store/observability.go b/internal/codeintel/autoindexing/internal/store/observability.go index 27beec312d6..bbdfea230f1 100644 --- a/internal/codeintel/autoindexing/internal/store/observability.go +++ b/internal/codeintel/autoindexing/internal/store/observability.go @@ -33,6 +33,10 @@ type operations struct { // Index Configuration getIndexConfigurationByRepositoryID *observation.Operation updateIndexConfigurationByRepositoryID *observation.Operation + + // Language Support + getLanguagesRequestedBy *observation.Operation + setRequestLanguageSupport *observation.Operation } func newOperations(observationContext *observation.Context) *operations { @@ -81,5 +85,9 @@ func newOperations(observationContext *observation.Context) *operations { // Index Configuration getIndexConfigurationByRepositoryID: op("GetIndexConfigurationByRepositoryID"), updateIndexConfigurationByRepositoryID: op("UpdateIndexConfigurationByRepositoryID"), + + // Language Support + getLanguagesRequestedBy: op("GetLanguagesRequestedBy"), + setRequestLanguageSupport: op("SetRequestLanguageSupport"), } } diff --git a/internal/codeintel/autoindexing/internal/store/scan.go b/internal/codeintel/autoindexing/internal/store/scan.go index 25bb922f9fa..59168ead649 100644 --- a/internal/codeintel/autoindexing/internal/store/scan.go +++ b/internal/codeintel/autoindexing/internal/store/scan.go @@ -9,6 +9,7 @@ import ( "github.com/lib/pq" "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/database/dbutil" ) @@ -19,8 +20,8 @@ var scanIndexes = basestore.NewSliceScanner(scanIndex) // scanFirstIndex scans a slice of indexes from the return value of `*Store.query` and returns the first. var scanFirstIndex = basestore.NewFirstScanner(scanIndex) -func scanIndex(s dbutil.Scanner) (index shared.Index, err error) { - var executionLogs []shared.ExecutionLogEntry +func scanIndex(s dbutil.Scanner) (index types.Index, err error) { + var executionLogs []types.ExecutionLogEntry if err := s.Scan( &index.ID, &index.Commit, @@ -76,8 +77,8 @@ func scanIndexConfiguration(s dbutil.Scanner) (indexConfiguration shared.IndexCo var scanIndexesWithCount = basestore.NewSliceWithCountScanner(scanIndexWithCount) // scanIndexes scans a slice of indexes from the return value of `*Store.query`. -func scanIndexWithCount(s dbutil.Scanner) (index shared.Index, count int, err error) { - var executionLogs []shared.ExecutionLogEntry +func scanIndexWithCount(s dbutil.Scanner) (index types.Index, count int, err error) { + var executionLogs []types.ExecutionLogEntry if err := s.Scan( &index.ID, diff --git a/internal/codeintel/autoindexing/internal/store/store.go b/internal/codeintel/autoindexing/internal/store/store.go index 8d32c2a7869..4a23390ca5f 100644 --- a/internal/codeintel/autoindexing/internal/store/store.go +++ b/internal/codeintel/autoindexing/internal/store/store.go @@ -7,6 +7,7 @@ import ( logger "github.com/sourcegraph/log" "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/observation" @@ -24,10 +25,10 @@ type Store interface { DeleteSourcedCommits(ctx context.Context, repositoryID int, commit string, maximumCommitLag time.Duration) (indexesDeleted int, err error) // Indexes - InsertIndexes(ctx context.Context, indexes []shared.Index) (_ []shared.Index, err error) - GetIndexes(ctx context.Context, opts shared.GetIndexesOptions) (_ []shared.Index, _ int, err error) - GetIndexByID(ctx context.Context, id int) (_ shared.Index, _ bool, err error) - GetIndexesByIDs(ctx context.Context, ids ...int) (_ []shared.Index, err error) + InsertIndexes(ctx context.Context, indexes []types.Index) (_ []types.Index, err error) + GetIndexes(ctx context.Context, opts types.GetIndexesOptions) (_ []types.Index, _ int, err error) + GetIndexByID(ctx context.Context, id int) (_ types.Index, _ bool, err error) + GetIndexesByIDs(ctx context.Context, ids ...int) (_ []types.Index, err error) GetRecentIndexesSummary(ctx context.Context, repositoryID int) (summaries []shared.IndexesWithRepositoryNamespace, err error) GetLastIndexScanForRepository(ctx context.Context, repositoryID int) (_ *time.Time, err error) DeleteIndexByID(ctx context.Context, id int) (_ bool, err error) @@ -40,12 +41,14 @@ type Store interface { // Index configurations GetIndexConfigurationByRepositoryID(ctx context.Context, repositoryID int) (_ shared.IndexConfiguration, _ bool, err error) UpdateIndexConfigurationByRepositoryID(ctx context.Context, repositoryID int, data []byte) (err error) -} -type RepoRev struct { - ID int - RepositoryID int - Rev string + // Language support + GetLanguagesRequestedBy(ctx context.Context, userID int) (_ []string, err error) + SetRequestLanguageSupport(ctx context.Context, userID int, language string) (err error) + + // GetUnsafeDB returns the underlying database handle. This is used by the + // resolvers that have the old convention of using the database handle directly. + GetUnsafeDB() database.DB } // store manages the autoindexing store. @@ -84,3 +87,9 @@ func (s *store) transact(ctx context.Context) (*store, error) { func (s *store) Done(err error) error { return s.db.Done(err) } + +// GetUnsafeDB returns the underlying database handle. This is used by the +// resolvers that have the old convention of using the database handle directly. +func (s *store) GetUnsafeDB() database.DB { + return database.NewDBWith(s.logger, s.db) +} diff --git a/internal/codeintel/autoindexing/internal/store/store_indexes.go b/internal/codeintel/autoindexing/internal/store/store_indexes.go index 24bd6dcb735..b920ce53070 100644 --- a/internal/codeintel/autoindexing/internal/store/store_indexes.go +++ b/internal/codeintel/autoindexing/internal/store/store_indexes.go @@ -9,13 +9,14 @@ import ( "github.com/opentracing/opentracing-go/log" "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/observation" ) // InsertIndexes inserts a new index and returns the hydrated index models. -func (s *store) InsertIndexes(ctx context.Context, indexes []shared.Index) (_ []shared.Index, err error) { +func (s *store) InsertIndexes(ctx context.Context, indexes []types.Index) (_ []types.Index, err error) { ctx, _, endObservation := s.operations.insertIndex.With(ctx, &err, observation.Args{}) defer func() { endObservation(1, observation.Args{LogFields: []log.Field{ @@ -30,7 +31,7 @@ func (s *store) InsertIndexes(ctx context.Context, indexes []shared.Index) (_ [] values := make([]*sqlf.Query, 0, len(indexes)) for _, index := range indexes { if index.DockerSteps == nil { - index.DockerSteps = []shared.DockerStep{} + index.DockerSteps = []types.DockerStep{} } if index.IndexerArgs == nil { index.IndexerArgs = []string{} @@ -88,7 +89,7 @@ RETURNING id ` // GetIndexes returns a list of indexes and the total count of records matching the given conditions. -func (s *store) GetIndexes(ctx context.Context, opts shared.GetIndexesOptions) (_ []shared.Index, _ int, err error) { +func (s *store) GetIndexes(ctx context.Context, opts types.GetIndexesOptions) (_ []types.Index, _ int, err error) { ctx, trace, endObservation := s.operations.getIndexes.With(ctx, &err, observation.Args{LogFields: []log.Field{ log.Int("repositoryID", opts.RepositoryID), log.String("state", opts.State), @@ -204,7 +205,7 @@ func makeStateCondition(state string) *sqlf.Query { } // GetIndexByID returns an index by its identifier and boolean flag indicating its existence. -func (s *store) GetIndexByID(ctx context.Context, id int) (_ shared.Index, _ bool, err error) { +func (s *store) GetIndexByID(ctx context.Context, id int) (_ types.Index, _ bool, err error) { ctx, _, endObservation := s.operations.getIndexByID.With(ctx, &err, observation.Args{LogFields: []log.Field{ log.Int("id", id), }}) @@ -212,7 +213,7 @@ func (s *store) GetIndexByID(ctx context.Context, id int) (_ shared.Index, _ boo authzConds, err := database.AuthzQueryConds(ctx, database.NewDBWith(s.logger, s.db)) if err != nil { - return shared.Index{}, false, err + return types.Index{}, false, err } return scanFirstIndex(s.db.Query(ctx, sqlf.Sprintf(getIndexByIDQuery, id, authzConds))) @@ -265,7 +266,7 @@ WHERE repo.deleted_at IS NULL AND u.id = %s AND %s // GetIndexesByIDs returns an index for each of the given identifiers. Not all given ids will necessarily // have a corresponding element in the returned list. -func (s *store) GetIndexesByIDs(ctx context.Context, ids ...int) (_ []shared.Index, err error) { +func (s *store) GetIndexesByIDs(ctx context.Context, ids ...int) (_ []types.Index, err error) { ctx, _, endObservation := s.operations.getIndexesByIDs.With(ctx, &err, observation.Args{LogFields: []log.Field{ log.String("ids", intsToString(ids)), }}) @@ -474,6 +475,12 @@ VALUES (%s, %s) ON CONFLICT DO NOTHING ` +type RepoRev struct { + ID int + RepositoryID int + Rev string +} + // GetQueuedRepoRev selects a batch of repository and revisions to be processed by the auto-indexing // scheduler. If in a transaction, the seleted records will remain locked until the enclosing transaction // has been committed or rolled back. diff --git a/internal/codeintel/autoindexing/internal/store/store_indexes_test.go b/internal/codeintel/autoindexing/internal/store/store_indexes_test.go index 7484f9d30cf..33db433431c 100644 --- a/internal/codeintel/autoindexing/internal/store/store_indexes_test.go +++ b/internal/codeintel/autoindexing/internal/store/store_indexes_test.go @@ -16,6 +16,7 @@ import ( "github.com/sourcegraph/sourcegraph/cmd/frontend/globals" "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" @@ -31,12 +32,12 @@ func TestInsertIndexes(t *testing.T) { insertRepo(t, db, 50, "") - indexes, err := store.InsertIndexes(ctx, []shared.Index{ + indexes, err := store.InsertIndexes(ctx, []types.Index{ { State: "queued", Commit: makeCommit(1), RepositoryID: 50, - DockerSteps: []shared.DockerStep{ + DockerSteps: []types.DockerStep{ { Image: "cimg/node:12.16", Commands: []string{"yarn install --frozen-lockfile --no-progress"}, @@ -47,7 +48,7 @@ func TestInsertIndexes(t *testing.T) { Indexer: "sourcegraph/scip-typescript:latest", IndexerArgs: []string{"index", "--yarn-workspaces"}, Outfile: "dump.lsif", - ExecutionLogs: []shared.ExecutionLogEntry{ + ExecutionLogs: []types.ExecutionLogEntry{ {Command: []string{"op", "1"}, Out: "Indexing\nUploading\nDone with 1.\n"}, {Command: []string{"op", "2"}, Out: "Indexing\nUploading\nDone with 2.\n"}, }, @@ -56,7 +57,7 @@ func TestInsertIndexes(t *testing.T) { State: "queued", Commit: makeCommit(2), RepositoryID: 50, - DockerSteps: []shared.DockerStep{ + DockerSteps: []types.DockerStep{ { Image: "cimg/rust:nightly", Commands: []string{"cargo install"}, @@ -67,7 +68,7 @@ func TestInsertIndexes(t *testing.T) { Indexer: "sourcegraph/lsif-rust:15", IndexerArgs: []string{"-v"}, Outfile: "dump.lsif", - ExecutionLogs: []shared.ExecutionLogEntry{ + ExecutionLogs: []types.ExecutionLogEntry{ {Command: []string{"op", "1"}, Out: "Done with 1.\n"}, {Command: []string{"op", "2"}, Out: "Done with 2.\n"}, }, @@ -82,7 +83,7 @@ func TestInsertIndexes(t *testing.T) { rank1 := 1 rank2 := 2 - expected := []shared.Index{ + expected := []types.Index{ { ID: 1, Commit: makeCommit(1), @@ -93,7 +94,7 @@ func TestInsertIndexes(t *testing.T) { FinishedAt: nil, RepositoryID: 50, RepositoryName: "n-50", - DockerSteps: []shared.DockerStep{ + DockerSteps: []types.DockerStep{ { Image: "cimg/node:12.16", Commands: []string{"yarn install --frozen-lockfile --no-progress"}, @@ -104,7 +105,7 @@ func TestInsertIndexes(t *testing.T) { Indexer: "sourcegraph/scip-typescript:latest", IndexerArgs: []string{"index", "--yarn-workspaces"}, Outfile: "dump.lsif", - ExecutionLogs: []shared.ExecutionLogEntry{ + ExecutionLogs: []types.ExecutionLogEntry{ {Command: []string{"op", "1"}, Out: "Indexing\nUploading\nDone with 1.\n"}, {Command: []string{"op", "2"}, Out: "Indexing\nUploading\nDone with 2.\n"}, }, @@ -120,7 +121,7 @@ func TestInsertIndexes(t *testing.T) { FinishedAt: nil, RepositoryID: 50, RepositoryName: "n-50", - DockerSteps: []shared.DockerStep{ + DockerSteps: []types.DockerStep{ { Image: "cimg/rust:nightly", Commands: []string{"cargo install"}, @@ -131,7 +132,7 @@ func TestInsertIndexes(t *testing.T) { Indexer: "sourcegraph/lsif-rust:15", IndexerArgs: []string{"-v"}, Outfile: "dump.lsif", - ExecutionLogs: []shared.ExecutionLogEntry{ + ExecutionLogs: []types.ExecutionLogEntry{ {Command: []string{"op", "1"}, Out: "Done with 1.\n"}, {Command: []string{"op", "2"}, Out: "Done with 2.\n"}, }, @@ -171,16 +172,16 @@ func TestGetIndexes(t *testing.T) { uploadID1, uploadID2, uploadID3, uploadID4 := 10, 11, 12, 13 insertIndexes(t, db, - shared.Index{ID: 1, Commit: makeCommit(3331), QueuedAt: t1, State: "queued", AssociatedUploadID: &uploadID1}, - shared.Index{ID: 2, QueuedAt: t2, State: "errored", FailureMessage: &failureMessage}, - shared.Index{ID: 3, Commit: makeCommit(3333), QueuedAt: t3, State: "queued", AssociatedUploadID: &uploadID1}, - shared.Index{ID: 4, QueuedAt: t4, State: "queued", RepositoryID: 51, RepositoryName: "foo bar x"}, - shared.Index{ID: 5, Commit: makeCommit(3333), QueuedAt: t5, State: "processing", AssociatedUploadID: &uploadID1}, - shared.Index{ID: 6, QueuedAt: t6, State: "processing", RepositoryID: 52, RepositoryName: "foo bar y"}, - shared.Index{ID: 7, QueuedAt: t7}, - shared.Index{ID: 8, QueuedAt: t8}, - shared.Index{ID: 9, QueuedAt: t9, State: "queued"}, - shared.Index{ID: 10, QueuedAt: t10}, + types.Index{ID: 1, Commit: makeCommit(3331), QueuedAt: t1, State: "queued", AssociatedUploadID: &uploadID1}, + types.Index{ID: 2, QueuedAt: t2, State: "errored", FailureMessage: &failureMessage}, + types.Index{ID: 3, Commit: makeCommit(3333), QueuedAt: t3, State: "queued", AssociatedUploadID: &uploadID1}, + types.Index{ID: 4, QueuedAt: t4, State: "queued", RepositoryID: 51, RepositoryName: "foo bar x"}, + types.Index{ID: 5, Commit: makeCommit(3333), QueuedAt: t5, State: "processing", AssociatedUploadID: &uploadID1}, + types.Index{ID: 6, QueuedAt: t6, State: "processing", RepositoryID: 52, RepositoryName: "foo bar y"}, + types.Index{ID: 7, QueuedAt: t7}, + types.Index{ID: 8, QueuedAt: t8}, + types.Index{ID: 9, QueuedAt: t9, State: "queued"}, + types.Index{ID: 10, QueuedAt: t10}, ) insertUploads(t, db, Upload{ID: uploadID1, AssociatedIndexID: &indexID1}, @@ -221,7 +222,7 @@ func TestGetIndexes(t *testing.T) { ) t.Run(name, func(t *testing.T) { - indexes, totalCount, err := store.GetIndexes(ctx, shared.GetIndexesOptions{ + indexes, totalCount, err := store.GetIndexes(ctx, types.GetIndexesOptions{ RepositoryID: testCase.repositoryID, State: testCase.state, Term: testCase.term, @@ -256,7 +257,7 @@ func TestGetIndexes(t *testing.T) { defer globals.SetPermissionsUserMapping(before) indexes, totalCount, err := store.GetIndexes(ctx, - shared.GetIndexesOptions{ + types.GetIndexesOptions{ Limit: 1, }, ) @@ -285,7 +286,7 @@ func TestGetIndexByID(t *testing.T) { uploadID := 5 queuedAt := time.Unix(1587396557, 0).UTC() startedAt := queuedAt.Add(time.Minute) - expected := shared.Index{ + expected := types.Index{ ID: 1, Commit: makeCommit(1), QueuedAt: queuedAt, @@ -295,7 +296,7 @@ func TestGetIndexByID(t *testing.T) { FinishedAt: nil, RepositoryID: 123, RepositoryName: "n-123", - DockerSteps: []shared.DockerStep{ + DockerSteps: []types.DockerStep{ { Image: "cimg/node:12.16", Commands: []string{"yarn install --frozen-lockfile --no-progress"}, @@ -306,7 +307,7 @@ func TestGetIndexByID(t *testing.T) { Indexer: "sourcegraph/scip-typescript:latest", IndexerArgs: []string{"index", "--yarn-workspaces"}, Outfile: "dump.lsif", - ExecutionLogs: []shared.ExecutionLogEntry{ + ExecutionLogs: []types.ExecutionLogEntry{ {Command: []string{"op", "1"}, Out: "Indexing\nUploading\nDone with 1.\n"}, {Command: []string{"op", "2"}, Out: "Indexing\nUploading\nDone with 2.\n"}, }, @@ -353,16 +354,16 @@ func TestGetIndexesByIDs(t *testing.T) { uploadID1, uploadID2, uploadID3, uploadID4 := 10, 11, 12, 13 insertIndexes(t, db, - shared.Index{ID: 1, AssociatedUploadID: &uploadID1}, - shared.Index{ID: 2}, - shared.Index{ID: 3, AssociatedUploadID: &uploadID1}, - shared.Index{ID: 4}, - shared.Index{ID: 5, AssociatedUploadID: &uploadID1}, - shared.Index{ID: 6}, - shared.Index{ID: 7}, - shared.Index{ID: 8}, - shared.Index{ID: 9}, - shared.Index{ID: 10}, + types.Index{ID: 1, AssociatedUploadID: &uploadID1}, + types.Index{ID: 2}, + types.Index{ID: 3, AssociatedUploadID: &uploadID1}, + types.Index{ID: 4}, + types.Index{ID: 5, AssociatedUploadID: &uploadID1}, + types.Index{ID: 6}, + types.Index{ID: 7}, + types.Index{ID: 8}, + types.Index{ID: 9}, + types.Index{ID: 10}, ) insertUploads(t, db, Upload{ID: uploadID1, AssociatedIndexID: &indexID1}, @@ -420,13 +421,13 @@ func TestGetQueuedIndexRank(t *testing.T) { t7 := t1.Add(+time.Minute * 5) insertIndexes(t, db, - shared.Index{ID: 1, QueuedAt: t1, State: "queued"}, - shared.Index{ID: 2, QueuedAt: t2, State: "queued"}, - shared.Index{ID: 3, QueuedAt: t3, State: "queued"}, - shared.Index{ID: 4, QueuedAt: t4, State: "queued"}, - shared.Index{ID: 5, QueuedAt: t5, State: "queued"}, - shared.Index{ID: 6, QueuedAt: t6, State: "processing"}, - shared.Index{ID: 7, QueuedAt: t1, State: "queued", ProcessAfter: &t7}, + types.Index{ID: 1, QueuedAt: t1, State: "queued"}, + types.Index{ID: 2, QueuedAt: t2, State: "queued"}, + types.Index{ID: 3, QueuedAt: t3, State: "queued"}, + types.Index{ID: 4, QueuedAt: t4, State: "queued"}, + types.Index{ID: 5, QueuedAt: t5, State: "queued"}, + types.Index{ID: 6, QueuedAt: t6, State: "processing"}, + types.Index{ID: 7, QueuedAt: t1, State: "queued", ProcessAfter: &t7}, ) if index, _, _ := store.GetIndexByID(context.Background(), 1); index.Rank == nil || *index.Rank != 1 { @@ -476,27 +477,27 @@ func TestRecentIndexesSummary(t *testing.T) { r1 := 1 r2 := 2 - addDefaults := func(index shared.Index) shared.Index { + addDefaults := func(index types.Index) types.Index { index.Commit = makeCommit(index.ID) index.RepositoryID = 50 index.RepositoryName = "n-50" - index.DockerSteps = []shared.DockerStep{} + index.DockerSteps = []types.DockerStep{} index.IndexerArgs = []string{} index.LocalSteps = []string{} return index } - indexes := []shared.Index{ - addDefaults(shared.Index{ID: 150, QueuedAt: t0, Root: "r1", Indexer: "i1", State: "queued", Rank: &r2}), // visible (group 1) - addDefaults(shared.Index{ID: 151, QueuedAt: t1, Root: "r1", Indexer: "i1", State: "queued", Rank: &r1}), // visible (group 1) - addDefaults(shared.Index{ID: 152, FinishedAt: &t2, Root: "r1", Indexer: "i1", State: "errored"}), // visible (group 1) - addDefaults(shared.Index{ID: 153, FinishedAt: &t3, Root: "r1", Indexer: "i2", State: "completed"}), // visible (group 2) - addDefaults(shared.Index{ID: 154, FinishedAt: &t4, Root: "r2", Indexer: "i1", State: "completed"}), // visible (group 3) - addDefaults(shared.Index{ID: 155, FinishedAt: &t5, Root: "r2", Indexer: "i1", State: "errored"}), // shadowed - addDefaults(shared.Index{ID: 156, FinishedAt: &t6, Root: "r2", Indexer: "i2", State: "completed"}), // visible (group 4) - addDefaults(shared.Index{ID: 157, FinishedAt: &t7, Root: "r2", Indexer: "i2", State: "errored"}), // shadowed - addDefaults(shared.Index{ID: 158, FinishedAt: &t8, Root: "r2", Indexer: "i2", State: "errored"}), // shadowed - addDefaults(shared.Index{ID: 159, FinishedAt: &t9, Root: "r2", Indexer: "i2", State: "errored"}), // shadowed + indexes := []types.Index{ + addDefaults(types.Index{ID: 150, QueuedAt: t0, Root: "r1", Indexer: "i1", State: "queued", Rank: &r2}), // visible (group 1) + addDefaults(types.Index{ID: 151, QueuedAt: t1, Root: "r1", Indexer: "i1", State: "queued", Rank: &r1}), // visible (group 1) + addDefaults(types.Index{ID: 152, FinishedAt: &t2, Root: "r1", Indexer: "i1", State: "errored"}), // visible (group 1) + addDefaults(types.Index{ID: 153, FinishedAt: &t3, Root: "r1", Indexer: "i2", State: "completed"}), // visible (group 2) + addDefaults(types.Index{ID: 154, FinishedAt: &t4, Root: "r2", Indexer: "i1", State: "completed"}), // visible (group 3) + addDefaults(types.Index{ID: 155, FinishedAt: &t5, Root: "r2", Indexer: "i1", State: "errored"}), // shadowed + addDefaults(types.Index{ID: 156, FinishedAt: &t6, Root: "r2", Indexer: "i2", State: "completed"}), // visible (group 4) + addDefaults(types.Index{ID: 157, FinishedAt: &t7, Root: "r2", Indexer: "i2", State: "errored"}), // shadowed + addDefaults(types.Index{ID: 158, FinishedAt: &t8, Root: "r2", Indexer: "i2", State: "errored"}), // shadowed + addDefaults(types.Index{ID: 159, FinishedAt: &t9, Root: "r2", Indexer: "i2", State: "errored"}), // shadowed } insertIndexes(t, db, indexes...) @@ -506,10 +507,10 @@ func TestRecentIndexesSummary(t *testing.T) { } expected := []shared.IndexesWithRepositoryNamespace{ - {Root: "r1", Indexer: "i1", Indexes: []shared.Index{indexes[0], indexes[1], indexes[2]}}, - {Root: "r1", Indexer: "i2", Indexes: []shared.Index{indexes[3]}}, - {Root: "r2", Indexer: "i1", Indexes: []shared.Index{indexes[4]}}, - {Root: "r2", Indexer: "i2", Indexes: []shared.Index{indexes[6]}}, + {Root: "r1", Indexer: "i1", Indexes: []types.Index{indexes[0], indexes[1], indexes[2]}}, + {Root: "r1", Indexer: "i2", Indexes: []types.Index{indexes[3]}}, + {Root: "r2", Indexer: "i1", Indexes: []types.Index{indexes[4]}}, + {Root: "r2", Indexer: "i2", Indexes: []types.Index{indexes[6]}}, } if diff := cmp.Diff(expected, summary); diff != "" { t.Errorf("unexpected index summary (-want +got):\n%s", diff) @@ -554,7 +555,7 @@ func TestDeleteIndexByID(t *testing.T) { db := database.NewDB(logger, dbtest.NewDB(logger, t)) store := New(db, &observation.TestContext) - insertIndexes(t, db, shared.Index{ID: 1}) + insertIndexes(t, db, types.Index{ID: 1}) if found, err := store.DeleteIndexByID(context.Background(), 1); err != nil { t.Fatalf("unexpected error deleting index: %s", err) @@ -587,10 +588,10 @@ func TestDeleteIndexesWithoutRepository(t *testing.T) { db := database.NewDB(logger, dbtest.NewDB(logger, t)) store := New(db, &observation.TestContext) - var indexes []shared.Index + var indexes []types.Index for i := 0; i < 25; i++ { for j := 0; j < 10+i; j++ { - indexes = append(indexes, shared.Index{ID: len(indexes) + 1, RepositoryID: 50 + i}) + indexes = append(indexes, types.Index{ID: len(indexes) + 1, RepositoryID: 50 + i}) } } insertIndexes(t, db, indexes...) @@ -632,7 +633,7 @@ func TestIsQueued(t *testing.T) { db := database.NewDB(logger, dbtest.NewDB(logger, t)) store := New(db, &observation.TestContext) - insertIndexes(t, db, shared.Index{ID: 1, RepositoryID: 1, Commit: makeCommit(1)}) + insertIndexes(t, db, types.Index{ID: 1, RepositoryID: 1, Commit: makeCommit(1)}) insertUploads(t, db, Upload{ID: 2, RepositoryID: 2, Commit: makeCommit(2)}) insertUploads(t, db, Upload{ID: 3, RepositoryID: 3, Commit: makeCommit(3), State: "deleted"}) diff --git a/internal/codeintel/autoindexing/internal/store/store_language_support.go b/internal/codeintel/autoindexing/internal/store/store_language_support.go new file mode 100644 index 00000000000..65a912330f1 --- /dev/null +++ b/internal/codeintel/autoindexing/internal/store/store_language_support.go @@ -0,0 +1,39 @@ +package store + +import ( + "context" + + "github.com/keegancsmith/sqlf" + + "github.com/sourcegraph/sourcegraph/internal/database/basestore" + "github.com/sourcegraph/sourcegraph/internal/observation" +) + +func (s *store) GetLanguagesRequestedBy(ctx context.Context, userID int) (_ []string, err error) { + ctx, _, endObservation := s.operations.getLanguagesRequestedBy.With(ctx, &err, observation.Args{}) + defer endObservation(1, observation.Args{}) + + return basestore.ScanStrings(s.db.Query(ctx, sqlf.Sprintf(languagesRequestedByQuery, userID))) +} + +const languagesRequestedByQuery = ` +-- source: internal/codeintel/autoindexing/internal/store/store_language_support.go:GetLanguagesRequestedBy +SELECT language_id +FROM codeintel_langugage_support_requests +WHERE user_id = %s +ORDER BY language_id +` + +func (s *store) SetRequestLanguageSupport(ctx context.Context, userID int, language string) (err error) { + ctx, _, endObservation := s.operations.setRequestLanguageSupport.With(ctx, &err, observation.Args{}) + defer endObservation(1, observation.Args{}) + + return s.db.Exec(ctx, sqlf.Sprintf(requestLanguageSupportQuery, userID, language)) +} + +const requestLanguageSupportQuery = ` +-- source: internal/codeintel/autoindexing/internal/store/store_language_support.go:SetRequestLanguageSupport +INSERT INTO codeintel_langugage_support_requests (user_id, language_id) +VALUES (%s, %s) +ON CONFLICT DO NOTHING +` diff --git a/internal/codeintel/codenav/internal/store/store_test.go b/internal/codeintel/autoindexing/internal/store/store_language_support_test.go similarity index 100% rename from internal/codeintel/codenav/internal/store/store_test.go rename to internal/codeintel/autoindexing/internal/store/store_language_support_test.go diff --git a/internal/codeintel/autoindexing/internal/store/store_sourced_commits_test.go b/internal/codeintel/autoindexing/internal/store/store_sourced_commits_test.go index dec632feaf2..255b90f5c44 100644 --- a/internal/codeintel/autoindexing/internal/store/store_sourced_commits_test.go +++ b/internal/codeintel/autoindexing/internal/store/store_sourced_commits_test.go @@ -14,6 +14,7 @@ import ( "github.com/sourcegraph/log/logtest" "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" @@ -29,11 +30,11 @@ func TestGetStaleSourcedCommits(t *testing.T) { now := time.Unix(1587396557, 0).UTC() insertIndexes(t, db, - shared.Index{ID: 1, RepositoryID: 50, Commit: makeCommit(1)}, - shared.Index{ID: 2, RepositoryID: 50, Commit: makeCommit(2)}, - shared.Index{ID: 3, RepositoryID: 50, Commit: makeCommit(3)}, - shared.Index{ID: 4, RepositoryID: 51, Commit: makeCommit(6)}, - shared.Index{ID: 5, RepositoryID: 52, Commit: makeCommit(7)}, + types.Index{ID: 1, RepositoryID: 50, Commit: makeCommit(1)}, + types.Index{ID: 2, RepositoryID: 50, Commit: makeCommit(2)}, + types.Index{ID: 3, RepositoryID: 50, Commit: makeCommit(3)}, + types.Index{ID: 4, RepositoryID: 51, Commit: makeCommit(6)}, + types.Index{ID: 5, RepositoryID: 52, Commit: makeCommit(7)}, ) sourcedCommits, err := store.GetStaleSourcedCommits(context.Background(), time.Minute, 5, now) @@ -82,11 +83,11 @@ func TestUpdateSourcedCommits(t *testing.T) { now := time.Unix(1587396557, 0).UTC() insertIndexes(t, db, - shared.Index{ID: 1, RepositoryID: 50, Commit: makeCommit(3)}, - shared.Index{ID: 2, RepositoryID: 50, Commit: makeCommit(2)}, - shared.Index{ID: 3, RepositoryID: 52, Commit: makeCommit(7)}, - shared.Index{ID: 4, RepositoryID: 51, Commit: makeCommit(6)}, - shared.Index{ID: 5, RepositoryID: 50, Commit: makeCommit(1)}, + types.Index{ID: 1, RepositoryID: 50, Commit: makeCommit(3)}, + types.Index{ID: 2, RepositoryID: 50, Commit: makeCommit(2)}, + types.Index{ID: 3, RepositoryID: 52, Commit: makeCommit(7)}, + types.Index{ID: 4, RepositoryID: 51, Commit: makeCommit(6)}, + types.Index{ID: 5, RepositoryID: 50, Commit: makeCommit(1)}, ) indexesUpdated, err := store.UpdateSourcedCommits(context.Background(), 50, makeCommit(1), now) @@ -120,11 +121,11 @@ func TestDeleteSourcedCommits(t *testing.T) { store := New(db, &observation.TestContext) insertIndexes(t, db, - shared.Index{ID: 1, RepositoryID: 50, Commit: makeCommit(3)}, - shared.Index{ID: 2, RepositoryID: 50, Commit: makeCommit(2)}, - shared.Index{ID: 3, RepositoryID: 52, Commit: makeCommit(7)}, - shared.Index{ID: 4, RepositoryID: 51, Commit: makeCommit(6)}, - shared.Index{ID: 5, RepositoryID: 50, Commit: makeCommit(1)}, + types.Index{ID: 1, RepositoryID: 50, Commit: makeCommit(3)}, + types.Index{ID: 2, RepositoryID: 50, Commit: makeCommit(2)}, + types.Index{ID: 3, RepositoryID: 52, Commit: makeCommit(7)}, + types.Index{ID: 4, RepositoryID: 51, Commit: makeCommit(6)}, + types.Index{ID: 5, RepositoryID: 50, Commit: makeCommit(1)}, ) indexesDeleted, err := store.DeleteSourcedCommits(context.Background(), 52, makeCommit(7), time.Hour) @@ -152,7 +153,7 @@ func TestDeleteSourcedCommits(t *testing.T) { } // insertIndexes populates the lsif_indexes table with the given index models. -func insertIndexes(t testing.TB, db database.DB, indexes ...shared.Index) { +func insertIndexes(t testing.TB, db database.DB, indexes ...types.Index) { for _, index := range indexes { if index.Commit == "" { index.Commit = makeCommit(index.ID) @@ -164,7 +165,7 @@ func insertIndexes(t testing.TB, db database.DB, indexes ...shared.Index) { index.RepositoryID = 50 } if index.DockerSteps == nil { - index.DockerSteps = []shared.DockerStep{} + index.DockerSteps = []types.DockerStep{} } if index.IndexerArgs == nil { index.IndexerArgs = []string{} diff --git a/internal/codeintel/autoindexing/mocks_test.go b/internal/codeintel/autoindexing/mocks_test.go index 53887cb4232..df706c7fba7 100644 --- a/internal/codeintel/autoindexing/mocks_test.go +++ b/internal/codeintel/autoindexing/mocks_test.go @@ -15,6 +15,9 @@ import ( api "github.com/sourcegraph/sourcegraph/internal/api" store "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/internal/store" shared "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" + types "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + database "github.com/sourcegraph/sourcegraph/internal/database" + gitdomain "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" protocol "github.com/sourcegraph/sourcegraph/internal/repoupdater/protocol" config "github.com/sourcegraph/sourcegraph/lib/codeintel/autoindex/config" ) @@ -50,6 +53,9 @@ type MockStore struct { // GetIndexesByIDsFunc is an instance of a mock function object // controlling the behavior of the method GetIndexesByIDs. GetIndexesByIDsFunc *StoreGetIndexesByIDsFunc + // GetLanguagesRequestedByFunc is an instance of a mock function object + // controlling the behavior of the method GetLanguagesRequestedBy. + GetLanguagesRequestedByFunc *StoreGetLanguagesRequestedByFunc // GetLastIndexScanForRepositoryFunc is an instance of a mock function // object controlling the behavior of the method // GetLastIndexScanForRepository. @@ -63,6 +69,9 @@ type MockStore struct { // GetStaleSourcedCommitsFunc is an instance of a mock function object // controlling the behavior of the method GetStaleSourcedCommits. GetStaleSourcedCommitsFunc *StoreGetStaleSourcedCommitsFunc + // GetUnsafeDBFunc is an instance of a mock function object controlling + // the behavior of the method GetUnsafeDB. + GetUnsafeDBFunc *StoreGetUnsafeDBFunc // InsertIndexesFunc is an instance of a mock function object // controlling the behavior of the method InsertIndexes. InsertIndexesFunc *StoreInsertIndexesFunc @@ -75,6 +84,10 @@ type MockStore struct { // QueueRepoRevFunc is an instance of a mock function object controlling // the behavior of the method QueueRepoRev. QueueRepoRevFunc *StoreQueueRepoRevFunc + // SetRequestLanguageSupportFunc is an instance of a mock function + // object controlling the behavior of the method + // SetRequestLanguageSupport. + SetRequestLanguageSupportFunc *StoreSetRequestLanguageSupportFunc // TransactFunc is an instance of a mock function object controlling the // behavior of the method Transact. TransactFunc *StoreTransactFunc @@ -112,7 +125,7 @@ func NewMockStore() *MockStore { }, }, GetIndexByIDFunc: &StoreGetIndexByIDFunc{ - defaultHook: func(context.Context, int) (r0 shared.Index, r1 bool, r2 error) { + defaultHook: func(context.Context, int) (r0 types.Index, r1 bool, r2 error) { return }, }, @@ -122,12 +135,17 @@ func NewMockStore() *MockStore { }, }, GetIndexesFunc: &StoreGetIndexesFunc{ - defaultHook: func(context.Context, shared.GetIndexesOptions) (r0 []shared.Index, r1 int, r2 error) { + defaultHook: func(context.Context, types.GetIndexesOptions) (r0 []types.Index, r1 int, r2 error) { return }, }, GetIndexesByIDsFunc: &StoreGetIndexesByIDsFunc{ - defaultHook: func(context.Context, ...int) (r0 []shared.Index, r1 error) { + defaultHook: func(context.Context, ...int) (r0 []types.Index, r1 error) { + return + }, + }, + GetLanguagesRequestedByFunc: &StoreGetLanguagesRequestedByFunc{ + defaultHook: func(context.Context, int) (r0 []string, r1 error) { return }, }, @@ -151,8 +169,13 @@ func NewMockStore() *MockStore { return }, }, + GetUnsafeDBFunc: &StoreGetUnsafeDBFunc{ + defaultHook: func() (r0 database.DB) { + return + }, + }, InsertIndexesFunc: &StoreInsertIndexesFunc{ - defaultHook: func(context.Context, []shared.Index) (r0 []shared.Index, r1 error) { + defaultHook: func(context.Context, []types.Index) (r0 []types.Index, r1 error) { return }, }, @@ -171,6 +194,11 @@ func NewMockStore() *MockStore { return }, }, + SetRequestLanguageSupportFunc: &StoreSetRequestLanguageSupportFunc{ + defaultHook: func(context.Context, int, string) (r0 error) { + return + }, + }, TransactFunc: &StoreTransactFunc{ defaultHook: func(context.Context) (r0 store.Store, r1 error) { return @@ -214,7 +242,7 @@ func NewStrictMockStore() *MockStore { }, }, GetIndexByIDFunc: &StoreGetIndexByIDFunc{ - defaultHook: func(context.Context, int) (shared.Index, bool, error) { + defaultHook: func(context.Context, int) (types.Index, bool, error) { panic("unexpected invocation of MockStore.GetIndexByID") }, }, @@ -224,15 +252,20 @@ func NewStrictMockStore() *MockStore { }, }, GetIndexesFunc: &StoreGetIndexesFunc{ - defaultHook: func(context.Context, shared.GetIndexesOptions) ([]shared.Index, int, error) { + defaultHook: func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { panic("unexpected invocation of MockStore.GetIndexes") }, }, GetIndexesByIDsFunc: &StoreGetIndexesByIDsFunc{ - defaultHook: func(context.Context, ...int) ([]shared.Index, error) { + defaultHook: func(context.Context, ...int) ([]types.Index, error) { panic("unexpected invocation of MockStore.GetIndexesByIDs") }, }, + GetLanguagesRequestedByFunc: &StoreGetLanguagesRequestedByFunc{ + defaultHook: func(context.Context, int) ([]string, error) { + panic("unexpected invocation of MockStore.GetLanguagesRequestedBy") + }, + }, GetLastIndexScanForRepositoryFunc: &StoreGetLastIndexScanForRepositoryFunc{ defaultHook: func(context.Context, int) (*time.Time, error) { panic("unexpected invocation of MockStore.GetLastIndexScanForRepository") @@ -253,8 +286,13 @@ func NewStrictMockStore() *MockStore { panic("unexpected invocation of MockStore.GetStaleSourcedCommits") }, }, + GetUnsafeDBFunc: &StoreGetUnsafeDBFunc{ + defaultHook: func() database.DB { + panic("unexpected invocation of MockStore.GetUnsafeDB") + }, + }, InsertIndexesFunc: &StoreInsertIndexesFunc{ - defaultHook: func(context.Context, []shared.Index) ([]shared.Index, error) { + defaultHook: func(context.Context, []types.Index) ([]types.Index, error) { panic("unexpected invocation of MockStore.InsertIndexes") }, }, @@ -273,6 +311,11 @@ func NewStrictMockStore() *MockStore { panic("unexpected invocation of MockStore.QueueRepoRev") }, }, + SetRequestLanguageSupportFunc: &StoreSetRequestLanguageSupportFunc{ + defaultHook: func(context.Context, int, string) error { + panic("unexpected invocation of MockStore.SetRequestLanguageSupport") + }, + }, TransactFunc: &StoreTransactFunc{ defaultHook: func(context.Context) (store.Store, error) { panic("unexpected invocation of MockStore.Transact") @@ -319,6 +362,9 @@ func NewMockStoreFrom(i store.Store) *MockStore { GetIndexesByIDsFunc: &StoreGetIndexesByIDsFunc{ defaultHook: i.GetIndexesByIDs, }, + GetLanguagesRequestedByFunc: &StoreGetLanguagesRequestedByFunc{ + defaultHook: i.GetLanguagesRequestedBy, + }, GetLastIndexScanForRepositoryFunc: &StoreGetLastIndexScanForRepositoryFunc{ defaultHook: i.GetLastIndexScanForRepository, }, @@ -331,6 +377,9 @@ func NewMockStoreFrom(i store.Store) *MockStore { GetStaleSourcedCommitsFunc: &StoreGetStaleSourcedCommitsFunc{ defaultHook: i.GetStaleSourcedCommits, }, + GetUnsafeDBFunc: &StoreGetUnsafeDBFunc{ + defaultHook: i.GetUnsafeDB, + }, InsertIndexesFunc: &StoreInsertIndexesFunc{ defaultHook: i.InsertIndexes, }, @@ -343,6 +392,9 @@ func NewMockStoreFrom(i store.Store) *MockStore { QueueRepoRevFunc: &StoreQueueRepoRevFunc{ defaultHook: i.QueueRepoRev, }, + SetRequestLanguageSupportFunc: &StoreSetRequestLanguageSupportFunc{ + defaultHook: i.SetRequestLanguageSupport, + }, TransactFunc: &StoreTransactFunc{ defaultHook: i.Transact, }, @@ -792,15 +844,15 @@ func (c StoreDoneFuncCall) Results() []interface{} { // StoreGetIndexByIDFunc describes the behavior when the GetIndexByID method // of the parent MockStore instance is invoked. type StoreGetIndexByIDFunc struct { - defaultHook func(context.Context, int) (shared.Index, bool, error) - hooks []func(context.Context, int) (shared.Index, bool, error) + defaultHook func(context.Context, int) (types.Index, bool, error) + hooks []func(context.Context, int) (types.Index, bool, error) history []StoreGetIndexByIDFuncCall mutex sync.Mutex } // GetIndexByID delegates to the next hook function in the queue and stores // the parameter and result values of this invocation. -func (m *MockStore) GetIndexByID(v0 context.Context, v1 int) (shared.Index, bool, error) { +func (m *MockStore) GetIndexByID(v0 context.Context, v1 int) (types.Index, bool, error) { r0, r1, r2 := m.GetIndexByIDFunc.nextHook()(v0, v1) m.GetIndexByIDFunc.appendCall(StoreGetIndexByIDFuncCall{v0, v1, r0, r1, r2}) return r0, r1, r2 @@ -808,7 +860,7 @@ func (m *MockStore) GetIndexByID(v0 context.Context, v1 int) (shared.Index, bool // SetDefaultHook sets function that is called when the GetIndexByID method // of the parent MockStore instance is invoked and the hook queue is empty. -func (f *StoreGetIndexByIDFunc) SetDefaultHook(hook func(context.Context, int) (shared.Index, bool, error)) { +func (f *StoreGetIndexByIDFunc) SetDefaultHook(hook func(context.Context, int) (types.Index, bool, error)) { f.defaultHook = hook } @@ -816,7 +868,7 @@ func (f *StoreGetIndexByIDFunc) SetDefaultHook(hook func(context.Context, int) ( // GetIndexByID method of the parent MockStore instance invokes the hook at // the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. -func (f *StoreGetIndexByIDFunc) PushHook(hook func(context.Context, int) (shared.Index, bool, error)) { +func (f *StoreGetIndexByIDFunc) PushHook(hook func(context.Context, int) (types.Index, bool, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -824,20 +876,20 @@ func (f *StoreGetIndexByIDFunc) PushHook(hook func(context.Context, int) (shared // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreGetIndexByIDFunc) SetDefaultReturn(r0 shared.Index, r1 bool, r2 error) { - f.SetDefaultHook(func(context.Context, int) (shared.Index, bool, error) { +func (f *StoreGetIndexByIDFunc) SetDefaultReturn(r0 types.Index, r1 bool, r2 error) { + f.SetDefaultHook(func(context.Context, int) (types.Index, bool, error) { return r0, r1, r2 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreGetIndexByIDFunc) PushReturn(r0 shared.Index, r1 bool, r2 error) { - f.PushHook(func(context.Context, int) (shared.Index, bool, error) { +func (f *StoreGetIndexByIDFunc) PushReturn(r0 types.Index, r1 bool, r2 error) { + f.PushHook(func(context.Context, int) (types.Index, bool, error) { return r0, r1, r2 }) } -func (f *StoreGetIndexByIDFunc) nextHook() func(context.Context, int) (shared.Index, bool, error) { +func (f *StoreGetIndexByIDFunc) nextHook() func(context.Context, int) (types.Index, bool, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -878,7 +930,7 @@ type StoreGetIndexByIDFuncCall struct { Arg1 int // Result0 is the value of the 1st result returned from this method // invocation. - Result0 shared.Index + Result0 types.Index // Result1 is the value of the 2nd result returned from this method // invocation. Result1 bool @@ -1018,15 +1070,15 @@ func (c StoreGetIndexConfigurationByRepositoryIDFuncCall) Results() []interface{ // StoreGetIndexesFunc describes the behavior when the GetIndexes method of // the parent MockStore instance is invoked. type StoreGetIndexesFunc struct { - defaultHook func(context.Context, shared.GetIndexesOptions) ([]shared.Index, int, error) - hooks []func(context.Context, shared.GetIndexesOptions) ([]shared.Index, int, error) + defaultHook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) + hooks []func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) history []StoreGetIndexesFuncCall mutex sync.Mutex } // GetIndexes delegates to the next hook function in the queue and stores // the parameter and result values of this invocation. -func (m *MockStore) GetIndexes(v0 context.Context, v1 shared.GetIndexesOptions) ([]shared.Index, int, error) { +func (m *MockStore) GetIndexes(v0 context.Context, v1 types.GetIndexesOptions) ([]types.Index, int, error) { r0, r1, r2 := m.GetIndexesFunc.nextHook()(v0, v1) m.GetIndexesFunc.appendCall(StoreGetIndexesFuncCall{v0, v1, r0, r1, r2}) return r0, r1, r2 @@ -1034,7 +1086,7 @@ func (m *MockStore) GetIndexes(v0 context.Context, v1 shared.GetIndexesOptions) // SetDefaultHook sets function that is called when the GetIndexes method of // the parent MockStore instance is invoked and the hook queue is empty. -func (f *StoreGetIndexesFunc) SetDefaultHook(hook func(context.Context, shared.GetIndexesOptions) ([]shared.Index, int, error)) { +func (f *StoreGetIndexesFunc) SetDefaultHook(hook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error)) { f.defaultHook = hook } @@ -1042,7 +1094,7 @@ func (f *StoreGetIndexesFunc) SetDefaultHook(hook func(context.Context, shared.G // GetIndexes method of the parent MockStore instance invokes the hook at // the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. -func (f *StoreGetIndexesFunc) PushHook(hook func(context.Context, shared.GetIndexesOptions) ([]shared.Index, int, error)) { +func (f *StoreGetIndexesFunc) PushHook(hook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -1050,20 +1102,20 @@ func (f *StoreGetIndexesFunc) PushHook(hook func(context.Context, shared.GetInde // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreGetIndexesFunc) SetDefaultReturn(r0 []shared.Index, r1 int, r2 error) { - f.SetDefaultHook(func(context.Context, shared.GetIndexesOptions) ([]shared.Index, int, error) { +func (f *StoreGetIndexesFunc) SetDefaultReturn(r0 []types.Index, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { return r0, r1, r2 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreGetIndexesFunc) PushReturn(r0 []shared.Index, r1 int, r2 error) { - f.PushHook(func(context.Context, shared.GetIndexesOptions) ([]shared.Index, int, error) { +func (f *StoreGetIndexesFunc) PushReturn(r0 []types.Index, r1 int, r2 error) { + f.PushHook(func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { return r0, r1, r2 }) } -func (f *StoreGetIndexesFunc) nextHook() func(context.Context, shared.GetIndexesOptions) ([]shared.Index, int, error) { +func (f *StoreGetIndexesFunc) nextHook() func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -1101,10 +1153,10 @@ type StoreGetIndexesFuncCall struct { Arg0 context.Context // Arg1 is the value of the 2nd argument passed to this method // invocation. - Arg1 shared.GetIndexesOptions + Arg1 types.GetIndexesOptions // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.Index + Result0 []types.Index // Result1 is the value of the 2nd result returned from this method // invocation. Result1 int @@ -1128,15 +1180,15 @@ func (c StoreGetIndexesFuncCall) Results() []interface{} { // StoreGetIndexesByIDsFunc describes the behavior when the GetIndexesByIDs // method of the parent MockStore instance is invoked. type StoreGetIndexesByIDsFunc struct { - defaultHook func(context.Context, ...int) ([]shared.Index, error) - hooks []func(context.Context, ...int) ([]shared.Index, error) + defaultHook func(context.Context, ...int) ([]types.Index, error) + hooks []func(context.Context, ...int) ([]types.Index, error) history []StoreGetIndexesByIDsFuncCall mutex sync.Mutex } // GetIndexesByIDs delegates to the next hook function in the queue and // stores the parameter and result values of this invocation. -func (m *MockStore) GetIndexesByIDs(v0 context.Context, v1 ...int) ([]shared.Index, error) { +func (m *MockStore) GetIndexesByIDs(v0 context.Context, v1 ...int) ([]types.Index, error) { r0, r1 := m.GetIndexesByIDsFunc.nextHook()(v0, v1...) m.GetIndexesByIDsFunc.appendCall(StoreGetIndexesByIDsFuncCall{v0, v1, r0, r1}) return r0, r1 @@ -1145,7 +1197,7 @@ func (m *MockStore) GetIndexesByIDs(v0 context.Context, v1 ...int) ([]shared.Ind // SetDefaultHook sets function that is called when the GetIndexesByIDs // method of the parent MockStore instance is invoked and the hook queue is // empty. -func (f *StoreGetIndexesByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]shared.Index, error)) { +func (f *StoreGetIndexesByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]types.Index, error)) { f.defaultHook = hook } @@ -1153,7 +1205,7 @@ func (f *StoreGetIndexesByIDsFunc) SetDefaultHook(hook func(context.Context, ... // GetIndexesByIDs method of the parent MockStore instance invokes the hook // at the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. -func (f *StoreGetIndexesByIDsFunc) PushHook(hook func(context.Context, ...int) ([]shared.Index, error)) { +func (f *StoreGetIndexesByIDsFunc) PushHook(hook func(context.Context, ...int) ([]types.Index, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -1161,20 +1213,20 @@ func (f *StoreGetIndexesByIDsFunc) PushHook(hook func(context.Context, ...int) ( // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreGetIndexesByIDsFunc) SetDefaultReturn(r0 []shared.Index, r1 error) { - f.SetDefaultHook(func(context.Context, ...int) ([]shared.Index, error) { +func (f *StoreGetIndexesByIDsFunc) SetDefaultReturn(r0 []types.Index, r1 error) { + f.SetDefaultHook(func(context.Context, ...int) ([]types.Index, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreGetIndexesByIDsFunc) PushReturn(r0 []shared.Index, r1 error) { - f.PushHook(func(context.Context, ...int) ([]shared.Index, error) { +func (f *StoreGetIndexesByIDsFunc) PushReturn(r0 []types.Index, r1 error) { + f.PushHook(func(context.Context, ...int) ([]types.Index, error) { return r0, r1 }) } -func (f *StoreGetIndexesByIDsFunc) nextHook() func(context.Context, ...int) ([]shared.Index, error) { +func (f *StoreGetIndexesByIDsFunc) nextHook() func(context.Context, ...int) ([]types.Index, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -1215,7 +1267,7 @@ type StoreGetIndexesByIDsFuncCall struct { Arg1 []int // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.Index + Result0 []types.Index // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error @@ -1240,6 +1292,115 @@ func (c StoreGetIndexesByIDsFuncCall) Results() []interface{} { return []interface{}{c.Result0, c.Result1} } +// StoreGetLanguagesRequestedByFunc describes the behavior when the +// GetLanguagesRequestedBy method of the parent MockStore instance is +// invoked. +type StoreGetLanguagesRequestedByFunc struct { + defaultHook func(context.Context, int) ([]string, error) + hooks []func(context.Context, int) ([]string, error) + history []StoreGetLanguagesRequestedByFuncCall + mutex sync.Mutex +} + +// GetLanguagesRequestedBy delegates to the next hook function in the queue +// and stores the parameter and result values of this invocation. +func (m *MockStore) GetLanguagesRequestedBy(v0 context.Context, v1 int) ([]string, error) { + r0, r1 := m.GetLanguagesRequestedByFunc.nextHook()(v0, v1) + m.GetLanguagesRequestedByFunc.appendCall(StoreGetLanguagesRequestedByFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the +// GetLanguagesRequestedBy method of the parent MockStore instance is +// invoked and the hook queue is empty. +func (f *StoreGetLanguagesRequestedByFunc) SetDefaultHook(hook func(context.Context, int) ([]string, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetLanguagesRequestedBy method of the parent MockStore instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *StoreGetLanguagesRequestedByFunc) PushHook(hook func(context.Context, int) ([]string, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *StoreGetLanguagesRequestedByFunc) SetDefaultReturn(r0 []string, r1 error) { + f.SetDefaultHook(func(context.Context, int) ([]string, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *StoreGetLanguagesRequestedByFunc) PushReturn(r0 []string, r1 error) { + f.PushHook(func(context.Context, int) ([]string, error) { + return r0, r1 + }) +} + +func (f *StoreGetLanguagesRequestedByFunc) nextHook() func(context.Context, int) ([]string, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *StoreGetLanguagesRequestedByFunc) appendCall(r0 StoreGetLanguagesRequestedByFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of StoreGetLanguagesRequestedByFuncCall +// objects describing the invocations of this function. +func (f *StoreGetLanguagesRequestedByFunc) History() []StoreGetLanguagesRequestedByFuncCall { + f.mutex.Lock() + history := make([]StoreGetLanguagesRequestedByFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// StoreGetLanguagesRequestedByFuncCall is an object that describes an +// invocation of method GetLanguagesRequestedBy on an instance of MockStore. +type StoreGetLanguagesRequestedByFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []string + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c StoreGetLanguagesRequestedByFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c StoreGetLanguagesRequestedByFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + // StoreGetLastIndexScanForRepositoryFunc describes the behavior when the // GetLastIndexScanForRepository method of the parent MockStore instance is // invoked. @@ -1683,34 +1844,34 @@ func (c StoreGetStaleSourcedCommitsFuncCall) Results() []interface{} { return []interface{}{c.Result0, c.Result1} } -// StoreInsertIndexesFunc describes the behavior when the InsertIndexes -// method of the parent MockStore instance is invoked. -type StoreInsertIndexesFunc struct { - defaultHook func(context.Context, []shared.Index) ([]shared.Index, error) - hooks []func(context.Context, []shared.Index) ([]shared.Index, error) - history []StoreInsertIndexesFuncCall +// StoreGetUnsafeDBFunc describes the behavior when the GetUnsafeDB method +// of the parent MockStore instance is invoked. +type StoreGetUnsafeDBFunc struct { + defaultHook func() database.DB + hooks []func() database.DB + history []StoreGetUnsafeDBFuncCall mutex sync.Mutex } -// InsertIndexes delegates to the next hook function in the queue and stores +// GetUnsafeDB delegates to the next hook function in the queue and stores // the parameter and result values of this invocation. -func (m *MockStore) InsertIndexes(v0 context.Context, v1 []shared.Index) ([]shared.Index, error) { - r0, r1 := m.InsertIndexesFunc.nextHook()(v0, v1) - m.InsertIndexesFunc.appendCall(StoreInsertIndexesFuncCall{v0, v1, r0, r1}) - return r0, r1 +func (m *MockStore) GetUnsafeDB() database.DB { + r0 := m.GetUnsafeDBFunc.nextHook()() + m.GetUnsafeDBFunc.appendCall(StoreGetUnsafeDBFuncCall{r0}) + return r0 } -// SetDefaultHook sets function that is called when the InsertIndexes method +// SetDefaultHook sets function that is called when the GetUnsafeDB method // of the parent MockStore instance is invoked and the hook queue is empty. -func (f *StoreInsertIndexesFunc) SetDefaultHook(hook func(context.Context, []shared.Index) ([]shared.Index, error)) { +func (f *StoreGetUnsafeDBFunc) SetDefaultHook(hook func() database.DB) { f.defaultHook = hook } // PushHook adds a function to the end of hook queue. Each invocation of the -// InsertIndexes method of the parent MockStore instance invokes the hook at +// GetUnsafeDB method of the parent MockStore instance invokes the hook at // the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. -func (f *StoreInsertIndexesFunc) PushHook(hook func(context.Context, []shared.Index) ([]shared.Index, error)) { +func (f *StoreGetUnsafeDBFunc) PushHook(hook func() database.DB) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -1718,20 +1879,118 @@ func (f *StoreInsertIndexesFunc) PushHook(hook func(context.Context, []shared.In // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreInsertIndexesFunc) SetDefaultReturn(r0 []shared.Index, r1 error) { - f.SetDefaultHook(func(context.Context, []shared.Index) ([]shared.Index, error) { +func (f *StoreGetUnsafeDBFunc) SetDefaultReturn(r0 database.DB) { + f.SetDefaultHook(func() database.DB { + return r0 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *StoreGetUnsafeDBFunc) PushReturn(r0 database.DB) { + f.PushHook(func() database.DB { + return r0 + }) +} + +func (f *StoreGetUnsafeDBFunc) nextHook() func() database.DB { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *StoreGetUnsafeDBFunc) appendCall(r0 StoreGetUnsafeDBFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of StoreGetUnsafeDBFuncCall objects describing +// the invocations of this function. +func (f *StoreGetUnsafeDBFunc) History() []StoreGetUnsafeDBFuncCall { + f.mutex.Lock() + history := make([]StoreGetUnsafeDBFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// StoreGetUnsafeDBFuncCall is an object that describes an invocation of +// method GetUnsafeDB on an instance of MockStore. +type StoreGetUnsafeDBFuncCall struct { + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 database.DB +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c StoreGetUnsafeDBFuncCall) Args() []interface{} { + return []interface{}{} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c StoreGetUnsafeDBFuncCall) Results() []interface{} { + return []interface{}{c.Result0} +} + +// StoreInsertIndexesFunc describes the behavior when the InsertIndexes +// method of the parent MockStore instance is invoked. +type StoreInsertIndexesFunc struct { + defaultHook func(context.Context, []types.Index) ([]types.Index, error) + hooks []func(context.Context, []types.Index) ([]types.Index, error) + history []StoreInsertIndexesFuncCall + mutex sync.Mutex +} + +// InsertIndexes delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockStore) InsertIndexes(v0 context.Context, v1 []types.Index) ([]types.Index, error) { + r0, r1 := m.InsertIndexesFunc.nextHook()(v0, v1) + m.InsertIndexesFunc.appendCall(StoreInsertIndexesFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the InsertIndexes method +// of the parent MockStore instance is invoked and the hook queue is empty. +func (f *StoreInsertIndexesFunc) SetDefaultHook(hook func(context.Context, []types.Index) ([]types.Index, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// InsertIndexes method of the parent MockStore instance invokes the hook at +// the front of the queue and discards it. After the queue is empty, the +// default hook function is invoked for any future action. +func (f *StoreInsertIndexesFunc) PushHook(hook func(context.Context, []types.Index) ([]types.Index, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *StoreInsertIndexesFunc) SetDefaultReturn(r0 []types.Index, r1 error) { + f.SetDefaultHook(func(context.Context, []types.Index) ([]types.Index, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreInsertIndexesFunc) PushReturn(r0 []shared.Index, r1 error) { - f.PushHook(func(context.Context, []shared.Index) ([]shared.Index, error) { +func (f *StoreInsertIndexesFunc) PushReturn(r0 []types.Index, r1 error) { + f.PushHook(func(context.Context, []types.Index) ([]types.Index, error) { return r0, r1 }) } -func (f *StoreInsertIndexesFunc) nextHook() func(context.Context, []shared.Index) ([]shared.Index, error) { +func (f *StoreInsertIndexesFunc) nextHook() func(context.Context, []types.Index) ([]types.Index, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -1769,10 +2028,10 @@ type StoreInsertIndexesFuncCall struct { Arg0 context.Context // Arg1 is the value of the 2nd argument passed to this method // invocation. - Arg1 []shared.Index + Arg1 []types.Index // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.Index + Result0 []types.Index // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error @@ -2113,6 +2372,116 @@ func (c StoreQueueRepoRevFuncCall) Results() []interface{} { return []interface{}{c.Result0} } +// StoreSetRequestLanguageSupportFunc describes the behavior when the +// SetRequestLanguageSupport method of the parent MockStore instance is +// invoked. +type StoreSetRequestLanguageSupportFunc struct { + defaultHook func(context.Context, int, string) error + hooks []func(context.Context, int, string) error + history []StoreSetRequestLanguageSupportFuncCall + mutex sync.Mutex +} + +// SetRequestLanguageSupport delegates to the next hook function in the +// queue and stores the parameter and result values of this invocation. +func (m *MockStore) SetRequestLanguageSupport(v0 context.Context, v1 int, v2 string) error { + r0 := m.SetRequestLanguageSupportFunc.nextHook()(v0, v1, v2) + m.SetRequestLanguageSupportFunc.appendCall(StoreSetRequestLanguageSupportFuncCall{v0, v1, v2, r0}) + return r0 +} + +// SetDefaultHook sets function that is called when the +// SetRequestLanguageSupport method of the parent MockStore instance is +// invoked and the hook queue is empty. +func (f *StoreSetRequestLanguageSupportFunc) SetDefaultHook(hook func(context.Context, int, string) error) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// SetRequestLanguageSupport method of the parent MockStore instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *StoreSetRequestLanguageSupportFunc) PushHook(hook func(context.Context, int, string) error) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *StoreSetRequestLanguageSupportFunc) SetDefaultReturn(r0 error) { + f.SetDefaultHook(func(context.Context, int, string) error { + return r0 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *StoreSetRequestLanguageSupportFunc) PushReturn(r0 error) { + f.PushHook(func(context.Context, int, string) error { + return r0 + }) +} + +func (f *StoreSetRequestLanguageSupportFunc) nextHook() func(context.Context, int, string) error { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *StoreSetRequestLanguageSupportFunc) appendCall(r0 StoreSetRequestLanguageSupportFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of StoreSetRequestLanguageSupportFuncCall +// objects describing the invocations of this function. +func (f *StoreSetRequestLanguageSupportFunc) History() []StoreSetRequestLanguageSupportFuncCall { + f.mutex.Lock() + history := make([]StoreSetRequestLanguageSupportFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// StoreSetRequestLanguageSupportFuncCall is an object that describes an +// invocation of method SetRequestLanguageSupport on an instance of +// MockStore. +type StoreSetRequestLanguageSupportFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c StoreSetRequestLanguageSupportFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c StoreSetRequestLanguageSupportFuncCall) Results() []interface{} { + return []interface{}{c.Result0} +} + // StoreTransactFunc describes the behavior when the Transact method of the // parent MockStore instance is invoked. type StoreTransactFunc struct { @@ -2461,6 +2830,9 @@ type MockGitserverClient struct { // ListFilesFunc is an instance of a mock function object controlling // the behavior of the method ListFiles. ListFilesFunc *GitserverClientListFilesFunc + // ListTagsFunc is an instance of a mock function object controlling the + // behavior of the method ListTags. + ListTagsFunc *GitserverClientListTagsFunc // RawContentsFunc is an instance of a mock function object controlling // the behavior of the method RawContents. RawContentsFunc *GitserverClientRawContentsFunc @@ -2494,6 +2866,11 @@ func NewMockGitserverClient() *MockGitserverClient { return }, }, + ListTagsFunc: &GitserverClientListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) (r0 []*gitdomain.Tag, r1 error) { + return + }, + }, RawContentsFunc: &GitserverClientRawContentsFunc{ defaultHook: func(context.Context, int, string, string) (r0 []byte, r1 error) { return @@ -2531,6 +2908,11 @@ func NewStrictMockGitserverClient() *MockGitserverClient { panic("unexpected invocation of MockGitserverClient.ListFiles") }, }, + ListTagsFunc: &GitserverClientListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + panic("unexpected invocation of MockGitserverClient.ListTags") + }, + }, RawContentsFunc: &GitserverClientRawContentsFunc{ defaultHook: func(context.Context, int, string, string) ([]byte, error) { panic("unexpected invocation of MockGitserverClient.RawContents") @@ -2561,6 +2943,9 @@ func NewMockGitserverClientFrom(i shared.GitserverClient) *MockGitserverClient { ListFilesFunc: &GitserverClientListFilesFunc{ defaultHook: i.ListFiles, }, + ListTagsFunc: &GitserverClientListTagsFunc{ + defaultHook: i.ListTags, + }, RawContentsFunc: &GitserverClientRawContentsFunc{ defaultHook: i.RawContents, }, @@ -3021,6 +3406,124 @@ func (c GitserverClientListFilesFuncCall) Results() []interface{} { return []interface{}{c.Result0, c.Result1} } +// GitserverClientListTagsFunc describes the behavior when the ListTags +// method of the parent MockGitserverClient instance is invoked. +type GitserverClientListTagsFunc struct { + defaultHook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + hooks []func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + history []GitserverClientListTagsFuncCall + mutex sync.Mutex +} + +// ListTags delegates to the next hook function in the queue and stores the +// parameter and result values of this invocation. +func (m *MockGitserverClient) ListTags(v0 context.Context, v1 api.RepoName, v2 ...string) ([]*gitdomain.Tag, error) { + r0, r1 := m.ListTagsFunc.nextHook()(v0, v1, v2...) + m.ListTagsFunc.appendCall(GitserverClientListTagsFuncCall{v0, v1, v2, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the ListTags method of +// the parent MockGitserverClient instance is invoked and the hook queue is +// empty. +func (f *GitserverClientListTagsFunc) SetDefaultHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// ListTags method of the parent MockGitserverClient instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *GitserverClientListTagsFunc) PushHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *GitserverClientListTagsFunc) SetDefaultReturn(r0 []*gitdomain.Tag, r1 error) { + f.SetDefaultHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *GitserverClientListTagsFunc) PushReturn(r0 []*gitdomain.Tag, r1 error) { + f.PushHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +func (f *GitserverClientListTagsFunc) nextHook() func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *GitserverClientListTagsFunc) appendCall(r0 GitserverClientListTagsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of GitserverClientListTagsFuncCall objects +// describing the invocations of this function. +func (f *GitserverClientListTagsFunc) History() []GitserverClientListTagsFuncCall { + f.mutex.Lock() + history := make([]GitserverClientListTagsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// GitserverClientListTagsFuncCall is an object that describes an invocation +// of method ListTags on an instance of MockGitserverClient. +type GitserverClientListTagsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 api.RepoName + // Arg2 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg2 []string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []*gitdomain.Tag + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c GitserverClientListTagsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg2 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0, c.Arg1}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c GitserverClientListTagsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + // GitserverClientRawContentsFunc describes the behavior when the // RawContents method of the parent MockGitserverClient instance is invoked. type GitserverClientRawContentsFunc struct { @@ -3712,6 +4215,9 @@ type MockUploadService struct { // GetRepoNameFunc is an instance of a mock function object controlling // the behavior of the method GetRepoName. GetRepoNameFunc *UploadServiceGetRepoNameFunc + // GetUploadsByIDsFunc is an instance of a mock function object + // controlling the behavior of the method GetUploadsByIDs. + GetUploadsByIDsFunc *UploadServiceGetUploadsByIDsFunc } // NewMockUploadService creates a new mock of the UploadService interface. @@ -3728,6 +4234,11 @@ func NewMockUploadService() *MockUploadService { return }, }, + GetUploadsByIDsFunc: &UploadServiceGetUploadsByIDsFunc{ + defaultHook: func(context.Context, ...int) (r0 []types.Upload, r1 error) { + return + }, + }, } } @@ -3745,6 +4256,11 @@ func NewStrictMockUploadService() *MockUploadService { panic("unexpected invocation of MockUploadService.GetRepoName") }, }, + GetUploadsByIDsFunc: &UploadServiceGetUploadsByIDsFunc{ + defaultHook: func(context.Context, ...int) ([]types.Upload, error) { + panic("unexpected invocation of MockUploadService.GetUploadsByIDs") + }, + }, } } @@ -3759,6 +4275,9 @@ func NewMockUploadServiceFrom(i shared.UploadService) *MockUploadService { GetRepoNameFunc: &UploadServiceGetRepoNameFunc{ defaultHook: i.GetRepoName, }, + GetUploadsByIDsFunc: &UploadServiceGetUploadsByIDsFunc{ + defaultHook: i.GetUploadsByIDs, + }, } } @@ -3977,3 +4496,119 @@ func (c UploadServiceGetRepoNameFuncCall) Args() []interface{} { func (c UploadServiceGetRepoNameFuncCall) Results() []interface{} { return []interface{}{c.Result0, c.Result1} } + +// UploadServiceGetUploadsByIDsFunc describes the behavior when the +// GetUploadsByIDs method of the parent MockUploadService instance is +// invoked. +type UploadServiceGetUploadsByIDsFunc struct { + defaultHook func(context.Context, ...int) ([]types.Upload, error) + hooks []func(context.Context, ...int) ([]types.Upload, error) + history []UploadServiceGetUploadsByIDsFuncCall + mutex sync.Mutex +} + +// GetUploadsByIDs delegates to the next hook function in the queue and +// stores the parameter and result values of this invocation. +func (m *MockUploadService) GetUploadsByIDs(v0 context.Context, v1 ...int) ([]types.Upload, error) { + r0, r1 := m.GetUploadsByIDsFunc.nextHook()(v0, v1...) + m.GetUploadsByIDsFunc.appendCall(UploadServiceGetUploadsByIDsFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetUploadsByIDs +// method of the parent MockUploadService instance is invoked and the hook +// queue is empty. +func (f *UploadServiceGetUploadsByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]types.Upload, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUploadsByIDs method of the parent MockUploadService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *UploadServiceGetUploadsByIDsFunc) PushHook(hook func(context.Context, ...int) ([]types.Upload, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadServiceGetUploadsByIDsFunc) SetDefaultReturn(r0 []types.Upload, r1 error) { + f.SetDefaultHook(func(context.Context, ...int) ([]types.Upload, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadServiceGetUploadsByIDsFunc) PushReturn(r0 []types.Upload, r1 error) { + f.PushHook(func(context.Context, ...int) ([]types.Upload, error) { + return r0, r1 + }) +} + +func (f *UploadServiceGetUploadsByIDsFunc) nextHook() func(context.Context, ...int) ([]types.Upload, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadServiceGetUploadsByIDsFunc) appendCall(r0 UploadServiceGetUploadsByIDsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadServiceGetUploadsByIDsFuncCall +// objects describing the invocations of this function. +func (f *UploadServiceGetUploadsByIDsFunc) History() []UploadServiceGetUploadsByIDsFuncCall { + f.mutex.Lock() + history := make([]UploadServiceGetUploadsByIDsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadServiceGetUploadsByIDsFuncCall is an object that describes an +// invocation of method GetUploadsByIDs on an instance of MockUploadService. +type UploadServiceGetUploadsByIDsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg1 []int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Upload + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c UploadServiceGetUploadsByIDsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg1 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadServiceGetUploadsByIDsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} diff --git a/internal/codeintel/autoindexing/observability.go b/internal/codeintel/autoindexing/observability.go index 725208631b5..39051ed50e0 100644 --- a/internal/codeintel/autoindexing/observability.go +++ b/internal/codeintel/autoindexing/observability.go @@ -29,6 +29,16 @@ type operations struct { getIndexConfigurationByRepositoryID *observation.Operation updateIndexConfigurationByRepositoryID *observation.Operation inferIndexConfiguration *observation.Operation + + // Auth + checkCurrentUserIsSiteAdmin *observation.Operation + + // Tags + getListTags *observation.Operation + + // Language support + getLanguagesRequestedBy *observation.Operation + setRequestLanguageSupport *observation.Operation } func newOperations(observationContext *observation.Context) *operations { @@ -69,5 +79,15 @@ func newOperations(observationContext *observation.Context) *operations { getIndexConfigurationByRepositoryID: op("GetIndexConfigurationByRepositoryID"), updateIndexConfigurationByRepositoryID: op("UpdateIndexConfigurationByRepositoryID"), inferIndexConfiguration: op("InferIndexConfiguration"), + + // Auth + checkCurrentUserIsSiteAdmin: op("CheckCurrentUserIsSiteAdmin"), + + // Tags + getListTags: op("GetListTags"), + + // Language support + getLanguagesRequestedBy: op("GetLanguagesRequestedBy"), + setRequestLanguageSupport: op("SetRequestLanguageSupport"), } } diff --git a/internal/codeintel/autoindexing/service.go b/internal/codeintel/autoindexing/service.go index a0c0151d176..aa94e936593 100644 --- a/internal/codeintel/autoindexing/service.go +++ b/internal/codeintel/autoindexing/service.go @@ -2,17 +2,24 @@ package autoindexing import ( "context" + "fmt" "os" "time" + "github.com/grafana/regexp" otlog "github.com/opentracing/opentracing-go/log" + traceLog "github.com/opentracing/opentracing-go/log" "github.com/sourcegraph/log" "github.com/sourcegraph/sourcegraph/internal/api" "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/internal/store" "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/errcode" + "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" "github.com/sourcegraph/sourcegraph/internal/observation" + "github.com/sourcegraph/sourcegraph/internal/symbols" "github.com/sourcegraph/sourcegraph/lib/codeintel/autoindex/config" "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -27,26 +34,41 @@ type service interface { DeleteSourcedCommits(ctx context.Context, repositoryID int, commit string, maximumCommitLag time.Duration, now time.Time) (indexesDeleted int, err error) // Indexes - GetIndexes(ctx context.Context, opts shared.GetIndexesOptions) (_ []shared.Index, _ int, err error) - GetIndexByID(ctx context.Context, id int) (_ shared.Index, _ bool, err error) - GetIndexesByIDs(ctx context.Context, ids ...int) (_ []shared.Index, err error) + GetIndexes(ctx context.Context, opts types.GetIndexesOptions) (_ []types.Index, _ int, err error) + GetIndexByID(ctx context.Context, id int) (_ types.Index, _ bool, err error) + GetIndexesByIDs(ctx context.Context, ids ...int) (_ []types.Index, err error) GetRecentIndexesSummary(ctx context.Context, repositoryID int) (summaries []shared.IndexesWithRepositoryNamespace, err error) GetLastIndexScanForRepository(ctx context.Context, repositoryID int) (_ *time.Time, err error) DeleteIndexByID(ctx context.Context, id int) (_ bool, err error) DeleteIndexesWithoutRepository(ctx context.Context, now time.Time) (map[int]int, error) - QueueIndexes(ctx context.Context, repositoryID int, rev, configuration string, force, bypassLimit bool) (_ []shared.Index, err error) + QueueIndexes(ctx context.Context, repositoryID int, rev, configuration string, force, bypassLimit bool) (_ []types.Index, err error) QueueIndexesForPackage(ctx context.Context, pkg precise.Package) (err error) // Index configurations GetIndexConfigurationByRepositoryID(ctx context.Context, repositoryID int) (_ shared.IndexConfiguration, _ bool, err error) InferIndexConfiguration(ctx context.Context, repositoryID int, commit string, bypassLimit bool) (_ *config.IndexConfiguration, hints []config.IndexJobHint, err error) UpdateIndexConfigurationByRepositoryID(ctx context.Context, repositoryID int, data []byte) (err error) + + // Tags + GetListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) (_ []*gitdomain.Tag, err error) + + // Utilities + GetUnsafeDB() database.DB + ListFiles(ctx context.Context, repositoryID int, commit string, pattern *regexp.Regexp) ([]string, error) + + // Symbols client + GetSupportedByCtags(ctx context.Context, filepath string, repoName api.RepoName) (bool, string, error) + + // Language Support + GetLanguagesRequestedBy(ctx context.Context, userID int) (_ []string, err error) + SetRequestLanguageSupport(ctx context.Context, userID int, language string) (err error) } type Service struct { store store.Store uploadSvc shared.UploadService gitserverClient shared.GitserverClient + symbolsClient *symbols.Client repoUpdater shared.RepoUpdaterClient inferenceService shared.InferenceService operations *operations @@ -57,6 +79,7 @@ func newService( store store.Store, uploadSvc shared.UploadService, gitserver shared.GitserverClient, + symbolsClient *symbols.Client, repoUpdater shared.RepoUpdaterClient, inferenceSvc shared.InferenceService, observationContext *observation.Context, @@ -65,6 +88,7 @@ func newService( store: store, uploadSvc: uploadSvc, gitserverClient: gitserver, + symbolsClient: symbolsClient, repoUpdater: repoUpdater, inferenceService: inferenceSvc, operations: newOperations(observationContext), @@ -72,21 +96,21 @@ func newService( } } -func (s *Service) GetIndexes(ctx context.Context, opts shared.GetIndexesOptions) (_ []shared.Index, _ int, err error) { +func (s *Service) GetIndexes(ctx context.Context, opts types.GetIndexesOptions) (_ []types.Index, _ int, err error) { ctx, _, endObservation := s.operations.getIndexes.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) return s.store.GetIndexes(ctx, opts) } -func (s *Service) GetIndexByID(ctx context.Context, id int) (_ shared.Index, _ bool, err error) { +func (s *Service) GetIndexByID(ctx context.Context, id int) (_ types.Index, _ bool, err error) { ctx, _, endObservation := s.operations.getIndexByID.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) return s.store.GetIndexByID(ctx, id) } -func (s *Service) GetIndexesByIDs(ctx context.Context, ids ...int) (_ []shared.Index, err error) { +func (s *Service) GetIndexesByIDs(ctx context.Context, ids ...int) (_ []types.Index, err error) { ctx, _, endObservation := s.operations.getIndexesByIDs.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) @@ -203,6 +227,58 @@ func (s *Service) UpdateIndexConfigurationByRepositoryID(ctx context.Context, re return s.store.UpdateIndexConfigurationByRepositoryID(ctx, repositoryID, data) } +func (s *Service) GetUnsafeDB() database.DB { + return s.store.GetUnsafeDB() +} + +func (s *Service) ListFiles(ctx context.Context, repositoryID int, commit string, pattern *regexp.Regexp) ([]string, error) { + return s.gitserverClient.ListFiles(ctx, repositoryID, commit, pattern) +} + +func (s *Service) GetSupportedByCtags(ctx context.Context, filepath string, repoName api.RepoName) (bool, string, error) { + mappings, err := s.symbolsClient.ListLanguageMappings(ctx, repoName) + if err != nil { + return false, "", err + } + + for language, globs := range mappings { + for _, glob := range globs { + if glob.Match(filepath) { + return true, language, nil + } + } + } + + return false, "", nil +} + +func (s *Service) SetRequestLanguageSupport(ctx context.Context, userID int, language string) (err error) { + ctx, _, endObservation := s.operations.setRequestLanguageSupport.With(ctx, &err, observation.Args{ + LogFields: []traceLog.Field{traceLog.Int("userID", userID), traceLog.String("language", language)}, + }) + defer endObservation(1, observation.Args{}) + + return s.store.SetRequestLanguageSupport(ctx, userID, language) +} + +func (s *Service) GetLanguagesRequestedBy(ctx context.Context, userID int) (_ []string, err error) { + ctx, _, endObservation := s.operations.getLanguagesRequestedBy.With(ctx, &err, observation.Args{ + LogFields: []traceLog.Field{traceLog.Int("userID", userID)}, + }) + defer endObservation(1, observation.Args{}) + + return s.store.GetLanguagesRequestedBy(ctx, userID) +} + +func (s *Service) GetListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) (_ []*gitdomain.Tag, err error) { + ctx, _, endObservation := s.operations.getListTags.With(ctx, &err, observation.Args{ + LogFields: []traceLog.Field{traceLog.String("repo", string(repo)), traceLog.String("commitObjs", fmt.Sprintf("%v", commitObjs))}, + }) + defer endObservation(1, observation.Args{}) + + return s.gitserverClient.ListTags(ctx, repo, commitObjs...) +} + func (s *Service) QueueRepoRev(ctx context.Context, repositoryID int, rev string) (err error) { ctx, _, endObservation := s.operations.queueRepoRev.With(ctx, &err, observation.Args{ LogFields: []otlog.Field{ @@ -256,7 +332,7 @@ func (s *Service) ProcessRepoRevs(ctx context.Context, batchSize int) (err error // If the force flag is false, then the presence of an upload or index record for this given repository and commit // will cause this method to no-op. Note that this is NOT a guarantee that there will never be any duplicate records // when the flag is false. -func (s *Service) QueueIndexes(ctx context.Context, repositoryID int, rev, configuration string, force, bypassLimit bool) (_ []shared.Index, err error) { +func (s *Service) QueueIndexes(ctx context.Context, repositoryID int, rev, configuration string, force, bypassLimit bool) (_ []types.Index, err error) { ctx, trace, endObservation := s.operations.queueIndex.With(ctx, &err, observation.Args{ LogFields: []otlog.Field{ otlog.Int("repositoryID", repositoryID), @@ -321,7 +397,7 @@ func (s *Service) QueueIndexesForPackage(ctx context.Context, pkg precise.Packag // If the force flag is false, then the presence of an upload or index record for this given repository and commit // will cause this method to no-op. Note that this is NOT a guarantee that there will never be any duplicate records // when the flag is false. -func (s *Service) queueIndexForRepositoryAndCommit(ctx context.Context, repositoryID int, commit, configuration string, force, bypassLimit bool, trace observation.TraceLogger) ([]shared.Index, error) { +func (s *Service) queueIndexForRepositoryAndCommit(ctx context.Context, repositoryID int, commit, configuration string, force, bypassLimit bool, trace observation.TraceLogger) ([]types.Index, error) { if !force { isQueued, err := s.store.IsQueued(ctx, repositoryID, commit) if err != nil { @@ -380,16 +456,16 @@ func (s *Service) inferIndexJobHintsFromRepositoryStructure(ctx context.Context, return indexes, nil } -type configurationFactoryFunc func(ctx context.Context, repositoryID int, commit string, bypassLimit bool) ([]shared.Index, bool, error) +type configurationFactoryFunc func(ctx context.Context, repositoryID int, commit string, bypassLimit bool) ([]types.Index, bool, error) // getIndexRecords determines the set of index records that should be enqueued for the given commit. // For each repository, we look for index configuration in the following order: // -// - supplied explicitly via parameter -// - in the database -// - committed to `sourcegraph.yaml` in the repository -// - inferred from the repository structure -func (s *Service) getIndexRecords(ctx context.Context, repositoryID int, commit, configuration string, bypassLimit bool) ([]shared.Index, error) { +// - supplied explicitly via parameter +// - in the database +// - committed to `sourcegraph.yaml` in the repository +// - inferred from the repository structure +func (s *Service) getIndexRecords(ctx context.Context, repositoryID int, commit, configuration string, bypassLimit bool) ([]types.Index, error) { fns := []configurationFactoryFunc{ makeExplicitConfigurationFactory(configuration), s.getIndexRecordsFromConfigurationInDatabase, @@ -413,7 +489,7 @@ func (s *Service) getIndexRecords(ctx context.Context, repositoryID int, commit, // flag is returned. func makeExplicitConfigurationFactory(configuration string) configurationFactoryFunc { logger := log.Scoped("explicitConfigurationFactory", "") - return func(ctx context.Context, repositoryID int, commit string, _ bool) ([]shared.Index, bool, error) { + return func(ctx context.Context, repositoryID int, commit string, _ bool) ([]types.Index, bool, error) { if configuration == "" { return nil, false, nil } @@ -433,7 +509,7 @@ func makeExplicitConfigurationFactory(configuration string) configurationFactory // getIndexRecordsFromConfigurationInDatabase returns a set of index jobs configured via the UI for // the given repository. If no jobs are configured via the UI then a false valued flag is returned. -func (s *Service) getIndexRecordsFromConfigurationInDatabase(ctx context.Context, repositoryID int, commit string, _ bool) ([]shared.Index, bool, error) { +func (s *Service) getIndexRecordsFromConfigurationInDatabase(ctx context.Context, repositoryID int, commit string, _ bool) ([]types.Index, bool, error) { indexConfigurationRecord, ok, err := s.store.GetIndexConfigurationByRepositoryID(ctx, repositoryID) if err != nil { return nil, false, errors.Wrap(err, "dbstore.GetIndexConfigurationByRepositoryID") @@ -457,7 +533,7 @@ func (s *Service) getIndexRecordsFromConfigurationInDatabase(ctx context.Context // getIndexRecordsFromConfigurationInRepository returns a set of index jobs configured via a committed // configuration file at the given commit. If no jobs are configured within the repository then a false // valued flag is returned. -func (s *Service) getIndexRecordsFromConfigurationInRepository(ctx context.Context, repositoryID int, commit string, _ bool) ([]shared.Index, bool, error) { +func (s *Service) getIndexRecordsFromConfigurationInRepository(ctx context.Context, repositoryID int, commit string, _ bool) ([]types.Index, bool, error) { isConfigured, err := s.gitserverClient.FileExists(ctx, repositoryID, commit, "sourcegraph.yaml") if err != nil { return nil, false, errors.Wrap(err, "gitserver.FileExists") @@ -486,7 +562,7 @@ func (s *Service) getIndexRecordsFromConfigurationInRepository(ctx context.Conte // inferIndexRecordsFromRepositoryStructure looks at the repository contents at the given commit and // determines a set of index jobs that are likely to succeed. If no jobs could be inferred then a // false valued flag is returned. -func (s *Service) inferIndexRecordsFromRepositoryStructure(ctx context.Context, repositoryID int, commit string, bypassLimit bool) ([]shared.Index, bool, error) { +func (s *Service) inferIndexRecordsFromRepositoryStructure(ctx context.Context, repositoryID int, commit string, bypassLimit bool) ([]types.Index, bool, error) { indexJobs, err := s.inferIndexJobsFromRepositoryStructure(ctx, repositoryID, commit, bypassLimit) if err != nil || len(indexJobs) == 0 { return nil, false, err @@ -497,25 +573,25 @@ func (s *Service) inferIndexRecordsFromRepositoryStructure(ctx context.Context, // convertIndexConfiguration converts an index configuration object into a set of index records to be // inserted into the database. -func convertIndexConfiguration(repositoryID int, commit string, indexConfiguration config.IndexConfiguration) (indexes []shared.Index) { +func convertIndexConfiguration(repositoryID int, commit string, indexConfiguration config.IndexConfiguration) (indexes []types.Index) { for _, indexJob := range indexConfiguration.IndexJobs { - var dockerSteps []shared.DockerStep + var dockerSteps []types.DockerStep for _, dockerStep := range indexConfiguration.SharedSteps { - dockerSteps = append(dockerSteps, shared.DockerStep{ + dockerSteps = append(dockerSteps, types.DockerStep{ Root: dockerStep.Root, Image: dockerStep.Image, Commands: dockerStep.Commands, }) } for _, dockerStep := range indexJob.Steps { - dockerSteps = append(dockerSteps, shared.DockerStep{ + dockerSteps = append(dockerSteps, types.DockerStep{ Root: dockerStep.Root, Image: dockerStep.Image, Commands: dockerStep.Commands, }) } - indexes = append(indexes, shared.Index{ + indexes = append(indexes, types.Index{ Commit: commit, RepositoryID: repositoryID, State: "queued", @@ -533,18 +609,18 @@ func convertIndexConfiguration(repositoryID int, commit string, indexConfigurati // convertInferredConfiguration converts a set of index jobs into a set of index records to be inserted // into the database. -func convertInferredConfiguration(repositoryID int, commit string, indexJobs []config.IndexJob) (indexes []shared.Index) { +func convertInferredConfiguration(repositoryID int, commit string, indexJobs []config.IndexJob) (indexes []types.Index) { for _, indexJob := range indexJobs { - var dockerSteps []shared.DockerStep + var dockerSteps []types.DockerStep for _, dockerStep := range indexJob.Steps { - dockerSteps = append(dockerSteps, shared.DockerStep{ + dockerSteps = append(dockerSteps, types.DockerStep{ Root: dockerStep.Root, Image: dockerStep.Image, Commands: dockerStep.Commands, }) } - indexes = append(indexes, shared.Index{ + indexes = append(indexes, types.Index{ RepositoryID: repositoryID, Commit: commit, State: "queued", diff --git a/internal/codeintel/autoindexing/service_test.go b/internal/codeintel/autoindexing/service_test.go index e66d9bc6d2a..716de755498 100644 --- a/internal/codeintel/autoindexing/service_test.go +++ b/internal/codeintel/autoindexing/service_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" + types "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/google/go-cmp/cmp" "github.com/grafana/regexp" @@ -57,7 +58,7 @@ func TestQueueIndexesExplicit(t *testing.T) { }` mockDBStore := NewMockStore() - mockDBStore.InsertIndexesFunc.SetDefaultHook(func(ctx context.Context, indexes []shared.Index) ([]shared.Index, error) { return indexes, nil }) + mockDBStore.InsertIndexesFunc.SetDefaultHook(func(ctx context.Context, indexes []types.Index) ([]types.Index, error) { return indexes, nil }) mockGitserverClient := NewMockGitserverClient() mockGitserverClient.ResolveRevisionFunc.SetDefaultHook(func(ctx context.Context, repositoryID int, rev string) (api.CommitID, error) { return api.CommitID(fmt.Sprintf("c%d", repositoryID)), nil @@ -65,7 +66,7 @@ func TestQueueIndexesExplicit(t *testing.T) { mockUploadSvc := NewMockUploadService() inferenceService := NewMockInferenceService() - scheduler := newService(mockDBStore, mockUploadSvc, mockGitserverClient, nil, inferenceService, &observation.TestContext) + scheduler := newService(mockDBStore, mockUploadSvc, mockGitserverClient, nil, nil, inferenceService, &observation.TestContext) _, _ = scheduler.QueueIndexes(context.Background(), 42, "HEAD", config, false, false) if len(mockDBStore.IsQueuedFunc.History()) != 1 { @@ -82,17 +83,17 @@ func TestQueueIndexesExplicit(t *testing.T) { } } - var indexes []shared.Index + var indexes []types.Index for _, call := range mockDBStore.InsertIndexesFunc.History() { indexes = append(indexes, call.Result0...) } - expectedIndexes := []shared.Index{ + expectedIndexes := []types.Index{ { RepositoryID: 42, Commit: "c42", State: "queued", - DockerSteps: []shared.DockerStep{ + DockerSteps: []types.DockerStep{ { Root: "/", Image: "node:12", @@ -110,7 +111,7 @@ func TestQueueIndexesExplicit(t *testing.T) { RepositoryID: 42, Commit: "c42", State: "queued", - DockerSteps: []shared.DockerStep{ + DockerSteps: []types.DockerStep{ { Root: "/", Image: "node:12", @@ -165,7 +166,7 @@ func TestQueueIndexesInDatabase(t *testing.T) { } mockDBStore := NewMockStore() - mockDBStore.InsertIndexesFunc.SetDefaultHook(func(ctx context.Context, indexes []shared.Index) ([]shared.Index, error) { return indexes, nil }) + mockDBStore.InsertIndexesFunc.SetDefaultHook(func(ctx context.Context, indexes []types.Index) ([]types.Index, error) { return indexes, nil }) mockDBStore.GetIndexConfigurationByRepositoryIDFunc.SetDefaultReturn(indexConfiguration, true, nil) mockGitserverClient := NewMockGitserverClient() @@ -175,7 +176,7 @@ func TestQueueIndexesInDatabase(t *testing.T) { mockUploadSvc := NewMockUploadService() inferenceService := NewMockInferenceService() - scheduler := newService(mockDBStore, mockUploadSvc, mockGitserverClient, nil, inferenceService, &observation.TestContext) + scheduler := newService(mockDBStore, mockUploadSvc, mockGitserverClient, nil, nil, inferenceService, &observation.TestContext) _, _ = scheduler.QueueIndexes(context.Background(), 42, "HEAD", "", false, false) if len(mockDBStore.GetIndexConfigurationByRepositoryIDFunc.History()) != 1 { @@ -206,17 +207,17 @@ func TestQueueIndexesInDatabase(t *testing.T) { } } - var indexes []shared.Index + var indexes []types.Index for _, call := range mockDBStore.InsertIndexesFunc.History() { indexes = append(indexes, call.Result0...) } - expectedIndexes := []shared.Index{ + expectedIndexes := []types.Index{ { RepositoryID: 42, Commit: "c42", State: "queued", - DockerSteps: []shared.DockerStep{ + DockerSteps: []types.DockerStep{ { Root: "/", Image: "node:12", @@ -234,7 +235,7 @@ func TestQueueIndexesInDatabase(t *testing.T) { RepositoryID: 42, Commit: "c42", State: "queued", - DockerSteps: []shared.DockerStep{ + DockerSteps: []types.DockerStep{ { Root: "/", Image: "node:12", @@ -277,7 +278,7 @@ index_jobs: func TestQueueIndexesInRepository(t *testing.T) { mockDBStore := NewMockStore() - mockDBStore.InsertIndexesFunc.SetDefaultHook(func(ctx context.Context, indexes []shared.Index) ([]shared.Index, error) { return indexes, nil }) + mockDBStore.InsertIndexesFunc.SetDefaultHook(func(ctx context.Context, indexes []types.Index) ([]types.Index, error) { return indexes, nil }) mockGitserverClient := NewMockGitserverClient() mockGitserverClient.ResolveRevisionFunc.SetDefaultHook(func(ctx context.Context, repositoryID int, rev string) (api.CommitID, error) { @@ -290,7 +291,7 @@ func TestQueueIndexesInRepository(t *testing.T) { mockUploadSvc := NewMockUploadService() inferenceService := NewMockInferenceService() - scheduler := newService(mockDBStore, mockUploadSvc, mockGitserverClient, nil, inferenceService, &observation.TestContext) + scheduler := newService(mockDBStore, mockUploadSvc, mockGitserverClient, nil, nil, inferenceService, &observation.TestContext) if _, err := scheduler.QueueIndexes(context.Background(), 42, "HEAD", "", false, false); err != nil { t.Fatalf("unexpected error performing update: %s", err) @@ -310,17 +311,17 @@ func TestQueueIndexesInRepository(t *testing.T) { } } - var indexes []shared.Index + var indexes []types.Index for _, call := range mockDBStore.InsertIndexesFunc.History() { indexes = append(indexes, call.Result0...) } - expectedIndexes := []shared.Index{ + expectedIndexes := []types.Index{ { RepositoryID: 42, Commit: "c42", State: "queued", - DockerSteps: []shared.DockerStep{ + DockerSteps: []types.DockerStep{ { Root: "/", Image: "node:12", @@ -338,7 +339,7 @@ func TestQueueIndexesInRepository(t *testing.T) { RepositoryID: 42, Commit: "c42", State: "queued", - DockerSteps: []shared.DockerStep{ + DockerSteps: []types.DockerStep{ { Root: "/", Image: "node:12", @@ -358,7 +359,7 @@ func TestQueueIndexesInRepository(t *testing.T) { func TestQueueIndexesInferred(t *testing.T) { mockDBStore := NewMockStore() - mockDBStore.InsertIndexesFunc.SetDefaultHook(func(ctx context.Context, indexes []shared.Index) ([]shared.Index, error) { return indexes, nil }) + mockDBStore.InsertIndexesFunc.SetDefaultHook(func(ctx context.Context, indexes []types.Index) ([]types.Index, error) { return indexes, nil }) mockGitserverClient := NewMockGitserverClient() mockGitserverClient.ResolveRevisionFunc.SetDefaultHook(func(ctx context.Context, repositoryID int, rev string) (api.CommitID, error) { @@ -388,7 +389,7 @@ func TestQueueIndexesInferred(t *testing.T) { } }) - scheduler := newService(mockDBStore, mockUploadSvc, mockGitserverClient, nil, inferenceService, &observation.TestContext) + scheduler := newService(mockDBStore, mockUploadSvc, mockGitserverClient, nil, nil, inferenceService, &observation.TestContext) for _, id := range []int{41, 42, 43, 44} { if _, err := scheduler.QueueIndexes(context.Background(), id, "HEAD", "", false, false); err != nil { @@ -428,7 +429,7 @@ func TestQueueIndexesInferred(t *testing.T) { func TestQueueIndexesInferredTooLarge(t *testing.T) { mockDBStore := NewMockStore() - mockDBStore.InsertIndexesFunc.SetDefaultHook(func(ctx context.Context, indexes []shared.Index) ([]shared.Index, error) { return indexes, nil }) + mockDBStore.InsertIndexesFunc.SetDefaultHook(func(ctx context.Context, indexes []types.Index) ([]types.Index, error) { return indexes, nil }) var paths []string for i := 0; i < 25; i++ { @@ -450,7 +451,7 @@ func TestQueueIndexesInferredTooLarge(t *testing.T) { inferenceService := NewMockInferenceService() maximumIndexJobsPerInferredConfiguration = 20 - scheduler := newService(mockDBStore, mockUploadSvc, mockGitserverClient, nil, inferenceService, &observation.TestContext) + scheduler := newService(mockDBStore, mockUploadSvc, mockGitserverClient, nil, nil, inferenceService, &observation.TestContext) if _, err := scheduler.QueueIndexes(context.Background(), 42, "HEAD", "", false, false); err != nil { t.Fatalf("unexpected error performing update: %s", err) @@ -463,7 +464,7 @@ func TestQueueIndexesInferredTooLarge(t *testing.T) { func TestQueueIndexesForPackage(t *testing.T) { mockDBStore := NewMockStore() - mockDBStore.InsertIndexesFunc.SetDefaultHook(func(ctx context.Context, indexes []shared.Index) ([]shared.Index, error) { return indexes, nil }) + mockDBStore.InsertIndexesFunc.SetDefaultHook(func(ctx context.Context, indexes []types.Index) ([]types.Index, error) { return indexes, nil }) mockDBStore.IsQueuedFunc.SetDefaultReturn(false, nil) mockGitserverClient := NewMockGitserverClient() @@ -503,7 +504,7 @@ func TestQueueIndexesForPackage(t *testing.T) { }, nil }) - scheduler := newService(mockDBStore, mockUploadSvc, mockGitserverClient, mockRepoUpdater, inferenceService, &observation.TestContext) + scheduler := newService(mockDBStore, mockUploadSvc, mockGitserverClient, nil, mockRepoUpdater, inferenceService, &observation.TestContext) _ = scheduler.QueueIndexesForPackage(context.Background(), precise.Package{ Scheme: "gomod", @@ -528,17 +529,17 @@ func TestQueueIndexesForPackage(t *testing.T) { if len(mockDBStore.InsertIndexesFunc.History()) != 1 { t.Errorf("unexpected number of calls to InsertIndexes. want=%d have=%d", 1, len(mockDBStore.InsertIndexesFunc.History())) } else { - var indexes []shared.Index + var indexes []types.Index for _, call := range mockDBStore.InsertIndexesFunc.History() { indexes = append(indexes, call.Result0...) } - expectedIndexes := []shared.Index{ + expectedIndexes := []types.Index{ { RepositoryID: 42, Commit: "c42", State: "queued", - DockerSteps: []shared.DockerStep{ + DockerSteps: []types.DockerStep{ { Image: "sourcegraph/lsif-go:latest", Commands: []string{"go mod download"}, diff --git a/internal/codeintel/autoindexing/shared/iface.go b/internal/codeintel/autoindexing/shared/iface.go index d760cfa64ae..0248f1da859 100644 --- a/internal/codeintel/autoindexing/shared/iface.go +++ b/internal/codeintel/autoindexing/shared/iface.go @@ -6,6 +6,8 @@ import ( "github.com/grafana/regexp" "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" "github.com/sourcegraph/sourcegraph/internal/repoupdater/protocol" "github.com/sourcegraph/sourcegraph/lib/codeintel/autoindex/config" ) @@ -21,6 +23,7 @@ type GitserverClient interface { FileExists(ctx context.Context, repositoryID int, commit, file string) (bool, error) RawContents(ctx context.Context, repositoryID int, commit, file string) ([]byte, error) ResolveRevision(ctx context.Context, repositoryID int, versionString string) (api.CommitID, error) + ListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) (_ []*gitdomain.Tag, err error) } type InferenceService interface { @@ -29,6 +32,7 @@ type InferenceService interface { } type UploadService interface { - GetRepoName(ctx context.Context, repositoryID int) (_ string, err error) // upload service - GetDirtyRepositories(ctx context.Context) (_ map[int]int, err error) // upload service + GetRepoName(ctx context.Context, repositoryID int) (_ string, err error) // upload service + GetDirtyRepositories(ctx context.Context) (_ map[int]int, err error) // upload service + GetUploadsByIDs(ctx context.Context, ids ...int) (_ []types.Upload, err error) // upload service } diff --git a/internal/codeintel/autoindexing/shared/types.go b/internal/codeintel/autoindexing/shared/types.go index dc1f95078ed..7b163b68446 100644 --- a/internal/codeintel/autoindexing/shared/types.go +++ b/internal/codeintel/autoindexing/shared/types.go @@ -1,12 +1,9 @@ package shared import ( - "database/sql/driver" - "encoding/json" "time" - "github.com/sourcegraph/sourcegraph/internal/workerutil" - "github.com/sourcegraph/sourcegraph/lib/errors" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" ) type IndexJob struct { @@ -19,82 +16,6 @@ type SourcedCommits struct { Commits []string } -// Index is a subset of the lsif_indexes table and stores both processed and unprocessed -// records. -type Index struct { - ID int `json:"id"` - Commit string `json:"commit"` - QueuedAt time.Time `json:"queuedAt"` - State string `json:"state"` - FailureMessage *string `json:"failureMessage"` - StartedAt *time.Time `json:"startedAt"` - FinishedAt *time.Time `json:"finishedAt"` - ProcessAfter *time.Time `json:"processAfter"` - NumResets int `json:"numResets"` - NumFailures int `json:"numFailures"` - RepositoryID int `json:"repositoryId"` - LocalSteps []string `json:"local_steps"` - RepositoryName string `json:"repositoryName"` - DockerSteps []DockerStep `json:"docker_steps"` - Root string `json:"root"` - Indexer string `json:"indexer"` - IndexerArgs []string `json:"indexer_args"` // TODO - convert this to `IndexCommand string` - Outfile string `json:"outfile"` - ExecutionLogs []ExecutionLogEntry `json:"execution_logs"` - Rank *int `json:"placeInQueue"` - AssociatedUploadID *int `json:"associatedUpload"` -} - -type DockerStep struct { - Root string `json:"root"` - Image string `json:"image"` - Commands []string `json:"commands"` -} - -func (s *DockerStep) Scan(value any) error { - b, ok := value.([]byte) - if !ok { - return errors.Errorf("value is not []byte: %T", value) - } - - return json.Unmarshal(b, &s) -} - -func (s DockerStep) Value() (driver.Value, error) { - return json.Marshal(s) -} - -// ExecutionLogEntry represents a command run by the executor. -type ExecutionLogEntry struct { - Key string `json:"key"` - Command []string `json:"command"` - StartTime time.Time `json:"startTime"` - ExitCode *int `json:"exitCode,omitempty"` - Out string `json:"out,omitempty"` - DurationMs *int `json:"durationMs,omitempty"` -} - -func (e *ExecutionLogEntry) Scan(value any) error { - b, ok := value.([]byte) - if !ok { - return errors.Errorf("value is not []byte: %T", value) - } - - return json.Unmarshal(b, &e) -} - -func (e ExecutionLogEntry) Value() (driver.Value, error) { - return json.Marshal(e) -} - -func ExecutionLogEntries(raw []workerutil.ExecutionLogEntry) (entries []ExecutionLogEntry) { - for _, entry := range raw { - entries = append(entries, ExecutionLogEntry(entry)) - } - - return entries -} - // IndexConfiguration stores the index configuration for a repository. type IndexConfiguration struct { ID int `json:"id"` @@ -102,16 +23,51 @@ type IndexConfiguration struct { Data []byte `json:"data"` } -type GetIndexesOptions struct { - RepositoryID int - State string - Term string - Limit int - Offset int -} - type IndexesWithRepositoryNamespace struct { Root string Indexer string - Indexes []Index + Indexes []types.Index +} + +// UploadLocation is a path and range pair from within a particular upload. The target commit +// denotes the target commit for which the location was set (the originally requested commit). +type UploadLocation struct { + Dump Dump + Path string + TargetCommit string + TargetRange Range +} + +// Dump is a subset of the lsif_uploads table (queried via the lsif_dumps_with_repository_name view) +// and stores only processed records. +type Dump struct { + ID int `json:"id"` + Commit string `json:"commit"` + Root string `json:"root"` + VisibleAtTip bool `json:"visibleAtTip"` + UploadedAt time.Time `json:"uploadedAt"` + State string `json:"state"` + FailureMessage *string `json:"failureMessage"` + StartedAt *time.Time `json:"startedAt"` + FinishedAt *time.Time `json:"finishedAt"` + ProcessAfter *time.Time `json:"processAfter"` + NumResets int `json:"numResets"` + NumFailures int `json:"numFailures"` + RepositoryID int `json:"repositoryId"` + RepositoryName string `json:"repositoryName"` + Indexer string `json:"indexer"` + IndexerVersion string `json:"indexerVersion"` + AssociatedIndexID *int `json:"associatedIndex"` +} + +// Range is an inclusive bounds within a file. +type Range struct { + Start Position + End Position +} + +// Position is a unique position within a file. +type Position struct { + Line int + Character int } diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/codeintel_blob_info_resolver.go b/internal/codeintel/autoindexing/transport/graphql/codeintel_support_resolver.go similarity index 54% rename from enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/codeintel_blob_info_resolver.go rename to internal/codeintel/autoindexing/transport/graphql/codeintel_support_resolver.go index b7b3516e8f1..91e38d9f9c5 100644 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/codeintel_blob_info_resolver.go +++ b/internal/codeintel/autoindexing/transport/graphql/codeintel_support_resolver.go @@ -5,29 +5,32 @@ import ( "github.com/opentracing/opentracing-go/log" - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers" "github.com/sourcegraph/sourcegraph/internal/api" "github.com/sourcegraph/sourcegraph/internal/observation" ) -type codeIntelSupportResolver struct { - repo api.RepoName - path string - resolver resolvers.Resolver - errTracer *observation.ErrCollector +type GitBlobCodeIntelSupportResolver interface { + SearchBasedSupport(context.Context) (SearchBasedSupportResolver, error) + PreciseSupport(context.Context) (PreciseSupportResolver, error) } -func NewCodeIntelSupportResolver(resolver resolvers.Resolver, repoName api.RepoName, path string, errTracer *observation.ErrCollector) gql.GitBlobCodeIntelSupportResolver { +type codeIntelSupportResolver struct { + repo api.RepoName + path string + autoindexSvc AutoIndexingService + errTracer *observation.ErrCollector +} + +func NewCodeIntelSupportResolver(autoindexSvc AutoIndexingService, repoName api.RepoName, path string, errTracer *observation.ErrCollector) GitBlobCodeIntelSupportResolver { return &codeIntelSupportResolver{ - repo: repoName, - path: path, - resolver: resolver, - errTracer: errTracer, + repo: repoName, + path: path, + autoindexSvc: autoindexSvc, + errTracer: errTracer, } } -func (r *codeIntelSupportResolver) SearchBasedSupport(ctx context.Context) (_ gql.SearchBasedSupportResolver, err error) { +func (r *codeIntelSupportResolver) SearchBasedSupport(ctx context.Context) (_ SearchBasedSupportResolver, err error) { var ( ctagsSupported bool language string @@ -40,8 +43,7 @@ func (r *codeIntelSupportResolver) SearchBasedSupport(ctx context.Context) (_ gq log.Bool("ctagsSupported", ctagsSupported)) }() - codeNavResolver := r.resolver.CodeNavResolver() - ctagsSupported, language, err = codeNavResolver.GetSupportedByCtags(ctx, r.path, r.repo) + ctagsSupported, language, err = r.autoindexSvc.GetSupportedByCtags(ctx, r.path, r.repo) if err != nil { return nil, err } @@ -53,6 +55,6 @@ func (r *codeIntelSupportResolver) SearchBasedSupport(ctx context.Context) (_ gq return NewSearchBasedCodeIntelResolver(language), nil } -func (r *codeIntelSupportResolver) PreciseSupport(ctx context.Context) (gql.PreciseSupportResolver, error) { +func (r *codeIntelSupportResolver) PreciseSupport(ctx context.Context) (PreciseSupportResolver, error) { return NewPreciseCodeIntelSupportResolver(r.path), nil } diff --git a/internal/codeintel/autoindexing/transport/graphql/codeintel_tree_info_resolver.go b/internal/codeintel/autoindexing/transport/graphql/codeintel_tree_info_resolver.go new file mode 100644 index 00000000000..ad134bbbdfd --- /dev/null +++ b/internal/codeintel/autoindexing/transport/graphql/codeintel_tree_info_resolver.go @@ -0,0 +1,115 @@ +package graphql + +import ( + "context" + "strings" + + codeinteltypes "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/observation" + "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/codeintel/autoindex/config" +) + +type GitTreeCodeIntelSupportResolver interface { + SearchBasedSupport(context.Context) (*[]GitTreeSearchBasedCoverage, error) + PreciseSupport(context.Context) (*[]GitTreePreciseCoverage, error) +} + +type preciseSupportInferenceConfidence string + +const ( + languageSupport preciseSupportInferenceConfidence = "LANGUAGE_SUPPORTED" + projectStructureSupported preciseSupportInferenceConfidence = "PROJECT_STRUCTURE_SUPPORTED" + indexJobInfered preciseSupportInferenceConfidence = "INDEX_JOB_INFERED" +) + +type codeIntelTreeInfoResolver struct { + autoindexSvc AutoIndexingService + commit string + path string + files []string + repo *types.Repo + errTracer *observation.ErrCollector +} + +func NewCodeIntelTreeInfoResolver(autoindexSvc AutoIndexingService, repo *types.Repo, commit, path string, files []string, errTracer *observation.ErrCollector) GitTreeCodeIntelSupportResolver { + return &codeIntelTreeInfoResolver{ + autoindexSvc: autoindexSvc, + repo: repo, + commit: commit, + path: path, + files: files, + errTracer: errTracer, + } +} + +func (r *codeIntelTreeInfoResolver) SearchBasedSupport(ctx context.Context) (*[]GitTreeSearchBasedCoverage, error) { + langMapping := make(map[string][]string) + for _, file := range r.files { + ok, lang, err := r.autoindexSvc.GetSupportedByCtags(ctx, file, r.repo.Name) + if err != nil { + return nil, err + } + if ok { + langMapping[lang] = append(langMapping[lang], file) + } + } + + resolvers := make([]GitTreeSearchBasedCoverage, 0, len(langMapping)) + + for lang, files := range langMapping { + resolvers = append(resolvers, &codeIntelTreeSearchBasedCoverageResolver{ + paths: files, + language: lang, + }) + } + + return &resolvers, nil +} + +func (r *codeIntelTreeInfoResolver) PreciseSupport(ctx context.Context) (*[]GitTreePreciseCoverage, error) { + configurations, _, err := r.autoindexSvc.InferIndexConfiguration(ctx, int(r.repo.ID), r.commit, true) + if err != nil { + return nil, err + } + + var resolvers []GitTreePreciseCoverage + + if configurations != nil { + for _, job := range configurations.IndexJobs { + if job.Root == r.path { + resolvers = append(resolvers, &codeIntelTreePreciseCoverageResolver{ + confidence: indexJobInfered, + // drop the tag if it exists + indexer: codeinteltypes.ImageToIndexer[strings.Split(job.Indexer, ":")[0]], + }) + } + } + } + + _, hints, err := r.autoindexSvc.InferIndexConfiguration(ctx, int(r.repo.ID), r.commit, true) + if err != nil { + return nil, err + } + + for _, hint := range hints { + if hint.Root == r.path { + var confidence preciseSupportInferenceConfidence + switch hint.HintConfidence { + case config.HintConfidenceLanguageSupport: + confidence = languageSupport + case config.HintConfidenceProjectStructureSupported: + confidence = projectStructureSupported + default: + continue + } + resolvers = append(resolvers, &codeIntelTreePreciseCoverageResolver{ + confidence: confidence, + // expected that job hints don't include a tag in the indexer name + indexer: codeinteltypes.ImageToIndexer[hint.Indexer], + }) + } + } + + return &resolvers, nil +} diff --git a/internal/codeintel/autoindexing/transport/graphql/codeintel_tree_precise_coverage_resolver.go b/internal/codeintel/autoindexing/transport/graphql/codeintel_tree_precise_coverage_resolver.go new file mode 100644 index 00000000000..cfe450f138f --- /dev/null +++ b/internal/codeintel/autoindexing/transport/graphql/codeintel_tree_precise_coverage_resolver.go @@ -0,0 +1,23 @@ +package graphql + +import ( + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" +) + +type GitTreePreciseCoverage interface { + Support() PreciseSupportResolver + Confidence() string +} + +type codeIntelTreePreciseCoverageResolver struct { + confidence preciseSupportInferenceConfidence + indexer types.CodeIntelIndexerResolver +} + +func (r *codeIntelTreePreciseCoverageResolver) Support() PreciseSupportResolver { + return NewPreciseCodeIntelSupportResolverFromIndexers([]types.CodeIntelIndexerResolver{r.indexer}) +} + +func (r *codeIntelTreePreciseCoverageResolver) Confidence() string { + return string(r.confidence) +} diff --git a/internal/codeintel/autoindexing/transport/graphql/codeintel_tree_searchbased_coverage_resolver.go b/internal/codeintel/autoindexing/transport/graphql/codeintel_tree_searchbased_coverage_resolver.go new file mode 100644 index 00000000000..6381b46f493 --- /dev/null +++ b/internal/codeintel/autoindexing/transport/graphql/codeintel_tree_searchbased_coverage_resolver.go @@ -0,0 +1,19 @@ +package graphql + +type GitTreeSearchBasedCoverage interface { + CoveredPaths() []string + Support() SearchBasedSupportResolver +} + +type codeIntelTreeSearchBasedCoverageResolver struct { + paths []string + language string +} + +func (r *codeIntelTreeSearchBasedCoverageResolver) CoveredPaths() []string { + return r.paths +} + +func (r *codeIntelTreeSearchBasedCoverageResolver) Support() SearchBasedSupportResolver { + return NewSearchBasedCodeIntelResolver(r.language) +} diff --git a/internal/codeintel/autoindexing/transport/graphql/iface.go b/internal/codeintel/autoindexing/transport/graphql/iface.go new file mode 100644 index 00000000000..fffc976768a --- /dev/null +++ b/internal/codeintel/autoindexing/transport/graphql/iface.go @@ -0,0 +1,53 @@ +package graphql + +import ( + "context" + "time" + + "github.com/grafana/regexp" + + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + uploadshared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/database" + "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" + "github.com/sourcegraph/sourcegraph/lib/codeintel/autoindex/config" +) + +type AutoIndexingService interface { + GetIndexConfigurationByRepositoryID(ctx context.Context, repositoryID int) (_ shared.IndexConfiguration, _ bool, err error) + GetIndexes(ctx context.Context, opts types.GetIndexesOptions) (_ []types.Index, _ int, err error) + GetIndexByID(ctx context.Context, id int) (_ types.Index, _ bool, err error) + GetIndexesByIDs(ctx context.Context, ids ...int) (_ []types.Index, err error) + GetRecentIndexesSummary(ctx context.Context, repositoryID int) (summaries []shared.IndexesWithRepositoryNamespace, err error) + GetLastIndexScanForRepository(ctx context.Context, repositoryID int) (_ *time.Time, err error) + UpdateIndexConfigurationByRepositoryID(ctx context.Context, repositoryID int, data []byte) (err error) + DeleteIndexByID(ctx context.Context, id int) (_ bool, err error) + + InferIndexConfiguration(ctx context.Context, repositoryID int, commit string, bypassLimit bool) (_ *config.IndexConfiguration, hints []config.IndexJobHint, err error) + QueueIndexes(ctx context.Context, repositoryID int, rev, configuration string, force, bypassLimit bool) (_ []types.Index, err error) + + GetListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) (_ []*gitdomain.Tag, err error) + ListFiles(ctx context.Context, repositoryID int, commit string, pattern *regexp.Regexp) ([]string, error) + + GetSupportedByCtags(ctx context.Context, filepath string, repoName api.RepoName) (bool, string, error) + GetLanguagesRequestedBy(ctx context.Context, userID int) (_ []string, err error) + SetRequestLanguageSupport(ctx context.Context, userID int, language string) (err error) + + GetUnsafeDB() database.DB +} + +type UploadsService interface { + GetLastUploadRetentionScanForRepository(ctx context.Context, repositoryID int) (_ *time.Time, err error) + GetRecentUploadsSummary(ctx context.Context, repositoryID int) (upload []uploadshared.UploadsWithRepositoryNamespace, err error) + GetUploads(ctx context.Context, opts types.GetUploadsOptions) (uploads []types.Upload, totalCount int, err error) + GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []types.UploadLog, err error) + GetListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) (_ []*gitdomain.Tag, err error) + GetUploadDocumentsForPath(ctx context.Context, bundleID int, pathPattern string) ([]string, int, error) + GetUploadsByIDs(ctx context.Context, ids ...int) (_ []types.Upload, err error) +} + +type PolicyService interface { + GetRetentionPolicyOverview(ctx context.Context, upload types.Upload, matchesOnly bool, first int, after int64, query string, now time.Time) (matches []types.RetentionPolicyMatchCandidate, totalCount int, err error) +} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/configuration.go b/internal/codeintel/autoindexing/transport/graphql/index_configuration_resolver.go similarity index 50% rename from enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/configuration.go rename to internal/codeintel/autoindexing/transport/graphql/index_configuration_resolver.go index 866b52e9525..3d729470c0b 100644 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/configuration.go +++ b/internal/codeintel/autoindexing/transport/graphql/index_configuration_resolver.go @@ -7,30 +7,32 @@ import ( "github.com/opentracing/opentracing-go/log" - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers" "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/lib/codeintel/autoindex/config" ) -type IndexConfigurationResolver struct { - resolver resolvers.Resolver +type IndexConfigurationResolver interface { + Configuration(ctx context.Context) (*string, error) + InferredConfiguration(ctx context.Context) (*string, error) +} + +type indexConfigurationResolver struct { + autoindexSvc AutoIndexingService repositoryID int errTracer *observation.ErrCollector } -func NewIndexConfigurationResolver(resolver resolvers.Resolver, repositoryID int, errTracer *observation.ErrCollector) gql.IndexConfigurationResolver { - return &IndexConfigurationResolver{ - resolver: resolver, +func NewIndexConfigurationResolver(autoindexSvc AutoIndexingService, repositoryID int, errTracer *observation.ErrCollector) IndexConfigurationResolver { + return &indexConfigurationResolver{ + autoindexSvc: autoindexSvc, repositoryID: repositoryID, errTracer: errTracer, } } -func (r *IndexConfigurationResolver) Configuration(ctx context.Context) (_ *string, err error) { +func (r *indexConfigurationResolver) Configuration(ctx context.Context) (_ *string, err error) { defer r.errTracer.Collect(&err, log.String("indexConfigResolver.field", "configuration")) - autoIndexingResolver := r.resolver.AutoIndexingResolver() - configuration, exists, err := autoIndexingResolver.GetIndexConfiguration(ctx, r.repositoryID) + configuration, exists, err := r.autoindexSvc.GetIndexConfigurationByRepositoryID(ctx, r.repositoryID) if err != nil { return nil, err } @@ -38,17 +40,16 @@ func (r *IndexConfigurationResolver) Configuration(ctx context.Context) (_ *stri return nil, nil } - return strPtr(string(configuration)), nil + return strPtr(string(configuration.Data)), nil } -func (r *IndexConfigurationResolver) InferredConfiguration(ctx context.Context) (_ *string, err error) { +func (r *indexConfigurationResolver) InferredConfiguration(ctx context.Context) (_ *string, err error) { defer r.errTracer.Collect(&err, log.String("indexConfigResolver.field", "inferredConfiguration")) - autoIndexingResolver := r.resolver.AutoIndexingResolver() - configuration, exists, err := autoIndexingResolver.InferedIndexConfiguration(ctx, r.repositoryID, "") + configuration, _, err := r.autoindexSvc.InferIndexConfiguration(ctx, r.repositoryID, "", true) if err != nil { return nil, err } - if !exists { + if configuration == nil { return nil, nil } diff --git a/internal/codeintel/autoindexing/transport/graphql/mocks_temp.go b/internal/codeintel/autoindexing/transport/graphql/mocks_temp.go new file mode 100644 index 00000000000..bd19ea23b7b --- /dev/null +++ b/internal/codeintel/autoindexing/transport/graphql/mocks_temp.go @@ -0,0 +1,3266 @@ +// Code generated by go-mockgen 1.3.4; DO NOT EDIT. +// +// This file was generated by running `sg generate` (or `go-mockgen`) at the root of +// this repository. To add additional mocks to this or another package, add a new entry +// to the mockgen.yaml file in the root of this repository. + +package graphql + +import ( + "context" + "sync" + "time" + + regexp "github.com/grafana/regexp" + api "github.com/sourcegraph/sourcegraph/internal/api" + shared "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" + types "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + shared1 "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + database "github.com/sourcegraph/sourcegraph/internal/database" + gitdomain "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" + config "github.com/sourcegraph/sourcegraph/lib/codeintel/autoindex/config" +) + +// MockAutoIndexingService is a mock implementation of the +// AutoIndexingService interface (from the package +// github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/transport/graphql) +// used for unit testing. +type MockAutoIndexingService struct { + // DeleteIndexByIDFunc is an instance of a mock function object + // controlling the behavior of the method DeleteIndexByID. + DeleteIndexByIDFunc *AutoIndexingServiceDeleteIndexByIDFunc + // GetIndexByIDFunc is an instance of a mock function object controlling + // the behavior of the method GetIndexByID. + GetIndexByIDFunc *AutoIndexingServiceGetIndexByIDFunc + // GetIndexConfigurationByRepositoryIDFunc is an instance of a mock + // function object controlling the behavior of the method + // GetIndexConfigurationByRepositoryID. + GetIndexConfigurationByRepositoryIDFunc *AutoIndexingServiceGetIndexConfigurationByRepositoryIDFunc + // GetIndexesFunc is an instance of a mock function object controlling + // the behavior of the method GetIndexes. + GetIndexesFunc *AutoIndexingServiceGetIndexesFunc + // GetIndexesByIDsFunc is an instance of a mock function object + // controlling the behavior of the method GetIndexesByIDs. + GetIndexesByIDsFunc *AutoIndexingServiceGetIndexesByIDsFunc + // GetLanguagesRequestedByFunc is an instance of a mock function object + // controlling the behavior of the method GetLanguagesRequestedBy. + GetLanguagesRequestedByFunc *AutoIndexingServiceGetLanguagesRequestedByFunc + // GetLastIndexScanForRepositoryFunc is an instance of a mock function + // object controlling the behavior of the method + // GetLastIndexScanForRepository. + GetLastIndexScanForRepositoryFunc *AutoIndexingServiceGetLastIndexScanForRepositoryFunc + // GetListTagsFunc is an instance of a mock function object controlling + // the behavior of the method GetListTags. + GetListTagsFunc *AutoIndexingServiceGetListTagsFunc + // GetRecentIndexesSummaryFunc is an instance of a mock function object + // controlling the behavior of the method GetRecentIndexesSummary. + GetRecentIndexesSummaryFunc *AutoIndexingServiceGetRecentIndexesSummaryFunc + // GetSupportedByCtagsFunc is an instance of a mock function object + // controlling the behavior of the method GetSupportedByCtags. + GetSupportedByCtagsFunc *AutoIndexingServiceGetSupportedByCtagsFunc + // GetUnsafeDBFunc is an instance of a mock function object controlling + // the behavior of the method GetUnsafeDB. + GetUnsafeDBFunc *AutoIndexingServiceGetUnsafeDBFunc + // InferIndexConfigurationFunc is an instance of a mock function object + // controlling the behavior of the method InferIndexConfiguration. + InferIndexConfigurationFunc *AutoIndexingServiceInferIndexConfigurationFunc + // ListFilesFunc is an instance of a mock function object controlling + // the behavior of the method ListFiles. + ListFilesFunc *AutoIndexingServiceListFilesFunc + // QueueIndexesFunc is an instance of a mock function object controlling + // the behavior of the method QueueIndexes. + QueueIndexesFunc *AutoIndexingServiceQueueIndexesFunc + // SetRequestLanguageSupportFunc is an instance of a mock function + // object controlling the behavior of the method + // SetRequestLanguageSupport. + SetRequestLanguageSupportFunc *AutoIndexingServiceSetRequestLanguageSupportFunc + // UpdateIndexConfigurationByRepositoryIDFunc is an instance of a mock + // function object controlling the behavior of the method + // UpdateIndexConfigurationByRepositoryID. + UpdateIndexConfigurationByRepositoryIDFunc *AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFunc +} + +// NewMockAutoIndexingService creates a new mock of the AutoIndexingService +// interface. All methods return zero values for all results, unless +// overwritten. +func NewMockAutoIndexingService() *MockAutoIndexingService { + return &MockAutoIndexingService{ + DeleteIndexByIDFunc: &AutoIndexingServiceDeleteIndexByIDFunc{ + defaultHook: func(context.Context, int) (r0 bool, r1 error) { + return + }, + }, + GetIndexByIDFunc: &AutoIndexingServiceGetIndexByIDFunc{ + defaultHook: func(context.Context, int) (r0 types.Index, r1 bool, r2 error) { + return + }, + }, + GetIndexConfigurationByRepositoryIDFunc: &AutoIndexingServiceGetIndexConfigurationByRepositoryIDFunc{ + defaultHook: func(context.Context, int) (r0 shared.IndexConfiguration, r1 bool, r2 error) { + return + }, + }, + GetIndexesFunc: &AutoIndexingServiceGetIndexesFunc{ + defaultHook: func(context.Context, types.GetIndexesOptions) (r0 []types.Index, r1 int, r2 error) { + return + }, + }, + GetIndexesByIDsFunc: &AutoIndexingServiceGetIndexesByIDsFunc{ + defaultHook: func(context.Context, ...int) (r0 []types.Index, r1 error) { + return + }, + }, + GetLanguagesRequestedByFunc: &AutoIndexingServiceGetLanguagesRequestedByFunc{ + defaultHook: func(context.Context, int) (r0 []string, r1 error) { + return + }, + }, + GetLastIndexScanForRepositoryFunc: &AutoIndexingServiceGetLastIndexScanForRepositoryFunc{ + defaultHook: func(context.Context, int) (r0 *time.Time, r1 error) { + return + }, + }, + GetListTagsFunc: &AutoIndexingServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) (r0 []*gitdomain.Tag, r1 error) { + return + }, + }, + GetRecentIndexesSummaryFunc: &AutoIndexingServiceGetRecentIndexesSummaryFunc{ + defaultHook: func(context.Context, int) (r0 []shared.IndexesWithRepositoryNamespace, r1 error) { + return + }, + }, + GetSupportedByCtagsFunc: &AutoIndexingServiceGetSupportedByCtagsFunc{ + defaultHook: func(context.Context, string, api.RepoName) (r0 bool, r1 string, r2 error) { + return + }, + }, + GetUnsafeDBFunc: &AutoIndexingServiceGetUnsafeDBFunc{ + defaultHook: func() (r0 database.DB) { + return + }, + }, + InferIndexConfigurationFunc: &AutoIndexingServiceInferIndexConfigurationFunc{ + defaultHook: func(context.Context, int, string, bool) (r0 *config.IndexConfiguration, r1 []config.IndexJobHint, r2 error) { + return + }, + }, + ListFilesFunc: &AutoIndexingServiceListFilesFunc{ + defaultHook: func(context.Context, int, string, *regexp.Regexp) (r0 []string, r1 error) { + return + }, + }, + QueueIndexesFunc: &AutoIndexingServiceQueueIndexesFunc{ + defaultHook: func(context.Context, int, string, string, bool, bool) (r0 []types.Index, r1 error) { + return + }, + }, + SetRequestLanguageSupportFunc: &AutoIndexingServiceSetRequestLanguageSupportFunc{ + defaultHook: func(context.Context, int, string) (r0 error) { + return + }, + }, + UpdateIndexConfigurationByRepositoryIDFunc: &AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFunc{ + defaultHook: func(context.Context, int, []byte) (r0 error) { + return + }, + }, + } +} + +// NewStrictMockAutoIndexingService creates a new mock of the +// AutoIndexingService interface. All methods panic on invocation, unless +// overwritten. +func NewStrictMockAutoIndexingService() *MockAutoIndexingService { + return &MockAutoIndexingService{ + DeleteIndexByIDFunc: &AutoIndexingServiceDeleteIndexByIDFunc{ + defaultHook: func(context.Context, int) (bool, error) { + panic("unexpected invocation of MockAutoIndexingService.DeleteIndexByID") + }, + }, + GetIndexByIDFunc: &AutoIndexingServiceGetIndexByIDFunc{ + defaultHook: func(context.Context, int) (types.Index, bool, error) { + panic("unexpected invocation of MockAutoIndexingService.GetIndexByID") + }, + }, + GetIndexConfigurationByRepositoryIDFunc: &AutoIndexingServiceGetIndexConfigurationByRepositoryIDFunc{ + defaultHook: func(context.Context, int) (shared.IndexConfiguration, bool, error) { + panic("unexpected invocation of MockAutoIndexingService.GetIndexConfigurationByRepositoryID") + }, + }, + GetIndexesFunc: &AutoIndexingServiceGetIndexesFunc{ + defaultHook: func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + panic("unexpected invocation of MockAutoIndexingService.GetIndexes") + }, + }, + GetIndexesByIDsFunc: &AutoIndexingServiceGetIndexesByIDsFunc{ + defaultHook: func(context.Context, ...int) ([]types.Index, error) { + panic("unexpected invocation of MockAutoIndexingService.GetIndexesByIDs") + }, + }, + GetLanguagesRequestedByFunc: &AutoIndexingServiceGetLanguagesRequestedByFunc{ + defaultHook: func(context.Context, int) ([]string, error) { + panic("unexpected invocation of MockAutoIndexingService.GetLanguagesRequestedBy") + }, + }, + GetLastIndexScanForRepositoryFunc: &AutoIndexingServiceGetLastIndexScanForRepositoryFunc{ + defaultHook: func(context.Context, int) (*time.Time, error) { + panic("unexpected invocation of MockAutoIndexingService.GetLastIndexScanForRepository") + }, + }, + GetListTagsFunc: &AutoIndexingServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + panic("unexpected invocation of MockAutoIndexingService.GetListTags") + }, + }, + GetRecentIndexesSummaryFunc: &AutoIndexingServiceGetRecentIndexesSummaryFunc{ + defaultHook: func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error) { + panic("unexpected invocation of MockAutoIndexingService.GetRecentIndexesSummary") + }, + }, + GetSupportedByCtagsFunc: &AutoIndexingServiceGetSupportedByCtagsFunc{ + defaultHook: func(context.Context, string, api.RepoName) (bool, string, error) { + panic("unexpected invocation of MockAutoIndexingService.GetSupportedByCtags") + }, + }, + GetUnsafeDBFunc: &AutoIndexingServiceGetUnsafeDBFunc{ + defaultHook: func() database.DB { + panic("unexpected invocation of MockAutoIndexingService.GetUnsafeDB") + }, + }, + InferIndexConfigurationFunc: &AutoIndexingServiceInferIndexConfigurationFunc{ + defaultHook: func(context.Context, int, string, bool) (*config.IndexConfiguration, []config.IndexJobHint, error) { + panic("unexpected invocation of MockAutoIndexingService.InferIndexConfiguration") + }, + }, + ListFilesFunc: &AutoIndexingServiceListFilesFunc{ + defaultHook: func(context.Context, int, string, *regexp.Regexp) ([]string, error) { + panic("unexpected invocation of MockAutoIndexingService.ListFiles") + }, + }, + QueueIndexesFunc: &AutoIndexingServiceQueueIndexesFunc{ + defaultHook: func(context.Context, int, string, string, bool, bool) ([]types.Index, error) { + panic("unexpected invocation of MockAutoIndexingService.QueueIndexes") + }, + }, + SetRequestLanguageSupportFunc: &AutoIndexingServiceSetRequestLanguageSupportFunc{ + defaultHook: func(context.Context, int, string) error { + panic("unexpected invocation of MockAutoIndexingService.SetRequestLanguageSupport") + }, + }, + UpdateIndexConfigurationByRepositoryIDFunc: &AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFunc{ + defaultHook: func(context.Context, int, []byte) error { + panic("unexpected invocation of MockAutoIndexingService.UpdateIndexConfigurationByRepositoryID") + }, + }, + } +} + +// NewMockAutoIndexingServiceFrom creates a new mock of the +// MockAutoIndexingService interface. All methods delegate to the given +// implementation, unless overwritten. +func NewMockAutoIndexingServiceFrom(i AutoIndexingService) *MockAutoIndexingService { + return &MockAutoIndexingService{ + DeleteIndexByIDFunc: &AutoIndexingServiceDeleteIndexByIDFunc{ + defaultHook: i.DeleteIndexByID, + }, + GetIndexByIDFunc: &AutoIndexingServiceGetIndexByIDFunc{ + defaultHook: i.GetIndexByID, + }, + GetIndexConfigurationByRepositoryIDFunc: &AutoIndexingServiceGetIndexConfigurationByRepositoryIDFunc{ + defaultHook: i.GetIndexConfigurationByRepositoryID, + }, + GetIndexesFunc: &AutoIndexingServiceGetIndexesFunc{ + defaultHook: i.GetIndexes, + }, + GetIndexesByIDsFunc: &AutoIndexingServiceGetIndexesByIDsFunc{ + defaultHook: i.GetIndexesByIDs, + }, + GetLanguagesRequestedByFunc: &AutoIndexingServiceGetLanguagesRequestedByFunc{ + defaultHook: i.GetLanguagesRequestedBy, + }, + GetLastIndexScanForRepositoryFunc: &AutoIndexingServiceGetLastIndexScanForRepositoryFunc{ + defaultHook: i.GetLastIndexScanForRepository, + }, + GetListTagsFunc: &AutoIndexingServiceGetListTagsFunc{ + defaultHook: i.GetListTags, + }, + GetRecentIndexesSummaryFunc: &AutoIndexingServiceGetRecentIndexesSummaryFunc{ + defaultHook: i.GetRecentIndexesSummary, + }, + GetSupportedByCtagsFunc: &AutoIndexingServiceGetSupportedByCtagsFunc{ + defaultHook: i.GetSupportedByCtags, + }, + GetUnsafeDBFunc: &AutoIndexingServiceGetUnsafeDBFunc{ + defaultHook: i.GetUnsafeDB, + }, + InferIndexConfigurationFunc: &AutoIndexingServiceInferIndexConfigurationFunc{ + defaultHook: i.InferIndexConfiguration, + }, + ListFilesFunc: &AutoIndexingServiceListFilesFunc{ + defaultHook: i.ListFiles, + }, + QueueIndexesFunc: &AutoIndexingServiceQueueIndexesFunc{ + defaultHook: i.QueueIndexes, + }, + SetRequestLanguageSupportFunc: &AutoIndexingServiceSetRequestLanguageSupportFunc{ + defaultHook: i.SetRequestLanguageSupport, + }, + UpdateIndexConfigurationByRepositoryIDFunc: &AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFunc{ + defaultHook: i.UpdateIndexConfigurationByRepositoryID, + }, + } +} + +// AutoIndexingServiceDeleteIndexByIDFunc describes the behavior when the +// DeleteIndexByID method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceDeleteIndexByIDFunc struct { + defaultHook func(context.Context, int) (bool, error) + hooks []func(context.Context, int) (bool, error) + history []AutoIndexingServiceDeleteIndexByIDFuncCall + mutex sync.Mutex +} + +// DeleteIndexByID delegates to the next hook function in the queue and +// stores the parameter and result values of this invocation. +func (m *MockAutoIndexingService) DeleteIndexByID(v0 context.Context, v1 int) (bool, error) { + r0, r1 := m.DeleteIndexByIDFunc.nextHook()(v0, v1) + m.DeleteIndexByIDFunc.appendCall(AutoIndexingServiceDeleteIndexByIDFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the DeleteIndexByID +// method of the parent MockAutoIndexingService instance is invoked and the +// hook queue is empty. +func (f *AutoIndexingServiceDeleteIndexByIDFunc) SetDefaultHook(hook func(context.Context, int) (bool, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// DeleteIndexByID method of the parent MockAutoIndexingService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *AutoIndexingServiceDeleteIndexByIDFunc) PushHook(hook func(context.Context, int) (bool, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceDeleteIndexByIDFunc) SetDefaultReturn(r0 bool, r1 error) { + f.SetDefaultHook(func(context.Context, int) (bool, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceDeleteIndexByIDFunc) PushReturn(r0 bool, r1 error) { + f.PushHook(func(context.Context, int) (bool, error) { + return r0, r1 + }) +} + +func (f *AutoIndexingServiceDeleteIndexByIDFunc) nextHook() func(context.Context, int) (bool, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceDeleteIndexByIDFunc) appendCall(r0 AutoIndexingServiceDeleteIndexByIDFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceDeleteIndexByIDFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceDeleteIndexByIDFunc) History() []AutoIndexingServiceDeleteIndexByIDFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceDeleteIndexByIDFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceDeleteIndexByIDFuncCall is an object that describes an +// invocation of method DeleteIndexByID on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceDeleteIndexByIDFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 bool + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceDeleteIndexByIDFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceDeleteIndexByIDFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// AutoIndexingServiceGetIndexByIDFunc describes the behavior when the +// GetIndexByID method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetIndexByIDFunc struct { + defaultHook func(context.Context, int) (types.Index, bool, error) + hooks []func(context.Context, int) (types.Index, bool, error) + history []AutoIndexingServiceGetIndexByIDFuncCall + mutex sync.Mutex +} + +// GetIndexByID delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetIndexByID(v0 context.Context, v1 int) (types.Index, bool, error) { + r0, r1, r2 := m.GetIndexByIDFunc.nextHook()(v0, v1) + m.GetIndexByIDFunc.appendCall(AutoIndexingServiceGetIndexByIDFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the GetIndexByID method +// of the parent MockAutoIndexingService instance is invoked and the hook +// queue is empty. +func (f *AutoIndexingServiceGetIndexByIDFunc) SetDefaultHook(hook func(context.Context, int) (types.Index, bool, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetIndexByID method of the parent MockAutoIndexingService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *AutoIndexingServiceGetIndexByIDFunc) PushHook(hook func(context.Context, int) (types.Index, bool, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetIndexByIDFunc) SetDefaultReturn(r0 types.Index, r1 bool, r2 error) { + f.SetDefaultHook(func(context.Context, int) (types.Index, bool, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetIndexByIDFunc) PushReturn(r0 types.Index, r1 bool, r2 error) { + f.PushHook(func(context.Context, int) (types.Index, bool, error) { + return r0, r1, r2 + }) +} + +func (f *AutoIndexingServiceGetIndexByIDFunc) nextHook() func(context.Context, int) (types.Index, bool, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetIndexByIDFunc) appendCall(r0 AutoIndexingServiceGetIndexByIDFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetIndexByIDFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetIndexByIDFunc) History() []AutoIndexingServiceGetIndexByIDFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetIndexByIDFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetIndexByIDFuncCall is an object that describes an +// invocation of method GetIndexByID on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetIndexByIDFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 types.Index + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 bool + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetIndexByIDFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetIndexByIDFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// AutoIndexingServiceGetIndexConfigurationByRepositoryIDFunc describes the +// behavior when the GetIndexConfigurationByRepositoryID method of the +// parent MockAutoIndexingService instance is invoked. +type AutoIndexingServiceGetIndexConfigurationByRepositoryIDFunc struct { + defaultHook func(context.Context, int) (shared.IndexConfiguration, bool, error) + hooks []func(context.Context, int) (shared.IndexConfiguration, bool, error) + history []AutoIndexingServiceGetIndexConfigurationByRepositoryIDFuncCall + mutex sync.Mutex +} + +// GetIndexConfigurationByRepositoryID delegates to the next hook function +// in the queue and stores the parameter and result values of this +// invocation. +func (m *MockAutoIndexingService) GetIndexConfigurationByRepositoryID(v0 context.Context, v1 int) (shared.IndexConfiguration, bool, error) { + r0, r1, r2 := m.GetIndexConfigurationByRepositoryIDFunc.nextHook()(v0, v1) + m.GetIndexConfigurationByRepositoryIDFunc.appendCall(AutoIndexingServiceGetIndexConfigurationByRepositoryIDFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the +// GetIndexConfigurationByRepositoryID method of the parent +// MockAutoIndexingService instance is invoked and the hook queue is empty. +func (f *AutoIndexingServiceGetIndexConfigurationByRepositoryIDFunc) SetDefaultHook(hook func(context.Context, int) (shared.IndexConfiguration, bool, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetIndexConfigurationByRepositoryID method of the parent +// MockAutoIndexingService instance invokes the hook at the front of the +// queue and discards it. After the queue is empty, the default hook +// function is invoked for any future action. +func (f *AutoIndexingServiceGetIndexConfigurationByRepositoryIDFunc) PushHook(hook func(context.Context, int) (shared.IndexConfiguration, bool, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetIndexConfigurationByRepositoryIDFunc) SetDefaultReturn(r0 shared.IndexConfiguration, r1 bool, r2 error) { + f.SetDefaultHook(func(context.Context, int) (shared.IndexConfiguration, bool, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetIndexConfigurationByRepositoryIDFunc) PushReturn(r0 shared.IndexConfiguration, r1 bool, r2 error) { + f.PushHook(func(context.Context, int) (shared.IndexConfiguration, bool, error) { + return r0, r1, r2 + }) +} + +func (f *AutoIndexingServiceGetIndexConfigurationByRepositoryIDFunc) nextHook() func(context.Context, int) (shared.IndexConfiguration, bool, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetIndexConfigurationByRepositoryIDFunc) appendCall(r0 AutoIndexingServiceGetIndexConfigurationByRepositoryIDFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// AutoIndexingServiceGetIndexConfigurationByRepositoryIDFuncCall objects +// describing the invocations of this function. +func (f *AutoIndexingServiceGetIndexConfigurationByRepositoryIDFunc) History() []AutoIndexingServiceGetIndexConfigurationByRepositoryIDFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetIndexConfigurationByRepositoryIDFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetIndexConfigurationByRepositoryIDFuncCall is an +// object that describes an invocation of method +// GetIndexConfigurationByRepositoryID on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetIndexConfigurationByRepositoryIDFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 shared.IndexConfiguration + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 bool + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetIndexConfigurationByRepositoryIDFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetIndexConfigurationByRepositoryIDFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// AutoIndexingServiceGetIndexesFunc describes the behavior when the +// GetIndexes method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetIndexesFunc struct { + defaultHook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) + hooks []func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) + history []AutoIndexingServiceGetIndexesFuncCall + mutex sync.Mutex +} + +// GetIndexes delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetIndexes(v0 context.Context, v1 types.GetIndexesOptions) ([]types.Index, int, error) { + r0, r1, r2 := m.GetIndexesFunc.nextHook()(v0, v1) + m.GetIndexesFunc.appendCall(AutoIndexingServiceGetIndexesFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the GetIndexes method of +// the parent MockAutoIndexingService instance is invoked and the hook queue +// is empty. +func (f *AutoIndexingServiceGetIndexesFunc) SetDefaultHook(hook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetIndexes method of the parent MockAutoIndexingService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *AutoIndexingServiceGetIndexesFunc) PushHook(hook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetIndexesFunc) SetDefaultReturn(r0 []types.Index, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetIndexesFunc) PushReturn(r0 []types.Index, r1 int, r2 error) { + f.PushHook(func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + return r0, r1, r2 + }) +} + +func (f *AutoIndexingServiceGetIndexesFunc) nextHook() func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetIndexesFunc) appendCall(r0 AutoIndexingServiceGetIndexesFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetIndexesFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetIndexesFunc) History() []AutoIndexingServiceGetIndexesFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetIndexesFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetIndexesFuncCall is an object that describes an +// invocation of method GetIndexes on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetIndexesFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 types.GetIndexesOptions + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Index + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetIndexesFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetIndexesFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// AutoIndexingServiceGetIndexesByIDsFunc describes the behavior when the +// GetIndexesByIDs method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetIndexesByIDsFunc struct { + defaultHook func(context.Context, ...int) ([]types.Index, error) + hooks []func(context.Context, ...int) ([]types.Index, error) + history []AutoIndexingServiceGetIndexesByIDsFuncCall + mutex sync.Mutex +} + +// GetIndexesByIDs delegates to the next hook function in the queue and +// stores the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetIndexesByIDs(v0 context.Context, v1 ...int) ([]types.Index, error) { + r0, r1 := m.GetIndexesByIDsFunc.nextHook()(v0, v1...) + m.GetIndexesByIDsFunc.appendCall(AutoIndexingServiceGetIndexesByIDsFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetIndexesByIDs +// method of the parent MockAutoIndexingService instance is invoked and the +// hook queue is empty. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]types.Index, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetIndexesByIDs method of the parent MockAutoIndexingService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) PushHook(hook func(context.Context, ...int) ([]types.Index, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) SetDefaultReturn(r0 []types.Index, r1 error) { + f.SetDefaultHook(func(context.Context, ...int) ([]types.Index, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) PushReturn(r0 []types.Index, r1 error) { + f.PushHook(func(context.Context, ...int) ([]types.Index, error) { + return r0, r1 + }) +} + +func (f *AutoIndexingServiceGetIndexesByIDsFunc) nextHook() func(context.Context, ...int) ([]types.Index, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetIndexesByIDsFunc) appendCall(r0 AutoIndexingServiceGetIndexesByIDsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetIndexesByIDsFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) History() []AutoIndexingServiceGetIndexesByIDsFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetIndexesByIDsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetIndexesByIDsFuncCall is an object that describes an +// invocation of method GetIndexesByIDs on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetIndexesByIDsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg1 []int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Index + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c AutoIndexingServiceGetIndexesByIDsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg1 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetIndexesByIDsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// AutoIndexingServiceGetLanguagesRequestedByFunc describes the behavior +// when the GetLanguagesRequestedBy method of the parent +// MockAutoIndexingService instance is invoked. +type AutoIndexingServiceGetLanguagesRequestedByFunc struct { + defaultHook func(context.Context, int) ([]string, error) + hooks []func(context.Context, int) ([]string, error) + history []AutoIndexingServiceGetLanguagesRequestedByFuncCall + mutex sync.Mutex +} + +// GetLanguagesRequestedBy delegates to the next hook function in the queue +// and stores the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetLanguagesRequestedBy(v0 context.Context, v1 int) ([]string, error) { + r0, r1 := m.GetLanguagesRequestedByFunc.nextHook()(v0, v1) + m.GetLanguagesRequestedByFunc.appendCall(AutoIndexingServiceGetLanguagesRequestedByFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the +// GetLanguagesRequestedBy method of the parent MockAutoIndexingService +// instance is invoked and the hook queue is empty. +func (f *AutoIndexingServiceGetLanguagesRequestedByFunc) SetDefaultHook(hook func(context.Context, int) ([]string, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetLanguagesRequestedBy method of the parent MockAutoIndexingService +// instance invokes the hook at the front of the queue and discards it. +// After the queue is empty, the default hook function is invoked for any +// future action. +func (f *AutoIndexingServiceGetLanguagesRequestedByFunc) PushHook(hook func(context.Context, int) ([]string, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetLanguagesRequestedByFunc) SetDefaultReturn(r0 []string, r1 error) { + f.SetDefaultHook(func(context.Context, int) ([]string, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetLanguagesRequestedByFunc) PushReturn(r0 []string, r1 error) { + f.PushHook(func(context.Context, int) ([]string, error) { + return r0, r1 + }) +} + +func (f *AutoIndexingServiceGetLanguagesRequestedByFunc) nextHook() func(context.Context, int) ([]string, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetLanguagesRequestedByFunc) appendCall(r0 AutoIndexingServiceGetLanguagesRequestedByFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// AutoIndexingServiceGetLanguagesRequestedByFuncCall objects describing the +// invocations of this function. +func (f *AutoIndexingServiceGetLanguagesRequestedByFunc) History() []AutoIndexingServiceGetLanguagesRequestedByFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetLanguagesRequestedByFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetLanguagesRequestedByFuncCall is an object that +// describes an invocation of method GetLanguagesRequestedBy on an instance +// of MockAutoIndexingService. +type AutoIndexingServiceGetLanguagesRequestedByFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []string + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetLanguagesRequestedByFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetLanguagesRequestedByFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// AutoIndexingServiceGetLastIndexScanForRepositoryFunc describes the +// behavior when the GetLastIndexScanForRepository method of the parent +// MockAutoIndexingService instance is invoked. +type AutoIndexingServiceGetLastIndexScanForRepositoryFunc struct { + defaultHook func(context.Context, int) (*time.Time, error) + hooks []func(context.Context, int) (*time.Time, error) + history []AutoIndexingServiceGetLastIndexScanForRepositoryFuncCall + mutex sync.Mutex +} + +// GetLastIndexScanForRepository delegates to the next hook function in the +// queue and stores the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetLastIndexScanForRepository(v0 context.Context, v1 int) (*time.Time, error) { + r0, r1 := m.GetLastIndexScanForRepositoryFunc.nextHook()(v0, v1) + m.GetLastIndexScanForRepositoryFunc.appendCall(AutoIndexingServiceGetLastIndexScanForRepositoryFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the +// GetLastIndexScanForRepository method of the parent +// MockAutoIndexingService instance is invoked and the hook queue is empty. +func (f *AutoIndexingServiceGetLastIndexScanForRepositoryFunc) SetDefaultHook(hook func(context.Context, int) (*time.Time, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetLastIndexScanForRepository method of the parent +// MockAutoIndexingService instance invokes the hook at the front of the +// queue and discards it. After the queue is empty, the default hook +// function is invoked for any future action. +func (f *AutoIndexingServiceGetLastIndexScanForRepositoryFunc) PushHook(hook func(context.Context, int) (*time.Time, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetLastIndexScanForRepositoryFunc) SetDefaultReturn(r0 *time.Time, r1 error) { + f.SetDefaultHook(func(context.Context, int) (*time.Time, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetLastIndexScanForRepositoryFunc) PushReturn(r0 *time.Time, r1 error) { + f.PushHook(func(context.Context, int) (*time.Time, error) { + return r0, r1 + }) +} + +func (f *AutoIndexingServiceGetLastIndexScanForRepositoryFunc) nextHook() func(context.Context, int) (*time.Time, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetLastIndexScanForRepositoryFunc) appendCall(r0 AutoIndexingServiceGetLastIndexScanForRepositoryFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// AutoIndexingServiceGetLastIndexScanForRepositoryFuncCall objects +// describing the invocations of this function. +func (f *AutoIndexingServiceGetLastIndexScanForRepositoryFunc) History() []AutoIndexingServiceGetLastIndexScanForRepositoryFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetLastIndexScanForRepositoryFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetLastIndexScanForRepositoryFuncCall is an object +// that describes an invocation of method GetLastIndexScanForRepository on +// an instance of MockAutoIndexingService. +type AutoIndexingServiceGetLastIndexScanForRepositoryFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 *time.Time + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetLastIndexScanForRepositoryFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetLastIndexScanForRepositoryFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// AutoIndexingServiceGetListTagsFunc describes the behavior when the +// GetListTags method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetListTagsFunc struct { + defaultHook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + hooks []func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + history []AutoIndexingServiceGetListTagsFuncCall + mutex sync.Mutex +} + +// GetListTags delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetListTags(v0 context.Context, v1 api.RepoName, v2 ...string) ([]*gitdomain.Tag, error) { + r0, r1 := m.GetListTagsFunc.nextHook()(v0, v1, v2...) + m.GetListTagsFunc.appendCall(AutoIndexingServiceGetListTagsFuncCall{v0, v1, v2, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetListTags method +// of the parent MockAutoIndexingService instance is invoked and the hook +// queue is empty. +func (f *AutoIndexingServiceGetListTagsFunc) SetDefaultHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetListTags method of the parent MockAutoIndexingService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *AutoIndexingServiceGetListTagsFunc) PushHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetListTagsFunc) SetDefaultReturn(r0 []*gitdomain.Tag, r1 error) { + f.SetDefaultHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetListTagsFunc) PushReturn(r0 []*gitdomain.Tag, r1 error) { + f.PushHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +func (f *AutoIndexingServiceGetListTagsFunc) nextHook() func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetListTagsFunc) appendCall(r0 AutoIndexingServiceGetListTagsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetListTagsFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetListTagsFunc) History() []AutoIndexingServiceGetListTagsFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetListTagsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetListTagsFuncCall is an object that describes an +// invocation of method GetListTags on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetListTagsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 api.RepoName + // Arg2 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg2 []string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []*gitdomain.Tag + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c AutoIndexingServiceGetListTagsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg2 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0, c.Arg1}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetListTagsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// AutoIndexingServiceGetRecentIndexesSummaryFunc describes the behavior +// when the GetRecentIndexesSummary method of the parent +// MockAutoIndexingService instance is invoked. +type AutoIndexingServiceGetRecentIndexesSummaryFunc struct { + defaultHook func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error) + hooks []func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error) + history []AutoIndexingServiceGetRecentIndexesSummaryFuncCall + mutex sync.Mutex +} + +// GetRecentIndexesSummary delegates to the next hook function in the queue +// and stores the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetRecentIndexesSummary(v0 context.Context, v1 int) ([]shared.IndexesWithRepositoryNamespace, error) { + r0, r1 := m.GetRecentIndexesSummaryFunc.nextHook()(v0, v1) + m.GetRecentIndexesSummaryFunc.appendCall(AutoIndexingServiceGetRecentIndexesSummaryFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the +// GetRecentIndexesSummary method of the parent MockAutoIndexingService +// instance is invoked and the hook queue is empty. +func (f *AutoIndexingServiceGetRecentIndexesSummaryFunc) SetDefaultHook(hook func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetRecentIndexesSummary method of the parent MockAutoIndexingService +// instance invokes the hook at the front of the queue and discards it. +// After the queue is empty, the default hook function is invoked for any +// future action. +func (f *AutoIndexingServiceGetRecentIndexesSummaryFunc) PushHook(hook func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetRecentIndexesSummaryFunc) SetDefaultReturn(r0 []shared.IndexesWithRepositoryNamespace, r1 error) { + f.SetDefaultHook(func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetRecentIndexesSummaryFunc) PushReturn(r0 []shared.IndexesWithRepositoryNamespace, r1 error) { + f.PushHook(func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error) { + return r0, r1 + }) +} + +func (f *AutoIndexingServiceGetRecentIndexesSummaryFunc) nextHook() func(context.Context, int) ([]shared.IndexesWithRepositoryNamespace, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetRecentIndexesSummaryFunc) appendCall(r0 AutoIndexingServiceGetRecentIndexesSummaryFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// AutoIndexingServiceGetRecentIndexesSummaryFuncCall objects describing the +// invocations of this function. +func (f *AutoIndexingServiceGetRecentIndexesSummaryFunc) History() []AutoIndexingServiceGetRecentIndexesSummaryFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetRecentIndexesSummaryFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetRecentIndexesSummaryFuncCall is an object that +// describes an invocation of method GetRecentIndexesSummary on an instance +// of MockAutoIndexingService. +type AutoIndexingServiceGetRecentIndexesSummaryFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []shared.IndexesWithRepositoryNamespace + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetRecentIndexesSummaryFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetRecentIndexesSummaryFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// AutoIndexingServiceGetSupportedByCtagsFunc describes the behavior when +// the GetSupportedByCtags method of the parent MockAutoIndexingService +// instance is invoked. +type AutoIndexingServiceGetSupportedByCtagsFunc struct { + defaultHook func(context.Context, string, api.RepoName) (bool, string, error) + hooks []func(context.Context, string, api.RepoName) (bool, string, error) + history []AutoIndexingServiceGetSupportedByCtagsFuncCall + mutex sync.Mutex +} + +// GetSupportedByCtags delegates to the next hook function in the queue and +// stores the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetSupportedByCtags(v0 context.Context, v1 string, v2 api.RepoName) (bool, string, error) { + r0, r1, r2 := m.GetSupportedByCtagsFunc.nextHook()(v0, v1, v2) + m.GetSupportedByCtagsFunc.appendCall(AutoIndexingServiceGetSupportedByCtagsFuncCall{v0, v1, v2, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the GetSupportedByCtags +// method of the parent MockAutoIndexingService instance is invoked and the +// hook queue is empty. +func (f *AutoIndexingServiceGetSupportedByCtagsFunc) SetDefaultHook(hook func(context.Context, string, api.RepoName) (bool, string, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetSupportedByCtags method of the parent MockAutoIndexingService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *AutoIndexingServiceGetSupportedByCtagsFunc) PushHook(hook func(context.Context, string, api.RepoName) (bool, string, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetSupportedByCtagsFunc) SetDefaultReturn(r0 bool, r1 string, r2 error) { + f.SetDefaultHook(func(context.Context, string, api.RepoName) (bool, string, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetSupportedByCtagsFunc) PushReturn(r0 bool, r1 string, r2 error) { + f.PushHook(func(context.Context, string, api.RepoName) (bool, string, error) { + return r0, r1, r2 + }) +} + +func (f *AutoIndexingServiceGetSupportedByCtagsFunc) nextHook() func(context.Context, string, api.RepoName) (bool, string, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetSupportedByCtagsFunc) appendCall(r0 AutoIndexingServiceGetSupportedByCtagsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// AutoIndexingServiceGetSupportedByCtagsFuncCall objects describing the +// invocations of this function. +func (f *AutoIndexingServiceGetSupportedByCtagsFunc) History() []AutoIndexingServiceGetSupportedByCtagsFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetSupportedByCtagsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetSupportedByCtagsFuncCall is an object that +// describes an invocation of method GetSupportedByCtags on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetSupportedByCtagsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 string + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 api.RepoName + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 bool + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 string + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetSupportedByCtagsFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetSupportedByCtagsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// AutoIndexingServiceGetUnsafeDBFunc describes the behavior when the +// GetUnsafeDB method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetUnsafeDBFunc struct { + defaultHook func() database.DB + hooks []func() database.DB + history []AutoIndexingServiceGetUnsafeDBFuncCall + mutex sync.Mutex +} + +// GetUnsafeDB delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetUnsafeDB() database.DB { + r0 := m.GetUnsafeDBFunc.nextHook()() + m.GetUnsafeDBFunc.appendCall(AutoIndexingServiceGetUnsafeDBFuncCall{r0}) + return r0 +} + +// SetDefaultHook sets function that is called when the GetUnsafeDB method +// of the parent MockAutoIndexingService instance is invoked and the hook +// queue is empty. +func (f *AutoIndexingServiceGetUnsafeDBFunc) SetDefaultHook(hook func() database.DB) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUnsafeDB method of the parent MockAutoIndexingService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *AutoIndexingServiceGetUnsafeDBFunc) PushHook(hook func() database.DB) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetUnsafeDBFunc) SetDefaultReturn(r0 database.DB) { + f.SetDefaultHook(func() database.DB { + return r0 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetUnsafeDBFunc) PushReturn(r0 database.DB) { + f.PushHook(func() database.DB { + return r0 + }) +} + +func (f *AutoIndexingServiceGetUnsafeDBFunc) nextHook() func() database.DB { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetUnsafeDBFunc) appendCall(r0 AutoIndexingServiceGetUnsafeDBFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetUnsafeDBFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetUnsafeDBFunc) History() []AutoIndexingServiceGetUnsafeDBFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetUnsafeDBFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetUnsafeDBFuncCall is an object that describes an +// invocation of method GetUnsafeDB on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetUnsafeDBFuncCall struct { + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 database.DB +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetUnsafeDBFuncCall) Args() []interface{} { + return []interface{}{} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetUnsafeDBFuncCall) Results() []interface{} { + return []interface{}{c.Result0} +} + +// AutoIndexingServiceInferIndexConfigurationFunc describes the behavior +// when the InferIndexConfiguration method of the parent +// MockAutoIndexingService instance is invoked. +type AutoIndexingServiceInferIndexConfigurationFunc struct { + defaultHook func(context.Context, int, string, bool) (*config.IndexConfiguration, []config.IndexJobHint, error) + hooks []func(context.Context, int, string, bool) (*config.IndexConfiguration, []config.IndexJobHint, error) + history []AutoIndexingServiceInferIndexConfigurationFuncCall + mutex sync.Mutex +} + +// InferIndexConfiguration delegates to the next hook function in the queue +// and stores the parameter and result values of this invocation. +func (m *MockAutoIndexingService) InferIndexConfiguration(v0 context.Context, v1 int, v2 string, v3 bool) (*config.IndexConfiguration, []config.IndexJobHint, error) { + r0, r1, r2 := m.InferIndexConfigurationFunc.nextHook()(v0, v1, v2, v3) + m.InferIndexConfigurationFunc.appendCall(AutoIndexingServiceInferIndexConfigurationFuncCall{v0, v1, v2, v3, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the +// InferIndexConfiguration method of the parent MockAutoIndexingService +// instance is invoked and the hook queue is empty. +func (f *AutoIndexingServiceInferIndexConfigurationFunc) SetDefaultHook(hook func(context.Context, int, string, bool) (*config.IndexConfiguration, []config.IndexJobHint, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// InferIndexConfiguration method of the parent MockAutoIndexingService +// instance invokes the hook at the front of the queue and discards it. +// After the queue is empty, the default hook function is invoked for any +// future action. +func (f *AutoIndexingServiceInferIndexConfigurationFunc) PushHook(hook func(context.Context, int, string, bool) (*config.IndexConfiguration, []config.IndexJobHint, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceInferIndexConfigurationFunc) SetDefaultReturn(r0 *config.IndexConfiguration, r1 []config.IndexJobHint, r2 error) { + f.SetDefaultHook(func(context.Context, int, string, bool) (*config.IndexConfiguration, []config.IndexJobHint, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceInferIndexConfigurationFunc) PushReturn(r0 *config.IndexConfiguration, r1 []config.IndexJobHint, r2 error) { + f.PushHook(func(context.Context, int, string, bool) (*config.IndexConfiguration, []config.IndexJobHint, error) { + return r0, r1, r2 + }) +} + +func (f *AutoIndexingServiceInferIndexConfigurationFunc) nextHook() func(context.Context, int, string, bool) (*config.IndexConfiguration, []config.IndexJobHint, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceInferIndexConfigurationFunc) appendCall(r0 AutoIndexingServiceInferIndexConfigurationFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// AutoIndexingServiceInferIndexConfigurationFuncCall objects describing the +// invocations of this function. +func (f *AutoIndexingServiceInferIndexConfigurationFunc) History() []AutoIndexingServiceInferIndexConfigurationFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceInferIndexConfigurationFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceInferIndexConfigurationFuncCall is an object that +// describes an invocation of method InferIndexConfiguration on an instance +// of MockAutoIndexingService. +type AutoIndexingServiceInferIndexConfigurationFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 string + // Arg3 is the value of the 4th argument passed to this method + // invocation. + Arg3 bool + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 *config.IndexConfiguration + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 []config.IndexJobHint + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceInferIndexConfigurationFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceInferIndexConfigurationFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// AutoIndexingServiceListFilesFunc describes the behavior when the +// ListFiles method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceListFilesFunc struct { + defaultHook func(context.Context, int, string, *regexp.Regexp) ([]string, error) + hooks []func(context.Context, int, string, *regexp.Regexp) ([]string, error) + history []AutoIndexingServiceListFilesFuncCall + mutex sync.Mutex +} + +// ListFiles delegates to the next hook function in the queue and stores the +// parameter and result values of this invocation. +func (m *MockAutoIndexingService) ListFiles(v0 context.Context, v1 int, v2 string, v3 *regexp.Regexp) ([]string, error) { + r0, r1 := m.ListFilesFunc.nextHook()(v0, v1, v2, v3) + m.ListFilesFunc.appendCall(AutoIndexingServiceListFilesFuncCall{v0, v1, v2, v3, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the ListFiles method of +// the parent MockAutoIndexingService instance is invoked and the hook queue +// is empty. +func (f *AutoIndexingServiceListFilesFunc) SetDefaultHook(hook func(context.Context, int, string, *regexp.Regexp) ([]string, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// ListFiles method of the parent MockAutoIndexingService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *AutoIndexingServiceListFilesFunc) PushHook(hook func(context.Context, int, string, *regexp.Regexp) ([]string, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceListFilesFunc) SetDefaultReturn(r0 []string, r1 error) { + f.SetDefaultHook(func(context.Context, int, string, *regexp.Regexp) ([]string, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceListFilesFunc) PushReturn(r0 []string, r1 error) { + f.PushHook(func(context.Context, int, string, *regexp.Regexp) ([]string, error) { + return r0, r1 + }) +} + +func (f *AutoIndexingServiceListFilesFunc) nextHook() func(context.Context, int, string, *regexp.Regexp) ([]string, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceListFilesFunc) appendCall(r0 AutoIndexingServiceListFilesFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceListFilesFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceListFilesFunc) History() []AutoIndexingServiceListFilesFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceListFilesFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceListFilesFuncCall is an object that describes an +// invocation of method ListFiles on an instance of MockAutoIndexingService. +type AutoIndexingServiceListFilesFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 string + // Arg3 is the value of the 4th argument passed to this method + // invocation. + Arg3 *regexp.Regexp + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []string + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceListFilesFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceListFilesFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// AutoIndexingServiceQueueIndexesFunc describes the behavior when the +// QueueIndexes method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceQueueIndexesFunc struct { + defaultHook func(context.Context, int, string, string, bool, bool) ([]types.Index, error) + hooks []func(context.Context, int, string, string, bool, bool) ([]types.Index, error) + history []AutoIndexingServiceQueueIndexesFuncCall + mutex sync.Mutex +} + +// QueueIndexes delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) QueueIndexes(v0 context.Context, v1 int, v2 string, v3 string, v4 bool, v5 bool) ([]types.Index, error) { + r0, r1 := m.QueueIndexesFunc.nextHook()(v0, v1, v2, v3, v4, v5) + m.QueueIndexesFunc.appendCall(AutoIndexingServiceQueueIndexesFuncCall{v0, v1, v2, v3, v4, v5, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the QueueIndexes method +// of the parent MockAutoIndexingService instance is invoked and the hook +// queue is empty. +func (f *AutoIndexingServiceQueueIndexesFunc) SetDefaultHook(hook func(context.Context, int, string, string, bool, bool) ([]types.Index, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// QueueIndexes method of the parent MockAutoIndexingService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *AutoIndexingServiceQueueIndexesFunc) PushHook(hook func(context.Context, int, string, string, bool, bool) ([]types.Index, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceQueueIndexesFunc) SetDefaultReturn(r0 []types.Index, r1 error) { + f.SetDefaultHook(func(context.Context, int, string, string, bool, bool) ([]types.Index, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceQueueIndexesFunc) PushReturn(r0 []types.Index, r1 error) { + f.PushHook(func(context.Context, int, string, string, bool, bool) ([]types.Index, error) { + return r0, r1 + }) +} + +func (f *AutoIndexingServiceQueueIndexesFunc) nextHook() func(context.Context, int, string, string, bool, bool) ([]types.Index, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceQueueIndexesFunc) appendCall(r0 AutoIndexingServiceQueueIndexesFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceQueueIndexesFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceQueueIndexesFunc) History() []AutoIndexingServiceQueueIndexesFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceQueueIndexesFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceQueueIndexesFuncCall is an object that describes an +// invocation of method QueueIndexes on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceQueueIndexesFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 string + // Arg3 is the value of the 4th argument passed to this method + // invocation. + Arg3 string + // Arg4 is the value of the 5th argument passed to this method + // invocation. + Arg4 bool + // Arg5 is the value of the 6th argument passed to this method + // invocation. + Arg5 bool + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Index + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceQueueIndexesFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3, c.Arg4, c.Arg5} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceQueueIndexesFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// AutoIndexingServiceSetRequestLanguageSupportFunc describes the behavior +// when the SetRequestLanguageSupport method of the parent +// MockAutoIndexingService instance is invoked. +type AutoIndexingServiceSetRequestLanguageSupportFunc struct { + defaultHook func(context.Context, int, string) error + hooks []func(context.Context, int, string) error + history []AutoIndexingServiceSetRequestLanguageSupportFuncCall + mutex sync.Mutex +} + +// SetRequestLanguageSupport delegates to the next hook function in the +// queue and stores the parameter and result values of this invocation. +func (m *MockAutoIndexingService) SetRequestLanguageSupport(v0 context.Context, v1 int, v2 string) error { + r0 := m.SetRequestLanguageSupportFunc.nextHook()(v0, v1, v2) + m.SetRequestLanguageSupportFunc.appendCall(AutoIndexingServiceSetRequestLanguageSupportFuncCall{v0, v1, v2, r0}) + return r0 +} + +// SetDefaultHook sets function that is called when the +// SetRequestLanguageSupport method of the parent MockAutoIndexingService +// instance is invoked and the hook queue is empty. +func (f *AutoIndexingServiceSetRequestLanguageSupportFunc) SetDefaultHook(hook func(context.Context, int, string) error) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// SetRequestLanguageSupport method of the parent MockAutoIndexingService +// instance invokes the hook at the front of the queue and discards it. +// After the queue is empty, the default hook function is invoked for any +// future action. +func (f *AutoIndexingServiceSetRequestLanguageSupportFunc) PushHook(hook func(context.Context, int, string) error) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceSetRequestLanguageSupportFunc) SetDefaultReturn(r0 error) { + f.SetDefaultHook(func(context.Context, int, string) error { + return r0 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceSetRequestLanguageSupportFunc) PushReturn(r0 error) { + f.PushHook(func(context.Context, int, string) error { + return r0 + }) +} + +func (f *AutoIndexingServiceSetRequestLanguageSupportFunc) nextHook() func(context.Context, int, string) error { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceSetRequestLanguageSupportFunc) appendCall(r0 AutoIndexingServiceSetRequestLanguageSupportFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// AutoIndexingServiceSetRequestLanguageSupportFuncCall objects describing +// the invocations of this function. +func (f *AutoIndexingServiceSetRequestLanguageSupportFunc) History() []AutoIndexingServiceSetRequestLanguageSupportFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceSetRequestLanguageSupportFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceSetRequestLanguageSupportFuncCall is an object that +// describes an invocation of method SetRequestLanguageSupport on an +// instance of MockAutoIndexingService. +type AutoIndexingServiceSetRequestLanguageSupportFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceSetRequestLanguageSupportFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceSetRequestLanguageSupportFuncCall) Results() []interface{} { + return []interface{}{c.Result0} +} + +// AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFunc describes +// the behavior when the UpdateIndexConfigurationByRepositoryID method of +// the parent MockAutoIndexingService instance is invoked. +type AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFunc struct { + defaultHook func(context.Context, int, []byte) error + hooks []func(context.Context, int, []byte) error + history []AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFuncCall + mutex sync.Mutex +} + +// UpdateIndexConfigurationByRepositoryID delegates to the next hook +// function in the queue and stores the parameter and result values of this +// invocation. +func (m *MockAutoIndexingService) UpdateIndexConfigurationByRepositoryID(v0 context.Context, v1 int, v2 []byte) error { + r0 := m.UpdateIndexConfigurationByRepositoryIDFunc.nextHook()(v0, v1, v2) + m.UpdateIndexConfigurationByRepositoryIDFunc.appendCall(AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFuncCall{v0, v1, v2, r0}) + return r0 +} + +// SetDefaultHook sets function that is called when the +// UpdateIndexConfigurationByRepositoryID method of the parent +// MockAutoIndexingService instance is invoked and the hook queue is empty. +func (f *AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFunc) SetDefaultHook(hook func(context.Context, int, []byte) error) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// UpdateIndexConfigurationByRepositoryID method of the parent +// MockAutoIndexingService instance invokes the hook at the front of the +// queue and discards it. After the queue is empty, the default hook +// function is invoked for any future action. +func (f *AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFunc) PushHook(hook func(context.Context, int, []byte) error) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFunc) SetDefaultReturn(r0 error) { + f.SetDefaultHook(func(context.Context, int, []byte) error { + return r0 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFunc) PushReturn(r0 error) { + f.PushHook(func(context.Context, int, []byte) error { + return r0 + }) +} + +func (f *AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFunc) nextHook() func(context.Context, int, []byte) error { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFunc) appendCall(r0 AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFuncCall objects +// describing the invocations of this function. +func (f *AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFunc) History() []AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFuncCall is an +// object that describes an invocation of method +// UpdateIndexConfigurationByRepositoryID on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 []byte + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceUpdateIndexConfigurationByRepositoryIDFuncCall) Results() []interface{} { + return []interface{}{c.Result0} +} + +// MockPolicyService is a mock implementation of the PolicyService interface +// (from the package +// github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/transport/graphql) +// used for unit testing. +type MockPolicyService struct { + // GetRetentionPolicyOverviewFunc is an instance of a mock function + // object controlling the behavior of the method + // GetRetentionPolicyOverview. + GetRetentionPolicyOverviewFunc *PolicyServiceGetRetentionPolicyOverviewFunc +} + +// NewMockPolicyService creates a new mock of the PolicyService interface. +// All methods return zero values for all results, unless overwritten. +func NewMockPolicyService() *MockPolicyService { + return &MockPolicyService{ + GetRetentionPolicyOverviewFunc: &PolicyServiceGetRetentionPolicyOverviewFunc{ + defaultHook: func(context.Context, types.Upload, bool, int, int64, string, time.Time) (r0 []types.RetentionPolicyMatchCandidate, r1 int, r2 error) { + return + }, + }, + } +} + +// NewStrictMockPolicyService creates a new mock of the PolicyService +// interface. All methods panic on invocation, unless overwritten. +func NewStrictMockPolicyService() *MockPolicyService { + return &MockPolicyService{ + GetRetentionPolicyOverviewFunc: &PolicyServiceGetRetentionPolicyOverviewFunc{ + defaultHook: func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + panic("unexpected invocation of MockPolicyService.GetRetentionPolicyOverview") + }, + }, + } +} + +// NewMockPolicyServiceFrom creates a new mock of the MockPolicyService +// interface. All methods delegate to the given implementation, unless +// overwritten. +func NewMockPolicyServiceFrom(i PolicyService) *MockPolicyService { + return &MockPolicyService{ + GetRetentionPolicyOverviewFunc: &PolicyServiceGetRetentionPolicyOverviewFunc{ + defaultHook: i.GetRetentionPolicyOverview, + }, + } +} + +// PolicyServiceGetRetentionPolicyOverviewFunc describes the behavior when +// the GetRetentionPolicyOverview method of the parent MockPolicyService +// instance is invoked. +type PolicyServiceGetRetentionPolicyOverviewFunc struct { + defaultHook func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) + hooks []func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) + history []PolicyServiceGetRetentionPolicyOverviewFuncCall + mutex sync.Mutex +} + +// GetRetentionPolicyOverview delegates to the next hook function in the +// queue and stores the parameter and result values of this invocation. +func (m *MockPolicyService) GetRetentionPolicyOverview(v0 context.Context, v1 types.Upload, v2 bool, v3 int, v4 int64, v5 string, v6 time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + r0, r1, r2 := m.GetRetentionPolicyOverviewFunc.nextHook()(v0, v1, v2, v3, v4, v5, v6) + m.GetRetentionPolicyOverviewFunc.appendCall(PolicyServiceGetRetentionPolicyOverviewFuncCall{v0, v1, v2, v3, v4, v5, v6, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the +// GetRetentionPolicyOverview method of the parent MockPolicyService +// instance is invoked and the hook queue is empty. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) SetDefaultHook(hook func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetRetentionPolicyOverview method of the parent MockPolicyService +// instance invokes the hook at the front of the queue and discards it. +// After the queue is empty, the default hook function is invoked for any +// future action. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) PushHook(hook func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) SetDefaultReturn(r0 []types.RetentionPolicyMatchCandidate, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) PushReturn(r0 []types.RetentionPolicyMatchCandidate, r1 int, r2 error) { + f.PushHook(func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + return r0, r1, r2 + }) +} + +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) nextHook() func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) appendCall(r0 PolicyServiceGetRetentionPolicyOverviewFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// PolicyServiceGetRetentionPolicyOverviewFuncCall objects describing the +// invocations of this function. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) History() []PolicyServiceGetRetentionPolicyOverviewFuncCall { + f.mutex.Lock() + history := make([]PolicyServiceGetRetentionPolicyOverviewFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// PolicyServiceGetRetentionPolicyOverviewFuncCall is an object that +// describes an invocation of method GetRetentionPolicyOverview on an +// instance of MockPolicyService. +type PolicyServiceGetRetentionPolicyOverviewFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 types.Upload + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 bool + // Arg3 is the value of the 4th argument passed to this method + // invocation. + Arg3 int + // Arg4 is the value of the 5th argument passed to this method + // invocation. + Arg4 int64 + // Arg5 is the value of the 6th argument passed to this method + // invocation. + Arg5 string + // Arg6 is the value of the 7th argument passed to this method + // invocation. + Arg6 time.Time + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.RetentionPolicyMatchCandidate + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c PolicyServiceGetRetentionPolicyOverviewFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3, c.Arg4, c.Arg5, c.Arg6} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c PolicyServiceGetRetentionPolicyOverviewFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// MockUploadsService is a mock implementation of the UploadsService +// interface (from the package +// github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/transport/graphql) +// used for unit testing. +type MockUploadsService struct { + // GetAuditLogsForUploadFunc is an instance of a mock function object + // controlling the behavior of the method GetAuditLogsForUpload. + GetAuditLogsForUploadFunc *UploadsServiceGetAuditLogsForUploadFunc + // GetLastUploadRetentionScanForRepositoryFunc is an instance of a mock + // function object controlling the behavior of the method + // GetLastUploadRetentionScanForRepository. + GetLastUploadRetentionScanForRepositoryFunc *UploadsServiceGetLastUploadRetentionScanForRepositoryFunc + // GetListTagsFunc is an instance of a mock function object controlling + // the behavior of the method GetListTags. + GetListTagsFunc *UploadsServiceGetListTagsFunc + // GetRecentUploadsSummaryFunc is an instance of a mock function object + // controlling the behavior of the method GetRecentUploadsSummary. + GetRecentUploadsSummaryFunc *UploadsServiceGetRecentUploadsSummaryFunc + // GetUploadDocumentsForPathFunc is an instance of a mock function + // object controlling the behavior of the method + // GetUploadDocumentsForPath. + GetUploadDocumentsForPathFunc *UploadsServiceGetUploadDocumentsForPathFunc + // GetUploadsFunc is an instance of a mock function object controlling + // the behavior of the method GetUploads. + GetUploadsFunc *UploadsServiceGetUploadsFunc + // GetUploadsByIDsFunc is an instance of a mock function object + // controlling the behavior of the method GetUploadsByIDs. + GetUploadsByIDsFunc *UploadsServiceGetUploadsByIDsFunc +} + +// NewMockUploadsService creates a new mock of the UploadsService interface. +// All methods return zero values for all results, unless overwritten. +func NewMockUploadsService() *MockUploadsService { + return &MockUploadsService{ + GetAuditLogsForUploadFunc: &UploadsServiceGetAuditLogsForUploadFunc{ + defaultHook: func(context.Context, int) (r0 []types.UploadLog, r1 error) { + return + }, + }, + GetLastUploadRetentionScanForRepositoryFunc: &UploadsServiceGetLastUploadRetentionScanForRepositoryFunc{ + defaultHook: func(context.Context, int) (r0 *time.Time, r1 error) { + return + }, + }, + GetListTagsFunc: &UploadsServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) (r0 []*gitdomain.Tag, r1 error) { + return + }, + }, + GetRecentUploadsSummaryFunc: &UploadsServiceGetRecentUploadsSummaryFunc{ + defaultHook: func(context.Context, int) (r0 []shared1.UploadsWithRepositoryNamespace, r1 error) { + return + }, + }, + GetUploadDocumentsForPathFunc: &UploadsServiceGetUploadDocumentsForPathFunc{ + defaultHook: func(context.Context, int, string) (r0 []string, r1 int, r2 error) { + return + }, + }, + GetUploadsFunc: &UploadsServiceGetUploadsFunc{ + defaultHook: func(context.Context, types.GetUploadsOptions) (r0 []types.Upload, r1 int, r2 error) { + return + }, + }, + GetUploadsByIDsFunc: &UploadsServiceGetUploadsByIDsFunc{ + defaultHook: func(context.Context, ...int) (r0 []types.Upload, r1 error) { + return + }, + }, + } +} + +// NewStrictMockUploadsService creates a new mock of the UploadsService +// interface. All methods panic on invocation, unless overwritten. +func NewStrictMockUploadsService() *MockUploadsService { + return &MockUploadsService{ + GetAuditLogsForUploadFunc: &UploadsServiceGetAuditLogsForUploadFunc{ + defaultHook: func(context.Context, int) ([]types.UploadLog, error) { + panic("unexpected invocation of MockUploadsService.GetAuditLogsForUpload") + }, + }, + GetLastUploadRetentionScanForRepositoryFunc: &UploadsServiceGetLastUploadRetentionScanForRepositoryFunc{ + defaultHook: func(context.Context, int) (*time.Time, error) { + panic("unexpected invocation of MockUploadsService.GetLastUploadRetentionScanForRepository") + }, + }, + GetListTagsFunc: &UploadsServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + panic("unexpected invocation of MockUploadsService.GetListTags") + }, + }, + GetRecentUploadsSummaryFunc: &UploadsServiceGetRecentUploadsSummaryFunc{ + defaultHook: func(context.Context, int) ([]shared1.UploadsWithRepositoryNamespace, error) { + panic("unexpected invocation of MockUploadsService.GetRecentUploadsSummary") + }, + }, + GetUploadDocumentsForPathFunc: &UploadsServiceGetUploadDocumentsForPathFunc{ + defaultHook: func(context.Context, int, string) ([]string, int, error) { + panic("unexpected invocation of MockUploadsService.GetUploadDocumentsForPath") + }, + }, + GetUploadsFunc: &UploadsServiceGetUploadsFunc{ + defaultHook: func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + panic("unexpected invocation of MockUploadsService.GetUploads") + }, + }, + GetUploadsByIDsFunc: &UploadsServiceGetUploadsByIDsFunc{ + defaultHook: func(context.Context, ...int) ([]types.Upload, error) { + panic("unexpected invocation of MockUploadsService.GetUploadsByIDs") + }, + }, + } +} + +// NewMockUploadsServiceFrom creates a new mock of the MockUploadsService +// interface. All methods delegate to the given implementation, unless +// overwritten. +func NewMockUploadsServiceFrom(i UploadsService) *MockUploadsService { + return &MockUploadsService{ + GetAuditLogsForUploadFunc: &UploadsServiceGetAuditLogsForUploadFunc{ + defaultHook: i.GetAuditLogsForUpload, + }, + GetLastUploadRetentionScanForRepositoryFunc: &UploadsServiceGetLastUploadRetentionScanForRepositoryFunc{ + defaultHook: i.GetLastUploadRetentionScanForRepository, + }, + GetListTagsFunc: &UploadsServiceGetListTagsFunc{ + defaultHook: i.GetListTags, + }, + GetRecentUploadsSummaryFunc: &UploadsServiceGetRecentUploadsSummaryFunc{ + defaultHook: i.GetRecentUploadsSummary, + }, + GetUploadDocumentsForPathFunc: &UploadsServiceGetUploadDocumentsForPathFunc{ + defaultHook: i.GetUploadDocumentsForPath, + }, + GetUploadsFunc: &UploadsServiceGetUploadsFunc{ + defaultHook: i.GetUploads, + }, + GetUploadsByIDsFunc: &UploadsServiceGetUploadsByIDsFunc{ + defaultHook: i.GetUploadsByIDs, + }, + } +} + +// UploadsServiceGetAuditLogsForUploadFunc describes the behavior when the +// GetAuditLogsForUpload method of the parent MockUploadsService instance is +// invoked. +type UploadsServiceGetAuditLogsForUploadFunc struct { + defaultHook func(context.Context, int) ([]types.UploadLog, error) + hooks []func(context.Context, int) ([]types.UploadLog, error) + history []UploadsServiceGetAuditLogsForUploadFuncCall + mutex sync.Mutex +} + +// GetAuditLogsForUpload delegates to the next hook function in the queue +// and stores the parameter and result values of this invocation. +func (m *MockUploadsService) GetAuditLogsForUpload(v0 context.Context, v1 int) ([]types.UploadLog, error) { + r0, r1 := m.GetAuditLogsForUploadFunc.nextHook()(v0, v1) + m.GetAuditLogsForUploadFunc.appendCall(UploadsServiceGetAuditLogsForUploadFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the +// GetAuditLogsForUpload method of the parent MockUploadsService instance is +// invoked and the hook queue is empty. +func (f *UploadsServiceGetAuditLogsForUploadFunc) SetDefaultHook(hook func(context.Context, int) ([]types.UploadLog, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetAuditLogsForUpload method of the parent MockUploadsService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *UploadsServiceGetAuditLogsForUploadFunc) PushHook(hook func(context.Context, int) ([]types.UploadLog, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetAuditLogsForUploadFunc) SetDefaultReturn(r0 []types.UploadLog, r1 error) { + f.SetDefaultHook(func(context.Context, int) ([]types.UploadLog, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetAuditLogsForUploadFunc) PushReturn(r0 []types.UploadLog, r1 error) { + f.PushHook(func(context.Context, int) ([]types.UploadLog, error) { + return r0, r1 + }) +} + +func (f *UploadsServiceGetAuditLogsForUploadFunc) nextHook() func(context.Context, int) ([]types.UploadLog, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetAuditLogsForUploadFunc) appendCall(r0 UploadsServiceGetAuditLogsForUploadFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadsServiceGetAuditLogsForUploadFuncCall +// objects describing the invocations of this function. +func (f *UploadsServiceGetAuditLogsForUploadFunc) History() []UploadsServiceGetAuditLogsForUploadFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetAuditLogsForUploadFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetAuditLogsForUploadFuncCall is an object that describes +// an invocation of method GetAuditLogsForUpload on an instance of +// MockUploadsService. +type UploadsServiceGetAuditLogsForUploadFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.UploadLog + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadsServiceGetAuditLogsForUploadFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetAuditLogsForUploadFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// UploadsServiceGetLastUploadRetentionScanForRepositoryFunc describes the +// behavior when the GetLastUploadRetentionScanForRepository method of the +// parent MockUploadsService instance is invoked. +type UploadsServiceGetLastUploadRetentionScanForRepositoryFunc struct { + defaultHook func(context.Context, int) (*time.Time, error) + hooks []func(context.Context, int) (*time.Time, error) + history []UploadsServiceGetLastUploadRetentionScanForRepositoryFuncCall + mutex sync.Mutex +} + +// GetLastUploadRetentionScanForRepository delegates to the next hook +// function in the queue and stores the parameter and result values of this +// invocation. +func (m *MockUploadsService) GetLastUploadRetentionScanForRepository(v0 context.Context, v1 int) (*time.Time, error) { + r0, r1 := m.GetLastUploadRetentionScanForRepositoryFunc.nextHook()(v0, v1) + m.GetLastUploadRetentionScanForRepositoryFunc.appendCall(UploadsServiceGetLastUploadRetentionScanForRepositoryFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the +// GetLastUploadRetentionScanForRepository method of the parent +// MockUploadsService instance is invoked and the hook queue is empty. +func (f *UploadsServiceGetLastUploadRetentionScanForRepositoryFunc) SetDefaultHook(hook func(context.Context, int) (*time.Time, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetLastUploadRetentionScanForRepository method of the parent +// MockUploadsService instance invokes the hook at the front of the queue +// and discards it. After the queue is empty, the default hook function is +// invoked for any future action. +func (f *UploadsServiceGetLastUploadRetentionScanForRepositoryFunc) PushHook(hook func(context.Context, int) (*time.Time, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetLastUploadRetentionScanForRepositoryFunc) SetDefaultReturn(r0 *time.Time, r1 error) { + f.SetDefaultHook(func(context.Context, int) (*time.Time, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetLastUploadRetentionScanForRepositoryFunc) PushReturn(r0 *time.Time, r1 error) { + f.PushHook(func(context.Context, int) (*time.Time, error) { + return r0, r1 + }) +} + +func (f *UploadsServiceGetLastUploadRetentionScanForRepositoryFunc) nextHook() func(context.Context, int) (*time.Time, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetLastUploadRetentionScanForRepositoryFunc) appendCall(r0 UploadsServiceGetLastUploadRetentionScanForRepositoryFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// UploadsServiceGetLastUploadRetentionScanForRepositoryFuncCall objects +// describing the invocations of this function. +func (f *UploadsServiceGetLastUploadRetentionScanForRepositoryFunc) History() []UploadsServiceGetLastUploadRetentionScanForRepositoryFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetLastUploadRetentionScanForRepositoryFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetLastUploadRetentionScanForRepositoryFuncCall is an +// object that describes an invocation of method +// GetLastUploadRetentionScanForRepository on an instance of +// MockUploadsService. +type UploadsServiceGetLastUploadRetentionScanForRepositoryFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 *time.Time + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadsServiceGetLastUploadRetentionScanForRepositoryFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetLastUploadRetentionScanForRepositoryFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// UploadsServiceGetListTagsFunc describes the behavior when the GetListTags +// method of the parent MockUploadsService instance is invoked. +type UploadsServiceGetListTagsFunc struct { + defaultHook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + hooks []func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + history []UploadsServiceGetListTagsFuncCall + mutex sync.Mutex +} + +// GetListTags delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockUploadsService) GetListTags(v0 context.Context, v1 api.RepoName, v2 ...string) ([]*gitdomain.Tag, error) { + r0, r1 := m.GetListTagsFunc.nextHook()(v0, v1, v2...) + m.GetListTagsFunc.appendCall(UploadsServiceGetListTagsFuncCall{v0, v1, v2, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetListTags method +// of the parent MockUploadsService instance is invoked and the hook queue +// is empty. +func (f *UploadsServiceGetListTagsFunc) SetDefaultHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetListTags method of the parent MockUploadsService instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *UploadsServiceGetListTagsFunc) PushHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetListTagsFunc) SetDefaultReturn(r0 []*gitdomain.Tag, r1 error) { + f.SetDefaultHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetListTagsFunc) PushReturn(r0 []*gitdomain.Tag, r1 error) { + f.PushHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +func (f *UploadsServiceGetListTagsFunc) nextHook() func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetListTagsFunc) appendCall(r0 UploadsServiceGetListTagsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadsServiceGetListTagsFuncCall objects +// describing the invocations of this function. +func (f *UploadsServiceGetListTagsFunc) History() []UploadsServiceGetListTagsFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetListTagsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetListTagsFuncCall is an object that describes an +// invocation of method GetListTags on an instance of MockUploadsService. +type UploadsServiceGetListTagsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 api.RepoName + // Arg2 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg2 []string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []*gitdomain.Tag + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c UploadsServiceGetListTagsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg2 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0, c.Arg1}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetListTagsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// UploadsServiceGetRecentUploadsSummaryFunc describes the behavior when the +// GetRecentUploadsSummary method of the parent MockUploadsService instance +// is invoked. +type UploadsServiceGetRecentUploadsSummaryFunc struct { + defaultHook func(context.Context, int) ([]shared1.UploadsWithRepositoryNamespace, error) + hooks []func(context.Context, int) ([]shared1.UploadsWithRepositoryNamespace, error) + history []UploadsServiceGetRecentUploadsSummaryFuncCall + mutex sync.Mutex +} + +// GetRecentUploadsSummary delegates to the next hook function in the queue +// and stores the parameter and result values of this invocation. +func (m *MockUploadsService) GetRecentUploadsSummary(v0 context.Context, v1 int) ([]shared1.UploadsWithRepositoryNamespace, error) { + r0, r1 := m.GetRecentUploadsSummaryFunc.nextHook()(v0, v1) + m.GetRecentUploadsSummaryFunc.appendCall(UploadsServiceGetRecentUploadsSummaryFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the +// GetRecentUploadsSummary method of the parent MockUploadsService instance +// is invoked and the hook queue is empty. +func (f *UploadsServiceGetRecentUploadsSummaryFunc) SetDefaultHook(hook func(context.Context, int) ([]shared1.UploadsWithRepositoryNamespace, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetRecentUploadsSummary method of the parent MockUploadsService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *UploadsServiceGetRecentUploadsSummaryFunc) PushHook(hook func(context.Context, int) ([]shared1.UploadsWithRepositoryNamespace, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetRecentUploadsSummaryFunc) SetDefaultReturn(r0 []shared1.UploadsWithRepositoryNamespace, r1 error) { + f.SetDefaultHook(func(context.Context, int) ([]shared1.UploadsWithRepositoryNamespace, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetRecentUploadsSummaryFunc) PushReturn(r0 []shared1.UploadsWithRepositoryNamespace, r1 error) { + f.PushHook(func(context.Context, int) ([]shared1.UploadsWithRepositoryNamespace, error) { + return r0, r1 + }) +} + +func (f *UploadsServiceGetRecentUploadsSummaryFunc) nextHook() func(context.Context, int) ([]shared1.UploadsWithRepositoryNamespace, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetRecentUploadsSummaryFunc) appendCall(r0 UploadsServiceGetRecentUploadsSummaryFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// UploadsServiceGetRecentUploadsSummaryFuncCall objects describing the +// invocations of this function. +func (f *UploadsServiceGetRecentUploadsSummaryFunc) History() []UploadsServiceGetRecentUploadsSummaryFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetRecentUploadsSummaryFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetRecentUploadsSummaryFuncCall is an object that describes +// an invocation of method GetRecentUploadsSummary on an instance of +// MockUploadsService. +type UploadsServiceGetRecentUploadsSummaryFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []shared1.UploadsWithRepositoryNamespace + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadsServiceGetRecentUploadsSummaryFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetRecentUploadsSummaryFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// UploadsServiceGetUploadDocumentsForPathFunc describes the behavior when +// the GetUploadDocumentsForPath method of the parent MockUploadsService +// instance is invoked. +type UploadsServiceGetUploadDocumentsForPathFunc struct { + defaultHook func(context.Context, int, string) ([]string, int, error) + hooks []func(context.Context, int, string) ([]string, int, error) + history []UploadsServiceGetUploadDocumentsForPathFuncCall + mutex sync.Mutex +} + +// GetUploadDocumentsForPath delegates to the next hook function in the +// queue and stores the parameter and result values of this invocation. +func (m *MockUploadsService) GetUploadDocumentsForPath(v0 context.Context, v1 int, v2 string) ([]string, int, error) { + r0, r1, r2 := m.GetUploadDocumentsForPathFunc.nextHook()(v0, v1, v2) + m.GetUploadDocumentsForPathFunc.appendCall(UploadsServiceGetUploadDocumentsForPathFuncCall{v0, v1, v2, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the +// GetUploadDocumentsForPath method of the parent MockUploadsService +// instance is invoked and the hook queue is empty. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) SetDefaultHook(hook func(context.Context, int, string) ([]string, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUploadDocumentsForPath method of the parent MockUploadsService +// instance invokes the hook at the front of the queue and discards it. +// After the queue is empty, the default hook function is invoked for any +// future action. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) PushHook(hook func(context.Context, int, string) ([]string, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) SetDefaultReturn(r0 []string, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, int, string) ([]string, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) PushReturn(r0 []string, r1 int, r2 error) { + f.PushHook(func(context.Context, int, string) ([]string, int, error) { + return r0, r1, r2 + }) +} + +func (f *UploadsServiceGetUploadDocumentsForPathFunc) nextHook() func(context.Context, int, string) ([]string, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetUploadDocumentsForPathFunc) appendCall(r0 UploadsServiceGetUploadDocumentsForPathFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// UploadsServiceGetUploadDocumentsForPathFuncCall objects describing the +// invocations of this function. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) History() []UploadsServiceGetUploadDocumentsForPathFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetUploadDocumentsForPathFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetUploadDocumentsForPathFuncCall is an object that +// describes an invocation of method GetUploadDocumentsForPath on an +// instance of MockUploadsService. +type UploadsServiceGetUploadDocumentsForPathFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []string + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadsServiceGetUploadDocumentsForPathFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetUploadDocumentsForPathFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// UploadsServiceGetUploadsFunc describes the behavior when the GetUploads +// method of the parent MockUploadsService instance is invoked. +type UploadsServiceGetUploadsFunc struct { + defaultHook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) + hooks []func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) + history []UploadsServiceGetUploadsFuncCall + mutex sync.Mutex +} + +// GetUploads delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockUploadsService) GetUploads(v0 context.Context, v1 types.GetUploadsOptions) ([]types.Upload, int, error) { + r0, r1, r2 := m.GetUploadsFunc.nextHook()(v0, v1) + m.GetUploadsFunc.appendCall(UploadsServiceGetUploadsFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the GetUploads method of +// the parent MockUploadsService instance is invoked and the hook queue is +// empty. +func (f *UploadsServiceGetUploadsFunc) SetDefaultHook(hook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUploads method of the parent MockUploadsService instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *UploadsServiceGetUploadsFunc) PushHook(hook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetUploadsFunc) SetDefaultReturn(r0 []types.Upload, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetUploadsFunc) PushReturn(r0 []types.Upload, r1 int, r2 error) { + f.PushHook(func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + return r0, r1, r2 + }) +} + +func (f *UploadsServiceGetUploadsFunc) nextHook() func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetUploadsFunc) appendCall(r0 UploadsServiceGetUploadsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadsServiceGetUploadsFuncCall objects +// describing the invocations of this function. +func (f *UploadsServiceGetUploadsFunc) History() []UploadsServiceGetUploadsFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetUploadsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetUploadsFuncCall is an object that describes an +// invocation of method GetUploads on an instance of MockUploadsService. +type UploadsServiceGetUploadsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 types.GetUploadsOptions + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Upload + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadsServiceGetUploadsFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetUploadsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// UploadsServiceGetUploadsByIDsFunc describes the behavior when the +// GetUploadsByIDs method of the parent MockUploadsService instance is +// invoked. +type UploadsServiceGetUploadsByIDsFunc struct { + defaultHook func(context.Context, ...int) ([]types.Upload, error) + hooks []func(context.Context, ...int) ([]types.Upload, error) + history []UploadsServiceGetUploadsByIDsFuncCall + mutex sync.Mutex +} + +// GetUploadsByIDs delegates to the next hook function in the queue and +// stores the parameter and result values of this invocation. +func (m *MockUploadsService) GetUploadsByIDs(v0 context.Context, v1 ...int) ([]types.Upload, error) { + r0, r1 := m.GetUploadsByIDsFunc.nextHook()(v0, v1...) + m.GetUploadsByIDsFunc.appendCall(UploadsServiceGetUploadsByIDsFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetUploadsByIDs +// method of the parent MockUploadsService instance is invoked and the hook +// queue is empty. +func (f *UploadsServiceGetUploadsByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]types.Upload, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUploadsByIDs method of the parent MockUploadsService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *UploadsServiceGetUploadsByIDsFunc) PushHook(hook func(context.Context, ...int) ([]types.Upload, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetUploadsByIDsFunc) SetDefaultReturn(r0 []types.Upload, r1 error) { + f.SetDefaultHook(func(context.Context, ...int) ([]types.Upload, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetUploadsByIDsFunc) PushReturn(r0 []types.Upload, r1 error) { + f.PushHook(func(context.Context, ...int) ([]types.Upload, error) { + return r0, r1 + }) +} + +func (f *UploadsServiceGetUploadsByIDsFunc) nextHook() func(context.Context, ...int) ([]types.Upload, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetUploadsByIDsFunc) appendCall(r0 UploadsServiceGetUploadsByIDsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadsServiceGetUploadsByIDsFuncCall +// objects describing the invocations of this function. +func (f *UploadsServiceGetUploadsByIDsFunc) History() []UploadsServiceGetUploadsByIDsFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetUploadsByIDsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetUploadsByIDsFuncCall is an object that describes an +// invocation of method GetUploadsByIDs on an instance of +// MockUploadsService. +type UploadsServiceGetUploadsByIDsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg1 []int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Upload + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c UploadsServiceGetUploadsByIDsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg1 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetUploadsByIDsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} diff --git a/internal/codeintel/autoindexing/transport/graphql/observability.go b/internal/codeintel/autoindexing/transport/graphql/observability.go index c38566644fb..b5b4f4312f0 100644 --- a/internal/codeintel/autoindexing/transport/graphql/observability.go +++ b/internal/codeintel/autoindexing/transport/graphql/observability.go @@ -9,18 +9,29 @@ import ( type operations struct { // Indexes - getIndexByID *observation.Operation - getIndexesByIDs *observation.Operation getRecentIndexesSummary *observation.Operation getLastIndexScanForRepository *observation.Operation - deleteIndexByID *observation.Operation + deleteLsifIndexes *observation.Operation queueAutoIndexJobsForRepo *observation.Operation + lsifIndexByID *observation.Operation + lsifIndexes *observation.Operation + lsifIndexesByRepo *observation.Operation + indexConfiguration *observation.Operation + updateIndexConfiguration *observation.Operation // Index Configuration - getIndexConfiguration *observation.Operation - updateIndexConfigurationByRepositoryID *observation.Operation - inferedIndexConfiguration *observation.Operation - inferedIndexConfigurationHints *observation.Operation + inferedIndexConfiguration *observation.Operation + inferedIndexConfigurationHints *observation.Operation + + // Language Support + requestLanguageSupport *observation.Operation + requestedLanguageSupport *observation.Operation + setRequestLanguageSupport *observation.Operation + + // Misc + repositorySummary *observation.Operation + getSupportedByCtags *observation.Operation + gitBlobCodeIntelInfo *observation.Operation } func newOperations(observationContext *observation.Context) *operations { @@ -41,17 +52,28 @@ func newOperations(observationContext *observation.Context) *operations { return &operations{ // Indexes - getIndexByID: op("GetIndexByID"), - getIndexesByIDs: op("GetIndexesByIDs"), getRecentIndexesSummary: op("GetRecentIndexesSummary"), getLastIndexScanForRepository: op("GetLastIndexScanForRepository"), - deleteIndexByID: op("DeleteIndexByID"), queueAutoIndexJobsForRepo: op("QueueAutoIndexJobsForRepo"), + deleteLsifIndexes: op("DeleteLsifIndexes"), + lsifIndexByID: op("LsifIndexByID"), + lsifIndexes: op("LsifIndexes"), + lsifIndexesByRepo: op("LsifIndexesByRepo"), + indexConfiguration: op("IndexConfiguration"), + updateIndexConfiguration: op("UpdateIndexConfiguration"), // Index Configuration - getIndexConfiguration: op("IndexConfiguration"), - updateIndexConfigurationByRepositoryID: op("UpdateIndexConfigurationByRepositoryID"), - inferedIndexConfiguration: op("InferedIndexConfiguration"), - inferedIndexConfigurationHints: op("InferedIndexConfigurationHints"), + inferedIndexConfiguration: op("InferedIndexConfiguration"), + inferedIndexConfigurationHints: op("InferedIndexConfigurationHints"), + + // Language Support + requestLanguageSupport: op("RequestLanguageSupport"), + requestedLanguageSupport: op("RequestedLanguageSupport"), + setRequestLanguageSupport: op("SetRequestLanguageSupport"), + + // Misc + repositorySummary: op("RepositorySummary"), + getSupportedByCtags: op("GetSupportedByCtags"), + gitBlobCodeIntelInfo: op("GitBlobCodeIntelInfo"), } } diff --git a/internal/codeintel/autoindexing/transport/graphql/precise_based_support_resolver.go b/internal/codeintel/autoindexing/transport/graphql/precise_based_support_resolver.go new file mode 100644 index 00000000000..829a0253d2a --- /dev/null +++ b/internal/codeintel/autoindexing/transport/graphql/precise_based_support_resolver.go @@ -0,0 +1,58 @@ +package graphql + +import ( + "path" + "strings" + + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" +) + +type PreciseSupportResolver interface { + SupportLevel() string + Indexers() *[]types.CodeIntelIndexerResolver +} + +type preciseCodeIntelSupportType string + +const ( + native preciseCodeIntelSupportType = "NATIVE" + thirdParty preciseCodeIntelSupportType = "THIRD_PARTY" + unknown preciseCodeIntelSupportType = "UNKNOWN" +) + +type preciseCodeIntelSupportResolver struct { + indexers []types.CodeIntelIndexerResolver +} + +func NewPreciseCodeIntelSupportResolver(filepath string) PreciseSupportResolver { + return &preciseCodeIntelSupportResolver{ + indexers: types.LanguageToIndexer[path.Ext(filepath)], + } +} + +func NewPreciseCodeIntelSupportResolverFromIndexers(indexers []types.CodeIntelIndexerResolver) PreciseSupportResolver { + return &preciseCodeIntelSupportResolver{ + indexers: indexers, + } +} + +func (r *preciseCodeIntelSupportResolver) SupportLevel() string { + // if the first indexer in a list is from us, consider native support + nativeRecommendation := len(r.indexers) > 0 && + strings.HasPrefix(r.indexers[0].URL(), "https://github.com/sourcegraph") + + if nativeRecommendation { + return string(native) + } else if len(r.indexers) > 0 { + return string(thirdParty) + } else { + return string(unknown) + } +} + +func (r *preciseCodeIntelSupportResolver) Indexers() *[]types.CodeIntelIndexerResolver { + if len(r.indexers) == 0 { + return nil + } + return &r.indexers +} diff --git a/internal/codeintel/autoindexing/transport/graphql/resolver.go b/internal/codeintel/autoindexing/transport/graphql/resolver.go deleted file mode 100644 index 3dfbb139d75..00000000000 --- a/internal/codeintel/autoindexing/transport/graphql/resolver.go +++ /dev/null @@ -1,161 +0,0 @@ -package graphql - -import ( - "context" - "time" - - "github.com/opentracing/opentracing-go/log" - - "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing" - "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" - "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/lib/codeintel/autoindex/config" -) - -type Resolver interface { - // Indexes - GetIndexByID(ctx context.Context, id int) (shared.Index, bool, error) // simple dbstore - GetIndexesByIDs(ctx context.Context, ids ...int) ([]shared.Index, error) // simple dbstore - GetRecentIndexesSummary(ctx context.Context, repositoryID int) (summaries []shared.IndexesWithRepositoryNamespace, err error) - GetLastIndexScanForRepository(ctx context.Context, repositoryID int) (_ *time.Time, err error) - DeleteIndexByID(ctx context.Context, id int) error // simple dbstore - QueueAutoIndexJobsForRepo(ctx context.Context, repositoryID int, rev, configuration string) ([]shared.Index, error) // in the service QueueIndexes - - // Index Configuration - GetIndexConfiguration(ctx context.Context, repositoryID int) ([]byte, bool, error) // GetIndexConfigurationByRepositoryID - InferedIndexConfiguration(ctx context.Context, repositoryID int, commit string) (*config.IndexConfiguration, bool, error) // in the service InferIndexConfiguration first return - InferedIndexConfigurationHints(ctx context.Context, repositoryID int, commit string) ([]config.IndexJobHint, error) // in the service InferIndexConfiguration second return - UpdateIndexConfigurationByRepositoryID(ctx context.Context, repositoryID int, configuration string) error // simple dbstore - - // Index Connection Factory - IndexConnectionResolverFromFactory(opts shared.GetIndexesOptions) *IndexesResolver // for the resolver -} - -type resolver struct { - svc *autoindexing.Service - operations *operations -} - -func New(svc *autoindexing.Service, observationContext *observation.Context) Resolver { - return &resolver{ - svc: svc, - operations: newOperations(observationContext), - } -} - -func (r *resolver) GetIndexByID(ctx context.Context, id int) (_ shared.Index, _ bool, err error) { - ctx, _, endObservation := r.operations.getIndexByID.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("id", id)}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.GetIndexByID(ctx, id) -} - -func (r *resolver) GetIndexesByIDs(ctx context.Context, ids ...int) (_ []shared.Index, err error) { - ctx, _, endObservation := r.operations.getIndexesByIDs.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("totalIds", len(ids))}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.GetIndexesByIDs(ctx, ids...) -} - -func (r *resolver) GetRecentIndexesSummary(ctx context.Context, repositoryID int) (summaries []shared.IndexesWithRepositoryNamespace, err error) { - ctx, _, endObservation := r.operations.getRecentIndexesSummary.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("repositoryID", repositoryID)}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.GetRecentIndexesSummary(ctx, repositoryID) -} - -func (r *resolver) GetLastIndexScanForRepository(ctx context.Context, repositoryID int) (_ *time.Time, err error) { - ctx, _, endObservation := r.operations.getLastIndexScanForRepository.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("repositoryID", repositoryID)}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.GetLastIndexScanForRepository(ctx, repositoryID) -} - -func (r *resolver) DeleteIndexByID(ctx context.Context, id int) (err error) { - ctx, _, endObservation := r.operations.deleteIndexByID.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("id", id)}, - }) - defer endObservation(1, observation.Args{}) - - _, err = r.svc.DeleteIndexByID(ctx, id) - return err -} - -func (r *resolver) QueueAutoIndexJobsForRepo(ctx context.Context, repositoryID int, rev, configuration string) (_ []shared.Index, err error) { - ctx, _, endObservation := r.operations.queueAutoIndexJobsForRepo.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("repositoryID", repositoryID), log.String("rev", rev), log.String("configuration", configuration)}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.QueueIndexes(ctx, repositoryID, rev, configuration, true, true) -} - -func (r *resolver) GetIndexConfiguration(ctx context.Context, repositoryID int) (_ []byte, _ bool, err error) { - ctx, _, endObservation := r.operations.getIndexConfiguration.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("repositoryID", repositoryID)}, - }) - defer endObservation(1, observation.Args{}) - - configuration, exists, err := r.svc.GetIndexConfigurationByRepositoryID(ctx, repositoryID) - if err != nil { - return nil, false, err - } - if !exists { - return nil, false, nil - } - - return configuration.Data, true, nil -} - -func (r *resolver) InferedIndexConfiguration(ctx context.Context, repositoryID int, commit string) (_ *config.IndexConfiguration, _ bool, err error) { - ctx, _, endObservation := r.operations.inferedIndexConfiguration.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("repositoryID", repositoryID), log.String("commit", commit)}, - }) - defer endObservation(1, observation.Args{}) - - maybeConfig, _, err := r.svc.InferIndexConfiguration(ctx, repositoryID, commit, true) - if err != nil || maybeConfig == nil { - return nil, false, err - } - - return maybeConfig, true, nil -} - -func (r *resolver) InferedIndexConfigurationHints(ctx context.Context, repositoryID int, commit string) (_ []config.IndexJobHint, err error) { - ctx, _, endObservation := r.operations.inferedIndexConfigurationHints.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("repositoryID", repositoryID), log.String("commit", commit)}, - }) - defer endObservation(1, observation.Args{}) - - _, hints, err := r.svc.InferIndexConfiguration(ctx, repositoryID, commit, true) - if err != nil { - return nil, err - } - - return hints, nil -} - -func (r *resolver) UpdateIndexConfigurationByRepositoryID(ctx context.Context, repositoryID int, configuration string) (err error) { - ctx, _, endObservation := r.operations.updateIndexConfigurationByRepositoryID.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("repositoryID", repositoryID), log.String("configuration", configuration)}, - }) - defer endObservation(1, observation.Args{}) - - if _, err := config.UnmarshalJSON([]byte(configuration)); err != nil { - return err - } - - return r.svc.UpdateIndexConfigurationByRepositoryID(ctx, repositoryID, []byte(configuration)) -} - -func (r *resolver) IndexConnectionResolverFromFactory(opts shared.GetIndexesOptions) *IndexesResolver { - return NewIndexesResolver(r.svc, opts) -} diff --git a/internal/codeintel/autoindexing/transport/graphql/root_resolver.go b/internal/codeintel/autoindexing/transport/graphql/root_resolver.go new file mode 100644 index 00000000000..73773a8565f --- /dev/null +++ b/internal/codeintel/autoindexing/transport/graphql/root_resolver.go @@ -0,0 +1,464 @@ +package graphql + +import ( + "context" + "time" + + "github.com/grafana/regexp" + "github.com/graph-gophers/graphql-go" + "github.com/opentracing/opentracing-go/log" + + "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" + "github.com/sourcegraph/sourcegraph/internal/actor" + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" + resolvers "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" + "github.com/sourcegraph/sourcegraph/internal/conf" + "github.com/sourcegraph/sourcegraph/internal/observation" + "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/lib/codeintel/autoindex/config" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +type RootResolver interface { + // Mirrors AutoindexingServiceResolver in graphqlbackend + IndexConfiguration(ctx context.Context, id graphql.ID) (IndexConfigurationResolver, error) // TODO - rename ...ForRepo + DeleteLSIFIndex(ctx context.Context, args *struct{ ID graphql.ID }) (*resolvers.EmptyResponse, error) + LSIFIndexByID(ctx context.Context, id graphql.ID) (_ resolvers.LSIFIndexResolver, err error) + LSIFIndexes(ctx context.Context, args *LSIFIndexesQueryArgs) (resolvers.LSIFIndexConnectionResolver, error) + LSIFIndexesByRepo(ctx context.Context, args *LSIFRepositoryIndexesQueryArgs) (resolvers.LSIFIndexConnectionResolver, error) + QueueAutoIndexJobsForRepo(ctx context.Context, args *QueueAutoIndexJobsForRepoArgs) ([]resolvers.LSIFIndexResolver, error) + UpdateRepositoryIndexConfiguration(ctx context.Context, args *UpdateRepositoryIndexConfigurationArgs) (*resolvers.EmptyResponse, error) + RepositorySummary(ctx context.Context, id graphql.ID) (_ resolvers.CodeIntelRepositorySummaryResolver, err error) + GitBlobCodeIntelInfo(ctx context.Context, args *GitTreeEntryCodeIntelInfoArgs) (_ GitBlobCodeIntelSupportResolver, err error) + GitTreeCodeIntelInfo(ctx context.Context, args *GitTreeEntryCodeIntelInfoArgs) (resolver GitTreeCodeIntelSupportResolver, err error) + RequestLanguageSupport(ctx context.Context, args *RequestLanguageSupportArgs) (_ *sharedresolvers.EmptyResponse, err error) + RequestedLanguageSupport(ctx context.Context) (_ []string, err error) + + // AutoIndexing + GetRecentIndexesSummary(ctx context.Context, repositoryID int) (summaries []shared.IndexesWithRepositoryNamespace, err error) + GetLastIndexScanForRepository(ctx context.Context, repositoryID int) (_ *time.Time, err error) + InferedIndexConfiguration(ctx context.Context, repositoryID int, commit string) (_ *config.IndexConfiguration, _ bool, err error) + InferedIndexConfigurationHints(ctx context.Context, repositoryID int, commit string) (_ []config.IndexJobHint, err error) + + // Symbols client + GetSupportedByCtags(ctx context.Context, filepath string, repoName api.RepoName) (bool, string, error) +} + +type rootResolver struct { + autoindexSvc AutoIndexingService + uploadSvc UploadsService + policySvc PolicyService + operations *operations +} + +func NewRootResolver(autoindexSvc AutoIndexingService, uploadSvc UploadsService, policySvc PolicyService, observationContext *observation.Context) RootResolver { + return &rootResolver{ + autoindexSvc: autoindexSvc, + uploadSvc: uploadSvc, + policySvc: policySvc, + operations: newOperations(observationContext), + } +} + +var ( + autoIndexingEnabled = conf.CodeIntelAutoIndexingEnabled + errAutoIndexingNotEnabled = errors.New("precise code intelligence auto-indexing is not enabled") +) + +// 🚨 SECURITY: Only entrypoint is within the repository resolver so the user is already authenticated +func (r *rootResolver) IndexConfiguration(ctx context.Context, id graphql.ID) (_ IndexConfigurationResolver, err error) { + _, traceErrs, endObservation := r.operations.indexConfiguration.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ + log.String("repoID", string(id)), + }}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + if !autoIndexingEnabled() { + return nil, errAutoIndexingNotEnabled + } + + repositoryID, err := UnmarshalRepositoryID(id) + if err != nil { + return nil, err + } + + return NewIndexConfigurationResolver(r.autoindexSvc, int(repositoryID), traceErrs), nil +} + +// 🚨 SECURITY: Only site admins may modify code intelligence index data +func (r *rootResolver) DeleteLSIFIndex(ctx context.Context, args *struct{ ID graphql.ID }) (_ *resolvers.EmptyResponse, err error) { + ctx, _, endObservation := r.operations.deleteLsifIndexes.With(ctx, &err, observation.Args{LogFields: []log.Field{ + log.String("indexID", string(args.ID)), + }}) + defer endObservation(1, observation.Args{}) + + if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.autoindexSvc.GetUnsafeDB()); err != nil { + return nil, err + } + if !autoIndexingEnabled() { + return nil, errAutoIndexingNotEnabled + } + + indexID, err := unmarshalLSIFIndexGQLID(args.ID) + if err != nil { + return nil, err + } + + if _, err := r.autoindexSvc.DeleteIndexByID(ctx, int(indexID)); err != nil { + return nil, err + } + + return &resolvers.EmptyResponse{}, nil +} + +// 🚨 SECURITY: dbstore layer handles authz for GetIndexByID +func (r *rootResolver) LSIFIndexByID(ctx context.Context, id graphql.ID) (_ resolvers.LSIFIndexResolver, err error) { + if !autoIndexingEnabled() { + return nil, errAutoIndexingNotEnabled + } + + ctx, traceErrs, endObservation := r.operations.lsifIndexByID.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ + log.String("indexID", string(id)), + }}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + indexID, err := unmarshalLSIFIndexGQLID(id) + if err != nil { + return nil, err + } + + // Create a new prefetcher here as we only want to cache upload and index records in + // the same graphQL request, not across different request. + prefetcher := resolvers.NewPrefetcher(r.autoindexSvc, r.uploadSvc) + + index, exists, err := prefetcher.GetIndexByID(ctx, int(indexID)) + if err != nil || !exists { + return nil, err + } + + return resolvers.NewIndexResolver(r.autoindexSvc, r.uploadSvc, r.policySvc, index, prefetcher, traceErrs), nil +} + +type LSIFIndexesQueryArgs struct { + ConnectionArgs + Query *string + State *string + After *string +} + +type LSIFRepositoryIndexesQueryArgs struct { + *LSIFIndexesQueryArgs + RepositoryID graphql.ID +} + +// 🚨 SECURITY: dbstore layer handles authz for GetIndexes +func (r *rootResolver) LSIFIndexes(ctx context.Context, args *LSIFIndexesQueryArgs) (_ resolvers.LSIFIndexConnectionResolver, err error) { + if !autoIndexingEnabled() { + return nil, errAutoIndexingNotEnabled + } + + ctx, _, endObservation := r.operations.lsifIndexes.With(ctx, &err, observation.Args{}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + // Delegate behavior to LSIFIndexesByRepo with no specified repository identifier + return r.LSIFIndexesByRepo(ctx, &LSIFRepositoryIndexesQueryArgs{LSIFIndexesQueryArgs: args}) +} + +// 🚨 SECURITY: dbstore layer handles authz for GetIndexes +func (r *rootResolver) LSIFIndexesByRepo(ctx context.Context, args *LSIFRepositoryIndexesQueryArgs) (_ resolvers.LSIFIndexConnectionResolver, err error) { + if !autoIndexingEnabled() { + return nil, errAutoIndexingNotEnabled + } + + ctx, traceErrs, endObservation := r.operations.lsifIndexesByRepo.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ + log.String("repoID", string(args.RepositoryID)), + }}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + opts, err := makeGetIndexesOptions(args) + if err != nil { + return nil, err + } + + // Create a new prefetcher here as we only want to cache upload and index records in + // the same graphQL request, not across different request. + prefetcher := resolvers.NewPrefetcher(r.autoindexSvc, r.uploadSvc) + + // Create a new indexConnectionResolver here as we only want to index records in + // the same graphQL request, not across different request. + // indexConnectionResolver := r.resolver.AutoIndexingResolver().IndexConnectionResolverFromFactory(opts) + indexConnectionResolver := resolvers.NewIndexesResolver(r.autoindexSvc, opts) + + return resolvers.NewIndexConnectionResolver(r.autoindexSvc, r.uploadSvc, r.policySvc, indexConnectionResolver, prefetcher, traceErrs), nil +} + +type QueueAutoIndexJobsForRepoArgs struct { + Repository graphql.ID + Rev *string + Configuration *string +} + +// 🚨 SECURITY: Only site admins may queue auto-index jobs +func (r *rootResolver) QueueAutoIndexJobsForRepo(ctx context.Context, args *QueueAutoIndexJobsForRepoArgs) (_ []resolvers.LSIFIndexResolver, err error) { + ctx, traceErrs, endObservation := r.operations.queueAutoIndexJobsForRepo.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ + log.String("repoID", string(args.Repository)), + }}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.autoindexSvc.GetUnsafeDB()); err != nil { + return nil, err + } + if !autoIndexingEnabled() { + return nil, errAutoIndexingNotEnabled + } + + repositoryID, err := UnmarshalRepositoryID(args.Repository) + if err != nil { + return nil, err + } + + rev := "HEAD" + if args.Rev != nil { + rev = *args.Rev + } + + configuration := "" + if args.Configuration != nil { + configuration = *args.Configuration + } + + // autoindexingResolver := r.resolver.AutoIndexingResolver() + // indexes, err := r.autoindexSvc.QueueAutoIndexJobsForRepo(ctx, int(repositoryID), rev, configuration) + indexes, err := r.autoindexSvc.QueueIndexes(ctx, int(repositoryID), rev, configuration, true, true) + if err != nil { + return nil, err + } + + // Create a new prefetcher here as we only want to cache upload and index records in + // the same graphQL request, not across different request. + prefetcher := resolvers.NewPrefetcher(r.autoindexSvc, r.uploadSvc) + + lsifIndexResolvers := make([]resolvers.LSIFIndexResolver, 0, len(indexes)) + for i := range indexes { + // index := convertSharedIndexToDBStoreIndex(indexes[i]) + lsifIndexResolvers = append(lsifIndexResolvers, resolvers.NewIndexResolver(r.autoindexSvc, r.uploadSvc, r.policySvc, indexes[i], prefetcher, traceErrs)) + } + + return lsifIndexResolvers, nil +} + +type UpdateRepositoryIndexConfigurationArgs struct { + Repository graphql.ID + Configuration string +} + +// 🚨 SECURITY: Only site admins may modify code intelligence indexing configuration +func (r *rootResolver) UpdateRepositoryIndexConfiguration(ctx context.Context, args *UpdateRepositoryIndexConfigurationArgs) (_ *resolvers.EmptyResponse, err error) { + ctx, _, endObservation := r.operations.updateIndexConfiguration.With(ctx, &err, observation.Args{LogFields: []log.Field{ + log.String("repoID", string(args.Repository)), + }}) + defer endObservation(1, observation.Args{}) + + if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.autoindexSvc.GetUnsafeDB()); err != nil { + return nil, err + } + if !autoIndexingEnabled() { + return nil, errAutoIndexingNotEnabled + } + + repositoryID, err := unmarshalLSIFIndexGQLID(args.Repository) + if err != nil { + return nil, err + } + + if _, err := config.UnmarshalJSON([]byte(args.Configuration)); err != nil { + return nil, err + } + + if err := r.autoindexSvc.UpdateIndexConfigurationByRepositoryID(ctx, int(repositoryID), []byte(args.Configuration)); err != nil { + return nil, err + } + + return &resolvers.EmptyResponse{}, nil +} + +type GitTreeEntryCodeIntelInfoArgs struct { + Repo *types.Repo + Path string + Commit string +} + +func (r *rootResolver) GitBlobCodeIntelInfo(ctx context.Context, args *GitTreeEntryCodeIntelInfoArgs) (_ GitBlobCodeIntelSupportResolver, err error) { + ctx, errTracer, endObservation := r.operations.gitBlobCodeIntelInfo.WithErrors(ctx, &err, observation.Args{}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + return NewCodeIntelSupportResolver(r.autoindexSvc, args.Repo.Name, args.Path, errTracer), nil +} + +func (r *rootResolver) GitTreeCodeIntelInfo(ctx context.Context, args *GitTreeEntryCodeIntelInfoArgs) (resolver GitTreeCodeIntelSupportResolver, err error) { + ctx, errTracer, endObservation := r.operations.gitBlobCodeIntelInfo.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ + log.Int("repoID", int(args.Repo.ID)), + log.String("path", args.Path), + log.String("commit", args.Commit), + }}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + filesRegex, err := regexp.Compile("^" + regexp.QuoteMeta(args.Path) + "[^.]{1}[^/]*$") + if err != nil { + return nil, errors.Wrapf(err, "path '%s' caused invalid regex", args.Path) + } + + files, err := r.autoindexSvc.ListFiles(ctx, int(args.Repo.ID), args.Commit, filesRegex) + if err != nil { + return nil, errors.Wrapf(err, "gitserver.ListFiles: error listing files at %s for repo %d", args.Path, args.Repo.ID) + } + + return NewCodeIntelTreeInfoResolver(r.autoindexSvc, args.Repo, args.Commit, args.Path, files, errTracer), nil +} + +func (r *rootResolver) GetRecentIndexesSummary(ctx context.Context, repositoryID int) (summaries []shared.IndexesWithRepositoryNamespace, err error) { + ctx, _, endObservation := r.operations.getRecentIndexesSummary.With(ctx, &err, observation.Args{ + LogFields: []log.Field{log.Int("repositoryID", repositoryID)}, + }) + defer endObservation(1, observation.Args{}) + + return r.autoindexSvc.GetRecentIndexesSummary(ctx, repositoryID) +} + +func (r *rootResolver) GetLastIndexScanForRepository(ctx context.Context, repositoryID int) (_ *time.Time, err error) { + ctx, _, endObservation := r.operations.getLastIndexScanForRepository.With(ctx, &err, observation.Args{ + LogFields: []log.Field{log.Int("repositoryID", repositoryID)}, + }) + defer endObservation(1, observation.Args{}) + + return r.autoindexSvc.GetLastIndexScanForRepository(ctx, repositoryID) +} + +func (r *rootResolver) InferedIndexConfiguration(ctx context.Context, repositoryID int, commit string) (_ *config.IndexConfiguration, _ bool, err error) { + ctx, _, endObservation := r.operations.inferedIndexConfiguration.With(ctx, &err, observation.Args{ + LogFields: []log.Field{log.Int("repositoryID", repositoryID), log.String("commit", commit)}, + }) + defer endObservation(1, observation.Args{}) + + maybeConfig, _, err := r.autoindexSvc.InferIndexConfiguration(ctx, repositoryID, commit, true) + if err != nil || maybeConfig == nil { + return nil, false, err + } + + return maybeConfig, true, nil +} + +func (r *rootResolver) InferedIndexConfigurationHints(ctx context.Context, repositoryID int, commit string) (_ []config.IndexJobHint, err error) { + ctx, _, endObservation := r.operations.inferedIndexConfigurationHints.With(ctx, &err, observation.Args{ + LogFields: []log.Field{log.Int("repositoryID", repositoryID), log.String("commit", commit)}, + }) + defer endObservation(1, observation.Args{}) + + _, hints, err := r.autoindexSvc.InferIndexConfiguration(ctx, repositoryID, commit, true) + if err != nil { + return nil, err + } + + return hints, nil +} + +func (r *rootResolver) RepositorySummary(ctx context.Context, id graphql.ID) (_ resolvers.CodeIntelRepositorySummaryResolver, err error) { + ctx, errTracer, endObservation := r.operations.repositorySummary.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ + log.String("repoID", string(id)), + }}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + repositoryID, err := UnmarshalRepositoryID(id) + if err != nil { + return nil, err + } + repoID := int(repositoryID) + + // uploadResolver := r.resolver.UploadsResolver() + recentUploads, err := r.uploadSvc.GetRecentUploadsSummary(ctx, repoID) + if err != nil { + return nil, err + } + + lastUploadRetentionScan, err := r.uploadSvc.GetLastUploadRetentionScanForRepository(ctx, repoID) + if err != nil { + return nil, err + } + + // recentIndexes, err := r.resolver.AutoIndexingRootResolver().GetRecentIndexesSummary(ctx, repoID) + recentIndexes, err := r.autoindexSvc.GetRecentIndexesSummary(ctx, repoID) + if err != nil { + return nil, err + } + + // lastIndexScan, err := r.resolver.AutoIndexingRootResolver().GetLastIndexScanForRepository(ctx, repoID) + lastIndexScan, err := r.autoindexSvc.GetLastIndexScanForRepository(ctx, repoID) + if err != nil { + return nil, err + } + + summary := sharedresolvers.RepositorySummary{ + RecentUploads: recentUploads, + RecentIndexes: recentIndexes, + LastUploadRetentionScan: lastUploadRetentionScan, + LastIndexScan: lastIndexScan, + } + + // Create a new prefetcher here as we only want to cache upload and index records in + // the same graphQL request, not across different request. + prefetcher := sharedresolvers.NewPrefetcher(r.autoindexSvc, r.uploadSvc) + + return sharedresolvers.NewRepositorySummaryResolver(r.autoindexSvc, r.uploadSvc, r.policySvc, summary, prefetcher, errTracer), nil +} + +// HERE HERE HERE +func (r *rootResolver) GetSupportedByCtags(ctx context.Context, filepath string, repoName api.RepoName) (_ bool, _ string, err error) { + ctx, _, endObservation := r.operations.getSupportedByCtags.With(ctx, &err, observation.Args{ + LogFields: []log.Field{log.String("repoName", string(repoName))}, + }) + defer endObservation(1, observation.Args{}) + + return r.autoindexSvc.GetSupportedByCtags(ctx, filepath, repoName) +} + +type RequestLanguageSupportArgs struct { + Language string +} + +func (r *rootResolver) RequestLanguageSupport(ctx context.Context, args *RequestLanguageSupportArgs) (_ *sharedresolvers.EmptyResponse, err error) { + ctx, _, endObservation := r.operations.requestLanguageSupport.With(ctx, &err, observation.Args{}) + defer endObservation(1, observation.Args{}) + + userID := int(actor.FromContext(ctx).UID) + if userID == 0 { + return nil, errors.Newf("language support requests only logged for authenticated users") + } + + if err := r.autoindexSvc.SetRequestLanguageSupport(ctx, userID, args.Language); err != nil { + return nil, err + } + + return &sharedresolvers.EmptyResponse{}, nil +} + +func (r *rootResolver) SetRequestLanguageSupport(ctx context.Context, userID int, language string) (err error) { + ctx, _, endObservation := r.operations.setRequestLanguageSupport.With(ctx, &err, observation.Args{ + LogFields: []log.Field{log.Int("userID", userID), log.String("language", language)}, + }) + defer endObservation(1, observation.Args{}) + + return r.autoindexSvc.SetRequestLanguageSupport(ctx, userID, language) +} + +func (r *rootResolver) RequestedLanguageSupport(ctx context.Context) (_ []string, err error) { + ctx, _, endObservation := r.operations.requestedLanguageSupport.With(ctx, &err, observation.Args{}) + defer endObservation(1, observation.Args{}) + + userID := int(actor.FromContext(ctx).UID) + if userID == 0 { + return nil, errors.Newf("language support requests only logged for authenticated users") + } + + return r.autoindexSvc.GetLanguagesRequestedBy(ctx, userID) +} diff --git a/internal/codeintel/autoindexing/transport/graphql/root_resolver_test.go b/internal/codeintel/autoindexing/transport/graphql/root_resolver_test.go new file mode 100644 index 00000000000..036bb64bd1b --- /dev/null +++ b/internal/codeintel/autoindexing/transport/graphql/root_resolver_test.go @@ -0,0 +1,64 @@ +package graphql + +import ( + "context" + "encoding/base64" + "testing" + + "github.com/graph-gophers/graphql-go" + + "github.com/sourcegraph/log/logtest" + + "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" + "github.com/sourcegraph/sourcegraph/internal/database" + "github.com/sourcegraph/sourcegraph/internal/observation" + "github.com/sourcegraph/sourcegraph/internal/types" +) + +func init() { + autoIndexingEnabled = func() bool { return true } +} + +func TestDeleteLSIFIndex(t *testing.T) { + users := database.NewStrictMockUserStore() + users.GetByCurrentAuthUserFunc.SetDefaultReturn(&types.User{SiteAdmin: true}, nil) + + db := database.NewStrictMockDB() + db.UsersFunc.SetDefaultReturn(users) + + id := graphql.ID(base64.StdEncoding.EncodeToString([]byte("LSIFIndex:42"))) + mockUploadsService := NewMockUploadsService() + mockPolicyService := NewMockPolicyService() + mockAutoIndexingService := NewMockAutoIndexingService() + mockAutoIndexingService.GetUnsafeDBFunc.SetDefaultReturn(db) + + rootResolver := NewRootResolver(mockAutoIndexingService, mockUploadsService, mockPolicyService, &observation.TestContext) + + if _, err := rootResolver.DeleteLSIFIndex(context.Background(), &struct{ ID graphql.ID }{id}); err != nil { + t.Fatalf("unexpected error: %s", err) + } + + if len(mockAutoIndexingService.DeleteIndexByIDFunc.History()) != 1 { + t.Fatalf("unexpected call count. want=%d have=%d", 1, len(mockAutoIndexingService.DeleteIndexByIDFunc.History())) + } + if val := mockAutoIndexingService.DeleteIndexByIDFunc.History()[0].Arg1; val != 42 { + t.Fatalf("unexpected upload id. want=%d have=%d", 42, val) + } +} + +func TestDeleteLSIFIndexUnauthenticated(t *testing.T) { + logger := logtest.Scoped(t) + db := database.NewDB(logger, nil) + + id := graphql.ID(base64.StdEncoding.EncodeToString([]byte("LSIFIndex:42"))) + mockUploadsService := NewMockUploadsService() + mockPolicyService := NewMockPolicyService() + mockAutoIndexingService := NewMockAutoIndexingService() + mockAutoIndexingService.GetUnsafeDBFunc.SetDefaultReturn(db) + + rootResolver := NewRootResolver(mockAutoIndexingService, mockUploadsService, mockPolicyService, &observation.TestContext) + + if _, err := rootResolver.DeleteLSIFIndex(context.Background(), &struct{ ID graphql.ID }{id}); err != backend.ErrNotAuthenticated { + t.Errorf("unexpected error. want=%q have=%q", backend.ErrNotAuthenticated, err) + } +} diff --git a/internal/codeintel/autoindexing/transport/graphql/search_based_support_resolver.go b/internal/codeintel/autoindexing/transport/graphql/search_based_support_resolver.go new file mode 100644 index 00000000000..9255b0c556e --- /dev/null +++ b/internal/codeintel/autoindexing/transport/graphql/search_based_support_resolver.go @@ -0,0 +1,32 @@ +package graphql + +type SearchBasedSupportResolver interface { + SupportLevel() string + Language() string +} + +type searchBasedCodeIntelSupportType string + +const ( + unsupported searchBasedCodeIntelSupportType = "UNSUPPORTED" + basic searchBasedCodeIntelSupportType = "BASIC" +) + +type searchBasedSupportResolver struct { + language string +} + +func NewSearchBasedCodeIntelResolver(language string) SearchBasedSupportResolver { + return &searchBasedSupportResolver{language} +} + +func (r *searchBasedSupportResolver) SupportLevel() string { + if r.language != "" { + return string(basic) + } + return string(unsupported) +} + +func (r *searchBasedSupportResolver) Language() string { + return r.language +} diff --git a/internal/codeintel/autoindexing/transport/graphql/utils.go b/internal/codeintel/autoindexing/transport/graphql/utils.go new file mode 100644 index 00000000000..2bf03ab870b --- /dev/null +++ b/internal/codeintel/autoindexing/transport/graphql/utils.go @@ -0,0 +1,222 @@ +package graphql + +import ( + "encoding/base64" + "encoding/json" + "strconv" + "strings" + "time" + + "github.com/graph-gophers/graphql-go" + "github.com/graph-gophers/graphql-go/relay" + + "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// strPtr creates a pointer to the given value. If the value is an +// empty string, a nil pointer is returned. +func strPtr(val string) *string { + if val == "" { + return nil + } + + return &val +} + +// DateTime implements the DateTime GraphQL scalar type. +type DateTime struct{ time.Time } + +// DateTimeOrNil is a helper function that returns nil for time == nil and otherwise wraps time in +// DateTime. +func DateTimeOrNil(time *time.Time) *DateTime { + if time == nil { + return nil + } + return &DateTime{Time: *time} +} + +func (DateTime) ImplementsGraphQLType(name string) bool { + return name == "DateTime" +} + +func (v DateTime) MarshalJSON() ([]byte, error) { + return json.Marshal(v.Time.Format(time.RFC3339)) +} + +func (v *DateTime) UnmarshalGraphQL(input any) error { + s, ok := input.(string) + if !ok { + return errors.Errorf("invalid GraphQL DateTime scalar value input (got %T, expected string)", input) + } + t, err := time.Parse(time.RFC3339, s) + if err != nil { + return err + } + *v = DateTime{Time: t} + return nil +} + +func marshalLSIFIndexGQLID(indexID int64) graphql.ID { + return relay.MarshalID("LSIFIndex", indexID) +} + +func unmarshalLSIFIndexGQLID(id graphql.ID) (indexID int64, err error) { + err = relay.UnmarshalSpec(id, &indexID) + return indexID, err +} + +// ConnectionArgs is the common set of arguments to GraphQL fields that return connections (lists). +type ConnectionArgs struct { + First *int32 // return the first n items +} + +const DefaultIndexPageSize = 50 + +// makeGetIndexesOptions translates the given GraphQL arguments into options defined by the +// store.GetIndexes operations. +func makeGetIndexesOptions(args *LSIFRepositoryIndexesQueryArgs) (types.GetIndexesOptions, error) { + repositoryID, err := resolveRepositoryID(args.RepositoryID) + if err != nil { + return types.GetIndexesOptions{}, err + } + + offset, err := graphqlutil.DecodeIntCursor(args.After) + if err != nil { + return types.GetIndexesOptions{}, err + } + + return types.GetIndexesOptions{ + RepositoryID: repositoryID, + State: strings.ToLower(derefString(args.State, "")), + Term: derefString(args.Query, ""), + Limit: derefInt32(args.First, DefaultIndexPageSize), + Offset: offset, + }, nil +} + +// resolveRepositoryByID gets a repository's internal identifier from a GraphQL identifier. +func resolveRepositoryID(id graphql.ID) (int, error) { + if id == "" { + return 0, nil + } + + repoID, err := UnmarshalRepositoryID(id) + if err != nil { + return 0, err + } + + return int(repoID), nil +} + +func UnmarshalRepositoryID(id graphql.ID) (repo api.RepoID, err error) { + err = relay.UnmarshalSpec(id, &repo) + return +} + +// EncodeIntCursor creates a PageInfo object from the given new offset value. If the +// new offset value, then an object indicating the end of the result set is returned. +// The cursor is base64 encoded for transfer, and should be decoded using the function +// decodeIntCursor. +func EncodeIntCursor(val *int32) *PageInfo { + if val == nil { + return EncodeCursor(nil) + } + + str := strconv.FormatInt(int64(*val), 10) + return EncodeCursor(&str) +} + +// DecodeIntCursor decodes the given integer cursor value. It is assumed to be a value +// previously returned from the function encodeIntCursor. The zero value is returned if +// no cursor is supplied. Invalid cursors return errors. +func DecodeIntCursor(val *string) (int, error) { + cursor, err := DecodeCursor(val) + if err != nil || cursor == "" { + return 0, err + } + + return strconv.Atoi(cursor) +} + +// DecodeCursor decodes the given cursor value. It is assumed to be a value previously +// returned from the function encodeCursor. An empty string is returned if no cursor is +// supplied. Invalid cursors return errors. +func DecodeCursor(val *string) (string, error) { + if val == nil { + return "", nil + } + + decoded, err := base64.StdEncoding.DecodeString(*val) + if err != nil { + return "", err + } + + return string(decoded), nil +} + +// toInt32 translates the given int pointer into an int32 pointer. +func toInt32(val *int) *int32 { + if val == nil { + return nil + } + + v := int32(*val) + return &v +} + +// derefString returns the underlying value in the given pointer. +// If the pointer is nil, the default value is returned. +func derefString(val *string, defaultValue string) string { + if val != nil { + return *val + } + return defaultValue +} + +// derefInt32 returns the underlying value in the given pointer. +// If the pointer is nil, the default value is returned. +func derefInt32(val *int32, defaultValue int) int { + if val != nil { + return int(*val) + } + return defaultValue +} + +// intPtr creates a pointer to the given value. +func intPtr(val int32) *int32 { + return &val +} + +// PageInfo implements the GraphQL type PageInfo. +type PageInfo struct { + endCursor *string + hasNextPage bool +} + +// HasNextPage returns a new PageInfo with the given hasNextPage value. +func HasNextPage(hasNextPage bool) *PageInfo { + return &PageInfo{hasNextPage: hasNextPage} +} + +// NextPageCursor returns a new PageInfo indicating there is a next page with +// the given end cursor. +func NextPageCursor(endCursor string) *PageInfo { + return &PageInfo{endCursor: &endCursor, hasNextPage: true} +} + +func (r *PageInfo) EndCursor() *string { return r.endCursor } +func (r *PageInfo) HasNextPage() bool { return r.hasNextPage } + +// EncodeCursor creates a PageInfo object from the given cursor. If the cursor is not +// defined, then an object indicating the end of the result set is returned. The cursor +// is base64 encoded for transfer, and should be decoded using the function decodeCursor. +func EncodeCursor(val *string) *PageInfo { + if val != nil { + return NextPageCursor(base64.StdEncoding.EncodeToString([]byte(*val))) + } + + return HasNextPage(false) +} diff --git a/internal/codeintel/autoindexing/transport/graphql/utils_test.go b/internal/codeintel/autoindexing/transport/graphql/utils_test.go new file mode 100644 index 00000000000..d2ec1f945aa --- /dev/null +++ b/internal/codeintel/autoindexing/transport/graphql/utils_test.go @@ -0,0 +1,174 @@ +package graphql + +import ( + "encoding/base64" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/graph-gophers/graphql-go" + + codeinteltypes "github.com/sourcegraph/sourcegraph/internal/codeintel/types" +) + +func TestMakeGetIndexesOptions(t *testing.T) { + opts, err := makeGetIndexesOptions(&LSIFRepositoryIndexesQueryArgs{ + LSIFIndexesQueryArgs: &LSIFIndexesQueryArgs{ + ConnectionArgs: ConnectionArgs{ + First: intPtr(5), + }, + Query: strPtr("q"), + State: strPtr("s"), + After: EncodeIntCursor(intPtr(25)).EndCursor(), + }, + RepositoryID: graphql.ID(base64.StdEncoding.EncodeToString([]byte("Repo:50"))), + }) + if err != nil { + t.Fatalf("unexpected error making options: %s", err) + } + + expected := codeinteltypes.GetIndexesOptions{ + RepositoryID: 50, + State: "s", + Term: "q", + Limit: 5, + Offset: 25, + } + if diff := cmp.Diff(expected, opts); diff != "" { + t.Errorf("unexpected opts (-want +got):\n%s", diff) + } +} + +func TestMakeGetIndexesOptionsDefaults(t *testing.T) { + opts, err := makeGetIndexesOptions(&LSIFRepositoryIndexesQueryArgs{ + LSIFIndexesQueryArgs: &LSIFIndexesQueryArgs{}, + }) + if err != nil { + t.Fatalf("unexpected error making options: %s", err) + } + + expected := codeinteltypes.GetIndexesOptions{ + RepositoryID: 0, + State: "", + Term: "", + Limit: DefaultIndexPageSize, + Offset: 0, + } + if diff := cmp.Diff(expected, opts); diff != "" { + t.Errorf("unexpected opts (-want +got):\n%s", diff) + } +} + +func TestCursor(t *testing.T) { + expected := "test" + pageInfo := EncodeCursor(&expected) + + if !pageInfo.HasNextPage() { + t.Fatalf("expected next page") + } + if pageInfo.EndCursor() == nil { + t.Fatalf("unexpected nil cursor") + } + + value, err := DecodeCursor(pageInfo.EndCursor()) + if err != nil { + t.Fatalf("unexpected error decoding cursor: %s", err) + } + if value != expected { + t.Errorf("unexpected decoded cursor. want=%s have=%s", expected, value) + } +} + +func TestCursorEmpty(t *testing.T) { + pageInfo := EncodeCursor(nil) + + if pageInfo.HasNextPage() { + t.Errorf("unexpected next page") + } + if pageInfo.EndCursor() != nil { + t.Errorf("unexpected encoded cursor: %s", *pageInfo.EndCursor()) + } + + value, err := DecodeCursor(nil) + if err != nil { + t.Fatalf("unexpected error decoding cursor: %s", err) + } + if value != "" { + t.Errorf("unexpected decoded cursor: %s", value) + } +} + +func TestIntCursor(t *testing.T) { + expected := 42 + pageInfo := EncodeIntCursor(toInt32(&expected)) + + if !pageInfo.HasNextPage() { + t.Fatalf("expected next page") + } + if pageInfo.EndCursor() == nil { + t.Fatalf("unexpected nil cursor") + } + + value, err := DecodeIntCursor(pageInfo.EndCursor()) + if err != nil { + t.Fatalf("unexpected error decoding cursor: %s", err) + } + if value != expected { + t.Errorf("unexpected decoded cursor. want=%d have=%d", expected, value) + } +} + +func TestIntCursorEmpty(t *testing.T) { + pageInfo := EncodeIntCursor(nil) + + if pageInfo.HasNextPage() { + t.Errorf("unexpected next page") + } + if pageInfo.EndCursor() != nil { + t.Errorf("unexpected encoded cursor: %s", *pageInfo.EndCursor()) + } + + value, err := DecodeIntCursor(nil) + if err != nil { + t.Fatalf("unexpected error decoding cursor: %s", err) + } + if value != 0 { + t.Errorf("unexpected decoded cursor: %d", value) + } +} + +func TestIndexID(t *testing.T) { + expected := int64(42) + value, err := unmarshalLSIFIndexGQLID(marshalLSIFIndexGQLID(expected)) + if err != nil { + t.Fatalf("unexpected error marshalling id: %s", err) + } + if value != expected { + t.Errorf("unexpected id. have=%d want=%d", expected, value) + } +} + +func TestDerefInt32(t *testing.T) { + expected := 42 + expected32 := int32(expected) + + if val := derefInt32(nil, expected); val != expected { + t.Errorf("unexpected value. want=%d have=%d", expected, val) + } + if val := derefInt32(&expected32, expected); val != expected { + t.Errorf("unexpected value. want=%d have=%d", expected, val) + } +} + +func TestDerefString(t *testing.T) { + expected := "foo" + + if val := derefString(nil, expected); val != expected { + t.Errorf("unexpected value. want=%s have=%s", expected, val) + } + if val := derefString(&expected, ""); val != expected { + t.Errorf("unexpected value. want=%s have=%s", expected, val) + } + if val := derefString(&expected, expected); val != expected { + t.Errorf("unexpected value. want=%s have=%s", expected, val) + } +} diff --git a/internal/codeintel/codenav/gittree_translator.go b/internal/codeintel/codenav/gittree_translator.go index 1fe0c04464b..936119cfe4d 100644 --- a/internal/codeintel/codenav/gittree_translator.go +++ b/internal/codeintel/codenav/gittree_translator.go @@ -10,7 +10,8 @@ import ( "github.com/sourcegraph/sourcegraph/internal/authz" "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" - "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + sgtypes "github.com/sourcegraph/sourcegraph/internal/types" ) // GitTreeTranslator translates a position within a git tree at a source commit into the @@ -26,14 +27,14 @@ type GitTreeTranslator interface { // target commit. The target commit's path and position are returned, along with a boolean flag // indicating that the translation was successful. If revese is true, then the source and // target commits are swapped. - GetTargetCommitPositionFromSourcePosition(ctx context.Context, commit string, px shared.Position, reverse bool) (string, shared.Position, bool, error) + GetTargetCommitPositionFromSourcePosition(ctx context.Context, commit string, px types.Position, reverse bool) (string, types.Position, bool, error) // AdjustPosition // GetTargetCommitRangeFromSourceRange translates the given range from the source commit into the given target // commit. The target commit's path and range are returned, along with a boolean flag indicating // that the translation was successful. If revese is true, then the source and target commits // are swapped. - GetTargetCommitRangeFromSourceRange(ctx context.Context, commit, path string, rx shared.Range, reverse bool) (string, shared.Range, bool, error) + GetTargetCommitRangeFromSourceRange(ctx context.Context, commit, path string, rx types.Range, reverse bool) (string, types.Range, bool, error) } type gitTreeTranslator struct { @@ -43,7 +44,7 @@ type gitTreeTranslator struct { } type requestArgs struct { - repo *types.Repo + repo *sgtypes.Repo commit string path string } @@ -92,10 +93,10 @@ func (g *gitTreeTranslator) GetTargetCommitPathFromSourcePath(ctx context.Contex // indicating that the translation was successful. If revese is true, then the source and // target commits are swapped. // TODO: No todo just letting me know that I updated path just on this one. Need to do it like that. -func (g *gitTreeTranslator) GetTargetCommitPositionFromSourcePosition(ctx context.Context, commit string, px shared.Position, reverse bool) (string, shared.Position, bool, error) { +func (g *gitTreeTranslator) GetTargetCommitPositionFromSourcePosition(ctx context.Context, commit string, px types.Position, reverse bool) (string, types.Position, bool, error) { hunks, err := g.readCachedHunks(ctx, g.localRequestArgs.repo, g.localRequestArgs.commit, commit, g.localRequestArgs.path, reverse) if err != nil { - return "", shared.Position{}, false, err + return "", types.Position{}, false, err } commitPosition, ok := translatePosition(hunks, px) @@ -106,10 +107,10 @@ func (g *gitTreeTranslator) GetTargetCommitPositionFromSourcePosition(ctx contex // commit. The target commit path and range are returned, along with a boolean flag indicating // that the translation was successful. If revese is true, then the source and target commits // are swapped. -func (g *gitTreeTranslator) GetTargetCommitRangeFromSourceRange(ctx context.Context, commit, path string, rx shared.Range, reverse bool) (string, shared.Range, bool, error) { +func (g *gitTreeTranslator) GetTargetCommitRangeFromSourceRange(ctx context.Context, commit, path string, rx types.Range, reverse bool) (string, types.Range, bool, error) { hunks, err := g.readCachedHunks(ctx, g.localRequestArgs.repo, g.localRequestArgs.commit, commit, path, reverse) if err != nil { - return "", shared.Range{}, false, err + return "", types.Range{}, false, err } commitRange, ok := translateRange(hunks, rx) @@ -121,7 +122,7 @@ func (g *gitTreeTranslator) GetTargetCommitRangeFromSourceRange(ctx context.Cont // source and target commits are swapped. If the git tree translator has a hunk cache, it // will read from it before attempting to contact a remote server, and populate the cache // with new results -func (g *gitTreeTranslator) readCachedHunks(ctx context.Context, repo *types.Repo, sourceCommit, targetCommit, path string, reverse bool) ([]*diff.Hunk, error) { +func (g *gitTreeTranslator) readCachedHunks(ctx context.Context, repo *sgtypes.Repo, sourceCommit, targetCommit, path string, reverse bool) ([]*diff.Hunk, error) { if sourceCommit == targetCommit { return nil, nil } @@ -154,7 +155,7 @@ func (g *gitTreeTranslator) readCachedHunks(ctx context.Context, repo *types.Rep // readHunks returns a position-ordered slice of changes (additions or deletions) of // the given path between the given source and target commits. -func (g *gitTreeTranslator) readHunks(ctx context.Context, repo *types.Repo, sourceCommit, targetCommit, path string) ([]*diff.Hunk, error) { +func (g *gitTreeTranslator) readHunks(ctx context.Context, repo *sgtypes.Repo, sourceCommit, targetCommit, path string) ([]*diff.Hunk, error) { return g.client.DiffPath(ctx, authz.DefaultSubRepoPermsChecker, repo.Name, sourceCommit, targetCommit, path) } @@ -174,31 +175,31 @@ func findHunk(hunks []*diff.Hunk, line int) *diff.Hunk { // translateRange translates the given range by calling translatePosition on both of the range's // endpoints. This function returns a boolean flag indicating that the translation was // successful (which occurs when both endpoints of the range can be translated). -func translateRange(hunks []*diff.Hunk, r shared.Range) (shared.Range, bool) { +func translateRange(hunks []*diff.Hunk, r types.Range) (types.Range, bool) { start, ok := translatePosition(hunks, r.Start) if !ok { - return shared.Range{}, false + return types.Range{}, false } end, ok := translatePosition(hunks, r.End) if !ok { - return shared.Range{}, false + return types.Range{}, false } - return shared.Range{Start: start, End: end}, true + return types.Range{Start: start, End: end}, true } // translatePosition translates the given position by setting the line number based on the // number of additions and deletions that occur before that line. This function returns a // boolean flag indicating that the translation is successful. A translation fails when the // line indicated by the position has been edited. -func translatePosition(hunks []*diff.Hunk, pos shared.Position) (shared.Position, bool) { +func translatePosition(hunks []*diff.Hunk, pos types.Position) (types.Position, bool) { line, ok := translateLineNumbers(hunks, pos.Line) if !ok { - return shared.Position{}, false + return types.Position{}, false } - return shared.Position{Line: line, Character: pos.Character}, true + return types.Position{Line: line, Character: pos.Character}, true } // translateLineNumbers translates the given line number based on the number of additions and deletions diff --git a/internal/codeintel/codenav/gittree_translator_test.go b/internal/codeintel/codenav/gittree_translator_test.go index 05082e9d99f..eaffdf32c65 100644 --- a/internal/codeintel/codenav/gittree_translator_test.go +++ b/internal/codeintel/codenav/gittree_translator_test.go @@ -10,19 +10,19 @@ import ( "github.com/google/go-cmp/cmp" "github.com/sourcegraph/go-diff/diff" - "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" codeintelgitserver "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/gitserver" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/gitserver" "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/internal/types" + sgtypes "github.com/sourcegraph/sourcegraph/internal/types" ) var client = codeintelgitserver.New(database.NewMockDB(), NewMockDBStore(), &observation.TestContext) func TestGetTargetCommitPathFromSourcePath(t *testing.T) { args := &requestArgs{ - repo: &types.Repo{ID: 50}, + repo: &sgtypes.Repo{ID: 50}, commit: "deadbeef1", path: "/foo/bar.go", } @@ -53,10 +53,10 @@ func TestGetTargetCommitPositionFromSourcePosition(t *testing.T) { return io.NopCloser(bytes.NewReader([]byte(hugoDiff))), nil } - posIn := shared.Position{Line: 302, Character: 15} + posIn := types.Position{Line: 302, Character: 15} args := &requestArgs{ - repo: &types.Repo{ID: 50}, + repo: &sgtypes.Repo{ID: 50}, commit: "deadbeef1", path: "/foo/bar.go", } @@ -73,7 +73,7 @@ func TestGetTargetCommitPositionFromSourcePosition(t *testing.T) { t.Errorf("unexpected path. want=%s have=%s", "/foo/bar.go", path) } - expectedPos := shared.Position{Line: 294, Character: 15} + expectedPos := types.Position{Line: 294, Character: 15} if diff := cmp.Diff(expectedPos, posOut); diff != "" { t.Errorf("unexpected position (-want +got):\n%s", diff) } @@ -87,10 +87,10 @@ func TestGetTargetCommitPositionFromSourcePositionEmptyDiff(t *testing.T) { return io.NopCloser(bytes.NewReader(nil)), nil } - posIn := shared.Position{Line: 10, Character: 15} + posIn := types.Position{Line: 10, Character: 15} args := &requestArgs{ - repo: &types.Repo{ID: 50}, + repo: &sgtypes.Repo{ID: 50}, commit: "deadbeef1", path: "/foo/bar.go", } @@ -124,10 +124,10 @@ func TestGetTargetCommitPositionFromSourcePositionReverse(t *testing.T) { return io.NopCloser(bytes.NewReader([]byte(hugoDiff))), nil } - posIn := shared.Position{Line: 302, Character: 15} + posIn := types.Position{Line: 302, Character: 15} args := &requestArgs{ - repo: &types.Repo{ID: 50}, + repo: &sgtypes.Repo{ID: 50}, commit: "deadbeef1", path: "/foo/bar.go", } @@ -144,7 +144,7 @@ func TestGetTargetCommitPositionFromSourcePositionReverse(t *testing.T) { t.Errorf("unexpected path. want=%s have=%s", "/foo/bar.go", path) } - expectedPos := shared.Position{Line: 294, Character: 15} + expectedPos := types.Position{Line: 294, Character: 15} if diff := cmp.Diff(expectedPos, posOut); diff != "" { t.Errorf("unexpected position (-want +got):\n%s", diff) } @@ -163,13 +163,13 @@ func TestGetTargetCommitRangeFromSourceRange(t *testing.T) { return io.NopCloser(bytes.NewReader([]byte(hugoDiff))), nil } - rIn := shared.Range{ - Start: shared.Position{Line: 302, Character: 15}, - End: shared.Position{Line: 305, Character: 20}, + rIn := types.Range{ + Start: types.Position{Line: 302, Character: 15}, + End: types.Position{Line: 305, Character: 20}, } args := &requestArgs{ - repo: &types.Repo{ID: 50}, + repo: &sgtypes.Repo{ID: 50}, commit: "deadbeef1", path: "/foo/bar.go", } @@ -186,9 +186,9 @@ func TestGetTargetCommitRangeFromSourceRange(t *testing.T) { t.Errorf("unexpected path. want=%s have=%s", "/foo/bar.go", path) } - expectedRange := shared.Range{ - Start: shared.Position{Line: 294, Character: 15}, - End: shared.Position{Line: 297, Character: 20}, + expectedRange := types.Range{ + Start: types.Position{Line: 294, Character: 15}, + End: types.Position{Line: 297, Character: 20}, } if diff := cmp.Diff(expectedRange, rOut); diff != "" { t.Errorf("unexpected position (-want +got):\n%s", diff) @@ -203,13 +203,13 @@ func TestGetTargetCommitRangeFromSourceRangeEmptyDiff(t *testing.T) { return io.NopCloser(bytes.NewReader(nil)), nil } - rIn := shared.Range{ - Start: shared.Position{Line: 302, Character: 15}, - End: shared.Position{Line: 305, Character: 20}, + rIn := types.Range{ + Start: types.Position{Line: 302, Character: 15}, + End: types.Position{Line: 305, Character: 20}, } args := &requestArgs{ - repo: &types.Repo{ID: 50}, + repo: &sgtypes.Repo{ID: 50}, commit: "deadbeef1", path: "/foo/bar.go", } @@ -243,13 +243,13 @@ func TestGetTargetCommitRangeFromSourceRangeReverse(t *testing.T) { return io.NopCloser(bytes.NewReader([]byte(hugoDiff))), nil } - rIn := shared.Range{ - Start: shared.Position{Line: 302, Character: 15}, - End: shared.Position{Line: 305, Character: 20}, + rIn := types.Range{ + Start: types.Position{Line: 302, Character: 15}, + End: types.Position{Line: 305, Character: 20}, } args := &requestArgs{ - repo: &types.Repo{ID: 50}, + repo: &sgtypes.Repo{ID: 50}, commit: "deadbeef1", path: "/foo/bar.go", } @@ -266,9 +266,9 @@ func TestGetTargetCommitRangeFromSourceRangeReverse(t *testing.T) { t.Errorf("unexpected path. want=%s have=%s", "/foo/bar.go", path) } - expectedRange := shared.Range{ - Start: shared.Position{Line: 294, Character: 15}, - End: shared.Position{Line: 297, Character: 20}, + expectedRange := types.Range{ + Start: types.Position{Line: 294, Character: 15}, + End: types.Position{Line: 297, Character: 20}, } if diff := cmp.Diff(expectedRange, rOut); diff != "" { t.Errorf("unexpected position (-want +got):\n%s", diff) @@ -399,7 +399,7 @@ func TestRawGetTargetCommitPositionFromSourcePosition(t *testing.T) { } hunks := diff.Hunks - pos := shared.Position{ + pos := types.Position{ Line: testCase.line - 1, // 1-index -> 0-index Character: 10, } diff --git a/internal/codeintel/codenav/iface.go b/internal/codeintel/codenav/iface.go index 1d7242cdec0..46ca39acfd5 100644 --- a/internal/codeintel/codenav/iface.go +++ b/internal/codeintel/codenav/iface.go @@ -8,15 +8,15 @@ import ( "github.com/sourcegraph/sourcegraph/internal/api" "github.com/sourcegraph/sourcegraph/internal/authz" "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/gitserver" - uploads "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" ) type UploadService interface { - GetDumpsWithDefinitionsForMonikers(ctx context.Context, monikers []precise.QualifiedMonikerData) (_ []uploads.Dump, err error) + GetDumpsWithDefinitionsForMonikers(ctx context.Context, monikers []precise.QualifiedMonikerData) (_ []types.Dump, err error) GetUploadIDsWithReferences(ctx context.Context, orderedMonikers []precise.QualifiedMonikerData, ignoreIDs []int, repositoryID int, commit string, limit int, offset int) (ids []int, recordsScanned int, totalCount int, err error) - GetDumpsByIDs(ctx context.Context, ids []int) (_ []uploads.Dump, err error) - InferClosestUploads(ctx context.Context, repositoryID int, commit, path string, exactPath bool, indexer string) (_ []uploads.Dump, err error) + GetDumpsByIDs(ctx context.Context, ids []int) (_ []types.Dump, err error) + InferClosestUploads(ctx context.Context, repositoryID int, commit, path string, exactPath bool, indexer string) (_ []types.Dump, err error) } type GitserverClient interface { diff --git a/internal/codeintel/codenav/init.go b/internal/codeintel/codenav/init.go index d79ef314f59..31da33e63e7 100644 --- a/internal/codeintel/codenav/init.go +++ b/internal/codeintel/codenav/init.go @@ -12,7 +12,6 @@ import ( "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/internal/store" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/internal/symbols" "github.com/sourcegraph/sourcegraph/internal/trace" ) @@ -23,7 +22,7 @@ var ( // GetService creates or returns an already-initialized symbols service. If the service is // new, it will use the given database handle. -func GetService(db, codeIntelDB database.DB, uploadSvc UploadService, gitserver GitserverClient, symbolsClient *symbols.Client) *Service { +func GetService(db, codeIntelDB database.DB, uploadSvc UploadService, gitserver GitserverClient) *Service { svcOnce.Do(func() { oc := func(name string) *observation.Context { return &observation.Context{ @@ -35,7 +34,7 @@ func GetService(db, codeIntelDB database.DB, uploadSvc UploadService, gitserver store := store.New(db, oc("store")) lsifstore := lsifstore.New(codeIntelDB, oc("lsifstore")) - svc = newService(store, lsifstore, uploadSvc, gitserver, symbolsClient, oc("service")) + svc = newService(store, lsifstore, uploadSvc, gitserver, oc("service")) }) return svc diff --git a/internal/codeintel/codenav/internal/lsifstore/lsifstore.go b/internal/codeintel/codenav/internal/lsifstore/lsifstore.go index 55200d926da..d1ac3fa70d0 100644 --- a/internal/codeintel/codenav/internal/lsifstore/lsifstore.go +++ b/internal/codeintel/codenav/internal/lsifstore/lsifstore.go @@ -4,6 +4,7 @@ import ( "context" "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/observation" @@ -12,7 +13,7 @@ import ( type LsifStore interface { // Hover - GetHover(ctx context.Context, bundleID int, path string, line, character int) (string, shared.Range, bool, error) + GetHover(ctx context.Context, bundleID int, path string, line, character int) (string, types.Range, bool, error) // References GetReferenceLocations(ctx context.Context, uploadID int, path string, line, character, limit, offset int) (_ []shared.Location, _ int, err error) @@ -34,7 +35,7 @@ type LsifStore interface { GetDiagnostics(ctx context.Context, bundleID int, prefix string, limit, offset int) (_ []shared.Diagnostic, _ int, err error) // Stencil - GetStencil(ctx context.Context, bundleID int, path string) (_ []shared.Range, err error) + GetStencil(ctx context.Context, bundleID int, path string) (_ []types.Range, err error) // Ranges GetRanges(ctx context.Context, bundleID int, path string, startLine, endLine int) (_ []shared.CodeIntelligenceRange, err error) diff --git a/internal/codeintel/codenav/internal/lsifstore/lsifstore_hover.go b/internal/codeintel/codenav/internal/lsifstore/lsifstore_hover.go index 01fdedb5aac..0c90632a7d2 100644 --- a/internal/codeintel/codenav/internal/lsifstore/lsifstore_hover.go +++ b/internal/codeintel/codenav/internal/lsifstore/lsifstore_hover.go @@ -6,13 +6,13 @@ import ( "github.com/keegancsmith/sqlf" "github.com/opentracing/opentracing-go/log" - "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" ) // GetHover returns the hover text of the symbol at the given position. -func (s *store) GetHover(ctx context.Context, bundleID int, path string, line, character int) (_ string, _ shared.Range, _ bool, err error) { +func (s *store) GetHover(ctx context.Context, bundleID int, path string, line, character int) (_ string, _ types.Range, _ bool, err error) { ctx, trace, endObservation := s.operations.getHover.With(ctx, &err, observation.Args{LogFields: []log.Field{ log.Int("bundleID", bundleID), log.String("path", path), @@ -23,7 +23,7 @@ func (s *store) GetHover(ctx context.Context, bundleID int, path string, line, c documentData, exists, err := s.scanFirstDocumentData(s.db.Query(ctx, sqlf.Sprintf(hoverDocumentQuery, bundleID, path))) if err != nil || !exists { - return "", shared.Range{}, false, err + return "", types.Range{}, false, err } trace.Log(log.Int("numRanges", len(documentData.Document.Ranges))) @@ -36,7 +36,7 @@ func (s *store) GetHover(ctx context.Context, bundleID int, path string, line, c } } - return "", shared.Range{}, false, nil + return "", types.Range{}, false, nil } const hoverDocumentQuery = ` diff --git a/internal/codeintel/codenav/internal/lsifstore/lsifstore_locations.go b/internal/codeintel/codenav/internal/lsifstore/lsifstore_locations.go index 1ff17122f10..e1cbe750cb1 100644 --- a/internal/codeintel/codenav/internal/lsifstore/lsifstore_locations.go +++ b/internal/codeintel/codenav/internal/lsifstore/lsifstore_locations.go @@ -11,6 +11,7 @@ import ( "github.com/opentracing/opentracing-go/log" "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" @@ -339,13 +340,13 @@ func (s *store) readRangesFromDocument(bundleID int, rangeIDsByResultID map[prec return totalCount } -func newRange(startLine, startCharacter, endLine, endCharacter int) shared.Range { - return shared.Range{ - Start: shared.Position{ +func newRange(startLine, startCharacter, endLine, endCharacter int) types.Range { + return types.Range{ + Start: types.Position{ Line: startLine, Character: startCharacter, }, - End: shared.Position{ + End: types.Position{ Line: endLine, Character: endCharacter, }, @@ -364,7 +365,7 @@ func sortLocations(locations []shared.Location) { } // compareBundleRanges returns true if r1's start position occurs before r2's start position. -func compareBundleRanges(r1, r2 shared.Range) bool { +func compareBundleRanges(r1, r2 types.Range) bool { cmp := r1.Start.Line - r2.Start.Line if cmp == 0 { cmp = r1.Start.Character - r2.Start.Character diff --git a/internal/codeintel/codenav/internal/lsifstore/lsifstore_stencil.go b/internal/codeintel/codenav/internal/lsifstore/lsifstore_stencil.go index 2c4704cfc5d..981da9e4590 100644 --- a/internal/codeintel/codenav/internal/lsifstore/lsifstore_stencil.go +++ b/internal/codeintel/codenav/internal/lsifstore/lsifstore_stencil.go @@ -6,12 +6,12 @@ import ( "github.com/keegancsmith/sqlf" "github.com/opentracing/opentracing-go/log" - "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/observation" ) // Stencil returns all ranges within a single document. -func (s *store) GetStencil(ctx context.Context, bundleID int, path string) (_ []shared.Range, err error) { +func (s *store) GetStencil(ctx context.Context, bundleID int, path string) (_ []types.Range, err error) { ctx, trace, endObservation := s.operations.getStencil.With(ctx, &err, observation.Args{LogFields: []log.Field{ log.Int("bundleID", bundleID), log.String("path", path), @@ -25,7 +25,7 @@ func (s *store) GetStencil(ctx context.Context, bundleID int, path string) (_ [] trace.Log(log.Int("numRanges", len(documentData.Document.Ranges))) - ranges := make([]shared.Range, 0, len(documentData.Document.Ranges)) + ranges := make([]types.Range, 0, len(documentData.Document.Ranges)) for _, r := range documentData.Document.Ranges { ranges = append(ranges, newRange(r.StartLine, r.StartCharacter, r.EndLine, r.EndCharacter)) } diff --git a/internal/codeintel/codenav/internal/store/observability.go b/internal/codeintel/codenav/internal/store/observability.go index 5c75ebad56e..f4c8bedb8ac 100644 --- a/internal/codeintel/codenav/internal/store/observability.go +++ b/internal/codeintel/codenav/internal/store/observability.go @@ -8,8 +8,8 @@ import ( ) type operations struct { - getLanguagesRequestedBy *observation.Operation - setRequestLanguageSupport *observation.Operation + // noop is a no-op operation to keep the newOperation scaffolding. + noop *observation.Operation } func newOperations(observationContext *observation.Context) *operations { @@ -29,7 +29,6 @@ func newOperations(observationContext *observation.Context) *operations { } return &operations{ - getLanguagesRequestedBy: op("GetLanguagesRequestedBy"), - setRequestLanguageSupport: op("SetRequestLanguageSupport"), + noop: op("noop"), } } diff --git a/internal/codeintel/codenav/internal/store/store.go b/internal/codeintel/codenav/internal/store/store.go index 42fbaa59020..e8f1d9b20c1 100644 --- a/internal/codeintel/codenav/internal/store/store.go +++ b/internal/codeintel/codenav/internal/store/store.go @@ -1,9 +1,7 @@ package store import ( - "context" - - "github.com/keegancsmith/sqlf" + logger "github.com/sourcegraph/log" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" @@ -12,13 +10,13 @@ import ( // Store provides the interface for codenav storage. type Store interface { - GetLanguagesRequestedBy(ctx context.Context, userID int) (_ []string, err error) - SetRequestLanguageSupport(ctx context.Context, userID int, language string) (err error) + GetUnsafeDB() database.DB } // store manages the codenav store. type store struct { db *basestore.Store + logger logger.Logger operations *operations } @@ -26,35 +24,13 @@ type store struct { func New(db database.DB, observationContext *observation.Context) Store { return &store{ db: basestore.NewWithHandle(db.Handle()), + logger: logger.Scoped("codenav.store", ""), operations: newOperations(observationContext), } } -func (s *store) GetLanguagesRequestedBy(ctx context.Context, userID int) (_ []string, err error) { - ctx, _, endObservation := s.operations.getLanguagesRequestedBy.With(ctx, &err, observation.Args{}) - defer endObservation(1, observation.Args{}) - - return basestore.ScanStrings(s.db.Query(ctx, sqlf.Sprintf(languagesRequestedByQuery, userID))) +// GetUnsafeDB returns the underlying database handle. This is used by the +// resolvers that have the old convention of using the database handle directly. +func (s *store) GetUnsafeDB() database.DB { + return database.NewDBWith(s.logger, s.db) } - -const languagesRequestedByQuery = ` --- source: internal/codeintel/codenav/internal/store/store.go:GetLanguagesRequestedBy -SELECT language_id -FROM codeintel_langugage_support_requests -WHERE user_id = %s -ORDER BY language_id -` - -func (s *store) SetRequestLanguageSupport(ctx context.Context, userID int, language string) (err error) { - ctx, _, endObservation := s.operations.setRequestLanguageSupport.With(ctx, &err, observation.Args{}) - defer endObservation(1, observation.Args{}) - - return s.db.Exec(ctx, sqlf.Sprintf(requestLanguageSupportQuery, userID, language)) -} - -const requestLanguageSupportQuery = ` --- source: internal/codeintel/codenav/internal/store/store.go:SetRequestLanguageSupport -INSERT INTO codeintel_langugage_support_requests (user_id, language_id) -VALUES (%s, %s) -ON CONFLICT DO NOTHING -` diff --git a/internal/codeintel/codenav/mocks_test.go b/internal/codeintel/codenav/mocks_test.go index 57a8876e436..2364b533767 100644 --- a/internal/codeintel/codenav/mocks_test.go +++ b/internal/codeintel/codenav/mocks_test.go @@ -17,7 +17,8 @@ import ( store "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/internal/store" shared "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" gitserver "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/gitserver" - shared1 "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + types "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + database "github.com/sourcegraph/sourcegraph/internal/database" precise "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" ) @@ -26,26 +27,17 @@ import ( // github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/internal/store) // used for unit testing. type MockStore struct { - // GetLanguagesRequestedByFunc is an instance of a mock function object - // controlling the behavior of the method GetLanguagesRequestedBy. - GetLanguagesRequestedByFunc *StoreGetLanguagesRequestedByFunc - // SetRequestLanguageSupportFunc is an instance of a mock function - // object controlling the behavior of the method - // SetRequestLanguageSupport. - SetRequestLanguageSupportFunc *StoreSetRequestLanguageSupportFunc + // GetUnsafeDBFunc is an instance of a mock function object controlling + // the behavior of the method GetUnsafeDB. + GetUnsafeDBFunc *StoreGetUnsafeDBFunc } // NewMockStore creates a new mock of the Store interface. All methods // return zero values for all results, unless overwritten. func NewMockStore() *MockStore { return &MockStore{ - GetLanguagesRequestedByFunc: &StoreGetLanguagesRequestedByFunc{ - defaultHook: func(context.Context, int) (r0 []string, r1 error) { - return - }, - }, - SetRequestLanguageSupportFunc: &StoreSetRequestLanguageSupportFunc{ - defaultHook: func(context.Context, int, string) (r0 error) { + GetUnsafeDBFunc: &StoreGetUnsafeDBFunc{ + defaultHook: func() (r0 database.DB) { return }, }, @@ -56,14 +48,9 @@ func NewMockStore() *MockStore { // panic on invocation, unless overwritten. func NewStrictMockStore() *MockStore { return &MockStore{ - GetLanguagesRequestedByFunc: &StoreGetLanguagesRequestedByFunc{ - defaultHook: func(context.Context, int) ([]string, error) { - panic("unexpected invocation of MockStore.GetLanguagesRequestedBy") - }, - }, - SetRequestLanguageSupportFunc: &StoreSetRequestLanguageSupportFunc{ - defaultHook: func(context.Context, int, string) error { - panic("unexpected invocation of MockStore.SetRequestLanguageSupport") + GetUnsafeDBFunc: &StoreGetUnsafeDBFunc{ + defaultHook: func() database.DB { + panic("unexpected invocation of MockStore.GetUnsafeDB") }, }, } @@ -73,154 +60,40 @@ func NewStrictMockStore() *MockStore { // methods delegate to the given implementation, unless overwritten. func NewMockStoreFrom(i store.Store) *MockStore { return &MockStore{ - GetLanguagesRequestedByFunc: &StoreGetLanguagesRequestedByFunc{ - defaultHook: i.GetLanguagesRequestedBy, - }, - SetRequestLanguageSupportFunc: &StoreSetRequestLanguageSupportFunc{ - defaultHook: i.SetRequestLanguageSupport, + GetUnsafeDBFunc: &StoreGetUnsafeDBFunc{ + defaultHook: i.GetUnsafeDB, }, } } -// StoreGetLanguagesRequestedByFunc describes the behavior when the -// GetLanguagesRequestedBy method of the parent MockStore instance is -// invoked. -type StoreGetLanguagesRequestedByFunc struct { - defaultHook func(context.Context, int) ([]string, error) - hooks []func(context.Context, int) ([]string, error) - history []StoreGetLanguagesRequestedByFuncCall +// StoreGetUnsafeDBFunc describes the behavior when the GetUnsafeDB method +// of the parent MockStore instance is invoked. +type StoreGetUnsafeDBFunc struct { + defaultHook func() database.DB + hooks []func() database.DB + history []StoreGetUnsafeDBFuncCall mutex sync.Mutex } -// GetLanguagesRequestedBy delegates to the next hook function in the queue -// and stores the parameter and result values of this invocation. -func (m *MockStore) GetLanguagesRequestedBy(v0 context.Context, v1 int) ([]string, error) { - r0, r1 := m.GetLanguagesRequestedByFunc.nextHook()(v0, v1) - m.GetLanguagesRequestedByFunc.appendCall(StoreGetLanguagesRequestedByFuncCall{v0, v1, r0, r1}) - return r0, r1 -} - -// SetDefaultHook sets function that is called when the -// GetLanguagesRequestedBy method of the parent MockStore instance is -// invoked and the hook queue is empty. -func (f *StoreGetLanguagesRequestedByFunc) SetDefaultHook(hook func(context.Context, int) ([]string, error)) { - f.defaultHook = hook -} - -// PushHook adds a function to the end of hook queue. Each invocation of the -// GetLanguagesRequestedBy method of the parent MockStore instance invokes -// the hook at the front of the queue and discards it. After the queue is -// empty, the default hook function is invoked for any future action. -func (f *StoreGetLanguagesRequestedByFunc) PushHook(hook func(context.Context, int) ([]string, error)) { - f.mutex.Lock() - f.hooks = append(f.hooks, hook) - f.mutex.Unlock() -} - -// SetDefaultReturn calls SetDefaultHook with a function that returns the -// given values. -func (f *StoreGetLanguagesRequestedByFunc) SetDefaultReturn(r0 []string, r1 error) { - f.SetDefaultHook(func(context.Context, int) ([]string, error) { - return r0, r1 - }) -} - -// PushReturn calls PushHook with a function that returns the given values. -func (f *StoreGetLanguagesRequestedByFunc) PushReturn(r0 []string, r1 error) { - f.PushHook(func(context.Context, int) ([]string, error) { - return r0, r1 - }) -} - -func (f *StoreGetLanguagesRequestedByFunc) nextHook() func(context.Context, int) ([]string, error) { - f.mutex.Lock() - defer f.mutex.Unlock() - - if len(f.hooks) == 0 { - return f.defaultHook - } - - hook := f.hooks[0] - f.hooks = f.hooks[1:] - return hook -} - -func (f *StoreGetLanguagesRequestedByFunc) appendCall(r0 StoreGetLanguagesRequestedByFuncCall) { - f.mutex.Lock() - f.history = append(f.history, r0) - f.mutex.Unlock() -} - -// History returns a sequence of StoreGetLanguagesRequestedByFuncCall -// objects describing the invocations of this function. -func (f *StoreGetLanguagesRequestedByFunc) History() []StoreGetLanguagesRequestedByFuncCall { - f.mutex.Lock() - history := make([]StoreGetLanguagesRequestedByFuncCall, len(f.history)) - copy(history, f.history) - f.mutex.Unlock() - - return history -} - -// StoreGetLanguagesRequestedByFuncCall is an object that describes an -// invocation of method GetLanguagesRequestedBy on an instance of MockStore. -type StoreGetLanguagesRequestedByFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Result0 is the value of the 1st result returned from this method - // invocation. - Result0 []string - // Result1 is the value of the 2nd result returned from this method - // invocation. - Result1 error -} - -// Args returns an interface slice containing the arguments of this -// invocation. -func (c StoreGetLanguagesRequestedByFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1} -} - -// Results returns an interface slice containing the results of this -// invocation. -func (c StoreGetLanguagesRequestedByFuncCall) Results() []interface{} { - return []interface{}{c.Result0, c.Result1} -} - -// StoreSetRequestLanguageSupportFunc describes the behavior when the -// SetRequestLanguageSupport method of the parent MockStore instance is -// invoked. -type StoreSetRequestLanguageSupportFunc struct { - defaultHook func(context.Context, int, string) error - hooks []func(context.Context, int, string) error - history []StoreSetRequestLanguageSupportFuncCall - mutex sync.Mutex -} - -// SetRequestLanguageSupport delegates to the next hook function in the -// queue and stores the parameter and result values of this invocation. -func (m *MockStore) SetRequestLanguageSupport(v0 context.Context, v1 int, v2 string) error { - r0 := m.SetRequestLanguageSupportFunc.nextHook()(v0, v1, v2) - m.SetRequestLanguageSupportFunc.appendCall(StoreSetRequestLanguageSupportFuncCall{v0, v1, v2, r0}) +// GetUnsafeDB delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockStore) GetUnsafeDB() database.DB { + r0 := m.GetUnsafeDBFunc.nextHook()() + m.GetUnsafeDBFunc.appendCall(StoreGetUnsafeDBFuncCall{r0}) return r0 } -// SetDefaultHook sets function that is called when the -// SetRequestLanguageSupport method of the parent MockStore instance is -// invoked and the hook queue is empty. -func (f *StoreSetRequestLanguageSupportFunc) SetDefaultHook(hook func(context.Context, int, string) error) { +// SetDefaultHook sets function that is called when the GetUnsafeDB method +// of the parent MockStore instance is invoked and the hook queue is empty. +func (f *StoreGetUnsafeDBFunc) SetDefaultHook(hook func() database.DB) { f.defaultHook = hook } // PushHook adds a function to the end of hook queue. Each invocation of the -// SetRequestLanguageSupport method of the parent MockStore instance invokes -// the hook at the front of the queue and discards it. After the queue is -// empty, the default hook function is invoked for any future action. -func (f *StoreSetRequestLanguageSupportFunc) PushHook(hook func(context.Context, int, string) error) { +// GetUnsafeDB method of the parent MockStore instance invokes the hook at +// the front of the queue and discards it. After the queue is empty, the +// default hook function is invoked for any future action. +func (f *StoreGetUnsafeDBFunc) PushHook(hook func() database.DB) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -228,20 +101,20 @@ func (f *StoreSetRequestLanguageSupportFunc) PushHook(hook func(context.Context, // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreSetRequestLanguageSupportFunc) SetDefaultReturn(r0 error) { - f.SetDefaultHook(func(context.Context, int, string) error { +func (f *StoreGetUnsafeDBFunc) SetDefaultReturn(r0 database.DB) { + f.SetDefaultHook(func() database.DB { return r0 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreSetRequestLanguageSupportFunc) PushReturn(r0 error) { - f.PushHook(func(context.Context, int, string) error { +func (f *StoreGetUnsafeDBFunc) PushReturn(r0 database.DB) { + f.PushHook(func() database.DB { return r0 }) } -func (f *StoreSetRequestLanguageSupportFunc) nextHook() func(context.Context, int, string) error { +func (f *StoreGetUnsafeDBFunc) nextHook() func() database.DB { f.mutex.Lock() defer f.mutex.Unlock() @@ -254,50 +127,40 @@ func (f *StoreSetRequestLanguageSupportFunc) nextHook() func(context.Context, in return hook } -func (f *StoreSetRequestLanguageSupportFunc) appendCall(r0 StoreSetRequestLanguageSupportFuncCall) { +func (f *StoreGetUnsafeDBFunc) appendCall(r0 StoreGetUnsafeDBFuncCall) { f.mutex.Lock() f.history = append(f.history, r0) f.mutex.Unlock() } -// History returns a sequence of StoreSetRequestLanguageSupportFuncCall -// objects describing the invocations of this function. -func (f *StoreSetRequestLanguageSupportFunc) History() []StoreSetRequestLanguageSupportFuncCall { +// History returns a sequence of StoreGetUnsafeDBFuncCall objects describing +// the invocations of this function. +func (f *StoreGetUnsafeDBFunc) History() []StoreGetUnsafeDBFuncCall { f.mutex.Lock() - history := make([]StoreSetRequestLanguageSupportFuncCall, len(f.history)) + history := make([]StoreGetUnsafeDBFuncCall, len(f.history)) copy(history, f.history) f.mutex.Unlock() return history } -// StoreSetRequestLanguageSupportFuncCall is an object that describes an -// invocation of method SetRequestLanguageSupport on an instance of -// MockStore. -type StoreSetRequestLanguageSupportFuncCall struct { - // Arg0 is the value of the 1st argument passed to this method - // invocation. - Arg0 context.Context - // Arg1 is the value of the 2nd argument passed to this method - // invocation. - Arg1 int - // Arg2 is the value of the 3rd argument passed to this method - // invocation. - Arg2 string +// StoreGetUnsafeDBFuncCall is an object that describes an invocation of +// method GetUnsafeDB on an instance of MockStore. +type StoreGetUnsafeDBFuncCall struct { // Result0 is the value of the 1st result returned from this method // invocation. - Result0 error + Result0 database.DB } // Args returns an interface slice containing the arguments of this // invocation. -func (c StoreSetRequestLanguageSupportFuncCall) Args() []interface{} { - return []interface{}{c.Arg0, c.Arg1, c.Arg2} +func (c StoreGetUnsafeDBFuncCall) Args() []interface{} { + return []interface{}{} } // Results returns an interface slice containing the results of this // invocation. -func (c StoreSetRequestLanguageSupportFuncCall) Results() []interface{} { +func (c StoreGetUnsafeDBFuncCall) Results() []interface{} { return []interface{}{c.Result0} } @@ -362,7 +225,7 @@ func NewMockLsifStore() *MockLsifStore { }, }, GetHoverFunc: &LsifStoreGetHoverFunc{ - defaultHook: func(context.Context, int, string, int, int) (r0 string, r1 shared.Range, r2 bool, r3 error) { + defaultHook: func(context.Context, int, string, int, int) (r0 string, r1 types.Range, r2 bool, r3 error) { return }, }, @@ -397,7 +260,7 @@ func NewMockLsifStore() *MockLsifStore { }, }, GetStencilFunc: &LsifStoreGetStencilFunc{ - defaultHook: func(context.Context, int, string) (r0 []shared.Range, r1 error) { + defaultHook: func(context.Context, int, string) (r0 []types.Range, r1 error) { return }, }, @@ -424,7 +287,7 @@ func NewStrictMockLsifStore() *MockLsifStore { }, }, GetHoverFunc: &LsifStoreGetHoverFunc{ - defaultHook: func(context.Context, int, string, int, int) (string, shared.Range, bool, error) { + defaultHook: func(context.Context, int, string, int, int) (string, types.Range, bool, error) { panic("unexpected invocation of MockLsifStore.GetHover") }, }, @@ -459,7 +322,7 @@ func NewStrictMockLsifStore() *MockLsifStore { }, }, GetStencilFunc: &LsifStoreGetStencilFunc{ - defaultHook: func(context.Context, int, string) ([]shared.Range, error) { + defaultHook: func(context.Context, int, string) ([]types.Range, error) { panic("unexpected invocation of MockLsifStore.GetStencil") }, }, @@ -884,15 +747,15 @@ func (c LsifStoreGetDiagnosticsFuncCall) Results() []interface{} { // LsifStoreGetHoverFunc describes the behavior when the GetHover method of // the parent MockLsifStore instance is invoked. type LsifStoreGetHoverFunc struct { - defaultHook func(context.Context, int, string, int, int) (string, shared.Range, bool, error) - hooks []func(context.Context, int, string, int, int) (string, shared.Range, bool, error) + defaultHook func(context.Context, int, string, int, int) (string, types.Range, bool, error) + hooks []func(context.Context, int, string, int, int) (string, types.Range, bool, error) history []LsifStoreGetHoverFuncCall mutex sync.Mutex } // GetHover delegates to the next hook function in the queue and stores the // parameter and result values of this invocation. -func (m *MockLsifStore) GetHover(v0 context.Context, v1 int, v2 string, v3 int, v4 int) (string, shared.Range, bool, error) { +func (m *MockLsifStore) GetHover(v0 context.Context, v1 int, v2 string, v3 int, v4 int) (string, types.Range, bool, error) { r0, r1, r2, r3 := m.GetHoverFunc.nextHook()(v0, v1, v2, v3, v4) m.GetHoverFunc.appendCall(LsifStoreGetHoverFuncCall{v0, v1, v2, v3, v4, r0, r1, r2, r3}) return r0, r1, r2, r3 @@ -900,7 +763,7 @@ func (m *MockLsifStore) GetHover(v0 context.Context, v1 int, v2 string, v3 int, // SetDefaultHook sets function that is called when the GetHover method of // the parent MockLsifStore instance is invoked and the hook queue is empty. -func (f *LsifStoreGetHoverFunc) SetDefaultHook(hook func(context.Context, int, string, int, int) (string, shared.Range, bool, error)) { +func (f *LsifStoreGetHoverFunc) SetDefaultHook(hook func(context.Context, int, string, int, int) (string, types.Range, bool, error)) { f.defaultHook = hook } @@ -908,7 +771,7 @@ func (f *LsifStoreGetHoverFunc) SetDefaultHook(hook func(context.Context, int, s // GetHover method of the parent MockLsifStore instance invokes the hook at // the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. -func (f *LsifStoreGetHoverFunc) PushHook(hook func(context.Context, int, string, int, int) (string, shared.Range, bool, error)) { +func (f *LsifStoreGetHoverFunc) PushHook(hook func(context.Context, int, string, int, int) (string, types.Range, bool, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -916,20 +779,20 @@ func (f *LsifStoreGetHoverFunc) PushHook(hook func(context.Context, int, string, // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *LsifStoreGetHoverFunc) SetDefaultReturn(r0 string, r1 shared.Range, r2 bool, r3 error) { - f.SetDefaultHook(func(context.Context, int, string, int, int) (string, shared.Range, bool, error) { +func (f *LsifStoreGetHoverFunc) SetDefaultReturn(r0 string, r1 types.Range, r2 bool, r3 error) { + f.SetDefaultHook(func(context.Context, int, string, int, int) (string, types.Range, bool, error) { return r0, r1, r2, r3 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *LsifStoreGetHoverFunc) PushReturn(r0 string, r1 shared.Range, r2 bool, r3 error) { - f.PushHook(func(context.Context, int, string, int, int) (string, shared.Range, bool, error) { +func (f *LsifStoreGetHoverFunc) PushReturn(r0 string, r1 types.Range, r2 bool, r3 error) { + f.PushHook(func(context.Context, int, string, int, int) (string, types.Range, bool, error) { return r0, r1, r2, r3 }) } -func (f *LsifStoreGetHoverFunc) nextHook() func(context.Context, int, string, int, int) (string, shared.Range, bool, error) { +func (f *LsifStoreGetHoverFunc) nextHook() func(context.Context, int, string, int, int) (string, types.Range, bool, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -982,7 +845,7 @@ type LsifStoreGetHoverFuncCall struct { Result0 string // Result1 is the value of the 2nd result returned from this method // invocation. - Result1 shared.Range + Result1 types.Range // Result2 is the value of the 3rd result returned from this method // invocation. Result2 bool @@ -1728,15 +1591,15 @@ func (c LsifStoreGetReferenceLocationsFuncCall) Results() []interface{} { // LsifStoreGetStencilFunc describes the behavior when the GetStencil method // of the parent MockLsifStore instance is invoked. type LsifStoreGetStencilFunc struct { - defaultHook func(context.Context, int, string) ([]shared.Range, error) - hooks []func(context.Context, int, string) ([]shared.Range, error) + defaultHook func(context.Context, int, string) ([]types.Range, error) + hooks []func(context.Context, int, string) ([]types.Range, error) history []LsifStoreGetStencilFuncCall mutex sync.Mutex } // GetStencil delegates to the next hook function in the queue and stores // the parameter and result values of this invocation. -func (m *MockLsifStore) GetStencil(v0 context.Context, v1 int, v2 string) ([]shared.Range, error) { +func (m *MockLsifStore) GetStencil(v0 context.Context, v1 int, v2 string) ([]types.Range, error) { r0, r1 := m.GetStencilFunc.nextHook()(v0, v1, v2) m.GetStencilFunc.appendCall(LsifStoreGetStencilFuncCall{v0, v1, v2, r0, r1}) return r0, r1 @@ -1744,7 +1607,7 @@ func (m *MockLsifStore) GetStencil(v0 context.Context, v1 int, v2 string) ([]sha // SetDefaultHook sets function that is called when the GetStencil method of // the parent MockLsifStore instance is invoked and the hook queue is empty. -func (f *LsifStoreGetStencilFunc) SetDefaultHook(hook func(context.Context, int, string) ([]shared.Range, error)) { +func (f *LsifStoreGetStencilFunc) SetDefaultHook(hook func(context.Context, int, string) ([]types.Range, error)) { f.defaultHook = hook } @@ -1752,7 +1615,7 @@ func (f *LsifStoreGetStencilFunc) SetDefaultHook(hook func(context.Context, int, // GetStencil method of the parent MockLsifStore instance invokes the hook // at the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. -func (f *LsifStoreGetStencilFunc) PushHook(hook func(context.Context, int, string) ([]shared.Range, error)) { +func (f *LsifStoreGetStencilFunc) PushHook(hook func(context.Context, int, string) ([]types.Range, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -1760,20 +1623,20 @@ func (f *LsifStoreGetStencilFunc) PushHook(hook func(context.Context, int, strin // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *LsifStoreGetStencilFunc) SetDefaultReturn(r0 []shared.Range, r1 error) { - f.SetDefaultHook(func(context.Context, int, string) ([]shared.Range, error) { +func (f *LsifStoreGetStencilFunc) SetDefaultReturn(r0 []types.Range, r1 error) { + f.SetDefaultHook(func(context.Context, int, string) ([]types.Range, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *LsifStoreGetStencilFunc) PushReturn(r0 []shared.Range, r1 error) { - f.PushHook(func(context.Context, int, string) ([]shared.Range, error) { +func (f *LsifStoreGetStencilFunc) PushReturn(r0 []types.Range, r1 error) { + f.PushHook(func(context.Context, int, string) ([]types.Range, error) { return r0, r1 }) } -func (f *LsifStoreGetStencilFunc) nextHook() func(context.Context, int, string) ([]shared.Range, error) { +func (f *LsifStoreGetStencilFunc) nextHook() func(context.Context, int, string) ([]types.Range, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -1817,7 +1680,7 @@ type LsifStoreGetStencilFuncCall struct { Arg2 string // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.Range + Result0 []types.Range // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error @@ -2145,12 +2008,12 @@ func NewMockGitTreeTranslator() *MockGitTreeTranslator { }, }, GetTargetCommitPositionFromSourcePositionFunc: &GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc{ - defaultHook: func(context.Context, string, shared.Position, bool) (r0 string, r1 shared.Position, r2 bool, r3 error) { + defaultHook: func(context.Context, string, types.Position, bool) (r0 string, r1 types.Position, r2 bool, r3 error) { return }, }, GetTargetCommitRangeFromSourceRangeFunc: &GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc{ - defaultHook: func(context.Context, string, string, shared.Range, bool) (r0 string, r1 shared.Range, r2 bool, r3 error) { + defaultHook: func(context.Context, string, string, types.Range, bool) (r0 string, r1 types.Range, r2 bool, r3 error) { return }, }, @@ -2168,12 +2031,12 @@ func NewStrictMockGitTreeTranslator() *MockGitTreeTranslator { }, }, GetTargetCommitPositionFromSourcePositionFunc: &GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc{ - defaultHook: func(context.Context, string, shared.Position, bool) (string, shared.Position, bool, error) { + defaultHook: func(context.Context, string, types.Position, bool) (string, types.Position, bool, error) { panic("unexpected invocation of MockGitTreeTranslator.GetTargetCommitPositionFromSourcePosition") }, }, GetTargetCommitRangeFromSourceRangeFunc: &GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc{ - defaultHook: func(context.Context, string, string, shared.Range, bool) (string, shared.Range, bool, error) { + defaultHook: func(context.Context, string, string, types.Range, bool) (string, types.Range, bool, error) { panic("unexpected invocation of MockGitTreeTranslator.GetTargetCommitRangeFromSourceRange") }, }, @@ -2322,8 +2185,8 @@ func (c GitTreeTranslatorGetTargetCommitPathFromSourcePathFuncCall) Results() [] // the behavior when the GetTargetCommitPositionFromSourcePosition method of // the parent MockGitTreeTranslator instance is invoked. type GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc struct { - defaultHook func(context.Context, string, shared.Position, bool) (string, shared.Position, bool, error) - hooks []func(context.Context, string, shared.Position, bool) (string, shared.Position, bool, error) + defaultHook func(context.Context, string, types.Position, bool) (string, types.Position, bool, error) + hooks []func(context.Context, string, types.Position, bool) (string, types.Position, bool, error) history []GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFuncCall mutex sync.Mutex } @@ -2331,7 +2194,7 @@ type GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc struct { // GetTargetCommitPositionFromSourcePosition delegates to the next hook // function in the queue and stores the parameter and result values of this // invocation. -func (m *MockGitTreeTranslator) GetTargetCommitPositionFromSourcePosition(v0 context.Context, v1 string, v2 shared.Position, v3 bool) (string, shared.Position, bool, error) { +func (m *MockGitTreeTranslator) GetTargetCommitPositionFromSourcePosition(v0 context.Context, v1 string, v2 types.Position, v3 bool) (string, types.Position, bool, error) { r0, r1, r2, r3 := m.GetTargetCommitPositionFromSourcePositionFunc.nextHook()(v0, v1, v2, v3) m.GetTargetCommitPositionFromSourcePositionFunc.appendCall(GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFuncCall{v0, v1, v2, v3, r0, r1, r2, r3}) return r0, r1, r2, r3 @@ -2340,7 +2203,7 @@ func (m *MockGitTreeTranslator) GetTargetCommitPositionFromSourcePosition(v0 con // SetDefaultHook sets function that is called when the // GetTargetCommitPositionFromSourcePosition method of the parent // MockGitTreeTranslator instance is invoked and the hook queue is empty. -func (f *GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc) SetDefaultHook(hook func(context.Context, string, shared.Position, bool) (string, shared.Position, bool, error)) { +func (f *GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc) SetDefaultHook(hook func(context.Context, string, types.Position, bool) (string, types.Position, bool, error)) { f.defaultHook = hook } @@ -2349,7 +2212,7 @@ func (f *GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc) SetDefa // MockGitTreeTranslator instance invokes the hook at the front of the queue // and discards it. After the queue is empty, the default hook function is // invoked for any future action. -func (f *GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc) PushHook(hook func(context.Context, string, shared.Position, bool) (string, shared.Position, bool, error)) { +func (f *GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc) PushHook(hook func(context.Context, string, types.Position, bool) (string, types.Position, bool, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -2357,20 +2220,20 @@ func (f *GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc) PushHoo // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc) SetDefaultReturn(r0 string, r1 shared.Position, r2 bool, r3 error) { - f.SetDefaultHook(func(context.Context, string, shared.Position, bool) (string, shared.Position, bool, error) { +func (f *GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc) SetDefaultReturn(r0 string, r1 types.Position, r2 bool, r3 error) { + f.SetDefaultHook(func(context.Context, string, types.Position, bool) (string, types.Position, bool, error) { return r0, r1, r2, r3 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc) PushReturn(r0 string, r1 shared.Position, r2 bool, r3 error) { - f.PushHook(func(context.Context, string, shared.Position, bool) (string, shared.Position, bool, error) { +func (f *GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc) PushReturn(r0 string, r1 types.Position, r2 bool, r3 error) { + f.PushHook(func(context.Context, string, types.Position, bool) (string, types.Position, bool, error) { return r0, r1, r2, r3 }) } -func (f *GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc) nextHook() func(context.Context, string, shared.Position, bool) (string, shared.Position, bool, error) { +func (f *GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFunc) nextHook() func(context.Context, string, types.Position, bool) (string, types.Position, bool, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -2414,7 +2277,7 @@ type GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFuncCall struct { Arg1 string // Arg2 is the value of the 3rd argument passed to this method // invocation. - Arg2 shared.Position + Arg2 types.Position // Arg3 is the value of the 4th argument passed to this method // invocation. Arg3 bool @@ -2423,7 +2286,7 @@ type GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFuncCall struct { Result0 string // Result1 is the value of the 2nd result returned from this method // invocation. - Result1 shared.Position + Result1 types.Position // Result2 is the value of the 3rd result returned from this method // invocation. Result2 bool @@ -2448,8 +2311,8 @@ func (c GitTreeTranslatorGetTargetCommitPositionFromSourcePositionFuncCall) Resu // behavior when the GetTargetCommitRangeFromSourceRange method of the // parent MockGitTreeTranslator instance is invoked. type GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc struct { - defaultHook func(context.Context, string, string, shared.Range, bool) (string, shared.Range, bool, error) - hooks []func(context.Context, string, string, shared.Range, bool) (string, shared.Range, bool, error) + defaultHook func(context.Context, string, string, types.Range, bool) (string, types.Range, bool, error) + hooks []func(context.Context, string, string, types.Range, bool) (string, types.Range, bool, error) history []GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFuncCall mutex sync.Mutex } @@ -2457,7 +2320,7 @@ type GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc struct { // GetTargetCommitRangeFromSourceRange delegates to the next hook function // in the queue and stores the parameter and result values of this // invocation. -func (m *MockGitTreeTranslator) GetTargetCommitRangeFromSourceRange(v0 context.Context, v1 string, v2 string, v3 shared.Range, v4 bool) (string, shared.Range, bool, error) { +func (m *MockGitTreeTranslator) GetTargetCommitRangeFromSourceRange(v0 context.Context, v1 string, v2 string, v3 types.Range, v4 bool) (string, types.Range, bool, error) { r0, r1, r2, r3 := m.GetTargetCommitRangeFromSourceRangeFunc.nextHook()(v0, v1, v2, v3, v4) m.GetTargetCommitRangeFromSourceRangeFunc.appendCall(GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFuncCall{v0, v1, v2, v3, v4, r0, r1, r2, r3}) return r0, r1, r2, r3 @@ -2466,7 +2329,7 @@ func (m *MockGitTreeTranslator) GetTargetCommitRangeFromSourceRange(v0 context.C // SetDefaultHook sets function that is called when the // GetTargetCommitRangeFromSourceRange method of the parent // MockGitTreeTranslator instance is invoked and the hook queue is empty. -func (f *GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc) SetDefaultHook(hook func(context.Context, string, string, shared.Range, bool) (string, shared.Range, bool, error)) { +func (f *GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc) SetDefaultHook(hook func(context.Context, string, string, types.Range, bool) (string, types.Range, bool, error)) { f.defaultHook = hook } @@ -2475,7 +2338,7 @@ func (f *GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc) SetDefaultHoo // MockGitTreeTranslator instance invokes the hook at the front of the queue // and discards it. After the queue is empty, the default hook function is // invoked for any future action. -func (f *GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc) PushHook(hook func(context.Context, string, string, shared.Range, bool) (string, shared.Range, bool, error)) { +func (f *GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc) PushHook(hook func(context.Context, string, string, types.Range, bool) (string, types.Range, bool, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -2483,20 +2346,20 @@ func (f *GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc) PushHook(hook // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc) SetDefaultReturn(r0 string, r1 shared.Range, r2 bool, r3 error) { - f.SetDefaultHook(func(context.Context, string, string, shared.Range, bool) (string, shared.Range, bool, error) { +func (f *GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc) SetDefaultReturn(r0 string, r1 types.Range, r2 bool, r3 error) { + f.SetDefaultHook(func(context.Context, string, string, types.Range, bool) (string, types.Range, bool, error) { return r0, r1, r2, r3 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc) PushReturn(r0 string, r1 shared.Range, r2 bool, r3 error) { - f.PushHook(func(context.Context, string, string, shared.Range, bool) (string, shared.Range, bool, error) { +func (f *GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc) PushReturn(r0 string, r1 types.Range, r2 bool, r3 error) { + f.PushHook(func(context.Context, string, string, types.Range, bool) (string, types.Range, bool, error) { return r0, r1, r2, r3 }) } -func (f *GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc) nextHook() func(context.Context, string, string, shared.Range, bool) (string, shared.Range, bool, error) { +func (f *GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFunc) nextHook() func(context.Context, string, string, types.Range, bool) (string, types.Range, bool, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -2543,7 +2406,7 @@ type GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFuncCall struct { Arg2 string // Arg3 is the value of the 4th argument passed to this method // invocation. - Arg3 shared.Range + Arg3 types.Range // Arg4 is the value of the 5th argument passed to this method // invocation. Arg4 bool @@ -2552,7 +2415,7 @@ type GitTreeTranslatorGetTargetCommitRangeFromSourceRangeFuncCall struct { Result0 string // Result1 is the value of the 2nd result returned from this method // invocation. - Result1 shared.Range + Result1 types.Range // Result2 is the value of the 3rd result returned from this method // invocation. Result2 bool @@ -2890,12 +2753,12 @@ type MockUploadService struct { func NewMockUploadService() *MockUploadService { return &MockUploadService{ GetDumpsByIDsFunc: &UploadServiceGetDumpsByIDsFunc{ - defaultHook: func(context.Context, []int) (r0 []shared1.Dump, r1 error) { + defaultHook: func(context.Context, []int) (r0 []types.Dump, r1 error) { return }, }, GetDumpsWithDefinitionsForMonikersFunc: &UploadServiceGetDumpsWithDefinitionsForMonikersFunc{ - defaultHook: func(context.Context, []precise.QualifiedMonikerData) (r0 []shared1.Dump, r1 error) { + defaultHook: func(context.Context, []precise.QualifiedMonikerData) (r0 []types.Dump, r1 error) { return }, }, @@ -2905,7 +2768,7 @@ func NewMockUploadService() *MockUploadService { }, }, InferClosestUploadsFunc: &UploadServiceInferClosestUploadsFunc{ - defaultHook: func(context.Context, int, string, string, bool, string) (r0 []shared1.Dump, r1 error) { + defaultHook: func(context.Context, int, string, string, bool, string) (r0 []types.Dump, r1 error) { return }, }, @@ -2917,12 +2780,12 @@ func NewMockUploadService() *MockUploadService { func NewStrictMockUploadService() *MockUploadService { return &MockUploadService{ GetDumpsByIDsFunc: &UploadServiceGetDumpsByIDsFunc{ - defaultHook: func(context.Context, []int) ([]shared1.Dump, error) { + defaultHook: func(context.Context, []int) ([]types.Dump, error) { panic("unexpected invocation of MockUploadService.GetDumpsByIDs") }, }, GetDumpsWithDefinitionsForMonikersFunc: &UploadServiceGetDumpsWithDefinitionsForMonikersFunc{ - defaultHook: func(context.Context, []precise.QualifiedMonikerData) ([]shared1.Dump, error) { + defaultHook: func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error) { panic("unexpected invocation of MockUploadService.GetDumpsWithDefinitionsForMonikers") }, }, @@ -2932,7 +2795,7 @@ func NewStrictMockUploadService() *MockUploadService { }, }, InferClosestUploadsFunc: &UploadServiceInferClosestUploadsFunc{ - defaultHook: func(context.Context, int, string, string, bool, string) ([]shared1.Dump, error) { + defaultHook: func(context.Context, int, string, string, bool, string) ([]types.Dump, error) { panic("unexpected invocation of MockUploadService.InferClosestUploads") }, }, @@ -2962,15 +2825,15 @@ func NewMockUploadServiceFrom(i UploadService) *MockUploadService { // UploadServiceGetDumpsByIDsFunc describes the behavior when the // GetDumpsByIDs method of the parent MockUploadService instance is invoked. type UploadServiceGetDumpsByIDsFunc struct { - defaultHook func(context.Context, []int) ([]shared1.Dump, error) - hooks []func(context.Context, []int) ([]shared1.Dump, error) + defaultHook func(context.Context, []int) ([]types.Dump, error) + hooks []func(context.Context, []int) ([]types.Dump, error) history []UploadServiceGetDumpsByIDsFuncCall mutex sync.Mutex } // GetDumpsByIDs delegates to the next hook function in the queue and stores // the parameter and result values of this invocation. -func (m *MockUploadService) GetDumpsByIDs(v0 context.Context, v1 []int) ([]shared1.Dump, error) { +func (m *MockUploadService) GetDumpsByIDs(v0 context.Context, v1 []int) ([]types.Dump, error) { r0, r1 := m.GetDumpsByIDsFunc.nextHook()(v0, v1) m.GetDumpsByIDsFunc.appendCall(UploadServiceGetDumpsByIDsFuncCall{v0, v1, r0, r1}) return r0, r1 @@ -2979,7 +2842,7 @@ func (m *MockUploadService) GetDumpsByIDs(v0 context.Context, v1 []int) ([]share // SetDefaultHook sets function that is called when the GetDumpsByIDs method // of the parent MockUploadService instance is invoked and the hook queue is // empty. -func (f *UploadServiceGetDumpsByIDsFunc) SetDefaultHook(hook func(context.Context, []int) ([]shared1.Dump, error)) { +func (f *UploadServiceGetDumpsByIDsFunc) SetDefaultHook(hook func(context.Context, []int) ([]types.Dump, error)) { f.defaultHook = hook } @@ -2987,7 +2850,7 @@ func (f *UploadServiceGetDumpsByIDsFunc) SetDefaultHook(hook func(context.Contex // GetDumpsByIDs method of the parent MockUploadService instance invokes the // hook at the front of the queue and discards it. After the queue is empty, // the default hook function is invoked for any future action. -func (f *UploadServiceGetDumpsByIDsFunc) PushHook(hook func(context.Context, []int) ([]shared1.Dump, error)) { +func (f *UploadServiceGetDumpsByIDsFunc) PushHook(hook func(context.Context, []int) ([]types.Dump, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -2995,20 +2858,20 @@ func (f *UploadServiceGetDumpsByIDsFunc) PushHook(hook func(context.Context, []i // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *UploadServiceGetDumpsByIDsFunc) SetDefaultReturn(r0 []shared1.Dump, r1 error) { - f.SetDefaultHook(func(context.Context, []int) ([]shared1.Dump, error) { +func (f *UploadServiceGetDumpsByIDsFunc) SetDefaultReturn(r0 []types.Dump, r1 error) { + f.SetDefaultHook(func(context.Context, []int) ([]types.Dump, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *UploadServiceGetDumpsByIDsFunc) PushReturn(r0 []shared1.Dump, r1 error) { - f.PushHook(func(context.Context, []int) ([]shared1.Dump, error) { +func (f *UploadServiceGetDumpsByIDsFunc) PushReturn(r0 []types.Dump, r1 error) { + f.PushHook(func(context.Context, []int) ([]types.Dump, error) { return r0, r1 }) } -func (f *UploadServiceGetDumpsByIDsFunc) nextHook() func(context.Context, []int) ([]shared1.Dump, error) { +func (f *UploadServiceGetDumpsByIDsFunc) nextHook() func(context.Context, []int) ([]types.Dump, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -3049,7 +2912,7 @@ type UploadServiceGetDumpsByIDsFuncCall struct { Arg1 []int // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared1.Dump + Result0 []types.Dump // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error @@ -3071,15 +2934,15 @@ func (c UploadServiceGetDumpsByIDsFuncCall) Results() []interface{} { // behavior when the GetDumpsWithDefinitionsForMonikers method of the parent // MockUploadService instance is invoked. type UploadServiceGetDumpsWithDefinitionsForMonikersFunc struct { - defaultHook func(context.Context, []precise.QualifiedMonikerData) ([]shared1.Dump, error) - hooks []func(context.Context, []precise.QualifiedMonikerData) ([]shared1.Dump, error) + defaultHook func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error) + hooks []func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error) history []UploadServiceGetDumpsWithDefinitionsForMonikersFuncCall mutex sync.Mutex } // GetDumpsWithDefinitionsForMonikers delegates to the next hook function in // the queue and stores the parameter and result values of this invocation. -func (m *MockUploadService) GetDumpsWithDefinitionsForMonikers(v0 context.Context, v1 []precise.QualifiedMonikerData) ([]shared1.Dump, error) { +func (m *MockUploadService) GetDumpsWithDefinitionsForMonikers(v0 context.Context, v1 []precise.QualifiedMonikerData) ([]types.Dump, error) { r0, r1 := m.GetDumpsWithDefinitionsForMonikersFunc.nextHook()(v0, v1) m.GetDumpsWithDefinitionsForMonikersFunc.appendCall(UploadServiceGetDumpsWithDefinitionsForMonikersFuncCall{v0, v1, r0, r1}) return r0, r1 @@ -3088,7 +2951,7 @@ func (m *MockUploadService) GetDumpsWithDefinitionsForMonikers(v0 context.Contex // SetDefaultHook sets function that is called when the // GetDumpsWithDefinitionsForMonikers method of the parent MockUploadService // instance is invoked and the hook queue is empty. -func (f *UploadServiceGetDumpsWithDefinitionsForMonikersFunc) SetDefaultHook(hook func(context.Context, []precise.QualifiedMonikerData) ([]shared1.Dump, error)) { +func (f *UploadServiceGetDumpsWithDefinitionsForMonikersFunc) SetDefaultHook(hook func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error)) { f.defaultHook = hook } @@ -3097,7 +2960,7 @@ func (f *UploadServiceGetDumpsWithDefinitionsForMonikersFunc) SetDefaultHook(hoo // instance invokes the hook at the front of the queue and discards it. // After the queue is empty, the default hook function is invoked for any // future action. -func (f *UploadServiceGetDumpsWithDefinitionsForMonikersFunc) PushHook(hook func(context.Context, []precise.QualifiedMonikerData) ([]shared1.Dump, error)) { +func (f *UploadServiceGetDumpsWithDefinitionsForMonikersFunc) PushHook(hook func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -3105,20 +2968,20 @@ func (f *UploadServiceGetDumpsWithDefinitionsForMonikersFunc) PushHook(hook func // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *UploadServiceGetDumpsWithDefinitionsForMonikersFunc) SetDefaultReturn(r0 []shared1.Dump, r1 error) { - f.SetDefaultHook(func(context.Context, []precise.QualifiedMonikerData) ([]shared1.Dump, error) { +func (f *UploadServiceGetDumpsWithDefinitionsForMonikersFunc) SetDefaultReturn(r0 []types.Dump, r1 error) { + f.SetDefaultHook(func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *UploadServiceGetDumpsWithDefinitionsForMonikersFunc) PushReturn(r0 []shared1.Dump, r1 error) { - f.PushHook(func(context.Context, []precise.QualifiedMonikerData) ([]shared1.Dump, error) { +func (f *UploadServiceGetDumpsWithDefinitionsForMonikersFunc) PushReturn(r0 []types.Dump, r1 error) { + f.PushHook(func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error) { return r0, r1 }) } -func (f *UploadServiceGetDumpsWithDefinitionsForMonikersFunc) nextHook() func(context.Context, []precise.QualifiedMonikerData) ([]shared1.Dump, error) { +func (f *UploadServiceGetDumpsWithDefinitionsForMonikersFunc) nextHook() func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -3161,7 +3024,7 @@ type UploadServiceGetDumpsWithDefinitionsForMonikersFuncCall struct { Arg1 []precise.QualifiedMonikerData // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared1.Dump + Result0 []types.Dump // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error @@ -3316,15 +3179,15 @@ func (c UploadServiceGetUploadIDsWithReferencesFuncCall) Results() []interface{} // InferClosestUploads method of the parent MockUploadService instance is // invoked. type UploadServiceInferClosestUploadsFunc struct { - defaultHook func(context.Context, int, string, string, bool, string) ([]shared1.Dump, error) - hooks []func(context.Context, int, string, string, bool, string) ([]shared1.Dump, error) + defaultHook func(context.Context, int, string, string, bool, string) ([]types.Dump, error) + hooks []func(context.Context, int, string, string, bool, string) ([]types.Dump, error) history []UploadServiceInferClosestUploadsFuncCall mutex sync.Mutex } // InferClosestUploads delegates to the next hook function in the queue and // stores the parameter and result values of this invocation. -func (m *MockUploadService) InferClosestUploads(v0 context.Context, v1 int, v2 string, v3 string, v4 bool, v5 string) ([]shared1.Dump, error) { +func (m *MockUploadService) InferClosestUploads(v0 context.Context, v1 int, v2 string, v3 string, v4 bool, v5 string) ([]types.Dump, error) { r0, r1 := m.InferClosestUploadsFunc.nextHook()(v0, v1, v2, v3, v4, v5) m.InferClosestUploadsFunc.appendCall(UploadServiceInferClosestUploadsFuncCall{v0, v1, v2, v3, v4, v5, r0, r1}) return r0, r1 @@ -3333,7 +3196,7 @@ func (m *MockUploadService) InferClosestUploads(v0 context.Context, v1 int, v2 s // SetDefaultHook sets function that is called when the InferClosestUploads // method of the parent MockUploadService instance is invoked and the hook // queue is empty. -func (f *UploadServiceInferClosestUploadsFunc) SetDefaultHook(hook func(context.Context, int, string, string, bool, string) ([]shared1.Dump, error)) { +func (f *UploadServiceInferClosestUploadsFunc) SetDefaultHook(hook func(context.Context, int, string, string, bool, string) ([]types.Dump, error)) { f.defaultHook = hook } @@ -3342,7 +3205,7 @@ func (f *UploadServiceInferClosestUploadsFunc) SetDefaultHook(hook func(context. // invokes the hook at the front of the queue and discards it. After the // queue is empty, the default hook function is invoked for any future // action. -func (f *UploadServiceInferClosestUploadsFunc) PushHook(hook func(context.Context, int, string, string, bool, string) ([]shared1.Dump, error)) { +func (f *UploadServiceInferClosestUploadsFunc) PushHook(hook func(context.Context, int, string, string, bool, string) ([]types.Dump, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -3350,20 +3213,20 @@ func (f *UploadServiceInferClosestUploadsFunc) PushHook(hook func(context.Contex // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *UploadServiceInferClosestUploadsFunc) SetDefaultReturn(r0 []shared1.Dump, r1 error) { - f.SetDefaultHook(func(context.Context, int, string, string, bool, string) ([]shared1.Dump, error) { +func (f *UploadServiceInferClosestUploadsFunc) SetDefaultReturn(r0 []types.Dump, r1 error) { + f.SetDefaultHook(func(context.Context, int, string, string, bool, string) ([]types.Dump, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *UploadServiceInferClosestUploadsFunc) PushReturn(r0 []shared1.Dump, r1 error) { - f.PushHook(func(context.Context, int, string, string, bool, string) ([]shared1.Dump, error) { +func (f *UploadServiceInferClosestUploadsFunc) PushReturn(r0 []types.Dump, r1 error) { + f.PushHook(func(context.Context, int, string, string, bool, string) ([]types.Dump, error) { return r0, r1 }) } -func (f *UploadServiceInferClosestUploadsFunc) nextHook() func(context.Context, int, string, string, bool, string) ([]shared1.Dump, error) { +func (f *UploadServiceInferClosestUploadsFunc) nextHook() func(context.Context, int, string, string, bool, string) ([]types.Dump, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -3417,7 +3280,7 @@ type UploadServiceInferClosestUploadsFuncCall struct { Arg5 string // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared1.Dump + Result0 []types.Dump // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error diff --git a/internal/codeintel/codenav/observability.go b/internal/codeintel/codenav/observability.go index 52d0ca86b70..57f5dae3d6e 100644 --- a/internal/codeintel/codenav/observability.go +++ b/internal/codeintel/codenav/observability.go @@ -26,8 +26,6 @@ type operations struct { getUploadIDsWithReferences *observation.Operation getDumpsByIDs *observation.Operation getClosestDumpsForBlob *observation.Operation - getLanguagesRequestedBy *observation.Operation - setRequestLanguageSupport *observation.Operation } func newOperations(observationContext *observation.Context) *operations { @@ -61,8 +59,6 @@ func newOperations(observationContext *observation.Context) *operations { getUploadIDsWithReferences: op("GetUploadIDsWithReferences"), getDumpsByIDs: op("GetDumpsByIDs"), getClosestDumpsForBlob: op("GetClosestDumpsForBlob"), - getLanguagesRequestedBy: op("GetLanguagesRequestedBy"), - setRequestLanguageSupport: op("SetRequestLanguageSupport"), } } diff --git a/internal/codeintel/codenav/request_state.go b/internal/codeintel/codenav/request_state.go index 098fb449d69..7e8ded44952 100644 --- a/internal/codeintel/codenav/request_state.go +++ b/internal/codeintel/codenav/request_state.go @@ -5,7 +5,8 @@ import ( "github.com/sourcegraph/sourcegraph/internal/authz" "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" - "github.com/sourcegraph/sourcegraph/internal/types" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + sgTypes "github.com/sourcegraph/sourcegraph/internal/types" ) type RequestState struct { @@ -25,9 +26,9 @@ type RequestState struct { } func NewRequestState( - uploads []shared.Dump, + uploads []types.Dump, authChecker authz.SubRepoPermissionChecker, - gitclient shared.GitserverClient, repo *types.Repo, commit, path string, + gitclient shared.GitserverClient, repo *sgTypes.Repo, commit, path string, maxIndexes int, hunkCacheSize int, ) RequestState { @@ -41,13 +42,13 @@ func NewRequestState( return *r } -func (r RequestState) GetCacheUploads() []shared.Dump { +func (r RequestState) GetCacheUploads() []types.Dump { return r.dataLoader.uploads } -func (r RequestState) GetCacheUploadsAtIndex(index int) shared.Dump { +func (r RequestState) GetCacheUploadsAtIndex(index int) types.Dump { if index < 0 || index >= len(r.dataLoader.uploads) { - return shared.Dump{} + return types.Dump{} } return r.dataLoader.uploads[index] @@ -57,14 +58,14 @@ func (r *RequestState) SetAuthChecker(authChecker authz.SubRepoPermissionChecker r.authChecker = authChecker } -func (r *RequestState) SetUploadsDataLoader(uploads []shared.Dump) { +func (r *RequestState) SetUploadsDataLoader(uploads []types.Dump) { r.dataLoader = NewUploadsDataLoader() for _, upload := range uploads { r.dataLoader.AddUpload(upload) } } -func (r *RequestState) SetLocalGitTreeTranslator(client shared.GitserverClient, repo *types.Repo, commit, path string, hunkCacheSize int) error { +func (r *RequestState) SetLocalGitTreeTranslator(client shared.GitserverClient, repo *sgTypes.Repo, commit, path string, hunkCacheSize int) error { hunkCache, err := NewHunkCache(hunkCacheSize) if err != nil { return err @@ -90,18 +91,18 @@ func (r *RequestState) SetMaximumIndexesPerMonikerSearch(maxNumber int) { } type UploadsDataLoader struct { - uploads []shared.Dump - uploadsByID map[int]shared.Dump + uploads []types.Dump + uploadsByID map[int]types.Dump cacheMutex sync.RWMutex } func NewUploadsDataLoader() *UploadsDataLoader { return &UploadsDataLoader{ - uploadsByID: make(map[int]shared.Dump), + uploadsByID: make(map[int]types.Dump), } } -func (l *UploadsDataLoader) GetUploadFromCacheMap(id int) (shared.Dump, bool) { +func (l *UploadsDataLoader) GetUploadFromCacheMap(id int) (types.Dump, bool) { l.cacheMutex.RLock() defer l.cacheMutex.RUnlock() @@ -109,7 +110,7 @@ func (l *UploadsDataLoader) GetUploadFromCacheMap(id int) (shared.Dump, bool) { return upload, ok } -func (l *UploadsDataLoader) SetUploadInCacheMap(uploads []shared.Dump) { +func (l *UploadsDataLoader) SetUploadInCacheMap(uploads []types.Dump) { l.cacheMutex.Lock() defer l.cacheMutex.Unlock() @@ -118,7 +119,7 @@ func (l *UploadsDataLoader) SetUploadInCacheMap(uploads []shared.Dump) { } } -func (l *UploadsDataLoader) AddUpload(dump shared.Dump) { +func (l *UploadsDataLoader) AddUpload(dump types.Dump) { l.cacheMutex.Lock() defer l.cacheMutex.Unlock() diff --git a/internal/codeintel/codenav/service.go b/internal/codeintel/codenav/service.go index e43da502eb6..6a9bf1e3cb1 100644 --- a/internal/codeintel/codenav/service.go +++ b/internal/codeintel/codenav/service.go @@ -13,9 +13,9 @@ import ( "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/internal/store" "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" codeintelgitserver "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/gitserver" - uploads "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/internal/symbols" "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" "github.com/sourcegraph/sourcegraph/lib/errors" ) @@ -23,54 +23,48 @@ import ( var _ service = (*Service)(nil) type service interface { - GetDefinitions(ctx context.Context, args shared.RequestArgs, requestState RequestState) (_ []shared.UploadLocation, err error) + GetDefinitions(ctx context.Context, args shared.RequestArgs, requestState RequestState) (_ []types.UploadLocation, err error) GetDiagnostics(ctx context.Context, args shared.RequestArgs, requestState RequestState) (diagnosticsAtUploads []shared.DiagnosticAtUpload, _ int, err error) - GetHover(ctx context.Context, args shared.RequestArgs, requestState RequestState) (_ string, _ shared.Range, _ bool, err error) - GetImplementations(ctx context.Context, args shared.RequestArgs, requestState RequestState, cursor shared.ImplementationsCursor) (_ []shared.UploadLocation, nextCursor shared.ImplementationsCursor, err error) + GetHover(ctx context.Context, args shared.RequestArgs, requestState RequestState) (_ string, _ types.Range, _ bool, err error) + GetImplementations(ctx context.Context, args shared.RequestArgs, requestState RequestState, cursor shared.ImplementationsCursor) (_ []types.UploadLocation, nextCursor shared.ImplementationsCursor, err error) GetRanges(ctx context.Context, args shared.RequestArgs, requestState RequestState, startLine, endLine int) (adjustedRanges []shared.AdjustedCodeIntelligenceRange, err error) - GetReferences(ctx context.Context, args shared.RequestArgs, requestState RequestState, cursor shared.ReferencesCursor) (_ []shared.UploadLocation, nextCursor shared.ReferencesCursor, err error) - GetStencil(ctx context.Context, args shared.RequestArgs, requestState RequestState) (adjustedRanges []shared.Range, err error) + GetReferences(ctx context.Context, args shared.RequestArgs, requestState RequestState, cursor shared.ReferencesCursor) (_ []types.UploadLocation, nextCursor shared.ReferencesCursor, err error) + GetStencil(ctx context.Context, args shared.RequestArgs, requestState RequestState) (adjustedRanges []types.Range, err error) GetMonikersByPosition(ctx context.Context, bundleID int, path string, line, character int) (_ [][]precise.MonikerData, err error) GetBulkMonikerLocations(ctx context.Context, tableName string, uploadIDs []int, monikers []precise.MonikerData, limit, offset int) (_ []shared.Location, _ int, err error) GetPackageInformation(ctx context.Context, bundleID int, path, packageInformationID string) (_ precise.PackageInformationData, _ bool, err error) - GetClosestDumpsForBlob(ctx context.Context, repositoryID int, commit, path string, exactPath bool, indexer string) (_ []shared.Dump, err error) - - // Symbols client - GetSupportedByCtags(ctx context.Context, filepath string, repoName api.RepoName) (bool, string, error) - - // Language Support - GetLanguagesRequestedBy(ctx context.Context, userID int) (_ []string, err error) - SetRequestLanguageSupport(ctx context.Context, userID int, language string) (err error) + GetClosestDumpsForBlob(ctx context.Context, repositoryID int, commit, path string, exactPath bool, indexer string) (_ []types.Dump, err error) // Uploads Service - GetDumpsByIDs(ctx context.Context, ids []int) (_ []shared.Dump, err error) - GetUploadsWithDefinitionsForMonikers(ctx context.Context, monikers []precise.QualifiedMonikerData) (_ []shared.Dump, err error) + GetDumpsByIDs(ctx context.Context, ids []int) (_ []types.Dump, err error) + GetUploadsWithDefinitionsForMonikers(ctx context.Context, monikers []precise.QualifiedMonikerData) (_ []types.Dump, err error) GetUploadIDsWithReferences(ctx context.Context, orderedMonikers []precise.QualifiedMonikerData, ignoreIDs []int, repositoryID int, commit string, limit int, offset int) (ids []int, recordsScanned int, totalCount int, err error) + + // Utilities + GetUnsafeDB() database.DB } type Service struct { - store store.Store - lsifstore lsifstore.LsifStore - gitserver GitserverClient - symbolsClient *symbols.Client - uploadSvc UploadService - operations *operations + store store.Store + lsifstore lsifstore.LsifStore + gitserver GitserverClient + uploadSvc UploadService + operations *operations } -func newService(store store.Store, lsifstore lsifstore.LsifStore, uploadSvc UploadService, gitserver GitserverClient, symbolsClient *symbols.Client, observationContext *observation.Context) *Service { +func newService(store store.Store, lsifstore lsifstore.LsifStore, uploadSvc UploadService, gitserver GitserverClient, observationContext *observation.Context) *Service { return &Service{ - store: store, - lsifstore: lsifstore, - gitserver: gitserver, - symbolsClient: symbolsClient, - uploadSvc: uploadSvc, - operations: newOperations(observationContext), + store: store, + lsifstore: lsifstore, + gitserver: gitserver, + uploadSvc: uploadSvc, + operations: newOperations(observationContext), } } // GetHover returns the set of locations defining the symbol at the given position. -func (s *Service) GetHover(ctx context.Context, args shared.RequestArgs, requestState RequestState) (_ string, _ shared.Range, _ bool, err error) { +func (s *Service) GetHover(ctx context.Context, args shared.RequestArgs, requestState RequestState) (_ string, _ types.Range, _ bool, err error) { ctx, trace, endObservation := observeResolver(ctx, &err, s.operations.getHover, serviceObserverThreshold, observation.Args{ LogFields: []traceLog.Field{ traceLog.Int("repositoryID", args.RepositoryID), @@ -86,7 +80,7 @@ func (s *Service) GetHover(ctx context.Context, args shared.RequestArgs, request adjustedUploads, err := s.getVisibleUploads(ctx, args.Line, args.Character, requestState) if err != nil { - return "", shared.Range{}, false, err + return "", types.Range{}, false, err } // Keep track of each adjusted range we know about enclosing the requested position. @@ -95,7 +89,7 @@ func (s *Service) GetHover(ctx context.Context, args shared.RequestArgs, request // have to look in the definition index and search for the text there. We don't // want to return the range associated with the definition, as the range is used // as a hint to highlight a range in the current document. - adjustedRanges := make([]shared.Range, 0, len(adjustedUploads)) + adjustedRanges := make([]types.Range, 0, len(adjustedUploads)) cachedUploads := requestState.GetCacheUploads() for i := range adjustedUploads { @@ -111,7 +105,7 @@ func (s *Service) GetHover(ctx context.Context, args shared.RequestArgs, request adjustedUpload.TargetPosition.Character, ) if err != nil { - return "", shared.Range{}, false, errors.Wrap(err, "lsifStore.Hover") + return "", types.Range{}, false, errors.Wrap(err, "lsifStore.Hover") } if !exists { continue @@ -120,7 +114,7 @@ func (s *Service) GetHover(ctx context.Context, args shared.RequestArgs, request // Adjust the highlighted range back to the appropriate range in the target commit _, adjustedRange, _, err := s.getSourceRange(ctx, args, requestState, cachedUploads[i].RepositoryID, cachedUploads[i].Commit, args.Path, rn) if err != nil { - return "", shared.Range{}, false, err + return "", types.Range{}, false, err } if text != "" { // Text attached to source range @@ -140,7 +134,7 @@ func (s *Service) GetHover(ctx context.Context, args shared.RequestArgs, request // The range we will end up returning is interpreted within the context of the current text // document, so any range inside of a remote index would be of no use. We'll return the first // (inner-most) range that we adjusted from the source index traversals above. - var adjustedRange shared.Range + var adjustedRange types.Range if len(adjustedRanges) > 0 { adjustedRange = adjustedRanges[0] } @@ -148,7 +142,7 @@ func (s *Service) GetHover(ctx context.Context, args shared.RequestArgs, request // Gather all import monikers attached to the ranges enclosing the requested position orderedMonikers, err := s.getOrderedMonikers(ctx, adjustedUploads, "import") if err != nil { - return "", shared.Range{}, false, err + return "", types.Range{}, false, err } trace.Log( traceLog.Int("numMonikers", len(orderedMonikers)), @@ -160,7 +154,7 @@ func (s *Service) GetHover(ctx context.Context, args shared.RequestArgs, request // any of the indexes we have already performed an LSIF graph traversal in above. uploads, err := s.getUploadsWithDefinitionsForMonikers(ctx, orderedMonikers, requestState) if err != nil { - return "", shared.Range{}, false, err + return "", types.Range{}, false, err } trace.Log( traceLog.Int("numDefinitionUploads", len(uploads)), @@ -171,7 +165,7 @@ func (s *Service) GetHover(ctx context.Context, args shared.RequestArgs, request // attached to one of the source ranges. locations, _, err := s.getBulkMonikerLocations(ctx, uploads, orderedMonikers, "definitions", DefinitionsLimit, 0) if err != nil { - return "", shared.Range{}, false, err + return "", types.Range{}, false, err } trace.Log(traceLog.Int("numLocations", len(locations))) @@ -185,7 +179,7 @@ func (s *Service) GetHover(ctx context.Context, args shared.RequestArgs, request locations[i].Range.Start.Character, ) if err != nil { - return "", shared.Range{}, false, errors.Wrap(err, "lsifStore.Hover") + return "", types.Range{}, false, errors.Wrap(err, "lsifStore.Hover") } if exists && text != "" { // Text attached to definition @@ -194,11 +188,11 @@ func (s *Service) GetHover(ctx context.Context, args shared.RequestArgs, request } // No text available - return "", shared.Range{}, false, nil + return "", types.Range{}, false, nil } // GetReferences returns the list of source locations that reference the symbol at the given position. -func (s *Service) GetReferences(ctx context.Context, args shared.RequestArgs, requestState RequestState, cursor shared.ReferencesCursor) (_ []shared.UploadLocation, _ shared.ReferencesCursor, err error) { +func (s *Service) GetReferences(ctx context.Context, args shared.RequestArgs, requestState RequestState, cursor shared.ReferencesCursor) (_ []types.UploadLocation, _ shared.ReferencesCursor, err error) { ctx, trace, endObservation := observeResolver(ctx, &err, s.operations.getReferences, serviceObserverThreshold, observation.Args{ LogFields: []traceLog.Field{ traceLog.Int("repositoryID", args.RepositoryID), @@ -317,7 +311,7 @@ func (s *Service) GetReferences(ctx context.Context, args shared.RequestArgs, re // getUploadsWithDefinitionsForMonikers returns the set of uploads that provide any of the given monikers. // This method will not return uploads for commits which are unknown to gitserver. -func (s *Service) getUploadsWithDefinitionsForMonikers(ctx context.Context, orderedMonikers []precise.QualifiedMonikerData, requestState RequestState) ([]shared.Dump, error) { +func (s *Service) getUploadsWithDefinitionsForMonikers(ctx context.Context, orderedMonikers []precise.QualifiedMonikerData, requestState RequestState) ([]types.Dump, error) { uploads, err := s.GetUploadsWithDefinitionsForMonikers(ctx, orderedMonikers) if err != nil { return nil, errors.Wrap(err, "dbstore.DefinitionDumps") @@ -521,8 +515,8 @@ func (s *Service) getPageRemoteLocations( // getUploadLocations translates a set of locations into an equivalent set of locations in the requested // commit. -func (s *Service) getUploadLocations(ctx context.Context, args shared.RequestArgs, requestState RequestState, locations []shared.Location) ([]shared.UploadLocation, error) { - uploadLocations := make([]shared.UploadLocation, 0, len(locations)) +func (s *Service) getUploadLocations(ctx context.Context, args shared.RequestArgs, requestState RequestState, locations []shared.Location) ([]types.UploadLocation, error) { + uploadLocations := make([]types.UploadLocation, 0, len(locations)) checkerEnabled := authz.SubRepoEnabled(requestState.authChecker) var a *actor.Actor @@ -558,13 +552,13 @@ func (s *Service) getUploadLocations(ctx context.Context, args shared.RequestArg // getUploadLocation translates a location (relative to the indexed commit) into an equivalent location in // the requested commit. If the translation fails, then the original commit and range are used as the // commit and range of the adjusted location. -func (s *Service) getUploadLocation(ctx context.Context, args shared.RequestArgs, requestState RequestState, dump shared.Dump, location shared.Location) (shared.UploadLocation, error) { +func (s *Service) getUploadLocation(ctx context.Context, args shared.RequestArgs, requestState RequestState, dump types.Dump, location shared.Location) (types.UploadLocation, error) { adjustedCommit, adjustedRange, _, err := s.getSourceRange(ctx, args, requestState, dump.RepositoryID, dump.Commit, dump.Root+location.Path, location.Range) if err != nil { - return shared.UploadLocation{}, err + return types.UploadLocation{}, err } - return shared.UploadLocation{ + return types.UploadLocation{ Dump: dump, Path: dump.Root + location.Path, TargetCommit: adjustedCommit, @@ -575,14 +569,14 @@ func (s *Service) getUploadLocation(ctx context.Context, args shared.RequestArgs // getSourceRange translates a range (relative to the indexed commit) into an equivalent range in the requested // commit. If the translation fails, then the original commit and range are returned along with a false-valued // flag. -func (s *Service) getSourceRange(ctx context.Context, args shared.RequestArgs, requestState RequestState, repositoryID int, commit, path string, rng shared.Range) (string, shared.Range, bool, error) { +func (s *Service) getSourceRange(ctx context.Context, args shared.RequestArgs, requestState RequestState, repositoryID int, commit, path string, rng types.Range) (string, types.Range, bool, error) { if repositoryID != args.RepositoryID { // No diffs between distinct repositories return commit, rng, true, nil } if _, sourceRange, ok, err := requestState.GitTreeTranslator.GetTargetCommitRangeFromSourceRange(ctx, commit, path, rng, true); err != nil { - return "", shared.Range{}, false, errors.Wrap(err, "gitTreeTranslator.GetTargetCommitRangeFromSourceRange") + return "", types.Range{}, false, errors.Wrap(err, "gitTreeTranslator.GetTargetCommitRangeFromSourceRange") } else if ok { return args.Commit, sourceRange, true, nil } @@ -593,9 +587,9 @@ func (s *Service) getSourceRange(ctx context.Context, args shared.RequestArgs, r // getUploadsByIDs returns a slice of uploads with the given identifiers. This method will not return a // new upload record for a commit which is unknown to gitserver. The given upload map is used as a // caching mechanism - uploads present in the map are not fetched again from the database. -func (s *Service) getUploadsByIDs(ctx context.Context, ids []int, requestState RequestState) ([]shared.Dump, error) { +func (s *Service) getUploadsByIDs(ctx context.Context, ids []int, requestState RequestState) ([]types.Dump, error) { missingIDs := make([]int, 0, len(ids)) - existingUploads := make([]shared.Dump, 0, len(ids)) + existingUploads := make([]types.Dump, 0, len(ids)) for _, id := range ids { if upload, ok := requestState.dataLoader.GetUploadFromCacheMap(id); ok { @@ -623,7 +617,7 @@ func (s *Service) getUploadsByIDs(ctx context.Context, ids []int, requestState R // removeUploadsWithUnknownCommits removes uploads for commits which are unknown to gitserver from the given // slice. The slice is filtered in-place and returned (to update the slice length). -func (s *Service) removeUploadsWithUnknownCommits(ctx context.Context, uploads []shared.Dump, requestState RequestState) ([]shared.Dump, error) { +func (s *Service) removeUploadsWithUnknownCommits(ctx context.Context, uploads []types.Dump, requestState RequestState) ([]types.Dump, error) { rcs := make([]codeintelgitserver.RepositoryCommit, 0, len(uploads)) for _, upload := range uploads { rcs = append(rcs, codeintelgitserver.RepositoryCommit{ @@ -648,7 +642,7 @@ func (s *Service) removeUploadsWithUnknownCommits(ctx context.Context, uploads [ // getBulkMonikerLocations returns the set of locations (within the given uploads) with an attached moniker // whose scheme+identifier matches any of the given monikers. -func (s *Service) getBulkMonikerLocations(ctx context.Context, uploads []shared.Dump, orderedMonikers []precise.QualifiedMonikerData, tableName string, limit, offset int) ([]shared.Location, int, error) { +func (s *Service) getBulkMonikerLocations(ctx context.Context, uploads []types.Dump, orderedMonikers []precise.QualifiedMonikerData, tableName string, limit, offset int) ([]shared.Location, int, error) { ids := make([]int, 0, len(uploads)) for i := range uploads { ids = append(ids, uploads[i].ID) @@ -670,7 +664,7 @@ func (s *Service) getBulkMonikerLocations(ctx context.Context, uploads []shared. // DefinitionsLimit is maximum the number of locations returned from Definitions. const DefinitionsLimit = 100 -func (s *Service) GetImplementations(ctx context.Context, args shared.RequestArgs, requestState RequestState, cursor shared.ImplementationsCursor) (_ []shared.UploadLocation, _ shared.ImplementationsCursor, err error) { +func (s *Service) GetImplementations(ctx context.Context, args shared.RequestArgs, requestState RequestState, cursor shared.ImplementationsCursor) (_ []types.UploadLocation, _ shared.ImplementationsCursor, err error) { ctx, trace, endObservation := observeResolver(ctx, &err, s.operations.getImplementations, serviceObserverThreshold, observation.Args{ LogFields: []traceLog.Field{ traceLog.Int("repositoryID", args.RepositoryID), @@ -791,7 +785,7 @@ func (s *Service) GetImplementations(ctx context.Context, args shared.RequestArg } // GetDefinitions returns the set of locations defining the symbol at the given position. -func (s *Service) GetDefinitions(ctx context.Context, args shared.RequestArgs, requestState RequestState) (_ []shared.UploadLocation, err error) { +func (s *Service) GetDefinitions(ctx context.Context, args shared.RequestArgs, requestState RequestState) (_ []types.UploadLocation, err error) { ctx, trace, endObservation := observeResolver(ctx, &err, s.operations.getDefinitions, serviceObserverThreshold, observation.Args{ LogFields: []traceLog.Field{ traceLog.Int("repositoryID", args.RepositoryID), @@ -953,12 +947,12 @@ func (s *Service) GetDiagnostics(ctx context.Context, args shared.RequestArgs, r // getRequestedCommitDiagnostic translates a diagnostic (relative to the indexed commit) into an equivalent diagnostic // in the requested commit. func (s *Service) getRequestedCommitDiagnostic(ctx context.Context, args shared.RequestArgs, requestState RequestState, adjustedUpload visibleUpload, diagnostic shared.Diagnostic) (shared.DiagnosticAtUpload, error) { - rn := shared.Range{ - Start: shared.Position{ + rn := types.Range{ + Start: types.Position{ Line: diagnostic.StartLine, Character: diagnostic.StartCharacter, }, - End: shared.Position{ + End: types.Position{ Line: diagnostic.EndLine, Character: diagnostic.EndCharacter, }, @@ -1097,7 +1091,7 @@ func (s *Service) getCodeIntelligenceRange(ctx context.Context, args shared.Requ } // GetStencil returns the set of locations defining the symbol at the given position. -func (s *Service) GetStencil(ctx context.Context, args shared.RequestArgs, requestState RequestState) (adjustedRanges []shared.Range, err error) { +func (s *Service) GetStencil(ctx context.Context, args shared.RequestArgs, requestState RequestState) (adjustedRanges []types.Range, err error) { ctx, trace, endObservation := observeResolver(ctx, &err, s.operations.getStencil, serviceObserverThreshold, observation.Args{ LogFields: []traceLog.Field{ traceLog.Int("repositoryID", args.RepositoryID), @@ -1157,7 +1151,7 @@ func (s *Service) GetBulkMonikerLocations(ctx context.Context, tableName string, return s.lsifstore.GetBulkMonikerLocations(ctx, tableName, uploadIDs, monikers, limit, offset) } -func (s *Service) GetUploadsWithDefinitionsForMonikers(ctx context.Context, monikers []precise.QualifiedMonikerData) (_ []shared.Dump, err error) { +func (s *Service) GetUploadsWithDefinitionsForMonikers(ctx context.Context, monikers []precise.QualifiedMonikerData) (_ []types.Dump, err error) { ctx, _, endObservation := s.operations.getUploadsWithDefinitionsForMonikers.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) @@ -1170,7 +1164,7 @@ func (s *Service) GetUploadsWithDefinitionsForMonikers(ctx context.Context, moni return dumps, nil } -func (s *Service) GetDumpsByIDs(ctx context.Context, ids []int) (_ []shared.Dump, err error) { +func (s *Service) GetDumpsByIDs(ctx context.Context, ids []int) (_ []types.Dump, err error) { ctx, _, endObservation := s.operations.getDumpsByIDs.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) @@ -1205,7 +1199,7 @@ func (s *Service) GetPackageInformation(ctx context.Context, bundleID int, path, return s.lsifstore.GetPackageInformation(ctx, bundleID, path, packageInformationID) } -func (s *Service) GetClosestDumpsForBlob(ctx context.Context, repositoryID int, commit, path string, exactPath bool, indexer string) (_ []shared.Dump, err error) { +func (s *Service) GetClosestDumpsForBlob(ctx context.Context, repositoryID int, commit, path string, exactPath bool, indexer string) (_ []types.Dump, err error) { ctx, trace, endObservation := s.operations.getClosestDumpsForBlob.With(ctx, &err, observation.Args{ LogFields: []traceLog.Field{ traceLog.Int("repositoryID", repositoryID), @@ -1267,44 +1261,13 @@ func (s *Service) GetClosestDumpsForBlob(ctx context.Context, repositoryID int, return filtered, nil } -func (s *Service) GetSupportedByCtags(ctx context.Context, filepath string, repoName api.RepoName) (bool, string, error) { - mappings, err := s.symbolsClient.ListLanguageMappings(ctx, repoName) - if err != nil { - return false, "", err - } - - for language, globs := range mappings { - for _, glob := range globs { - if glob.Match(filepath) { - return true, language, nil - } - } - } - - return false, "", nil -} - -func (s *Service) SetRequestLanguageSupport(ctx context.Context, userID int, language string) (err error) { - ctx, _, endObservation := s.operations.setRequestLanguageSupport.With(ctx, &err, observation.Args{ - LogFields: []traceLog.Field{traceLog.Int("userID", userID), traceLog.String("language", language)}, - }) - defer endObservation(1, observation.Args{}) - - return s.store.SetRequestLanguageSupport(ctx, userID, language) -} - -func (s *Service) GetLanguagesRequestedBy(ctx context.Context, userID int) (_ []string, err error) { - ctx, _, endObservation := s.operations.getLanguagesRequestedBy.With(ctx, &err, observation.Args{ - LogFields: []traceLog.Field{traceLog.Int("userID", userID)}, - }) - defer endObservation(1, observation.Args{}) - - return s.store.GetLanguagesRequestedBy(ctx, userID) +func (s *Service) GetUnsafeDB() database.DB { + return s.store.GetUnsafeDB() } // filterUploadsWithCommits removes the uploads for commits which are unknown to gitserver from the given // slice. The slice is filtered in-place and returned (to update the slice length). -func filterUploadsWithCommits(ctx context.Context, commitCache CommitCache, uploads []shared.Dump) ([]shared.Dump, error) { +func filterUploadsWithCommits(ctx context.Context, commitCache CommitCache, uploads []types.Dump) ([]types.Dump, error) { rcs := make([]codeintelgitserver.RepositoryCommit, 0, len(uploads)) for _, upload := range uploads { rcs = append(rcs, codeintelgitserver.RepositoryCommit{ @@ -1327,10 +1290,10 @@ func filterUploadsWithCommits(ctx context.Context, commitCache CommitCache, uplo return filtered, nil } -func updateSvcDumpToSharedDump(uploadDumps []uploads.Dump) []shared.Dump { - dumps := make([]shared.Dump, 0, len(uploadDumps)) +func updateSvcDumpToSharedDump(uploadDumps []types.Dump) []types.Dump { + dumps := make([]types.Dump, 0, len(uploadDumps)) for _, d := range uploadDumps { - dumps = append(dumps, shared.Dump{ + dumps = append(dumps, types.Dump{ ID: d.ID, Commit: d.Commit, Root: d.Root, @@ -1423,8 +1386,8 @@ func (s *Service) getVisibleUploads(ctx context.Context, line, character int, r // getVisibleUpload returns the current target path and the given position for the given upload. If // the upload cannot be adjusted, a false-valued flag is returned. -func (s *Service) getVisibleUpload(ctx context.Context, line, character int, upload shared.Dump, r RequestState) (visibleUpload, bool, error) { - position := shared.Position{ +func (s *Service) getVisibleUpload(ctx context.Context, line, character int, upload types.Dump, r RequestState) (visibleUpload, bool, error) { + position := types.Position{ Line: line, Character: character, } diff --git a/internal/codeintel/codenav/service_definitions_test.go b/internal/codeintel/codenav/service_definitions_test.go index 30463168c65..b11999db221 100644 --- a/internal/codeintel/codenav/service_definitions_test.go +++ b/internal/codeintel/codenav/service_definitions_test.go @@ -10,10 +10,10 @@ import ( "github.com/sourcegraph/sourcegraph/internal/authz" "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" codeintelgitserver "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/gitserver" - uploadsShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/internal/types" + sgtypes "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" ) @@ -27,13 +27,13 @@ func TestDefinitions(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: mockCommit, Root: "sub1/"}, {ID: 51, Commit: mockCommit, Root: "sub2/"}, {ID: 52, Commit: mockCommit, Root: "sub3/"}, @@ -61,7 +61,7 @@ func TestDefinitions(t *testing.T) { if err != nil { t.Fatalf("unexpected error querying definitions: %s", err) } - expectedLocations := []shared.UploadLocation{ + expectedLocations := []types.UploadLocation{ {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: mockCommit, TargetRange: testRange1}, {Dump: uploads[1], Path: "sub2/b.go", TargetCommit: mockCommit, TargetRange: testRange2}, {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: mockCommit, TargetRange: testRange3}, @@ -84,13 +84,13 @@ func TestDefinitionsWithSubRepoPermissions(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: mockCommit, Root: "sub1/"}, {ID: 51, Commit: mockCommit, Root: "sub2/"}, {ID: 52, Commit: mockCommit, Root: "sub3/"}, @@ -133,7 +133,7 @@ func TestDefinitionsWithSubRepoPermissions(t *testing.T) { t.Fatalf("unexpected error querying definitions: %s", err) } - expectedLocations := []shared.UploadLocation{ + expectedLocations := []types.UploadLocation{ {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange1}, {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange3}, } @@ -152,17 +152,17 @@ func TestDefinitionsRemote(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - err := mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{ID: 42}, mockCommit, mockPath, 50) + err := mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{ID: 42}, mockCommit, mockPath, 50) if err != nil { t.Fatalf("unexpected error setting local git tree translator: %s", err) } mockRequestState.GitTreeTranslator = mockedGitTreeTranslator() - uploads := []shared.Dump{ + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, @@ -170,7 +170,7 @@ func TestDefinitionsRemote(t *testing.T) { } mockRequestState.SetUploadsDataLoader(uploads) - dumps := []uploadsShared.Dump{ + dumps := []types.Dump{ {ID: 150, Commit: "deadbeef1", Root: "sub1/"}, {ID: 151, Commit: "deadbeef2", Root: "sub2/"}, {ID: 152, Commit: "deadbeef3", Root: "sub3/"}, @@ -224,15 +224,15 @@ func TestDefinitionsRemote(t *testing.T) { t.Fatalf("unexpected error querying definitions: %s", err) } - xLocations := []shared.UploadLocation{ + xLocations := []types.UploadLocation{ {Dump: remoteUploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef2", TargetRange: testRange1}, {Dump: remoteUploads[1], Path: "sub2/b.go", TargetCommit: "deadbeef2", TargetRange: testRange2}, {Dump: remoteUploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef2", TargetRange: testRange3}, {Dump: remoteUploads[1], Path: "sub2/b.go", TargetCommit: "deadbeef2", TargetRange: testRange4}, {Dump: remoteUploads[1], Path: "sub2/c.go", TargetCommit: "deadbeef2", TargetRange: testRange5}, } - expectedLocations := uploadLocationsToAdjustedLocations(xLocations) - if diff := cmp.Diff(expectedLocations, adjustedLocations); diff != "" { + + if diff := cmp.Diff(xLocations, adjustedLocations); diff != "" { t.Errorf("unexpected locations (-want +got):\n%s", diff) } @@ -275,13 +275,13 @@ func TestDefinitionsRemoteWithSubRepoPermissions(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{ID: 42}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{ID: 42}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, @@ -303,7 +303,7 @@ func TestDefinitionsRemoteWithSubRepoPermissions(t *testing.T) { }) mockRequestState.SetAuthChecker(checker) - dumps := []uploadsShared.Dump{ + dumps := []types.Dump{ {ID: 150, Commit: "deadbeef1", Root: "sub1/"}, {ID: 151, Commit: "deadbeef2", Root: "sub2/"}, {ID: 152, Commit: "deadbeef3", Root: "sub3/"}, @@ -357,10 +357,10 @@ func TestDefinitionsRemoteWithSubRepoPermissions(t *testing.T) { if err != nil { t.Fatalf("unexpected error querying definitions: %s", err) } - remoteUploads := uploadDumpToCodeNavDump(dumps) - expectedLocations := []shared.UploadLocation{ - {Dump: remoteUploads[1], Path: "sub2/b.go", TargetCommit: "deadbeef2", TargetRange: testRange2}, - {Dump: remoteUploads[1], Path: "sub2/b.go", TargetCommit: "deadbeef2", TargetRange: testRange4}, + + expectedLocations := []types.UploadLocation{ + {Dump: dumps[1], Path: "sub2/b.go", TargetCommit: "deadbeef2", TargetRange: testRange2}, + {Dump: dumps[1], Path: "sub2/b.go", TargetCommit: "deadbeef2", TargetRange: testRange4}, } if diff := cmp.Diff(expectedLocations, adjustedLocations); diff != "" { t.Errorf("unexpected locations (-want +got):\n%s", diff) @@ -400,84 +400,12 @@ func mockedGitTreeTranslator() GitTreeTranslator { mockPositionAdjuster.GetTargetCommitPathFromSourcePathFunc.SetDefaultHook(func(ctx context.Context, commit string, path string, _ bool) (string, bool, error) { return commit, true, nil }) - mockPositionAdjuster.GetTargetCommitPositionFromSourcePositionFunc.SetDefaultHook(func(ctx context.Context, commit string, pos shared.Position, _ bool) (string, shared.Position, bool, error) { + mockPositionAdjuster.GetTargetCommitPositionFromSourcePositionFunc.SetDefaultHook(func(ctx context.Context, commit string, pos types.Position, _ bool) (string, types.Position, bool, error) { return commit, pos, true, nil }) - mockPositionAdjuster.GetTargetCommitRangeFromSourceRangeFunc.SetDefaultHook(func(ctx context.Context, commit string, path string, rx shared.Range, _ bool) (string, shared.Range, bool, error) { + mockPositionAdjuster.GetTargetCommitRangeFromSourceRangeFunc.SetDefaultHook(func(ctx context.Context, commit string, path string, rx types.Range, _ bool) (string, types.Range, bool, error) { return commit, rx, true, nil }) return mockPositionAdjuster } - -func uploadLocationsToAdjustedLocations(location []shared.UploadLocation) []shared.UploadLocation { - uploadLocation := make([]shared.UploadLocation, 0, len(location)) - for _, loc := range location { - dump := shared.Dump{ - ID: loc.Dump.ID, - Commit: loc.Dump.Commit, - Root: loc.Dump.Root, - VisibleAtTip: loc.Dump.VisibleAtTip, - UploadedAt: loc.Dump.UploadedAt, - State: loc.Dump.State, - FailureMessage: loc.Dump.FailureMessage, - StartedAt: loc.Dump.StartedAt, - FinishedAt: loc.Dump.FinishedAt, - ProcessAfter: loc.Dump.ProcessAfter, - NumResets: loc.Dump.NumResets, - NumFailures: loc.Dump.NumFailures, - RepositoryID: loc.Dump.RepositoryID, - RepositoryName: loc.Dump.RepositoryName, - Indexer: loc.Dump.Indexer, - IndexerVersion: loc.Dump.IndexerVersion, - AssociatedIndexID: loc.Dump.AssociatedIndexID, - } - - targetRange := shared.Range{ - Start: shared.Position{ - Line: loc.TargetRange.Start.Line, - Character: loc.TargetRange.Start.Character, - }, - End: shared.Position{ - Line: loc.TargetRange.End.Line, - Character: loc.TargetRange.End.Character, - }, - } - - uploadLocation = append(uploadLocation, shared.UploadLocation{ - Dump: dump, - Path: loc.Path, - TargetCommit: loc.TargetCommit, - TargetRange: targetRange, - }) - } - - return uploadLocation -} - -func uploadDumpToCodeNavDump(storeDumps []uploadsShared.Dump) []shared.Dump { - dumps := make([]shared.Dump, 0, len(storeDumps)) - for _, d := range storeDumps { - dumps = append(dumps, shared.Dump{ - ID: d.ID, - Commit: d.Commit, - Root: d.Root, - VisibleAtTip: d.VisibleAtTip, - UploadedAt: d.UploadedAt, - State: d.State, - FailureMessage: d.FailureMessage, - StartedAt: d.StartedAt, - FinishedAt: d.FinishedAt, - ProcessAfter: d.ProcessAfter, - NumResets: d.NumResets, - NumFailures: d.NumFailures, - RepositoryID: d.RepositoryID, - RepositoryName: d.RepositoryName, - Indexer: d.Indexer, - IndexerVersion: d.IndexerVersion, - AssociatedIndexID: d.AssociatedIndexID, - }) - } - - return dumps -} diff --git a/internal/codeintel/codenav/service_diagnostics_test.go b/internal/codeintel/codenav/service_diagnostics_test.go index 4bd204a363a..71d447557b7 100644 --- a/internal/codeintel/codenav/service_diagnostics_test.go +++ b/internal/codeintel/codenav/service_diagnostics_test.go @@ -10,9 +10,10 @@ import ( "github.com/sourcegraph/sourcegraph/internal/authz" "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" codeintelgitserver "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/gitserver" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/internal/types" + sgtypes "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" ) @@ -26,13 +27,13 @@ func TestDiagnostics(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, @@ -98,13 +99,13 @@ func TestDiagnosticsWithSubRepoPermissions(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, diff --git a/internal/codeintel/codenav/service_hover_test.go b/internal/codeintel/codenav/service_hover_test.go index 1b1d11cddce..5065073ca4c 100644 --- a/internal/codeintel/codenav/service_hover_test.go +++ b/internal/codeintel/codenav/service_hover_test.go @@ -8,10 +8,10 @@ import ( "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" codeintelgitserver "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/gitserver" - uploadsShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/internal/types" + sgtypes "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" ) @@ -25,13 +25,13 @@ func TestHover(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{ID: 42}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{ID: 42}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, @@ -39,11 +39,11 @@ func TestHover(t *testing.T) { } mockRequestState.SetUploadsDataLoader(uploads) - expectedRange := shared.Range{ - Start: shared.Position{Line: 10, Character: 10}, - End: shared.Position{Line: 15, Character: 25}, + expectedRange := types.Range{ + Start: types.Position{Line: 10, Character: 10}, + End: types.Position{Line: 15, Character: 25}, } - mockLsifStore.GetHoverFunc.PushReturn("", shared.Range{}, false, nil) + mockLsifStore.GetHoverFunc.PushReturn("", types.Range{}, false, nil) mockLsifStore.GetHoverFunc.PushReturn("doctext", expectedRange, true, nil) mockRequest := shared.RequestArgs{ @@ -80,30 +80,30 @@ func TestHoverRemote(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{ID: 42}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{ID: 42}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef"}, } mockRequestState.SetUploadsDataLoader(uploads) - expectedRange := shared.Range{ - Start: shared.Position{Line: 10, Character: 10}, - End: shared.Position{Line: 15, Character: 25}, + expectedRange := types.Range{ + Start: types.Position{Line: 10, Character: 10}, + End: types.Position{Line: 15, Character: 25}, } mockLsifStore.GetHoverFunc.PushReturn("", expectedRange, true, nil) - remoteRange := shared.Range{ - Start: shared.Position{Line: 30, Character: 30}, - End: shared.Position{Line: 35, Character: 45}, + remoteRange := types.Range{ + Start: types.Position{Line: 30, Character: 30}, + End: types.Position{Line: 35, Character: 45}, } mockLsifStore.GetHoverFunc.PushReturn("doctext", remoteRange, true, nil) - uploadsWithDefinitions := []uploadsShared.Dump{ + uploadsWithDefinitions := []types.Dump{ {ID: 150, Commit: "deadbeef1", Root: "sub1/"}, {ID: 151, Commit: "deadbeef2", Root: "sub2/"}, {ID: 152, Commit: "deadbeef3", Root: "sub3/"}, diff --git a/internal/codeintel/codenav/service_implementations_test.go b/internal/codeintel/codenav/service_implementations_test.go index 414c485eec1..91129d2dff1 100644 --- a/internal/codeintel/codenav/service_implementations_test.go +++ b/internal/codeintel/codenav/service_implementations_test.go @@ -10,10 +10,10 @@ import ( "github.com/sourcegraph/sourcegraph/internal/authz" "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" codeintelgitserver "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/gitserver" - uploadsShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/internal/types" + sgtypes "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" ) @@ -27,12 +27,12 @@ func TestImplementations(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{}, mockCommit, mockPath, 50) + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{}, mockCommit, mockPath, 50) // Empty result set (prevents nil pointer as scanner is always non-nil) mockUploadSvc.GetUploadIDsWithReferencesFunc.PushReturn([]int{}, 0, 0, nil) @@ -48,7 +48,7 @@ func TestImplementations(t *testing.T) { mockLsifStore.GetImplementationLocationsFunc.PushReturn(locations[1:4], 3, nil) mockLsifStore.GetImplementationLocationsFunc.PushReturn(locations[4:], 1, nil) - uploads := []shared.Dump{ + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, @@ -69,7 +69,7 @@ func TestImplementations(t *testing.T) { t.Fatalf("unexpected error querying implementations: %s", err) } - expectedLocations := []shared.UploadLocation{ + expectedLocations := []types.UploadLocation{ {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange1}, {Dump: uploads[1], Path: "sub2/b.go", TargetCommit: "deadbeef", TargetRange: testRange2}, {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange3}, @@ -91,12 +91,12 @@ func TestImplementationsWithSubRepoPermissions(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{}, mockCommit, mockPath, 50) + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{}, mockCommit, mockPath, 50) // Empty result set (prevents nil pointer as scanner is always non-nil) mockUploadSvc.GetUploadIDsWithReferencesFunc.PushReturn([]int{}, 0, 0, nil) @@ -112,7 +112,7 @@ func TestImplementationsWithSubRepoPermissions(t *testing.T) { mockLsifStore.GetImplementationLocationsFunc.PushReturn(locations[1:4], 3, nil) mockLsifStore.GetImplementationLocationsFunc.PushReturn(locations[4:], 1, nil) - uploads := []shared.Dump{ + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, @@ -148,7 +148,7 @@ func TestImplementationsWithSubRepoPermissions(t *testing.T) { t.Fatalf("unexpected error querying implementations: %s", err) } - expectedLocations := []shared.UploadLocation{ + expectedLocations := []types.UploadLocation{ {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange1}, {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange3}, } @@ -167,13 +167,13 @@ func TestImplementationsRemote(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{ID: 42}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{ID: 42}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, @@ -181,7 +181,7 @@ func TestImplementationsRemote(t *testing.T) { } mockRequestState.SetUploadsDataLoader(uploads) - remoteUploads := []uploadsShared.Dump{ + remoteUploads := []types.Dump{ {ID: 150, Commit: "deadbeef1", Root: "sub1/"}, {ID: 151, Commit: "deadbeef2", Root: "sub2/"}, {ID: 152, Commit: "deadbeef3", Root: "sub3/"}, @@ -189,7 +189,7 @@ func TestImplementationsRemote(t *testing.T) { } mockUploadSvc.GetDumpsWithDefinitionsForMonikersFunc.PushReturn(remoteUploads, nil) - referenceUploads := []uploadsShared.Dump{ + referenceUploads := []types.Dump{ {ID: 250, Commit: "deadbeef1", Root: "sub1/"}, {ID: 251, Commit: "deadbeef2", Root: "sub2/"}, {ID: 252, Commit: "deadbeef3", Root: "sub3/"}, @@ -260,7 +260,7 @@ func TestImplementationsRemote(t *testing.T) { t.Fatalf("unexpected error querying references: %s", err) } - expectedLocations := []shared.UploadLocation{ + expectedLocations := []types.UploadLocation{ {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange1}, {Dump: uploads[1], Path: "sub2/b.go", TargetCommit: "deadbeef", TargetRange: testRange2}, {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange3}, @@ -324,13 +324,13 @@ func TestImplementationsRemoteWithSubRepoPermissions(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, @@ -351,7 +351,7 @@ func TestImplementationsRemoteWithSubRepoPermissions(t *testing.T) { }) mockRequestState.SetAuthChecker(checker) - definitionUploads := []uploadsShared.Dump{ + definitionUploads := []types.Dump{ {ID: 150, Commit: "deadbeef1", Root: "sub1/"}, {ID: 151, Commit: "deadbeef2", Root: "sub2/"}, {ID: 152, Commit: "deadbeef3", Root: "sub3/"}, @@ -359,7 +359,7 @@ func TestImplementationsRemoteWithSubRepoPermissions(t *testing.T) { } mockUploadSvc.GetDumpsWithDefinitionsForMonikersFunc.PushReturn(definitionUploads, nil) - referenceUploads := []uploadsShared.Dump{ + referenceUploads := []types.Dump{ {ID: 250, Commit: "deadbeef1", Root: "sub1/"}, {ID: 251, Commit: "deadbeef2", Root: "sub2/"}, {ID: 252, Commit: "deadbeef3", Root: "sub3/"}, @@ -431,7 +431,7 @@ func TestImplementationsRemoteWithSubRepoPermissions(t *testing.T) { t.Fatalf("unexpected error querying references: %s", err) } - expectedLocations := []shared.UploadLocation{ + expectedLocations := []types.UploadLocation{ {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange1}, {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange3}, {Dump: uploads[3], Path: "sub4/a.go", TargetCommit: "deadbeef", TargetRange: testRange1}, diff --git a/internal/codeintel/codenav/service_ranges_test.go b/internal/codeintel/codenav/service_ranges_test.go index 753a5354025..3bc860e20a5 100644 --- a/internal/codeintel/codenav/service_ranges_test.go +++ b/internal/codeintel/codenav/service_ranges_test.go @@ -8,9 +8,10 @@ import ( "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" codeintelgitserver "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/gitserver" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/internal/types" + sgtypes "github.com/sourcegraph/sourcegraph/internal/types" ) func TestRanges(t *testing.T) { @@ -23,13 +24,13 @@ func TestRanges(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, @@ -71,21 +72,21 @@ func TestRanges(t *testing.T) { t.Fatalf("unexpected error querying ranges: %s", err) } - adjustedLocation1 := shared.UploadLocation{Dump: uploads[0], Path: "sub1/a.go", TargetCommit: "deadbeef", TargetRange: testRange1} - adjustedLocation2 := shared.UploadLocation{Dump: uploads[1], Path: "sub2/b.go", TargetCommit: "deadbeef", TargetRange: testRange2} - adjustedLocation3 := shared.UploadLocation{Dump: uploads[1], Path: "sub2/c.go", TargetCommit: "deadbeef", TargetRange: testRange1} - adjustedLocation4 := shared.UploadLocation{Dump: uploads[1], Path: "sub2/d.go", TargetCommit: "deadbeef", TargetRange: testRange2} - adjustedLocation5 := shared.UploadLocation{Dump: uploads[1], Path: "sub2/e.go", TargetCommit: "deadbeef", TargetRange: testRange1} - adjustedLocation6 := shared.UploadLocation{Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange2} - adjustedLocation7 := shared.UploadLocation{Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange3} - adjustedLocation8 := shared.UploadLocation{Dump: uploads[2], Path: "sub3/a.go", TargetCommit: "deadbeef", TargetRange: testRange4} + adjustedLocation1 := types.UploadLocation{Dump: uploads[0], Path: "sub1/a.go", TargetCommit: "deadbeef", TargetRange: testRange1} + adjustedLocation2 := types.UploadLocation{Dump: uploads[1], Path: "sub2/b.go", TargetCommit: "deadbeef", TargetRange: testRange2} + adjustedLocation3 := types.UploadLocation{Dump: uploads[1], Path: "sub2/c.go", TargetCommit: "deadbeef", TargetRange: testRange1} + adjustedLocation4 := types.UploadLocation{Dump: uploads[1], Path: "sub2/d.go", TargetCommit: "deadbeef", TargetRange: testRange2} + adjustedLocation5 := types.UploadLocation{Dump: uploads[1], Path: "sub2/e.go", TargetCommit: "deadbeef", TargetRange: testRange1} + adjustedLocation6 := types.UploadLocation{Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange2} + adjustedLocation7 := types.UploadLocation{Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange3} + adjustedLocation8 := types.UploadLocation{Dump: uploads[2], Path: "sub3/a.go", TargetCommit: "deadbeef", TargetRange: testRange4} expectedRanges := []shared.AdjustedCodeIntelligenceRange{ - {Range: testRange1, HoverText: "text1", Definitions: []shared.UploadLocation{}, References: []shared.UploadLocation{adjustedLocation1}, Implementations: []shared.UploadLocation{}}, - {Range: testRange2, HoverText: "text2", Definitions: []shared.UploadLocation{adjustedLocation2}, References: []shared.UploadLocation{adjustedLocation3}, Implementations: []shared.UploadLocation{}}, - {Range: testRange3, HoverText: "text3", Definitions: []shared.UploadLocation{adjustedLocation4}, References: []shared.UploadLocation{adjustedLocation5}, Implementations: []shared.UploadLocation{}}, - {Range: testRange4, HoverText: "text4", Definitions: []shared.UploadLocation{adjustedLocation6}, References: []shared.UploadLocation{adjustedLocation7}, Implementations: []shared.UploadLocation{}}, - {Range: testRange5, HoverText: "text5", Definitions: []shared.UploadLocation{adjustedLocation8}, References: []shared.UploadLocation{}, Implementations: []shared.UploadLocation{}}, + {Range: testRange1, HoverText: "text1", Definitions: []types.UploadLocation{}, References: []types.UploadLocation{adjustedLocation1}, Implementations: []types.UploadLocation{}}, + {Range: testRange2, HoverText: "text2", Definitions: []types.UploadLocation{adjustedLocation2}, References: []types.UploadLocation{adjustedLocation3}, Implementations: []types.UploadLocation{}}, + {Range: testRange3, HoverText: "text3", Definitions: []types.UploadLocation{adjustedLocation4}, References: []types.UploadLocation{adjustedLocation5}, Implementations: []types.UploadLocation{}}, + {Range: testRange4, HoverText: "text4", Definitions: []types.UploadLocation{adjustedLocation6}, References: []types.UploadLocation{adjustedLocation7}, Implementations: []types.UploadLocation{}}, + {Range: testRange5, HoverText: "text5", Definitions: []types.UploadLocation{adjustedLocation8}, References: []types.UploadLocation{}, Implementations: []types.UploadLocation{}}, } if diff := cmp.Diff(expectedRanges, adjustedRanges); diff != "" { t.Errorf("unexpected ranges (-want +got):\n%s", diff) diff --git a/internal/codeintel/codenav/service_references_test.go b/internal/codeintel/codenav/service_references_test.go index f9ac4a1f061..42bab13bb96 100644 --- a/internal/codeintel/codenav/service_references_test.go +++ b/internal/codeintel/codenav/service_references_test.go @@ -10,19 +10,19 @@ import ( "github.com/sourcegraph/sourcegraph/internal/authz" "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" codeintelgitserver "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/gitserver" - uploadsShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/internal/types" + sgtypes "github.com/sourcegraph/sourcegraph/internal/types" "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" ) var ( - testRange1 = shared.Range{Start: shared.Position{Line: 11, Character: 21}, End: shared.Position{Line: 31, Character: 41}} - testRange2 = shared.Range{Start: shared.Position{Line: 12, Character: 22}, End: shared.Position{Line: 32, Character: 42}} - testRange3 = shared.Range{Start: shared.Position{Line: 13, Character: 23}, End: shared.Position{Line: 33, Character: 43}} - testRange4 = shared.Range{Start: shared.Position{Line: 14, Character: 24}, End: shared.Position{Line: 34, Character: 44}} - testRange5 = shared.Range{Start: shared.Position{Line: 15, Character: 25}, End: shared.Position{Line: 35, Character: 45}} + testRange1 = types.Range{Start: types.Position{Line: 11, Character: 21}, End: types.Position{Line: 31, Character: 41}} + testRange2 = types.Range{Start: types.Position{Line: 12, Character: 22}, End: types.Position{Line: 32, Character: 42}} + testRange3 = types.Range{Start: types.Position{Line: 13, Character: 23}, End: types.Position{Line: 33, Character: 43}} + testRange4 = types.Range{Start: types.Position{Line: 14, Character: 24}, End: types.Position{Line: 34, Character: 44}} + testRange5 = types.Range{Start: types.Position{Line: 15, Character: 25}, End: types.Position{Line: 35, Character: 45}} mockPath = "s1/main.go" mockCommit = "deadbeef" @@ -38,13 +38,13 @@ func TestReferences(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, @@ -80,7 +80,7 @@ func TestReferences(t *testing.T) { t.Fatalf("unexpected error querying references: %s", err) } - expectedLocations := []shared.UploadLocation{ + expectedLocations := []types.UploadLocation{ {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange1}, {Dump: uploads[1], Path: "sub2/b.go", TargetCommit: "deadbeef", TargetRange: testRange2}, {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange3}, @@ -102,13 +102,13 @@ func TestReferencesWithSubRepoPermissions(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, @@ -158,7 +158,7 @@ func TestReferencesWithSubRepoPermissions(t *testing.T) { if err != nil { t.Fatalf("unexpected error querying references: %s", err) } - expectedLocations := []shared.UploadLocation{ + expectedLocations := []types.UploadLocation{ {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange1}, {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange3}, } @@ -177,13 +177,13 @@ func TestReferencesRemote(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, @@ -191,7 +191,7 @@ func TestReferencesRemote(t *testing.T) { } mockRequestState.SetUploadsDataLoader(uploads) - definitionUploads := []uploadsShared.Dump{ + definitionUploads := []types.Dump{ {ID: 150, Commit: "deadbeef1", Root: "sub1/"}, {ID: 151, Commit: "deadbeef2", Root: "sub2/"}, {ID: 152, Commit: "deadbeef3", Root: "sub3/"}, @@ -199,7 +199,7 @@ func TestReferencesRemote(t *testing.T) { } mockUploadSvc.GetDumpsWithDefinitionsForMonikersFunc.PushReturn(definitionUploads, nil) - referenceUploads := []uploadsShared.Dump{ + referenceUploads := []types.Dump{ {ID: 250, Commit: "deadbeef1", Root: "sub1/"}, {ID: 251, Commit: "deadbeef2", Root: "sub2/"}, {ID: 252, Commit: "deadbeef3", Root: "sub3/"}, @@ -282,7 +282,7 @@ func TestReferencesRemote(t *testing.T) { t.Fatalf("unexpected error querying references: %s", err) } - expectedLocations := []shared.UploadLocation{ + expectedLocations := []types.UploadLocation{ {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange1}, {Dump: uploads[1], Path: "sub2/b.go", TargetCommit: "deadbeef", TargetRange: testRange2}, {Dump: uploads[1], Path: "sub2/a.go", TargetCommit: "deadbeef", TargetRange: testRange3}, @@ -353,13 +353,13 @@ func TestReferencesRemoteWithSubRepoPermissions(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, @@ -380,7 +380,7 @@ func TestReferencesRemoteWithSubRepoPermissions(t *testing.T) { }) mockRequestState.SetAuthChecker(checker) - definitionUploads := []uploadsShared.Dump{ + definitionUploads := []types.Dump{ {ID: 150, Commit: "deadbeef1", Root: "sub1/"}, {ID: 151, Commit: "deadbeef2", Root: "sub2/"}, {ID: 152, Commit: "deadbeef3", Root: "sub3/"}, @@ -388,7 +388,7 @@ func TestReferencesRemoteWithSubRepoPermissions(t *testing.T) { } mockUploadSvc.GetDumpsWithDefinitionsForMonikersFunc.PushReturn(definitionUploads, nil) - referenceUploads := []uploadsShared.Dump{ + referenceUploads := []types.Dump{ {ID: 250, Commit: "deadbeef1", Root: "sub1/"}, {ID: 251, Commit: "deadbeef2", Root: "sub2/"}, {ID: 252, Commit: "deadbeef3", Root: "sub3/"}, @@ -464,7 +464,7 @@ func TestReferencesRemoteWithSubRepoPermissions(t *testing.T) { t.Fatalf("unexpected error querying references: %s", err) } - expectedLocations := []shared.UploadLocation{ + expectedLocations := []types.UploadLocation{ {Dump: uploads[1], Path: "sub2/b.go", TargetCommit: "deadbeef", TargetRange: testRange2}, {Dump: uploads[1], Path: "sub2/b.go", TargetCommit: "deadbeef", TargetRange: testRange4}, {Dump: uploads[3], Path: "sub4/b.go", TargetCommit: "deadbeef", TargetRange: testRange2}, diff --git a/internal/codeintel/codenav/service_stencil_test.go b/internal/codeintel/codenav/service_stencil_test.go index 16e3b06af54..1896f0230d1 100644 --- a/internal/codeintel/codenav/service_stencil_test.go +++ b/internal/codeintel/codenav/service_stencil_test.go @@ -8,9 +8,10 @@ import ( "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" codeintelgitserver "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/gitserver" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/internal/types" + sgtypes "github.com/sourcegraph/sourcegraph/internal/types" ) func TestStencil(t *testing.T) { @@ -23,13 +24,13 @@ func TestStencil(t *testing.T) { mockGitServer := codeintelgitserver.New(database.NewMockDB(), mockDBStore, &observation.TestContext) // Init service - svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, nil, &observation.TestContext) + svc := newService(mockStore, mockLsifStore, mockUploadSvc, mockGitserverClient, &observation.TestContext) // Set up request state mockRequestState := RequestState{} mockRequestState.SetLocalCommitCache(mockGitserverClient) - mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &types.Repo{}, mockCommit, mockPath, 50) - uploads := []shared.Dump{ + mockRequestState.SetLocalGitTreeTranslator(mockGitServer, &sgtypes.Repo{}, mockCommit, mockPath, 50) + uploads := []types.Dump{ {ID: 50, Commit: "deadbeef", Root: "sub1/"}, {ID: 51, Commit: "deadbeef", Root: "sub2/"}, {ID: 52, Commit: "deadbeef", Root: "sub3/"}, @@ -37,17 +38,17 @@ func TestStencil(t *testing.T) { } mockRequestState.SetUploadsDataLoader(uploads) - expectedRanges := []shared.Range{ - {Start: shared.Position{Line: 10, Character: 20}, End: shared.Position{Line: 10, Character: 30}}, - {Start: shared.Position{Line: 11, Character: 20}, End: shared.Position{Line: 11, Character: 30}}, - {Start: shared.Position{Line: 12, Character: 20}, End: shared.Position{Line: 12, Character: 30}}, - {Start: shared.Position{Line: 13, Character: 20}, End: shared.Position{Line: 13, Character: 30}}, - {Start: shared.Position{Line: 14, Character: 20}, End: shared.Position{Line: 14, Character: 30}}, - {Start: shared.Position{Line: 15, Character: 20}, End: shared.Position{Line: 15, Character: 30}}, - {Start: shared.Position{Line: 16, Character: 20}, End: shared.Position{Line: 16, Character: 30}}, - {Start: shared.Position{Line: 17, Character: 20}, End: shared.Position{Line: 17, Character: 30}}, - {Start: shared.Position{Line: 18, Character: 20}, End: shared.Position{Line: 18, Character: 30}}, - {Start: shared.Position{Line: 19, Character: 20}, End: shared.Position{Line: 19, Character: 30}}, + expectedRanges := []types.Range{ + {Start: types.Position{Line: 10, Character: 20}, End: types.Position{Line: 10, Character: 30}}, + {Start: types.Position{Line: 11, Character: 20}, End: types.Position{Line: 11, Character: 30}}, + {Start: types.Position{Line: 12, Character: 20}, End: types.Position{Line: 12, Character: 30}}, + {Start: types.Position{Line: 13, Character: 20}, End: types.Position{Line: 13, Character: 30}}, + {Start: types.Position{Line: 14, Character: 20}, End: types.Position{Line: 14, Character: 30}}, + {Start: types.Position{Line: 15, Character: 20}, End: types.Position{Line: 15, Character: 30}}, + {Start: types.Position{Line: 16, Character: 20}, End: types.Position{Line: 16, Character: 30}}, + {Start: types.Position{Line: 17, Character: 20}, End: types.Position{Line: 17, Character: 30}}, + {Start: types.Position{Line: 18, Character: 20}, End: types.Position{Line: 18, Character: 30}}, + {Start: types.Position{Line: 19, Character: 20}, End: types.Position{Line: 19, Character: 30}}, } mockLsifStore.GetStencilFunc.PushReturn(nil, nil) mockLsifStore.GetStencilFunc.PushReturn(expectedRanges, nil) diff --git a/internal/codeintel/codenav/shared/types.go b/internal/codeintel/codenav/shared/types.go index 5b6fb00f279..b1cf2b17d28 100644 --- a/internal/codeintel/codenav/shared/types.go +++ b/internal/codeintel/codenav/shared/types.go @@ -1,8 +1,7 @@ package shared import ( - "time" - + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" ) @@ -14,19 +13,7 @@ type Symbol struct { type Location struct { DumpID int Path string - Range Range -} - -// Range is an inclusive bounds within a file. -type Range struct { - Start Position - End Position -} - -// Position is a unique position within a file. -type Position struct { - Line int - Character int + Range types.Range } type RequestArgs struct { @@ -39,22 +26,13 @@ type RequestArgs struct { RawCursor string } -// UploadLocation is a path and range pair from within a particular upload. The target commit -// denotes the target commit for which the location was set (the originally requested commit). -type UploadLocation struct { - Dump Dump - Path string - TargetCommit string - TargetRange Range -} - // DiagnosticAtUpload is a diagnostic from within a particular upload. The adjusted commit denotes // the target commit for which the location was adjusted (the originally requested commit). type DiagnosticAtUpload struct { Diagnostic - Dump Dump + Dump types.Dump AdjustedCommit string - AdjustedRange Range + AdjustedRange types.Range } // Diagnostic describes diagnostic information attached to a location within a @@ -65,42 +43,20 @@ type Diagnostic struct { precise.DiagnosticData } -// Dump is a subset of the lsif_uploads table (queried via the lsif_dumps_with_repository_name view) -// and stores only processed records. -type Dump struct { - ID int `json:"id"` - Commit string `json:"commit"` - Root string `json:"root"` - VisibleAtTip bool `json:"visibleAtTip"` - UploadedAt time.Time `json:"uploadedAt"` - State string `json:"state"` - FailureMessage *string `json:"failureMessage"` - StartedAt *time.Time `json:"startedAt"` - FinishedAt *time.Time `json:"finishedAt"` - ProcessAfter *time.Time `json:"processAfter"` - NumResets int `json:"numResets"` - NumFailures int `json:"numFailures"` - RepositoryID int `json:"repositoryId"` - RepositoryName string `json:"repositoryName"` - Indexer string `json:"indexer"` - IndexerVersion string `json:"indexerVersion"` - AssociatedIndexID *int `json:"associatedIndex"` -} - // AdjustedCodeIntelligenceRange stores definition, reference, and hover information for all ranges // within a block of lines. The definition and reference locations have been adjusted to fit the // target (originally requested) commit. type AdjustedCodeIntelligenceRange struct { - Range Range - Definitions []UploadLocation - References []UploadLocation - Implementations []UploadLocation + Range types.Range + Definitions []types.UploadLocation + References []types.UploadLocation + Implementations []types.UploadLocation HoverText string } // CodeIntelligenceRange pairs a range with its definitions, references, implementations, and hover text. type CodeIntelligenceRange struct { - Range Range + Range types.Range Definitions []Location References []Location Implementations []Location @@ -130,10 +86,10 @@ type ImplementationsCursor struct { // cursorAdjustedUpload type CursorToVisibleUpload struct { - DumpID int `json:"dumpID"` - TargetPath string `json:"adjustedPath"` - TargetPosition Position `json:"adjustedPosition"` - TargetPathWithoutRoot string `json:"adjustedPathInBundle"` + DumpID int `json:"dumpID"` + TargetPath string `json:"adjustedPath"` + TargetPosition types.Position `json:"adjustedPosition"` + TargetPathWithoutRoot string `json:"adjustedPathInBundle"` } // localCursor is an upload offset and a location offset within that upload. diff --git a/internal/codeintel/codenav/transport/graphql/diagnostic.go b/internal/codeintel/codenav/transport/graphql/diagnostic.go new file mode 100644 index 00000000000..61eba990ea4 --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/diagnostic.go @@ -0,0 +1,64 @@ +package graphql + +import ( + "context" + + "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +type DiagnosticResolver interface { + Severity() (*string, error) + Code() (*string, error) + Source() (*string, error) + Message() (*string, error) + Location(ctx context.Context) (LocationResolver, error) +} + +type diagnosticResolver struct { + diagnostic shared.DiagnosticAtUpload + locationResolver *sharedresolvers.CachedLocationResolver +} + +func NewDiagnosticResolver(diagnostic shared.DiagnosticAtUpload, locationResolver *sharedresolvers.CachedLocationResolver) DiagnosticResolver { + return &diagnosticResolver{ + diagnostic: diagnostic, + locationResolver: locationResolver, + } +} + +func (r *diagnosticResolver) Severity() (*string, error) { return toSeverity(r.diagnostic.Severity) } +func (r *diagnosticResolver) Code() (*string, error) { return strPtr(r.diagnostic.Code), nil } +func (r *diagnosticResolver) Source() (*string, error) { return strPtr(r.diagnostic.Source), nil } +func (r *diagnosticResolver) Message() (*string, error) { return strPtr(r.diagnostic.Message), nil } + +func (r *diagnosticResolver) Location(ctx context.Context) (LocationResolver, error) { + return resolveLocation( + ctx, + r.locationResolver, + types.UploadLocation{ + Dump: r.diagnostic.Dump, + Path: r.diagnostic.Path, + TargetCommit: r.diagnostic.AdjustedCommit, + TargetRange: r.diagnostic.AdjustedRange, + }, + ) +} + +var severities = map[int]string{ + 1: "ERROR", + 2: "WARNING", + 3: "INFORMATION", + 4: "HINT", +} + +func toSeverity(val int) (*string, error) { + severity, ok := severities[val] + if !ok { + return nil, errors.Errorf("unknown diagnostic severity %d", val) + } + + return &severity, nil +} diff --git a/internal/codeintel/codenav/transport/graphql/diagnostic_connection.go b/internal/codeintel/codenav/transport/graphql/diagnostic_connection.go new file mode 100644 index 00000000000..38a91640bf3 --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/diagnostic_connection.go @@ -0,0 +1,44 @@ +package graphql + +import ( + "context" + + "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" +) + +type DiagnosticConnectionResolver interface { + Nodes(ctx context.Context) ([]DiagnosticResolver, error) + TotalCount(ctx context.Context) (int32, error) + PageInfo(ctx context.Context) (*PageInfo, error) +} + +type diagnosticConnectionResolver struct { + diagnostics []shared.DiagnosticAtUpload + totalCount int + locationResolver *sharedresolvers.CachedLocationResolver +} + +func NewDiagnosticConnectionResolver(diagnostics []shared.DiagnosticAtUpload, totalCount int, locationResolver *sharedresolvers.CachedLocationResolver) DiagnosticConnectionResolver { + return &diagnosticConnectionResolver{ + diagnostics: diagnostics, + totalCount: totalCount, + locationResolver: locationResolver, + } +} + +func (r *diagnosticConnectionResolver) Nodes(ctx context.Context) ([]DiagnosticResolver, error) { + resolvers := make([]DiagnosticResolver, 0, len(r.diagnostics)) + for i := range r.diagnostics { + resolvers = append(resolvers, NewDiagnosticResolver(r.diagnostics[i], r.locationResolver)) + } + return resolvers, nil +} + +func (r *diagnosticConnectionResolver) TotalCount(ctx context.Context) (int32, error) { + return int32(r.totalCount), nil +} + +func (r *diagnosticConnectionResolver) PageInfo(ctx context.Context) (*PageInfo, error) { + return HasNextPage(len(r.diagnostics) < r.totalCount), nil +} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/query.go b/internal/codeintel/codenav/transport/graphql/gitblob_lsif_data_resolver.go similarity index 51% rename from enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/query.go rename to internal/codeintel/codenav/transport/graphql/gitblob_lsif_data_resolver.go index 31f72d1def2..c006c02e180 100644 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/query.go +++ b/internal/codeintel/codenav/transport/graphql/gitblob_lsif_data_resolver.go @@ -6,60 +6,63 @@ import ( "github.com/opentracing/opentracing-go/log" - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" - "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers" - "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql" - store "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/lsifstore" + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/lib/errors" ) -// DefaultReferencesPageSize is the reference result page size when no limit is supplied. -const DefaultReferencesPageSize = 100 +type GitBlobLSIFDataResolver interface { + GitTreeLSIFDataResolver + ToGitTreeLSIFData() (GitTreeLSIFDataResolver, bool) + ToGitBlobLSIFData() (GitBlobLSIFDataResolver, bool) -// DefaultReferencesPageSize is the implementation result page size when no limit is supplied. -const DefaultImplementationsPageSize = 100 + Stencil(ctx context.Context) ([]RangeResolver, error) + Ranges(ctx context.Context, args *LSIFRangesArgs) (CodeIntelligenceRangeConnectionResolver, error) + Definitions(ctx context.Context, args *LSIFQueryPositionArgs) (LocationConnectionResolver, error) + References(ctx context.Context, args *LSIFPagedQueryPositionArgs) (LocationConnectionResolver, error) + Implementations(ctx context.Context, args *LSIFPagedQueryPositionArgs) (LocationConnectionResolver, error) + Hover(ctx context.Context, args *LSIFQueryPositionArgs) (HoverResolver, error) +} -// DefaultDiagnosticsPageSize is the diagnostic result page size when no limit is supplied. -const DefaultDiagnosticsPageSize = 100 - -// ErrIllegalLimit occurs when the user requests less than one object per page. -var ErrIllegalLimit = errors.New("illegal limit") - -// ErrIllegalBounds occurs when a negative or zero-width bound is supplied by the user. -var ErrIllegalBounds = errors.New("illegal bounds") - -// QueryResolver is the main interface to bundle-related operations exposed to the GraphQL API. This +// gitBlobLSIFDataResolver is the main interface to bundle-related operations exposed to the GraphQL API. This // resolver concerns itself with GraphQL/API-specific behaviors (auth, validation, marshaling, etc.). // All code intel-specific behavior is delegated to the underlying resolver instance, which is defined // in the parent package. -type QueryResolver struct { - gitBlobLSIFDataResolver graphql.GitBlobLSIFDataResolver - resolver resolvers.Resolver +type gitBlobLSIFDataResolverQueryResolver struct { + autoindexingSvc AutoIndexingService + uploadSvc UploadsService + policiesSvc PolicyService + gitBlobLSIFDataResolver GitBlobResolver gitserver GitserverClient - locationResolver *CachedLocationResolver + locationResolver *sharedresolvers.CachedLocationResolver errTracer *observation.ErrCollector } // NewQueryResolver creates a new QueryResolver with the given resolver that defines all code intel-specific // behavior. A cached location resolver instance is also given to the query resolver, which should be used // to resolve all location-related values. -func NewQueryResolver(gitserver GitserverClient, gitBlobResolver graphql.GitBlobLSIFDataResolver, resolver resolvers.Resolver, locationResolver *CachedLocationResolver, errTracer *observation.ErrCollector) gql.GitBlobLSIFDataResolver { - return &QueryResolver{ +func NewGitBlobLSIFDataResolverQueryResolver(autoindexSvc AutoIndexingService, uploadSvc UploadsService, policiesSvc PolicyService, gitserver GitserverClient, gitBlobResolver GitBlobResolver, errTracer *observation.ErrCollector) GitBlobLSIFDataResolver { + return &gitBlobLSIFDataResolverQueryResolver{ gitBlobLSIFDataResolver: gitBlobResolver, - resolver: resolver, + autoindexingSvc: autoindexSvc, + uploadSvc: uploadSvc, + policiesSvc: policiesSvc, gitserver: gitserver, - locationResolver: locationResolver, + locationResolver: sharedresolvers.NewCachedLocationResolver(autoindexSvc.GetUnsafeDB()), errTracer: errTracer, } } -func (r *QueryResolver) ToGitTreeLSIFData() (gql.GitTreeLSIFDataResolver, bool) { return r, true } -func (r *QueryResolver) ToGitBlobLSIFData() (gql.GitBlobLSIFDataResolver, bool) { return r, true } +func (r *gitBlobLSIFDataResolverQueryResolver) ToGitTreeLSIFData() (GitTreeLSIFDataResolver, bool) { + return r, true +} -func (r *QueryResolver) Stencil(ctx context.Context) (_ []gql.RangeResolver, err error) { +func (r *gitBlobLSIFDataResolverQueryResolver) ToGitBlobLSIFData() (GitBlobLSIFDataResolver, bool) { + return r, true +} + +func (r *gitBlobLSIFDataResolverQueryResolver) Stencil(ctx context.Context) (_ []RangeResolver, err error) { defer r.errTracer.Collect(&err, log.String("queryResolver.field", "stencil")) ranges, err := r.gitBlobLSIFDataResolver.Stencil(ctx) @@ -67,20 +70,23 @@ func (r *QueryResolver) Stencil(ctx context.Context) (_ []gql.RangeResolver, err return nil, err } - var adjustedRanges []lsifstore.Range + resolvers := make([]RangeResolver, 0, len(ranges)) for _, r := range ranges { - adjustedRanges = append(adjustedRanges, sharedRangeTolsifstoreRange(r)) - } - - resolvers := make([]gql.RangeResolver, 0, len(adjustedRanges)) - for _, r := range adjustedRanges { - resolvers = append(resolvers, gql.NewRangeResolver(convertRange(r))) + resolvers = append(resolvers, NewRangeResolver(convertRange(r))) } return resolvers, nil } -func (r *QueryResolver) Ranges(ctx context.Context, args *gql.LSIFRangesArgs) (_ gql.CodeIntelligenceRangeConnectionResolver, err error) { +type LSIFRangesArgs struct { + StartLine int32 + EndLine int32 +} + +// ErrIllegalBounds occurs when a negative or zero-width bound is supplied by the user. +var ErrIllegalBounds = errors.New("illegal bounds") + +func (r *gitBlobLSIFDataResolverQueryResolver) Ranges(ctx context.Context, args *LSIFRangesArgs) (_ CodeIntelligenceRangeConnectionResolver, err error) { defer r.errTracer.Collect(&err, log.String("queryResolver.field", "ranges")) if args.StartLine < 0 || args.EndLine < args.StartLine { @@ -92,13 +98,10 @@ func (r *QueryResolver) Ranges(ctx context.Context, args *gql.LSIFRangesArgs) (_ return nil, err } - return &CodeIntelligenceRangeConnectionResolver{ - ranges: sharedRangeToAdjustedRange(ranges), - locationResolver: r.locationResolver, - }, nil + return NewCodeIntelligenceRangeConnectionResolver(ranges, r.locationResolver), nil } -func (r *QueryResolver) Definitions(ctx context.Context, args *gql.LSIFQueryPositionArgs) (_ gql.LocationConnectionResolver, err error) { +func (r *gitBlobLSIFDataResolverQueryResolver) Definitions(ctx context.Context, args *LSIFQueryPositionArgs) (_ LocationConnectionResolver, err error) { defer r.errTracer.Collect(&err, log.String("queryResolver.field", "definitions")) locations, err := r.gitBlobLSIFDataResolver.Definitions(ctx, int(args.Line), int(args.Character)) @@ -116,12 +119,12 @@ func (r *QueryResolver) Definitions(ctx context.Context, args *gql.LSIFQueryPosi locations = filtered } - lct := uploadLocationToAdjustedLocations(locations) - - return NewLocationConnectionResolver(lct, nil, r.locationResolver), nil + return NewLocationConnectionResolver(locations, nil, r.locationResolver), nil } -func (r *QueryResolver) References(ctx context.Context, args *gql.LSIFPagedQueryPositionArgs) (_ gql.LocationConnectionResolver, err error) { +const DefaultReferencesPageSize = 100 + +func (r *gitBlobLSIFDataResolverQueryResolver) References(ctx context.Context, args *LSIFPagedQueryPositionArgs) (_ LocationConnectionResolver, err error) { defer r.errTracer.Collect(&err, log.String("queryResolver.field", "references")) limit := derefInt32(args.First, DefaultReferencesPageSize) @@ -129,7 +132,7 @@ func (r *QueryResolver) References(ctx context.Context, args *gql.LSIFPagedQuery return nil, ErrIllegalLimit } - cursor, err := graphqlutil.DecodeCursor(args.After) + cursor, err := DecodeCursor(args.After) if err != nil { return nil, err } @@ -149,12 +152,29 @@ func (r *QueryResolver) References(ctx context.Context, args *gql.LSIFPagedQuery locations = filtered } - lct := uploadLocationToAdjustedLocations(locations) - - return NewLocationConnectionResolver(lct, strPtr(cursor), r.locationResolver), nil + return NewLocationConnectionResolver(locations, strPtr(cursor), r.locationResolver), nil } -func (r *QueryResolver) Implementations(ctx context.Context, args *gql.LSIFPagedQueryPositionArgs) (_ gql.LocationConnectionResolver, err error) { +// DefaultReferencesPageSize is the implementation result page size when no limit is supplied. +const DefaultImplementationsPageSize = 100 + +// ErrIllegalLimit occurs when the user requests less than one object per page. +var ErrIllegalLimit = errors.New("illegal limit") + +type LSIFPagedQueryPositionArgs struct { + LSIFQueryPositionArgs + ConnectionArgs + After *string + Filter *string +} + +type LSIFQueryPositionArgs struct { + Line int32 + Character int32 + Filter *string +} + +func (r *gitBlobLSIFDataResolverQueryResolver) Implementations(ctx context.Context, args *LSIFPagedQueryPositionArgs) (_ LocationConnectionResolver, err error) { defer r.errTracer.Collect(&err, log.String("queryResolver.field", "implementations")) limit := derefInt32(args.First, DefaultImplementationsPageSize) @@ -162,7 +182,7 @@ func (r *QueryResolver) Implementations(ctx context.Context, args *gql.LSIFPaged return nil, ErrIllegalLimit } - cursor, err := graphqlutil.DecodeCursor(args.After) + cursor, err := DecodeCursor(args.After) if err != nil { return nil, err } @@ -182,12 +202,10 @@ func (r *QueryResolver) Implementations(ctx context.Context, args *gql.LSIFPaged locations = filtered } - lct := uploadLocationToAdjustedLocations(locations) - - return NewLocationConnectionResolver(lct, strPtr(cursor), r.locationResolver), nil + return NewLocationConnectionResolver(locations, strPtr(cursor), r.locationResolver), nil } -func (r *QueryResolver) Hover(ctx context.Context, args *gql.LSIFQueryPositionArgs) (_ gql.HoverResolver, err error) { +func (r *gitBlobLSIFDataResolverQueryResolver) Hover(ctx context.Context, args *LSIFQueryPositionArgs) (_ HoverResolver, err error) { defer r.errTracer.Collect(&err, log.String("queryResolver.field", "hover")) text, rx, exists, err := r.gitBlobLSIFDataResolver.Hover(ctx, int(args.Line), int(args.Character)) @@ -198,7 +216,7 @@ func (r *QueryResolver) Hover(ctx context.Context, args *gql.LSIFQueryPositionAr return NewHoverResolver(text, sharedRangeTolspRange(rx)), nil } -func (r *QueryResolver) LSIFUploads(ctx context.Context) (_ []gql.LSIFUploadResolver, err error) { +func (r *gitBlobLSIFDataResolverQueryResolver) LSIFUploads(ctx context.Context) (_ []sharedresolvers.LSIFUploadResolver, err error) { defer r.errTracer.Collect(&err, log.String("queryResolver.field", "lsifUploads")) uploads, err := r.gitBlobLSIFDataResolver.LSIFUploads(ctx) @@ -206,22 +224,29 @@ func (r *QueryResolver) LSIFUploads(ctx context.Context) (_ []gql.LSIFUploadReso return nil, err } - dbUploads := []store.Upload{} + dbUploads := []types.Upload{} for _, u := range uploads { dbUploads = append(dbUploads, sharedDumpToDbstoreUpload(u)) } - prefetcher := NewPrefetcher(r.resolver) + prefetcher := sharedresolvers.NewPrefetcher(r.autoindexingSvc, r.uploadSvc) - resolvers := make([]gql.LSIFUploadResolver, 0, len(dbUploads)) + resolvers := make([]sharedresolvers.LSIFUploadResolver, 0, len(uploads)) for _, upload := range dbUploads { - resolvers = append(resolvers, NewUploadResolver(r.locationResolver.db, r.gitserver, r.resolver, upload, prefetcher, r.locationResolver, r.errTracer)) + resolvers = append(resolvers, sharedresolvers.NewUploadResolver(r.uploadSvc, r.autoindexingSvc, r.policiesSvc, upload, prefetcher, r.errTracer)) } return resolvers, nil } -func (r *QueryResolver) Diagnostics(ctx context.Context, args *gql.LSIFDiagnosticsArgs) (_ gql.DiagnosticConnectionResolver, err error) { +// DefaultDiagnosticsPageSize is the diagnostic result page size when no limit is supplied. +const DefaultDiagnosticsPageSize = 100 + +type LSIFDiagnosticsArgs struct { + ConnectionArgs +} + +func (r *gitBlobLSIFDataResolverQueryResolver) Diagnostics(ctx context.Context, args *LSIFDiagnosticsArgs) (_ DiagnosticConnectionResolver, err error) { defer r.errTracer.Collect(&err, log.String("queryResolver.field", "diagnostics")) limit := derefInt32(args.First, DefaultDiagnosticsPageSize) @@ -234,7 +259,5 @@ func (r *QueryResolver) Diagnostics(ctx context.Context, args *gql.LSIFDiagnosti return nil, err } - adjustedDiag := sharedDiagnosticAtUploadToAdjustedDiagnostic(diagnostics) - - return NewDiagnosticConnectionResolver(adjustedDiag, totalCount, r.locationResolver), nil + return NewDiagnosticConnectionResolver(diagnostics, totalCount, r.locationResolver), nil } diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/query_test.go b/internal/codeintel/codenav/transport/graphql/gitblob_lsif_data_resolver_test.go similarity index 50% rename from enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/query_test.go rename to internal/codeintel/codenav/transport/graphql/gitblob_lsif_data_resolver_test.go index 341e8779aba..ace4a88ea32 100644 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/query_test.go +++ b/internal/codeintel/codenav/transport/graphql/gitblob_lsif_data_resolver_test.go @@ -5,25 +5,27 @@ import ( "encoding/base64" "testing" - "github.com/sourcegraph/log/logtest" - - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" - resolvermocks "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks" - transportmocks "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport" - "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" - "github.com/sourcegraph/sourcegraph/internal/database" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/observation" ) func TestRanges(t *testing.T) { - logger := logtest.Scoped(t) - db := database.NewDB(logger, nil) + mockGitBlobResolver := NewMockGitBlobResolver() + mockAutoIndexingSvc := NewMockAutoIndexingService() + mockUploadsService := NewMockUploadsService() + mockPolicyService := NewMockPolicyService() + mockGitserverClient := NewMockGitserverClient() - mockGitBlobResolver := transportmocks.NewMockGitBlobLSIFDataResolver() - resolver := NewQueryResolver(nil, mockGitBlobResolver, nil, NewCachedLocationResolver(db), nil) + resolver := NewGitBlobLSIFDataResolverQueryResolver( + mockAutoIndexingSvc, + mockUploadsService, + mockPolicyService, + mockGitserverClient, + mockGitBlobResolver, + observation.NewErrorCollector(), + ) - args := &gql.LSIFRangesArgs{StartLine: 10, EndLine: 20} + args := &LSIFRangesArgs{StartLine: 10, EndLine: 20} if _, err := resolver.Ranges(context.Background(), args); err != nil { t.Fatalf("unexpected error: %s", err) } @@ -40,13 +42,22 @@ func TestRanges(t *testing.T) { } func TestDefinitions(t *testing.T) { - logger := logtest.Scoped(t) - db := database.NewDB(logger, nil) + mockGitBlobResolver := NewMockGitBlobResolver() + mockAutoIndexingSvc := NewMockAutoIndexingService() + mockUploadsService := NewMockUploadsService() + mockPolicyService := NewMockPolicyService() + mockGitserverClient := NewMockGitserverClient() - mockGitBlobResolver := transportmocks.NewMockGitBlobLSIFDataResolver() - resolver := NewQueryResolver(nil, mockGitBlobResolver, nil, NewCachedLocationResolver(db), nil) + resolver := NewGitBlobLSIFDataResolverQueryResolver( + mockAutoIndexingSvc, + mockUploadsService, + mockPolicyService, + mockGitserverClient, + mockGitBlobResolver, + observation.NewErrorCollector(), + ) - args := &gql.LSIFQueryPositionArgs{Line: 10, Character: 15} + args := &LSIFQueryPositionArgs{Line: 10, Character: 15} if _, err := resolver.Definitions(context.Background(), args); err != nil { t.Fatalf("unexpected error: %s", err) } @@ -63,21 +74,30 @@ func TestDefinitions(t *testing.T) { } func TestReferences(t *testing.T) { - logger := logtest.Scoped(t) - db := database.NewDB(logger, nil) + mockGitBlobResolver := NewMockGitBlobResolver() + mockAutoIndexingSvc := NewMockAutoIndexingService() + mockUploadsService := NewMockUploadsService() + mockPolicyService := NewMockPolicyService() + mockGitserverClient := NewMockGitserverClient() - mockGitBlobResolver := transportmocks.NewMockGitBlobLSIFDataResolver() - resolver := NewQueryResolver(nil, mockGitBlobResolver, nil, NewCachedLocationResolver(db), nil) + resolver := NewGitBlobLSIFDataResolverQueryResolver( + mockAutoIndexingSvc, + mockUploadsService, + mockPolicyService, + mockGitserverClient, + mockGitBlobResolver, + observation.NewErrorCollector(), + ) offset := int32(25) cursor := base64.StdEncoding.EncodeToString([]byte("test-cursor")) - args := &gql.LSIFPagedQueryPositionArgs{ - LSIFQueryPositionArgs: gql.LSIFQueryPositionArgs{ + args := &LSIFPagedQueryPositionArgs{ + LSIFQueryPositionArgs: LSIFQueryPositionArgs{ Line: 10, Character: 15, }, - ConnectionArgs: graphqlutil.ConnectionArgs{First: &offset}, + ConnectionArgs: ConnectionArgs{First: &offset}, After: &cursor, } @@ -103,18 +123,27 @@ func TestReferences(t *testing.T) { } func TestReferencesDefaultLimit(t *testing.T) { - logger := logtest.Scoped(t) - db := database.NewDB(logger, nil) + mockGitBlobResolver := NewMockGitBlobResolver() + mockAutoIndexingSvc := NewMockAutoIndexingService() + mockUploadsService := NewMockUploadsService() + mockPolicyService := NewMockPolicyService() + mockGitserverClient := NewMockGitserverClient() - mockGitBlobResolver := transportmocks.NewMockGitBlobLSIFDataResolver() - resolver := NewQueryResolver(nil, mockGitBlobResolver, nil, NewCachedLocationResolver(db), nil) + resolver := NewGitBlobLSIFDataResolverQueryResolver( + mockAutoIndexingSvc, + mockUploadsService, + mockPolicyService, + mockGitserverClient, + mockGitBlobResolver, + observation.NewErrorCollector(), + ) - args := &gql.LSIFPagedQueryPositionArgs{ - LSIFQueryPositionArgs: gql.LSIFQueryPositionArgs{ + args := &LSIFPagedQueryPositionArgs{ + LSIFQueryPositionArgs: LSIFQueryPositionArgs{ Line: 10, Character: 15, }, - ConnectionArgs: graphqlutil.ConnectionArgs{}, + ConnectionArgs: ConnectionArgs{}, } if _, err := resolver.References(context.Background(), args); err != nil { @@ -130,19 +159,28 @@ func TestReferencesDefaultLimit(t *testing.T) { } func TestReferencesDefaultIllegalLimit(t *testing.T) { - logger := logtest.Scoped(t) - db := database.NewDB(logger, nil) + mockGitBlobResolver := NewMockGitBlobResolver() + mockAutoIndexingSvc := NewMockAutoIndexingService() + mockUploadsService := NewMockUploadsService() + mockPolicyService := NewMockPolicyService() + mockGitserverClient := NewMockGitserverClient() - mockGitBlobResolver := transportmocks.NewMockGitBlobLSIFDataResolver() - resolver := NewQueryResolver(nil, mockGitBlobResolver, nil, NewCachedLocationResolver(db), observation.NewErrorCollector()) + resolver := NewGitBlobLSIFDataResolverQueryResolver( + mockAutoIndexingSvc, + mockUploadsService, + mockPolicyService, + mockGitserverClient, + mockGitBlobResolver, + observation.NewErrorCollector(), + ) offset := int32(-1) - args := &gql.LSIFPagedQueryPositionArgs{ - LSIFQueryPositionArgs: gql.LSIFQueryPositionArgs{ + args := &LSIFPagedQueryPositionArgs{ + LSIFQueryPositionArgs: LSIFQueryPositionArgs{ Line: 10, Character: 15, }, - ConnectionArgs: graphqlutil.ConnectionArgs{First: &offset}, + ConnectionArgs: ConnectionArgs{First: &offset}, } if _, err := resolver.References(context.Background(), args); err != ErrIllegalLimit { @@ -151,15 +189,22 @@ func TestReferencesDefaultIllegalLimit(t *testing.T) { } func TestHover(t *testing.T) { - logger := logtest.Scoped(t) - db := database.NewDB(logger, nil) + mockGitBlobResolver := NewMockGitBlobResolver() + mockAutoIndexingSvc := NewMockAutoIndexingService() + mockUploadsService := NewMockUploadsService() + mockPolicyService := NewMockPolicyService() + mockGitserverClient := NewMockGitserverClient() - mockGitBlobResolver := transportmocks.NewMockGitBlobLSIFDataResolver() - mockGitBlobResolver.HoverFunc.SetDefaultReturn("text", shared.Range{}, true, nil) - mockResolver := resolvermocks.NewMockResolver() - resolver := NewQueryResolver(nil, mockGitBlobResolver, mockResolver, NewCachedLocationResolver(db), nil) - - args := &gql.LSIFQueryPositionArgs{Line: 10, Character: 15} + resolver := NewGitBlobLSIFDataResolverQueryResolver( + mockAutoIndexingSvc, + mockUploadsService, + mockPolicyService, + mockGitserverClient, + mockGitBlobResolver, + observation.NewErrorCollector(), + ) + mockGitBlobResolver.HoverFunc.SetDefaultReturn("text", types.Range{}, true, nil) + args := &LSIFQueryPositionArgs{Line: 10, Character: 15} if _, err := resolver.Hover(context.Background(), args); err != nil { t.Fatalf("unexpected error: %s", err) } @@ -176,15 +221,24 @@ func TestHover(t *testing.T) { } func TestDiagnostics(t *testing.T) { - logger := logtest.Scoped(t) - db := database.NewDB(logger, nil) + mockGitBlobResolver := NewMockGitBlobResolver() + mockAutoIndexingSvc := NewMockAutoIndexingService() + mockUploadsService := NewMockUploadsService() + mockPolicyService := NewMockPolicyService() + mockGitserverClient := NewMockGitserverClient() - mockGitBlobResolver := transportmocks.NewMockGitBlobLSIFDataResolver() - resolver := NewQueryResolver(nil, mockGitBlobResolver, nil, NewCachedLocationResolver(db), nil) + resolver := NewGitBlobLSIFDataResolverQueryResolver( + mockAutoIndexingSvc, + mockUploadsService, + mockPolicyService, + mockGitserverClient, + mockGitBlobResolver, + observation.NewErrorCollector(), + ) offset := int32(25) - args := &gql.LSIFDiagnosticsArgs{ - ConnectionArgs: graphqlutil.ConnectionArgs{First: &offset}, + args := &LSIFDiagnosticsArgs{ + ConnectionArgs: ConnectionArgs{First: &offset}, } if _, err := resolver.Diagnostics(context.Background(), args); err != nil { @@ -200,14 +254,23 @@ func TestDiagnostics(t *testing.T) { } func TestDiagnosticsDefaultLimit(t *testing.T) { - logger := logtest.Scoped(t) - db := database.NewDB(logger, nil) + mockGitBlobResolver := NewMockGitBlobResolver() + mockAutoIndexingSvc := NewMockAutoIndexingService() + mockUploadsService := NewMockUploadsService() + mockPolicyService := NewMockPolicyService() + mockGitserverClient := NewMockGitserverClient() - mockGitBlobResolver := transportmocks.NewMockGitBlobLSIFDataResolver() - resolver := NewQueryResolver(nil, mockGitBlobResolver, nil, NewCachedLocationResolver(db), nil) + resolver := NewGitBlobLSIFDataResolverQueryResolver( + mockAutoIndexingSvc, + mockUploadsService, + mockPolicyService, + mockGitserverClient, + mockGitBlobResolver, + observation.NewErrorCollector(), + ) - args := &gql.LSIFDiagnosticsArgs{ - ConnectionArgs: graphqlutil.ConnectionArgs{}, + args := &LSIFDiagnosticsArgs{ + ConnectionArgs: ConnectionArgs{}, } if _, err := resolver.Diagnostics(context.Background(), args); err != nil { @@ -223,15 +286,24 @@ func TestDiagnosticsDefaultLimit(t *testing.T) { } func TestDiagnosticsDefaultIllegalLimit(t *testing.T) { - logger := logtest.Scoped(t) - db := database.NewDB(logger, nil) + mockGitBlobResolver := NewMockGitBlobResolver() + mockAutoIndexingSvc := NewMockAutoIndexingService() + mockUploadsService := NewMockUploadsService() + mockPolicyService := NewMockPolicyService() + mockGitserverClient := NewMockGitserverClient() - mockGitBlobResolver := transportmocks.NewMockGitBlobLSIFDataResolver() - resolver := NewQueryResolver(nil, mockGitBlobResolver, nil, NewCachedLocationResolver(db), observation.NewErrorCollector()) + resolver := NewGitBlobLSIFDataResolverQueryResolver( + mockAutoIndexingSvc, + mockUploadsService, + mockPolicyService, + mockGitserverClient, + mockGitBlobResolver, + observation.NewErrorCollector(), + ) offset := int32(-1) - args := &gql.LSIFDiagnosticsArgs{ - ConnectionArgs: graphqlutil.ConnectionArgs{First: &offset}, + args := &LSIFDiagnosticsArgs{ + ConnectionArgs: ConnectionArgs{First: &offset}, } if _, err := resolver.Diagnostics(context.Background(), args); err != ErrIllegalLimit { diff --git a/internal/codeintel/codenav/transport/graphql/gitblob_resolver.go b/internal/codeintel/codenav/transport/graphql/gitblob_resolver.go index 07e2315d87d..6f73fce6fe6 100644 --- a/internal/codeintel/codenav/transport/graphql/gitblob_resolver.go +++ b/internal/codeintel/codenav/transport/graphql/gitblob_resolver.go @@ -9,26 +9,27 @@ import ( "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav" "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/lib/errors" ) -// GitBlobLSIFDataResolver is the main interface to bundle-related operations exposed to the GraphQL API. This +// GitBlobResolver is the main interface to bundle-related operations exposed to the GraphQL API. This // resolver consolidates the logic for bundle operations and is not itself concerned with GraphQL/API // specifics (auth, validation, marshaling, etc.). This resolver is wrapped by a symmetrics resolver // in this package's graphql subpackage, which is exposed directly by the API. -type GitBlobLSIFDataResolver interface { - LSIFUploads(ctx context.Context) ([]shared.Dump, error) +type GitBlobResolver interface { + LSIFUploads(ctx context.Context) ([]types.Dump, error) Ranges(ctx context.Context, startLine, endLine int) ([]shared.AdjustedCodeIntelligenceRange, error) - Stencil(ctx context.Context) ([]shared.Range, error) + Stencil(ctx context.Context) ([]types.Range, error) Diagnostics(ctx context.Context, limit int) ([]shared.DiagnosticAtUpload, int, error) - Hover(ctx context.Context, line, character int) (string, shared.Range, bool, error) - Definitions(ctx context.Context, line, character int) ([]shared.UploadLocation, error) - References(ctx context.Context, line, character, limit int, rawCursor string) ([]shared.UploadLocation, string, error) - Implementations(ctx context.Context, line, character, limit int, rawCursor string) ([]shared.UploadLocation, string, error) + Hover(ctx context.Context, line, character int) (string, types.Range, bool, error) + Definitions(ctx context.Context, line, character int) ([]types.UploadLocation, error) + References(ctx context.Context, line, character, limit int, rawCursor string) ([]types.UploadLocation, string, error) + Implementations(ctx context.Context, line, character, limit int, rawCursor string) ([]types.UploadLocation, string, error) } -type gitBlobLSIFDataResolver struct { +type gitBlobResolver struct { svc Service repositoryID int @@ -43,8 +44,8 @@ type gitBlobLSIFDataResolver struct { // NewGitBlobLSIFDataResolver create a new query resolver with the given services. The methods of this // struct return queries for the given repository, commit, and path, and will query only the // bundles associated with the given dump objects. -func NewGitBlobLSIFDataResolver(svc Service, repositoryID int, commit, path string, operations *operations, requestState codenav.RequestState) GitBlobLSIFDataResolver { - return &gitBlobLSIFDataResolver{ +func NewGitBlobResolver(svc Service, repositoryID int, commit, path string, operations *operations, requestState codenav.RequestState) GitBlobResolver { + return &gitBlobResolver{ svc: svc, repositoryID: repositoryID, @@ -58,7 +59,7 @@ func NewGitBlobLSIFDataResolver(svc Service, repositoryID int, commit, path stri } // Definitions returns the list of source locations that define the symbol at the given position. -func (r *gitBlobLSIFDataResolver) Definitions(ctx context.Context, line, character int) (_ []shared.UploadLocation, err error) { +func (r *gitBlobResolver) Definitions(ctx context.Context, line, character int) (_ []types.UploadLocation, err error) { args := shared.RequestArgs{RepositoryID: r.repositoryID, Commit: r.commit, Path: r.path, Line: line, Character: character} ctx, _, endObservation := observeResolver(ctx, &err, r.operations.definitions, time.Second, getObservationArgs(args)) defer endObservation() @@ -72,7 +73,7 @@ func (r *gitBlobLSIFDataResolver) Definitions(ctx context.Context, line, charact } // Diagnostics returns the diagnostics for documents with the given path prefix. -func (r *gitBlobLSIFDataResolver) Diagnostics(ctx context.Context, limit int) (diagnosticsAtUploads []shared.DiagnosticAtUpload, _ int, err error) { +func (r *gitBlobResolver) Diagnostics(ctx context.Context, limit int) (diagnosticsAtUploads []shared.DiagnosticAtUpload, _ int, err error) { args := shared.RequestArgs{RepositoryID: r.repositoryID, Commit: r.commit, Path: r.path, Limit: limit} ctx, _, endObservation := observeResolver(ctx, &err, r.operations.diagnostics, time.Second, getObservationArgs(args)) defer endObservation() @@ -86,21 +87,21 @@ func (r *gitBlobLSIFDataResolver) Diagnostics(ctx context.Context, limit int) (d } // Hover returns the hover text and range for the symbol at the given position. -func (r *gitBlobLSIFDataResolver) Hover(ctx context.Context, line, character int) (_ string, _ shared.Range, _ bool, err error) { +func (r *gitBlobResolver) Hover(ctx context.Context, line, character int) (_ string, _ types.Range, _ bool, err error) { args := shared.RequestArgs{RepositoryID: r.repositoryID, Commit: r.commit, Path: r.path, Line: line, Character: character} ctx, _, endObservation := observeResolver(ctx, &err, r.operations.hover, time.Second, getObservationArgs(args)) defer endObservation() hover, rng, ok, err := r.svc.GetHover(ctx, args, r.requestState) if err != nil { - return "", shared.Range{}, false, err + return "", types.Range{}, false, err } return hover, rng, ok, err } // Implementations returns the list of source locations that define the symbol at the given position. -func (r *gitBlobLSIFDataResolver) Implementations(ctx context.Context, line, character int, limit int, rawCursor string) (_ []shared.UploadLocation, nextCursor string, err error) { +func (r *gitBlobResolver) Implementations(ctx context.Context, line, character int, limit int, rawCursor string) (_ []types.UploadLocation, nextCursor string, err error) { args := shared.RequestArgs{RepositoryID: r.repositoryID, Commit: r.commit, Path: r.path, Line: line, Character: character, Limit: limit, RawCursor: rawCursor} ctx, _, endObservation := observeResolver(ctx, &err, r.operations.implementations, time.Second, getObservationArgs(args)) defer endObservation() @@ -128,7 +129,7 @@ func (r *gitBlobLSIFDataResolver) Implementations(ctx context.Context, line, cha // LSIFUploads returns the list of dbstore.Uploads for the store.Dumps determined to be applicable // for answering code-intel queries. -func (r *gitBlobLSIFDataResolver) LSIFUploads(ctx context.Context) (uploads []shared.Dump, err error) { +func (r *gitBlobResolver) LSIFUploads(ctx context.Context) (uploads []types.Dump, err error) { cacheUploads := r.requestState.GetCacheUploads() ids := make([]int, 0, len(cacheUploads)) for _, dump := range cacheUploads { @@ -143,7 +144,7 @@ func (r *gitBlobLSIFDataResolver) LSIFUploads(ctx context.Context) (uploads []sh // Ranges returns code intelligence for the ranges that fall within the given range of lines. These // results are partial and do not include references outside the current file, or any location that // requires cross-linking of bundles (cross-repo or cross-root). -func (r *gitBlobLSIFDataResolver) Ranges(ctx context.Context, startLine, endLine int) (adjustedRanges []shared.AdjustedCodeIntelligenceRange, err error) { +func (r *gitBlobResolver) Ranges(ctx context.Context, startLine, endLine int) (adjustedRanges []shared.AdjustedCodeIntelligenceRange, err error) { args := shared.RequestArgs{RepositoryID: r.repositoryID, Commit: r.commit, Path: r.path} ctx, _, endObservation := observeResolver(ctx, &err, r.operations.ranges, time.Second, observation.Args{ LogFields: []log.Field{ @@ -165,7 +166,7 @@ func (r *gitBlobLSIFDataResolver) Ranges(ctx context.Context, startLine, endLine } // References returns the list of source locations that reference the symbol at the given position. -func (r *gitBlobLSIFDataResolver) References(ctx context.Context, line, character, limit int, rawCursor string) (_ []shared.UploadLocation, nextCursor string, err error) { +func (r *gitBlobResolver) References(ctx context.Context, line, character, limit int, rawCursor string) (_ []types.UploadLocation, nextCursor string, err error) { args := shared.RequestArgs{RepositoryID: r.repositoryID, Commit: r.commit, Path: r.path, Line: line, Character: character, Limit: limit, RawCursor: rawCursor} ctx, _, endObservation := observeResolver(ctx, &err, r.operations.references, time.Second, getObservationArgs(args)) defer endObservation() @@ -192,7 +193,7 @@ func (r *gitBlobLSIFDataResolver) References(ctx context.Context, line, characte } // Stencil returns all ranges within a single document. -func (r *gitBlobLSIFDataResolver) Stencil(ctx context.Context) (adjustedRanges []shared.Range, err error) { +func (r *gitBlobResolver) Stencil(ctx context.Context) (adjustedRanges []types.Range, err error) { args := shared.RequestArgs{RepositoryID: r.repositoryID, Commit: r.commit, Path: r.path} ctx, _, endObservation := observeResolver(ctx, &err, r.operations.stencil, time.Second, getObservationArgs(args)) defer endObservation() diff --git a/internal/codeintel/codenav/transport/graphql/gitblob_tree_lsif_data_resolver.go b/internal/codeintel/codenav/transport/graphql/gitblob_tree_lsif_data_resolver.go new file mode 100644 index 00000000000..65a6ee776c0 --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/gitblob_tree_lsif_data_resolver.go @@ -0,0 +1,12 @@ +package graphql + +import ( + "context" + + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" +) + +type GitTreeLSIFDataResolver interface { + LSIFUploads(ctx context.Context) ([]sharedresolvers.LSIFUploadResolver, error) + Diagnostics(ctx context.Context, args *LSIFDiagnosticsArgs) (DiagnosticConnectionResolver, error) +} diff --git a/internal/codeintel/codenav/transport/graphql/hover.go b/internal/codeintel/codenav/transport/graphql/hover.go new file mode 100644 index 00000000000..4742c35d02d --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/hover.go @@ -0,0 +1,25 @@ +package graphql + +import ( + "github.com/sourcegraph/go-lsp" +) + +type HoverResolver interface { + Markdown() Markdown + Range() RangeResolver +} + +type hoverResolver struct { + text string + lspRange lsp.Range +} + +func NewHoverResolver(text string, lspRange lsp.Range) HoverResolver { + return &hoverResolver{ + text: text, + lspRange: lspRange, + } +} + +func (r *hoverResolver) Markdown() Markdown { return Markdown(r.text) } +func (r *hoverResolver) Range() RangeResolver { return NewRangeResolver(r.lspRange) } diff --git a/internal/codeintel/codenav/transport/graphql/iface.go b/internal/codeintel/codenav/transport/graphql/iface.go index b89fa55aed7..d8ea292c26f 100644 --- a/internal/codeintel/codenav/transport/graphql/iface.go +++ b/internal/codeintel/codenav/transport/graphql/iface.go @@ -2,6 +2,7 @@ package graphql import ( "context" + "time" "github.com/sourcegraph/go-diff/diff" @@ -10,27 +11,25 @@ import ( "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav" "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/gitserver" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/database" + "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" ) type Service interface { - GetHover(ctx context.Context, args shared.RequestArgs, requestState codenav.RequestState) (_ string, _ shared.Range, _ bool, err error) - GetReferences(ctx context.Context, args shared.RequestArgs, requestState codenav.RequestState, cursor shared.ReferencesCursor) (_ []shared.UploadLocation, nextCursor shared.ReferencesCursor, err error) - GetImplementations(ctx context.Context, args shared.RequestArgs, requestState codenav.RequestState, cursor shared.ImplementationsCursor) (_ []shared.UploadLocation, nextCursor shared.ImplementationsCursor, err error) - GetDefinitions(ctx context.Context, args shared.RequestArgs, requestState codenav.RequestState) (_ []shared.UploadLocation, err error) + GetHover(ctx context.Context, args shared.RequestArgs, requestState codenav.RequestState) (_ string, _ types.Range, _ bool, err error) + GetReferences(ctx context.Context, args shared.RequestArgs, requestState codenav.RequestState, cursor shared.ReferencesCursor) (_ []types.UploadLocation, nextCursor shared.ReferencesCursor, err error) + GetImplementations(ctx context.Context, args shared.RequestArgs, requestState codenav.RequestState, cursor shared.ImplementationsCursor) (_ []types.UploadLocation, nextCursor shared.ImplementationsCursor, err error) + GetDefinitions(ctx context.Context, args shared.RequestArgs, requestState codenav.RequestState) (_ []types.UploadLocation, err error) GetDiagnostics(ctx context.Context, args shared.RequestArgs, requestState codenav.RequestState) (diagnosticsAtUploads []shared.DiagnosticAtUpload, _ int, err error) GetRanges(ctx context.Context, args shared.RequestArgs, requestState codenav.RequestState, startLine, endLine int) (adjustedRanges []shared.AdjustedCodeIntelligenceRange, err error) - GetStencil(ctx context.Context, args shared.RequestArgs, requestState codenav.RequestState) (adjustedRanges []shared.Range, err error) - - // Symbols client - GetSupportedByCtags(ctx context.Context, filepath string, repoName api.RepoName) (bool, string, error) - - // Language Support - GetLanguagesRequestedBy(ctx context.Context, userID int) (_ []string, err error) - SetRequestLanguageSupport(ctx context.Context, userID int, language string) (err error) + GetStencil(ctx context.Context, args shared.RequestArgs, requestState codenav.RequestState) (adjustedRanges []types.Range, err error) // Uploads Service - GetDumpsByIDs(ctx context.Context, ids []int) (_ []shared.Dump, err error) - GetClosestDumpsForBlob(ctx context.Context, repositoryID int, commit, path string, exactPath bool, indexer string) (_ []shared.Dump, err error) + GetDumpsByIDs(ctx context.Context, ids []int) (_ []types.Dump, err error) + GetClosestDumpsForBlob(ctx context.Context, repositoryID int, commit, path string, exactPath bool, indexer string) (_ []types.Dump, err error) + + GetUnsafeDB() database.DB } type GitserverClient interface { @@ -38,6 +37,23 @@ type GitserverClient interface { DiffPath(ctx context.Context, checker authz.SubRepoPermissionChecker, repo api.RepoName, sourceCommit, targetCommit, path string) ([]*diff.Hunk, error) } -type AutoindexingService interface { +type AutoIndexingService interface { + GetIndexes(ctx context.Context, opts types.GetIndexesOptions) (_ []types.Index, _ int, err error) + GetIndexByID(ctx context.Context, id int) (_ types.Index, _ bool, err error) + GetIndexesByIDs(ctx context.Context, ids ...int) (_ []types.Index, err error) + GetUnsafeDB() database.DB + GetListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) (_ []*gitdomain.Tag, err error) QueueRepoRev(ctx context.Context, repositoryID int, rev string) error } + +type UploadsService interface { + GetUploads(ctx context.Context, opts types.GetUploadsOptions) (uploads []types.Upload, totalCount int, err error) + GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []types.UploadLog, err error) + GetListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) (_ []*gitdomain.Tag, err error) + GetUploadDocumentsForPath(ctx context.Context, bundleID int, pathPattern string) ([]string, int, error) + GetUploadsByIDs(ctx context.Context, ids ...int) (_ []types.Upload, err error) +} + +type PolicyService interface { + GetRetentionPolicyOverview(ctx context.Context, upload types.Upload, matchesOnly bool, first int, after int64, query string, now time.Time) (matches []types.RetentionPolicyMatchCandidate, totalCount int, err error) +} diff --git a/internal/codeintel/codenav/transport/graphql/location_resolver.go b/internal/codeintel/codenav/transport/graphql/location_resolver.go new file mode 100644 index 00000000000..e6136d9e90b --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/location_resolver.go @@ -0,0 +1,60 @@ +package graphql + +import ( + "context" + + "github.com/sourcegraph/go-lsp" + + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" +) + +type LocationResolver interface { + Resource() *sharedresolvers.GitTreeEntryResolver + Range() *rangeResolver + URL(ctx context.Context) (string, error) + CanonicalURL() string +} + +type locationResolver struct { + resource *sharedresolvers.GitTreeEntryResolver + lspRange *lsp.Range +} + +var _ LocationResolver = &locationResolver{} + +func NewLocationResolver(resource *sharedresolvers.GitTreeEntryResolver, lspRange *lsp.Range) LocationResolver { + return &locationResolver{ + resource: resource, + lspRange: lspRange, + } +} + +func (r *locationResolver) Resource() *sharedresolvers.GitTreeEntryResolver { return r.resource } + +func (r *locationResolver) Range() *rangeResolver { + if r.lspRange == nil { + return nil + } + return &rangeResolver{*r.lspRange} +} + +func (r *locationResolver) URL(ctx context.Context) (string, error) { + url, err := r.resource.URL(ctx) + if err != nil { + return "", err + } + return r.urlPath(url), nil +} + +func (r *locationResolver) CanonicalURL() string { + url := r.resource.CanonicalURL() + return r.urlPath(url) +} + +func (r *locationResolver) urlPath(prefix string) string { + url := prefix + if r.lspRange != nil { + url += "?L" + r.Range().urlFragment() + } + return url +} diff --git a/internal/codeintel/codenav/transport/graphql/location_resolver_connection.go b/internal/codeintel/codenav/transport/graphql/location_resolver_connection.go new file mode 100644 index 00000000000..00e1c0ed9f1 --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/location_resolver_connection.go @@ -0,0 +1,35 @@ +package graphql + +import ( + "context" + + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" +) + +type LocationConnectionResolver interface { + Nodes(ctx context.Context) ([]LocationResolver, error) + PageInfo(ctx context.Context) (*PageInfo, error) +} + +type locationConnectionResolver struct { + locations []types.UploadLocation + cursor *string + locationResolver *sharedresolvers.CachedLocationResolver +} + +func NewLocationConnectionResolver(locations []types.UploadLocation, cursor *string, locationResolver *sharedresolvers.CachedLocationResolver) LocationConnectionResolver { + return &locationConnectionResolver{ + locations: locations, + cursor: cursor, + locationResolver: locationResolver, + } +} + +func (r *locationConnectionResolver) Nodes(ctx context.Context) ([]LocationResolver, error) { + return resolveLocations(ctx, r.locationResolver, r.locations) +} + +func (r *locationConnectionResolver) PageInfo(ctx context.Context) (*PageInfo, error) { + return EncodeCursor(r.cursor), nil +} diff --git a/internal/codeintel/codenav/transport/graphql/markdown.go b/internal/codeintel/codenav/transport/graphql/markdown.go new file mode 100644 index 00000000000..459e458a8cd --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/markdown.go @@ -0,0 +1,41 @@ +package graphql + +import ( + "regexp" //nolint:depguard // bluemonday requires this pkg + "sync" + + "github.com/microcosm-cc/bluemonday" + gfm "github.com/shurcooL/github_flavored_markdown" +) + +type Markdown string + +func (m Markdown) Text() string { + return string(m) +} + +func (m Markdown) HTML() string { + return render(string(m)) +} + +var ( + once sync.Once + policy *bluemonday.Policy +) + +// Render renders Markdown content into sanitized HTML that is safe to render anywhere. +func render(content string) string { + once.Do(func() { + policy = bluemonday.UGCPolicy() + policy.AllowAttrs("name").Matching(bluemonday.SpaceSeparatedTokens).OnElements("a") + policy.AllowAttrs("rel").Matching(regexp.MustCompile(`^nofollow$`)).OnElements("a") + policy.AllowAttrs("class").Matching(regexp.MustCompile(`^anchor$`)).OnElements("a") + policy.AllowAttrs("aria-hidden").Matching(regexp.MustCompile(`^true$`)).OnElements("a") + policy.AllowAttrs("type").Matching(regexp.MustCompile(`^checkbox$`)).OnElements("input") + policy.AllowAttrs("checked", "disabled").Matching(regexp.MustCompile(`^$`)).OnElements("input") + policy.AllowAttrs("class").Matching(regexp.MustCompile("^language-[a-zA-Z0-9]+$")).OnElements("code") + }) + + unsafeHTML := gfm.Markdown([]byte(content)) + return string(policy.SanitizeBytes(unsafeHTML)) +} diff --git a/internal/codeintel/codenav/transport/graphql/mocks_test.go b/internal/codeintel/codenav/transport/graphql/mocks_test.go new file mode 100644 index 00000000000..88ca75540f8 --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/mocks_test.go @@ -0,0 +1,3038 @@ +// Code generated by go-mockgen 1.3.4; DO NOT EDIT. +// +// This file was generated by running `sg generate` (or `go-mockgen`) at the root of +// this repository. To add additional mocks to this or another package, add a new entry +// to the mockgen.yaml file in the root of this repository. + +package graphql + +import ( + "context" + "sync" + "time" + + diff "github.com/sourcegraph/go-diff/diff" + api "github.com/sourcegraph/sourcegraph/internal/api" + authz "github.com/sourcegraph/sourcegraph/internal/authz" + shared "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" + gitserver "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/gitserver" + types "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + database "github.com/sourcegraph/sourcegraph/internal/database" + gitdomain "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" +) + +// MockAutoIndexingService is a mock implementation of the +// AutoIndexingService interface (from the package +// github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql) +// used for unit testing. +type MockAutoIndexingService struct { + // GetIndexByIDFunc is an instance of a mock function object controlling + // the behavior of the method GetIndexByID. + GetIndexByIDFunc *AutoIndexingServiceGetIndexByIDFunc + // GetIndexesFunc is an instance of a mock function object controlling + // the behavior of the method GetIndexes. + GetIndexesFunc *AutoIndexingServiceGetIndexesFunc + // GetIndexesByIDsFunc is an instance of a mock function object + // controlling the behavior of the method GetIndexesByIDs. + GetIndexesByIDsFunc *AutoIndexingServiceGetIndexesByIDsFunc + // GetListTagsFunc is an instance of a mock function object controlling + // the behavior of the method GetListTags. + GetListTagsFunc *AutoIndexingServiceGetListTagsFunc + // GetUnsafeDBFunc is an instance of a mock function object controlling + // the behavior of the method GetUnsafeDB. + GetUnsafeDBFunc *AutoIndexingServiceGetUnsafeDBFunc + // QueueRepoRevFunc is an instance of a mock function object controlling + // the behavior of the method QueueRepoRev. + QueueRepoRevFunc *AutoIndexingServiceQueueRepoRevFunc +} + +// NewMockAutoIndexingService creates a new mock of the AutoIndexingService +// interface. All methods return zero values for all results, unless +// overwritten. +func NewMockAutoIndexingService() *MockAutoIndexingService { + return &MockAutoIndexingService{ + GetIndexByIDFunc: &AutoIndexingServiceGetIndexByIDFunc{ + defaultHook: func(context.Context, int) (r0 types.Index, r1 bool, r2 error) { + return + }, + }, + GetIndexesFunc: &AutoIndexingServiceGetIndexesFunc{ + defaultHook: func(context.Context, types.GetIndexesOptions) (r0 []types.Index, r1 int, r2 error) { + return + }, + }, + GetIndexesByIDsFunc: &AutoIndexingServiceGetIndexesByIDsFunc{ + defaultHook: func(context.Context, ...int) (r0 []types.Index, r1 error) { + return + }, + }, + GetListTagsFunc: &AutoIndexingServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) (r0 []*gitdomain.Tag, r1 error) { + return + }, + }, + GetUnsafeDBFunc: &AutoIndexingServiceGetUnsafeDBFunc{ + defaultHook: func() (r0 database.DB) { + return + }, + }, + QueueRepoRevFunc: &AutoIndexingServiceQueueRepoRevFunc{ + defaultHook: func(context.Context, int, string) (r0 error) { + return + }, + }, + } +} + +// NewStrictMockAutoIndexingService creates a new mock of the +// AutoIndexingService interface. All methods panic on invocation, unless +// overwritten. +func NewStrictMockAutoIndexingService() *MockAutoIndexingService { + return &MockAutoIndexingService{ + GetIndexByIDFunc: &AutoIndexingServiceGetIndexByIDFunc{ + defaultHook: func(context.Context, int) (types.Index, bool, error) { + panic("unexpected invocation of MockAutoIndexingService.GetIndexByID") + }, + }, + GetIndexesFunc: &AutoIndexingServiceGetIndexesFunc{ + defaultHook: func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + panic("unexpected invocation of MockAutoIndexingService.GetIndexes") + }, + }, + GetIndexesByIDsFunc: &AutoIndexingServiceGetIndexesByIDsFunc{ + defaultHook: func(context.Context, ...int) ([]types.Index, error) { + panic("unexpected invocation of MockAutoIndexingService.GetIndexesByIDs") + }, + }, + GetListTagsFunc: &AutoIndexingServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + panic("unexpected invocation of MockAutoIndexingService.GetListTags") + }, + }, + GetUnsafeDBFunc: &AutoIndexingServiceGetUnsafeDBFunc{ + defaultHook: func() database.DB { + panic("unexpected invocation of MockAutoIndexingService.GetUnsafeDB") + }, + }, + QueueRepoRevFunc: &AutoIndexingServiceQueueRepoRevFunc{ + defaultHook: func(context.Context, int, string) error { + panic("unexpected invocation of MockAutoIndexingService.QueueRepoRev") + }, + }, + } +} + +// NewMockAutoIndexingServiceFrom creates a new mock of the +// MockAutoIndexingService interface. All methods delegate to the given +// implementation, unless overwritten. +func NewMockAutoIndexingServiceFrom(i AutoIndexingService) *MockAutoIndexingService { + return &MockAutoIndexingService{ + GetIndexByIDFunc: &AutoIndexingServiceGetIndexByIDFunc{ + defaultHook: i.GetIndexByID, + }, + GetIndexesFunc: &AutoIndexingServiceGetIndexesFunc{ + defaultHook: i.GetIndexes, + }, + GetIndexesByIDsFunc: &AutoIndexingServiceGetIndexesByIDsFunc{ + defaultHook: i.GetIndexesByIDs, + }, + GetListTagsFunc: &AutoIndexingServiceGetListTagsFunc{ + defaultHook: i.GetListTags, + }, + GetUnsafeDBFunc: &AutoIndexingServiceGetUnsafeDBFunc{ + defaultHook: i.GetUnsafeDB, + }, + QueueRepoRevFunc: &AutoIndexingServiceQueueRepoRevFunc{ + defaultHook: i.QueueRepoRev, + }, + } +} + +// AutoIndexingServiceGetIndexByIDFunc describes the behavior when the +// GetIndexByID method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetIndexByIDFunc struct { + defaultHook func(context.Context, int) (types.Index, bool, error) + hooks []func(context.Context, int) (types.Index, bool, error) + history []AutoIndexingServiceGetIndexByIDFuncCall + mutex sync.Mutex +} + +// GetIndexByID delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetIndexByID(v0 context.Context, v1 int) (types.Index, bool, error) { + r0, r1, r2 := m.GetIndexByIDFunc.nextHook()(v0, v1) + m.GetIndexByIDFunc.appendCall(AutoIndexingServiceGetIndexByIDFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the GetIndexByID method +// of the parent MockAutoIndexingService instance is invoked and the hook +// queue is empty. +func (f *AutoIndexingServiceGetIndexByIDFunc) SetDefaultHook(hook func(context.Context, int) (types.Index, bool, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetIndexByID method of the parent MockAutoIndexingService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *AutoIndexingServiceGetIndexByIDFunc) PushHook(hook func(context.Context, int) (types.Index, bool, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetIndexByIDFunc) SetDefaultReturn(r0 types.Index, r1 bool, r2 error) { + f.SetDefaultHook(func(context.Context, int) (types.Index, bool, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetIndexByIDFunc) PushReturn(r0 types.Index, r1 bool, r2 error) { + f.PushHook(func(context.Context, int) (types.Index, bool, error) { + return r0, r1, r2 + }) +} + +func (f *AutoIndexingServiceGetIndexByIDFunc) nextHook() func(context.Context, int) (types.Index, bool, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetIndexByIDFunc) appendCall(r0 AutoIndexingServiceGetIndexByIDFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetIndexByIDFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetIndexByIDFunc) History() []AutoIndexingServiceGetIndexByIDFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetIndexByIDFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetIndexByIDFuncCall is an object that describes an +// invocation of method GetIndexByID on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetIndexByIDFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 types.Index + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 bool + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetIndexByIDFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetIndexByIDFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// AutoIndexingServiceGetIndexesFunc describes the behavior when the +// GetIndexes method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetIndexesFunc struct { + defaultHook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) + hooks []func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) + history []AutoIndexingServiceGetIndexesFuncCall + mutex sync.Mutex +} + +// GetIndexes delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetIndexes(v0 context.Context, v1 types.GetIndexesOptions) ([]types.Index, int, error) { + r0, r1, r2 := m.GetIndexesFunc.nextHook()(v0, v1) + m.GetIndexesFunc.appendCall(AutoIndexingServiceGetIndexesFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the GetIndexes method of +// the parent MockAutoIndexingService instance is invoked and the hook queue +// is empty. +func (f *AutoIndexingServiceGetIndexesFunc) SetDefaultHook(hook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetIndexes method of the parent MockAutoIndexingService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *AutoIndexingServiceGetIndexesFunc) PushHook(hook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetIndexesFunc) SetDefaultReturn(r0 []types.Index, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetIndexesFunc) PushReturn(r0 []types.Index, r1 int, r2 error) { + f.PushHook(func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + return r0, r1, r2 + }) +} + +func (f *AutoIndexingServiceGetIndexesFunc) nextHook() func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetIndexesFunc) appendCall(r0 AutoIndexingServiceGetIndexesFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetIndexesFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetIndexesFunc) History() []AutoIndexingServiceGetIndexesFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetIndexesFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetIndexesFuncCall is an object that describes an +// invocation of method GetIndexes on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetIndexesFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 types.GetIndexesOptions + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Index + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetIndexesFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetIndexesFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// AutoIndexingServiceGetIndexesByIDsFunc describes the behavior when the +// GetIndexesByIDs method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetIndexesByIDsFunc struct { + defaultHook func(context.Context, ...int) ([]types.Index, error) + hooks []func(context.Context, ...int) ([]types.Index, error) + history []AutoIndexingServiceGetIndexesByIDsFuncCall + mutex sync.Mutex +} + +// GetIndexesByIDs delegates to the next hook function in the queue and +// stores the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetIndexesByIDs(v0 context.Context, v1 ...int) ([]types.Index, error) { + r0, r1 := m.GetIndexesByIDsFunc.nextHook()(v0, v1...) + m.GetIndexesByIDsFunc.appendCall(AutoIndexingServiceGetIndexesByIDsFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetIndexesByIDs +// method of the parent MockAutoIndexingService instance is invoked and the +// hook queue is empty. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]types.Index, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetIndexesByIDs method of the parent MockAutoIndexingService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) PushHook(hook func(context.Context, ...int) ([]types.Index, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) SetDefaultReturn(r0 []types.Index, r1 error) { + f.SetDefaultHook(func(context.Context, ...int) ([]types.Index, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) PushReturn(r0 []types.Index, r1 error) { + f.PushHook(func(context.Context, ...int) ([]types.Index, error) { + return r0, r1 + }) +} + +func (f *AutoIndexingServiceGetIndexesByIDsFunc) nextHook() func(context.Context, ...int) ([]types.Index, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetIndexesByIDsFunc) appendCall(r0 AutoIndexingServiceGetIndexesByIDsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetIndexesByIDsFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) History() []AutoIndexingServiceGetIndexesByIDsFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetIndexesByIDsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetIndexesByIDsFuncCall is an object that describes an +// invocation of method GetIndexesByIDs on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetIndexesByIDsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg1 []int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Index + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c AutoIndexingServiceGetIndexesByIDsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg1 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetIndexesByIDsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// AutoIndexingServiceGetListTagsFunc describes the behavior when the +// GetListTags method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetListTagsFunc struct { + defaultHook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + hooks []func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + history []AutoIndexingServiceGetListTagsFuncCall + mutex sync.Mutex +} + +// GetListTags delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetListTags(v0 context.Context, v1 api.RepoName, v2 ...string) ([]*gitdomain.Tag, error) { + r0, r1 := m.GetListTagsFunc.nextHook()(v0, v1, v2...) + m.GetListTagsFunc.appendCall(AutoIndexingServiceGetListTagsFuncCall{v0, v1, v2, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetListTags method +// of the parent MockAutoIndexingService instance is invoked and the hook +// queue is empty. +func (f *AutoIndexingServiceGetListTagsFunc) SetDefaultHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetListTags method of the parent MockAutoIndexingService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *AutoIndexingServiceGetListTagsFunc) PushHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetListTagsFunc) SetDefaultReturn(r0 []*gitdomain.Tag, r1 error) { + f.SetDefaultHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetListTagsFunc) PushReturn(r0 []*gitdomain.Tag, r1 error) { + f.PushHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +func (f *AutoIndexingServiceGetListTagsFunc) nextHook() func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetListTagsFunc) appendCall(r0 AutoIndexingServiceGetListTagsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetListTagsFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetListTagsFunc) History() []AutoIndexingServiceGetListTagsFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetListTagsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetListTagsFuncCall is an object that describes an +// invocation of method GetListTags on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetListTagsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 api.RepoName + // Arg2 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg2 []string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []*gitdomain.Tag + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c AutoIndexingServiceGetListTagsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg2 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0, c.Arg1}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetListTagsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// AutoIndexingServiceGetUnsafeDBFunc describes the behavior when the +// GetUnsafeDB method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetUnsafeDBFunc struct { + defaultHook func() database.DB + hooks []func() database.DB + history []AutoIndexingServiceGetUnsafeDBFuncCall + mutex sync.Mutex +} + +// GetUnsafeDB delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetUnsafeDB() database.DB { + r0 := m.GetUnsafeDBFunc.nextHook()() + m.GetUnsafeDBFunc.appendCall(AutoIndexingServiceGetUnsafeDBFuncCall{r0}) + return r0 +} + +// SetDefaultHook sets function that is called when the GetUnsafeDB method +// of the parent MockAutoIndexingService instance is invoked and the hook +// queue is empty. +func (f *AutoIndexingServiceGetUnsafeDBFunc) SetDefaultHook(hook func() database.DB) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUnsafeDB method of the parent MockAutoIndexingService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *AutoIndexingServiceGetUnsafeDBFunc) PushHook(hook func() database.DB) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetUnsafeDBFunc) SetDefaultReturn(r0 database.DB) { + f.SetDefaultHook(func() database.DB { + return r0 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetUnsafeDBFunc) PushReturn(r0 database.DB) { + f.PushHook(func() database.DB { + return r0 + }) +} + +func (f *AutoIndexingServiceGetUnsafeDBFunc) nextHook() func() database.DB { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetUnsafeDBFunc) appendCall(r0 AutoIndexingServiceGetUnsafeDBFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetUnsafeDBFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetUnsafeDBFunc) History() []AutoIndexingServiceGetUnsafeDBFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetUnsafeDBFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetUnsafeDBFuncCall is an object that describes an +// invocation of method GetUnsafeDB on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetUnsafeDBFuncCall struct { + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 database.DB +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetUnsafeDBFuncCall) Args() []interface{} { + return []interface{}{} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetUnsafeDBFuncCall) Results() []interface{} { + return []interface{}{c.Result0} +} + +// AutoIndexingServiceQueueRepoRevFunc describes the behavior when the +// QueueRepoRev method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceQueueRepoRevFunc struct { + defaultHook func(context.Context, int, string) error + hooks []func(context.Context, int, string) error + history []AutoIndexingServiceQueueRepoRevFuncCall + mutex sync.Mutex +} + +// QueueRepoRev delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) QueueRepoRev(v0 context.Context, v1 int, v2 string) error { + r0 := m.QueueRepoRevFunc.nextHook()(v0, v1, v2) + m.QueueRepoRevFunc.appendCall(AutoIndexingServiceQueueRepoRevFuncCall{v0, v1, v2, r0}) + return r0 +} + +// SetDefaultHook sets function that is called when the QueueRepoRev method +// of the parent MockAutoIndexingService instance is invoked and the hook +// queue is empty. +func (f *AutoIndexingServiceQueueRepoRevFunc) SetDefaultHook(hook func(context.Context, int, string) error) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// QueueRepoRev method of the parent MockAutoIndexingService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *AutoIndexingServiceQueueRepoRevFunc) PushHook(hook func(context.Context, int, string) error) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceQueueRepoRevFunc) SetDefaultReturn(r0 error) { + f.SetDefaultHook(func(context.Context, int, string) error { + return r0 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceQueueRepoRevFunc) PushReturn(r0 error) { + f.PushHook(func(context.Context, int, string) error { + return r0 + }) +} + +func (f *AutoIndexingServiceQueueRepoRevFunc) nextHook() func(context.Context, int, string) error { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceQueueRepoRevFunc) appendCall(r0 AutoIndexingServiceQueueRepoRevFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceQueueRepoRevFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceQueueRepoRevFunc) History() []AutoIndexingServiceQueueRepoRevFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceQueueRepoRevFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceQueueRepoRevFuncCall is an object that describes an +// invocation of method QueueRepoRev on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceQueueRepoRevFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceQueueRepoRevFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceQueueRepoRevFuncCall) Results() []interface{} { + return []interface{}{c.Result0} +} + +// MockGitBlobResolver is a mock implementation of the GitBlobResolver +// interface (from the package +// github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql) +// used for unit testing. +type MockGitBlobResolver struct { + // DefinitionsFunc is an instance of a mock function object controlling + // the behavior of the method Definitions. + DefinitionsFunc *GitBlobResolverDefinitionsFunc + // DiagnosticsFunc is an instance of a mock function object controlling + // the behavior of the method Diagnostics. + DiagnosticsFunc *GitBlobResolverDiagnosticsFunc + // HoverFunc is an instance of a mock function object controlling the + // behavior of the method Hover. + HoverFunc *GitBlobResolverHoverFunc + // ImplementationsFunc is an instance of a mock function object + // controlling the behavior of the method Implementations. + ImplementationsFunc *GitBlobResolverImplementationsFunc + // LSIFUploadsFunc is an instance of a mock function object controlling + // the behavior of the method LSIFUploads. + LSIFUploadsFunc *GitBlobResolverLSIFUploadsFunc + // RangesFunc is an instance of a mock function object controlling the + // behavior of the method Ranges. + RangesFunc *GitBlobResolverRangesFunc + // ReferencesFunc is an instance of a mock function object controlling + // the behavior of the method References. + ReferencesFunc *GitBlobResolverReferencesFunc + // StencilFunc is an instance of a mock function object controlling the + // behavior of the method Stencil. + StencilFunc *GitBlobResolverStencilFunc +} + +// NewMockGitBlobResolver creates a new mock of the GitBlobResolver +// interface. All methods return zero values for all results, unless +// overwritten. +func NewMockGitBlobResolver() *MockGitBlobResolver { + return &MockGitBlobResolver{ + DefinitionsFunc: &GitBlobResolverDefinitionsFunc{ + defaultHook: func(context.Context, int, int) (r0 []types.UploadLocation, r1 error) { + return + }, + }, + DiagnosticsFunc: &GitBlobResolverDiagnosticsFunc{ + defaultHook: func(context.Context, int) (r0 []shared.DiagnosticAtUpload, r1 int, r2 error) { + return + }, + }, + HoverFunc: &GitBlobResolverHoverFunc{ + defaultHook: func(context.Context, int, int) (r0 string, r1 types.Range, r2 bool, r3 error) { + return + }, + }, + ImplementationsFunc: &GitBlobResolverImplementationsFunc{ + defaultHook: func(context.Context, int, int, int, string) (r0 []types.UploadLocation, r1 string, r2 error) { + return + }, + }, + LSIFUploadsFunc: &GitBlobResolverLSIFUploadsFunc{ + defaultHook: func(context.Context) (r0 []types.Dump, r1 error) { + return + }, + }, + RangesFunc: &GitBlobResolverRangesFunc{ + defaultHook: func(context.Context, int, int) (r0 []shared.AdjustedCodeIntelligenceRange, r1 error) { + return + }, + }, + ReferencesFunc: &GitBlobResolverReferencesFunc{ + defaultHook: func(context.Context, int, int, int, string) (r0 []types.UploadLocation, r1 string, r2 error) { + return + }, + }, + StencilFunc: &GitBlobResolverStencilFunc{ + defaultHook: func(context.Context) (r0 []types.Range, r1 error) { + return + }, + }, + } +} + +// NewStrictMockGitBlobResolver creates a new mock of the GitBlobResolver +// interface. All methods panic on invocation, unless overwritten. +func NewStrictMockGitBlobResolver() *MockGitBlobResolver { + return &MockGitBlobResolver{ + DefinitionsFunc: &GitBlobResolverDefinitionsFunc{ + defaultHook: func(context.Context, int, int) ([]types.UploadLocation, error) { + panic("unexpected invocation of MockGitBlobResolver.Definitions") + }, + }, + DiagnosticsFunc: &GitBlobResolverDiagnosticsFunc{ + defaultHook: func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error) { + panic("unexpected invocation of MockGitBlobResolver.Diagnostics") + }, + }, + HoverFunc: &GitBlobResolverHoverFunc{ + defaultHook: func(context.Context, int, int) (string, types.Range, bool, error) { + panic("unexpected invocation of MockGitBlobResolver.Hover") + }, + }, + ImplementationsFunc: &GitBlobResolverImplementationsFunc{ + defaultHook: func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error) { + panic("unexpected invocation of MockGitBlobResolver.Implementations") + }, + }, + LSIFUploadsFunc: &GitBlobResolverLSIFUploadsFunc{ + defaultHook: func(context.Context) ([]types.Dump, error) { + panic("unexpected invocation of MockGitBlobResolver.LSIFUploads") + }, + }, + RangesFunc: &GitBlobResolverRangesFunc{ + defaultHook: func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error) { + panic("unexpected invocation of MockGitBlobResolver.Ranges") + }, + }, + ReferencesFunc: &GitBlobResolverReferencesFunc{ + defaultHook: func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error) { + panic("unexpected invocation of MockGitBlobResolver.References") + }, + }, + StencilFunc: &GitBlobResolverStencilFunc{ + defaultHook: func(context.Context) ([]types.Range, error) { + panic("unexpected invocation of MockGitBlobResolver.Stencil") + }, + }, + } +} + +// NewMockGitBlobResolverFrom creates a new mock of the MockGitBlobResolver +// interface. All methods delegate to the given implementation, unless +// overwritten. +func NewMockGitBlobResolverFrom(i GitBlobResolver) *MockGitBlobResolver { + return &MockGitBlobResolver{ + DefinitionsFunc: &GitBlobResolverDefinitionsFunc{ + defaultHook: i.Definitions, + }, + DiagnosticsFunc: &GitBlobResolverDiagnosticsFunc{ + defaultHook: i.Diagnostics, + }, + HoverFunc: &GitBlobResolverHoverFunc{ + defaultHook: i.Hover, + }, + ImplementationsFunc: &GitBlobResolverImplementationsFunc{ + defaultHook: i.Implementations, + }, + LSIFUploadsFunc: &GitBlobResolverLSIFUploadsFunc{ + defaultHook: i.LSIFUploads, + }, + RangesFunc: &GitBlobResolverRangesFunc{ + defaultHook: i.Ranges, + }, + ReferencesFunc: &GitBlobResolverReferencesFunc{ + defaultHook: i.References, + }, + StencilFunc: &GitBlobResolverStencilFunc{ + defaultHook: i.Stencil, + }, + } +} + +// GitBlobResolverDefinitionsFunc describes the behavior when the +// Definitions method of the parent MockGitBlobResolver instance is invoked. +type GitBlobResolverDefinitionsFunc struct { + defaultHook func(context.Context, int, int) ([]types.UploadLocation, error) + hooks []func(context.Context, int, int) ([]types.UploadLocation, error) + history []GitBlobResolverDefinitionsFuncCall + mutex sync.Mutex +} + +// Definitions delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockGitBlobResolver) Definitions(v0 context.Context, v1 int, v2 int) ([]types.UploadLocation, error) { + r0, r1 := m.DefinitionsFunc.nextHook()(v0, v1, v2) + m.DefinitionsFunc.appendCall(GitBlobResolverDefinitionsFuncCall{v0, v1, v2, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the Definitions method +// of the parent MockGitBlobResolver instance is invoked and the hook queue +// is empty. +func (f *GitBlobResolverDefinitionsFunc) SetDefaultHook(hook func(context.Context, int, int) ([]types.UploadLocation, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// Definitions method of the parent MockGitBlobResolver instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *GitBlobResolverDefinitionsFunc) PushHook(hook func(context.Context, int, int) ([]types.UploadLocation, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *GitBlobResolverDefinitionsFunc) SetDefaultReturn(r0 []types.UploadLocation, r1 error) { + f.SetDefaultHook(func(context.Context, int, int) ([]types.UploadLocation, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *GitBlobResolverDefinitionsFunc) PushReturn(r0 []types.UploadLocation, r1 error) { + f.PushHook(func(context.Context, int, int) ([]types.UploadLocation, error) { + return r0, r1 + }) +} + +func (f *GitBlobResolverDefinitionsFunc) nextHook() func(context.Context, int, int) ([]types.UploadLocation, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *GitBlobResolverDefinitionsFunc) appendCall(r0 GitBlobResolverDefinitionsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of GitBlobResolverDefinitionsFuncCall objects +// describing the invocations of this function. +func (f *GitBlobResolverDefinitionsFunc) History() []GitBlobResolverDefinitionsFuncCall { + f.mutex.Lock() + history := make([]GitBlobResolverDefinitionsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// GitBlobResolverDefinitionsFuncCall is an object that describes an +// invocation of method Definitions on an instance of MockGitBlobResolver. +type GitBlobResolverDefinitionsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.UploadLocation + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c GitBlobResolverDefinitionsFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c GitBlobResolverDefinitionsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// GitBlobResolverDiagnosticsFunc describes the behavior when the +// Diagnostics method of the parent MockGitBlobResolver instance is invoked. +type GitBlobResolverDiagnosticsFunc struct { + defaultHook func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error) + hooks []func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error) + history []GitBlobResolverDiagnosticsFuncCall + mutex sync.Mutex +} + +// Diagnostics delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockGitBlobResolver) Diagnostics(v0 context.Context, v1 int) ([]shared.DiagnosticAtUpload, int, error) { + r0, r1, r2 := m.DiagnosticsFunc.nextHook()(v0, v1) + m.DiagnosticsFunc.appendCall(GitBlobResolverDiagnosticsFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the Diagnostics method +// of the parent MockGitBlobResolver instance is invoked and the hook queue +// is empty. +func (f *GitBlobResolverDiagnosticsFunc) SetDefaultHook(hook func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// Diagnostics method of the parent MockGitBlobResolver instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *GitBlobResolverDiagnosticsFunc) PushHook(hook func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *GitBlobResolverDiagnosticsFunc) SetDefaultReturn(r0 []shared.DiagnosticAtUpload, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *GitBlobResolverDiagnosticsFunc) PushReturn(r0 []shared.DiagnosticAtUpload, r1 int, r2 error) { + f.PushHook(func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error) { + return r0, r1, r2 + }) +} + +func (f *GitBlobResolverDiagnosticsFunc) nextHook() func(context.Context, int) ([]shared.DiagnosticAtUpload, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *GitBlobResolverDiagnosticsFunc) appendCall(r0 GitBlobResolverDiagnosticsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of GitBlobResolverDiagnosticsFuncCall objects +// describing the invocations of this function. +func (f *GitBlobResolverDiagnosticsFunc) History() []GitBlobResolverDiagnosticsFuncCall { + f.mutex.Lock() + history := make([]GitBlobResolverDiagnosticsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// GitBlobResolverDiagnosticsFuncCall is an object that describes an +// invocation of method Diagnostics on an instance of MockGitBlobResolver. +type GitBlobResolverDiagnosticsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []shared.DiagnosticAtUpload + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c GitBlobResolverDiagnosticsFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c GitBlobResolverDiagnosticsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// GitBlobResolverHoverFunc describes the behavior when the Hover method of +// the parent MockGitBlobResolver instance is invoked. +type GitBlobResolverHoverFunc struct { + defaultHook func(context.Context, int, int) (string, types.Range, bool, error) + hooks []func(context.Context, int, int) (string, types.Range, bool, error) + history []GitBlobResolverHoverFuncCall + mutex sync.Mutex +} + +// Hover delegates to the next hook function in the queue and stores the +// parameter and result values of this invocation. +func (m *MockGitBlobResolver) Hover(v0 context.Context, v1 int, v2 int) (string, types.Range, bool, error) { + r0, r1, r2, r3 := m.HoverFunc.nextHook()(v0, v1, v2) + m.HoverFunc.appendCall(GitBlobResolverHoverFuncCall{v0, v1, v2, r0, r1, r2, r3}) + return r0, r1, r2, r3 +} + +// SetDefaultHook sets function that is called when the Hover method of the +// parent MockGitBlobResolver instance is invoked and the hook queue is +// empty. +func (f *GitBlobResolverHoverFunc) SetDefaultHook(hook func(context.Context, int, int) (string, types.Range, bool, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// Hover method of the parent MockGitBlobResolver instance invokes the hook +// at the front of the queue and discards it. After the queue is empty, the +// default hook function is invoked for any future action. +func (f *GitBlobResolverHoverFunc) PushHook(hook func(context.Context, int, int) (string, types.Range, bool, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *GitBlobResolverHoverFunc) SetDefaultReturn(r0 string, r1 types.Range, r2 bool, r3 error) { + f.SetDefaultHook(func(context.Context, int, int) (string, types.Range, bool, error) { + return r0, r1, r2, r3 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *GitBlobResolverHoverFunc) PushReturn(r0 string, r1 types.Range, r2 bool, r3 error) { + f.PushHook(func(context.Context, int, int) (string, types.Range, bool, error) { + return r0, r1, r2, r3 + }) +} + +func (f *GitBlobResolverHoverFunc) nextHook() func(context.Context, int, int) (string, types.Range, bool, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *GitBlobResolverHoverFunc) appendCall(r0 GitBlobResolverHoverFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of GitBlobResolverHoverFuncCall objects +// describing the invocations of this function. +func (f *GitBlobResolverHoverFunc) History() []GitBlobResolverHoverFuncCall { + f.mutex.Lock() + history := make([]GitBlobResolverHoverFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// GitBlobResolverHoverFuncCall is an object that describes an invocation of +// method Hover on an instance of MockGitBlobResolver. +type GitBlobResolverHoverFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 string + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 types.Range + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 bool + // Result3 is the value of the 4th result returned from this method + // invocation. + Result3 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c GitBlobResolverHoverFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c GitBlobResolverHoverFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2, c.Result3} +} + +// GitBlobResolverImplementationsFunc describes the behavior when the +// Implementations method of the parent MockGitBlobResolver instance is +// invoked. +type GitBlobResolverImplementationsFunc struct { + defaultHook func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error) + hooks []func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error) + history []GitBlobResolverImplementationsFuncCall + mutex sync.Mutex +} + +// Implementations delegates to the next hook function in the queue and +// stores the parameter and result values of this invocation. +func (m *MockGitBlobResolver) Implementations(v0 context.Context, v1 int, v2 int, v3 int, v4 string) ([]types.UploadLocation, string, error) { + r0, r1, r2 := m.ImplementationsFunc.nextHook()(v0, v1, v2, v3, v4) + m.ImplementationsFunc.appendCall(GitBlobResolverImplementationsFuncCall{v0, v1, v2, v3, v4, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the Implementations +// method of the parent MockGitBlobResolver instance is invoked and the hook +// queue is empty. +func (f *GitBlobResolverImplementationsFunc) SetDefaultHook(hook func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// Implementations method of the parent MockGitBlobResolver instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *GitBlobResolverImplementationsFunc) PushHook(hook func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *GitBlobResolverImplementationsFunc) SetDefaultReturn(r0 []types.UploadLocation, r1 string, r2 error) { + f.SetDefaultHook(func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *GitBlobResolverImplementationsFunc) PushReturn(r0 []types.UploadLocation, r1 string, r2 error) { + f.PushHook(func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error) { + return r0, r1, r2 + }) +} + +func (f *GitBlobResolverImplementationsFunc) nextHook() func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *GitBlobResolverImplementationsFunc) appendCall(r0 GitBlobResolverImplementationsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of GitBlobResolverImplementationsFuncCall +// objects describing the invocations of this function. +func (f *GitBlobResolverImplementationsFunc) History() []GitBlobResolverImplementationsFuncCall { + f.mutex.Lock() + history := make([]GitBlobResolverImplementationsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// GitBlobResolverImplementationsFuncCall is an object that describes an +// invocation of method Implementations on an instance of +// MockGitBlobResolver. +type GitBlobResolverImplementationsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 int + // Arg3 is the value of the 4th argument passed to this method + // invocation. + Arg3 int + // Arg4 is the value of the 5th argument passed to this method + // invocation. + Arg4 string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.UploadLocation + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 string + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c GitBlobResolverImplementationsFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3, c.Arg4} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c GitBlobResolverImplementationsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// GitBlobResolverLSIFUploadsFunc describes the behavior when the +// LSIFUploads method of the parent MockGitBlobResolver instance is invoked. +type GitBlobResolverLSIFUploadsFunc struct { + defaultHook func(context.Context) ([]types.Dump, error) + hooks []func(context.Context) ([]types.Dump, error) + history []GitBlobResolverLSIFUploadsFuncCall + mutex sync.Mutex +} + +// LSIFUploads delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockGitBlobResolver) LSIFUploads(v0 context.Context) ([]types.Dump, error) { + r0, r1 := m.LSIFUploadsFunc.nextHook()(v0) + m.LSIFUploadsFunc.appendCall(GitBlobResolverLSIFUploadsFuncCall{v0, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the LSIFUploads method +// of the parent MockGitBlobResolver instance is invoked and the hook queue +// is empty. +func (f *GitBlobResolverLSIFUploadsFunc) SetDefaultHook(hook func(context.Context) ([]types.Dump, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// LSIFUploads method of the parent MockGitBlobResolver instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *GitBlobResolverLSIFUploadsFunc) PushHook(hook func(context.Context) ([]types.Dump, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *GitBlobResolverLSIFUploadsFunc) SetDefaultReturn(r0 []types.Dump, r1 error) { + f.SetDefaultHook(func(context.Context) ([]types.Dump, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *GitBlobResolverLSIFUploadsFunc) PushReturn(r0 []types.Dump, r1 error) { + f.PushHook(func(context.Context) ([]types.Dump, error) { + return r0, r1 + }) +} + +func (f *GitBlobResolverLSIFUploadsFunc) nextHook() func(context.Context) ([]types.Dump, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *GitBlobResolverLSIFUploadsFunc) appendCall(r0 GitBlobResolverLSIFUploadsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of GitBlobResolverLSIFUploadsFuncCall objects +// describing the invocations of this function. +func (f *GitBlobResolverLSIFUploadsFunc) History() []GitBlobResolverLSIFUploadsFuncCall { + f.mutex.Lock() + history := make([]GitBlobResolverLSIFUploadsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// GitBlobResolverLSIFUploadsFuncCall is an object that describes an +// invocation of method LSIFUploads on an instance of MockGitBlobResolver. +type GitBlobResolverLSIFUploadsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Dump + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c GitBlobResolverLSIFUploadsFuncCall) Args() []interface{} { + return []interface{}{c.Arg0} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c GitBlobResolverLSIFUploadsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// GitBlobResolverRangesFunc describes the behavior when the Ranges method +// of the parent MockGitBlobResolver instance is invoked. +type GitBlobResolverRangesFunc struct { + defaultHook func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error) + hooks []func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error) + history []GitBlobResolverRangesFuncCall + mutex sync.Mutex +} + +// Ranges delegates to the next hook function in the queue and stores the +// parameter and result values of this invocation. +func (m *MockGitBlobResolver) Ranges(v0 context.Context, v1 int, v2 int) ([]shared.AdjustedCodeIntelligenceRange, error) { + r0, r1 := m.RangesFunc.nextHook()(v0, v1, v2) + m.RangesFunc.appendCall(GitBlobResolverRangesFuncCall{v0, v1, v2, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the Ranges method of the +// parent MockGitBlobResolver instance is invoked and the hook queue is +// empty. +func (f *GitBlobResolverRangesFunc) SetDefaultHook(hook func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// Ranges method of the parent MockGitBlobResolver instance invokes the hook +// at the front of the queue and discards it. After the queue is empty, the +// default hook function is invoked for any future action. +func (f *GitBlobResolverRangesFunc) PushHook(hook func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *GitBlobResolverRangesFunc) SetDefaultReturn(r0 []shared.AdjustedCodeIntelligenceRange, r1 error) { + f.SetDefaultHook(func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *GitBlobResolverRangesFunc) PushReturn(r0 []shared.AdjustedCodeIntelligenceRange, r1 error) { + f.PushHook(func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error) { + return r0, r1 + }) +} + +func (f *GitBlobResolverRangesFunc) nextHook() func(context.Context, int, int) ([]shared.AdjustedCodeIntelligenceRange, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *GitBlobResolverRangesFunc) appendCall(r0 GitBlobResolverRangesFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of GitBlobResolverRangesFuncCall objects +// describing the invocations of this function. +func (f *GitBlobResolverRangesFunc) History() []GitBlobResolverRangesFuncCall { + f.mutex.Lock() + history := make([]GitBlobResolverRangesFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// GitBlobResolverRangesFuncCall is an object that describes an invocation +// of method Ranges on an instance of MockGitBlobResolver. +type GitBlobResolverRangesFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []shared.AdjustedCodeIntelligenceRange + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c GitBlobResolverRangesFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c GitBlobResolverRangesFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// GitBlobResolverReferencesFunc describes the behavior when the References +// method of the parent MockGitBlobResolver instance is invoked. +type GitBlobResolverReferencesFunc struct { + defaultHook func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error) + hooks []func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error) + history []GitBlobResolverReferencesFuncCall + mutex sync.Mutex +} + +// References delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockGitBlobResolver) References(v0 context.Context, v1 int, v2 int, v3 int, v4 string) ([]types.UploadLocation, string, error) { + r0, r1, r2 := m.ReferencesFunc.nextHook()(v0, v1, v2, v3, v4) + m.ReferencesFunc.appendCall(GitBlobResolverReferencesFuncCall{v0, v1, v2, v3, v4, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the References method of +// the parent MockGitBlobResolver instance is invoked and the hook queue is +// empty. +func (f *GitBlobResolverReferencesFunc) SetDefaultHook(hook func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// References method of the parent MockGitBlobResolver instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *GitBlobResolverReferencesFunc) PushHook(hook func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *GitBlobResolverReferencesFunc) SetDefaultReturn(r0 []types.UploadLocation, r1 string, r2 error) { + f.SetDefaultHook(func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *GitBlobResolverReferencesFunc) PushReturn(r0 []types.UploadLocation, r1 string, r2 error) { + f.PushHook(func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error) { + return r0, r1, r2 + }) +} + +func (f *GitBlobResolverReferencesFunc) nextHook() func(context.Context, int, int, int, string) ([]types.UploadLocation, string, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *GitBlobResolverReferencesFunc) appendCall(r0 GitBlobResolverReferencesFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of GitBlobResolverReferencesFuncCall objects +// describing the invocations of this function. +func (f *GitBlobResolverReferencesFunc) History() []GitBlobResolverReferencesFuncCall { + f.mutex.Lock() + history := make([]GitBlobResolverReferencesFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// GitBlobResolverReferencesFuncCall is an object that describes an +// invocation of method References on an instance of MockGitBlobResolver. +type GitBlobResolverReferencesFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 int + // Arg3 is the value of the 4th argument passed to this method + // invocation. + Arg3 int + // Arg4 is the value of the 5th argument passed to this method + // invocation. + Arg4 string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.UploadLocation + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 string + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c GitBlobResolverReferencesFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3, c.Arg4} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c GitBlobResolverReferencesFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// GitBlobResolverStencilFunc describes the behavior when the Stencil method +// of the parent MockGitBlobResolver instance is invoked. +type GitBlobResolverStencilFunc struct { + defaultHook func(context.Context) ([]types.Range, error) + hooks []func(context.Context) ([]types.Range, error) + history []GitBlobResolverStencilFuncCall + mutex sync.Mutex +} + +// Stencil delegates to the next hook function in the queue and stores the +// parameter and result values of this invocation. +func (m *MockGitBlobResolver) Stencil(v0 context.Context) ([]types.Range, error) { + r0, r1 := m.StencilFunc.nextHook()(v0) + m.StencilFunc.appendCall(GitBlobResolverStencilFuncCall{v0, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the Stencil method of +// the parent MockGitBlobResolver instance is invoked and the hook queue is +// empty. +func (f *GitBlobResolverStencilFunc) SetDefaultHook(hook func(context.Context) ([]types.Range, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// Stencil method of the parent MockGitBlobResolver instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *GitBlobResolverStencilFunc) PushHook(hook func(context.Context) ([]types.Range, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *GitBlobResolverStencilFunc) SetDefaultReturn(r0 []types.Range, r1 error) { + f.SetDefaultHook(func(context.Context) ([]types.Range, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *GitBlobResolverStencilFunc) PushReturn(r0 []types.Range, r1 error) { + f.PushHook(func(context.Context) ([]types.Range, error) { + return r0, r1 + }) +} + +func (f *GitBlobResolverStencilFunc) nextHook() func(context.Context) ([]types.Range, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *GitBlobResolverStencilFunc) appendCall(r0 GitBlobResolverStencilFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of GitBlobResolverStencilFuncCall objects +// describing the invocations of this function. +func (f *GitBlobResolverStencilFunc) History() []GitBlobResolverStencilFuncCall { + f.mutex.Lock() + history := make([]GitBlobResolverStencilFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// GitBlobResolverStencilFuncCall is an object that describes an invocation +// of method Stencil on an instance of MockGitBlobResolver. +type GitBlobResolverStencilFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Range + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c GitBlobResolverStencilFuncCall) Args() []interface{} { + return []interface{}{c.Arg0} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c GitBlobResolverStencilFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// MockGitserverClient is a mock implementation of the GitserverClient +// interface (from the package +// github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql) +// used for unit testing. +type MockGitserverClient struct { + // CommitsExistFunc is an instance of a mock function object controlling + // the behavior of the method CommitsExist. + CommitsExistFunc *GitserverClientCommitsExistFunc + // DiffPathFunc is an instance of a mock function object controlling the + // behavior of the method DiffPath. + DiffPathFunc *GitserverClientDiffPathFunc +} + +// NewMockGitserverClient creates a new mock of the GitserverClient +// interface. All methods return zero values for all results, unless +// overwritten. +func NewMockGitserverClient() *MockGitserverClient { + return &MockGitserverClient{ + CommitsExistFunc: &GitserverClientCommitsExistFunc{ + defaultHook: func(context.Context, []gitserver.RepositoryCommit) (r0 []bool, r1 error) { + return + }, + }, + DiffPathFunc: &GitserverClientDiffPathFunc{ + defaultHook: func(context.Context, authz.SubRepoPermissionChecker, api.RepoName, string, string, string) (r0 []*diff.Hunk, r1 error) { + return + }, + }, + } +} + +// NewStrictMockGitserverClient creates a new mock of the GitserverClient +// interface. All methods panic on invocation, unless overwritten. +func NewStrictMockGitserverClient() *MockGitserverClient { + return &MockGitserverClient{ + CommitsExistFunc: &GitserverClientCommitsExistFunc{ + defaultHook: func(context.Context, []gitserver.RepositoryCommit) ([]bool, error) { + panic("unexpected invocation of MockGitserverClient.CommitsExist") + }, + }, + DiffPathFunc: &GitserverClientDiffPathFunc{ + defaultHook: func(context.Context, authz.SubRepoPermissionChecker, api.RepoName, string, string, string) ([]*diff.Hunk, error) { + panic("unexpected invocation of MockGitserverClient.DiffPath") + }, + }, + } +} + +// NewMockGitserverClientFrom creates a new mock of the MockGitserverClient +// interface. All methods delegate to the given implementation, unless +// overwritten. +func NewMockGitserverClientFrom(i GitserverClient) *MockGitserverClient { + return &MockGitserverClient{ + CommitsExistFunc: &GitserverClientCommitsExistFunc{ + defaultHook: i.CommitsExist, + }, + DiffPathFunc: &GitserverClientDiffPathFunc{ + defaultHook: i.DiffPath, + }, + } +} + +// GitserverClientCommitsExistFunc describes the behavior when the +// CommitsExist method of the parent MockGitserverClient instance is +// invoked. +type GitserverClientCommitsExistFunc struct { + defaultHook func(context.Context, []gitserver.RepositoryCommit) ([]bool, error) + hooks []func(context.Context, []gitserver.RepositoryCommit) ([]bool, error) + history []GitserverClientCommitsExistFuncCall + mutex sync.Mutex +} + +// CommitsExist delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockGitserverClient) CommitsExist(v0 context.Context, v1 []gitserver.RepositoryCommit) ([]bool, error) { + r0, r1 := m.CommitsExistFunc.nextHook()(v0, v1) + m.CommitsExistFunc.appendCall(GitserverClientCommitsExistFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the CommitsExist method +// of the parent MockGitserverClient instance is invoked and the hook queue +// is empty. +func (f *GitserverClientCommitsExistFunc) SetDefaultHook(hook func(context.Context, []gitserver.RepositoryCommit) ([]bool, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// CommitsExist method of the parent MockGitserverClient instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *GitserverClientCommitsExistFunc) PushHook(hook func(context.Context, []gitserver.RepositoryCommit) ([]bool, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *GitserverClientCommitsExistFunc) SetDefaultReturn(r0 []bool, r1 error) { + f.SetDefaultHook(func(context.Context, []gitserver.RepositoryCommit) ([]bool, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *GitserverClientCommitsExistFunc) PushReturn(r0 []bool, r1 error) { + f.PushHook(func(context.Context, []gitserver.RepositoryCommit) ([]bool, error) { + return r0, r1 + }) +} + +func (f *GitserverClientCommitsExistFunc) nextHook() func(context.Context, []gitserver.RepositoryCommit) ([]bool, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *GitserverClientCommitsExistFunc) appendCall(r0 GitserverClientCommitsExistFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of GitserverClientCommitsExistFuncCall objects +// describing the invocations of this function. +func (f *GitserverClientCommitsExistFunc) History() []GitserverClientCommitsExistFuncCall { + f.mutex.Lock() + history := make([]GitserverClientCommitsExistFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// GitserverClientCommitsExistFuncCall is an object that describes an +// invocation of method CommitsExist on an instance of MockGitserverClient. +type GitserverClientCommitsExistFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 []gitserver.RepositoryCommit + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []bool + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c GitserverClientCommitsExistFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c GitserverClientCommitsExistFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// GitserverClientDiffPathFunc describes the behavior when the DiffPath +// method of the parent MockGitserverClient instance is invoked. +type GitserverClientDiffPathFunc struct { + defaultHook func(context.Context, authz.SubRepoPermissionChecker, api.RepoName, string, string, string) ([]*diff.Hunk, error) + hooks []func(context.Context, authz.SubRepoPermissionChecker, api.RepoName, string, string, string) ([]*diff.Hunk, error) + history []GitserverClientDiffPathFuncCall + mutex sync.Mutex +} + +// DiffPath delegates to the next hook function in the queue and stores the +// parameter and result values of this invocation. +func (m *MockGitserverClient) DiffPath(v0 context.Context, v1 authz.SubRepoPermissionChecker, v2 api.RepoName, v3 string, v4 string, v5 string) ([]*diff.Hunk, error) { + r0, r1 := m.DiffPathFunc.nextHook()(v0, v1, v2, v3, v4, v5) + m.DiffPathFunc.appendCall(GitserverClientDiffPathFuncCall{v0, v1, v2, v3, v4, v5, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the DiffPath method of +// the parent MockGitserverClient instance is invoked and the hook queue is +// empty. +func (f *GitserverClientDiffPathFunc) SetDefaultHook(hook func(context.Context, authz.SubRepoPermissionChecker, api.RepoName, string, string, string) ([]*diff.Hunk, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// DiffPath method of the parent MockGitserverClient instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *GitserverClientDiffPathFunc) PushHook(hook func(context.Context, authz.SubRepoPermissionChecker, api.RepoName, string, string, string) ([]*diff.Hunk, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *GitserverClientDiffPathFunc) SetDefaultReturn(r0 []*diff.Hunk, r1 error) { + f.SetDefaultHook(func(context.Context, authz.SubRepoPermissionChecker, api.RepoName, string, string, string) ([]*diff.Hunk, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *GitserverClientDiffPathFunc) PushReturn(r0 []*diff.Hunk, r1 error) { + f.PushHook(func(context.Context, authz.SubRepoPermissionChecker, api.RepoName, string, string, string) ([]*diff.Hunk, error) { + return r0, r1 + }) +} + +func (f *GitserverClientDiffPathFunc) nextHook() func(context.Context, authz.SubRepoPermissionChecker, api.RepoName, string, string, string) ([]*diff.Hunk, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *GitserverClientDiffPathFunc) appendCall(r0 GitserverClientDiffPathFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of GitserverClientDiffPathFuncCall objects +// describing the invocations of this function. +func (f *GitserverClientDiffPathFunc) History() []GitserverClientDiffPathFuncCall { + f.mutex.Lock() + history := make([]GitserverClientDiffPathFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// GitserverClientDiffPathFuncCall is an object that describes an invocation +// of method DiffPath on an instance of MockGitserverClient. +type GitserverClientDiffPathFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 authz.SubRepoPermissionChecker + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 api.RepoName + // Arg3 is the value of the 4th argument passed to this method + // invocation. + Arg3 string + // Arg4 is the value of the 5th argument passed to this method + // invocation. + Arg4 string + // Arg5 is the value of the 6th argument passed to this method + // invocation. + Arg5 string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []*diff.Hunk + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c GitserverClientDiffPathFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3, c.Arg4, c.Arg5} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c GitserverClientDiffPathFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// MockPolicyService is a mock implementation of the PolicyService interface +// (from the package +// github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql) +// used for unit testing. +type MockPolicyService struct { + // GetRetentionPolicyOverviewFunc is an instance of a mock function + // object controlling the behavior of the method + // GetRetentionPolicyOverview. + GetRetentionPolicyOverviewFunc *PolicyServiceGetRetentionPolicyOverviewFunc +} + +// NewMockPolicyService creates a new mock of the PolicyService interface. +// All methods return zero values for all results, unless overwritten. +func NewMockPolicyService() *MockPolicyService { + return &MockPolicyService{ + GetRetentionPolicyOverviewFunc: &PolicyServiceGetRetentionPolicyOverviewFunc{ + defaultHook: func(context.Context, types.Upload, bool, int, int64, string, time.Time) (r0 []types.RetentionPolicyMatchCandidate, r1 int, r2 error) { + return + }, + }, + } +} + +// NewStrictMockPolicyService creates a new mock of the PolicyService +// interface. All methods panic on invocation, unless overwritten. +func NewStrictMockPolicyService() *MockPolicyService { + return &MockPolicyService{ + GetRetentionPolicyOverviewFunc: &PolicyServiceGetRetentionPolicyOverviewFunc{ + defaultHook: func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + panic("unexpected invocation of MockPolicyService.GetRetentionPolicyOverview") + }, + }, + } +} + +// NewMockPolicyServiceFrom creates a new mock of the MockPolicyService +// interface. All methods delegate to the given implementation, unless +// overwritten. +func NewMockPolicyServiceFrom(i PolicyService) *MockPolicyService { + return &MockPolicyService{ + GetRetentionPolicyOverviewFunc: &PolicyServiceGetRetentionPolicyOverviewFunc{ + defaultHook: i.GetRetentionPolicyOverview, + }, + } +} + +// PolicyServiceGetRetentionPolicyOverviewFunc describes the behavior when +// the GetRetentionPolicyOverview method of the parent MockPolicyService +// instance is invoked. +type PolicyServiceGetRetentionPolicyOverviewFunc struct { + defaultHook func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) + hooks []func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) + history []PolicyServiceGetRetentionPolicyOverviewFuncCall + mutex sync.Mutex +} + +// GetRetentionPolicyOverview delegates to the next hook function in the +// queue and stores the parameter and result values of this invocation. +func (m *MockPolicyService) GetRetentionPolicyOverview(v0 context.Context, v1 types.Upload, v2 bool, v3 int, v4 int64, v5 string, v6 time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + r0, r1, r2 := m.GetRetentionPolicyOverviewFunc.nextHook()(v0, v1, v2, v3, v4, v5, v6) + m.GetRetentionPolicyOverviewFunc.appendCall(PolicyServiceGetRetentionPolicyOverviewFuncCall{v0, v1, v2, v3, v4, v5, v6, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the +// GetRetentionPolicyOverview method of the parent MockPolicyService +// instance is invoked and the hook queue is empty. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) SetDefaultHook(hook func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetRetentionPolicyOverview method of the parent MockPolicyService +// instance invokes the hook at the front of the queue and discards it. +// After the queue is empty, the default hook function is invoked for any +// future action. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) PushHook(hook func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) SetDefaultReturn(r0 []types.RetentionPolicyMatchCandidate, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) PushReturn(r0 []types.RetentionPolicyMatchCandidate, r1 int, r2 error) { + f.PushHook(func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + return r0, r1, r2 + }) +} + +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) nextHook() func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) appendCall(r0 PolicyServiceGetRetentionPolicyOverviewFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// PolicyServiceGetRetentionPolicyOverviewFuncCall objects describing the +// invocations of this function. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) History() []PolicyServiceGetRetentionPolicyOverviewFuncCall { + f.mutex.Lock() + history := make([]PolicyServiceGetRetentionPolicyOverviewFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// PolicyServiceGetRetentionPolicyOverviewFuncCall is an object that +// describes an invocation of method GetRetentionPolicyOverview on an +// instance of MockPolicyService. +type PolicyServiceGetRetentionPolicyOverviewFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 types.Upload + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 bool + // Arg3 is the value of the 4th argument passed to this method + // invocation. + Arg3 int + // Arg4 is the value of the 5th argument passed to this method + // invocation. + Arg4 int64 + // Arg5 is the value of the 6th argument passed to this method + // invocation. + Arg5 string + // Arg6 is the value of the 7th argument passed to this method + // invocation. + Arg6 time.Time + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.RetentionPolicyMatchCandidate + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c PolicyServiceGetRetentionPolicyOverviewFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3, c.Arg4, c.Arg5, c.Arg6} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c PolicyServiceGetRetentionPolicyOverviewFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// MockUploadsService is a mock implementation of the UploadsService +// interface (from the package +// github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql) +// used for unit testing. +type MockUploadsService struct { + // GetAuditLogsForUploadFunc is an instance of a mock function object + // controlling the behavior of the method GetAuditLogsForUpload. + GetAuditLogsForUploadFunc *UploadsServiceGetAuditLogsForUploadFunc + // GetListTagsFunc is an instance of a mock function object controlling + // the behavior of the method GetListTags. + GetListTagsFunc *UploadsServiceGetListTagsFunc + // GetUploadDocumentsForPathFunc is an instance of a mock function + // object controlling the behavior of the method + // GetUploadDocumentsForPath. + GetUploadDocumentsForPathFunc *UploadsServiceGetUploadDocumentsForPathFunc + // GetUploadsFunc is an instance of a mock function object controlling + // the behavior of the method GetUploads. + GetUploadsFunc *UploadsServiceGetUploadsFunc + // GetUploadsByIDsFunc is an instance of a mock function object + // controlling the behavior of the method GetUploadsByIDs. + GetUploadsByIDsFunc *UploadsServiceGetUploadsByIDsFunc +} + +// NewMockUploadsService creates a new mock of the UploadsService interface. +// All methods return zero values for all results, unless overwritten. +func NewMockUploadsService() *MockUploadsService { + return &MockUploadsService{ + GetAuditLogsForUploadFunc: &UploadsServiceGetAuditLogsForUploadFunc{ + defaultHook: func(context.Context, int) (r0 []types.UploadLog, r1 error) { + return + }, + }, + GetListTagsFunc: &UploadsServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) (r0 []*gitdomain.Tag, r1 error) { + return + }, + }, + GetUploadDocumentsForPathFunc: &UploadsServiceGetUploadDocumentsForPathFunc{ + defaultHook: func(context.Context, int, string) (r0 []string, r1 int, r2 error) { + return + }, + }, + GetUploadsFunc: &UploadsServiceGetUploadsFunc{ + defaultHook: func(context.Context, types.GetUploadsOptions) (r0 []types.Upload, r1 int, r2 error) { + return + }, + }, + GetUploadsByIDsFunc: &UploadsServiceGetUploadsByIDsFunc{ + defaultHook: func(context.Context, ...int) (r0 []types.Upload, r1 error) { + return + }, + }, + } +} + +// NewStrictMockUploadsService creates a new mock of the UploadsService +// interface. All methods panic on invocation, unless overwritten. +func NewStrictMockUploadsService() *MockUploadsService { + return &MockUploadsService{ + GetAuditLogsForUploadFunc: &UploadsServiceGetAuditLogsForUploadFunc{ + defaultHook: func(context.Context, int) ([]types.UploadLog, error) { + panic("unexpected invocation of MockUploadsService.GetAuditLogsForUpload") + }, + }, + GetListTagsFunc: &UploadsServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + panic("unexpected invocation of MockUploadsService.GetListTags") + }, + }, + GetUploadDocumentsForPathFunc: &UploadsServiceGetUploadDocumentsForPathFunc{ + defaultHook: func(context.Context, int, string) ([]string, int, error) { + panic("unexpected invocation of MockUploadsService.GetUploadDocumentsForPath") + }, + }, + GetUploadsFunc: &UploadsServiceGetUploadsFunc{ + defaultHook: func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + panic("unexpected invocation of MockUploadsService.GetUploads") + }, + }, + GetUploadsByIDsFunc: &UploadsServiceGetUploadsByIDsFunc{ + defaultHook: func(context.Context, ...int) ([]types.Upload, error) { + panic("unexpected invocation of MockUploadsService.GetUploadsByIDs") + }, + }, + } +} + +// NewMockUploadsServiceFrom creates a new mock of the MockUploadsService +// interface. All methods delegate to the given implementation, unless +// overwritten. +func NewMockUploadsServiceFrom(i UploadsService) *MockUploadsService { + return &MockUploadsService{ + GetAuditLogsForUploadFunc: &UploadsServiceGetAuditLogsForUploadFunc{ + defaultHook: i.GetAuditLogsForUpload, + }, + GetListTagsFunc: &UploadsServiceGetListTagsFunc{ + defaultHook: i.GetListTags, + }, + GetUploadDocumentsForPathFunc: &UploadsServiceGetUploadDocumentsForPathFunc{ + defaultHook: i.GetUploadDocumentsForPath, + }, + GetUploadsFunc: &UploadsServiceGetUploadsFunc{ + defaultHook: i.GetUploads, + }, + GetUploadsByIDsFunc: &UploadsServiceGetUploadsByIDsFunc{ + defaultHook: i.GetUploadsByIDs, + }, + } +} + +// UploadsServiceGetAuditLogsForUploadFunc describes the behavior when the +// GetAuditLogsForUpload method of the parent MockUploadsService instance is +// invoked. +type UploadsServiceGetAuditLogsForUploadFunc struct { + defaultHook func(context.Context, int) ([]types.UploadLog, error) + hooks []func(context.Context, int) ([]types.UploadLog, error) + history []UploadsServiceGetAuditLogsForUploadFuncCall + mutex sync.Mutex +} + +// GetAuditLogsForUpload delegates to the next hook function in the queue +// and stores the parameter and result values of this invocation. +func (m *MockUploadsService) GetAuditLogsForUpload(v0 context.Context, v1 int) ([]types.UploadLog, error) { + r0, r1 := m.GetAuditLogsForUploadFunc.nextHook()(v0, v1) + m.GetAuditLogsForUploadFunc.appendCall(UploadsServiceGetAuditLogsForUploadFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the +// GetAuditLogsForUpload method of the parent MockUploadsService instance is +// invoked and the hook queue is empty. +func (f *UploadsServiceGetAuditLogsForUploadFunc) SetDefaultHook(hook func(context.Context, int) ([]types.UploadLog, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetAuditLogsForUpload method of the parent MockUploadsService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *UploadsServiceGetAuditLogsForUploadFunc) PushHook(hook func(context.Context, int) ([]types.UploadLog, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetAuditLogsForUploadFunc) SetDefaultReturn(r0 []types.UploadLog, r1 error) { + f.SetDefaultHook(func(context.Context, int) ([]types.UploadLog, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetAuditLogsForUploadFunc) PushReturn(r0 []types.UploadLog, r1 error) { + f.PushHook(func(context.Context, int) ([]types.UploadLog, error) { + return r0, r1 + }) +} + +func (f *UploadsServiceGetAuditLogsForUploadFunc) nextHook() func(context.Context, int) ([]types.UploadLog, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetAuditLogsForUploadFunc) appendCall(r0 UploadsServiceGetAuditLogsForUploadFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadsServiceGetAuditLogsForUploadFuncCall +// objects describing the invocations of this function. +func (f *UploadsServiceGetAuditLogsForUploadFunc) History() []UploadsServiceGetAuditLogsForUploadFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetAuditLogsForUploadFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetAuditLogsForUploadFuncCall is an object that describes +// an invocation of method GetAuditLogsForUpload on an instance of +// MockUploadsService. +type UploadsServiceGetAuditLogsForUploadFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.UploadLog + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadsServiceGetAuditLogsForUploadFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetAuditLogsForUploadFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// UploadsServiceGetListTagsFunc describes the behavior when the GetListTags +// method of the parent MockUploadsService instance is invoked. +type UploadsServiceGetListTagsFunc struct { + defaultHook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + hooks []func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + history []UploadsServiceGetListTagsFuncCall + mutex sync.Mutex +} + +// GetListTags delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockUploadsService) GetListTags(v0 context.Context, v1 api.RepoName, v2 ...string) ([]*gitdomain.Tag, error) { + r0, r1 := m.GetListTagsFunc.nextHook()(v0, v1, v2...) + m.GetListTagsFunc.appendCall(UploadsServiceGetListTagsFuncCall{v0, v1, v2, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetListTags method +// of the parent MockUploadsService instance is invoked and the hook queue +// is empty. +func (f *UploadsServiceGetListTagsFunc) SetDefaultHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetListTags method of the parent MockUploadsService instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *UploadsServiceGetListTagsFunc) PushHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetListTagsFunc) SetDefaultReturn(r0 []*gitdomain.Tag, r1 error) { + f.SetDefaultHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetListTagsFunc) PushReturn(r0 []*gitdomain.Tag, r1 error) { + f.PushHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +func (f *UploadsServiceGetListTagsFunc) nextHook() func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetListTagsFunc) appendCall(r0 UploadsServiceGetListTagsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadsServiceGetListTagsFuncCall objects +// describing the invocations of this function. +func (f *UploadsServiceGetListTagsFunc) History() []UploadsServiceGetListTagsFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetListTagsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetListTagsFuncCall is an object that describes an +// invocation of method GetListTags on an instance of MockUploadsService. +type UploadsServiceGetListTagsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 api.RepoName + // Arg2 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg2 []string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []*gitdomain.Tag + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c UploadsServiceGetListTagsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg2 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0, c.Arg1}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetListTagsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// UploadsServiceGetUploadDocumentsForPathFunc describes the behavior when +// the GetUploadDocumentsForPath method of the parent MockUploadsService +// instance is invoked. +type UploadsServiceGetUploadDocumentsForPathFunc struct { + defaultHook func(context.Context, int, string) ([]string, int, error) + hooks []func(context.Context, int, string) ([]string, int, error) + history []UploadsServiceGetUploadDocumentsForPathFuncCall + mutex sync.Mutex +} + +// GetUploadDocumentsForPath delegates to the next hook function in the +// queue and stores the parameter and result values of this invocation. +func (m *MockUploadsService) GetUploadDocumentsForPath(v0 context.Context, v1 int, v2 string) ([]string, int, error) { + r0, r1, r2 := m.GetUploadDocumentsForPathFunc.nextHook()(v0, v1, v2) + m.GetUploadDocumentsForPathFunc.appendCall(UploadsServiceGetUploadDocumentsForPathFuncCall{v0, v1, v2, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the +// GetUploadDocumentsForPath method of the parent MockUploadsService +// instance is invoked and the hook queue is empty. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) SetDefaultHook(hook func(context.Context, int, string) ([]string, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUploadDocumentsForPath method of the parent MockUploadsService +// instance invokes the hook at the front of the queue and discards it. +// After the queue is empty, the default hook function is invoked for any +// future action. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) PushHook(hook func(context.Context, int, string) ([]string, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) SetDefaultReturn(r0 []string, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, int, string) ([]string, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) PushReturn(r0 []string, r1 int, r2 error) { + f.PushHook(func(context.Context, int, string) ([]string, int, error) { + return r0, r1, r2 + }) +} + +func (f *UploadsServiceGetUploadDocumentsForPathFunc) nextHook() func(context.Context, int, string) ([]string, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetUploadDocumentsForPathFunc) appendCall(r0 UploadsServiceGetUploadDocumentsForPathFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// UploadsServiceGetUploadDocumentsForPathFuncCall objects describing the +// invocations of this function. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) History() []UploadsServiceGetUploadDocumentsForPathFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetUploadDocumentsForPathFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetUploadDocumentsForPathFuncCall is an object that +// describes an invocation of method GetUploadDocumentsForPath on an +// instance of MockUploadsService. +type UploadsServiceGetUploadDocumentsForPathFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []string + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadsServiceGetUploadDocumentsForPathFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetUploadDocumentsForPathFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// UploadsServiceGetUploadsFunc describes the behavior when the GetUploads +// method of the parent MockUploadsService instance is invoked. +type UploadsServiceGetUploadsFunc struct { + defaultHook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) + hooks []func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) + history []UploadsServiceGetUploadsFuncCall + mutex sync.Mutex +} + +// GetUploads delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockUploadsService) GetUploads(v0 context.Context, v1 types.GetUploadsOptions) ([]types.Upload, int, error) { + r0, r1, r2 := m.GetUploadsFunc.nextHook()(v0, v1) + m.GetUploadsFunc.appendCall(UploadsServiceGetUploadsFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the GetUploads method of +// the parent MockUploadsService instance is invoked and the hook queue is +// empty. +func (f *UploadsServiceGetUploadsFunc) SetDefaultHook(hook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUploads method of the parent MockUploadsService instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *UploadsServiceGetUploadsFunc) PushHook(hook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetUploadsFunc) SetDefaultReturn(r0 []types.Upload, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetUploadsFunc) PushReturn(r0 []types.Upload, r1 int, r2 error) { + f.PushHook(func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + return r0, r1, r2 + }) +} + +func (f *UploadsServiceGetUploadsFunc) nextHook() func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetUploadsFunc) appendCall(r0 UploadsServiceGetUploadsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadsServiceGetUploadsFuncCall objects +// describing the invocations of this function. +func (f *UploadsServiceGetUploadsFunc) History() []UploadsServiceGetUploadsFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetUploadsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetUploadsFuncCall is an object that describes an +// invocation of method GetUploads on an instance of MockUploadsService. +type UploadsServiceGetUploadsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 types.GetUploadsOptions + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Upload + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadsServiceGetUploadsFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetUploadsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// UploadsServiceGetUploadsByIDsFunc describes the behavior when the +// GetUploadsByIDs method of the parent MockUploadsService instance is +// invoked. +type UploadsServiceGetUploadsByIDsFunc struct { + defaultHook func(context.Context, ...int) ([]types.Upload, error) + hooks []func(context.Context, ...int) ([]types.Upload, error) + history []UploadsServiceGetUploadsByIDsFuncCall + mutex sync.Mutex +} + +// GetUploadsByIDs delegates to the next hook function in the queue and +// stores the parameter and result values of this invocation. +func (m *MockUploadsService) GetUploadsByIDs(v0 context.Context, v1 ...int) ([]types.Upload, error) { + r0, r1 := m.GetUploadsByIDsFunc.nextHook()(v0, v1...) + m.GetUploadsByIDsFunc.appendCall(UploadsServiceGetUploadsByIDsFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetUploadsByIDs +// method of the parent MockUploadsService instance is invoked and the hook +// queue is empty. +func (f *UploadsServiceGetUploadsByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]types.Upload, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUploadsByIDs method of the parent MockUploadsService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *UploadsServiceGetUploadsByIDsFunc) PushHook(hook func(context.Context, ...int) ([]types.Upload, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetUploadsByIDsFunc) SetDefaultReturn(r0 []types.Upload, r1 error) { + f.SetDefaultHook(func(context.Context, ...int) ([]types.Upload, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetUploadsByIDsFunc) PushReturn(r0 []types.Upload, r1 error) { + f.PushHook(func(context.Context, ...int) ([]types.Upload, error) { + return r0, r1 + }) +} + +func (f *UploadsServiceGetUploadsByIDsFunc) nextHook() func(context.Context, ...int) ([]types.Upload, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetUploadsByIDsFunc) appendCall(r0 UploadsServiceGetUploadsByIDsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadsServiceGetUploadsByIDsFuncCall +// objects describing the invocations of this function. +func (f *UploadsServiceGetUploadsByIDsFunc) History() []UploadsServiceGetUploadsByIDsFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetUploadsByIDsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetUploadsByIDsFuncCall is an object that describes an +// invocation of method GetUploadsByIDs on an instance of +// MockUploadsService. +type UploadsServiceGetUploadsByIDsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg1 []int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Upload + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c UploadsServiceGetUploadsByIDsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg1 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetUploadsByIDsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} diff --git a/internal/codeintel/codenav/transport/graphql/observability.go b/internal/codeintel/codenav/transport/graphql/observability.go index e871f3c8d34..8d951e30b33 100644 --- a/internal/codeintel/codenav/transport/graphql/observability.go +++ b/internal/codeintel/codenav/transport/graphql/observability.go @@ -22,10 +22,7 @@ type operations struct { stencil *observation.Operation ranges *observation.Operation - getSupportedByCtags *observation.Operation - getGitBlobLSIFDataResolver *observation.Operation - getLanguagesRequestedBy *observation.Operation - setRequestLanguageSupport *observation.Operation + gitBlobLsifData *observation.Operation } func newOperations(observationContext *observation.Context) *operations { @@ -53,10 +50,7 @@ func newOperations(observationContext *observation.Context) *operations { stencil: op("Stencil"), ranges: op("Ranges"), - getSupportedByCtags: op("GetSupportedByCtags"), - getGitBlobLSIFDataResolver: op("GetGitBlobLSIFDataResolver"), - getLanguagesRequestedBy: op("GetLanguagesRequestedBy"), - setRequestLanguageSupport: op("SetRequestLanguageSupport"), + gitBlobLsifData: op("GitBlobLsifData"), } } diff --git a/internal/codeintel/codenav/transport/graphql/position_resolver.go b/internal/codeintel/codenav/transport/graphql/position_resolver.go new file mode 100644 index 00000000000..e49509714e0 --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/position_resolver.go @@ -0,0 +1,29 @@ +package graphql + +import ( + "fmt" + "strconv" + + "github.com/sourcegraph/go-lsp" +) + +type PositionResolver interface { + Line() int32 + Character() int32 +} + +type positionResolver struct{ pos lsp.Position } + +func NewPositionResolver(pos lsp.Position) PositionResolver { + return &positionResolver{pos: pos} +} + +func (r *positionResolver) Line() int32 { return int32(r.pos.Line) } +func (r *positionResolver) Character() int32 { return int32(r.pos.Character) } + +func (r *positionResolver) urlFragment(forceIncludeCharacter bool) string { + if !forceIncludeCharacter && r.pos.Character == 0 { + return strconv.Itoa(r.pos.Line + 1) + } + return fmt.Sprintf("%d:%d", r.pos.Line+1, r.pos.Character+1) +} diff --git a/internal/codeintel/codenav/transport/graphql/range_resolver.go b/internal/codeintel/codenav/transport/graphql/range_resolver.go new file mode 100644 index 00000000000..bd7c712870f --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/range_resolver.go @@ -0,0 +1,30 @@ +package graphql + +import "github.com/sourcegraph/go-lsp" + +type RangeResolver interface { + Start() PositionResolver + End() PositionResolver +} + +type rangeResolver struct{ lspRange lsp.Range } + +func NewRangeResolver(lspRange lsp.Range) RangeResolver { + return &rangeResolver{ + lspRange: lspRange, + } +} + +func (r *rangeResolver) Start() PositionResolver { return r.start() } +func (r *rangeResolver) End() PositionResolver { return r.end() } + +func (r *rangeResolver) start() *positionResolver { return &positionResolver{r.lspRange.Start} } +func (r *rangeResolver) end() *positionResolver { return &positionResolver{r.lspRange.End} } + +func (r *rangeResolver) urlFragment() string { + if r.lspRange.Start == r.lspRange.End { + return r.start().urlFragment(false) + } + hasCharacter := r.lspRange.Start.Character != 0 || r.lspRange.End.Character != 0 + return r.start().urlFragment(hasCharacter) + "-" + r.end().urlFragment(hasCharacter) +} diff --git a/internal/codeintel/codenav/transport/graphql/ranges_resolver.go b/internal/codeintel/codenav/transport/graphql/ranges_resolver.go new file mode 100644 index 00000000000..3fb0458f373 --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/ranges_resolver.go @@ -0,0 +1,48 @@ +package graphql + +import ( + "context" + + "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" +) + +type CodeIntelligenceRangeResolver interface { + Range(ctx context.Context) (RangeResolver, error) + Definitions(ctx context.Context) (LocationConnectionResolver, error) + References(ctx context.Context) (LocationConnectionResolver, error) + Implementations(ctx context.Context) (LocationConnectionResolver, error) + Hover(ctx context.Context) (HoverResolver, error) +} + +type codeIntelligenceRangeResolver struct { + r shared.AdjustedCodeIntelligenceRange + locationResolver *sharedresolvers.CachedLocationResolver +} + +func NewCodeIntelligenceRangeResolver(r shared.AdjustedCodeIntelligenceRange, locationResolver *sharedresolvers.CachedLocationResolver) CodeIntelligenceRangeResolver { + return &codeIntelligenceRangeResolver{ + r: r, + locationResolver: locationResolver, + } +} + +func (r *codeIntelligenceRangeResolver) Range(ctx context.Context) (RangeResolver, error) { + return NewRangeResolver(convertRange(r.r.Range)), nil +} + +func (r *codeIntelligenceRangeResolver) Definitions(ctx context.Context) (LocationConnectionResolver, error) { + return NewLocationConnectionResolver(r.r.Definitions, nil, r.locationResolver), nil +} + +func (r *codeIntelligenceRangeResolver) References(ctx context.Context) (LocationConnectionResolver, error) { + return NewLocationConnectionResolver(r.r.References, nil, r.locationResolver), nil +} + +func (r *codeIntelligenceRangeResolver) Implementations(ctx context.Context) (LocationConnectionResolver, error) { + return NewLocationConnectionResolver(r.r.Implementations, nil, r.locationResolver), nil +} + +func (r *codeIntelligenceRangeResolver) Hover(ctx context.Context) (HoverResolver, error) { + return NewHoverResolver(r.r.HoverText, convertRange(r.r.Range)), nil +} diff --git a/internal/codeintel/codenav/transport/graphql/ranges_resolver_connection.go b/internal/codeintel/codenav/transport/graphql/ranges_resolver_connection.go new file mode 100644 index 00000000000..0f32c5b8d42 --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/ranges_resolver_connection.go @@ -0,0 +1,36 @@ +package graphql + +import ( + "context" + + "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" +) + +type CodeIntelligenceRangeConnectionResolver interface { + Nodes(ctx context.Context) ([]CodeIntelligenceRangeResolver, error) +} + +type codeIntelligenceRangeConnectionResolver struct { + ranges []shared.AdjustedCodeIntelligenceRange + locationResolver *sharedresolvers.CachedLocationResolver +} + +func NewCodeIntelligenceRangeConnectionResolver(ranges []shared.AdjustedCodeIntelligenceRange, locationResolver *sharedresolvers.CachedLocationResolver) CodeIntelligenceRangeConnectionResolver { + return &codeIntelligenceRangeConnectionResolver{ + ranges: ranges, + locationResolver: locationResolver, + } +} + +func (r *codeIntelligenceRangeConnectionResolver) Nodes(ctx context.Context) ([]CodeIntelligenceRangeResolver, error) { + var resolvers []CodeIntelligenceRangeResolver + for _, rn := range r.ranges { + resolvers = append(resolvers, &codeIntelligenceRangeResolver{ + r: rn, + locationResolver: r.locationResolver, + }) + } + + return resolvers, nil +} diff --git a/internal/codeintel/codenav/transport/graphql/resolver.go b/internal/codeintel/codenav/transport/graphql/resolver.go deleted file mode 100644 index 9d92fbda4e7..00000000000 --- a/internal/codeintel/codenav/transport/graphql/resolver.go +++ /dev/null @@ -1,110 +0,0 @@ -package graphql - -import ( - "context" - "strings" - "time" - - "github.com/opentracing/opentracing-go/log" - - "github.com/sourcegraph/sourcegraph/cmd/frontend/envvar" - "github.com/sourcegraph/sourcegraph/internal/api" - "github.com/sourcegraph/sourcegraph/internal/authz" - "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav" - "github.com/sourcegraph/sourcegraph/internal/observation" - "github.com/sourcegraph/sourcegraph/internal/types" -) - -type Resolver interface { - // Symbols client - GetSupportedByCtags(ctx context.Context, filepath string, repoName api.RepoName) (bool, string, error) - - // Language support - GetLanguagesRequestedBy(ctx context.Context, userID int) (_ []string, err error) - SetRequestLanguageSupport(ctx context.Context, userID int, language string) (err error) - - // Factory for GitBlobLSIFDataResolver - GitBlobLSIFDataResolverFactory(ctx context.Context, repo *types.Repo, commit, path, toolName string, exactPath bool) (_ GitBlobLSIFDataResolver, err error) -} - -type resolver struct { - svc Service - gitserver GitserverClient - autoindexingSvc AutoindexingService - maximumIndexesPerMonikerSearch int - hunkCacheSize int - - // Metrics - operations *operations -} - -func New(svc Service, gitserver GitserverClient, autoindexingSvc AutoindexingService, maxIndexSearch, hunkCacheSize int, observationContext *observation.Context) Resolver { - return &resolver{ - svc: svc, - gitserver: gitserver, - autoindexingSvc: autoindexingSvc, - operations: newOperations(observationContext), - hunkCacheSize: hunkCacheSize, - maximumIndexesPerMonikerSearch: maxIndexSearch, - } -} - -func (r *resolver) GetSupportedByCtags(ctx context.Context, filepath string, repoName api.RepoName) (_ bool, _ string, err error) { - ctx, _, endObservation := r.operations.getSupportedByCtags.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.String("repoName", string(repoName))}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.GetSupportedByCtags(ctx, filepath, repoName) -} - -func (r *resolver) SetRequestLanguageSupport(ctx context.Context, userID int, language string) (err error) { - ctx, _, endObservation := r.operations.setRequestLanguageSupport.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("userID", userID), log.String("language", language)}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.SetRequestLanguageSupport(ctx, userID, language) -} - -func (r *resolver) GetLanguagesRequestedBy(ctx context.Context, userID int) (_ []string, err error) { - ctx, _, endObservation := r.operations.getLanguagesRequestedBy.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("userID", userID)}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.GetLanguagesRequestedBy(ctx, userID) -} - -const slowQueryResolverRequestThreshold = time.Second - -func (r *resolver) GitBlobLSIFDataResolverFactory(ctx context.Context, repo *types.Repo, commit, path, toolName string, exactPath bool) (_ GitBlobLSIFDataResolver, err error) { - ctx, _, endObservation := observeResolver(ctx, &err, r.operations.getGitBlobLSIFDataResolver, slowQueryResolverRequestThreshold, observation.Args{ - LogFields: []log.Field{ - log.Int("repositoryID", int(repo.ID)), - log.String("commit", commit), - log.String("path", path), - log.Bool("exactPath", exactPath), - log.String("indexer", toolName), - }, - }) - defer endObservation() - - uploads, err := r.svc.GetClosestDumpsForBlob(ctx, int(repo.ID), commit, path, exactPath, toolName) - if err != nil { - return nil, err - } - if len(uploads) == 0 { - // If we're on sourcegraph.com and it's a rust package repo, index it on-demand - if envvar.SourcegraphDotComMode() && strings.HasPrefix(string(repo.Name), "crates/") { - err = r.autoindexingSvc.QueueRepoRev(ctx, int(repo.ID), commit) - } - - return nil, err - } - - reqState := codenav.NewRequestState(uploads, authz.DefaultSubRepoPermsChecker, r.gitserver, repo, commit, path, r.maximumIndexesPerMonikerSearch, r.hunkCacheSize) - gbr := NewGitBlobLSIFDataResolver(r.svc, int(repo.ID), commit, path, r.operations, reqState) - - return gbr, nil -} diff --git a/internal/codeintel/codenav/transport/graphql/root_resolver.go b/internal/codeintel/codenav/transport/graphql/root_resolver.go new file mode 100644 index 00000000000..9b493a0f479 --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/root_resolver.go @@ -0,0 +1,65 @@ +package graphql + +import ( + "context" + + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/authz" + "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav" + "github.com/sourcegraph/sourcegraph/internal/observation" + "github.com/sourcegraph/sourcegraph/internal/types" +) + +type RootResolver interface { + GitBlobLSIFData(ctx context.Context, args *GitBlobLSIFDataArgs) (_ GitBlobLSIFDataResolver, err error) +} + +type rootResolver struct { + svc Service + autoindexingSvc AutoIndexingService + uploadSvc UploadsService + policiesSvc PolicyService + gitserver GitserverClient + maximumIndexesPerMonikerSearch int + hunkCacheSize int + + // Metrics + operations *operations +} + +func NewRootResolver(svc Service, autoindexingSvc AutoIndexingService, uploadSvc UploadsService, policiesSvc PolicyService, gitserver GitserverClient, maxIndexSearch, hunkCacheSize int, observationContext *observation.Context) RootResolver { + return &rootResolver{ + svc: svc, + autoindexingSvc: autoindexingSvc, + uploadSvc: uploadSvc, + policiesSvc: policiesSvc, + gitserver: gitserver, + operations: newOperations(observationContext), + hunkCacheSize: hunkCacheSize, + maximumIndexesPerMonikerSearch: maxIndexSearch, + } +} + +type GitBlobLSIFDataArgs struct { + Repo *types.Repo + Commit api.CommitID + Path string + ExactPath bool + ToolName string +} + +// 🚨 SECURITY: dbstore layer handles authz for query resolution +func (r *rootResolver) GitBlobLSIFData(ctx context.Context, args *GitBlobLSIFDataArgs) (_ GitBlobLSIFDataResolver, err error) { + ctx, errTracer, endObservation := r.operations.gitBlobLsifData.WithErrors(ctx, &err, observation.Args{}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + uploads, err := r.svc.GetClosestDumpsForBlob(ctx, int(args.Repo.ID), string(args.Commit), args.Path, args.ExactPath, args.ToolName) + if err != nil || len(uploads) == 0 { + return nil, err + } + + reqState := codenav.NewRequestState(uploads, authz.DefaultSubRepoPermsChecker, r.gitserver, args.Repo, string(args.Commit), args.Path, r.maximumIndexesPerMonikerSearch, r.hunkCacheSize) + gbr := NewGitBlobResolver(r.svc, int(args.Repo.ID), string(args.Commit), args.Path, r.operations, reqState) + + return NewGitBlobLSIFDataResolverQueryResolver(r.autoindexingSvc, r.uploadSvc, r.policiesSvc, r.gitserver, gbr, errTracer), nil +} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/types.go b/internal/codeintel/codenav/transport/graphql/types.go similarity index 57% rename from enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/types.go rename to internal/codeintel/codenav/transport/graphql/types.go index 009a1935db4..2d2f44814bc 100644 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/types.go +++ b/internal/codeintel/codenav/transport/graphql/types.go @@ -1,52 +1,35 @@ package graphql import ( - "time" - - autoindexingShared "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" - store "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/lsifstore" - uploadsShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" ) // AdjustedLocation is a path and range pair from within a particular upload. The adjusted commit // denotes the target commit for which the location was adjusted (the originally requested commit). type AdjustedLocation struct { - Dump store.Dump + Dump types.Dump Path string AdjustedCommit string - AdjustedRange lsifstore.Range -} - -// AdjustedDiagnostic is a diagnostic from within a particular upload. The adjusted commit denotes -// the target commit for which the location was adjusted (the originally requested commit). -type AdjustedDiagnostic struct { - lsifstore.Diagnostic - Dump store.Dump - AdjustedCommit string - AdjustedRange lsifstore.Range + AdjustedRange types.Range } // AdjustedCodeIntelligenceRange stores definition, reference, and hover information for all ranges // within a block of lines. The definition and reference locations have been adjusted to fit the // target (originally requested) commit. type AdjustedCodeIntelligenceRange struct { - Range lsifstore.Range + Range types.Range Definitions []AdjustedLocation References []AdjustedLocation Implementations []AdjustedLocation HoverText string } -type RepositorySummary struct { - RecentUploads []uploadsShared.UploadsWithRepositoryNamespace - RecentIndexes []autoindexingShared.IndexesWithRepositoryNamespace - LastUploadRetentionScan *time.Time - LastIndexScan *time.Time -} - -type RetentionPolicyMatchCandidate struct { - *store.ConfigurationPolicy - Matched bool - ProtectingCommits []string +// AdjustedDiagnostic is a diagnostic from within a particular upload. The adjusted commit denotes +// the target commit for which the location was adjusted (the originally requested commit). +type AdjustedDiagnostic struct { + lsifstore.Diagnostic + Dump types.Dump + AdjustedCommit string + AdjustedRange types.Range } diff --git a/internal/codeintel/codenav/transport/graphql/utils.go b/internal/codeintel/codenav/transport/graphql/utils.go new file mode 100644 index 00000000000..9595917c49c --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/utils.go @@ -0,0 +1,171 @@ +package graphql + +import ( + "context" + "encoding/base64" + + "github.com/sourcegraph/go-lsp" + + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/database" +) + +// convertRange creates an LSP range from a bundle range. +func convertRange(r types.Range) lsp.Range { + return lsp.Range{Start: convertPosition(r.Start.Line, r.Start.Character), End: convertPosition(r.End.Line, r.End.Character)} +} + +func convertPosition(line, character int) lsp.Position { + return lsp.Position{Line: line, Character: character} +} + +func sharedRangeTolspRange(r types.Range) lsp.Range { + return lsp.Range{Start: convertPosition(r.Start.Line, r.Start.Character), End: convertPosition(r.End.Line, r.End.Character)} +} + +// strPtr creates a pointer to the given value. If the value is an +// empty string, a nil pointer is returned. +func strPtr(val string) *string { + if val == "" { + return nil + } + + return &val +} + +// DecodeCursor decodes the given cursor value. It is assumed to be a value previously +// returned from the function encodeCursor. An empty string is returned if no cursor is +// supplied. Invalid cursors return errors. +func DecodeCursor(val *string) (string, error) { + if val == nil { + return "", nil + } + + decoded, err := base64.StdEncoding.DecodeString(*val) + if err != nil { + return "", err + } + + return string(decoded), nil +} + +// derefInt32 returns the underlying value in the given pointer. +// If the pointer is nil, the default value is returned. +func derefInt32(val *int32, defaultValue int) int { + if val != nil { + return int(*val) + } + return defaultValue +} + +// EncodeCursor creates a PageInfo object from the given cursor. If the cursor is not +// defined, then an object indicating the end of the result set is returned. The cursor +// is base64 encoded for transfer, and should be decoded using the function decodeCursor. +func EncodeCursor(val *string) *PageInfo { + if val != nil { + return NextPageCursor(base64.StdEncoding.EncodeToString([]byte(*val))) + } + + return HasNextPage(false) +} + +// PageInfo implements the GraphQL type PageInfo. +type PageInfo struct { + endCursor *string + hasNextPage bool +} + +// HasNextPage returns a new PageInfo with the given hasNextPage value. +func HasNextPage(hasNextPage bool) *PageInfo { + return &PageInfo{hasNextPage: hasNextPage} +} + +// NextPageCursor returns a new PageInfo indicating there is a next page with +// the given end cursor. +func NextPageCursor(endCursor string) *PageInfo { + return &PageInfo{endCursor: &endCursor, hasNextPage: true} +} + +func (r *PageInfo) EndCursor() *string { return r.endCursor } +func (r *PageInfo) HasNextPage() bool { return r.hasNextPage } + +func sharedDumpToDbstoreUpload(dump types.Dump) types.Upload { + return types.Upload{ + ID: dump.ID, + Commit: dump.Commit, + Root: dump.Root, + VisibleAtTip: dump.VisibleAtTip, + UploadedAt: dump.UploadedAt, + State: dump.State, + FailureMessage: dump.FailureMessage, + StartedAt: dump.StartedAt, + FinishedAt: dump.FinishedAt, + ProcessAfter: dump.ProcessAfter, + NumResets: dump.NumResets, + NumFailures: dump.NumFailures, + RepositoryID: dump.RepositoryID, + RepositoryName: dump.RepositoryName, + Indexer: dump.Indexer, + IndexerVersion: dump.IndexerVersion, + NumParts: 0, + UploadedParts: []int{}, + UploadSize: nil, + Rank: nil, + AssociatedIndexID: dump.AssociatedIndexID, + } +} + +// ConnectionArgs is the common set of arguments to GraphQL fields that return connections (lists). +type ConnectionArgs struct { + First *int32 // return the first n items +} + +// Set is a convenience method for setting the DB limit and offset in a DB XyzListOptions struct. +func (a ConnectionArgs) Set(o **database.LimitOffset) { + if a.First != nil { + *o = &database.LimitOffset{Limit: int(*a.First)} + } +} + +// GetFirst is a convenience method returning the value of First, defaulting to +// the type's zero value if nil. +func (a ConnectionArgs) GetFirst() int32 { + if a.First == nil { + return 0 + } + return *a.First +} + +// resolveLocations creates a slide of LocationResolvers for the given list of adjusted locations. The +// resulting list may be smaller than the input list as any locations with a commit not known by +// gitserver will be skipped. +func resolveLocations(ctx context.Context, locationResolver *sharedresolvers.CachedLocationResolver, locations []types.UploadLocation) ([]LocationResolver, error) { + resolvedLocations := make([]LocationResolver, 0, len(locations)) + for i := range locations { + resolver, err := resolveLocation(ctx, locationResolver, locations[i]) + if err != nil { + return nil, err + } + if resolver == nil { + continue + } + + resolvedLocations = append(resolvedLocations, resolver) + } + + return resolvedLocations, nil +} + +// resolveLocation creates a LocationResolver for the given adjusted location. This function may return a +// nil resolver if the location's commit is not known by gitserver. +func resolveLocation(ctx context.Context, locationResolver *sharedresolvers.CachedLocationResolver, location types.UploadLocation) (LocationResolver, error) { + treeResolver, err := locationResolver.Path(ctx, api.RepoID(location.Dump.RepositoryID), location.TargetCommit, location.Path) + if err != nil || treeResolver == nil { + return nil, err + } + + lspRange := convertRange(location.TargetRange) + return NewLocationResolver(treeResolver, &lspRange), nil +} diff --git a/internal/codeintel/codenav/transport/graphql/utils_test.go b/internal/codeintel/codenav/transport/graphql/utils_test.go new file mode 100644 index 00000000000..bd9ad676a93 --- /dev/null +++ b/internal/codeintel/codenav/transport/graphql/utils_test.go @@ -0,0 +1,113 @@ +package graphql + +import ( + "context" + "fmt" + "testing" + + mockrequire "github.com/derision-test/go-mockgen/testutil/require" + + "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/database" + "github.com/sourcegraph/sourcegraph/internal/gitserver" + "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" + sgtypes "github.com/sourcegraph/sourcegraph/internal/types" +) + +func TestCursor(t *testing.T) { + expected := "test" + pageInfo := EncodeCursor(&expected) + + if !pageInfo.HasNextPage() { + t.Fatalf("expected next page") + } + if pageInfo.EndCursor() == nil { + t.Fatalf("unexpected nil cursor") + } + + value, err := DecodeCursor(pageInfo.EndCursor()) + if err != nil { + t.Fatalf("unexpected error decoding cursor: %s", err) + } + if value != expected { + t.Errorf("unexpected decoded cursor. want=%s have=%s", expected, value) + } +} + +func TestCursorEmpty(t *testing.T) { + pageInfo := EncodeCursor(nil) + + if pageInfo.HasNextPage() { + t.Errorf("unexpected next page") + } + if pageInfo.EndCursor() != nil { + t.Errorf("unexpected encoded cursor: %s", *pageInfo.EndCursor()) + } + + value, err := DecodeCursor(nil) + if err != nil { + t.Fatalf("unexpected error decoding cursor: %s", err) + } + if value != "" { + t.Errorf("unexpected decoded cursor: %s", value) + } +} + +func TestResolveLocations(t *testing.T) { + repos := database.NewStrictMockRepoStore() + repos.GetFunc.SetDefaultHook(func(_ context.Context, id api.RepoID) (*sgtypes.Repo, error) { + return &sgtypes.Repo{ID: id, Name: api.RepoName(fmt.Sprintf("repo%d", id))}, nil + }) + + db := database.NewStrictMockDB() + db.ReposFunc.SetDefaultReturn(repos) + + t.Cleanup(func() { + gitserver.Mocks.ResolveRevision = nil + backend.Mocks.Repos.GetCommit = nil + }) + + gitserver.Mocks.ResolveRevision = func(spec string, _ gitserver.ResolveRevisionOptions) (api.CommitID, error) { + if spec == "deadbeef3" { + return "", &gitdomain.RevisionNotFoundError{} + } + return api.CommitID(spec), nil + } + + backend.Mocks.Repos.GetCommit = func(v0 context.Context, repo *sgtypes.Repo, commitID api.CommitID) (*gitdomain.Commit, error) { + return &gitdomain.Commit{ID: commitID}, nil + } + + r1 := types.Range{Start: types.Position{Line: 11, Character: 12}, End: types.Position{Line: 13, Character: 14}} + r2 := types.Range{Start: types.Position{Line: 21, Character: 22}, End: types.Position{Line: 23, Character: 24}} + r3 := types.Range{Start: types.Position{Line: 31, Character: 32}, End: types.Position{Line: 33, Character: 34}} + r4 := types.Range{Start: types.Position{Line: 41, Character: 42}, End: types.Position{Line: 43, Character: 44}} + + locations, err := resolveLocations(context.Background(), sharedresolvers.NewCachedLocationResolver(db), []types.UploadLocation{ + {Dump: types.Dump{RepositoryID: 50}, TargetCommit: "deadbeef1", TargetRange: r1, Path: "p1"}, + {Dump: types.Dump{RepositoryID: 51}, TargetCommit: "deadbeef2", TargetRange: r2, Path: "p2"}, + {Dump: types.Dump{RepositoryID: 52}, TargetCommit: "deadbeef3", TargetRange: r3, Path: "p3"}, + {Dump: types.Dump{RepositoryID: 53}, TargetCommit: "deadbeef4", TargetRange: r4, Path: "p4"}, + }) + if err != nil { + t.Fatalf("Unexpected error: %s", err) + } + + mockrequire.Called(t, repos.GetFunc) + + if len(locations) != 3 { + t.Fatalf("unexpected length. want=%d have=%d", 3, len(locations)) + } + if url := locations[0].CanonicalURL(); url != "/repo50@deadbeef1/-/blob/p1?L12:13-14:15" { + t.Errorf("unexpected canonical url. want=%s have=%s", "/repo50@deadbeef1/-/blob/p1?L12:13-14:15", url) + } + if url := locations[1].CanonicalURL(); url != "/repo51@deadbeef2/-/blob/p2?L22:23-24:25" { + t.Errorf("unexpected canonical url. want=%s have=%s", "/repo51@deadbeef2/-/blob/p2?L22:23-24:25", url) + } + if url := locations[2].CanonicalURL(); url != "/repo53@deadbeef4/-/blob/p4?L42:43-44:45" { + t.Errorf("unexpected canonical url. want=%s have=%s", "/repo53@deadbeef4/-/blob/p4?L42:43-44:45", url) + } +} diff --git a/internal/codeintel/codenav/types.go b/internal/codeintel/codenav/types.go index 0139a24d4d3..04939f28293 100644 --- a/internal/codeintel/codenav/types.go +++ b/internal/codeintel/codenav/types.go @@ -3,16 +3,16 @@ package codenav import ( "strings" - "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" ) // visibleUpload pairs an upload visible from the current target commit with the // current target path and position matched to the data within the underlying index. type visibleUpload struct { - Upload shared.Dump + Upload types.Dump TargetPath string - TargetPosition shared.Position + TargetPosition types.Position TargetPathWithoutRoot string } diff --git a/internal/codeintel/codenav/utils.go b/internal/codeintel/codenav/utils.go index 6bcf88407b4..9f77314a974 100644 --- a/internal/codeintel/codenav/utils.go +++ b/internal/codeintel/codenav/utils.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/lib/codeintel/precise" ) @@ -28,7 +29,7 @@ func sliceContains(slice []string, str string) bool { return false } -func uploadIDsToString(vs []shared.Dump) string { +func uploadIDsToString(vs []types.Dump) string { ids := make([]string, 0, len(vs)) for _, v := range vs { ids = append(ids, strconv.Itoa(v.ID)) @@ -51,7 +52,7 @@ func isSourceLocation(visibleUploads []visibleUpload, location shared.Location) } // rangeContainsPosition returns true if the given range encloses the given position. -func rangeContainsPosition(r shared.Range, pos shared.Position) bool { +func rangeContainsPosition(r types.Range, pos types.Position) bool { if pos.Line < r.Start.Line { return false } @@ -71,7 +72,7 @@ func rangeContainsPosition(r shared.Range, pos shared.Position) bool { return true } -func sortRanges(ranges []shared.Range) []shared.Range { +func sortRanges(ranges []types.Range) []types.Range { sort.Slice(ranges, func(i, j int) bool { iStart := ranges[i].Start jStart := ranges[j].Start diff --git a/internal/codeintel/policies/background/repomatcher/iface.go b/internal/codeintel/policies/background/repomatcher/iface.go index 6945009b22a..2b61b408cfa 100644 --- a/internal/codeintel/policies/background/repomatcher/iface.go +++ b/internal/codeintel/policies/background/repomatcher/iface.go @@ -3,10 +3,10 @@ package repomatcher import ( "context" - "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" ) type PolicyService interface { - SelectPoliciesForRepositoryMembershipUpdate(ctx context.Context, batchSize int) (configurationPolicies []shared.ConfigurationPolicy, err error) + SelectPoliciesForRepositoryMembershipUpdate(ctx context.Context, batchSize int) (configurationPolicies []types.ConfigurationPolicy, err error) UpdateReposMatchingPatterns(ctx context.Context, patterns []string, policyID int, repositoryMatchLimit *int) (err error) } diff --git a/internal/codeintel/policies/enterprise/matcher.go b/internal/codeintel/policies/enterprise/matcher.go index 8dec6751a9d..dae02dc9e14 100644 --- a/internal/codeintel/policies/enterprise/matcher.go +++ b/internal/codeintel/policies/enterprise/matcher.go @@ -7,8 +7,8 @@ import ( "github.com/gobwas/glob" - "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" "github.com/sourcegraph/sourcegraph/lib/errors" ) @@ -107,7 +107,7 @@ func (m *Matcher) CommitsDescribedByPolicy(ctx context.Context, repositoryID int return context.commitMap, nil } -func (m *Matcher) CommitsDescribedByPolicyInternal(ctx context.Context, repositoryID int, policies []shared.ConfigurationPolicy, now time.Time, filterCommits ...string) (map[string][]PolicyMatch, error) { +func (m *Matcher) CommitsDescribedByPolicyInternal(ctx context.Context, repositoryID int, policies []types.ConfigurationPolicy, now time.Time, filterCommits ...string) (map[string][]PolicyMatch, error) { dbStorePolicies := make([]dbstore.ConfigurationPolicy, 0, len(policies)) for _, p := range policies { dbStorePolicies = append(dbStorePolicies, dbstore.ConfigurationPolicy{ diff --git a/internal/codeintel/policies/internal/store/scan.go b/internal/codeintel/policies/internal/store/scan.go index b1a611670bf..55f1ee072c2 100644 --- a/internal/codeintel/policies/internal/store/scan.go +++ b/internal/codeintel/policies/internal/store/scan.go @@ -6,6 +6,7 @@ import ( "github.com/lib/pq" "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/database/dbutil" ) @@ -21,7 +22,7 @@ var scanPolicies = basestore.NewSliceScanner(scanPolicy) // scanConfigurationPolicies scans a slice of configuration policies from the return value of `*Store.query`. var scanConfigurationPolicies = basestore.NewSliceScanner(scanConfigurationPolicy) -func scanConfigurationPolicy(s dbutil.Scanner) (configurationPolicy shared.ConfigurationPolicy, err error) { +func scanConfigurationPolicy(s dbutil.Scanner) (configurationPolicy types.ConfigurationPolicy, err error) { var repositoryPatterns []string var retentionDurationHours, indexCommitMaxAgeHours *int diff --git a/internal/codeintel/policies/internal/store/store.go b/internal/codeintel/policies/internal/store/store.go index adef813fab6..465586ff511 100644 --- a/internal/codeintel/policies/internal/store/store.go +++ b/internal/codeintel/policies/internal/store/store.go @@ -5,7 +5,7 @@ import ( logger "github.com/sourcegraph/log" - "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/observation" @@ -14,16 +14,19 @@ import ( // Store provides the interface for policies storage. type Store interface { // Configurations - GetConfigurationPolicies(ctx context.Context, opts shared.GetConfigurationPoliciesOptions) (_ []shared.ConfigurationPolicy, totalCount int, err error) - GetConfigurationPolicyByID(ctx context.Context, id int) (_ shared.ConfigurationPolicy, _ bool, err error) - CreateConfigurationPolicy(ctx context.Context, configurationPolicy shared.ConfigurationPolicy) (shared.ConfigurationPolicy, error) - UpdateConfigurationPolicy(ctx context.Context, policy shared.ConfigurationPolicy) (err error) + GetConfigurationPolicies(ctx context.Context, opts types.GetConfigurationPoliciesOptions) (_ []types.ConfigurationPolicy, totalCount int, err error) + GetConfigurationPolicyByID(ctx context.Context, id int) (_ types.ConfigurationPolicy, _ bool, err error) + CreateConfigurationPolicy(ctx context.Context, configurationPolicy types.ConfigurationPolicy) (types.ConfigurationPolicy, error) + UpdateConfigurationPolicy(ctx context.Context, policy types.ConfigurationPolicy) (err error) DeleteConfigurationPolicyByID(ctx context.Context, id int) (err error) // Repositories GetRepoIDsByGlobPatterns(ctx context.Context, patterns []string, limit, offset int) (_ []int, _ int, err error) UpdateReposMatchingPatterns(ctx context.Context, patterns []string, policyID int, repositoryMatchLimit *int) (err error) - SelectPoliciesForRepositoryMembershipUpdate(ctx context.Context, batchSize int) (configurationPolicies []shared.ConfigurationPolicy, err error) + + // Utilities + GetUnsafeDB() database.DB + SelectPoliciesForRepositoryMembershipUpdate(ctx context.Context, batchSize int) (configurationPolicies []types.ConfigurationPolicy, err error) } // store manages the policies store. @@ -41,3 +44,9 @@ func New(db database.DB, observationContext *observation.Context) Store { operations: newOperations(observationContext), } } + +// GetUnsafeDB returns the underlying database handle. This is used by the +// resolvers that have the old convention of using the database handle directly. +func (s *store) GetUnsafeDB() database.DB { + return database.NewDBWith(s.logger, s.db) +} diff --git a/internal/codeintel/policies/internal/store/store_configuration.go b/internal/codeintel/policies/internal/store/store_configuration.go index a45fd463def..10e237f2d10 100644 --- a/internal/codeintel/policies/internal/store/store_configuration.go +++ b/internal/codeintel/policies/internal/store/store_configuration.go @@ -9,7 +9,7 @@ import ( "github.com/lib/pq" "github.com/opentracing/opentracing-go/log" - "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/observation" @@ -18,7 +18,7 @@ import ( // GetConfigurationPolicies retrieves the set of configuration policies matching the the given options. // If a repository identifier is supplied (is non-zero), then only the configuration policies that apply // to repository are returned. If repository is not supplied, then all policies may be returned. -func (s *store) GetConfigurationPolicies(ctx context.Context, opts shared.GetConfigurationPoliciesOptions) (_ []shared.ConfigurationPolicy, totalCount int, err error) { +func (s *store) GetConfigurationPolicies(ctx context.Context, opts types.GetConfigurationPoliciesOptions) (_ []types.ConfigurationPolicy, totalCount int, err error) { ctx, trace, endObservation := s.operations.getConfigurationPolicies.With(ctx, &err, observation.Args{LogFields: []log.Field{ log.Int("repositoryID", opts.RepositoryID), log.String("term", opts.Term), @@ -118,7 +118,7 @@ LIMIT %s OFFSET %s ` // GetConfigurationPolicyByID retrieves the configuration policy with the given identifier. -func (s *store) GetConfigurationPolicyByID(ctx context.Context, id int) (_ shared.ConfigurationPolicy, _ bool, err error) { +func (s *store) GetConfigurationPolicyByID(ctx context.Context, id int) (_ types.ConfigurationPolicy, _ bool, err error) { ctx, _, endObservation := s.operations.getConfigurationPolicyByID.With(ctx, &err, observation.Args{LogFields: []log.Field{ log.Int("id", id), }}) @@ -126,7 +126,7 @@ func (s *store) GetConfigurationPolicyByID(ctx context.Context, id int) (_ share authzConds, err := database.AuthzQueryConds(ctx, database.NewDBWith(s.logger, s.db)) if err != nil { - return shared.ConfigurationPolicy{}, false, err + return types.ConfigurationPolicy{}, false, err } return scanFirstConfigurationPolicy(s.db.Query(ctx, sqlf.Sprintf(getConfigurationPolicyByIDQuery, id, authzConds))) @@ -157,7 +157,7 @@ WHERE p.id = %s AND (p.repository_id IS NULL OR (%s)) // CreateConfigurationPolicy creates a configuration policy with the given fields (ignoring ID). The hydrated // configuration policy record is returned. -func (s *store) CreateConfigurationPolicy(ctx context.Context, configurationPolicy shared.ConfigurationPolicy) (_ shared.ConfigurationPolicy, err error) { +func (s *store) CreateConfigurationPolicy(ctx context.Context, configurationPolicy types.ConfigurationPolicy) (_ types.ConfigurationPolicy, err error) { ctx, _, endObservation := s.operations.createConfigurationPolicy.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) @@ -193,7 +193,7 @@ func (s *store) CreateConfigurationPolicy(ctx context.Context, configurationPoli configurationPolicy.IndexIntermediateCommits, ))) if err != nil { - return shared.ConfigurationPolicy{}, err + return types.ConfigurationPolicy{}, err } return hydratedConfigurationPolicy, nil @@ -237,7 +237,7 @@ var ( ) // UpdateConfigurationPolicy updates the fields of the configuration policy record with the given identifier. -func (s *store) UpdateConfigurationPolicy(ctx context.Context, policy shared.ConfigurationPolicy) (err error) { +func (s *store) UpdateConfigurationPolicy(ctx context.Context, policy types.ConfigurationPolicy) (err error) { ctx, _, endObservation := s.operations.updateConfigurationPolicy.With(ctx, &err, observation.Args{LogFields: []log.Field{ log.Int("id", policy.ID), }}) diff --git a/internal/codeintel/policies/internal/store/store_configuration_test.go b/internal/codeintel/policies/internal/store/store_configuration_test.go index a5fdfd2d1cc..0f7016c80c3 100644 --- a/internal/codeintel/policies/internal/store/store_configuration_test.go +++ b/internal/codeintel/policies/internal/store/store_configuration_test.go @@ -12,7 +12,7 @@ import ( "github.com/keegancsmith/sqlf" "github.com/sourcegraph/log/logtest" - "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/observation" @@ -108,7 +108,7 @@ func TestGetConfigurationPolicies(t *testing.T) { ) t.Run(name, func(t *testing.T) { - policies, totalCount, err := store.GetConfigurationPolicies(ctx, shared.GetConfigurationPoliciesOptions{ + policies, totalCount, err := store.GetConfigurationPolicies(ctx, types.GetConfigurationPoliciesOptions{ RepositoryID: testCase.repositoryID, Term: testCase.term, ForDataRetention: testCase.forDataRetention, @@ -160,10 +160,10 @@ func TestDeleteConfigurationPolicyByID(t *testing.T) { d1 := time.Hour * 5 d2 := time.Hour * 6 - configurationPolicy := shared.ConfigurationPolicy{ + configurationPolicy := types.ConfigurationPolicy{ RepositoryID: &repositoryID, Name: "name", - Type: shared.GitObjectTypeCommit, + Type: types.GitObjectTypeCommit, Pattern: "deadbeef", RetentionEnabled: false, RetentionDuration: &d1, @@ -204,10 +204,10 @@ func TestDeleteConfigurationProtectedPolicy(t *testing.T) { d1 := time.Hour * 5 d2 := time.Hour * 6 - configurationPolicy := shared.ConfigurationPolicy{ + configurationPolicy := types.ConfigurationPolicy{ RepositoryID: &repositoryID, Name: "name", - Type: shared.GitObjectTypeCommit, + Type: types.GitObjectTypeCommit, Pattern: "deadbeef", RetentionEnabled: false, RetentionDuration: &d1, diff --git a/internal/codeintel/policies/internal/store/store_repo_test.go b/internal/codeintel/policies/internal/store/store_repo_test.go index 9b9e44180ef..e1f7bf00175 100644 --- a/internal/codeintel/policies/internal/store/store_repo_test.go +++ b/internal/codeintel/policies/internal/store/store_repo_test.go @@ -11,7 +11,7 @@ import ( "github.com/sourcegraph/log/logtest" "github.com/sourcegraph/sourcegraph/cmd/frontend/globals" - "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" @@ -228,7 +228,7 @@ func TestSelectPoliciesForRepositoryMembershipUpdate(t *testing.T) { t.Fatalf("unexpected error while inserting configuration policies: %s", err) } - ids := func(policies []shared.ConfigurationPolicy) (ids []int) { + ids := func(policies []types.ConfigurationPolicy) (ids []int) { for _, policy := range policies { ids = append(ids, policy.ID) } diff --git a/internal/codeintel/policies/internal/store/store_repos.go b/internal/codeintel/policies/internal/store/store_repos.go index ef2968edb94..20de7386a99 100644 --- a/internal/codeintel/policies/internal/store/store_repos.go +++ b/internal/codeintel/policies/internal/store/store_repos.go @@ -7,7 +7,7 @@ import ( "github.com/keegancsmith/sqlf" "github.com/opentracing/opentracing-go/log" - "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/observation" @@ -52,7 +52,7 @@ func (s *store) UpdateReposMatchingPatterns(ctx context.Context, patterns []stri } const updateReposMatchingPatternsQuery = ` --- source: internal/codeintel/policies/internal/store/store_configuration.go:UpdateReposMatchingPatterns +-- source: internal/codeintel/policies/internal/store/store_repos.go:UpdateReposMatchingPatterns WITH matching_repositories AS ( SELECT id AS repo_id @@ -150,7 +150,7 @@ func (s *store) GetRepoIDsByGlobPatterns(ctx context.Context, patterns []string, } const repoIDsByGlobPatternsCountQuery = ` --- source: internal/codeintel/stores/dbstore/repo.go:RepoIDsByGlobPatterns +-- source: internal/codeintel/policies/internal/store/store_repos.go:RepoIDsByGlobPatterns SELECT COUNT(*) FROM repo WHERE @@ -161,7 +161,7 @@ WHERE ` const repoIDsByGlobPatternsQuery = ` --- source: internal/codeintel/stores/dbstore/repo.go:RepoIDsByGlobPatterns +-- source: internal/codeintel/policies/internal/store/store_repos.go:RepoIDsByGlobPatterns SELECT id FROM repo WHERE @@ -175,7 +175,7 @@ LIMIT %s OFFSET %s // SelectPoliciesForRepositoryMembershipUpdate returns a slice of configuration policies that should be considered // for repository membership updates. Configuration policies are returned in the order of least recently updated. -func (s *store) SelectPoliciesForRepositoryMembershipUpdate(ctx context.Context, batchSize int) (configurationPolicies []shared.ConfigurationPolicy, err error) { +func (s *store) SelectPoliciesForRepositoryMembershipUpdate(ctx context.Context, batchSize int) (configurationPolicies []types.ConfigurationPolicy, err error) { ctx, trace, endObservation := s.operations.selectPoliciesForRepositoryMembershipUpdate.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) @@ -189,7 +189,7 @@ func (s *store) SelectPoliciesForRepositoryMembershipUpdate(ctx context.Context, } const selectPoliciesForRepositoryMembershipUpdate = ` --- source: internal/codeintel/stores/dbstore/configuration_policies.go:SelectPoliciesForRepositoryMembershipUpdate +-- source: internal/codeintel/policies/internal/store/store_repos.go:SelectPoliciesForRepositoryMembershipUpdate WITH candidate_policies AS ( SELECT p.id diff --git a/internal/codeintel/policies/mocks_test.go b/internal/codeintel/policies/mocks_test.go index 03bddffea3c..5c82c789d12 100644 --- a/internal/codeintel/policies/mocks_test.go +++ b/internal/codeintel/policies/mocks_test.go @@ -12,7 +12,8 @@ import ( "time" store "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/internal/store" - shared "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" + types "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + database "github.com/sourcegraph/sourcegraph/internal/database" gitdomain "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" ) @@ -39,6 +40,9 @@ type MockStore struct { // GetRepoIDsByGlobPatternsFunc is an instance of a mock function object // controlling the behavior of the method GetRepoIDsByGlobPatterns. GetRepoIDsByGlobPatternsFunc *StoreGetRepoIDsByGlobPatternsFunc + // GetUnsafeDBFunc is an instance of a mock function object controlling + // the behavior of the method GetUnsafeDB. + GetUnsafeDBFunc *StoreGetUnsafeDBFunc // SelectPoliciesForRepositoryMembershipUpdateFunc is an instance of a // mock function object controlling the behavior of the method // SelectPoliciesForRepositoryMembershipUpdate. @@ -58,7 +62,7 @@ type MockStore struct { func NewMockStore() *MockStore { return &MockStore{ CreateConfigurationPolicyFunc: &StoreCreateConfigurationPolicyFunc{ - defaultHook: func(context.Context, shared.ConfigurationPolicy) (r0 shared.ConfigurationPolicy, r1 error) { + defaultHook: func(context.Context, types.ConfigurationPolicy) (r0 types.ConfigurationPolicy, r1 error) { return }, }, @@ -68,12 +72,12 @@ func NewMockStore() *MockStore { }, }, GetConfigurationPoliciesFunc: &StoreGetConfigurationPoliciesFunc{ - defaultHook: func(context.Context, shared.GetConfigurationPoliciesOptions) (r0 []shared.ConfigurationPolicy, r1 int, r2 error) { + defaultHook: func(context.Context, types.GetConfigurationPoliciesOptions) (r0 []types.ConfigurationPolicy, r1 int, r2 error) { return }, }, GetConfigurationPolicyByIDFunc: &StoreGetConfigurationPolicyByIDFunc{ - defaultHook: func(context.Context, int) (r0 shared.ConfigurationPolicy, r1 bool, r2 error) { + defaultHook: func(context.Context, int) (r0 types.ConfigurationPolicy, r1 bool, r2 error) { return }, }, @@ -82,13 +86,18 @@ func NewMockStore() *MockStore { return }, }, + GetUnsafeDBFunc: &StoreGetUnsafeDBFunc{ + defaultHook: func() (r0 database.DB) { + return + }, + }, SelectPoliciesForRepositoryMembershipUpdateFunc: &StoreSelectPoliciesForRepositoryMembershipUpdateFunc{ - defaultHook: func(context.Context, int) (r0 []shared.ConfigurationPolicy, r1 error) { + defaultHook: func(context.Context, int) (r0 []types.ConfigurationPolicy, r1 error) { return }, }, UpdateConfigurationPolicyFunc: &StoreUpdateConfigurationPolicyFunc{ - defaultHook: func(context.Context, shared.ConfigurationPolicy) (r0 error) { + defaultHook: func(context.Context, types.ConfigurationPolicy) (r0 error) { return }, }, @@ -105,7 +114,7 @@ func NewMockStore() *MockStore { func NewStrictMockStore() *MockStore { return &MockStore{ CreateConfigurationPolicyFunc: &StoreCreateConfigurationPolicyFunc{ - defaultHook: func(context.Context, shared.ConfigurationPolicy) (shared.ConfigurationPolicy, error) { + defaultHook: func(context.Context, types.ConfigurationPolicy) (types.ConfigurationPolicy, error) { panic("unexpected invocation of MockStore.CreateConfigurationPolicy") }, }, @@ -115,12 +124,12 @@ func NewStrictMockStore() *MockStore { }, }, GetConfigurationPoliciesFunc: &StoreGetConfigurationPoliciesFunc{ - defaultHook: func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) { + defaultHook: func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) { panic("unexpected invocation of MockStore.GetConfigurationPolicies") }, }, GetConfigurationPolicyByIDFunc: &StoreGetConfigurationPolicyByIDFunc{ - defaultHook: func(context.Context, int) (shared.ConfigurationPolicy, bool, error) { + defaultHook: func(context.Context, int) (types.ConfigurationPolicy, bool, error) { panic("unexpected invocation of MockStore.GetConfigurationPolicyByID") }, }, @@ -129,13 +138,18 @@ func NewStrictMockStore() *MockStore { panic("unexpected invocation of MockStore.GetRepoIDsByGlobPatterns") }, }, + GetUnsafeDBFunc: &StoreGetUnsafeDBFunc{ + defaultHook: func() database.DB { + panic("unexpected invocation of MockStore.GetUnsafeDB") + }, + }, SelectPoliciesForRepositoryMembershipUpdateFunc: &StoreSelectPoliciesForRepositoryMembershipUpdateFunc{ - defaultHook: func(context.Context, int) ([]shared.ConfigurationPolicy, error) { + defaultHook: func(context.Context, int) ([]types.ConfigurationPolicy, error) { panic("unexpected invocation of MockStore.SelectPoliciesForRepositoryMembershipUpdate") }, }, UpdateConfigurationPolicyFunc: &StoreUpdateConfigurationPolicyFunc{ - defaultHook: func(context.Context, shared.ConfigurationPolicy) error { + defaultHook: func(context.Context, types.ConfigurationPolicy) error { panic("unexpected invocation of MockStore.UpdateConfigurationPolicy") }, }, @@ -166,6 +180,9 @@ func NewMockStoreFrom(i store.Store) *MockStore { GetRepoIDsByGlobPatternsFunc: &StoreGetRepoIDsByGlobPatternsFunc{ defaultHook: i.GetRepoIDsByGlobPatterns, }, + GetUnsafeDBFunc: &StoreGetUnsafeDBFunc{ + defaultHook: i.GetUnsafeDB, + }, SelectPoliciesForRepositoryMembershipUpdateFunc: &StoreSelectPoliciesForRepositoryMembershipUpdateFunc{ defaultHook: i.SelectPoliciesForRepositoryMembershipUpdate, }, @@ -182,15 +199,15 @@ func NewMockStoreFrom(i store.Store) *MockStore { // CreateConfigurationPolicy method of the parent MockStore instance is // invoked. type StoreCreateConfigurationPolicyFunc struct { - defaultHook func(context.Context, shared.ConfigurationPolicy) (shared.ConfigurationPolicy, error) - hooks []func(context.Context, shared.ConfigurationPolicy) (shared.ConfigurationPolicy, error) + defaultHook func(context.Context, types.ConfigurationPolicy) (types.ConfigurationPolicy, error) + hooks []func(context.Context, types.ConfigurationPolicy) (types.ConfigurationPolicy, error) history []StoreCreateConfigurationPolicyFuncCall mutex sync.Mutex } // CreateConfigurationPolicy delegates to the next hook function in the // queue and stores the parameter and result values of this invocation. -func (m *MockStore) CreateConfigurationPolicy(v0 context.Context, v1 shared.ConfigurationPolicy) (shared.ConfigurationPolicy, error) { +func (m *MockStore) CreateConfigurationPolicy(v0 context.Context, v1 types.ConfigurationPolicy) (types.ConfigurationPolicy, error) { r0, r1 := m.CreateConfigurationPolicyFunc.nextHook()(v0, v1) m.CreateConfigurationPolicyFunc.appendCall(StoreCreateConfigurationPolicyFuncCall{v0, v1, r0, r1}) return r0, r1 @@ -199,7 +216,7 @@ func (m *MockStore) CreateConfigurationPolicy(v0 context.Context, v1 shared.Conf // SetDefaultHook sets function that is called when the // CreateConfigurationPolicy method of the parent MockStore instance is // invoked and the hook queue is empty. -func (f *StoreCreateConfigurationPolicyFunc) SetDefaultHook(hook func(context.Context, shared.ConfigurationPolicy) (shared.ConfigurationPolicy, error)) { +func (f *StoreCreateConfigurationPolicyFunc) SetDefaultHook(hook func(context.Context, types.ConfigurationPolicy) (types.ConfigurationPolicy, error)) { f.defaultHook = hook } @@ -207,7 +224,7 @@ func (f *StoreCreateConfigurationPolicyFunc) SetDefaultHook(hook func(context.Co // CreateConfigurationPolicy method of the parent MockStore instance invokes // the hook at the front of the queue and discards it. After the queue is // empty, the default hook function is invoked for any future action. -func (f *StoreCreateConfigurationPolicyFunc) PushHook(hook func(context.Context, shared.ConfigurationPolicy) (shared.ConfigurationPolicy, error)) { +func (f *StoreCreateConfigurationPolicyFunc) PushHook(hook func(context.Context, types.ConfigurationPolicy) (types.ConfigurationPolicy, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -215,20 +232,20 @@ func (f *StoreCreateConfigurationPolicyFunc) PushHook(hook func(context.Context, // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreCreateConfigurationPolicyFunc) SetDefaultReturn(r0 shared.ConfigurationPolicy, r1 error) { - f.SetDefaultHook(func(context.Context, shared.ConfigurationPolicy) (shared.ConfigurationPolicy, error) { +func (f *StoreCreateConfigurationPolicyFunc) SetDefaultReturn(r0 types.ConfigurationPolicy, r1 error) { + f.SetDefaultHook(func(context.Context, types.ConfigurationPolicy) (types.ConfigurationPolicy, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreCreateConfigurationPolicyFunc) PushReturn(r0 shared.ConfigurationPolicy, r1 error) { - f.PushHook(func(context.Context, shared.ConfigurationPolicy) (shared.ConfigurationPolicy, error) { +func (f *StoreCreateConfigurationPolicyFunc) PushReturn(r0 types.ConfigurationPolicy, r1 error) { + f.PushHook(func(context.Context, types.ConfigurationPolicy) (types.ConfigurationPolicy, error) { return r0, r1 }) } -func (f *StoreCreateConfigurationPolicyFunc) nextHook() func(context.Context, shared.ConfigurationPolicy) (shared.ConfigurationPolicy, error) { +func (f *StoreCreateConfigurationPolicyFunc) nextHook() func(context.Context, types.ConfigurationPolicy) (types.ConfigurationPolicy, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -267,10 +284,10 @@ type StoreCreateConfigurationPolicyFuncCall struct { Arg0 context.Context // Arg1 is the value of the 2nd argument passed to this method // invocation. - Arg1 shared.ConfigurationPolicy + Arg1 types.ConfigurationPolicy // Result0 is the value of the 1st result returned from this method // invocation. - Result0 shared.ConfigurationPolicy + Result0 types.ConfigurationPolicy // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error @@ -400,15 +417,15 @@ func (c StoreDeleteConfigurationPolicyByIDFuncCall) Results() []interface{} { // GetConfigurationPolicies method of the parent MockStore instance is // invoked. type StoreGetConfigurationPoliciesFunc struct { - defaultHook func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) - hooks []func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) + defaultHook func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) + hooks []func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) history []StoreGetConfigurationPoliciesFuncCall mutex sync.Mutex } // GetConfigurationPolicies delegates to the next hook function in the queue // and stores the parameter and result values of this invocation. -func (m *MockStore) GetConfigurationPolicies(v0 context.Context, v1 shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) { +func (m *MockStore) GetConfigurationPolicies(v0 context.Context, v1 types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) { r0, r1, r2 := m.GetConfigurationPoliciesFunc.nextHook()(v0, v1) m.GetConfigurationPoliciesFunc.appendCall(StoreGetConfigurationPoliciesFuncCall{v0, v1, r0, r1, r2}) return r0, r1, r2 @@ -417,7 +434,7 @@ func (m *MockStore) GetConfigurationPolicies(v0 context.Context, v1 shared.GetCo // SetDefaultHook sets function that is called when the // GetConfigurationPolicies method of the parent MockStore instance is // invoked and the hook queue is empty. -func (f *StoreGetConfigurationPoliciesFunc) SetDefaultHook(hook func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error)) { +func (f *StoreGetConfigurationPoliciesFunc) SetDefaultHook(hook func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error)) { f.defaultHook = hook } @@ -425,7 +442,7 @@ func (f *StoreGetConfigurationPoliciesFunc) SetDefaultHook(hook func(context.Con // GetConfigurationPolicies method of the parent MockStore instance invokes // the hook at the front of the queue and discards it. After the queue is // empty, the default hook function is invoked for any future action. -func (f *StoreGetConfigurationPoliciesFunc) PushHook(hook func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error)) { +func (f *StoreGetConfigurationPoliciesFunc) PushHook(hook func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -433,20 +450,20 @@ func (f *StoreGetConfigurationPoliciesFunc) PushHook(hook func(context.Context, // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreGetConfigurationPoliciesFunc) SetDefaultReturn(r0 []shared.ConfigurationPolicy, r1 int, r2 error) { - f.SetDefaultHook(func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) { +func (f *StoreGetConfigurationPoliciesFunc) SetDefaultReturn(r0 []types.ConfigurationPolicy, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) { return r0, r1, r2 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreGetConfigurationPoliciesFunc) PushReturn(r0 []shared.ConfigurationPolicy, r1 int, r2 error) { - f.PushHook(func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) { +func (f *StoreGetConfigurationPoliciesFunc) PushReturn(r0 []types.ConfigurationPolicy, r1 int, r2 error) { + f.PushHook(func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) { return r0, r1, r2 }) } -func (f *StoreGetConfigurationPoliciesFunc) nextHook() func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) { +func (f *StoreGetConfigurationPoliciesFunc) nextHook() func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -485,10 +502,10 @@ type StoreGetConfigurationPoliciesFuncCall struct { Arg0 context.Context // Arg1 is the value of the 2nd argument passed to this method // invocation. - Arg1 shared.GetConfigurationPoliciesOptions + Arg1 types.GetConfigurationPoliciesOptions // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.ConfigurationPolicy + Result0 []types.ConfigurationPolicy // Result1 is the value of the 2nd result returned from this method // invocation. Result1 int @@ -513,15 +530,15 @@ func (c StoreGetConfigurationPoliciesFuncCall) Results() []interface{} { // GetConfigurationPolicyByID method of the parent MockStore instance is // invoked. type StoreGetConfigurationPolicyByIDFunc struct { - defaultHook func(context.Context, int) (shared.ConfigurationPolicy, bool, error) - hooks []func(context.Context, int) (shared.ConfigurationPolicy, bool, error) + defaultHook func(context.Context, int) (types.ConfigurationPolicy, bool, error) + hooks []func(context.Context, int) (types.ConfigurationPolicy, bool, error) history []StoreGetConfigurationPolicyByIDFuncCall mutex sync.Mutex } // GetConfigurationPolicyByID delegates to the next hook function in the // queue and stores the parameter and result values of this invocation. -func (m *MockStore) GetConfigurationPolicyByID(v0 context.Context, v1 int) (shared.ConfigurationPolicy, bool, error) { +func (m *MockStore) GetConfigurationPolicyByID(v0 context.Context, v1 int) (types.ConfigurationPolicy, bool, error) { r0, r1, r2 := m.GetConfigurationPolicyByIDFunc.nextHook()(v0, v1) m.GetConfigurationPolicyByIDFunc.appendCall(StoreGetConfigurationPolicyByIDFuncCall{v0, v1, r0, r1, r2}) return r0, r1, r2 @@ -530,7 +547,7 @@ func (m *MockStore) GetConfigurationPolicyByID(v0 context.Context, v1 int) (shar // SetDefaultHook sets function that is called when the // GetConfigurationPolicyByID method of the parent MockStore instance is // invoked and the hook queue is empty. -func (f *StoreGetConfigurationPolicyByIDFunc) SetDefaultHook(hook func(context.Context, int) (shared.ConfigurationPolicy, bool, error)) { +func (f *StoreGetConfigurationPolicyByIDFunc) SetDefaultHook(hook func(context.Context, int) (types.ConfigurationPolicy, bool, error)) { f.defaultHook = hook } @@ -539,7 +556,7 @@ func (f *StoreGetConfigurationPolicyByIDFunc) SetDefaultHook(hook func(context.C // invokes the hook at the front of the queue and discards it. After the // queue is empty, the default hook function is invoked for any future // action. -func (f *StoreGetConfigurationPolicyByIDFunc) PushHook(hook func(context.Context, int) (shared.ConfigurationPolicy, bool, error)) { +func (f *StoreGetConfigurationPolicyByIDFunc) PushHook(hook func(context.Context, int) (types.ConfigurationPolicy, bool, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -547,20 +564,20 @@ func (f *StoreGetConfigurationPolicyByIDFunc) PushHook(hook func(context.Context // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreGetConfigurationPolicyByIDFunc) SetDefaultReturn(r0 shared.ConfigurationPolicy, r1 bool, r2 error) { - f.SetDefaultHook(func(context.Context, int) (shared.ConfigurationPolicy, bool, error) { +func (f *StoreGetConfigurationPolicyByIDFunc) SetDefaultReturn(r0 types.ConfigurationPolicy, r1 bool, r2 error) { + f.SetDefaultHook(func(context.Context, int) (types.ConfigurationPolicy, bool, error) { return r0, r1, r2 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreGetConfigurationPolicyByIDFunc) PushReturn(r0 shared.ConfigurationPolicy, r1 bool, r2 error) { - f.PushHook(func(context.Context, int) (shared.ConfigurationPolicy, bool, error) { +func (f *StoreGetConfigurationPolicyByIDFunc) PushReturn(r0 types.ConfigurationPolicy, r1 bool, r2 error) { + f.PushHook(func(context.Context, int) (types.ConfigurationPolicy, bool, error) { return r0, r1, r2 }) } -func (f *StoreGetConfigurationPolicyByIDFunc) nextHook() func(context.Context, int) (shared.ConfigurationPolicy, bool, error) { +func (f *StoreGetConfigurationPolicyByIDFunc) nextHook() func(context.Context, int) (types.ConfigurationPolicy, bool, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -602,7 +619,7 @@ type StoreGetConfigurationPolicyByIDFuncCall struct { Arg1 int // Result0 is the value of the 1st result returned from this method // invocation. - Result0 shared.ConfigurationPolicy + Result0 types.ConfigurationPolicy // Result1 is the value of the 2nd result returned from this method // invocation. Result1 bool @@ -742,12 +759,110 @@ func (c StoreGetRepoIDsByGlobPatternsFuncCall) Results() []interface{} { return []interface{}{c.Result0, c.Result1, c.Result2} } +// StoreGetUnsafeDBFunc describes the behavior when the GetUnsafeDB method +// of the parent MockStore instance is invoked. +type StoreGetUnsafeDBFunc struct { + defaultHook func() database.DB + hooks []func() database.DB + history []StoreGetUnsafeDBFuncCall + mutex sync.Mutex +} + +// GetUnsafeDB delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockStore) GetUnsafeDB() database.DB { + r0 := m.GetUnsafeDBFunc.nextHook()() + m.GetUnsafeDBFunc.appendCall(StoreGetUnsafeDBFuncCall{r0}) + return r0 +} + +// SetDefaultHook sets function that is called when the GetUnsafeDB method +// of the parent MockStore instance is invoked and the hook queue is empty. +func (f *StoreGetUnsafeDBFunc) SetDefaultHook(hook func() database.DB) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUnsafeDB method of the parent MockStore instance invokes the hook at +// the front of the queue and discards it. After the queue is empty, the +// default hook function is invoked for any future action. +func (f *StoreGetUnsafeDBFunc) PushHook(hook func() database.DB) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *StoreGetUnsafeDBFunc) SetDefaultReturn(r0 database.DB) { + f.SetDefaultHook(func() database.DB { + return r0 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *StoreGetUnsafeDBFunc) PushReturn(r0 database.DB) { + f.PushHook(func() database.DB { + return r0 + }) +} + +func (f *StoreGetUnsafeDBFunc) nextHook() func() database.DB { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *StoreGetUnsafeDBFunc) appendCall(r0 StoreGetUnsafeDBFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of StoreGetUnsafeDBFuncCall objects describing +// the invocations of this function. +func (f *StoreGetUnsafeDBFunc) History() []StoreGetUnsafeDBFuncCall { + f.mutex.Lock() + history := make([]StoreGetUnsafeDBFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// StoreGetUnsafeDBFuncCall is an object that describes an invocation of +// method GetUnsafeDB on an instance of MockStore. +type StoreGetUnsafeDBFuncCall struct { + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 database.DB +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c StoreGetUnsafeDBFuncCall) Args() []interface{} { + return []interface{}{} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c StoreGetUnsafeDBFuncCall) Results() []interface{} { + return []interface{}{c.Result0} +} + // StoreSelectPoliciesForRepositoryMembershipUpdateFunc describes the // behavior when the SelectPoliciesForRepositoryMembershipUpdate method of // the parent MockStore instance is invoked. type StoreSelectPoliciesForRepositoryMembershipUpdateFunc struct { - defaultHook func(context.Context, int) ([]shared.ConfigurationPolicy, error) - hooks []func(context.Context, int) ([]shared.ConfigurationPolicy, error) + defaultHook func(context.Context, int) ([]types.ConfigurationPolicy, error) + hooks []func(context.Context, int) ([]types.ConfigurationPolicy, error) history []StoreSelectPoliciesForRepositoryMembershipUpdateFuncCall mutex sync.Mutex } @@ -755,7 +870,7 @@ type StoreSelectPoliciesForRepositoryMembershipUpdateFunc struct { // SelectPoliciesForRepositoryMembershipUpdate delegates to the next hook // function in the queue and stores the parameter and result values of this // invocation. -func (m *MockStore) SelectPoliciesForRepositoryMembershipUpdate(v0 context.Context, v1 int) ([]shared.ConfigurationPolicy, error) { +func (m *MockStore) SelectPoliciesForRepositoryMembershipUpdate(v0 context.Context, v1 int) ([]types.ConfigurationPolicy, error) { r0, r1 := m.SelectPoliciesForRepositoryMembershipUpdateFunc.nextHook()(v0, v1) m.SelectPoliciesForRepositoryMembershipUpdateFunc.appendCall(StoreSelectPoliciesForRepositoryMembershipUpdateFuncCall{v0, v1, r0, r1}) return r0, r1 @@ -764,7 +879,7 @@ func (m *MockStore) SelectPoliciesForRepositoryMembershipUpdate(v0 context.Conte // SetDefaultHook sets function that is called when the // SelectPoliciesForRepositoryMembershipUpdate method of the parent // MockStore instance is invoked and the hook queue is empty. -func (f *StoreSelectPoliciesForRepositoryMembershipUpdateFunc) SetDefaultHook(hook func(context.Context, int) ([]shared.ConfigurationPolicy, error)) { +func (f *StoreSelectPoliciesForRepositoryMembershipUpdateFunc) SetDefaultHook(hook func(context.Context, int) ([]types.ConfigurationPolicy, error)) { f.defaultHook = hook } @@ -773,7 +888,7 @@ func (f *StoreSelectPoliciesForRepositoryMembershipUpdateFunc) SetDefaultHook(ho // MockStore instance invokes the hook at the front of the queue and // discards it. After the queue is empty, the default hook function is // invoked for any future action. -func (f *StoreSelectPoliciesForRepositoryMembershipUpdateFunc) PushHook(hook func(context.Context, int) ([]shared.ConfigurationPolicy, error)) { +func (f *StoreSelectPoliciesForRepositoryMembershipUpdateFunc) PushHook(hook func(context.Context, int) ([]types.ConfigurationPolicy, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -781,20 +896,20 @@ func (f *StoreSelectPoliciesForRepositoryMembershipUpdateFunc) PushHook(hook fun // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreSelectPoliciesForRepositoryMembershipUpdateFunc) SetDefaultReturn(r0 []shared.ConfigurationPolicy, r1 error) { - f.SetDefaultHook(func(context.Context, int) ([]shared.ConfigurationPolicy, error) { +func (f *StoreSelectPoliciesForRepositoryMembershipUpdateFunc) SetDefaultReturn(r0 []types.ConfigurationPolicy, r1 error) { + f.SetDefaultHook(func(context.Context, int) ([]types.ConfigurationPolicy, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreSelectPoliciesForRepositoryMembershipUpdateFunc) PushReturn(r0 []shared.ConfigurationPolicy, r1 error) { - f.PushHook(func(context.Context, int) ([]shared.ConfigurationPolicy, error) { +func (f *StoreSelectPoliciesForRepositoryMembershipUpdateFunc) PushReturn(r0 []types.ConfigurationPolicy, r1 error) { + f.PushHook(func(context.Context, int) ([]types.ConfigurationPolicy, error) { return r0, r1 }) } -func (f *StoreSelectPoliciesForRepositoryMembershipUpdateFunc) nextHook() func(context.Context, int) ([]shared.ConfigurationPolicy, error) { +func (f *StoreSelectPoliciesForRepositoryMembershipUpdateFunc) nextHook() func(context.Context, int) ([]types.ConfigurationPolicy, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -837,7 +952,7 @@ type StoreSelectPoliciesForRepositoryMembershipUpdateFuncCall struct { Arg1 int // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.ConfigurationPolicy + Result0 []types.ConfigurationPolicy // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error @@ -859,15 +974,15 @@ func (c StoreSelectPoliciesForRepositoryMembershipUpdateFuncCall) Results() []in // UpdateConfigurationPolicy method of the parent MockStore instance is // invoked. type StoreUpdateConfigurationPolicyFunc struct { - defaultHook func(context.Context, shared.ConfigurationPolicy) error - hooks []func(context.Context, shared.ConfigurationPolicy) error + defaultHook func(context.Context, types.ConfigurationPolicy) error + hooks []func(context.Context, types.ConfigurationPolicy) error history []StoreUpdateConfigurationPolicyFuncCall mutex sync.Mutex } // UpdateConfigurationPolicy delegates to the next hook function in the // queue and stores the parameter and result values of this invocation. -func (m *MockStore) UpdateConfigurationPolicy(v0 context.Context, v1 shared.ConfigurationPolicy) error { +func (m *MockStore) UpdateConfigurationPolicy(v0 context.Context, v1 types.ConfigurationPolicy) error { r0 := m.UpdateConfigurationPolicyFunc.nextHook()(v0, v1) m.UpdateConfigurationPolicyFunc.appendCall(StoreUpdateConfigurationPolicyFuncCall{v0, v1, r0}) return r0 @@ -876,7 +991,7 @@ func (m *MockStore) UpdateConfigurationPolicy(v0 context.Context, v1 shared.Conf // SetDefaultHook sets function that is called when the // UpdateConfigurationPolicy method of the parent MockStore instance is // invoked and the hook queue is empty. -func (f *StoreUpdateConfigurationPolicyFunc) SetDefaultHook(hook func(context.Context, shared.ConfigurationPolicy) error) { +func (f *StoreUpdateConfigurationPolicyFunc) SetDefaultHook(hook func(context.Context, types.ConfigurationPolicy) error) { f.defaultHook = hook } @@ -884,7 +999,7 @@ func (f *StoreUpdateConfigurationPolicyFunc) SetDefaultHook(hook func(context.Co // UpdateConfigurationPolicy method of the parent MockStore instance invokes // the hook at the front of the queue and discards it. After the queue is // empty, the default hook function is invoked for any future action. -func (f *StoreUpdateConfigurationPolicyFunc) PushHook(hook func(context.Context, shared.ConfigurationPolicy) error) { +func (f *StoreUpdateConfigurationPolicyFunc) PushHook(hook func(context.Context, types.ConfigurationPolicy) error) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -893,19 +1008,19 @@ func (f *StoreUpdateConfigurationPolicyFunc) PushHook(hook func(context.Context, // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. func (f *StoreUpdateConfigurationPolicyFunc) SetDefaultReturn(r0 error) { - f.SetDefaultHook(func(context.Context, shared.ConfigurationPolicy) error { + f.SetDefaultHook(func(context.Context, types.ConfigurationPolicy) error { return r0 }) } // PushReturn calls PushHook with a function that returns the given values. func (f *StoreUpdateConfigurationPolicyFunc) PushReturn(r0 error) { - f.PushHook(func(context.Context, shared.ConfigurationPolicy) error { + f.PushHook(func(context.Context, types.ConfigurationPolicy) error { return r0 }) } -func (f *StoreUpdateConfigurationPolicyFunc) nextHook() func(context.Context, shared.ConfigurationPolicy) error { +func (f *StoreUpdateConfigurationPolicyFunc) nextHook() func(context.Context, types.ConfigurationPolicy) error { f.mutex.Lock() defer f.mutex.Unlock() @@ -944,7 +1059,7 @@ type StoreUpdateConfigurationPolicyFuncCall struct { Arg0 context.Context // Arg1 is the value of the 2nd argument passed to this method // invocation. - Arg1 shared.ConfigurationPolicy + Arg1 types.ConfigurationPolicy // Result0 is the value of the 1st result returned from this method // invocation. Result0 error diff --git a/internal/codeintel/policies/service.go b/internal/codeintel/policies/service.go index e701b36cb9f..2aa1ff48d98 100644 --- a/internal/codeintel/policies/service.go +++ b/internal/codeintel/policies/service.go @@ -7,8 +7,9 @@ import ( policies "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/enterprise" "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/internal/store" - "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/conf" + "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/internal/timeutil" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -18,20 +19,24 @@ var _ service = (*Service)(nil) type service interface { // Configurations - GetConfigurationPolicies(ctx context.Context, opts shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) - GetConfigurationPolicyByID(ctx context.Context, id int) (_ shared.ConfigurationPolicy, _ bool, err error) - CreateConfigurationPolicy(ctx context.Context, configurationPolicy shared.ConfigurationPolicy) (shared.ConfigurationPolicy, error) - UpdateConfigurationPolicy(ctx context.Context, policy shared.ConfigurationPolicy) (err error) + GetConfigurationPolicies(ctx context.Context, opts types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) + GetConfigurationPolicyByID(ctx context.Context, id int) (_ types.ConfigurationPolicy, _ bool, err error) + CreateConfigurationPolicy(ctx context.Context, configurationPolicy types.ConfigurationPolicy) (types.ConfigurationPolicy, error) + UpdateConfigurationPolicy(ctx context.Context, policy types.ConfigurationPolicy) (err error) DeleteConfigurationPolicyByID(ctx context.Context, id int) (err error) // Retention Policy - GetRetentionPolicyOverview(ctx context.Context, upload shared.Upload, matchesOnly bool, first int, after int64, query string, now time.Time) (matches []shared.RetentionPolicyMatchCandidate, totalCount int, err error) + GetRetentionPolicyOverview(ctx context.Context, upload types.Upload, matchesOnly bool, first int, after int64, query string, now time.Time) (matches []types.RetentionPolicyMatchCandidate, totalCount int, err error) // Repository GetPreviewRepositoryFilter(ctx context.Context, patterns []string, limit, offset int) (_ []int, totalCount int, repositoryMatchLimit *int, _ error) - GetPreviewGitObjectFilter(ctx context.Context, repositoryID int, gitObjectType shared.GitObjectType, pattern string) (map[string][]string, error) - SelectPoliciesForRepositoryMembershipUpdate(ctx context.Context, batchSize int) (configurationPolicies []shared.ConfigurationPolicy, err error) + GetPreviewGitObjectFilter(ctx context.Context, repositoryID int, gitObjectType types.GitObjectType, pattern string) (map[string][]string, error) + SelectPoliciesForRepositoryMembershipUpdate(ctx context.Context, batchSize int) (configurationPolicies []types.ConfigurationPolicy, err error) UpdateReposMatchingPatterns(ctx context.Context, patterns []string, policyID int, repositoryMatchLimit *int) (err error) + + // GetUnsafeDB returns the underlying database handle. This is used by the + // resolvers that have the old convention of using the database handle directly. + GetUnsafeDB() database.DB } type Service struct { @@ -50,31 +55,25 @@ func newService(policiesStore store.Store, uploadSvc UploadService, gitserver Gi } } -type Policy = shared.Policy - -type ListOpts struct { - Limit int -} - func (s *Service) getPolicyMatcherFromFactory(gitserver GitserverClient, extractor policies.Extractor, includeTipOfDefaultBranch bool, filterByCreatedDate bool) *policies.Matcher { return policies.NewMatcher(gitserver, extractor, includeTipOfDefaultBranch, filterByCreatedDate) } -func (s *Service) GetConfigurationPolicies(ctx context.Context, opts shared.GetConfigurationPoliciesOptions) (_ []shared.ConfigurationPolicy, totalCount int, err error) { +func (s *Service) GetConfigurationPolicies(ctx context.Context, opts types.GetConfigurationPoliciesOptions) (_ []types.ConfigurationPolicy, totalCount int, err error) { ctx, _, endObservation := s.operations.getConfigurationPolicies.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) return s.store.GetConfigurationPolicies(ctx, opts) } -func (s *Service) GetConfigurationPolicyByID(ctx context.Context, id int) (_ shared.ConfigurationPolicy, _ bool, err error) { +func (s *Service) GetConfigurationPolicyByID(ctx context.Context, id int) (_ types.ConfigurationPolicy, _ bool, err error) { ctx, _, endObservation := s.operations.getConfigurationPoliciesByID.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) return s.store.GetConfigurationPolicyByID(ctx, id) } -func (s *Service) CreateConfigurationPolicy(ctx context.Context, configurationPolicy shared.ConfigurationPolicy) (_ shared.ConfigurationPolicy, err error) { +func (s *Service) CreateConfigurationPolicy(ctx context.Context, configurationPolicy types.ConfigurationPolicy) (_ types.ConfigurationPolicy, err error) { ctx, _, endObservation := s.operations.createConfigurationPolicy.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) @@ -90,7 +89,7 @@ func (s *Service) CreateConfigurationPolicy(ctx context.Context, configurationPo return policy, nil } -func (s *Service) updateReposMatchingPolicyPatterns(ctx context.Context, policy shared.ConfigurationPolicy) error { +func (s *Service) updateReposMatchingPolicyPatterns(ctx context.Context, policy types.ConfigurationPolicy) error { var patterns []string if policy.RepositoryPatterns != nil { patterns = *policy.RepositoryPatterns @@ -112,7 +111,7 @@ func (s *Service) updateReposMatchingPolicyPatterns(ctx context.Context, policy return nil } -func (s *Service) UpdateConfigurationPolicy(ctx context.Context, policy shared.ConfigurationPolicy) (err error) { +func (s *Service) UpdateConfigurationPolicy(ctx context.Context, policy types.ConfigurationPolicy) (err error) { ctx, _, endObservation := s.operations.updateConfigurationPolicy.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) @@ -130,13 +129,13 @@ func (s *Service) DeleteConfigurationPolicyByID(ctx context.Context, id int) (er return s.store.DeleteConfigurationPolicyByID(ctx, id) } -func (s *Service) GetRetentionPolicyOverview(ctx context.Context, upload shared.Upload, matchesOnly bool, first int, after int64, query string, now time.Time) (matches []shared.RetentionPolicyMatchCandidate, totalCount int, err error) { +func (s *Service) GetRetentionPolicyOverview(ctx context.Context, upload types.Upload, matchesOnly bool, first int, after int64, query string, now time.Time) (matches []types.RetentionPolicyMatchCandidate, totalCount int, err error) { ctx, _, endObservation := s.operations.getRetentionPolicyOverview.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) policyMatcher := s.getPolicyMatcherFromFactory(s.gitserver, policies.RetentionExtractor, true, false) - configPolicies, _, err := s.GetConfigurationPolicies(ctx, shared.GetConfigurationPoliciesOptions{ + configPolicies, _, err := s.GetConfigurationPolicies(ctx, types.GetConfigurationPoliciesOptions{ RepositoryID: upload.RepositoryID, Term: query, ForDataRetention: true, @@ -159,7 +158,7 @@ func (s *Service) GetRetentionPolicyOverview(ctx context.Context, upload shared. var ( potentialMatchIndexSet map[int]int // map of policy ID to array index - potentialMatches []shared.RetentionPolicyMatchCandidate + potentialMatches []types.RetentionPolicyMatchCandidate ) potentialMatches, potentialMatchIndexSet = s.populateMatchingCommits(visibleCommits, upload, matchingPolicies, configPolicies, now) @@ -169,7 +168,7 @@ func (s *Service) GetRetentionPolicyOverview(ctx context.Context, upload shared. for _, policy := range configPolicies { policy := policy if _, ok := potentialMatchIndexSet[policy.ID]; !ok { - potentialMatches = append(potentialMatches, shared.RetentionPolicyMatchCandidate{ + potentialMatches = append(potentialMatches, types.RetentionPolicyMatchCandidate{ ConfigurationPolicy: &policy, Matched: false, }) @@ -209,12 +208,12 @@ func (s *Service) GetPreviewRepositoryFilter(ctx context.Context, patterns []str return ids, totalCount, repositoryMatchLimit, nil } -func (s *Service) GetPreviewGitObjectFilter(ctx context.Context, repositoryID int, gitObjectType shared.GitObjectType, pattern string) (_ map[string][]string, err error) { +func (s *Service) GetPreviewGitObjectFilter(ctx context.Context, repositoryID int, gitObjectType types.GitObjectType, pattern string) (_ map[string][]string, err error) { ctx, _, endObservation := s.operations.getPreviewGitObjectFilter.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) policyMatcher := s.getPolicyMatcherFromFactory(s.gitserver, policies.NoopExtractor, false, false) - policyMatches, err := policyMatcher.CommitsDescribedByPolicyInternal(ctx, repositoryID, []shared.ConfigurationPolicy{{Type: gitObjectType, Pattern: pattern}}, timeutil.Now()) + policyMatches, err := policyMatcher.CommitsDescribedByPolicyInternal(ctx, repositoryID, []types.ConfigurationPolicy{{Type: gitObjectType, Pattern: pattern}}, timeutil.Now()) if err != nil { return nil, err } @@ -232,7 +231,11 @@ func (s *Service) GetPreviewGitObjectFilter(ctx context.Context, repositoryID in return namesByCommit, nil } -func (s *Service) SelectPoliciesForRepositoryMembershipUpdate(ctx context.Context, batchSize int) (configurationPolicies []shared.ConfigurationPolicy, err error) { +func (s *Service) GetUnsafeDB() database.DB { + return s.store.GetUnsafeDB() +} + +func (s *Service) SelectPoliciesForRepositoryMembershipUpdate(ctx context.Context, batchSize int) (configurationPolicies []types.ConfigurationPolicy, err error) { ctx, _, endObservation := s.operations.selectPoliciesForRepositoryMembershipUpdate.With(ctx, &err, observation.Args{}) defer endObservation(1, observation.Args{}) @@ -251,7 +254,7 @@ func (s *Service) UpdateReposMatchingPatterns(ctx context.Context, patterns []st return s.store.UpdateReposMatchingPatterns(ctx, patterns, policyID, repositoryMatchLimit) } -func (s *Service) getCommitsVisibleToUpload(ctx context.Context, upload shared.Upload) (commits []string, err error) { +func (s *Service) getCommitsVisibleToUpload(ctx context.Context, upload types.Upload) (commits []string, err error) { var token *string for first := true; first || token != nil; first = false { cs, nextToken, err := s.uploadSvc.GetCommitsVisibleToUpload(ctx, upload.ID, 50, token) @@ -271,13 +274,13 @@ func (s *Service) getCommitsVisibleToUpload(ctx context.Context, upload shared.U // policy IDs mapped to their index in the slice. func (s *Service) populateMatchingCommits( visibleCommits []string, - upload shared.Upload, + upload types.Upload, matchingPolicies map[string][]policies.PolicyMatch, - policies []shared.ConfigurationPolicy, + policies []types.ConfigurationPolicy, now time.Time, -) ([]shared.RetentionPolicyMatchCandidate, map[int]int) { +) ([]types.RetentionPolicyMatchCandidate, map[int]int) { var ( - potentialMatches = make([]shared.RetentionPolicyMatchCandidate, 0, len(policies)) + potentialMatches = make([]types.RetentionPolicyMatchCandidate, 0, len(policies)) potentialMatchIndexSet = make(map[int]int, len(policies)) ) @@ -292,7 +295,7 @@ func (s *Service) populateMatchingCommits( if policyMatch.PolicyID != nil { policyID = *policyMatch.PolicyID } - potentialMatches = append(potentialMatches, shared.RetentionPolicyMatchCandidate{ + potentialMatches = append(potentialMatches, types.RetentionPolicyMatchCandidate{ ConfigurationPolicy: policyByID(policies, policyID), Matched: true, }) @@ -318,7 +321,7 @@ func (s *Service) populateMatchingCommits( } else if !ok { // Else if there's no entry for the policy, create an entry with this commit as the first "protecting commit". // This should never override an entry for a policy matched directly, see the first comment on how this is avoided. - potentialMatches = append(potentialMatches, shared.RetentionPolicyMatchCandidate{ + potentialMatches = append(potentialMatches, types.RetentionPolicyMatchCandidate{ ConfigurationPolicy: policyByID(policies, policyID), Matched: true, ProtectingCommits: []string{commit}, @@ -333,7 +336,7 @@ func (s *Service) populateMatchingCommits( return potentialMatches, potentialMatchIndexSet } -func policyByID(policies []shared.ConfigurationPolicy, id int) *shared.ConfigurationPolicy { +func policyByID(policies []types.ConfigurationPolicy, id int) *types.ConfigurationPolicy { if id == -1 { return nil } diff --git a/internal/codeintel/policies/service_test.go b/internal/codeintel/policies/service_test.go index fe82ae4bb92..dad7a81e235 100644 --- a/internal/codeintel/policies/service_test.go +++ b/internal/codeintel/policies/service_test.go @@ -8,7 +8,7 @@ import ( "github.com/derision-test/glock" "github.com/google/go-cmp/cmp" - "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" "github.com/sourcegraph/sourcegraph/internal/observation" ) @@ -25,23 +25,23 @@ func TestGetRetentionPolicyOverview(t *testing.T) { cases := []struct { name string expectedMatches int - upload shared.Upload - mockPolicies []shared.RetentionPolicyMatchCandidate + upload types.Upload + mockPolicies []types.RetentionPolicyMatchCandidate refDescriptions map[string][]gitdomain.RefDescription }{ { name: "basic single upload match", expectedMatches: 1, - upload: shared.Upload{ + upload: types.Upload{ Commit: "deadbeef0", UploadedAt: mockClock.Now().Add(-time.Hour * 23), }, - mockPolicies: []shared.RetentionPolicyMatchCandidate{ + mockPolicies: []types.RetentionPolicyMatchCandidate{ { - ConfigurationPolicy: &shared.ConfigurationPolicy{ + ConfigurationPolicy: &types.ConfigurationPolicy{ RetentionDuration: timePtr(time.Hour * 24), RetainIntermediateCommits: false, - Type: shared.GitObjectTypeTag, + Type: types.GitObjectTypeTag, Pattern: "*", }, Matched: true, @@ -60,16 +60,16 @@ func TestGetRetentionPolicyOverview(t *testing.T) { { name: "matching but expired", expectedMatches: 0, - upload: shared.Upload{ + upload: types.Upload{ Commit: "deadbeef0", UploadedAt: mockClock.Now().Add(-time.Hour * 25), }, - mockPolicies: []shared.RetentionPolicyMatchCandidate{ + mockPolicies: []types.RetentionPolicyMatchCandidate{ { - ConfigurationPolicy: &shared.ConfigurationPolicy{ + ConfigurationPolicy: &types.ConfigurationPolicy{ RetentionDuration: timePtr(time.Hour * 24), RetainIntermediateCommits: false, - Type: shared.GitObjectTypeTag, + Type: types.GitObjectTypeTag, Pattern: "*", }, Matched: false, @@ -88,11 +88,11 @@ func TestGetRetentionPolicyOverview(t *testing.T) { { name: "tip of default branch match", expectedMatches: 1, - upload: shared.Upload{ + upload: types.Upload{ Commit: "deadbeef0", UploadedAt: mockClock.Now().Add(-time.Hour * 25), }, - mockPolicies: []shared.RetentionPolicyMatchCandidate{ + mockPolicies: []types.RetentionPolicyMatchCandidate{ { ConfigurationPolicy: nil, Matched: true, @@ -111,25 +111,25 @@ func TestGetRetentionPolicyOverview(t *testing.T) { { name: "direct match (1 of 2 policies)", expectedMatches: 1, - upload: shared.Upload{ + upload: types.Upload{ Commit: "deadbeef0", UploadedAt: mockClock.Now().Add(-time.Minute), }, - mockPolicies: []shared.RetentionPolicyMatchCandidate{ + mockPolicies: []types.RetentionPolicyMatchCandidate{ { - ConfigurationPolicy: &shared.ConfigurationPolicy{ + ConfigurationPolicy: &types.ConfigurationPolicy{ RetentionDuration: timePtr(time.Hour * 24), RetainIntermediateCommits: false, - Type: shared.GitObjectTypeTag, + Type: types.GitObjectTypeTag, Pattern: "*", }, Matched: true, }, { - ConfigurationPolicy: &shared.ConfigurationPolicy{ + ConfigurationPolicy: &types.ConfigurationPolicy{ RetentionDuration: timePtr(time.Hour * 24), RetainIntermediateCommits: false, - Type: shared.GitObjectTypeTree, + Type: types.GitObjectTypeTree, Pattern: "*", }, Matched: false, @@ -148,16 +148,16 @@ func TestGetRetentionPolicyOverview(t *testing.T) { { name: "direct match (ignore visible)", expectedMatches: 1, - upload: shared.Upload{ + upload: types.Upload{ Commit: "deadbeef1", UploadedAt: mockClock.Now().Add(-time.Minute), }, - mockPolicies: []shared.RetentionPolicyMatchCandidate{ + mockPolicies: []types.RetentionPolicyMatchCandidate{ { - ConfigurationPolicy: &shared.ConfigurationPolicy{ + ConfigurationPolicy: &types.ConfigurationPolicy{ RetentionDuration: timePtr(time.Hour * 24), RetainIntermediateCommits: false, - Type: shared.GitObjectTypeTag, + Type: types.GitObjectTypeTag, Pattern: "*", }, Matched: true, @@ -227,8 +227,8 @@ func TestRetentionPolicyOverview_ByVisibility(t *testing.T) { cases := []struct { name string - upload shared.Upload - mockPolicies []shared.RetentionPolicyMatchCandidate + upload types.Upload + mockPolicies []types.RetentionPolicyMatchCandidate visibleCommits []string refDescriptions map[string][]gitdomain.RefDescription expectedMatches int @@ -236,17 +236,17 @@ func TestRetentionPolicyOverview_ByVisibility(t *testing.T) { { name: "basic single visibility", expectedMatches: 1, - upload: shared.Upload{ + upload: types.Upload{ Commit: "deadbeef0", UploadedAt: mockClock.Now().Add(-time.Minute * 24), }, visibleCommits: []string{"deadbeef1"}, - mockPolicies: []shared.RetentionPolicyMatchCandidate{ + mockPolicies: []types.RetentionPolicyMatchCandidate{ { - ConfigurationPolicy: &shared.ConfigurationPolicy{ + ConfigurationPolicy: &types.ConfigurationPolicy{ RetentionDuration: timePtr(time.Hour * 24), RetainIntermediateCommits: false, - Type: shared.GitObjectTypeTag, + Type: types.GitObjectTypeTag, Pattern: "*", }, ProtectingCommits: []string{"deadbeef1"}, @@ -267,11 +267,11 @@ func TestRetentionPolicyOverview_ByVisibility(t *testing.T) { name: "visibile to tip of default branch", expectedMatches: 1, visibleCommits: []string{"deadbeef0", "deadbeef1"}, - upload: shared.Upload{ + upload: types.Upload{ Commit: "deadbeef0", UploadedAt: mockClock.Now().Add(-time.Hour * 24), }, - mockPolicies: []shared.RetentionPolicyMatchCandidate{ + mockPolicies: []types.RetentionPolicyMatchCandidate{ { ConfigurationPolicy: nil, ProtectingCommits: []string{"deadbeef1"}, @@ -325,7 +325,7 @@ func timePtr(t time.Duration) *time.Duration { return &t } -func mockConfigurationPolicies(policies []shared.RetentionPolicyMatchCandidate) (mockedCandidates []shared.RetentionPolicyMatchCandidate, mockedPolicies []shared.ConfigurationPolicy) { +func mockConfigurationPolicies(policies []types.RetentionPolicyMatchCandidate) (mockedCandidates []types.RetentionPolicyMatchCandidate, mockedPolicies []types.ConfigurationPolicy) { for i, policy := range policies { if policy.ConfigurationPolicy != nil { policy.ID = i + 1 diff --git a/internal/codeintel/policies/shared/types.go b/internal/codeintel/policies/shared/types.go index d3a0eb26749..84c8d4eb430 100644 --- a/internal/codeintel/policies/shared/types.go +++ b/internal/codeintel/policies/shared/types.go @@ -1,87 +1,5 @@ package shared -import "time" - type Policy struct { ID int } - -type GitObjectType string - -const ( - GitObjectTypeCommit GitObjectType = "GIT_COMMIT" - GitObjectTypeTag GitObjectType = "GIT_TAG" - GitObjectTypeTree GitObjectType = "GIT_TREE" -) - -type ConfigurationPolicy struct { - ID int - RepositoryID *int - RepositoryPatterns *[]string - Name string - Type GitObjectType - Pattern string - Protected bool - RetentionEnabled bool - RetentionDuration *time.Duration - RetainIntermediateCommits bool - IndexingEnabled bool - IndexCommitMaxAge *time.Duration - IndexIntermediateCommits bool -} - -type GetConfigurationPoliciesOptions struct { - // RepositoryID indicates that only configuration policies that apply to the - // specified repository (directly or via pattern) should be returned. This value - // has no effect when equal to zero. - RepositoryID int - - // Term is a string to search within the configuration title. - Term string - - // ForIndexing indicates that only configuration policies with data retention enabled - // should be returned. - ForDataRetention bool - - // ForIndexing indicates that only configuration policies with indexing enabled should - // be returned. - ForIndexing bool - - // Limit indicates the number of results to take from the result set. - Limit int - - // Offset indicates the number of results to skip in the result set. - Offset int -} - -// Upload is a subset of the lsif_uploads table and stores both processed and unprocessed -// records. -type Upload struct { - ID int - Commit string - Root string - VisibleAtTip bool - UploadedAt time.Time - State string - FailureMessage *string - StartedAt *time.Time - FinishedAt *time.Time - ProcessAfter *time.Time - NumResets int - NumFailures int - RepositoryID int - RepositoryName string - Indexer string - IndexerVersion string - NumParts int - UploadedParts []int - UploadSize *int64 - Rank *int - AssociatedIndexID *int -} - -type RetentionPolicyMatchCandidate struct { - *ConfigurationPolicy - Matched bool - ProtectingCommits []string -} diff --git a/internal/codeintel/policies/transport/graphql/configuration_policy_resolver.go b/internal/codeintel/policies/transport/graphql/configuration_policy_resolver.go new file mode 100644 index 00000000000..baba61d228a --- /dev/null +++ b/internal/codeintel/policies/transport/graphql/configuration_policy_resolver.go @@ -0,0 +1,142 @@ +package graphql + +import ( + "context" + "time" + + "github.com/graph-gophers/graphql-go" + "github.com/opentracing/opentracing-go/log" + + sglog "github.com/sourcegraph/log" + + "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/codeintel/policies" + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/observation" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +type CodeIntelligenceConfigurationPolicyResolver interface { + ID() graphql.ID + Repository(ctx context.Context) (*sharedresolvers.RepositoryResolver, error) + RepositoryPatterns() *[]string + Name() string + Type() (sharedresolvers.GitObjectType, error) + Pattern() string + Protected() bool + RetentionEnabled() bool + RetentionDurationHours() *int32 + RetainIntermediateCommits() bool + IndexingEnabled() bool + IndexCommitMaxAgeHours() *int32 + IndexIntermediateCommits() bool +} + +type configurationPolicyResolver struct { + logger sglog.Logger + policySvc *policies.Service + configurationPolicy types.ConfigurationPolicy + errTracer *observation.ErrCollector +} + +func NewConfigurationPolicyResolver(policySvc *policies.Service, configurationPolicy types.ConfigurationPolicy, errTracer *observation.ErrCollector) CodeIntelligenceConfigurationPolicyResolver { + return &configurationPolicyResolver{ + policySvc: policySvc, + logger: sglog.Scoped("configurationPolicyResolver", ""), + configurationPolicy: configurationPolicy, + errTracer: errTracer, + } +} + +func (r *configurationPolicyResolver) ID() graphql.ID { + return marshalConfigurationPolicyGQLID(int64(r.configurationPolicy.ID)) +} + +func (r *configurationPolicyResolver) Name() string { + return r.configurationPolicy.Name +} + +func (r *configurationPolicyResolver) Repository(ctx context.Context) (_ *sharedresolvers.RepositoryResolver, err error) { + if r.configurationPolicy.RepositoryID == nil { + return nil, nil + } + + defer r.errTracer.Collect(&err, + log.String("configurationPolicyResolver.field", "repository"), + log.Int("configurationPolicyID", r.configurationPolicy.ID), + log.Int("repoID", *r.configurationPolicy.RepositoryID), + ) + + repo, err := backend.NewRepos(r.logger, r.policySvc.GetUnsafeDB()).Get(ctx, api.RepoID(*r.configurationPolicy.RepositoryID)) + if err != nil { + return nil, err + } + + return sharedresolvers.NewRepositoryResolver(r.policySvc.GetUnsafeDB(), repo), nil +} + +func (r *configurationPolicyResolver) RepositoryPatterns() *[]string { + return r.configurationPolicy.RepositoryPatterns +} + +func (r *configurationPolicyResolver) Type() (_ sharedresolvers.GitObjectType, err error) { + defer r.errTracer.Collect(&err, + log.String("configurationPolicyResolver.field", "type"), + log.Int("configurationPolicyID", r.configurationPolicy.ID), + log.String("policyType", string(r.configurationPolicy.Type)), + ) + + switch r.configurationPolicy.Type { + case types.GitObjectTypeCommit: + return sharedresolvers.GitObjectTypeCommit, nil + case types.GitObjectTypeTag: + return sharedresolvers.GitObjectTypeTag, nil + case types.GitObjectTypeTree: + return sharedresolvers.GitObjectTypeTree, nil + default: + return "", errors.Errorf("unknown git object type %s", r.configurationPolicy.Type) + } +} + +func (r *configurationPolicyResolver) Pattern() string { + return r.configurationPolicy.Pattern +} + +func (r *configurationPolicyResolver) Protected() bool { + return r.configurationPolicy.Protected +} + +func (r *configurationPolicyResolver) RetentionEnabled() bool { + return r.configurationPolicy.RetentionEnabled +} + +func (r *configurationPolicyResolver) RetentionDurationHours() *int32 { + return toHours(r.configurationPolicy.RetentionDuration) +} + +func (r *configurationPolicyResolver) RetainIntermediateCommits() bool { + return r.configurationPolicy.RetainIntermediateCommits +} + +func (r *configurationPolicyResolver) IndexingEnabled() bool { + return r.configurationPolicy.IndexingEnabled +} + +func (r *configurationPolicyResolver) IndexCommitMaxAgeHours() *int32 { + return toHours(r.configurationPolicy.IndexCommitMaxAge) +} + +func (r *configurationPolicyResolver) IndexIntermediateCommits() bool { + return r.configurationPolicy.IndexIntermediateCommits +} + +func toHours(duration *time.Duration) *int32 { + if duration == nil { + return nil + } + + v := int32(*duration / time.Hour) + return &v +} diff --git a/internal/codeintel/policies/transport/graphql/configuration_policy_resolver_connection.go b/internal/codeintel/policies/transport/graphql/configuration_policy_resolver_connection.go new file mode 100644 index 00000000000..6681a4d1a10 --- /dev/null +++ b/internal/codeintel/policies/transport/graphql/configuration_policy_resolver_connection.go @@ -0,0 +1,54 @@ +package graphql + +import ( + "context" + + "github.com/sourcegraph/sourcegraph/internal/codeintel/policies" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/observation" +) + +type CodeIntelligenceConfigurationPolicyConnectionResolver interface { + Nodes(ctx context.Context) ([]CodeIntelligenceConfigurationPolicyResolver, error) + TotalCount(ctx context.Context) (*int32, error) + PageInfo(ctx context.Context) (*PageInfo, error) +} + +type codeIntelligenceConfigurationPolicyConnectionResolver struct { + policySvc *policies.Service + policies []types.ConfigurationPolicy + totalCount int + errTracer *observation.ErrCollector +} + +func NewCodeIntelligenceConfigurationPolicyConnectionResolver( + policySvc *policies.Service, + policies []types.ConfigurationPolicy, + totalCount int, + errTracer *observation.ErrCollector, +) CodeIntelligenceConfigurationPolicyConnectionResolver { + return &codeIntelligenceConfigurationPolicyConnectionResolver{ + policySvc: policySvc, + policies: policies, + totalCount: totalCount, + errTracer: errTracer, + } +} + +func (r *codeIntelligenceConfigurationPolicyConnectionResolver) Nodes(ctx context.Context) ([]CodeIntelligenceConfigurationPolicyResolver, error) { + resolvers := make([]CodeIntelligenceConfigurationPolicyResolver, 0, len(r.policies)) + for _, policy := range r.policies { + resolvers = append(resolvers, NewConfigurationPolicyResolver(r.policySvc, policy, r.errTracer)) + } + + return resolvers, nil +} + +func (r *codeIntelligenceConfigurationPolicyConnectionResolver) TotalCount(ctx context.Context) (*int32, error) { + v := int32(r.totalCount) + return &v, nil +} + +func (r *codeIntelligenceConfigurationPolicyConnectionResolver) PageInfo(ctx context.Context) (*PageInfo, error) { + return HasNextPage(len(r.policies) < r.totalCount), nil +} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/git_object_filter_preview.go b/internal/codeintel/policies/transport/graphql/git_object_filter_preview_resolver.go similarity index 50% rename from enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/git_object_filter_preview.go rename to internal/codeintel/policies/transport/graphql/git_object_filter_preview_resolver.go index 6166a38755f..1e502e9c1b1 100644 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/git_object_filter_preview.go +++ b/internal/codeintel/policies/transport/graphql/git_object_filter_preview_resolver.go @@ -1,13 +1,18 @@ package graphql -import gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" +type GitObjectFilterPreviewResolver interface { + Name() string + Rev() string +} type gitObjectFilterPreviewResolver struct { name string rev string } -var _ gql.GitObjectFilterPreviewResolver = &gitObjectFilterPreviewResolver{} +func NewGitObjectFilterPreviewResolver(name, rev string) GitObjectFilterPreviewResolver { + return &gitObjectFilterPreviewResolver{name: name, rev: rev} +} func (r *gitObjectFilterPreviewResolver) Name() string { return r.name diff --git a/internal/codeintel/policies/transport/graphql/iface.go b/internal/codeintel/policies/transport/graphql/iface.go index cd049e49e79..c0635c25b63 100644 --- a/internal/codeintel/policies/transport/graphql/iface.go +++ b/internal/codeintel/policies/transport/graphql/iface.go @@ -4,21 +4,21 @@ import ( "context" "time" - "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" ) type Service interface { // Configurations - GetConfigurationPolicies(ctx context.Context, opts shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) - GetConfigurationPolicyByID(ctx context.Context, id int) (_ shared.ConfigurationPolicy, _ bool, err error) - CreateConfigurationPolicy(ctx context.Context, configurationPolicy shared.ConfigurationPolicy) (shared.ConfigurationPolicy, error) - UpdateConfigurationPolicy(ctx context.Context, policy shared.ConfigurationPolicy) (err error) + GetConfigurationPolicies(ctx context.Context, opts types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) + GetConfigurationPolicyByID(ctx context.Context, id int) (_ types.ConfigurationPolicy, _ bool, err error) + CreateConfigurationPolicy(ctx context.Context, configurationPolicy types.ConfigurationPolicy) (types.ConfigurationPolicy, error) + UpdateConfigurationPolicy(ctx context.Context, policy types.ConfigurationPolicy) (err error) DeleteConfigurationPolicyByID(ctx context.Context, id int) (err error) // Retention Policy - GetRetentionPolicyOverview(ctx context.Context, upload shared.Upload, matchesOnly bool, first int, after int64, query string, now time.Time) (matches []shared.RetentionPolicyMatchCandidate, totalCount int, err error) + GetRetentionPolicyOverview(ctx context.Context, upload types.Upload, matchesOnly bool, first int, after int64, query string, now time.Time) (matches []types.RetentionPolicyMatchCandidate, totalCount int, err error) // Repository GetPreviewRepositoryFilter(ctx context.Context, patterns []string, limit, offset int) (_ []int, totalCount int, repositoryMatchLimit *int, _ error) - GetPreviewGitObjectFilter(ctx context.Context, repositoryID int, gitObjectType shared.GitObjectType, pattern string) (map[string][]string, error) + GetPreviewGitObjectFilter(ctx context.Context, repositoryID int, gitObjectType types.GitObjectType, pattern string) (map[string][]string, error) } diff --git a/internal/codeintel/policies/transport/graphql/observability.go b/internal/codeintel/policies/transport/graphql/observability.go index 019c75c14df..e13da281c2c 100644 --- a/internal/codeintel/policies/transport/graphql/observability.go +++ b/internal/codeintel/policies/transport/graphql/observability.go @@ -1,11 +1,7 @@ package graphql import ( - "context" "fmt" - "time" - - "github.com/sourcegraph/log" "github.com/sourcegraph/sourcegraph/internal/metrics" "github.com/sourcegraph/sourcegraph/internal/observation" @@ -13,21 +9,17 @@ import ( type operations struct { // Configurations - getConfigurationPolicies *observation.Operation - getConfigurationPolicyByID *observation.Operation - createConfigurationPolicy *observation.Operation - updateConfigurationPolicy *observation.Operation - deleteConfigurationPolicyByID *observation.Operation + createConfigurationPolicy *observation.Operation + configurationPolicies *observation.Operation + configurationPolicyByID *observation.Operation + updateConfigurationPolicy *observation.Operation + deleteConfigurationPolicy *observation.Operation - // Retention Policy - getRetentionPolicyOverview *observation.Operation + // Retention + previewGitObjectFilter *observation.Operation // Repository - getPreviewRepositoryFilter *observation.Operation - getPreviewGitObjectFilter *observation.Operation - - // Factory - getPolicyResolverFactory *observation.Operation + previewRepoFilter *observation.Operation } func newOperations(observationContext *observation.Context) *operations { @@ -48,49 +40,16 @@ func newOperations(observationContext *observation.Context) *operations { return &operations{ // Configurations - getConfigurationPolicies: op("GetConfigurationPolicies"), - getConfigurationPolicyByID: op("GetConfigurationPolicyByID"), - createConfigurationPolicy: op("CreateConfigurationPolicy"), - updateConfigurationPolicy: op("UpdateConfigurationPolicy"), - deleteConfigurationPolicyByID: op("DeleteConfigurationPolicyByID"), + createConfigurationPolicy: op("CreateConfigurationPolicy"), + configurationPolicies: op("ConfigurationPolicies"), + configurationPolicyByID: op("ConfigurationPolicyByID"), + updateConfigurationPolicy: op("UpdateConfigurationPolicy"), + deleteConfigurationPolicy: op("DeleteConfigurationPolicy"), // Retention - getRetentionPolicyOverview: op("GetRetentionPolicyOverview"), + previewGitObjectFilter: op("PreviewGitObjectFilter"), // Repository - getPreviewRepositoryFilter: op("PreviewRepositoryFilter"), - getPreviewGitObjectFilter: op("PreviewGitObjectFilter"), - - // Factory - getPolicyResolverFactory: op("GetPolicyResolverFactory"), + previewRepoFilter: op("PreviewRepoFilter"), } } - -func observeResolver( - ctx context.Context, - err *error, - operation *observation.Operation, - threshold time.Duration, - observationArgs observation.Args, -) (context.Context, observation.TraceLogger, func()) { - start := time.Now() - ctx, trace, endObservation := operation.With(ctx, err, observationArgs) - - return ctx, trace, func() { - duration := time.Since(start) - endObservation(1, observation.Args{}) - - if duration >= threshold { - // use trace logger which includes all relevant fields - lowSlowRequest(trace, duration, err) - } - } -} - -func lowSlowRequest(logger log.Logger, duration time.Duration, err *error) { - fields := []log.Field{log.Duration("duration", duration)} - if err != nil && *err != nil { - fields = append(fields, log.Error(*err)) - } - logger.Warn("Slow codeintel request", fields...) -} diff --git a/internal/codeintel/policies/transport/graphql/policy_resolver.go b/internal/codeintel/policies/transport/graphql/policy_resolver.go deleted file mode 100644 index a30340a3dfc..00000000000 --- a/internal/codeintel/policies/transport/graphql/policy_resolver.go +++ /dev/null @@ -1,94 +0,0 @@ -package graphql - -import ( - "context" - "time" - - "github.com/sourcegraph/sourcegraph/internal/observation" - - "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" -) - -type PolicyResolver interface { - // Configurations - GetConfigurationPolicies(ctx context.Context, opts shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) - GetConfigurationPolicyByID(ctx context.Context, id int) (shared.ConfigurationPolicy, bool, error) - CreateConfigurationPolicy(ctx context.Context, configurationPolicy shared.ConfigurationPolicy) (shared.ConfigurationPolicy, error) - UpdateConfigurationPolicy(ctx context.Context, policy shared.ConfigurationPolicy) (err error) - DeleteConfigurationPolicyByID(ctx context.Context, id int) (err error) - - // Retention - GetRetentionPolicyOverview(ctx context.Context, upload shared.Upload, matchesOnly bool, first int, after int64, query string, now time.Time) (matches []shared.RetentionPolicyMatchCandidate, totalCount int, err error) - - // Previews - GetPreviewRepositoryFilter(ctx context.Context, patterns []string, limit, offset int) (_ []int, totalCount int, repositoryMatchLimit *int, _ error) - GetPreviewGitObjectFilter(ctx context.Context, repositoryID int, gitObjectType shared.GitObjectType, pattern string) (map[string][]string, error) -} - -type policyResolver struct { - svc Service - operations *operations -} - -func NewPolicyResolver(svc Service, operations *operations) PolicyResolver { - return &policyResolver{ - svc: svc, - operations: operations, - } -} - -func (p *policyResolver) GetConfigurationPolicies(ctx context.Context, opts shared.GetConfigurationPoliciesOptions) (_ []shared.ConfigurationPolicy, total int, err error) { - ctx, _, endObservation := p.operations.getConfigurationPolicies.With(ctx, &err, observation.Args{}) - defer endObservation(1, observation.Args{}) - - return p.svc.GetConfigurationPolicies(ctx, opts) -} - -func (p *policyResolver) GetConfigurationPolicyByID(ctx context.Context, id int) (_ shared.ConfigurationPolicy, _ bool, err error) { - ctx, _, endObservation := p.operations.getConfigurationPolicyByID.With(ctx, &err, observation.Args{}) - defer endObservation(1, observation.Args{}) - - return p.svc.GetConfigurationPolicyByID(ctx, id) -} - -func (p *policyResolver) CreateConfigurationPolicy(ctx context.Context, configurationPolicy shared.ConfigurationPolicy) (_ shared.ConfigurationPolicy, err error) { - ctx, _, endObservation := p.operations.createConfigurationPolicy.With(ctx, &err, observation.Args{}) - defer endObservation(1, observation.Args{}) - - return p.svc.CreateConfigurationPolicy(ctx, configurationPolicy) -} - -func (p *policyResolver) UpdateConfigurationPolicy(ctx context.Context, policy shared.ConfigurationPolicy) (err error) { - ctx, _, endObservation := p.operations.updateConfigurationPolicy.With(ctx, &err, observation.Args{}) - defer endObservation(1, observation.Args{}) - - return p.svc.UpdateConfigurationPolicy(ctx, policy) -} - -func (p *policyResolver) DeleteConfigurationPolicyByID(ctx context.Context, id int) (err error) { - ctx, _, endObservation := p.operations.deleteConfigurationPolicyByID.With(ctx, &err, observation.Args{}) - defer endObservation(1, observation.Args{}) - - return p.svc.DeleteConfigurationPolicyByID(ctx, id) -} - -func (p *policyResolver) GetRetentionPolicyOverview(ctx context.Context, upload shared.Upload, matchesOnly bool, first int, after int64, query string, now time.Time) (matches []shared.RetentionPolicyMatchCandidate, totalCount int, err error) { - ctx, _, endObservation := p.operations.getRetentionPolicyOverview.With(ctx, &err, observation.Args{}) - defer endObservation(1, observation.Args{}) - - return p.svc.GetRetentionPolicyOverview(ctx, upload, matchesOnly, first, after, query, now) -} - -func (p *policyResolver) GetPreviewRepositoryFilter(ctx context.Context, patterns []string, limit, offset int) (_ []int, totalCount int, repositoryMatchLimit *int, err error) { - ctx, _, endObservation := p.operations.getPreviewRepositoryFilter.With(ctx, &err, observation.Args{}) - defer endObservation(1, observation.Args{}) - - return p.svc.GetPreviewRepositoryFilter(ctx, patterns, limit, offset) -} - -func (p *policyResolver) GetPreviewGitObjectFilter(ctx context.Context, repositoryID int, gitObjectType shared.GitObjectType, pattern string) (_ map[string][]string, err error) { - ctx, _, endObservation := p.operations.getPreviewGitObjectFilter.With(ctx, &err, observation.Args{}) - defer endObservation(1, observation.Args{}) - - return p.svc.GetPreviewGitObjectFilter(ctx, repositoryID, gitObjectType, pattern) -} diff --git a/internal/codeintel/policies/transport/graphql/repository_filter_preview_resolver.go b/internal/codeintel/policies/transport/graphql/repository_filter_preview_resolver.go new file mode 100644 index 00000000000..7cac3a83d79 --- /dev/null +++ b/internal/codeintel/policies/transport/graphql/repository_filter_preview_resolver.go @@ -0,0 +1,56 @@ +package graphql + +import ( + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" +) + +type RepositoryFilterPreviewResolver interface { + Nodes() []*sharedresolvers.RepositoryResolver + TotalCount() int32 + Limit() *int32 + TotalMatches() int32 + PageInfo() *PageInfo +} + +type repositoryFilterPreviewResolver struct { + repositoryResolvers []*sharedresolvers.RepositoryResolver + totalCount int + offset int + totalMatches int + limit *int +} + +func NewRepositoryFilterPreviewResolver(repositoryResolvers []*sharedresolvers.RepositoryResolver, totalCount, offset, totalMatches int, limit *int) RepositoryFilterPreviewResolver { + return &repositoryFilterPreviewResolver{ + repositoryResolvers: repositoryResolvers, + totalCount: totalCount, + offset: offset, + totalMatches: totalMatches, + limit: limit, + } +} + +func (r *repositoryFilterPreviewResolver) Nodes() []*sharedresolvers.RepositoryResolver { + return r.repositoryResolvers +} + +func (r *repositoryFilterPreviewResolver) TotalCount() int32 { + return int32(r.totalCount) +} + +func (r *repositoryFilterPreviewResolver) TotalMatches() int32 { + return int32(r.totalMatches) +} + +func (r *repositoryFilterPreviewResolver) Limit() *int32 { + if r.limit == nil { + return nil + } + + v := int32(*r.limit) + return &v +} + +func (r *repositoryFilterPreviewResolver) PageInfo() *PageInfo { + return EncodeIntCursor(toInt32(NextOffset(r.offset, len(r.repositoryResolvers), r.totalCount))) +} diff --git a/internal/codeintel/policies/transport/graphql/resolver.go b/internal/codeintel/policies/transport/graphql/resolver.go deleted file mode 100644 index 6b858cb16bc..00000000000 --- a/internal/codeintel/policies/transport/graphql/resolver.go +++ /dev/null @@ -1,33 +0,0 @@ -package graphql - -import ( - "context" - "time" - - "github.com/sourcegraph/sourcegraph/internal/observation" -) - -type Resolver interface { - PolicyResolverFactory(ctx context.Context) (_ PolicyResolver, err error) -} - -type resolver struct { - svc Service - operations *operations -} - -func New(svc Service, observationContext *observation.Context) Resolver { - return &resolver{ - svc: svc, - operations: newOperations(observationContext), - } -} - -const slowQueryResolverRequestThreshold = time.Second - -func (r *resolver) PolicyResolverFactory(ctx context.Context) (_ PolicyResolver, err error) { - _, _, endObservation := observeResolver(ctx, &err, r.operations.getPolicyResolverFactory, slowQueryResolverRequestThreshold, observation.Args{}) - defer endObservation() - - return NewPolicyResolver(r.svc, r.operations), nil -} diff --git a/internal/codeintel/policies/transport/graphql/root_resolver.go b/internal/codeintel/policies/transport/graphql/root_resolver.go new file mode 100644 index 00000000000..ae27d112a3e --- /dev/null +++ b/internal/codeintel/policies/transport/graphql/root_resolver.go @@ -0,0 +1,338 @@ +package graphql + +import ( + "context" + "sort" + + "github.com/graph-gophers/graphql-go" + "github.com/opentracing/opentracing-go/log" + + sglog "github.com/sourcegraph/log" + + "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" + "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/codeintel/policies" + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/observation" +) + +type RootResolver interface { + CodeIntelligenceConfigurationPolicies(ctx context.Context, args *CodeIntelligenceConfigurationPoliciesArgs) (_ CodeIntelligenceConfigurationPolicyConnectionResolver, err error) + ConfigurationPolicyByID(ctx context.Context, id graphql.ID) (_ CodeIntelligenceConfigurationPolicyResolver, err error) + CreateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *CreateCodeIntelligenceConfigurationPolicyArgs) (_ CodeIntelligenceConfigurationPolicyResolver, err error) + UpdateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *UpdateCodeIntelligenceConfigurationPolicyArgs) (_ *sharedresolvers.EmptyResponse, err error) + DeleteCodeIntelligenceConfigurationPolicy(ctx context.Context, args *DeleteCodeIntelligenceConfigurationPolicyArgs) (_ *sharedresolvers.EmptyResponse, err error) + PreviewRepositoryFilter(ctx context.Context, args *PreviewRepositoryFilterArgs) (_ RepositoryFilterPreviewResolver, err error) + PreviewGitObjectFilter(ctx context.Context, id graphql.ID, args *PreviewGitObjectFilterArgs) (_ []GitObjectFilterPreviewResolver, err error) +} + +type rootResolver struct { + policySvc *policies.Service + operations *operations +} + +func NewRootResolver(policySvc *policies.Service, observationContext *observation.Context) RootResolver { + return &rootResolver{ + policySvc: policySvc, + operations: newOperations(observationContext), + } +} + +func (r *rootResolver) ConfigurationPolicyByID(ctx context.Context, id graphql.ID) (_ CodeIntelligenceConfigurationPolicyResolver, err error) { + ctx, traceErrs, endObservation := r.operations.configurationPolicyByID.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ + log.String("configPolicyID", string(id)), + }}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + configurationPolicyID, err := unmarshalConfigurationPolicyGQLID(id) + if err != nil { + return nil, err + } + + configurationPolicy, exists, err := r.policySvc.GetConfigurationPolicyByID(ctx, int(configurationPolicyID)) + if err != nil || !exists { + return nil, err + } + + return NewConfigurationPolicyResolver(r.policySvc, configurationPolicy, traceErrs), nil +} + +type CodeIntelligenceConfigurationPoliciesArgs struct { + ConnectionArgs + Repository *graphql.ID + Query *string + ForDataRetention *bool + ForIndexing *bool + After *string +} + +const DefaultConfigurationPolicyPageSize = 50 + +// 🚨 SECURITY: dbstore layer handles authz for GetConfigurationPolicies +func (r *rootResolver) CodeIntelligenceConfigurationPolicies(ctx context.Context, args *CodeIntelligenceConfigurationPoliciesArgs) (_ CodeIntelligenceConfigurationPolicyConnectionResolver, err error) { + fields := []log.Field{} + if args.Repository != nil { + fields = append(fields, log.String("repoID", string(*args.Repository))) + } + ctx, traceErrs, endObservation := r.operations.configurationPolicies.WithErrors(ctx, &err, observation.Args{LogFields: fields}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + offset, err := graphqlutil.DecodeIntCursor(args.After) + if err != nil { + return nil, err + } + + pageSize := DefaultConfigurationPolicyPageSize + if args.First != nil { + pageSize = int(*args.First) + } + + opts := types.GetConfigurationPoliciesOptions{ + Limit: pageSize, + Offset: offset, + } + if args.Repository != nil { + id64, err := unmarshalRepositoryID(*args.Repository) + if err != nil { + return nil, err + } + opts.RepositoryID = int(id64) + } + if args.Query != nil { + opts.Term = *args.Query + } + if args.ForDataRetention != nil { + opts.ForDataRetention = *args.ForDataRetention + } + if args.ForIndexing != nil { + opts.ForIndexing = *args.ForIndexing + } + + policies, totalCount, err := r.policySvc.GetConfigurationPolicies(ctx, opts) + if err != nil { + return nil, err + } + + return NewCodeIntelligenceConfigurationPolicyConnectionResolver(r.policySvc, policies, totalCount, traceErrs), nil +} + +type CodeIntelConfigurationPolicy struct { + Name string + RepositoryID *int32 + RepositoryPatterns *[]string + Type types.GitObjectType + Pattern string + RetentionEnabled bool + RetentionDurationHours *int32 + RetainIntermediateCommits bool + IndexingEnabled bool + IndexCommitMaxAgeHours *int32 + IndexIntermediateCommits bool +} + +type CreateCodeIntelligenceConfigurationPolicyArgs struct { + Repository *graphql.ID + CodeIntelConfigurationPolicy +} + +// 🚨 SECURITY: Only site admins may modify code intelligence configuration policies +func (r *rootResolver) CreateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *CreateCodeIntelligenceConfigurationPolicyArgs) (_ CodeIntelligenceConfigurationPolicyResolver, err error) { + ctx, traceErrs, endObservation := r.operations.createConfigurationPolicy.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{}}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.policySvc.GetUnsafeDB()); err != nil { + return nil, err + } + + if err := validateConfigurationPolicy(args.CodeIntelConfigurationPolicy); err != nil { + return nil, err + } + + var repositoryID *int + if args.Repository != nil { + id64, err := unmarshalRepositoryID(*args.Repository) + if err != nil { + return nil, err + } + + id := int(id64) + repositoryID = &id + } + + opts := types.ConfigurationPolicy{ + RepositoryID: repositoryID, + Name: args.Name, + RepositoryPatterns: args.RepositoryPatterns, + Type: args.Type, + Pattern: args.Pattern, + RetentionEnabled: args.RetentionEnabled, + RetentionDuration: toDuration(args.RetentionDurationHours), + RetainIntermediateCommits: args.RetainIntermediateCommits, + IndexingEnabled: args.IndexingEnabled, + IndexCommitMaxAge: toDuration(args.IndexCommitMaxAgeHours), + IndexIntermediateCommits: args.IndexIntermediateCommits, + } + configurationPolicy, err := r.policySvc.CreateConfigurationPolicy(ctx, opts) + if err != nil { + return nil, err + } + + return NewConfigurationPolicyResolver(r.policySvc, configurationPolicy, traceErrs), nil +} + +type UpdateCodeIntelligenceConfigurationPolicyArgs struct { + ID graphql.ID + Repository *graphql.ID + CodeIntelConfigurationPolicy +} + +// 🚨 SECURITY: Only site admins may modify code intelligence configuration policies +func (r *rootResolver) UpdateCodeIntelligenceConfigurationPolicy(ctx context.Context, args *UpdateCodeIntelligenceConfigurationPolicyArgs) (_ *sharedresolvers.EmptyResponse, err error) { + ctx, _, endObservation := r.operations.updateConfigurationPolicy.With(ctx, &err, observation.Args{LogFields: []log.Field{ + log.String("configPolicyID", string(args.ID)), + }}) + defer endObservation(1, observation.Args{}) + + if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.policySvc.GetUnsafeDB()); err != nil { + return nil, err + } + + if err := validateConfigurationPolicy(args.CodeIntelConfigurationPolicy); err != nil { + return nil, err + } + + id, err := unmarshalConfigurationPolicyGQLID(args.ID) + if err != nil { + return nil, err + } + + opts := types.ConfigurationPolicy{ + ID: int(id), + Name: args.Name, + RepositoryPatterns: args.RepositoryPatterns, + Type: args.Type, + Pattern: args.Pattern, + RetentionEnabled: args.RetentionEnabled, + RetentionDuration: toDuration(args.RetentionDurationHours), + RetainIntermediateCommits: args.RetainIntermediateCommits, + IndexingEnabled: args.IndexingEnabled, + IndexCommitMaxAge: toDuration(args.IndexCommitMaxAgeHours), + IndexIntermediateCommits: args.IndexIntermediateCommits, + } + if err := r.policySvc.UpdateConfigurationPolicy(ctx, opts); err != nil { + return nil, err + } + + return &sharedresolvers.EmptyResponse{}, nil +} + +type DeleteCodeIntelligenceConfigurationPolicyArgs struct { + Policy graphql.ID +} + +// 🚨 SECURITY: Only site admins may modify code intelligence configuration policies +func (r *rootResolver) DeleteCodeIntelligenceConfigurationPolicy(ctx context.Context, args *DeleteCodeIntelligenceConfigurationPolicyArgs) (_ *sharedresolvers.EmptyResponse, err error) { + ctx, _, endObservation := r.operations.deleteConfigurationPolicy.With(ctx, &err, observation.Args{LogFields: []log.Field{ + log.String("configPolicyID", string(args.Policy)), + }}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.policySvc.GetUnsafeDB()); err != nil { + return nil, err + } + + id, err := unmarshalConfigurationPolicyGQLID(args.Policy) + if err != nil { + return nil, err + } + + if err := r.policySvc.DeleteConfigurationPolicyByID(ctx, int(id)); err != nil { + return nil, err + } + + return &sharedresolvers.EmptyResponse{}, nil +} + +type PreviewRepositoryFilterArgs struct { + graphqlutil.ConnectionArgs + Patterns []string + After *string +} + +const DefaultRepositoryFilterPreviewPageSize = 50 + +func (r *rootResolver) PreviewRepositoryFilter(ctx context.Context, args *PreviewRepositoryFilterArgs) (_ RepositoryFilterPreviewResolver, err error) { + ctx, _, endObservation := r.operations.previewRepoFilter.With(ctx, &err, observation.Args{}) + defer endObservation(1, observation.Args{}) + + offset, err := graphqlutil.DecodeIntCursor(args.After) + if err != nil { + return nil, err + } + + pageSize := DefaultRepositoryFilterPreviewPageSize + if args.First != nil { + pageSize = int(*args.First) + } + + ids, totalMatches, repositoryMatchLimit, err := r.policySvc.GetPreviewRepositoryFilter(ctx, args.Patterns, pageSize, offset) + if err != nil { + return nil, err + } + + resv := make([]*sharedresolvers.RepositoryResolver, 0, len(ids)) + logger := sglog.Scoped("PreviewRepositoryFilter", "policies resolver") + for _, id := range ids { + repo, err := backend.NewRepos(logger, r.policySvc.GetUnsafeDB()).Get(ctx, api.RepoID(id)) + if err != nil { + return nil, err + } + + resv = append(resv, sharedresolvers.NewRepositoryResolver(r.policySvc.GetUnsafeDB(), repo)) + } + + limitedCount := totalMatches + if repositoryMatchLimit != nil && *repositoryMatchLimit < limitedCount { + limitedCount = *repositoryMatchLimit + } + + return NewRepositoryFilterPreviewResolver(resv, limitedCount, totalMatches, offset, repositoryMatchLimit), nil +} + +type PreviewGitObjectFilterArgs struct { + Type types.GitObjectType + Pattern string +} + +func (r *rootResolver) PreviewGitObjectFilter(ctx context.Context, id graphql.ID, args *PreviewGitObjectFilterArgs) (_ []GitObjectFilterPreviewResolver, err error) { + ctx, _, endObservation := r.operations.previewGitObjectFilter.With(ctx, &err, observation.Args{}) + defer endObservation(1, observation.Args{}) + + repositoryID, err := unmarshalLSIFIndexGQLID(id) + if err != nil { + return nil, err + } + + namesByRev, err := r.policySvc.GetPreviewGitObjectFilter(ctx, int(repositoryID), args.Type, args.Pattern) + if err != nil { + return nil, err + } + + var previews []GitObjectFilterPreviewResolver + for rev, names := range namesByRev { + for _, name := range names { + previews = append(previews, &gitObjectFilterPreviewResolver{ + name: name, + rev: rev, + }) + } + } + + sort.Slice(previews, func(i, j int) bool { + return previews[i].Name() < previews[j].Name() || (previews[i].Name() == previews[j].Name() && previews[i].Rev() < previews[j].Rev()) + }) + + return previews, nil +} diff --git a/internal/codeintel/policies/transport/graphql/utils.go b/internal/codeintel/policies/transport/graphql/utils.go new file mode 100644 index 00000000000..4abf99b0ce9 --- /dev/null +++ b/internal/codeintel/policies/transport/graphql/utils.go @@ -0,0 +1,156 @@ +package graphql + +import ( + "encoding/base64" + "strconv" + "time" + + "github.com/graph-gophers/graphql-go" + "github.com/graph-gophers/graphql-go/relay" + + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/database" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// ConnectionArgs is the common set of arguments to GraphQL fields that return connections (lists). +type ConnectionArgs struct { + First *int32 // return the first n items +} + +// Set is a convenience method for setting the DB limit and offset in a DB XyzListOptions struct. +func (a ConnectionArgs) Set(o **database.LimitOffset) { + if a.First != nil { + *o = &database.LimitOffset{Limit: int(*a.First)} + } +} + +// GetFirst is a convenience method returning the value of First, defaulting to +// the type's zero value if nil. +func (a ConnectionArgs) GetFirst() int32 { + if a.First == nil { + return 0 + } + return *a.First +} + +func marshalConfigurationPolicyGQLID(configurationPolicyID int64) graphql.ID { + return relay.MarshalID("CodeIntelligenceConfigurationPolicy", configurationPolicyID) +} + +func unmarshalRepositoryID(id graphql.ID) (repositoryID int64, err error) { + err = relay.UnmarshalSpec(id, &repositoryID) + return repositoryID, err +} + +// PageInfo implements the GraphQL type PageInfo. +type PageInfo struct { + endCursor *string + hasNextPage bool +} + +// HasNextPage returns a new PageInfo with the given hasNextPage value. +func HasNextPage(hasNextPage bool) *PageInfo { + return &PageInfo{hasNextPage: hasNextPage} +} + +// NextPageCursor returns a new PageInfo indicating there is a next page with +// the given end cursor. +func NextPageCursor(endCursor string) *PageInfo { + return &PageInfo{endCursor: &endCursor, hasNextPage: true} +} + +func (r *PageInfo) EndCursor() *string { return r.endCursor } +func (r *PageInfo) HasNextPage() bool { return r.hasNextPage } + +func validateConfigurationPolicy(policy CodeIntelConfigurationPolicy) error { + switch policy.Type { + case types.GitObjectTypeCommit: + case types.GitObjectTypeTag: + case types.GitObjectTypeTree: + default: + return errors.Errorf("illegal git object type '%s', expected 'GIT_COMMIT', 'GIT_TAG', or 'GIT_TREE'", policy.Type) + } + + if policy.Name == "" { + return errors.Errorf("no name supplied") + } + if policy.Pattern == "" { + return errors.Errorf("no pattern supplied") + } + if policy.Type == types.GitObjectTypeCommit && policy.Pattern != "HEAD" { + return errors.Errorf("pattern must be HEAD for policy type 'GIT_COMMIT'") + } + if policy.RetentionDurationHours != nil && *policy.RetentionDurationHours <= 0 { + return errors.Errorf("illegal retention duration '%d'", *policy.RetentionDurationHours) + } + if policy.IndexCommitMaxAgeHours != nil && *policy.IndexCommitMaxAgeHours <= 0 { + return errors.Errorf("illegal index commit max age '%d'", *policy.IndexCommitMaxAgeHours) + } + + return nil +} + +func toDuration(hours *int32) *time.Duration { + if hours == nil { + return nil + } + + v := time.Duration(*hours) * time.Hour + return &v +} + +func unmarshalConfigurationPolicyGQLID(id graphql.ID) (configurationPolicyID int64, err error) { + err = relay.UnmarshalSpec(id, &configurationPolicyID) + return configurationPolicyID, err +} + +// EncodeIntCursor creates a PageInfo object from the given new offset value. If the +// new offset value, then an object indicating the end of the result set is returned. +// The cursor is base64 encoded for transfer, and should be decoded using the function +// decodeIntCursor. +func EncodeIntCursor(val *int32) *PageInfo { + if val == nil { + return EncodeCursor(nil) + } + + str := strconv.FormatInt(int64(*val), 10) + return EncodeCursor(&str) +} + +// EncodeCursor creates a PageInfo object from the given cursor. If the cursor is not +// defined, then an object indicating the end of the result set is returned. The cursor +// is base64 encoded for transfer, and should be decoded using the function decodeCursor. +func EncodeCursor(val *string) *PageInfo { + if val != nil { + return NextPageCursor(base64.StdEncoding.EncodeToString([]byte(*val))) + } + + return HasNextPage(false) +} + +// toInt32 translates the given int pointer into an int32 pointer. +func toInt32(val *int) *int32 { + if val == nil { + return nil + } + + v := int32(*val) + return &v +} + +// NextOffset determines the offset that should be used for a subsequent request. +// If there are no more results in the paged result set, this function returns nil. +func NextOffset(offset, count, totalCount int) *int { + if offset+count < totalCount { + val := offset + count + return &val + } + + return nil +} + +func unmarshalLSIFIndexGQLID(id graphql.ID) (indexID int64, err error) { + err = relay.UnmarshalSpec(id, &indexID) + return indexID, err +} diff --git a/internal/codeintel/sharedresolvers/audit_log_column_resolver.go b/internal/codeintel/sharedresolvers/audit_log_column_resolver.go new file mode 100644 index 00000000000..1383a432876 --- /dev/null +++ b/internal/codeintel/sharedresolvers/audit_log_column_resolver.go @@ -0,0 +1,27 @@ +package sharedresolvers + +type AuditLogColumnChangeResolver interface { + Column() string + Old() *string + New() *string +} + +type auditLogColumnChangeResolver struct { + columnTransition map[string]*string +} + +func NewAuditLogColumnChangeResolver(columnTransition map[string]*string) AuditLogColumnChangeResolver { + return &auditLogColumnChangeResolver{columnTransition} +} + +func (r *auditLogColumnChangeResolver) Column() string { + return *r.columnTransition["column"] +} + +func (r *auditLogColumnChangeResolver) Old() *string { + return r.columnTransition["old"] +} + +func (r *auditLogColumnChangeResolver) New() *string { + return r.columnTransition["new"] +} diff --git a/internal/codeintel/sharedresolvers/audit_log_resolver.go b/internal/codeintel/sharedresolvers/audit_log_resolver.go new file mode 100644 index 00000000000..e8c4ccf88ac --- /dev/null +++ b/internal/codeintel/sharedresolvers/audit_log_resolver.go @@ -0,0 +1,67 @@ +package sharedresolvers + +import ( + "strings" + + "github.com/graph-gophers/graphql-go" + + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" +) + +type LSIFUploadsAuditLogsResolver interface { + LogTimestamp() DateTime + UploadDeletedAt() *DateTime + Reason() *string + ChangedColumns() []AuditLogColumnChange + UploadID() graphql.ID + InputCommit() string + InputRoot() string + InputIndexer() string + UploadedAt() DateTime + Operation() string + // AssociatedIndex(ctx context.Context) (LSIFIndexResolver, error) +} + +type AuditLogColumnChange interface { + Column() string + Old() *string + New() *string +} + +type lsifUploadsAuditLogResolver struct { + log types.UploadLog +} + +func NewLSIFUploadsAuditLogsResolver(log types.UploadLog) LSIFUploadsAuditLogsResolver { + return &lsifUploadsAuditLogResolver{log: log} +} + +func (r *lsifUploadsAuditLogResolver) Reason() *string { return r.log.Reason } +func (r *lsifUploadsAuditLogResolver) ChangedColumns() (values []AuditLogColumnChange) { + for _, transition := range r.log.TransitionColumns { + values = append(values, &auditLogColumnChangeResolver{transition}) + } + return values +} + +func (r *lsifUploadsAuditLogResolver) LogTimestamp() DateTime { + return DateTime{Time: r.log.LogTimestamp} +} + +func (r *lsifUploadsAuditLogResolver) UploadDeletedAt() *DateTime { + return DateTimeOrNil(r.log.RecordDeletedAt) +} + +func (r *lsifUploadsAuditLogResolver) UploadID() graphql.ID { + return marshalLSIFUploadGQLID(int64(r.log.UploadID)) +} +func (r *lsifUploadsAuditLogResolver) InputCommit() string { return r.log.Commit } +func (r *lsifUploadsAuditLogResolver) InputRoot() string { return r.log.Root } +func (r *lsifUploadsAuditLogResolver) InputIndexer() string { return r.log.Indexer } +func (r *lsifUploadsAuditLogResolver) UploadedAt() DateTime { + return DateTime{Time: r.log.UploadedAt} +} + +func (r *lsifUploadsAuditLogResolver) Operation() string { + return strings.ToUpper(r.log.Operation) +} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/locations.go b/internal/codeintel/sharedresolvers/cached_location_resolver.go similarity index 77% rename from enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/locations.go rename to internal/codeintel/sharedresolvers/cached_location_resolver.go index df1c3dbcefe..daf078eb12b 100644 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/locations.go +++ b/internal/codeintel/sharedresolvers/cached_location_resolver.go @@ -1,4 +1,4 @@ -package graphql +package sharedresolvers import ( "context" @@ -7,7 +7,6 @@ import ( "github.com/sourcegraph/log" "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" "github.com/sourcegraph/sourcegraph/internal/api" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/errcode" @@ -34,14 +33,14 @@ type CachedLocationResolver struct { type cachedRepositoryResolver struct { sync.RWMutex - resolver *gql.RepositoryResolver + resolver *RepositoryResolver children map[string]*cachedCommitResolver } type cachedCommitResolver struct { sync.RWMutex - resolver *gql.GitCommitResolver - children map[string]*gql.GitTreeEntryResolver + resolver *GitCommitResolver + children map[string]*GitTreeEntryResolver } // NewCachedLocationResolver creates a location resolver with an empty cache. @@ -56,7 +55,7 @@ func NewCachedLocationResolver(db database.DB) *CachedLocationResolver { // Repository resolves the repository with the given identifier. This method may return a nil resolver // if the repository is not known by gitserver - this happens if there is exists still a bundle for a // repo that has since been deleted. -func (r *CachedLocationResolver) Repository(ctx context.Context, id api.RepoID) (*gql.RepositoryResolver, error) { +func (r *CachedLocationResolver) Repository(ctx context.Context, id api.RepoID) (*RepositoryResolver, error) { cachedRepositoryResolver, err := r.cachedRepository(ctx, id) if err != nil || cachedRepositoryResolver == nil { return nil, err @@ -66,7 +65,7 @@ func (r *CachedLocationResolver) Repository(ctx context.Context, id api.RepoID) // Commit resolves the git commit with the given repository identifier and commit hash. This method may // return a nil resolver if the commit is not known by gitserver. -func (r *CachedLocationResolver) Commit(ctx context.Context, id api.RepoID, commit string) (*gql.GitCommitResolver, error) { +func (r *CachedLocationResolver) Commit(ctx context.Context, id api.RepoID, commit string) (*GitCommitResolver, error) { cachedCommitResolver, err := r.cachedCommit(ctx, id, commit) if err != nil || cachedCommitResolver == nil { return nil, err @@ -76,7 +75,7 @@ func (r *CachedLocationResolver) Commit(ctx context.Context, id api.RepoID, comm // Path resolves the git tree entry with the given repository identifier, commit hash, and relative path. // This method may return a nil resolver if the commit is not known by gitserver. -func (r *CachedLocationResolver) Path(ctx context.Context, id api.RepoID, commit, path string) (*gql.GitTreeEntryResolver, error) { +func (r *CachedLocationResolver) Path(ctx context.Context, id api.RepoID, commit, path string) (*GitTreeEntryResolver, error) { pathResolver, err := r.cachedPath(ctx, id, commit, path) if err != nil { return nil, err @@ -160,7 +159,7 @@ func (r *CachedLocationResolver) cachedCommit(ctx context.Context, id api.RepoID // of a path may result in a nil dereference. var cachedResolver *cachedCommitResolver if resolver != nil { - cachedResolver = &cachedCommitResolver{resolver: resolver, children: map[string]*gql.GitTreeEntryResolver{}} + cachedResolver = &cachedCommitResolver{resolver: resolver, children: map[string]*GitTreeEntryResolver{}} } parentResolver.children[commit] = cachedResolver return cachedResolver, nil @@ -171,7 +170,7 @@ func (r *CachedLocationResolver) cachedCommit(ctx context.Context, id api.RepoID // double-checked locking, which ensures that the resolver is created exactly once per GraphQL request. // // See https://en.wikipedia.org/wiki/Double-checked_locking. -func (r *CachedLocationResolver) cachedPath(ctx context.Context, id api.RepoID, commit, path string) (*gql.GitTreeEntryResolver, error) { +func (r *CachedLocationResolver) cachedPath(ctx context.Context, id api.RepoID, commit, path string) (*GitTreeEntryResolver, error) { parentResolver, err := r.cachedCommit(ctx, id, commit) if err != nil || parentResolver == nil { return nil, err @@ -203,7 +202,7 @@ func (r *CachedLocationResolver) cachedPath(ctx context.Context, id api.RepoID, // if the repository is not known by gitserver - this happens if there is exists still a bundle for a // repo that has since been deleted. This method must be called only when constructing a resolver to // populate the cache. -func (r *CachedLocationResolver) resolveRepository(ctx context.Context, id api.RepoID) (*gql.RepositoryResolver, error) { +func (r *CachedLocationResolver) resolveRepository(ctx context.Context, id api.RepoID) (*RepositoryResolver, error) { repo, err := backend.NewRepos(r.logger, r.db).Get(ctx, id) if err != nil { if errcode.IsNotFound(err) { @@ -212,13 +211,13 @@ func (r *CachedLocationResolver) resolveRepository(ctx context.Context, id api.R return nil, err } - return gql.NewRepositoryResolver(r.db, repo), nil + return NewRepositoryResolver(r.db, repo), nil } // Commit resolves the git commit with the given repository resolver and commit hash. This method may // return a nil resolver if the commit is not known by gitserver. This method must be called only when // constructing a resolver to populate the cache. -func (r *CachedLocationResolver) resolveCommit(ctx context.Context, repositoryResolver *gql.RepositoryResolver, commit string) (*gql.GitCommitResolver, error) { +func (r *CachedLocationResolver) resolveCommit(ctx context.Context, repositoryResolver *RepositoryResolver, commit string) (*GitCommitResolver, error) { repo, err := repositoryResolver.Type(ctx) if err != nil { return nil, err @@ -232,43 +231,11 @@ func (r *CachedLocationResolver) resolveCommit(ctx context.Context, repositoryRe return nil, err } - return repositoryResolver.CommitFromID(ctx, &gql.RepositoryCommitArgs{Rev: commit}, commitID) + return repositoryResolver.CommitFromID(ctx, &RepositoryCommitArgs{Rev: commit}, commitID) } // Path resolves the git tree entry with the given commit resolver and relative path. This method must be // called only when constructing a resolver to populate the cache. -func (r *CachedLocationResolver) resolvePath(commitResolver *gql.GitCommitResolver, path string) *gql.GitTreeEntryResolver { - return gql.NewGitTreeEntryResolver(r.db, commitResolver, gql.CreateFileInfo(path, false)) -} - -// resolveLocations creates a slide of LocationResolvers for the given list of adjusted locations. The -// resulting list may be smaller than the input list as any locations with a commit not known by -// gitserver will be skipped. -func resolveLocations(ctx context.Context, locationResolver *CachedLocationResolver, locations []AdjustedLocation) ([]gql.LocationResolver, error) { - resolvedLocations := make([]gql.LocationResolver, 0, len(locations)) - for i := range locations { - resolver, err := resolveLocation(ctx, locationResolver, locations[i]) - if err != nil { - return nil, err - } - if resolver == nil { - continue - } - - resolvedLocations = append(resolvedLocations, resolver) - } - - return resolvedLocations, nil -} - -// resolveLocation creates a LocationResolver for the given adjusted location. This function may return a -// nil resolver if the location's commit is not known by gitserver. -func resolveLocation(ctx context.Context, locationResolver *CachedLocationResolver, location AdjustedLocation) (gql.LocationResolver, error) { - treeResolver, err := locationResolver.Path(ctx, api.RepoID(location.Dump.RepositoryID), location.AdjustedCommit, location.Path) - if err != nil || treeResolver == nil { - return nil, err - } - - lspRange := convertRange(location.AdjustedRange) - return gql.NewLocationResolver(treeResolver, &lspRange), nil +func (r *CachedLocationResolver) resolvePath(commitResolver *GitCommitResolver, path string) *GitTreeEntryResolver { + return NewGitTreeEntryResolver(r.db, commitResolver, CreateFileInfo(path, false)) } diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/locations_test.go b/internal/codeintel/sharedresolvers/cached_location_resolver_test.go similarity index 66% rename from enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/locations_test.go rename to internal/codeintel/sharedresolvers/cached_location_resolver_test.go index 976c5455bcd..c60d1f80424 100644 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/locations_test.go +++ b/internal/codeintel/sharedresolvers/cached_location_resolver_test.go @@ -1,4 +1,4 @@ -package graphql +package sharedresolvers import ( "context" @@ -11,11 +11,7 @@ import ( mockrequire "github.com/derision-test/go-mockgen/testutil/require" "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" "github.com/sourcegraph/sourcegraph/internal/api" - store "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/lsifstore" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/gitserver" "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" @@ -73,7 +69,7 @@ func TestCachedLocationResolver(t *testing.T) { type resolverPair struct { key string - resolver *gql.GitTreeEntryResolver + resolver *GitTreeEntryResolver } resolvers := make(chan resolverPair, numRoutines*len(repositoryIDs)*len(commits)*len(paths)) @@ -91,7 +87,7 @@ func TestCachedLocationResolver(t *testing.T) { errs <- err return } - repoID, err := gql.UnmarshalRepositoryID(repositoryResolver.ID()) + repoID, err := UnmarshalRepositoryID(repositoryResolver.ID()) if err != nil { errs <- err return @@ -109,7 +105,7 @@ func TestCachedLocationResolver(t *testing.T) { errs <- err return } - if commitResolver.OID() != graphqlbackend.GitObjectID(commit) { + if commitResolver.OID() != GitObjectID(commit) { errs <- errors.Errorf("unexpected commit. want=%s have=%s", commit, commitResolver.OID()) return } @@ -152,7 +148,7 @@ func TestCachedLocationResolver(t *testing.T) { } close(resolvers) - resolversByKey := map[string][]*gql.GitTreeEntryResolver{} + resolversByKey := map[string][]*GitTreeEntryResolver{} for pair := range resolvers { resolversByKey[pair.key] = append(resolversByKey[pair.key], pair.resolver) } @@ -226,59 +222,3 @@ func TestCachedLocationResolverUnknownCommit(t *testing.T) { } mockrequire.Called(t, repos.GetFunc) } - -func TestResolveLocations(t *testing.T) { - repos := database.NewStrictMockRepoStore() - repos.GetFunc.SetDefaultHook(func(_ context.Context, id api.RepoID) (*types.Repo, error) { - return &types.Repo{ID: id, Name: api.RepoName(fmt.Sprintf("repo%d", id))}, nil - }) - - db := database.NewStrictMockDB() - db.ReposFunc.SetDefaultReturn(repos) - - t.Cleanup(func() { - gitserver.Mocks.ResolveRevision = nil - backend.Mocks.Repos.GetCommit = nil - }) - - gitserver.Mocks.ResolveRevision = func(spec string, _ gitserver.ResolveRevisionOptions) (api.CommitID, error) { - if spec == "deadbeef3" { - return "", &gitdomain.RevisionNotFoundError{} - } - return api.CommitID(spec), nil - } - - backend.Mocks.Repos.GetCommit = func(v0 context.Context, repo *types.Repo, commitID api.CommitID) (*gitdomain.Commit, error) { - return &gitdomain.Commit{ID: commitID}, nil - } - - r1 := lsifstore.Range{Start: lsifstore.Position{Line: 11, Character: 12}, End: lsifstore.Position{Line: 13, Character: 14}} - r2 := lsifstore.Range{Start: lsifstore.Position{Line: 21, Character: 22}, End: lsifstore.Position{Line: 23, Character: 24}} - r3 := lsifstore.Range{Start: lsifstore.Position{Line: 31, Character: 32}, End: lsifstore.Position{Line: 33, Character: 34}} - r4 := lsifstore.Range{Start: lsifstore.Position{Line: 41, Character: 42}, End: lsifstore.Position{Line: 43, Character: 44}} - - locations, err := resolveLocations(context.Background(), NewCachedLocationResolver(db), []AdjustedLocation{ - {Dump: store.Dump{RepositoryID: 50}, AdjustedCommit: "deadbeef1", AdjustedRange: r1, Path: "p1"}, - {Dump: store.Dump{RepositoryID: 51}, AdjustedCommit: "deadbeef2", AdjustedRange: r2, Path: "p2"}, - {Dump: store.Dump{RepositoryID: 52}, AdjustedCommit: "deadbeef3", AdjustedRange: r3, Path: "p3"}, - {Dump: store.Dump{RepositoryID: 53}, AdjustedCommit: "deadbeef4", AdjustedRange: r4, Path: "p4"}, - }) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - - mockrequire.Called(t, repos.GetFunc) - - if len(locations) != 3 { - t.Fatalf("unexpected length. want=%d have=%d", 3, len(locations)) - } - if url := locations[0].CanonicalURL(); url != "/repo50@deadbeef1/-/blob/p1?L12:13-14:15" { - t.Errorf("unexpected canonical url. want=%s have=%s", "/repo50@deadbeef1/-/blob/p1?L12:13-14:15", url) - } - if url := locations[1].CanonicalURL(); url != "/repo51@deadbeef2/-/blob/p2?L22:23-24:25" { - t.Errorf("unexpected canonical url. want=%s have=%s", "/repo51@deadbeef2/-/blob/p2?L22:23-24:25", url) - } - if url := locations[2].CanonicalURL(); url != "/repo53@deadbeef4/-/blob/p4?L42:43-44:45" { - t.Errorf("unexpected canonical url. want=%s have=%s", "/repo53@deadbeef4/-/blob/p4?L42:43-44:45", url) - } -} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/configuration_policy.go b/internal/codeintel/sharedresolvers/configuration_policy_resolver.go similarity index 65% rename from enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/configuration_policy.go rename to internal/codeintel/sharedresolvers/configuration_policy_resolver.go index e543fb2d894..56b7565b45a 100644 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/configuration_policy.go +++ b/internal/codeintel/sharedresolvers/configuration_policy_resolver.go @@ -1,48 +1,63 @@ -package graphql +package sharedresolvers import ( "context" "time" "github.com/graph-gophers/graphql-go" + "github.com/graph-gophers/graphql-go/relay" "github.com/opentracing/opentracing-go/log" sglog "github.com/sourcegraph/log" "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" - gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" "github.com/sourcegraph/sourcegraph/internal/api" - store "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - "github.com/sourcegraph/sourcegraph/internal/database" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/lib/errors" ) +type CodeIntelligenceConfigurationPolicyResolver interface { + ID() graphql.ID + Repository(ctx context.Context) (*RepositoryResolver, error) + RepositoryPatterns() *[]string + Name() string + Type() (types.GitObjectType, error) + Pattern() string + Protected() bool + RetentionEnabled() bool + RetentionDurationHours() *int32 + RetainIntermediateCommits() bool + IndexingEnabled() bool + IndexCommitMaxAgeHours() *int32 + IndexIntermediateCommits() bool +} + type configurationPolicyResolver struct { + svc AutoIndexingService logger sglog.Logger - db database.DB - configurationPolicy store.ConfigurationPolicy + configurationPolicy types.ConfigurationPolicy errTracer *observation.ErrCollector } -func NewConfigurationPolicyResolver(db database.DB, configurationPolicy store.ConfigurationPolicy, errTracer *observation.ErrCollector) gql.CodeIntelligenceConfigurationPolicyResolver { +func NewConfigurationPolicyResolver(svc AutoIndexingService, configurationPolicy types.ConfigurationPolicy, errTracer *observation.ErrCollector) CodeIntelligenceConfigurationPolicyResolver { return &configurationPolicyResolver{ + svc: svc, logger: sglog.Scoped("configurationPolicyResolver", ""), - db: db, configurationPolicy: configurationPolicy, errTracer: errTracer, } } func (r *configurationPolicyResolver) ID() graphql.ID { - return marshalConfigurationPolicyGQLID(int64(r.configurationPolicy.ID)) + return relay.MarshalID("CodeIntelligenceConfigurationPolicy", r.configurationPolicy.ID) } func (r *configurationPolicyResolver) Name() string { return r.configurationPolicy.Name } -func (r *configurationPolicyResolver) Repository(ctx context.Context) (_ *gql.RepositoryResolver, err error) { +func (r *configurationPolicyResolver) Repository(ctx context.Context) (_ *RepositoryResolver, err error) { if r.configurationPolicy.RepositoryID == nil { return nil, nil } @@ -53,19 +68,20 @@ func (r *configurationPolicyResolver) Repository(ctx context.Context) (_ *gql.Re log.Int("repoID", *r.configurationPolicy.RepositoryID), ) - repo, err := backend.NewRepos(r.logger, r.db).Get(ctx, api.RepoID(*r.configurationPolicy.RepositoryID)) + db := r.svc.GetUnsafeDB() + repo, err := backend.NewRepos(r.logger, db).Get(ctx, api.RepoID(*r.configurationPolicy.RepositoryID)) if err != nil { return nil, err } - return gql.NewRepositoryResolver(r.db, repo), nil + return NewRepositoryResolver(db, repo), nil } func (r *configurationPolicyResolver) RepositoryPatterns() *[]string { return r.configurationPolicy.RepositoryPatterns } -func (r *configurationPolicyResolver) Type() (_ gql.GitObjectType, err error) { +func (r *configurationPolicyResolver) Type() (_ types.GitObjectType, err error) { defer r.errTracer.Collect(&err, log.String("configurationPolicyResolver.field", "type"), log.Int("configurationPolicyID", r.configurationPolicy.ID), @@ -73,12 +89,12 @@ func (r *configurationPolicyResolver) Type() (_ gql.GitObjectType, err error) { ) switch r.configurationPolicy.Type { - case store.GitObjectTypeCommit: - return gql.GitObjectTypeCommit, nil - case store.GitObjectTypeTag: - return gql.GitObjectTypeTag, nil - case store.GitObjectTypeTree: - return gql.GitObjectTypeTree, nil + case types.GitObjectTypeCommit: + return types.GitObjectTypeCommit, nil + case types.GitObjectTypeTag: + return types.GitObjectTypeTag, nil + case types.GitObjectTypeTree: + return types.GitObjectTypeTree, nil default: return "", errors.Errorf("unknown git object type %s", r.configurationPolicy.Type) } diff --git a/internal/codeintel/sharedresolvers/empty_resolver.go b/internal/codeintel/sharedresolvers/empty_resolver.go new file mode 100644 index 00000000000..54d37206897 --- /dev/null +++ b/internal/codeintel/sharedresolvers/empty_resolver.go @@ -0,0 +1,11 @@ +package sharedresolvers + +// EmptyResponse is a type that can be used in the return signature for graphql queries +// that don't require a return value. +type EmptyResponse struct{} + +// AlwaysNil exists since various graphql tools expect at least one field to be +// present in the schema so we provide a dummy one here that is always nil. +func (er *EmptyResponse) AlwaysNil() *string { + return nil +} diff --git a/internal/codeintel/sharedresolvers/execution_log_entry_resolver.go b/internal/codeintel/sharedresolvers/execution_log_entry_resolver.go new file mode 100644 index 00000000000..3fcc296ce97 --- /dev/null +++ b/internal/codeintel/sharedresolvers/execution_log_entry_resolver.go @@ -0,0 +1,65 @@ +package sharedresolvers + +import ( + "context" + + "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" +) + +type ExecutionLogEntryResolver interface { + Key() string + Command() []string + StartTime() DateTime + ExitCode() *int32 + Out(ctx context.Context) (string, error) + DurationMilliseconds() *int32 +} + +type executionLogEntryResolver struct { + svc AutoIndexingService + entry types.ExecutionLogEntry +} + +func NewExecutionLogEntryResolver(svc AutoIndexingService, entry types.ExecutionLogEntry) ExecutionLogEntryResolver { + return &executionLogEntryResolver{ + svc: svc, + entry: entry, + } +} + +func (r *executionLogEntryResolver) Key() string { return r.entry.Key } +func (r *executionLogEntryResolver) Command() []string { return r.entry.Command } + +func (r *executionLogEntryResolver) ExitCode() *int32 { + if r.entry.ExitCode == nil { + return nil + } + val := int32(*r.entry.ExitCode) + return &val +} + +func (r *executionLogEntryResolver) StartTime() DateTime { + return DateTime{Time: r.entry.StartTime} +} + +func (r *executionLogEntryResolver) DurationMilliseconds() *int32 { + if r.entry.DurationMs == nil { + return nil + } + val := int32(*r.entry.DurationMs) + return &val +} + +func (r *executionLogEntryResolver) Out(ctx context.Context) (string, error) { + // 🚨 SECURITY: Only site admins can view executor log contents. + if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.svc.GetUnsafeDB()); err != nil { + if err != backend.ErrMustBeSiteAdmin { + return "", err + } + + return "", nil + } + + return r.entry.Out, nil +} diff --git a/internal/codeintel/sharedresolvers/git_commit_resolver.go b/internal/codeintel/sharedresolvers/git_commit_resolver.go new file mode 100644 index 00000000000..219d5baa221 --- /dev/null +++ b/internal/codeintel/sharedresolvers/git_commit_resolver.go @@ -0,0 +1,84 @@ +package sharedresolvers + +import ( + "net/url" + + "github.com/graph-gophers/graphql-go" + + "github.com/sourcegraph/sourcegraph/internal/api" +) + +type GitCommitResolver struct { + // oid MUST be specified and a 40-character Git SHA. + oid GitObjectID + + repoResolver *RepositoryResolver + + // inputRev is the Git revspec that the user originally requested that resolved to this Git commit. It is used + // to avoid redirecting a user browsing a revision "mybranch" to the absolute commit ID as they follow links in the UI. + inputRev *string +} + +// NewGitCommitResolver returns a new CommitResolver. When commit is set to nil, +// commit will be loaded lazily as needed by the resolver. Pass in a commit when +// you have batch-loaded a bunch of them and already have them at hand. +func NewGitCommitResolver(repo *RepositoryResolver, id api.CommitID) *GitCommitResolver { + return &GitCommitResolver{ + oid: GitObjectID(id), + repoResolver: repo, + } +} + +func (r *GitCommitResolver) ID() graphql.ID { + return marshalGitCommitID(r.repoResolver.ID(), r.oid) +} + +func (r *GitCommitResolver) Repository() *RepositoryResolver { return r.repoResolver } + +func (r *GitCommitResolver) OID() GitObjectID { return r.oid } + +func (r *GitCommitResolver) AbbreviatedOID() string { + return string(r.oid)[:7] +} + +func (r *GitCommitResolver) URL() string { + url := r.repoResolver.url() + url.Path += "/-/commit/" + r.inputRevOrImmutableRev() + return url.String() +} + +// inputRevOrImmutableRev returns the input revspec, if it is provided and nonempty. Otherwise it returns the +// canonical OID for the revision. +func (r *GitCommitResolver) inputRevOrImmutableRev() string { + if r.inputRev != nil && *r.inputRev != "" { + return *r.inputRev + } + return string(r.oid) +} + +func (r *GitCommitResolver) canonicalRepoRevURL() *url.URL { + // Dereference to copy the URL to avoid mutation + url := *r.repoResolver.RepoMatch.URL() + url.Path += "@" + string(r.oid) + return &url +} + +// repoRevURL returns the URL path prefix to use when constructing URLs to resources at this +// revision. Unlike inputRevOrImmutableRev, it does NOT use the OID if no input revspec is +// given. This is because the convention in the frontend is for repo-rev URLs to omit the "@rev" +// portion (unlike for commit page URLs, which must include some revspec in +// "/REPO/-/commit/REVSPEC"). +func (r *GitCommitResolver) repoRevURL() *url.URL { + // Dereference to copy to avoid mutation + url := *r.repoResolver.RepoMatch.URL() + var rev string + if r.inputRev != nil { + rev = *r.inputRev // use the original input rev from the user + } else { + rev = string(r.oid) + } + if rev != "" { + url.Path += "@" + rev + } + return &url +} diff --git a/internal/codeintel/sharedresolvers/git_object.go b/internal/codeintel/sharedresolvers/git_object.go new file mode 100644 index 00000000000..430268593fe --- /dev/null +++ b/internal/codeintel/sharedresolvers/git_object.go @@ -0,0 +1,32 @@ +package sharedresolvers + +import ( + "github.com/sourcegraph/sourcegraph/internal/gitserver" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +type GitObjectType string + +func (GitObjectType) ImplementsGraphQLType(name string) bool { return name == "GitObjectType" } + +const ( + GitObjectTypeCommit GitObjectType = "GIT_COMMIT" + GitObjectTypeTag GitObjectType = "GIT_TAG" + GitObjectTypeTree GitObjectType = "GIT_TREE" + GitObjectTypeBlob GitObjectType = "GIT_BLOB" + GitObjectTypeUnknown GitObjectType = "GIT_UNKNOWN" +) + +type GitObjectID string + +func (GitObjectID) ImplementsGraphQLType(name string) bool { + return name == "GitObjectID" +} + +func (id *GitObjectID) UnmarshalGraphQL(input any) error { + if input, ok := input.(string); ok && gitserver.IsAbsoluteRevision(input) { + *id = GitObjectID(input) + return nil + } + return errors.New("GitObjectID: expected 40-character string (SHA-1 hash)") +} diff --git a/internal/codeintel/sharedresolvers/git_tree_entry_resolver.go b/internal/codeintel/sharedresolvers/git_tree_entry_resolver.go new file mode 100644 index 00000000000..41c3bbffc63 --- /dev/null +++ b/internal/codeintel/sharedresolvers/git_tree_entry_resolver.go @@ -0,0 +1,143 @@ +package sharedresolvers + +import ( + "context" + "io/fs" + "net/url" + "path" + "strings" + "sync" + "time" + + "github.com/sourcegraph/log" + + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/authz" + "github.com/sourcegraph/sourcegraph/internal/cloneurls" + "github.com/sourcegraph/sourcegraph/internal/database" + "github.com/sourcegraph/sourcegraph/internal/gitserver" + "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// GitTreeEntryResolver resolves an entry in a Git tree in a repository. The entry can be any Git +// object type that is valid in a tree. +// +// Prefer using the constructor, NewGitTreeEntryResolver. +type GitTreeEntryResolver struct { + db database.DB + commit *GitCommitResolver + + contentOnce sync.Once + content []byte + contentErr error + + // stat is this tree entry's file info. Its Name method must return the full path relative to + // the root, not the basename. + stat fs.FileInfo +} + +func NewGitTreeEntryResolver(db database.DB, commit *GitCommitResolver, stat fs.FileInfo) *GitTreeEntryResolver { + return &GitTreeEntryResolver{db: db, commit: commit, stat: stat} +} +func (r *GitTreeEntryResolver) Path() string { return r.stat.Name() } +func (r *GitTreeEntryResolver) Name() string { return path.Base(r.stat.Name()) } + +func (r *GitTreeEntryResolver) ToGitTree() (*GitTreeEntryResolver, bool) { return r, r.IsDirectory() } +func (r *GitTreeEntryResolver) ToGitBlob() (*GitTreeEntryResolver, bool) { return r, !r.IsDirectory() } + +// func (r *GitTreeEntryResolver) ToVirtualFile() (*virtualFileResolver, bool) { return nil, false } + +func (r *GitTreeEntryResolver) ByteSize(ctx context.Context) (int32, error) { + content, err := r.Content(ctx) + if err != nil { + return 0, err + } + return int32(len([]byte(content))), nil +} + +func (r *GitTreeEntryResolver) Content(ctx context.Context) (string, error) { + r.contentOnce.Do(func() { + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + + r.content, r.contentErr = gitserver.NewClient(r.db).ReadFile( + ctx, + r.commit.repoResolver.RepoName(), + api.CommitID(r.commit.OID()), + r.Path(), + authz.DefaultSubRepoPermsChecker, + ) + }) + + return string(r.content), r.contentErr +} + +func (r *GitTreeEntryResolver) Commit() *GitCommitResolver { return r.commit } +func (r *GitTreeEntryResolver) Repository() *RepositoryResolver { return r.commit.repoResolver } +func (r *GitTreeEntryResolver) CanonicalURL() string { + url := r.commit.canonicalRepoRevURL() + return r.urlPath(url).String() +} + +func (r *GitTreeEntryResolver) IsRoot() bool { + path := path.Clean(r.Path()) + return path == "/" || path == "." || path == "" +} + +func (r *GitTreeEntryResolver) IsDirectory() bool { return r.stat.Mode().IsDir() } + +func (r *GitTreeEntryResolver) URL(ctx context.Context) (string, error) { + return r.url(ctx).String(), nil +} + +func (r *GitTreeEntryResolver) Submodule() *gitSubmoduleResolver { + if submoduleInfo, ok := r.stat.Sys().(gitdomain.Submodule); ok { + // return &gitSubmoduleResolver{submodule: submoduleInfo} + return NewGitSubmoduleResolver(submoduleInfo) + } + return nil +} + +func (r *GitTreeEntryResolver) url(ctx context.Context) *url.URL { + if submodule := r.Submodule(); submodule != nil { + submoduleURL := submodule.URL() + if strings.HasPrefix(submoduleURL, "../") { + submoduleURL = path.Join(r.Repository().Name(), submoduleURL) + } + repoName, err := cloneURLToRepoName(ctx, r.db, submoduleURL) + if err != nil { + log.Error(err) + return &url.URL{} + } + return &url.URL{Path: "/" + repoName + "@" + submodule.Commit()} + } + return r.urlPath(r.commit.repoRevURL()) +} + +func (r *GitTreeEntryResolver) urlPath(prefix *url.URL) *url.URL { + // Dereference to copy to avoid mutating the input + u := *prefix + if r.IsRoot() { + return &u + } + + typ := "blob" + if r.IsDirectory() { + typ = "tree" + } + + u.Path = path.Join(u.Path, "-", typ, r.Path()) + return &u +} + +func cloneURLToRepoName(ctx context.Context, db database.DB, cloneURL string) (string, error) { + repoName, err := cloneurls.ReposourceCloneURLToRepoName(ctx, db, cloneURL) + if err != nil { + return "", err + } + if repoName == "" { + return "", errors.Errorf("no matching code host found for %s", cloneURL) + } + return string(repoName), nil +} diff --git a/internal/codeintel/sharedresolvers/git_tree_submodule_resolver.go b/internal/codeintel/sharedresolvers/git_tree_submodule_resolver.go new file mode 100644 index 00000000000..712f5725cce --- /dev/null +++ b/internal/codeintel/sharedresolvers/git_tree_submodule_resolver.go @@ -0,0 +1,31 @@ +package sharedresolvers + +import ( + "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" +) + +type GitSubmoduleResolver interface { + URL() string + Commit() string + Path() string +} + +type gitSubmoduleResolver struct { + submodule gitdomain.Submodule +} + +func NewGitSubmoduleResolver(submodule gitdomain.Submodule) *gitSubmoduleResolver { + return &gitSubmoduleResolver{submodule: submodule} +} + +func (r *gitSubmoduleResolver) URL() string { + return r.submodule.URL +} + +func (r *gitSubmoduleResolver) Commit() string { + return string(r.submodule.CommitID) +} + +func (r *gitSubmoduleResolver) Path() string { + return r.submodule.Path +} diff --git a/internal/codeintel/sharedresolvers/iface.go b/internal/codeintel/sharedresolvers/iface.go new file mode 100644 index 00000000000..769e6260e6c --- /dev/null +++ b/internal/codeintel/sharedresolvers/iface.go @@ -0,0 +1,40 @@ +package sharedresolvers + +import ( + "context" + "time" + + "github.com/sourcegraph/sourcegraph/internal/api" + autoindexingShared "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + uploadsShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/database" + "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" +) + +type AutoIndexingService interface { + GetIndexes(ctx context.Context, opts types.GetIndexesOptions) (_ []types.Index, _ int, err error) + GetIndexByID(ctx context.Context, id int) (_ types.Index, _ bool, err error) + GetIndexesByIDs(ctx context.Context, ids ...int) (_ []types.Index, err error) + GetUnsafeDB() database.DB + GetListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) (_ []*gitdomain.Tag, err error) +} + +type UploadsService interface { + GetUploads(ctx context.Context, opts types.GetUploadsOptions) (uploads []types.Upload, totalCount int, err error) + GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []types.UploadLog, err error) + GetListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) (_ []*gitdomain.Tag, err error) + GetUploadDocumentsForPath(ctx context.Context, bundleID int, pathPattern string) ([]string, int, error) + GetUploadsByIDs(ctx context.Context, ids ...int) (_ []types.Upload, err error) +} + +type PolicyService interface { + GetRetentionPolicyOverview(ctx context.Context, upload types.Upload, matchesOnly bool, first int, after int64, query string, now time.Time) (matches []types.RetentionPolicyMatchCandidate, totalCount int, err error) +} + +type RepositorySummary struct { + RecentUploads []uploadsShared.UploadsWithRepositoryNamespace + RecentIndexes []autoindexingShared.IndexesWithRepositoryNamespace + LastUploadRetentionScan *time.Time + LastIndexScan *time.Time +} diff --git a/internal/codeintel/sharedresolvers/index_resolver_connection.go b/internal/codeintel/sharedresolvers/index_resolver_connection.go new file mode 100644 index 00000000000..98731c87f81 --- /dev/null +++ b/internal/codeintel/sharedresolvers/index_resolver_connection.go @@ -0,0 +1,68 @@ +package sharedresolvers + +import ( + "context" + + "github.com/opentracing/opentracing-go/log" + + "github.com/sourcegraph/sourcegraph/internal/observation" +) + +type LSIFIndexConnectionResolver interface { + Nodes(ctx context.Context) ([]LSIFIndexResolver, error) + TotalCount(ctx context.Context) (*int32, error) + PageInfo(ctx context.Context) (*PageInfo, error) +} + +type IndexConnectionResolver struct { + uploadsSvc UploadsService + autoindexingSvc AutoIndexingService + policySvc PolicyService + indexesResolver *IndexesResolver + prefetcher *Prefetcher + locationResolver *CachedLocationResolver + errTracer *observation.ErrCollector +} + +func NewIndexConnectionResolver(autoindexingSvc AutoIndexingService, uploadsSvc UploadsService, policySvc PolicyService, indexesResolver *IndexesResolver, prefetcher *Prefetcher, errTracer *observation.ErrCollector) LSIFIndexConnectionResolver { + return &IndexConnectionResolver{ + uploadsSvc: uploadsSvc, + autoindexingSvc: autoindexingSvc, + policySvc: policySvc, + indexesResolver: indexesResolver, + prefetcher: prefetcher, + locationResolver: NewCachedLocationResolver(autoindexingSvc.GetUnsafeDB()), + errTracer: errTracer, + } +} + +func (r *IndexConnectionResolver) Nodes(ctx context.Context) ([]LSIFIndexResolver, error) { + if err := r.indexesResolver.Resolve(ctx); err != nil { + return nil, err + } + + resolvers := make([]LSIFIndexResolver, 0, len(r.indexesResolver.Indexes)) + for i := range r.indexesResolver.Indexes { + // index := convertSharedIndexToDBStoreIndex(r.indexesResolver.Indexes[i]) + resolvers = append(resolvers, NewIndexResolver(r.autoindexingSvc, r.uploadsSvc, r.policySvc, r.indexesResolver.Indexes[i], r.prefetcher, r.errTracer)) + } + return resolvers, nil +} + +func (r *IndexConnectionResolver) TotalCount(ctx context.Context) (_ *int32, err error) { + defer r.errTracer.Collect(&err, log.String("indexConnectionResolver.field", "totalCount")) + + if err := r.indexesResolver.Resolve(ctx); err != nil { + return nil, err + } + return toInt32(&r.indexesResolver.TotalCount), nil +} + +func (r *IndexConnectionResolver) PageInfo(ctx context.Context) (_ *PageInfo, err error) { + defer r.errTracer.Collect(&err, log.String("indexConnectionResolver.field", "pageInfo")) + + if err := r.indexesResolver.Resolve(ctx); err != nil { + return nil, err + } + return EncodeIntCursor(toInt32(r.indexesResolver.NextOffset)), nil +} diff --git a/internal/codeintel/sharedresolvers/index_resolvers.go b/internal/codeintel/sharedresolvers/index_resolvers.go new file mode 100644 index 00000000000..f05a3936d49 --- /dev/null +++ b/internal/codeintel/sharedresolvers/index_resolvers.go @@ -0,0 +1,127 @@ +package sharedresolvers + +import ( + "context" + "strings" + + "github.com/graph-gophers/graphql-go" + "github.com/opentracing/opentracing-go/log" + + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/observation" +) + +type LSIFIndexResolver interface { + ID() graphql.ID + InputCommit() string + Tags(ctx context.Context) ([]string, error) + InputRoot() string + InputIndexer() string + Indexer() types.CodeIntelIndexerResolver + QueuedAt() DateTime + State() string + Failure() *string + StartedAt() *DateTime + FinishedAt() *DateTime + Steps() IndexStepsResolver + PlaceInQueue() *int32 + AssociatedUpload(ctx context.Context) (LSIFUploadResolver, error) + ProjectRoot(ctx context.Context) (*GitTreeEntryResolver, error) +} + +type indexResolver struct { + autoindexingSvc AutoIndexingService + uploadsSvc UploadsService + policySvc PolicyService + index types.Index + prefetcher *Prefetcher + locationResolver *CachedLocationResolver + traceErrs *observation.ErrCollector +} + +func NewIndexResolver(autoindexingSvc AutoIndexingService, uploadsSvc UploadsService, policySvc PolicyService, index types.Index, prefetcher *Prefetcher, errTrace *observation.ErrCollector) LSIFIndexResolver { + if index.AssociatedUploadID != nil { + // Request the next batch of upload fetches to contain the record's associated + // upload id, if one exists it exists. This allows the prefetcher.GetUploadByID + // invocation in the AssociatedUpload method to batch its work with sibling + // resolvers, which share the same prefetcher instance. + prefetcher.MarkUpload(*index.AssociatedUploadID) + } + + return &indexResolver{ + autoindexingSvc: autoindexingSvc, + uploadsSvc: uploadsSvc, + policySvc: policySvc, + index: index, + prefetcher: prefetcher, + locationResolver: NewCachedLocationResolver(autoindexingSvc.GetUnsafeDB()), + traceErrs: errTrace, + } +} + +func (r *indexResolver) ID() graphql.ID { return marshalLSIFIndexGQLID(int64(r.index.ID)) } +func (r *indexResolver) InputCommit() string { return r.index.Commit } +func (r *indexResolver) InputRoot() string { return r.index.Root } +func (r *indexResolver) InputIndexer() string { return r.index.Indexer } +func (r *indexResolver) QueuedAt() DateTime { return DateTime{Time: r.index.QueuedAt} } +func (r *indexResolver) Failure() *string { return r.index.FailureMessage } +func (r *indexResolver) StartedAt() *DateTime { return DateTimeOrNil(r.index.StartedAt) } +func (r *indexResolver) FinishedAt() *DateTime { return DateTimeOrNil(r.index.FinishedAt) } +func (r *indexResolver) Steps() IndexStepsResolver { + return NewIndexStepsResolver(r.autoindexingSvc, r.index) +} +func (r *indexResolver) PlaceInQueue() *int32 { return toInt32(r.index.Rank) } + +func (r *indexResolver) Tags(ctx context.Context) (tagsNames []string, err error) { + tags, err := r.autoindexingSvc.GetListTags(ctx, api.RepoName(r.index.RepositoryName), r.index.Commit) + if err != nil { + return nil, err + } + for _, tag := range tags { + tagsNames = append(tagsNames, tag.Name) + } + return +} + +func (r *indexResolver) State() string { + state := strings.ToUpper(r.index.State) + if state == "FAILED" { + state = "ERRORED" + } + + return state +} + +func (r *indexResolver) AssociatedUpload(ctx context.Context) (_ LSIFUploadResolver, err error) { + if r.index.AssociatedUploadID == nil { + return nil, nil + } + + defer r.traceErrs.Collect(&err, + log.String("indexResolver.field", "associatedUpload"), + log.Int("associatedUpload", *r.index.AssociatedUploadID), + ) + + upload, exists, err := r.prefetcher.GetUploadByID(ctx, *r.index.AssociatedUploadID) + if err != nil || !exists { + return nil, err + } + + return NewUploadResolver(r.uploadsSvc, r.autoindexingSvc, r.policySvc, upload, r.prefetcher, r.traceErrs), nil +} + +func (r *indexResolver) ProjectRoot(ctx context.Context) (_ *GitTreeEntryResolver, err error) { + defer r.traceErrs.Collect(&err, log.String("indexResolver.field", "projectRoot")) + + return r.locationResolver.Path(ctx, api.RepoID(r.index.RepositoryID), r.index.Commit, r.index.Root) +} + +func (r *indexResolver) Indexer() types.CodeIntelIndexerResolver { + // drop the tag if it exists + if idx, ok := types.ImageToIndexer[strings.Split(r.index.Indexer, ":")[0]]; ok { + return idx + } + + return types.NewCodeIntelIndexerResolver(r.index.Indexer) +} diff --git a/internal/codeintel/sharedresolvers/index_step_pre_resolver.go b/internal/codeintel/sharedresolvers/index_step_pre_resolver.go new file mode 100644 index 00000000000..3cbe29ac56b --- /dev/null +++ b/internal/codeintel/sharedresolvers/index_step_pre_resolver.go @@ -0,0 +1,36 @@ +package sharedresolvers + +import "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + +type PreIndexStepResolver interface { + Root() string + Image() string + Commands() []string + LogEntry() ExecutionLogEntryResolver +} + +type preIndexStepResolver struct { + svc AutoIndexingService + step types.DockerStep + entry *types.ExecutionLogEntry +} + +func NewPreIndexStepResolver(svc AutoIndexingService, step types.DockerStep, entry *types.ExecutionLogEntry) PreIndexStepResolver { + return &preIndexStepResolver{ + svc: svc, + step: step, + entry: entry, + } +} + +func (r *preIndexStepResolver) Root() string { return r.step.Root } +func (r *preIndexStepResolver) Image() string { return r.step.Image } +func (r *preIndexStepResolver) Commands() []string { return r.step.Commands } + +func (r *preIndexStepResolver) LogEntry() ExecutionLogEntryResolver { + if r.entry != nil { + return NewExecutionLogEntryResolver(r.svc, *r.entry) + } + + return nil +} diff --git a/internal/codeintel/sharedresolvers/index_step_resolver.go b/internal/codeintel/sharedresolvers/index_step_resolver.go new file mode 100644 index 00000000000..6322e799e4d --- /dev/null +++ b/internal/codeintel/sharedresolvers/index_step_resolver.go @@ -0,0 +1,34 @@ +package sharedresolvers + +import "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + +type IndexStepResolver interface { + IndexerArgs() []string + Outfile() *string + LogEntry() ExecutionLogEntryResolver +} + +type indexStepResolver struct { + svc AutoIndexingService + index types.Index + entry *types.ExecutionLogEntry +} + +func NewIndexStepResolver(svc AutoIndexingService, index types.Index, entry *types.ExecutionLogEntry) IndexStepResolver { + return &indexStepResolver{ + svc: svc, + index: index, + entry: entry, + } +} + +func (r *indexStepResolver) IndexerArgs() []string { return r.index.IndexerArgs } +func (r *indexStepResolver) Outfile() *string { return strPtr(r.index.Outfile) } + +func (r *indexStepResolver) LogEntry() ExecutionLogEntryResolver { + if r.entry != nil { + return NewExecutionLogEntryResolver(r.svc, *r.entry) + } + + return nil +} diff --git a/internal/codeintel/sharedresolvers/index_steps_resolver.go b/internal/codeintel/sharedresolvers/index_steps_resolver.go new file mode 100644 index 00000000000..1015fc1be13 --- /dev/null +++ b/internal/codeintel/sharedresolvers/index_steps_resolver.go @@ -0,0 +1,93 @@ +package sharedresolvers + +import ( + "fmt" + "strings" + + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" +) + +// indexStepsResolver resolves the steps of an index record. +// +// Index jobs are broken into three parts: +// - pre-index steps; all but the last docker step +// - index step; the last docker step +// - upload step; the only src-cli step +// +// The setup and teardown steps match the executor setup and teardown. +type IndexStepsResolver interface { + Setup() []ExecutionLogEntryResolver + PreIndex() []PreIndexStepResolver + Index() IndexStepResolver + Upload() ExecutionLogEntryResolver + Teardown() []ExecutionLogEntryResolver +} + +type indexStepsResolver struct { + svc AutoIndexingService + index types.Index +} + +func NewIndexStepsResolver(svc AutoIndexingService, index types.Index) IndexStepsResolver { + return &indexStepsResolver{svc: svc, index: index} +} + +func (r *indexStepsResolver) Setup() []ExecutionLogEntryResolver { + return r.executionLogEntryResolversWithPrefix("setup.") +} + +func (r *indexStepsResolver) PreIndex() []PreIndexStepResolver { + var resolvers []PreIndexStepResolver + for i, step := range r.index.DockerSteps { + if entry, ok := r.findExecutionLogEntry(fmt.Sprintf("step.docker.%d", i)); ok { + resolvers = append(resolvers, NewPreIndexStepResolver(r.svc, step, &entry)) + } else { + resolvers = append(resolvers, NewPreIndexStepResolver(r.svc, step, nil)) + } + } + + return resolvers +} + +func (r *indexStepsResolver) Index() IndexStepResolver { + if entry, ok := r.findExecutionLogEntry(fmt.Sprintf("step.docker.%d", len(r.index.DockerSteps))); ok { + return NewIndexStepResolver(r.svc, r.index, &entry) + } + + return NewIndexStepResolver(r.svc, r.index, nil) +} + +func (r *indexStepsResolver) Upload() ExecutionLogEntryResolver { + if entry, ok := r.findExecutionLogEntry("step.src.0"); ok { + return NewExecutionLogEntryResolver(r.svc, entry) + } + + return nil +} + +func (r *indexStepsResolver) Teardown() []ExecutionLogEntryResolver { + return r.executionLogEntryResolversWithPrefix("teardown.") +} + +func (r *indexStepsResolver) findExecutionLogEntry(key string) (types.ExecutionLogEntry, bool) { + for _, entry := range r.index.ExecutionLogs { + if entry.Key == key { + return entry, true + } + } + + return types.ExecutionLogEntry{}, false +} + +func (r *indexStepsResolver) executionLogEntryResolversWithPrefix(prefix string) []ExecutionLogEntryResolver { + var resolvers []ExecutionLogEntryResolver + for _, entry := range r.index.ExecutionLogs { + if !strings.HasPrefix(entry.Key, prefix) { + continue + } + r := NewExecutionLogEntryResolver(r.svc, entry) + resolvers = append(resolvers, r) + } + + return resolvers +} diff --git a/internal/codeintel/sharedresolvers/indexes_repository_namespace_resolver.go b/internal/codeintel/sharedresolvers/indexes_repository_namespace_resolver.go new file mode 100644 index 00000000000..28cafc5375a --- /dev/null +++ b/internal/codeintel/sharedresolvers/indexes_repository_namespace_resolver.go @@ -0,0 +1,43 @@ +package sharedresolvers + +import ( + "strings" + + "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" +) + +type LSIFIndexesWithRepositoryNamespaceResolver interface { + Root() string + Indexer() types.CodeIntelIndexerResolver + Indexes() []LSIFIndexResolver +} + +type lsifIndexesWithRepositoryNamespaceResolver struct { + indexesSummary dbstore.IndexesWithRepositoryNamespace + indexResolvers []LSIFIndexResolver +} + +func NewLSIFIndexesWithRepositoryNamespaceResolver(indexesSummary dbstore.IndexesWithRepositoryNamespace, indexResolvers []LSIFIndexResolver) LSIFIndexesWithRepositoryNamespaceResolver { + return &lsifIndexesWithRepositoryNamespaceResolver{ + indexesSummary: indexesSummary, + indexResolvers: indexResolvers, + } +} + +func (r *lsifIndexesWithRepositoryNamespaceResolver) Root() string { + return r.indexesSummary.Root +} + +func (r *lsifIndexesWithRepositoryNamespaceResolver) Indexer() types.CodeIntelIndexerResolver { + // drop the tag if it exists + if idx, ok := types.ImageToIndexer[strings.Split(r.indexesSummary.Indexer, ":")[0]]; ok { + return idx + } + + return types.NewCodeIntelIndexerResolver(r.indexesSummary.Indexer) +} + +func (r *lsifIndexesWithRepositoryNamespaceResolver) Indexes() []LSIFIndexResolver { + return r.indexResolvers +} diff --git a/internal/codeintel/autoindexing/transport/graphql/indexes_resolver.go b/internal/codeintel/sharedresolvers/indexes_resolver.go similarity index 76% rename from internal/codeintel/autoindexing/transport/graphql/indexes_resolver.go rename to internal/codeintel/sharedresolvers/indexes_resolver.go index 3b3e466e6c4..777e05946a8 100644 --- a/internal/codeintel/autoindexing/transport/graphql/indexes_resolver.go +++ b/internal/codeintel/sharedresolvers/indexes_resolver.go @@ -1,22 +1,21 @@ -package graphql +package sharedresolvers import ( "context" "sync" "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" - "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing" - "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" ) // IndexesResolver wraps store.GetIndexes so that the underlying function can be // invoked lazily and its results memoized. type IndexesResolver struct { - svc *autoindexing.Service - opts shared.GetIndexesOptions + svc AutoIndexingService + opts types.GetIndexesOptions once sync.Once // - Indexes []shared.Index + Indexes []types.Index TotalCount int NextOffset *int err error @@ -24,7 +23,7 @@ type IndexesResolver struct { // NewIndexesResolver creates a new IndexesResolver which wil invoke store.GetIndexes // with the given options. -func NewIndexesResolver(svc *autoindexing.Service, opts shared.GetIndexesOptions) *IndexesResolver { +func NewIndexesResolver(svc AutoIndexingService, opts types.GetIndexesOptions) *IndexesResolver { return &IndexesResolver{svc: svc, opts: opts} } diff --git a/internal/codeintel/sharedresolvers/mocks_temp.go b/internal/codeintel/sharedresolvers/mocks_temp.go new file mode 100644 index 00000000000..d4b7ca22078 --- /dev/null +++ b/internal/codeintel/sharedresolvers/mocks_temp.go @@ -0,0 +1,1379 @@ +// Code generated by go-mockgen 1.3.4; DO NOT EDIT. +// +// This file was generated by running `sg generate` (or `go-mockgen`) at the root of +// this repository. To add additional mocks to this or another package, add a new entry +// to the mockgen.yaml file in the root of this repository. + +package sharedresolvers + +import ( + "context" + "sync" + + api "github.com/sourcegraph/sourcegraph/internal/api" + types "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + database "github.com/sourcegraph/sourcegraph/internal/database" + gitdomain "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" +) + +// MockAutoIndexingService is a mock implementation of the +// AutoIndexingService interface (from the package +// github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers) +// used for unit testing. +type MockAutoIndexingService struct { + // GetIndexByIDFunc is an instance of a mock function object controlling + // the behavior of the method GetIndexByID. + GetIndexByIDFunc *AutoIndexingServiceGetIndexByIDFunc + // GetIndexesFunc is an instance of a mock function object controlling + // the behavior of the method GetIndexes. + GetIndexesFunc *AutoIndexingServiceGetIndexesFunc + // GetIndexesByIDsFunc is an instance of a mock function object + // controlling the behavior of the method GetIndexesByIDs. + GetIndexesByIDsFunc *AutoIndexingServiceGetIndexesByIDsFunc + // GetListTagsFunc is an instance of a mock function object controlling + // the behavior of the method GetListTags. + GetListTagsFunc *AutoIndexingServiceGetListTagsFunc + // GetUnsafeDBFunc is an instance of a mock function object controlling + // the behavior of the method GetUnsafeDB. + GetUnsafeDBFunc *AutoIndexingServiceGetUnsafeDBFunc +} + +// NewMockAutoIndexingService creates a new mock of the AutoIndexingService +// interface. All methods return zero values for all results, unless +// overwritten. +func NewMockAutoIndexingService() *MockAutoIndexingService { + return &MockAutoIndexingService{ + GetIndexByIDFunc: &AutoIndexingServiceGetIndexByIDFunc{ + defaultHook: func(context.Context, int) (r0 types.Index, r1 bool, r2 error) { + return + }, + }, + GetIndexesFunc: &AutoIndexingServiceGetIndexesFunc{ + defaultHook: func(context.Context, types.GetIndexesOptions) (r0 []types.Index, r1 int, r2 error) { + return + }, + }, + GetIndexesByIDsFunc: &AutoIndexingServiceGetIndexesByIDsFunc{ + defaultHook: func(context.Context, ...int) (r0 []types.Index, r1 error) { + return + }, + }, + GetListTagsFunc: &AutoIndexingServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) (r0 []*gitdomain.Tag, r1 error) { + return + }, + }, + GetUnsafeDBFunc: &AutoIndexingServiceGetUnsafeDBFunc{ + defaultHook: func() (r0 database.DB) { + return + }, + }, + } +} + +// NewStrictMockAutoIndexingService creates a new mock of the +// AutoIndexingService interface. All methods panic on invocation, unless +// overwritten. +func NewStrictMockAutoIndexingService() *MockAutoIndexingService { + return &MockAutoIndexingService{ + GetIndexByIDFunc: &AutoIndexingServiceGetIndexByIDFunc{ + defaultHook: func(context.Context, int) (types.Index, bool, error) { + panic("unexpected invocation of MockAutoIndexingService.GetIndexByID") + }, + }, + GetIndexesFunc: &AutoIndexingServiceGetIndexesFunc{ + defaultHook: func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + panic("unexpected invocation of MockAutoIndexingService.GetIndexes") + }, + }, + GetIndexesByIDsFunc: &AutoIndexingServiceGetIndexesByIDsFunc{ + defaultHook: func(context.Context, ...int) ([]types.Index, error) { + panic("unexpected invocation of MockAutoIndexingService.GetIndexesByIDs") + }, + }, + GetListTagsFunc: &AutoIndexingServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + panic("unexpected invocation of MockAutoIndexingService.GetListTags") + }, + }, + GetUnsafeDBFunc: &AutoIndexingServiceGetUnsafeDBFunc{ + defaultHook: func() database.DB { + panic("unexpected invocation of MockAutoIndexingService.GetUnsafeDB") + }, + }, + } +} + +// NewMockAutoIndexingServiceFrom creates a new mock of the +// MockAutoIndexingService interface. All methods delegate to the given +// implementation, unless overwritten. +func NewMockAutoIndexingServiceFrom(i AutoIndexingService) *MockAutoIndexingService { + return &MockAutoIndexingService{ + GetIndexByIDFunc: &AutoIndexingServiceGetIndexByIDFunc{ + defaultHook: i.GetIndexByID, + }, + GetIndexesFunc: &AutoIndexingServiceGetIndexesFunc{ + defaultHook: i.GetIndexes, + }, + GetIndexesByIDsFunc: &AutoIndexingServiceGetIndexesByIDsFunc{ + defaultHook: i.GetIndexesByIDs, + }, + GetListTagsFunc: &AutoIndexingServiceGetListTagsFunc{ + defaultHook: i.GetListTags, + }, + GetUnsafeDBFunc: &AutoIndexingServiceGetUnsafeDBFunc{ + defaultHook: i.GetUnsafeDB, + }, + } +} + +// AutoIndexingServiceGetIndexByIDFunc describes the behavior when the +// GetIndexByID method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetIndexByIDFunc struct { + defaultHook func(context.Context, int) (types.Index, bool, error) + hooks []func(context.Context, int) (types.Index, bool, error) + history []AutoIndexingServiceGetIndexByIDFuncCall + mutex sync.Mutex +} + +// GetIndexByID delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetIndexByID(v0 context.Context, v1 int) (types.Index, bool, error) { + r0, r1, r2 := m.GetIndexByIDFunc.nextHook()(v0, v1) + m.GetIndexByIDFunc.appendCall(AutoIndexingServiceGetIndexByIDFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the GetIndexByID method +// of the parent MockAutoIndexingService instance is invoked and the hook +// queue is empty. +func (f *AutoIndexingServiceGetIndexByIDFunc) SetDefaultHook(hook func(context.Context, int) (types.Index, bool, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetIndexByID method of the parent MockAutoIndexingService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *AutoIndexingServiceGetIndexByIDFunc) PushHook(hook func(context.Context, int) (types.Index, bool, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetIndexByIDFunc) SetDefaultReturn(r0 types.Index, r1 bool, r2 error) { + f.SetDefaultHook(func(context.Context, int) (types.Index, bool, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetIndexByIDFunc) PushReturn(r0 types.Index, r1 bool, r2 error) { + f.PushHook(func(context.Context, int) (types.Index, bool, error) { + return r0, r1, r2 + }) +} + +func (f *AutoIndexingServiceGetIndexByIDFunc) nextHook() func(context.Context, int) (types.Index, bool, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetIndexByIDFunc) appendCall(r0 AutoIndexingServiceGetIndexByIDFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetIndexByIDFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetIndexByIDFunc) History() []AutoIndexingServiceGetIndexByIDFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetIndexByIDFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetIndexByIDFuncCall is an object that describes an +// invocation of method GetIndexByID on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetIndexByIDFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 types.Index + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 bool + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetIndexByIDFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetIndexByIDFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// AutoIndexingServiceGetIndexesFunc describes the behavior when the +// GetIndexes method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetIndexesFunc struct { + defaultHook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) + hooks []func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) + history []AutoIndexingServiceGetIndexesFuncCall + mutex sync.Mutex +} + +// GetIndexes delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetIndexes(v0 context.Context, v1 types.GetIndexesOptions) ([]types.Index, int, error) { + r0, r1, r2 := m.GetIndexesFunc.nextHook()(v0, v1) + m.GetIndexesFunc.appendCall(AutoIndexingServiceGetIndexesFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the GetIndexes method of +// the parent MockAutoIndexingService instance is invoked and the hook queue +// is empty. +func (f *AutoIndexingServiceGetIndexesFunc) SetDefaultHook(hook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetIndexes method of the parent MockAutoIndexingService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *AutoIndexingServiceGetIndexesFunc) PushHook(hook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetIndexesFunc) SetDefaultReturn(r0 []types.Index, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetIndexesFunc) PushReturn(r0 []types.Index, r1 int, r2 error) { + f.PushHook(func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + return r0, r1, r2 + }) +} + +func (f *AutoIndexingServiceGetIndexesFunc) nextHook() func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetIndexesFunc) appendCall(r0 AutoIndexingServiceGetIndexesFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetIndexesFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetIndexesFunc) History() []AutoIndexingServiceGetIndexesFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetIndexesFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetIndexesFuncCall is an object that describes an +// invocation of method GetIndexes on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetIndexesFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 types.GetIndexesOptions + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Index + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetIndexesFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetIndexesFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// AutoIndexingServiceGetIndexesByIDsFunc describes the behavior when the +// GetIndexesByIDs method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetIndexesByIDsFunc struct { + defaultHook func(context.Context, ...int) ([]types.Index, error) + hooks []func(context.Context, ...int) ([]types.Index, error) + history []AutoIndexingServiceGetIndexesByIDsFuncCall + mutex sync.Mutex +} + +// GetIndexesByIDs delegates to the next hook function in the queue and +// stores the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetIndexesByIDs(v0 context.Context, v1 ...int) ([]types.Index, error) { + r0, r1 := m.GetIndexesByIDsFunc.nextHook()(v0, v1...) + m.GetIndexesByIDsFunc.appendCall(AutoIndexingServiceGetIndexesByIDsFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetIndexesByIDs +// method of the parent MockAutoIndexingService instance is invoked and the +// hook queue is empty. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]types.Index, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetIndexesByIDs method of the parent MockAutoIndexingService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) PushHook(hook func(context.Context, ...int) ([]types.Index, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) SetDefaultReturn(r0 []types.Index, r1 error) { + f.SetDefaultHook(func(context.Context, ...int) ([]types.Index, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) PushReturn(r0 []types.Index, r1 error) { + f.PushHook(func(context.Context, ...int) ([]types.Index, error) { + return r0, r1 + }) +} + +func (f *AutoIndexingServiceGetIndexesByIDsFunc) nextHook() func(context.Context, ...int) ([]types.Index, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetIndexesByIDsFunc) appendCall(r0 AutoIndexingServiceGetIndexesByIDsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetIndexesByIDsFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) History() []AutoIndexingServiceGetIndexesByIDsFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetIndexesByIDsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetIndexesByIDsFuncCall is an object that describes an +// invocation of method GetIndexesByIDs on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetIndexesByIDsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg1 []int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Index + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c AutoIndexingServiceGetIndexesByIDsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg1 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetIndexesByIDsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// AutoIndexingServiceGetListTagsFunc describes the behavior when the +// GetListTags method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetListTagsFunc struct { + defaultHook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + hooks []func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + history []AutoIndexingServiceGetListTagsFuncCall + mutex sync.Mutex +} + +// GetListTags delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetListTags(v0 context.Context, v1 api.RepoName, v2 ...string) ([]*gitdomain.Tag, error) { + r0, r1 := m.GetListTagsFunc.nextHook()(v0, v1, v2...) + m.GetListTagsFunc.appendCall(AutoIndexingServiceGetListTagsFuncCall{v0, v1, v2, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetListTags method +// of the parent MockAutoIndexingService instance is invoked and the hook +// queue is empty. +func (f *AutoIndexingServiceGetListTagsFunc) SetDefaultHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetListTags method of the parent MockAutoIndexingService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *AutoIndexingServiceGetListTagsFunc) PushHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetListTagsFunc) SetDefaultReturn(r0 []*gitdomain.Tag, r1 error) { + f.SetDefaultHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetListTagsFunc) PushReturn(r0 []*gitdomain.Tag, r1 error) { + f.PushHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +func (f *AutoIndexingServiceGetListTagsFunc) nextHook() func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetListTagsFunc) appendCall(r0 AutoIndexingServiceGetListTagsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetListTagsFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetListTagsFunc) History() []AutoIndexingServiceGetListTagsFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetListTagsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetListTagsFuncCall is an object that describes an +// invocation of method GetListTags on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetListTagsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 api.RepoName + // Arg2 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg2 []string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []*gitdomain.Tag + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c AutoIndexingServiceGetListTagsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg2 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0, c.Arg1}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetListTagsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// AutoIndexingServiceGetUnsafeDBFunc describes the behavior when the +// GetUnsafeDB method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetUnsafeDBFunc struct { + defaultHook func() database.DB + hooks []func() database.DB + history []AutoIndexingServiceGetUnsafeDBFuncCall + mutex sync.Mutex +} + +// GetUnsafeDB delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetUnsafeDB() database.DB { + r0 := m.GetUnsafeDBFunc.nextHook()() + m.GetUnsafeDBFunc.appendCall(AutoIndexingServiceGetUnsafeDBFuncCall{r0}) + return r0 +} + +// SetDefaultHook sets function that is called when the GetUnsafeDB method +// of the parent MockAutoIndexingService instance is invoked and the hook +// queue is empty. +func (f *AutoIndexingServiceGetUnsafeDBFunc) SetDefaultHook(hook func() database.DB) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUnsafeDB method of the parent MockAutoIndexingService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *AutoIndexingServiceGetUnsafeDBFunc) PushHook(hook func() database.DB) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetUnsafeDBFunc) SetDefaultReturn(r0 database.DB) { + f.SetDefaultHook(func() database.DB { + return r0 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetUnsafeDBFunc) PushReturn(r0 database.DB) { + f.PushHook(func() database.DB { + return r0 + }) +} + +func (f *AutoIndexingServiceGetUnsafeDBFunc) nextHook() func() database.DB { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetUnsafeDBFunc) appendCall(r0 AutoIndexingServiceGetUnsafeDBFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetUnsafeDBFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetUnsafeDBFunc) History() []AutoIndexingServiceGetUnsafeDBFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetUnsafeDBFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetUnsafeDBFuncCall is an object that describes an +// invocation of method GetUnsafeDB on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetUnsafeDBFuncCall struct { + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 database.DB +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetUnsafeDBFuncCall) Args() []interface{} { + return []interface{}{} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetUnsafeDBFuncCall) Results() []interface{} { + return []interface{}{c.Result0} +} + +// MockUploadsService is a mock implementation of the UploadsService +// interface (from the package +// github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers) +// used for unit testing. +type MockUploadsService struct { + // GetAuditLogsForUploadFunc is an instance of a mock function object + // controlling the behavior of the method GetAuditLogsForUpload. + GetAuditLogsForUploadFunc *UploadsServiceGetAuditLogsForUploadFunc + // GetListTagsFunc is an instance of a mock function object controlling + // the behavior of the method GetListTags. + GetListTagsFunc *UploadsServiceGetListTagsFunc + // GetUploadDocumentsForPathFunc is an instance of a mock function + // object controlling the behavior of the method + // GetUploadDocumentsForPath. + GetUploadDocumentsForPathFunc *UploadsServiceGetUploadDocumentsForPathFunc + // GetUploadsFunc is an instance of a mock function object controlling + // the behavior of the method GetUploads. + GetUploadsFunc *UploadsServiceGetUploadsFunc + // GetUploadsByIDsFunc is an instance of a mock function object + // controlling the behavior of the method GetUploadsByIDs. + GetUploadsByIDsFunc *UploadsServiceGetUploadsByIDsFunc +} + +// NewMockUploadsService creates a new mock of the UploadsService interface. +// All methods return zero values for all results, unless overwritten. +func NewMockUploadsService() *MockUploadsService { + return &MockUploadsService{ + GetAuditLogsForUploadFunc: &UploadsServiceGetAuditLogsForUploadFunc{ + defaultHook: func(context.Context, int) (r0 []types.UploadLog, r1 error) { + return + }, + }, + GetListTagsFunc: &UploadsServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) (r0 []*gitdomain.Tag, r1 error) { + return + }, + }, + GetUploadDocumentsForPathFunc: &UploadsServiceGetUploadDocumentsForPathFunc{ + defaultHook: func(context.Context, int, string) (r0 []string, r1 int, r2 error) { + return + }, + }, + GetUploadsFunc: &UploadsServiceGetUploadsFunc{ + defaultHook: func(context.Context, types.GetUploadsOptions) (r0 []types.Upload, r1 int, r2 error) { + return + }, + }, + GetUploadsByIDsFunc: &UploadsServiceGetUploadsByIDsFunc{ + defaultHook: func(context.Context, ...int) (r0 []types.Upload, r1 error) { + return + }, + }, + } +} + +// NewStrictMockUploadsService creates a new mock of the UploadsService +// interface. All methods panic on invocation, unless overwritten. +func NewStrictMockUploadsService() *MockUploadsService { + return &MockUploadsService{ + GetAuditLogsForUploadFunc: &UploadsServiceGetAuditLogsForUploadFunc{ + defaultHook: func(context.Context, int) ([]types.UploadLog, error) { + panic("unexpected invocation of MockUploadsService.GetAuditLogsForUpload") + }, + }, + GetListTagsFunc: &UploadsServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + panic("unexpected invocation of MockUploadsService.GetListTags") + }, + }, + GetUploadDocumentsForPathFunc: &UploadsServiceGetUploadDocumentsForPathFunc{ + defaultHook: func(context.Context, int, string) ([]string, int, error) { + panic("unexpected invocation of MockUploadsService.GetUploadDocumentsForPath") + }, + }, + GetUploadsFunc: &UploadsServiceGetUploadsFunc{ + defaultHook: func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + panic("unexpected invocation of MockUploadsService.GetUploads") + }, + }, + GetUploadsByIDsFunc: &UploadsServiceGetUploadsByIDsFunc{ + defaultHook: func(context.Context, ...int) ([]types.Upload, error) { + panic("unexpected invocation of MockUploadsService.GetUploadsByIDs") + }, + }, + } +} + +// NewMockUploadsServiceFrom creates a new mock of the MockUploadsService +// interface. All methods delegate to the given implementation, unless +// overwritten. +func NewMockUploadsServiceFrom(i UploadsService) *MockUploadsService { + return &MockUploadsService{ + GetAuditLogsForUploadFunc: &UploadsServiceGetAuditLogsForUploadFunc{ + defaultHook: i.GetAuditLogsForUpload, + }, + GetListTagsFunc: &UploadsServiceGetListTagsFunc{ + defaultHook: i.GetListTags, + }, + GetUploadDocumentsForPathFunc: &UploadsServiceGetUploadDocumentsForPathFunc{ + defaultHook: i.GetUploadDocumentsForPath, + }, + GetUploadsFunc: &UploadsServiceGetUploadsFunc{ + defaultHook: i.GetUploads, + }, + GetUploadsByIDsFunc: &UploadsServiceGetUploadsByIDsFunc{ + defaultHook: i.GetUploadsByIDs, + }, + } +} + +// UploadsServiceGetAuditLogsForUploadFunc describes the behavior when the +// GetAuditLogsForUpload method of the parent MockUploadsService instance is +// invoked. +type UploadsServiceGetAuditLogsForUploadFunc struct { + defaultHook func(context.Context, int) ([]types.UploadLog, error) + hooks []func(context.Context, int) ([]types.UploadLog, error) + history []UploadsServiceGetAuditLogsForUploadFuncCall + mutex sync.Mutex +} + +// GetAuditLogsForUpload delegates to the next hook function in the queue +// and stores the parameter and result values of this invocation. +func (m *MockUploadsService) GetAuditLogsForUpload(v0 context.Context, v1 int) ([]types.UploadLog, error) { + r0, r1 := m.GetAuditLogsForUploadFunc.nextHook()(v0, v1) + m.GetAuditLogsForUploadFunc.appendCall(UploadsServiceGetAuditLogsForUploadFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the +// GetAuditLogsForUpload method of the parent MockUploadsService instance is +// invoked and the hook queue is empty. +func (f *UploadsServiceGetAuditLogsForUploadFunc) SetDefaultHook(hook func(context.Context, int) ([]types.UploadLog, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetAuditLogsForUpload method of the parent MockUploadsService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *UploadsServiceGetAuditLogsForUploadFunc) PushHook(hook func(context.Context, int) ([]types.UploadLog, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetAuditLogsForUploadFunc) SetDefaultReturn(r0 []types.UploadLog, r1 error) { + f.SetDefaultHook(func(context.Context, int) ([]types.UploadLog, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetAuditLogsForUploadFunc) PushReturn(r0 []types.UploadLog, r1 error) { + f.PushHook(func(context.Context, int) ([]types.UploadLog, error) { + return r0, r1 + }) +} + +func (f *UploadsServiceGetAuditLogsForUploadFunc) nextHook() func(context.Context, int) ([]types.UploadLog, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetAuditLogsForUploadFunc) appendCall(r0 UploadsServiceGetAuditLogsForUploadFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadsServiceGetAuditLogsForUploadFuncCall +// objects describing the invocations of this function. +func (f *UploadsServiceGetAuditLogsForUploadFunc) History() []UploadsServiceGetAuditLogsForUploadFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetAuditLogsForUploadFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetAuditLogsForUploadFuncCall is an object that describes +// an invocation of method GetAuditLogsForUpload on an instance of +// MockUploadsService. +type UploadsServiceGetAuditLogsForUploadFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.UploadLog + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadsServiceGetAuditLogsForUploadFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetAuditLogsForUploadFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// UploadsServiceGetListTagsFunc describes the behavior when the GetListTags +// method of the parent MockUploadsService instance is invoked. +type UploadsServiceGetListTagsFunc struct { + defaultHook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + hooks []func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + history []UploadsServiceGetListTagsFuncCall + mutex sync.Mutex +} + +// GetListTags delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockUploadsService) GetListTags(v0 context.Context, v1 api.RepoName, v2 ...string) ([]*gitdomain.Tag, error) { + r0, r1 := m.GetListTagsFunc.nextHook()(v0, v1, v2...) + m.GetListTagsFunc.appendCall(UploadsServiceGetListTagsFuncCall{v0, v1, v2, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetListTags method +// of the parent MockUploadsService instance is invoked and the hook queue +// is empty. +func (f *UploadsServiceGetListTagsFunc) SetDefaultHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetListTags method of the parent MockUploadsService instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *UploadsServiceGetListTagsFunc) PushHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetListTagsFunc) SetDefaultReturn(r0 []*gitdomain.Tag, r1 error) { + f.SetDefaultHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetListTagsFunc) PushReturn(r0 []*gitdomain.Tag, r1 error) { + f.PushHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +func (f *UploadsServiceGetListTagsFunc) nextHook() func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetListTagsFunc) appendCall(r0 UploadsServiceGetListTagsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadsServiceGetListTagsFuncCall objects +// describing the invocations of this function. +func (f *UploadsServiceGetListTagsFunc) History() []UploadsServiceGetListTagsFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetListTagsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetListTagsFuncCall is an object that describes an +// invocation of method GetListTags on an instance of MockUploadsService. +type UploadsServiceGetListTagsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 api.RepoName + // Arg2 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg2 []string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []*gitdomain.Tag + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c UploadsServiceGetListTagsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg2 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0, c.Arg1}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetListTagsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// UploadsServiceGetUploadDocumentsForPathFunc describes the behavior when +// the GetUploadDocumentsForPath method of the parent MockUploadsService +// instance is invoked. +type UploadsServiceGetUploadDocumentsForPathFunc struct { + defaultHook func(context.Context, int, string) ([]string, int, error) + hooks []func(context.Context, int, string) ([]string, int, error) + history []UploadsServiceGetUploadDocumentsForPathFuncCall + mutex sync.Mutex +} + +// GetUploadDocumentsForPath delegates to the next hook function in the +// queue and stores the parameter and result values of this invocation. +func (m *MockUploadsService) GetUploadDocumentsForPath(v0 context.Context, v1 int, v2 string) ([]string, int, error) { + r0, r1, r2 := m.GetUploadDocumentsForPathFunc.nextHook()(v0, v1, v2) + m.GetUploadDocumentsForPathFunc.appendCall(UploadsServiceGetUploadDocumentsForPathFuncCall{v0, v1, v2, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the +// GetUploadDocumentsForPath method of the parent MockUploadsService +// instance is invoked and the hook queue is empty. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) SetDefaultHook(hook func(context.Context, int, string) ([]string, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUploadDocumentsForPath method of the parent MockUploadsService +// instance invokes the hook at the front of the queue and discards it. +// After the queue is empty, the default hook function is invoked for any +// future action. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) PushHook(hook func(context.Context, int, string) ([]string, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) SetDefaultReturn(r0 []string, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, int, string) ([]string, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) PushReturn(r0 []string, r1 int, r2 error) { + f.PushHook(func(context.Context, int, string) ([]string, int, error) { + return r0, r1, r2 + }) +} + +func (f *UploadsServiceGetUploadDocumentsForPathFunc) nextHook() func(context.Context, int, string) ([]string, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetUploadDocumentsForPathFunc) appendCall(r0 UploadsServiceGetUploadDocumentsForPathFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// UploadsServiceGetUploadDocumentsForPathFuncCall objects describing the +// invocations of this function. +func (f *UploadsServiceGetUploadDocumentsForPathFunc) History() []UploadsServiceGetUploadDocumentsForPathFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetUploadDocumentsForPathFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetUploadDocumentsForPathFuncCall is an object that +// describes an invocation of method GetUploadDocumentsForPath on an +// instance of MockUploadsService. +type UploadsServiceGetUploadDocumentsForPathFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []string + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadsServiceGetUploadDocumentsForPathFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetUploadDocumentsForPathFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// UploadsServiceGetUploadsFunc describes the behavior when the GetUploads +// method of the parent MockUploadsService instance is invoked. +type UploadsServiceGetUploadsFunc struct { + defaultHook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) + hooks []func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) + history []UploadsServiceGetUploadsFuncCall + mutex sync.Mutex +} + +// GetUploads delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockUploadsService) GetUploads(v0 context.Context, v1 types.GetUploadsOptions) ([]types.Upload, int, error) { + r0, r1, r2 := m.GetUploadsFunc.nextHook()(v0, v1) + m.GetUploadsFunc.appendCall(UploadsServiceGetUploadsFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the GetUploads method of +// the parent MockUploadsService instance is invoked and the hook queue is +// empty. +func (f *UploadsServiceGetUploadsFunc) SetDefaultHook(hook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUploads method of the parent MockUploadsService instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *UploadsServiceGetUploadsFunc) PushHook(hook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetUploadsFunc) SetDefaultReturn(r0 []types.Upload, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetUploadsFunc) PushReturn(r0 []types.Upload, r1 int, r2 error) { + f.PushHook(func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + return r0, r1, r2 + }) +} + +func (f *UploadsServiceGetUploadsFunc) nextHook() func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetUploadsFunc) appendCall(r0 UploadsServiceGetUploadsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadsServiceGetUploadsFuncCall objects +// describing the invocations of this function. +func (f *UploadsServiceGetUploadsFunc) History() []UploadsServiceGetUploadsFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetUploadsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetUploadsFuncCall is an object that describes an +// invocation of method GetUploads on an instance of MockUploadsService. +type UploadsServiceGetUploadsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 types.GetUploadsOptions + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Upload + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadsServiceGetUploadsFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetUploadsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// UploadsServiceGetUploadsByIDsFunc describes the behavior when the +// GetUploadsByIDs method of the parent MockUploadsService instance is +// invoked. +type UploadsServiceGetUploadsByIDsFunc struct { + defaultHook func(context.Context, ...int) ([]types.Upload, error) + hooks []func(context.Context, ...int) ([]types.Upload, error) + history []UploadsServiceGetUploadsByIDsFuncCall + mutex sync.Mutex +} + +// GetUploadsByIDs delegates to the next hook function in the queue and +// stores the parameter and result values of this invocation. +func (m *MockUploadsService) GetUploadsByIDs(v0 context.Context, v1 ...int) ([]types.Upload, error) { + r0, r1 := m.GetUploadsByIDsFunc.nextHook()(v0, v1...) + m.GetUploadsByIDsFunc.appendCall(UploadsServiceGetUploadsByIDsFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetUploadsByIDs +// method of the parent MockUploadsService instance is invoked and the hook +// queue is empty. +func (f *UploadsServiceGetUploadsByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]types.Upload, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUploadsByIDs method of the parent MockUploadsService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *UploadsServiceGetUploadsByIDsFunc) PushHook(hook func(context.Context, ...int) ([]types.Upload, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadsServiceGetUploadsByIDsFunc) SetDefaultReturn(r0 []types.Upload, r1 error) { + f.SetDefaultHook(func(context.Context, ...int) ([]types.Upload, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadsServiceGetUploadsByIDsFunc) PushReturn(r0 []types.Upload, r1 error) { + f.PushHook(func(context.Context, ...int) ([]types.Upload, error) { + return r0, r1 + }) +} + +func (f *UploadsServiceGetUploadsByIDsFunc) nextHook() func(context.Context, ...int) ([]types.Upload, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadsServiceGetUploadsByIDsFunc) appendCall(r0 UploadsServiceGetUploadsByIDsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadsServiceGetUploadsByIDsFuncCall +// objects describing the invocations of this function. +func (f *UploadsServiceGetUploadsByIDsFunc) History() []UploadsServiceGetUploadsByIDsFuncCall { + f.mutex.Lock() + history := make([]UploadsServiceGetUploadsByIDsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadsServiceGetUploadsByIDsFuncCall is an object that describes an +// invocation of method GetUploadsByIDs on an instance of +// MockUploadsService. +type UploadsServiceGetUploadsByIDsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg1 []int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Upload + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c UploadsServiceGetUploadsByIDsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg1 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadsServiceGetUploadsByIDsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/prefetcher.go b/internal/codeintel/sharedresolvers/prefetcher.go similarity index 77% rename from enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/prefetcher.go rename to internal/codeintel/sharedresolvers/prefetcher.go index 85c2abac637..bf22039cd3d 100644 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/prefetcher.go +++ b/internal/codeintel/sharedresolvers/prefetcher.go @@ -1,12 +1,11 @@ -package graphql +package sharedresolvers import ( "context" "sort" "sync" - "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers" - store "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" ) // Prefetcher is a batch query utility and cache used to reduce the amount of database @@ -15,19 +14,21 @@ import ( // well as index records resulting from an upload resolver (and vice versa). type Prefetcher struct { sync.RWMutex - resolver resolvers.Resolver - uploadIDs []int - indexIDs []int - uploadCache map[int]store.Upload - indexCache map[int]store.Index + autoindexingSvc AutoIndexingService + uploadSvc UploadsService + uploadIDs []int + indexIDs []int + uploadCache map[int]types.Upload + indexCache map[int]types.Index } // NewPrefetcher returns a prefetcher with an empty cache. -func NewPrefetcher(resolver resolvers.Resolver) *Prefetcher { +func NewPrefetcher(autoindexingSvc AutoIndexingService, uploadSvc UploadsService) *Prefetcher { return &Prefetcher{ - resolver: resolver, - uploadCache: map[int]store.Upload{}, - indexCache: map[int]store.Index{}, + autoindexingSvc: autoindexingSvc, + uploadSvc: uploadSvc, + uploadCache: map[int]types.Upload{}, + indexCache: map[int]types.Index{}, } } @@ -44,7 +45,7 @@ func (p *Prefetcher) MarkUpload(id int) { // the given identifier will be added to the current batch of identifiers constructed // via calls to MarkUpload. All uploads will in the current batch are requested at once // and the upload with the given identifier is returned from that result set. -func (p *Prefetcher) GetUploadByID(ctx context.Context, id int) (store.Upload, bool, error) { +func (p *Prefetcher) GetUploadByID(ctx context.Context, id int) (types.Upload, bool, error) { p.RLock() upload, ok := p.uploadCache[id] p.RUnlock() @@ -71,12 +72,11 @@ func (p *Prefetcher) GetUploadByID(ctx context.Context, id int) (store.Upload, b } sort.Ints(ids) - u, err := p.resolver.UploadsResolver().GetUploadsByIDs(ctx, ids...) + uploads, err := p.uploadSvc.GetUploadsByIDs(ctx, ids...) if err != nil { - return store.Upload{}, false, err + return types.Upload{}, false, err } - uploads := convertSharedUploadsListToDBStoreUploadsList(u) for _, upload := range uploads { p.uploadCache[upload.ID] = upload } @@ -99,7 +99,7 @@ func (p *Prefetcher) MarkIndex(id int) { // the given identifier will be added to the current batch of identifiers constructed // via calls to MarkIndex. All indexes will in the current batch are requested at once // and the index with the given identifier is returned from that result set. -func (p *Prefetcher) GetIndexByID(ctx context.Context, id int) (store.Index, bool, error) { +func (p *Prefetcher) GetIndexByID(ctx context.Context, id int) (types.Index, bool, error) { p.RLock() index, ok := p.indexCache[id] p.RUnlock() @@ -126,13 +126,12 @@ func (p *Prefetcher) GetIndexByID(ctx context.Context, id int) (store.Index, boo } sort.Ints(ids) - autoindexingResolver := p.resolver.AutoIndexingResolver() - indexes, err := autoindexingResolver.GetIndexesByIDs(ctx, ids...) + indexes, err := p.autoindexingSvc.GetIndexesByIDs(ctx, ids...) if err != nil { - return store.Index{}, false, err + return types.Index{}, false, err } for _, index := range indexes { - p.indexCache[index.ID] = convertSharedIndexToDBStoreIndex(index) + p.indexCache[index.ID] = index } p.indexIDs = nil diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/prefetcher_test.go b/internal/codeintel/sharedresolvers/prefetcher_test.go similarity index 73% rename from enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/prefetcher_test.go rename to internal/codeintel/sharedresolvers/prefetcher_test.go index 1b8b5c05308..5c53801dd9d 100644 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/prefetcher_test.go +++ b/internal/codeintel/sharedresolvers/prefetcher_test.go @@ -1,4 +1,4 @@ -package graphql +package sharedresolvers import ( "context" @@ -6,39 +6,26 @@ import ( "github.com/google/go-cmp/cmp" - resolvermocks "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks" - transportmocks "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport" - uploadtransportmocks "github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/uploads" - "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" - "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - uploadshared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" - "github.com/sourcegraph/sourcegraph/internal/workerutil" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" ) func TestPrefetcherUploads(t *testing.T) { - mockResolver := resolvermocks.NewMockResolver() - prefetcher := NewPrefetcher(mockResolver) + mockAutoIndexingResolver := NewMockAutoIndexingService() + mockUploadResolver := NewMockUploadsService() + prefetcher := NewPrefetcher(mockAutoIndexingResolver, mockUploadResolver) - uploads := map[int]dbstore.Upload{ + uploads := map[int]types.Upload{ 1: {ID: 1}, 2: {ID: 2}, 3: {ID: 3}, 4: {ID: 4}, 5: {ID: 5}, } - sharedUpload := map[int]uploadshared.Upload{ - 1: {ID: 1}, - 2: {ID: 2}, - 3: {ID: 3}, - 4: {ID: 4}, - 5: {ID: 5}, - } - mockUploadResolver := uploadtransportmocks.NewMockResolver() - mockResolver.UploadsResolverFunc.SetDefaultReturn(mockUploadResolver) - mockUploadResolver.GetUploadsByIDsFunc.SetDefaultHook(func(_ context.Context, ids ...int) ([]uploadshared.Upload, error) { - matching := make([]uploadshared.Upload, 0, len(ids)) + + mockUploadResolver.GetUploadsByIDsFunc.SetDefaultHook(func(_ context.Context, ids ...int) ([]types.Upload, error) { + matching := make([]types.Upload, 0, len(ids)) for _, id := range ids { - matching = append(matching, sharedUpload[id]) + matching = append(matching, uploads[id]) } return matching, nil @@ -95,32 +82,28 @@ func TestPrefetcherUploads(t *testing.T) { } func TestPrefetcherIndexes(t *testing.T) { - indexes := map[int]shared.Index{ + indexes := map[int]types.Index{ 1: {ID: 1}, 2: {ID: 2}, 3: {ID: 3}, 4: {ID: 4}, 5: {ID: 5}, } - mockResolver := resolvermocks.NewMockResolver() - mockAutoIndexingResolver := transportmocks.NewMockResolver() - mockAutoIndexingResolver.GetIndexesByIDsFunc.SetDefaultHook(func(_ context.Context, ids ...int) ([]shared.Index, error) { - matching := make([]shared.Index, 0, len(ids)) + + mockAutoIndexingResolver := NewMockAutoIndexingService() + mockAutoIndexingResolver.GetIndexesByIDsFunc.SetDefaultHook(func(_ context.Context, ids ...int) ([]types.Index, error) { + matching := make([]types.Index, 0, len(ids)) for _, id := range ids { matching = append(matching, indexes[id]) } return matching, nil }) - mockResolver.AutoIndexingResolverFunc.PushReturn(mockAutoIndexingResolver) - prefetcher := NewPrefetcher(mockResolver) + mockUploadResolver := NewMockUploadsService() + prefetcher := NewPrefetcher(mockAutoIndexingResolver, mockUploadResolver) // We do a conversion inside the function that I cannot reproduct inside the mock. - expectedIndex := dbstore.Index{ - ID: 1, - DockerSteps: []dbstore.DockerStep{}, - ExecutionLogs: []workerutil.ExecutionLogEntry{}, - } + expectedIndex := types.Index{ID: 1} // Bare fetch if index, exists, err := prefetcher.GetIndexByID(context.Background(), 1); err != nil { @@ -150,15 +133,14 @@ func TestPrefetcherIndexes(t *testing.T) { prefetcher.MarkIndex(4) prefetcher.MarkIndex(6) // unknown id - mockAutoIndexingResolver.GetIndexesByIDsFunc.SetDefaultHook(func(_ context.Context, ids ...int) ([]shared.Index, error) { - matching := make([]shared.Index, 0, len(ids)) + mockAutoIndexingResolver.GetIndexesByIDsFunc.SetDefaultHook(func(_ context.Context, ids ...int) ([]types.Index, error) { + matching := make([]types.Index, 0, len(ids)) for _, id := range ids { matching = append(matching, indexes[id]) } return matching, nil }) - mockResolver.AutoIndexingResolverFunc.PushReturn(mockAutoIndexingResolver) expectedIndex.ID = 2 if index, exists, err := prefetcher.GetIndexByID(context.Background(), 2); err != nil { diff --git a/internal/codeintel/sharedresolvers/repository_resolver.go b/internal/codeintel/sharedresolvers/repository_resolver.go new file mode 100644 index 00000000000..9f7a4023115 --- /dev/null +++ b/internal/codeintel/sharedresolvers/repository_resolver.go @@ -0,0 +1,138 @@ +package sharedresolvers + +import ( + "context" + "net/url" + "sync" + + "github.com/graph-gophers/graphql-go" + "github.com/graph-gophers/graphql-go/relay" + "github.com/sourcegraph/log" + sglog "github.com/sourcegraph/log" + + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/database" + "github.com/sourcegraph/sourcegraph/internal/search/result" + "github.com/sourcegraph/sourcegraph/internal/types" +) + +type CodeIntelRepositoryResolver interface { + ID() graphql.ID + Name() string + URL() string +} + +type RepositoryResolver struct { + logger sglog.Logger + hydration sync.Once + err error + + // Invariant: Name and ID of RepoMatch are always set and safe to use. They are + // used to hydrate the inner repo, and should always be the same as the name and + // id of the inner repo, but referring to the inner repo directly is unsafe + // because it may cause a race during hydration. + result.RepoMatch + + db database.DB + + // innerRepo may only contain ID and Name information. + // To access any other repo information, use repo() instead. + innerRepo *types.Repo +} + +func NewRepositoryResolver(db database.DB, repo *types.Repo) *RepositoryResolver { + // Protect against a nil repo + var name api.RepoName + var id api.RepoID + if repo != nil { + name = repo.Name + id = repo.ID + } + + return &RepositoryResolver{ + db: db, + innerRepo: repo, + RepoMatch: result.RepoMatch{ + ID: id, + Name: name, + }, + logger: log.Scoped("repositoryResolver", "resolve a specific repository"). + With(log.Object("repo", + log.String("name", string(name)), + log.Int32("id", int32(id)))), + } +} + +func (r *RepositoryResolver) ID() graphql.ID { + return relay.MarshalID("Repository", r.RepoMatch.ID) +} + +func (r *RepositoryResolver) Name() string { + return string(r.RepoMatch.Name) +} + +func (r *RepositoryResolver) Type(ctx context.Context) (*types.Repo, error) { + return r.repo(ctx) +} + +type RepositoryCommitArgs struct { + Rev string + InputRevspec *string +} + +func (r *RepositoryResolver) CommitFromID(ctx context.Context, args *RepositoryCommitArgs, commitID api.CommitID) (*GitCommitResolver, error) { + resolver := NewGitCommitResolver(r, commitID) + if args.InputRevspec != nil { + resolver.inputRev = args.InputRevspec + } else { + resolver.inputRev = &args.Rev + } + return resolver, nil +} + +func (r *RepositoryResolver) URL() string { + return r.url().String() +} + +func (r *RepositoryResolver) URI(ctx context.Context) (string, error) { + repo, err := r.repo(ctx) + return repo.URI, err +} + +func (r *RepositoryResolver) url() *url.URL { + path := "/" + string(r.RepoMatch.Name) + if r.Rev != "" { + path += "@" + r.Rev + } + return &url.URL{Path: path} +} + +// repo makes sure the repo is hydrated before returning it. +func (r *RepositoryResolver) repo(ctx context.Context) (*types.Repo, error) { + err := r.hydrate(ctx) + return r.innerRepo, err +} + +func (r *RepositoryResolver) RepoName() api.RepoName { + return r.RepoMatch.Name +} + +func (r *RepositoryResolver) hydrate(ctx context.Context) error { + r.hydration.Do(func() { + // Repositories with an empty creation date were created using RepoName.ToRepo(), + // they only contain ID and name information. + if r.innerRepo != nil && !r.innerRepo.CreatedAt.IsZero() { + return + } + + r.logger.Debug("RepositoryResolver.hydrate", sglog.String("repo.ID", string(r.RepoMatch.ID))) + + var repo *types.Repo + repo, r.err = r.db.Repos().Get(ctx, r.RepoMatch.ID) + if r.err == nil { + r.innerRepo = repo + } + }) + + return r.err +} diff --git a/internal/codeintel/sharedresolvers/retention_policy_matcher_connection.go b/internal/codeintel/sharedresolvers/retention_policy_matcher_connection.go new file mode 100644 index 00000000000..a5e25237359 --- /dev/null +++ b/internal/codeintel/sharedresolvers/retention_policy_matcher_connection.go @@ -0,0 +1,48 @@ +package sharedresolvers + +import ( + "context" + + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/observation" +) + +type CodeIntelligenceRetentionPolicyMatchesConnectionResolver interface { + Nodes(ctx context.Context) ([]CodeIntelligenceRetentionPolicyMatchResolver, error) + TotalCount(ctx context.Context) (*int32, error) + PageInfo(ctx context.Context) (*PageInfo, error) +} + +type codeIntelligenceRetentionPolicyMatcherConnectionResolver struct { + svc AutoIndexingService + policies []types.RetentionPolicyMatchCandidate + totalCount int + errTracer *observation.ErrCollector +} + +func NewCodeIntelligenceRetentionPolicyMatcherConnectionResolver(svc AutoIndexingService, policies []types.RetentionPolicyMatchCandidate, totalCount int, errTracer *observation.ErrCollector) *codeIntelligenceRetentionPolicyMatcherConnectionResolver { + return &codeIntelligenceRetentionPolicyMatcherConnectionResolver{ + svc: svc, + policies: policies, + totalCount: totalCount, + errTracer: errTracer, + } +} + +func (r *codeIntelligenceRetentionPolicyMatcherConnectionResolver) Nodes(ctx context.Context) ([]CodeIntelligenceRetentionPolicyMatchResolver, error) { + resolvers := make([]CodeIntelligenceRetentionPolicyMatchResolver, 0, len(r.policies)) + for _, policy := range r.policies { + resolvers = append(resolvers, NewRetentionPolicyMatcherResolver(r.svc, policy)) + } + + return resolvers, nil +} + +func (r *codeIntelligenceRetentionPolicyMatcherConnectionResolver) TotalCount(ctx context.Context) (*int32, error) { + v := int32(r.totalCount) + return &v, nil +} + +func (r *codeIntelligenceRetentionPolicyMatcherConnectionResolver) PageInfo(ctx context.Context) (*PageInfo, error) { + return HasNextPage(len(r.policies) < r.totalCount), nil +} diff --git a/internal/codeintel/sharedresolvers/retention_policy_matcher_resolver.go b/internal/codeintel/sharedresolvers/retention_policy_matcher_resolver.go new file mode 100644 index 00000000000..dd30d2153ca --- /dev/null +++ b/internal/codeintel/sharedresolvers/retention_policy_matcher_resolver.go @@ -0,0 +1,44 @@ +package sharedresolvers + +import ( + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/observation" +) + +// TODO(@Numbers88s): consolidate reference to these two interfaces +type CodeIntelligenceRetentionPolicyMatchResolver interface { + ConfigurationPolicy() CodeIntelligenceConfigurationPolicyResolver + Matches() bool + ProtectingCommits() *[]string +} + +type RetentionPolicyMatcherResolver interface { + ConfigurationPolicy() CodeIntelligenceConfigurationPolicyResolver + Matches() bool + ProtectingCommits() *[]string +} + +type retentionPolicyMatcherResolver struct { + svc AutoIndexingService + policy types.RetentionPolicyMatchCandidate + errCollector *observation.ErrCollector +} + +func NewRetentionPolicyMatcherResolver(svc AutoIndexingService, policy types.RetentionPolicyMatchCandidate) RetentionPolicyMatcherResolver { + return &retentionPolicyMatcherResolver{svc: svc, policy: policy} +} + +func (r *retentionPolicyMatcherResolver) ConfigurationPolicy() CodeIntelligenceConfigurationPolicyResolver { + if r.policy.ConfigurationPolicy == nil { + return nil + } + return NewConfigurationPolicyResolver(r.svc, *r.policy.ConfigurationPolicy, r.errCollector) +} + +func (r *retentionPolicyMatcherResolver) Matches() bool { + return r.policy.Matched +} + +func (r *retentionPolicyMatcherResolver) ProtectingCommits() *[]string { + return &r.policy.ProtectingCommits +} diff --git a/internal/codeintel/sharedresolvers/summary.go b/internal/codeintel/sharedresolvers/summary.go new file mode 100644 index 00000000000..10f5a1b6146 --- /dev/null +++ b/internal/codeintel/sharedresolvers/summary.go @@ -0,0 +1,70 @@ +package sharedresolvers + +import ( + "github.com/sourcegraph/sourcegraph/internal/observation" +) + +type CodeIntelRepositorySummaryResolver interface { + RecentUploads() []LSIFUploadsWithRepositoryNamespaceResolver + RecentIndexes() []LSIFIndexesWithRepositoryNamespaceResolver + LastUploadRetentionScan() *DateTime + LastIndexScan() *DateTime +} + +type repositorySummaryResolver struct { + autoindexingSvc AutoIndexingService + uploadsSvc UploadsService + policySvc PolicyService + summary RepositorySummary + prefetcher *Prefetcher + locationResolver *CachedLocationResolver + errTracer *observation.ErrCollector +} + +func NewRepositorySummaryResolver(autoindexingSvc AutoIndexingService, uploadsSvc UploadsService, policySvc PolicyService, summary RepositorySummary, prefetcher *Prefetcher, errTracer *observation.ErrCollector) CodeIntelRepositorySummaryResolver { + return &repositorySummaryResolver{ + autoindexingSvc: autoindexingSvc, + uploadsSvc: uploadsSvc, + policySvc: policySvc, + summary: summary, + prefetcher: prefetcher, + locationResolver: NewCachedLocationResolver(autoindexingSvc.GetUnsafeDB()), + errTracer: errTracer, + } +} + +func (r *repositorySummaryResolver) RecentUploads() []LSIFUploadsWithRepositoryNamespaceResolver { + resolvers := make([]LSIFUploadsWithRepositoryNamespaceResolver, 0, len(r.summary.RecentUploads)) + for _, upload := range r.summary.RecentUploads { + uploadResolvers := make([]LSIFUploadResolver, 0, len(upload.Uploads)) + for _, u := range upload.Uploads { + uploadResolvers = append(uploadResolvers, NewUploadResolver(r.uploadsSvc, r.autoindexingSvc, r.policySvc, u, r.prefetcher, r.errTracer)) + } + + resolvers = append(resolvers, NewLSIFUploadsWithRepositoryNamespaceResolver(upload, uploadResolvers)) + } + + return resolvers +} + +func (r *repositorySummaryResolver) RecentIndexes() []LSIFIndexesWithRepositoryNamespaceResolver { + resolvers := make([]LSIFIndexesWithRepositoryNamespaceResolver, 0, len(r.summary.RecentIndexes)) + for _, index := range r.summary.RecentIndexes { + indexResolvers := make([]LSIFIndexResolver, 0, len(index.Indexes)) + for _, idx := range index.Indexes { + indexResolvers = append(indexResolvers, NewIndexResolver(r.autoindexingSvc, r.uploadsSvc, r.policySvc, idx, r.prefetcher, r.errTracer)) + } + dbstoreIndex := convertSharedIndexesWithRepositoryNamespaceToDBStoreIndexesWithRepositoryNamespace(index) + resolvers = append(resolvers, NewLSIFIndexesWithRepositoryNamespaceResolver(dbstoreIndex, indexResolvers)) + } + + return resolvers +} + +func (r *repositorySummaryResolver) LastUploadRetentionScan() *DateTime { + return DateTimeOrNil(r.summary.LastUploadRetentionScan) +} + +func (r *repositorySummaryResolver) LastIndexScan() *DateTime { + return DateTimeOrNil(r.summary.LastIndexScan) +} diff --git a/internal/codeintel/sharedresolvers/upload_document_path_connection.go b/internal/codeintel/sharedresolvers/upload_document_path_connection.go new file mode 100644 index 00000000000..9368b1de54f --- /dev/null +++ b/internal/codeintel/sharedresolvers/upload_document_path_connection.go @@ -0,0 +1,34 @@ +package sharedresolvers + +import "context" + +type LSIFUploadDocumentPathsConnectionResolver interface { + Nodes(ctx context.Context) ([]string, error) + TotalCount(ctx context.Context) (*int32, error) +} + +type UploadDocumentPathsConnectionResolver interface { + Nodes(ctx context.Context) ([]string, error) + TotalCount(ctx context.Context) (*int32, error) +} + +type uploadDocumentPathsConnectionResolver struct { + totalCount int + documents []string +} + +func NewUploadDocumentPathsConnectionResolver(totalCount int, documents []string) UploadDocumentPathsConnectionResolver { + return &uploadDocumentPathsConnectionResolver{ + totalCount: totalCount, + documents: documents, + } +} + +func (r *uploadDocumentPathsConnectionResolver) Nodes(ctx context.Context) ([]string, error) { + return r.documents, nil +} + +func (r *uploadDocumentPathsConnectionResolver) TotalCount(ctx context.Context) (*int32, error) { + count := int32(r.totalCount) + return &count, nil +} diff --git a/internal/codeintel/sharedresolvers/upload_resolver.go b/internal/codeintel/sharedresolvers/upload_resolver.go new file mode 100644 index 00000000000..402877a1f4d --- /dev/null +++ b/internal/codeintel/sharedresolvers/upload_resolver.go @@ -0,0 +1,197 @@ +package sharedresolvers + +import ( + "context" + "strings" + "time" + + "github.com/graph-gophers/graphql-go" + "github.com/opentracing/opentracing-go/log" + + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/observation" +) + +type LSIFUploadResolver interface { + ID() graphql.ID + InputCommit() string + Tags(ctx context.Context) ([]string, error) + InputRoot() string + IsLatestForRepo() bool + UploadedAt() DateTime + State() string + Failure() *string + StartedAt() *DateTime + FinishedAt() *DateTime + InputIndexer() string + Indexer() types.CodeIntelIndexerResolver + PlaceInQueue() *int32 + AssociatedIndex(ctx context.Context) (LSIFIndexResolver, error) + ProjectRoot(ctx context.Context) (*GitTreeEntryResolver, error) + RetentionPolicyOverview(ctx context.Context, args *LSIFUploadRetentionPolicyMatchesArgs) (CodeIntelligenceRetentionPolicyMatchesConnectionResolver, error) + DocumentPaths(ctx context.Context, args *LSIFUploadDocumentPathsQueryArgs) (LSIFUploadDocumentPathsConnectionResolver, error) + AuditLogs(ctx context.Context) (*[]LSIFUploadsAuditLogsResolver, error) +} + +type UploadResolver struct { + uploadsSvc UploadsService + autoindexingSvc AutoIndexingService + policySvc PolicyService + upload types.Upload + prefetcher *Prefetcher + locationResolver *CachedLocationResolver + traceErrs *observation.ErrCollector +} + +func NewUploadResolver(uploadsSvc UploadsService, autoindexingSvc AutoIndexingService, policySvc PolicyService, upload types.Upload, prefetcher *Prefetcher, traceErrs *observation.ErrCollector) LSIFUploadResolver { + if upload.AssociatedIndexID != nil { + // Request the next batch of index fetches to contain the record's associated + // index id, if one exists it exists. This allows the prefetcher.GetIndexByID + // invocation in the AssociatedIndex method to batch its work with sibling + // resolvers, which share the same prefetcher instance. + prefetcher.MarkIndex(*upload.AssociatedIndexID) + } + + return &UploadResolver{ + uploadsSvc: uploadsSvc, + autoindexingSvc: autoindexingSvc, + policySvc: policySvc, + upload: upload, + prefetcher: prefetcher, + locationResolver: NewCachedLocationResolver(autoindexingSvc.GetUnsafeDB()), + traceErrs: traceErrs, + } +} + +func (r *UploadResolver) ID() graphql.ID { return marshalLSIFUploadGQLID(int64(r.upload.ID)) } +func (r *UploadResolver) InputCommit() string { return r.upload.Commit } +func (r *UploadResolver) InputRoot() string { return r.upload.Root } +func (r *UploadResolver) IsLatestForRepo() bool { return r.upload.VisibleAtTip } +func (r *UploadResolver) UploadedAt() DateTime { return DateTime{Time: r.upload.UploadedAt} } +func (r *UploadResolver) Failure() *string { return r.upload.FailureMessage } +func (r *UploadResolver) StartedAt() *DateTime { return DateTimeOrNil(r.upload.StartedAt) } +func (r *UploadResolver) FinishedAt() *DateTime { return DateTimeOrNil(r.upload.FinishedAt) } +func (r *UploadResolver) InputIndexer() string { return r.upload.Indexer } +func (r *UploadResolver) PlaceInQueue() *int32 { return toInt32(r.upload.Rank) } + +func (r *UploadResolver) Tags(ctx context.Context) (tagsNames []string, err error) { + tags, err := r.uploadsSvc.GetListTags(ctx, api.RepoName(r.upload.RepositoryName), r.upload.Commit) + if err != nil { + return nil, err + } + for _, tag := range tags { + tagsNames = append(tagsNames, tag.Name) + } + return +} + +func (r *UploadResolver) State() string { + state := strings.ToUpper(r.upload.State) + if state == "FAILED" { + state = "ERRORED" + } + + return state +} + +func (r *UploadResolver) AssociatedIndex(ctx context.Context) (_ LSIFIndexResolver, err error) { + // TODO - why are a bunch of them zero? + if r.upload.AssociatedIndexID == nil || *r.upload.AssociatedIndexID == 0 { + return nil, nil + } + + defer r.traceErrs.Collect(&err, + log.String("uploadResolver.field", "associatedIndex"), + log.Int("associatedIndex", *r.upload.AssociatedIndexID), + ) + + index, exists, err := r.prefetcher.GetIndexByID(ctx, *r.upload.AssociatedIndexID) + if err != nil || !exists { + return nil, err + } + + return NewIndexResolver(r.autoindexingSvc, r.uploadsSvc, r.policySvc, index, r.prefetcher, r.traceErrs), nil +} + +func (r *UploadResolver) ProjectRoot(ctx context.Context) (*GitTreeEntryResolver, error) { + return r.locationResolver.Path(ctx, api.RepoID(r.upload.RepositoryID), r.upload.Commit, r.upload.Root) +} + +const DefaultRetentionPolicyMatchesPageSize = 50 + +type LSIFUploadRetentionPolicyMatchesArgs struct { + MatchesOnly bool + First *int32 + After *string + Query *string +} + +func (r *UploadResolver) RetentionPolicyOverview(ctx context.Context, args *LSIFUploadRetentionPolicyMatchesArgs) (_ CodeIntelligenceRetentionPolicyMatchesConnectionResolver, err error) { + var afterID int64 + if args.After != nil { + afterID, err = unmarshalConfigurationPolicyGQLID(graphql.ID(*args.After)) + if err != nil { + return nil, err + } + } + + pageSize := DefaultRetentionPolicyMatchesPageSize + if args.First != nil { + pageSize = int(*args.First) + } + + var term string + if args.Query != nil { + term = *args.Query + } + + matches, totalCount, err := r.policySvc.GetRetentionPolicyOverview(ctx, r.upload, args.MatchesOnly, pageSize, afterID, term, time.Now()) + if err != nil { + return nil, err + } + + return NewCodeIntelligenceRetentionPolicyMatcherConnectionResolver(r.autoindexingSvc, matches, totalCount, r.traceErrs), nil +} + +func (r *UploadResolver) Indexer() types.CodeIntelIndexerResolver { + for _, indexer := range types.AllIndexers { + if indexer.Name() == r.upload.Indexer { + return indexer + } + } + + return types.NewCodeIntelIndexerResolver(r.upload.Indexer) +} + +type LSIFUploadDocumentPathsQueryArgs struct { + Pattern string +} + +func (r *UploadResolver) DocumentPaths(ctx context.Context, args *LSIFUploadDocumentPathsQueryArgs) (LSIFUploadDocumentPathsConnectionResolver, error) { + pattern := "%%" + if args.Pattern != "" { + pattern = args.Pattern + } + + documents, totalCount, err := r.uploadsSvc.GetUploadDocumentsForPath(ctx, r.upload.ID, pattern) + if err != nil { + return nil, err + } + + return NewUploadDocumentPathsConnectionResolver(totalCount, documents), nil +} + +func (r *UploadResolver) AuditLogs(ctx context.Context) (*[]LSIFUploadsAuditLogsResolver, error) { + logs, err := r.uploadsSvc.GetAuditLogsForUpload(ctx, r.upload.ID) + if err != nil { + return nil, err + } + + resolvers := make([]LSIFUploadsAuditLogsResolver, 0, len(logs)) + for _, log := range logs { + resolvers = append(resolvers, NewLSIFUploadsAuditLogsResolver(log)) + } + + return &resolvers, nil +} diff --git a/internal/codeintel/sharedresolvers/upload_resolver_connection.go b/internal/codeintel/sharedresolvers/upload_resolver_connection.go new file mode 100644 index 00000000000..9c2f10ed08e --- /dev/null +++ b/internal/codeintel/sharedresolvers/upload_resolver_connection.go @@ -0,0 +1,69 @@ +package sharedresolvers + +import ( + "context" + + "github.com/opentracing/opentracing-go/log" + + "github.com/sourcegraph/sourcegraph/internal/observation" +) + +type LSIFUploadConnectionResolver interface { + Nodes(ctx context.Context) ([]LSIFUploadResolver, error) + TotalCount(ctx context.Context) (*int32, error) + PageInfo(ctx context.Context) (*PageInfo, error) +} + +type UploadConnectionResolver struct { + uploadsSvc UploadsService + autoindexingSvc AutoIndexingService + policySvc PolicyService + uploadsResolver *UploadsResolver + prefetcher *Prefetcher + locationResolver *CachedLocationResolver + traceErrs *observation.ErrCollector +} + +func NewUploadConnectionResolver(uploadsSvc UploadsService, autoindexingSvc AutoIndexingService, policySvc PolicyService, uploadsResolver *UploadsResolver, prefetcher *Prefetcher, traceErrs *observation.ErrCollector) LSIFUploadConnectionResolver { + return &UploadConnectionResolver{ + uploadsSvc: uploadsSvc, + autoindexingSvc: autoindexingSvc, + policySvc: policySvc, + uploadsResolver: uploadsResolver, + prefetcher: prefetcher, + locationResolver: NewCachedLocationResolver(autoindexingSvc.GetUnsafeDB()), + traceErrs: traceErrs, + } +} + +func (r *UploadConnectionResolver) Nodes(ctx context.Context) (_ []LSIFUploadResolver, err error) { + defer r.traceErrs.Collect(&err, log.String("uploadConnectionResolver.field", "nodes")) + + if err := r.uploadsResolver.Resolve(ctx); err != nil { + return nil, err + } + + resolvers := make([]LSIFUploadResolver, 0, len(r.uploadsResolver.Uploads)) + for i := range r.uploadsResolver.Uploads { + resolvers = append(resolvers, NewUploadResolver(r.uploadsSvc, r.autoindexingSvc, r.policySvc, r.uploadsResolver.Uploads[i], r.prefetcher, r.traceErrs)) + } + return resolvers, nil +} + +func (r *UploadConnectionResolver) TotalCount(ctx context.Context) (_ *int32, err error) { + defer r.traceErrs.Collect(&err, log.String("uploadConnectionResolver.field", "totalCount")) + + if err := r.uploadsResolver.Resolve(ctx); err != nil { + return nil, err + } + return toInt32(&r.uploadsResolver.TotalCount), nil +} + +func (r *UploadConnectionResolver) PageInfo(ctx context.Context) (_ *PageInfo, err error) { + defer r.traceErrs.Collect(&err, log.String("uploadConnectionResolver.field", "pageInfo")) + + if err := r.uploadsResolver.Resolve(ctx); err != nil { + return nil, err + } + return EncodeIntCursor(toInt32(r.uploadsResolver.NextOffset)), nil +} diff --git a/internal/codeintel/sharedresolvers/uploads_repository_namespace_resolver.go b/internal/codeintel/sharedresolvers/uploads_repository_namespace_resolver.go new file mode 100644 index 00000000000..39c0e66b78f --- /dev/null +++ b/internal/codeintel/sharedresolvers/uploads_repository_namespace_resolver.go @@ -0,0 +1,42 @@ +package sharedresolvers + +import ( + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + uploadsShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" +) + +type LSIFUploadsWithRepositoryNamespaceResolver interface { + Root() string + Indexer() types.CodeIntelIndexerResolver + Uploads() []LSIFUploadResolver +} + +type lsifUploadsWithRepositoryNamespaceResolver struct { + uploadsSummary uploadsShared.UploadsWithRepositoryNamespace + uploadResolvers []LSIFUploadResolver +} + +func NewLSIFUploadsWithRepositoryNamespaceResolver(uploadsSummary uploadsShared.UploadsWithRepositoryNamespace, uploadResolvers []LSIFUploadResolver) LSIFUploadsWithRepositoryNamespaceResolver { + return &lsifUploadsWithRepositoryNamespaceResolver{ + uploadsSummary: uploadsSummary, + uploadResolvers: uploadResolvers, + } +} + +func (r *lsifUploadsWithRepositoryNamespaceResolver) Root() string { + return r.uploadsSummary.Root +} + +func (r *lsifUploadsWithRepositoryNamespaceResolver) Indexer() types.CodeIntelIndexerResolver { + for _, indexer := range types.AllIndexers { + if indexer.Name() == r.uploadsSummary.Indexer { + return indexer + } + } + + return types.NewCodeIntelIndexerResolver(r.uploadsSummary.Indexer) +} + +func (r *lsifUploadsWithRepositoryNamespaceResolver) Uploads() []LSIFUploadResolver { + return r.uploadResolvers +} diff --git a/internal/codeintel/uploads/transport/graphql/uploads_resolver.go b/internal/codeintel/sharedresolvers/uploads_resolver.go similarity index 67% rename from internal/codeintel/uploads/transport/graphql/uploads_resolver.go rename to internal/codeintel/sharedresolvers/uploads_resolver.go index ad08fd35868..6a162119c7e 100644 --- a/internal/codeintel/uploads/transport/graphql/uploads_resolver.go +++ b/internal/codeintel/sharedresolvers/uploads_resolver.go @@ -1,22 +1,20 @@ -package graphql +package sharedresolvers import ( "context" "sync" - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" - "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads" - "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" ) // UploadsResolver wraps store.GetUploads so that the underlying function can be // invoked lazily and its results memoized. type UploadsResolver struct { - svc *uploads.Service - opts shared.GetUploadsOptions + svc UploadsService + opts types.GetUploadsOptions once sync.Once - Uploads []shared.Upload + Uploads []types.Upload TotalCount int NextOffset *int err error @@ -24,7 +22,7 @@ type UploadsResolver struct { // NewUploadsResolver creates a new UploadsResolver which wil invoke store.GetUploads // with the given options. -func NewUploadsResolver(svc *uploads.Service, opts shared.GetUploadsOptions) *UploadsResolver { +func NewUploadsResolver(svc UploadsService, opts types.GetUploadsOptions) *UploadsResolver { return &UploadsResolver{svc: svc, opts: opts} } @@ -43,7 +41,7 @@ func (r *UploadsResolver) resolve(ctx context.Context) error { } r.Uploads = uploads - r.NextOffset = graphqlutil.NextOffset(r.opts.Offset, len(uploads), totalCount) + r.NextOffset = NextOffset(r.opts.Offset, len(uploads), totalCount) r.TotalCount = totalCount return nil } diff --git a/internal/codeintel/sharedresolvers/utils.go b/internal/codeintel/sharedresolvers/utils.go new file mode 100644 index 00000000000..25b550b1b53 --- /dev/null +++ b/internal/codeintel/sharedresolvers/utils.go @@ -0,0 +1,228 @@ +package sharedresolvers + +import ( + "encoding/base64" + "encoding/json" + "io/fs" + "os" + "strconv" + "time" + + "github.com/graph-gophers/graphql-go" + "github.com/graph-gophers/graphql-go/relay" + + "github.com/sourcegraph/sourcegraph/internal/api" + autoindexingShared "github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" + store "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/workerutil" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// DateTime implements the DateTime GraphQL scalar type. +type DateTime struct{ time.Time } + +// DateTimeOrNil is a helper function that returns nil for time == nil and otherwise wraps time in +// DateTime. +func DateTimeOrNil(time *time.Time) *DateTime { + if time == nil { + return nil + } + return &DateTime{Time: *time} +} + +func (DateTime) ImplementsGraphQLType(name string) bool { + return name == "DateTime" +} + +func (v DateTime) MarshalJSON() ([]byte, error) { + return json.Marshal(v.Time.Format(time.RFC3339)) +} + +func (v *DateTime) UnmarshalGraphQL(input any) error { + s, ok := input.(string) + if !ok { + return errors.Errorf("invalid GraphQL DateTime scalar value input (got %T, expected string)", input) + } + t, err := time.Parse(time.RFC3339, s) + if err != nil { + return err + } + *v = DateTime{Time: t} + return nil +} + +// strPtr creates a pointer to the given value. If the value is an +// empty string, a nil pointer is returned. +func strPtr(val string) *string { + if val == "" { + return nil + } + + return &val +} + +func marshalLSIFIndexGQLID(indexID int64) graphql.ID { + return relay.MarshalID("LSIFIndex", indexID) +} + +// toInt32 translates the given int pointer into an int32 pointer. +func toInt32(val *int) *int32 { + if val == nil { + return nil + } + + v := int32(*val) + return &v +} + +func marshalLSIFUploadGQLID(uploadID int64) graphql.ID { + return relay.MarshalID("LSIFUpload", uploadID) +} + +func unmarshalConfigurationPolicyGQLID(id graphql.ID) (configurationPolicyID int64, err error) { + err = relay.UnmarshalSpec(id, &configurationPolicyID) + return configurationPolicyID, err +} + +type PageInfo struct { + endCursor *string + hasNextPage bool +} + +// HasNextPage returns a new PageInfo with the given hasNextPage value. +func HasNextPage(hasNextPage bool) *PageInfo { + return &PageInfo{hasNextPage: hasNextPage} +} + +// NextPageCursor returns a new PageInfo indicating there is a next page with +// the given end cursor. +func NextPageCursor(endCursor string) *PageInfo { + return &PageInfo{endCursor: &endCursor, hasNextPage: true} +} + +func (r *PageInfo) EndCursor() *string { return r.endCursor } +func (r *PageInfo) HasNextPage() bool { return r.hasNextPage } + +// EncodeIntCursor creates a PageInfo object from the given new offset value. If the +// new offset value, then an object indicating the end of the result set is returned. +// The cursor is base64 encoded for transfer, and should be decoded using the function +// decodeIntCursor. +func EncodeIntCursor(val *int32) *PageInfo { + if val == nil { + return EncodeCursor(nil) + } + + str := strconv.FormatInt(int64(*val), 10) + return EncodeCursor(&str) +} + +// EncodeCursor creates a PageInfo object from the given cursor. If the cursor is not +// defined, then an object indicating the end of the result set is returned. The cursor +// is base64 encoded for transfer, and should be decoded using the function decodeCursor. +func EncodeCursor(val *string) *PageInfo { + if val != nil { + return NextPageCursor(base64.StdEncoding.EncodeToString([]byte(*val))) + } + + return HasNextPage(false) +} + +// NextOffset determines the offset that should be used for a subsequent request. +// If there are no more results in the paged result set, this function returns nil. +func NextOffset(offset, count, totalCount int) *int { + if offset+count < totalCount { + val := offset + count + return &val + } + + return nil +} + +func CreateFileInfo(path string, isDir bool) fs.FileInfo { + return fileInfo{path: path, isDir: isDir} +} + +type fileInfo struct { + path string + size int64 + isDir bool +} + +func (f fileInfo) Name() string { return f.path } +func (f fileInfo) Size() int64 { return f.size } +func (f fileInfo) IsDir() bool { return f.isDir } +func (f fileInfo) Mode() os.FileMode { + if f.IsDir() { + return os.ModeDir + } + return 0 +} +func (f fileInfo) ModTime() time.Time { return time.Now() } +func (f fileInfo) Sys() any { return any(nil) } + +func convertSharedIndexesWithRepositoryNamespaceToDBStoreIndexesWithRepositoryNamespace(shared autoindexingShared.IndexesWithRepositoryNamespace) dbstore.IndexesWithRepositoryNamespace { + indexes := make([]dbstore.Index, 0, len(shared.Indexes)) + for _, index := range shared.Indexes { + indexes = append(indexes, convertSharedIndexToDBStoreIndex(index)) + } + + return dbstore.IndexesWithRepositoryNamespace{ + Root: shared.Root, + Indexer: shared.Indexer, + Indexes: indexes, + } +} + +func convertSharedIndexToDBStoreIndex(index types.Index) store.Index { + dockerSteps := make([]store.DockerStep, 0, len(index.DockerSteps)) + for _, step := range index.DockerSteps { + dockerSteps = append(dockerSteps, store.DockerStep(step)) + } + + executionLogs := make([]workerutil.ExecutionLogEntry, 0, len(index.ExecutionLogs)) + for _, log := range index.ExecutionLogs { + executionLogs = append(executionLogs, workerutil.ExecutionLogEntry(log)) + } + + return store.Index{ + ID: index.ID, + Commit: index.Commit, + QueuedAt: index.QueuedAt, + State: index.State, + FailureMessage: index.FailureMessage, + StartedAt: index.StartedAt, + FinishedAt: index.FinishedAt, + ProcessAfter: index.ProcessAfter, + NumResets: index.NumResets, + NumFailures: index.NumFailures, + RepositoryID: index.RepositoryID, + LocalSteps: index.LocalSteps, + RepositoryName: index.RepositoryName, + DockerSteps: dockerSteps, + Root: index.Root, + Indexer: index.Indexer, + IndexerArgs: index.IndexerArgs, + Outfile: index.Outfile, + ExecutionLogs: executionLogs, + Rank: index.Rank, + AssociatedUploadID: index.AssociatedUploadID, + } +} + +func UnmarshalRepositoryID(id graphql.ID) (repo api.RepoID, err error) { + err = relay.UnmarshalSpec(id, &repo) + return +} + +// gitCommitGQLID is a type used for marshaling and unmarshaling a Git commit's +// GraphQL ID. +type gitCommitGQLID struct { + Repository graphql.ID `json:"r"` + CommitID GitObjectID `json:"c"` +} + +func marshalGitCommitID(repo graphql.ID, commitID GitObjectID) graphql.ID { + return relay.MarshalID("GitCommit", gitCommitGQLID{Repository: repo, CommitID: commitID}) +} diff --git a/internal/codeintel/types/index.go b/internal/codeintel/types/index.go new file mode 100644 index 00000000000..3d8c35d3e51 --- /dev/null +++ b/internal/codeintel/types/index.go @@ -0,0 +1,92 @@ +package types + +import ( + "database/sql/driver" + "encoding/json" + "time" + + "github.com/sourcegraph/sourcegraph/internal/workerutil" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +type Index struct { + ID int `json:"id"` + Commit string `json:"commit"` + QueuedAt time.Time `json:"queuedAt"` + State string `json:"state"` + FailureMessage *string `json:"failureMessage"` + StartedAt *time.Time `json:"startedAt"` + FinishedAt *time.Time `json:"finishedAt"` + ProcessAfter *time.Time `json:"processAfter"` + NumResets int `json:"numResets"` + NumFailures int `json:"numFailures"` + RepositoryID int `json:"repositoryId"` + LocalSteps []string `json:"local_steps"` + RepositoryName string `json:"repositoryName"` + DockerSteps []DockerStep `json:"docker_steps"` + Root string `json:"root"` + Indexer string `json:"indexer"` + IndexerArgs []string `json:"indexer_args"` // TODO - convert this to `IndexCommand string` + Outfile string `json:"outfile"` + ExecutionLogs []ExecutionLogEntry `json:"execution_logs"` + Rank *int `json:"placeInQueue"` + AssociatedUploadID *int `json:"associatedUpload"` +} + +type GetIndexesOptions struct { + RepositoryID int + State string + Term string + Limit int + Offset int +} + +type DockerStep struct { + Root string `json:"root"` + Image string `json:"image"` + Commands []string `json:"commands"` +} + +func (s *DockerStep) Scan(value any) error { + b, ok := value.([]byte) + if !ok { + return errors.Errorf("value is not []byte: %T", value) + } + + return json.Unmarshal(b, &s) +} + +func (s DockerStep) Value() (driver.Value, error) { + return json.Marshal(s) +} + +// ExecutionLogEntry represents a command run by the executor. +type ExecutionLogEntry struct { + Key string `json:"key"` + Command []string `json:"command"` + StartTime time.Time `json:"startTime"` + ExitCode *int `json:"exitCode,omitempty"` + Out string `json:"out,omitempty"` + DurationMs *int `json:"durationMs,omitempty"` +} + +func (e *ExecutionLogEntry) Scan(value any) error { + b, ok := value.([]byte) + if !ok { + return errors.Errorf("value is not []byte: %T", value) + } + + return json.Unmarshal(b, &e) +} + +func (e ExecutionLogEntry) Value() (driver.Value, error) { + return json.Marshal(e) +} + +func ExecutionLogEntries(raw []workerutil.ExecutionLogEntry) (entries []ExecutionLogEntry) { + for _, entry := range raw { + entries = append(entries, ExecutionLogEntry(entry)) + } + + return entries +} diff --git a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/indexers.go b/internal/codeintel/types/indexers.go similarity index 90% rename from enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/indexers.go rename to internal/codeintel/types/indexers.go index a08dfa79358..5aa3af8e4a8 100644 --- a/enterprise/cmd/frontend/internal/codeintel/resolvers/graphql/indexers.go +++ b/internal/codeintel/types/indexers.go @@ -1,12 +1,19 @@ -package graphql +package types -import gql "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" +type CodeIntelIndexerResolver interface { + Name() string + URL() string +} type codeIntelIndexerResolver struct { name string urn string } +func NewCodeIntelIndexerResolver(name string) CodeIntelIndexerResolver { + return &codeIntelIndexerResolver{name: name} +} + func (r *codeIntelIndexerResolver) Name() string { return r.name } @@ -94,7 +101,7 @@ var ( } ) -var allIndexers = []gql.CodeIntelIndexerResolver{ +var AllIndexers = []CodeIntelIndexerResolver{ &lsifNode, &msftNode, &lsifTypescript, @@ -117,7 +124,7 @@ var allIndexers = []gql.CodeIntelIndexerResolver{ // A map of file extension to a list of indexers in order of recommendation // from most to least. -var languageToIndexer = map[string][]gql.CodeIntelIndexerResolver{ +var LanguageToIndexer = map[string][]CodeIntelIndexerResolver{ ".go": {&lsifGo}, ".java": {&scipJava, &msftJava}, ".kt": {&scipJava}, @@ -143,7 +150,7 @@ var languageToIndexer = map[string][]gql.CodeIntelIndexerResolver{ ".cs": {&lsifDotnet}, } -var imageToIndexer = map[string]gql.CodeIntelIndexerResolver{ +var ImageToIndexer = map[string]CodeIntelIndexerResolver{ "sourcegraph/scip-java": &scipJava, "sourcegraph/lsif-go": &lsifGo, "sourcegraph/scip-typescript": &lsifTypescript, diff --git a/internal/codeintel/types/types.go b/internal/codeintel/types/types.go index 5ed5bd66be3..729472afaf8 100644 --- a/internal/codeintel/types/types.go +++ b/internal/codeintel/types/types.go @@ -1,6 +1,171 @@ package types -import "github.com/sourcegraph/sourcegraph/internal/api" +import ( + "time" + + "github.com/sourcegraph/sourcegraph/internal/api" +) // RevSpecSet is a utility type for a set of RevSpecs. type RevSpecSet map[api.RevSpec]struct{} + +// Dump is a subset of the lsif_uploads table (queried via the lsif_dumps_with_repository_name view) +// and stores only processed records. +type Dump struct { + ID int `json:"id"` + Commit string `json:"commit"` + Root string `json:"root"` + VisibleAtTip bool `json:"visibleAtTip"` + UploadedAt time.Time `json:"uploadedAt"` + State string `json:"state"` + FailureMessage *string `json:"failureMessage"` + StartedAt *time.Time `json:"startedAt"` + FinishedAt *time.Time `json:"finishedAt"` + ProcessAfter *time.Time `json:"processAfter"` + NumResets int `json:"numResets"` + NumFailures int `json:"numFailures"` + RepositoryID int `json:"repositoryId"` + RepositoryName string `json:"repositoryName"` + Indexer string `json:"indexer"` + IndexerVersion string `json:"indexerVersion"` + AssociatedIndexID *int `json:"associatedIndex"` +} + +// UploadLocation is a path and range pair from within a particular upload. The target commit +// denotes the target commit for which the location was set (the originally requested commit). +type UploadLocation struct { + Dump Dump + Path string + TargetCommit string + TargetRange Range +} + +type Range struct { + Start Position + End Position +} + +// Position is a unique position within a file. +type Position struct { + Line int + Character int +} + +type UploadLog struct { + LogTimestamp time.Time + RecordDeletedAt *time.Time + UploadID int + Commit string + Root string + RepositoryID int + UploadedAt time.Time + Indexer string + IndexerVersion *string + UploadSize *int + AssociatedIndexID *int + TransitionColumns []map[string]*string + Reason *string + Operation string +} + +type Upload struct { + ID int + Commit string + Root string + VisibleAtTip bool + UploadedAt time.Time + State string + FailureMessage *string + StartedAt *time.Time + FinishedAt *time.Time + ProcessAfter *time.Time + NumResets int + NumFailures int + RepositoryID int + RepositoryName string + Indexer string + IndexerVersion string + NumParts int + UploadedParts []int + UploadSize *int64 + UncompressedSize *int64 + Rank *int + AssociatedIndexID *int +} + +type GetUploadsOptions struct { + RepositoryID int + State string + Term string + VisibleAtTip bool + DependencyOf int + DependentOf int + UploadedBefore *time.Time + UploadedAfter *time.Time + LastRetentionScanBefore *time.Time + AllowExpired bool + AllowDeletedRepo bool + AllowDeletedUpload bool + OldestFirst bool + Limit int + Offset int + + // InCommitGraph ensures that the repository commit graph was updated strictly + // after this upload was processed. This condition helps us filter out new uploads + // that we might later mistake for unreachable. + InCommitGraph bool +} + +type GetConfigurationPoliciesOptions struct { + // RepositoryID indicates that only configuration policies that apply to the + // specified repository (directly or via pattern) should be returned. This value + // has no effect when equal to zero. + RepositoryID int + + // Term is a string to search within the configuration title. + Term string + + // ForIndexing indicates that only configuration policies with data retention enabled + // should be returned. + ForDataRetention bool + + // ForIndexing indicates that only configuration policies with indexing enabled should + // be returned. + ForIndexing bool + + // Limit indicates the number of results to take from the result set. + Limit int + + // Offset indicates the number of results to skip in the result set. + Offset int +} + +type ConfigurationPolicy struct { + ID int + RepositoryID *int + RepositoryPatterns *[]string + Name string + Type GitObjectType + Pattern string + Protected bool + RetentionEnabled bool + RetentionDuration *time.Duration + RetainIntermediateCommits bool + IndexingEnabled bool + IndexCommitMaxAge *time.Duration + IndexIntermediateCommits bool +} + +type RetentionPolicyMatchCandidate struct { + *ConfigurationPolicy + Matched bool + ProtectingCommits []string +} + +type GitObjectType string + +const ( + GitObjectTypeCommit GitObjectType = "GIT_COMMIT" + GitObjectTypeTag GitObjectType = "GIT_TAG" + GitObjectTypeTree GitObjectType = "GIT_TREE" +) diff --git a/internal/codeintel/uploads/background/expiration/iface.go b/internal/codeintel/uploads/background/expiration/iface.go index c5b821636a7..439ec6e9de3 100644 --- a/internal/codeintel/uploads/background/expiration/iface.go +++ b/internal/codeintel/uploads/background/expiration/iface.go @@ -5,18 +5,17 @@ import ( "time" policies "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/enterprise" - policyShared "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - uploadShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" ) type PolicyService interface { - GetConfigurationPolicies(ctx context.Context, opts policyShared.GetConfigurationPoliciesOptions) ([]policyShared.ConfigurationPolicy, int, error) + GetConfigurationPolicies(ctx context.Context, opts types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) } type UploadService interface { // Uploads - GetUploads(ctx context.Context, opts uploadShared.GetUploadsOptions) (uploads []uploadShared.Upload, totalCount int, err error) + GetUploads(ctx context.Context, opts types.GetUploadsOptions) (uploads []types.Upload, totalCount int, err error) UpdateUploadRetention(ctx context.Context, protectedIDs, expiredIDs []int) (err error) BackfillReferenceCountBatch(ctx context.Context, batchSize int) error diff --git a/internal/codeintel/uploads/background/expiration/mocks_test.go b/internal/codeintel/uploads/background/expiration/mocks_test.go index a0c2ca8a430..b34bdb14b17 100644 --- a/internal/codeintel/uploads/background/expiration/mocks_test.go +++ b/internal/codeintel/uploads/background/expiration/mocks_test.go @@ -12,9 +12,8 @@ import ( "time" enterprise "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/enterprise" - shared "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" dbstore "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - shared1 "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + types "github.com/sourcegraph/sourcegraph/internal/codeintel/types" ) // MockPolicyMatcher is a mock implementation of the PolicyMatcher interface @@ -205,7 +204,7 @@ type MockPolicyService struct { func NewMockPolicyService() *MockPolicyService { return &MockPolicyService{ GetConfigurationPoliciesFunc: &PolicyServiceGetConfigurationPoliciesFunc{ - defaultHook: func(context.Context, shared.GetConfigurationPoliciesOptions) (r0 []shared.ConfigurationPolicy, r1 int, r2 error) { + defaultHook: func(context.Context, types.GetConfigurationPoliciesOptions) (r0 []types.ConfigurationPolicy, r1 int, r2 error) { return }, }, @@ -217,7 +216,7 @@ func NewMockPolicyService() *MockPolicyService { func NewStrictMockPolicyService() *MockPolicyService { return &MockPolicyService{ GetConfigurationPoliciesFunc: &PolicyServiceGetConfigurationPoliciesFunc{ - defaultHook: func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) { + defaultHook: func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) { panic("unexpected invocation of MockPolicyService.GetConfigurationPolicies") }, }, @@ -239,15 +238,15 @@ func NewMockPolicyServiceFrom(i PolicyService) *MockPolicyService { // GetConfigurationPolicies method of the parent MockPolicyService instance // is invoked. type PolicyServiceGetConfigurationPoliciesFunc struct { - defaultHook func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) - hooks []func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) + defaultHook func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) + hooks []func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) history []PolicyServiceGetConfigurationPoliciesFuncCall mutex sync.Mutex } // GetConfigurationPolicies delegates to the next hook function in the queue // and stores the parameter and result values of this invocation. -func (m *MockPolicyService) GetConfigurationPolicies(v0 context.Context, v1 shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) { +func (m *MockPolicyService) GetConfigurationPolicies(v0 context.Context, v1 types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) { r0, r1, r2 := m.GetConfigurationPoliciesFunc.nextHook()(v0, v1) m.GetConfigurationPoliciesFunc.appendCall(PolicyServiceGetConfigurationPoliciesFuncCall{v0, v1, r0, r1, r2}) return r0, r1, r2 @@ -256,7 +255,7 @@ func (m *MockPolicyService) GetConfigurationPolicies(v0 context.Context, v1 shar // SetDefaultHook sets function that is called when the // GetConfigurationPolicies method of the parent MockPolicyService instance // is invoked and the hook queue is empty. -func (f *PolicyServiceGetConfigurationPoliciesFunc) SetDefaultHook(hook func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error)) { +func (f *PolicyServiceGetConfigurationPoliciesFunc) SetDefaultHook(hook func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error)) { f.defaultHook = hook } @@ -265,7 +264,7 @@ func (f *PolicyServiceGetConfigurationPoliciesFunc) SetDefaultHook(hook func(con // invokes the hook at the front of the queue and discards it. After the // queue is empty, the default hook function is invoked for any future // action. -func (f *PolicyServiceGetConfigurationPoliciesFunc) PushHook(hook func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error)) { +func (f *PolicyServiceGetConfigurationPoliciesFunc) PushHook(hook func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -273,20 +272,20 @@ func (f *PolicyServiceGetConfigurationPoliciesFunc) PushHook(hook func(context.C // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *PolicyServiceGetConfigurationPoliciesFunc) SetDefaultReturn(r0 []shared.ConfigurationPolicy, r1 int, r2 error) { - f.SetDefaultHook(func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) { +func (f *PolicyServiceGetConfigurationPoliciesFunc) SetDefaultReturn(r0 []types.ConfigurationPolicy, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) { return r0, r1, r2 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *PolicyServiceGetConfigurationPoliciesFunc) PushReturn(r0 []shared.ConfigurationPolicy, r1 int, r2 error) { - f.PushHook(func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) { +func (f *PolicyServiceGetConfigurationPoliciesFunc) PushReturn(r0 []types.ConfigurationPolicy, r1 int, r2 error) { + f.PushHook(func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) { return r0, r1, r2 }) } -func (f *PolicyServiceGetConfigurationPoliciesFunc) nextHook() func(context.Context, shared.GetConfigurationPoliciesOptions) ([]shared.ConfigurationPolicy, int, error) { +func (f *PolicyServiceGetConfigurationPoliciesFunc) nextHook() func(context.Context, types.GetConfigurationPoliciesOptions) ([]types.ConfigurationPolicy, int, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -326,10 +325,10 @@ type PolicyServiceGetConfigurationPoliciesFuncCall struct { Arg0 context.Context // Arg1 is the value of the 2nd argument passed to this method // invocation. - Arg1 shared.GetConfigurationPoliciesOptions + Arg1 types.GetConfigurationPoliciesOptions // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.ConfigurationPolicy + Result0 []types.ConfigurationPolicy // Result1 is the value of the 2nd result returned from this method // invocation. Result1 int @@ -390,7 +389,7 @@ func NewMockUploadService() *MockUploadService { }, }, GetUploadsFunc: &UploadServiceGetUploadsFunc{ - defaultHook: func(context.Context, shared1.GetUploadsOptions) (r0 []shared1.Upload, r1 int, r2 error) { + defaultHook: func(context.Context, types.GetUploadsOptions) (r0 []types.Upload, r1 int, r2 error) { return }, }, @@ -422,7 +421,7 @@ func NewStrictMockUploadService() *MockUploadService { }, }, GetUploadsFunc: &UploadServiceGetUploadsFunc{ - defaultHook: func(context.Context, shared1.GetUploadsOptions) ([]shared1.Upload, int, error) { + defaultHook: func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { panic("unexpected invocation of MockUploadService.GetUploads") }, }, @@ -695,15 +694,15 @@ func (c UploadServiceGetCommitsVisibleToUploadFuncCall) Results() []interface{} // UploadServiceGetUploadsFunc describes the behavior when the GetUploads // method of the parent MockUploadService instance is invoked. type UploadServiceGetUploadsFunc struct { - defaultHook func(context.Context, shared1.GetUploadsOptions) ([]shared1.Upload, int, error) - hooks []func(context.Context, shared1.GetUploadsOptions) ([]shared1.Upload, int, error) + defaultHook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) + hooks []func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) history []UploadServiceGetUploadsFuncCall mutex sync.Mutex } // GetUploads delegates to the next hook function in the queue and stores // the parameter and result values of this invocation. -func (m *MockUploadService) GetUploads(v0 context.Context, v1 shared1.GetUploadsOptions) ([]shared1.Upload, int, error) { +func (m *MockUploadService) GetUploads(v0 context.Context, v1 types.GetUploadsOptions) ([]types.Upload, int, error) { r0, r1, r2 := m.GetUploadsFunc.nextHook()(v0, v1) m.GetUploadsFunc.appendCall(UploadServiceGetUploadsFuncCall{v0, v1, r0, r1, r2}) return r0, r1, r2 @@ -712,7 +711,7 @@ func (m *MockUploadService) GetUploads(v0 context.Context, v1 shared1.GetUploads // SetDefaultHook sets function that is called when the GetUploads method of // the parent MockUploadService instance is invoked and the hook queue is // empty. -func (f *UploadServiceGetUploadsFunc) SetDefaultHook(hook func(context.Context, shared1.GetUploadsOptions) ([]shared1.Upload, int, error)) { +func (f *UploadServiceGetUploadsFunc) SetDefaultHook(hook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error)) { f.defaultHook = hook } @@ -720,7 +719,7 @@ func (f *UploadServiceGetUploadsFunc) SetDefaultHook(hook func(context.Context, // GetUploads method of the parent MockUploadService instance invokes the // hook at the front of the queue and discards it. After the queue is empty, // the default hook function is invoked for any future action. -func (f *UploadServiceGetUploadsFunc) PushHook(hook func(context.Context, shared1.GetUploadsOptions) ([]shared1.Upload, int, error)) { +func (f *UploadServiceGetUploadsFunc) PushHook(hook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -728,20 +727,20 @@ func (f *UploadServiceGetUploadsFunc) PushHook(hook func(context.Context, shared // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *UploadServiceGetUploadsFunc) SetDefaultReturn(r0 []shared1.Upload, r1 int, r2 error) { - f.SetDefaultHook(func(context.Context, shared1.GetUploadsOptions) ([]shared1.Upload, int, error) { +func (f *UploadServiceGetUploadsFunc) SetDefaultReturn(r0 []types.Upload, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { return r0, r1, r2 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *UploadServiceGetUploadsFunc) PushReturn(r0 []shared1.Upload, r1 int, r2 error) { - f.PushHook(func(context.Context, shared1.GetUploadsOptions) ([]shared1.Upload, int, error) { +func (f *UploadServiceGetUploadsFunc) PushReturn(r0 []types.Upload, r1 int, r2 error) { + f.PushHook(func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { return r0, r1, r2 }) } -func (f *UploadServiceGetUploadsFunc) nextHook() func(context.Context, shared1.GetUploadsOptions) ([]shared1.Upload, int, error) { +func (f *UploadServiceGetUploadsFunc) nextHook() func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -779,10 +778,10 @@ type UploadServiceGetUploadsFuncCall struct { Arg0 context.Context // Arg1 is the value of the 2nd argument passed to this method // invocation. - Arg1 shared1.GetUploadsOptions + Arg1 types.GetUploadsOptions // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared1.Upload + Result0 []types.Upload // Result1 is the value of the 2nd result returned from this method // invocation. Result1 int diff --git a/internal/codeintel/uploads/background/expiration/upload_expirer.go b/internal/codeintel/uploads/background/expiration/upload_expirer.go index f6ba4f2b75f..bf1d309e959 100644 --- a/internal/codeintel/uploads/background/expiration/upload_expirer.go +++ b/internal/codeintel/uploads/background/expiration/upload_expirer.go @@ -7,9 +7,8 @@ import ( "github.com/sourcegraph/log" policiesEnterprise "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/enterprise" - policyShared "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - uploadShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/timeutil" "github.com/sourcegraph/sourcegraph/lib/errors" ) @@ -88,7 +87,7 @@ func (e *expirer) handleRepository(ctx context.Context, repositoryID int, now ti // out new uploads that would happen to be visible to no commits since they were never // installed into the commit graph. - uploads, _, err := e.uploadSvc.GetUploads(ctx, uploadShared.GetUploadsOptions{ + uploads, _, err := e.uploadSvc.GetUploads(ctx, types.GetUploadsOptions{ State: "completed", RepositoryID: repositoryID, AllowExpired: false, @@ -115,12 +114,12 @@ func (e *expirer) handleRepository(ctx context.Context, repositoryID int, now ti func (e *expirer) buildCommitMap(ctx context.Context, repositoryID int, now time.Time) (map[string][]policiesEnterprise.PolicyMatch, error) { var ( offset int - policies []policyShared.ConfigurationPolicy + policies []types.ConfigurationPolicy ) for { // Retrieve the complete set of configuration policies that affect data retention for this repository - policyBatch, totalCount, err := e.policySvc.GetConfigurationPolicies(ctx, policyShared.GetConfigurationPoliciesOptions{ + policyBatch, totalCount, err := e.policySvc.GetConfigurationPolicies(ctx, types.GetConfigurationPoliciesOptions{ RepositoryID: repositoryID, ForDataRetention: true, Limit: ConfigInst.PolicyBatchSize, @@ -147,7 +146,7 @@ func (e *expirer) buildCommitMap(ctx context.Context, repositoryID int, now time func (e *expirer) handleUploads( ctx context.Context, commitMap map[string][]policiesEnterprise.PolicyMatch, - uploads []uploadShared.Upload, + uploads []types.Upload, now time.Time, ) (err error) { // Categorize each upload as protected or expired @@ -201,7 +200,7 @@ func (e *expirer) handleUploads( func (e *expirer) isUploadProtectedByPolicy( ctx context.Context, commitMap map[string][]policiesEnterprise.PolicyMatch, - upload uploadShared.Upload, + upload types.Upload, now time.Time, ) (bool, error) { e.metrics.numUploadsScanned.Inc() @@ -241,7 +240,7 @@ func (e *expirer) isUploadProtectedByPolicy( return false, nil } -func convertConfigPolicies(configs []policyShared.ConfigurationPolicy) []dbstore.ConfigurationPolicy { +func convertConfigPolicies(configs []types.ConfigurationPolicy) []dbstore.ConfigurationPolicy { configPolicy := make([]dbstore.ConfigurationPolicy, 0, len(configs)) for _, c := range configs { configPolicy = append(configPolicy, dbstore.ConfigurationPolicy{ diff --git a/internal/codeintel/uploads/background/expiration/upload_expirer_test.go b/internal/codeintel/uploads/background/expiration/upload_expirer_test.go index 0a4f83cb345..3187a90b0b8 100644 --- a/internal/codeintel/uploads/background/expiration/upload_expirer_test.go +++ b/internal/codeintel/uploads/background/expiration/upload_expirer_test.go @@ -11,9 +11,8 @@ import ( "github.com/sourcegraph/log/logtest" policiesEnterprise "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/enterprise" - policyShared "github.com/sourcegraph/sourcegraph/internal/codeintel/policies/shared" "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/dbstore" - uploadShared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/observation" "github.com/sourcegraph/sourcegraph/internal/timeutil" ) @@ -91,7 +90,7 @@ func TestUploadExpirer(t *testing.T) { } func setupMockPolicyService() *MockPolicyService { - policies := []policyShared.ConfigurationPolicy{ + policies := []types.ConfigurationPolicy{ {ID: 1, RepositoryID: nil}, {ID: 2, RepositoryID: intPtr(53)}, {ID: 3, RepositoryID: nil}, @@ -99,7 +98,7 @@ func setupMockPolicyService() *MockPolicyService { {ID: 5, RepositoryID: intPtr(50)}, } - getConfigurationPolicies := func(ctx context.Context, opts policyShared.GetConfigurationPoliciesOptions) (filtered []policyShared.ConfigurationPolicy, _ int, _ error) { + getConfigurationPolicies := func(ctx context.Context, opts types.GetConfigurationPoliciesOptions) (filtered []types.ConfigurationPolicy, _ int, _ error) { for _, policy := range policies { if policy.RepositoryID == nil || *policy.RepositoryID == opts.RepositoryID { filtered = append(filtered, policy) @@ -116,7 +115,7 @@ func setupMockPolicyService() *MockPolicyService { } func setupMockUploadService(now time.Time) *MockUploadService { - uploads := []uploadShared.Upload{ + uploads := []types.Upload{ {ID: 11, State: "completed", RepositoryID: 50, Commit: "deadbeef01", UploadedAt: daysAgo(now, 1)}, // repo 50 {ID: 12, State: "completed", RepositoryID: 50, Commit: "deadbeef02", UploadedAt: daysAgo(now, 2)}, {ID: 13, State: "completed", RepositoryID: 50, Commit: "deadbeef03", UploadedAt: daysAgo(now, 3)}, @@ -162,8 +161,8 @@ func setupMockUploadService(now time.Time) *MockUploadService { return scannedIDs, nil } - getUploads := func(ctx context.Context, opts uploadShared.GetUploadsOptions) ([]uploadShared.Upload, int, error) { - var filtered []uploadShared.Upload + getUploads := func(ctx context.Context, opts types.GetUploadsOptions) ([]types.Upload, int, error) { + var filtered []types.Upload for _, upload := range uploads { if upload.RepositoryID != opts.RepositoryID { continue diff --git a/internal/codeintel/uploads/internal/store/scan.go b/internal/codeintel/uploads/internal/store/scan.go index 59e50bc5fe9..180454c3a0f 100644 --- a/internal/codeintel/uploads/internal/store/scan.go +++ b/internal/codeintel/uploads/internal/store/scan.go @@ -8,18 +8,19 @@ import ( "github.com/lib/pq" "github.com/sourcegraph/sourcegraph/internal/codeintel/commitgraph" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/database/dbutil" ) -func scanUploadByID(s dbutil.Scanner) (upload shared.Upload, err error) { +func scanUploadByID(s dbutil.Scanner) (upload types.Upload, err error) { return upload, s.Scan( &upload.ID, ) } -func scanCompleteUpload(s dbutil.Scanner) (upload shared.Upload, _ error) { +func scanCompleteUpload(s dbutil.Scanner) (upload types.Upload, _ error) { var rawUploadedParts []sql.NullInt32 if err := s.Scan( &upload.ID, @@ -66,7 +67,7 @@ var scanFirstUpload = basestore.NewFirstScanner(scanCompleteUpload) var scanUploadsWithCount = basestore.NewSliceWithCountScanner(scanUploadWithCount) -func scanUploadWithCount(s dbutil.Scanner) (upload shared.Upload, count int, err error) { +func scanUploadWithCount(s dbutil.Scanner) (upload types.Upload, count int, err error) { var rawUploadedParts []sql.NullInt32 if err = s.Scan( &upload.ID, @@ -126,7 +127,7 @@ func scanCounts(rows *sql.Rows, queryErr error) (_ map[int]int, err error) { } // scanDumps scans a slice of dumps from the return value of `*Store.query`. -func scanDump(s dbutil.Scanner) (dump shared.Dump, err error) { +func scanDump(s dbutil.Scanner) (dump types.Dump, err error) { return dump, s.Scan( &dump.ID, &dump.Commit, @@ -283,7 +284,7 @@ func scanRepoNames(rows *sql.Rows, queryErr error) (_ map[int]string, err error) return names, nil } -func scanUploadAuditLog(s dbutil.Scanner) (log shared.UploadLog, _ error) { +func scanUploadAuditLog(s dbutil.Scanner) (log types.UploadLog, _ error) { hstores := pgtype.HstoreArray{} err := s.Scan( &log.LogTimestamp, diff --git a/internal/codeintel/uploads/internal/store/store.go b/internal/codeintel/uploads/internal/store/store.go index b3abb1091e9..c7fff0b2585 100644 --- a/internal/codeintel/uploads/internal/store/store.go +++ b/internal/codeintel/uploads/internal/store/store.go @@ -6,6 +6,7 @@ import ( logger "github.com/sourcegraph/log" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" @@ -41,9 +42,9 @@ type Store interface { HasRepository(ctx context.Context, repositoryID int) (_ bool, err error) // Uploads - GetUploads(ctx context.Context, opts shared.GetUploadsOptions) (_ []shared.Upload, _ int, err error) - GetUploadByID(ctx context.Context, id int) (_ shared.Upload, _ bool, err error) - GetUploadsByIDs(ctx context.Context, ids ...int) (_ []shared.Upload, err error) + GetUploads(ctx context.Context, opts types.GetUploadsOptions) (_ []types.Upload, _ int, err error) + GetUploadByID(ctx context.Context, id int) (_ types.Upload, _ bool, err error) + GetUploadsByIDs(ctx context.Context, ids ...int) (_ []types.Upload, err error) GetUploadIDsWithReferences(ctx context.Context, orderedMonikers []precise.QualifiedMonikerData, ignoreIDs []int, repositoryID int, commit string, limit int, offset int, trace observation.TraceLogger) (ids []int, recordsScanned int, totalCount int, err error) GetVisibleUploadsMatchingMonikers(ctx context.Context, repositoryID int, commit string, orderedMonikers []precise.QualifiedMonikerData, limit, offset int) (_ shared.PackageReferenceScanner, _ int, err error) GetRecentUploadsSummary(ctx context.Context, repositoryID int) (upload []shared.UploadsWithRepositoryNamespace, err error) @@ -67,10 +68,10 @@ type Store interface { MarkFailed(ctx context.Context, id int, reason string) error // Dumps - FindClosestDumps(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string) (_ []shared.Dump, err error) - FindClosestDumpsFromGraphFragment(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string, commitGraph *gitdomain.CommitGraph) (_ []shared.Dump, err error) - GetDumpsWithDefinitionsForMonikers(ctx context.Context, monikers []precise.QualifiedMonikerData) (_ []shared.Dump, err error) - GetDumpsByIDs(ctx context.Context, ids []int) (_ []shared.Dump, err error) + FindClosestDumps(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string) (_ []types.Dump, err error) + FindClosestDumpsFromGraphFragment(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string, commitGraph *gitdomain.CommitGraph) (_ []types.Dump, err error) + GetDumpsWithDefinitionsForMonikers(ctx context.Context, monikers []precise.QualifiedMonikerData) (_ []types.Dump, err error) + GetDumpsByIDs(ctx context.Context, ids []int) (_ []types.Dump, err error) // Packages UpdatePackages(ctx context.Context, dumpID int, packages []precise.Package) (err error) @@ -79,7 +80,7 @@ type Store interface { UpdatePackageReferences(ctx context.Context, dumpID int, references []precise.PackageReference) (err error) // Audit Logs - GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []shared.UploadLog, err error) + GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []types.UploadLog, err error) DeleteOldAuditLogs(ctx context.Context, maxAge time.Duration, now time.Time) (count int, err error) } diff --git a/internal/codeintel/uploads/internal/store/store_audit_logs.go b/internal/codeintel/uploads/internal/store/store_audit_logs.go index 63f92201b0f..cc0ea461eb2 100644 --- a/internal/codeintel/uploads/internal/store/store_audit_logs.go +++ b/internal/codeintel/uploads/internal/store/store_audit_logs.go @@ -6,7 +6,7 @@ import ( "github.com/keegancsmith/sqlf" - "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/observation" @@ -14,7 +14,7 @@ import ( // GetAuditLogsForUpload returns all the audit logs for the given upload ID in order of entry // from oldest to newest, according to the auto-incremented internal sequence field. -func (s *store) GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []shared.UploadLog, err error) { +func (s *store) GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []types.UploadLog, err error) { authzConds, err := database.AuthzQueryConds(ctx, database.NewDBWith(s.logger, s.db)) if err != nil { return nil, err diff --git a/internal/codeintel/uploads/internal/store/store_audit_logs_test.go b/internal/codeintel/uploads/internal/store/store_audit_logs_test.go index ca19f660609..837ab220417 100644 --- a/internal/codeintel/uploads/internal/store/store_audit_logs_test.go +++ b/internal/codeintel/uploads/internal/store/store_audit_logs_test.go @@ -7,7 +7,7 @@ import ( "github.com/sourcegraph/log/logtest" - "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/observation" @@ -19,8 +19,8 @@ func TestUploadAuditLogs(t *testing.T) { db := database.NewDB(logger, sqlDB) store := New(db, &observation.TestContext) - insertUploads(t, db, shared.Upload{ID: 1}) - updateUploads(t, db, shared.Upload{ID: 1, State: "deleting"}) + insertUploads(t, db, types.Upload{ID: 1}) + updateUploads(t, db, types.Upload{ID: 1, State: "deleting"}) logs, err := store.GetAuditLogsForUpload(context.Background(), 1) if err != nil { diff --git a/internal/codeintel/uploads/internal/store/store_commits_test.go b/internal/codeintel/uploads/internal/store/store_commits_test.go index edce3e675ee..469044b5702 100644 --- a/internal/codeintel/uploads/internal/store/store_commits_test.go +++ b/internal/codeintel/uploads/internal/store/store_commits_test.go @@ -14,6 +14,7 @@ import ( "github.com/sourcegraph/log/logtest" "github.com/sourcegraph/sourcegraph/internal/codeintel/commitgraph" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" @@ -31,12 +32,12 @@ func TestGetStaleSourcedCommits(t *testing.T) { now := time.Unix(1587396557, 0).UTC() insertUploads(t, db, - shared.Upload{ID: 1, RepositoryID: 50, Commit: makeCommit(1)}, - shared.Upload{ID: 2, RepositoryID: 50, Commit: makeCommit(1), Root: "sub/"}, - shared.Upload{ID: 3, RepositoryID: 51, Commit: makeCommit(4)}, - shared.Upload{ID: 4, RepositoryID: 51, Commit: makeCommit(5)}, - shared.Upload{ID: 5, RepositoryID: 52, Commit: makeCommit(7)}, - shared.Upload{ID: 6, RepositoryID: 52, Commit: makeCommit(8)}, + types.Upload{ID: 1, RepositoryID: 50, Commit: makeCommit(1)}, + types.Upload{ID: 2, RepositoryID: 50, Commit: makeCommit(1), Root: "sub/"}, + types.Upload{ID: 3, RepositoryID: 51, Commit: makeCommit(4)}, + types.Upload{ID: 4, RepositoryID: 51, Commit: makeCommit(5)}, + types.Upload{ID: 5, RepositoryID: 52, Commit: makeCommit(7)}, + types.Upload{ID: 6, RepositoryID: 52, Commit: makeCommit(8)}, ) sourcedCommits, err := store.GetStaleSourcedCommits(context.Background(), time.Minute, 5, now) @@ -85,12 +86,12 @@ func TestUpdateSourcedCommits(t *testing.T) { now := time.Unix(1587396557, 0).UTC() insertUploads(t, db, - shared.Upload{ID: 1, RepositoryID: 50, Commit: makeCommit(1)}, - shared.Upload{ID: 2, RepositoryID: 50, Commit: makeCommit(1), Root: "sub/"}, - shared.Upload{ID: 3, RepositoryID: 51, Commit: makeCommit(4)}, - shared.Upload{ID: 4, RepositoryID: 51, Commit: makeCommit(5)}, - shared.Upload{ID: 5, RepositoryID: 52, Commit: makeCommit(7)}, - shared.Upload{ID: 6, RepositoryID: 52, Commit: makeCommit(7), State: "uploading"}, + types.Upload{ID: 1, RepositoryID: 50, Commit: makeCommit(1)}, + types.Upload{ID: 2, RepositoryID: 50, Commit: makeCommit(1), Root: "sub/"}, + types.Upload{ID: 3, RepositoryID: 51, Commit: makeCommit(4)}, + types.Upload{ID: 4, RepositoryID: 51, Commit: makeCommit(5)}, + types.Upload{ID: 5, RepositoryID: 52, Commit: makeCommit(7)}, + types.Upload{ID: 6, RepositoryID: 52, Commit: makeCommit(7), State: "uploading"}, ) uploadsUpdated, err := store.UpdateSourcedCommits(context.Background(), 50, makeCommit(1), now) @@ -127,13 +128,13 @@ func TestDeleteSourcedCommits(t *testing.T) { now := time.Unix(1587396557, 0).UTC() insertUploads(t, db, - shared.Upload{ID: 1, RepositoryID: 50, Commit: makeCommit(1)}, - shared.Upload{ID: 2, RepositoryID: 50, Commit: makeCommit(1), Root: "sub/"}, - shared.Upload{ID: 3, RepositoryID: 51, Commit: makeCommit(4)}, - shared.Upload{ID: 4, RepositoryID: 51, Commit: makeCommit(5)}, - shared.Upload{ID: 5, RepositoryID: 52, Commit: makeCommit(7)}, - shared.Upload{ID: 6, RepositoryID: 52, Commit: makeCommit(7), State: "uploading", UploadedAt: now.Add(-time.Minute * 90)}, - shared.Upload{ID: 7, RepositoryID: 52, Commit: makeCommit(7), State: "queued", UploadedAt: now.Add(-time.Minute * 30)}, + types.Upload{ID: 1, RepositoryID: 50, Commit: makeCommit(1)}, + types.Upload{ID: 2, RepositoryID: 50, Commit: makeCommit(1), Root: "sub/"}, + types.Upload{ID: 3, RepositoryID: 51, Commit: makeCommit(4)}, + types.Upload{ID: 4, RepositoryID: 51, Commit: makeCommit(5)}, + types.Upload{ID: 5, RepositoryID: 52, Commit: makeCommit(7)}, + types.Upload{ID: 6, RepositoryID: 52, Commit: makeCommit(7), State: "uploading", UploadedAt: now.Add(-time.Minute * 90)}, + types.Upload{ID: 7, RepositoryID: 52, Commit: makeCommit(7), State: "queued", UploadedAt: now.Add(-time.Minute * 30)}, ) uploadsUpdated, uploadsDeleted, err := store.DeleteSourcedCommits(context.Background(), 52, makeCommit(7), time.Hour, now) @@ -176,14 +177,14 @@ func TestGetOldestCommitDate(t *testing.T) { t4 := t1.Add(time.Minute * 6) insertUploads(t, db, - shared.Upload{ID: 1, State: "completed"}, - shared.Upload{ID: 2, State: "completed"}, - shared.Upload{ID: 3, State: "completed"}, - shared.Upload{ID: 4, State: "errored"}, - shared.Upload{ID: 5, State: "completed"}, - shared.Upload{ID: 6, State: "completed", RepositoryID: 51}, - shared.Upload{ID: 7, State: "completed", RepositoryID: 51}, - shared.Upload{ID: 8, State: "completed", RepositoryID: 51}, + types.Upload{ID: 1, State: "completed"}, + types.Upload{ID: 2, State: "completed"}, + types.Upload{ID: 3, State: "completed"}, + types.Upload{ID: 4, State: "errored"}, + types.Upload{ID: 5, State: "completed"}, + types.Upload{ID: 6, State: "completed", RepositoryID: 51}, + types.Upload{ID: 7, State: "completed", RepositoryID: 51}, + types.Upload{ID: 8, State: "completed", RepositoryID: 51}, ) if _, err := db.ExecContext(context.Background(), "UPDATE lsif_uploads SET committed_at = '-infinity' WHERE id = 3"); err != nil { @@ -284,7 +285,7 @@ func TestHasCommit(t *testing.T) { } // insertUploads populates the lsif_uploads table with the given upload models. -func insertUploads(t testing.TB, db database.DB, uploads ...shared.Upload) { +func insertUploads(t testing.TB, db database.DB, uploads ...types.Upload) { for _, upload := range uploads { if upload.Commit == "" { upload.Commit = makeCommit(upload.ID) @@ -356,7 +357,7 @@ func insertUploads(t testing.TB, db database.DB, uploads ...shared.Upload) { } } -func updateUploads(t testing.TB, db database.DB, uploads ...shared.Upload) { +func updateUploads(t testing.TB, db database.DB, uploads ...types.Upload) { for _, upload := range uploads { query := sqlf.Sprintf(` UPDATE lsif_uploads diff --git a/internal/codeintel/uploads/internal/store/store_dumps.go b/internal/codeintel/uploads/internal/store/store_dumps.go index 25dd08ef68b..957ff1defc5 100644 --- a/internal/codeintel/uploads/internal/store/store_dumps.go +++ b/internal/codeintel/uploads/internal/store/store_dumps.go @@ -10,7 +10,7 @@ import ( "github.com/opentracing/opentracing-go/log" "github.com/sourcegraph/sourcegraph/internal/codeintel/commitgraph" - "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/dbutil" "github.com/sourcegraph/sourcegraph/internal/env" @@ -40,7 +40,7 @@ import ( // It is possible for some dumps to overlap theoretically, e.g. if someone uploads one dump covering the repository root and then later // splits the repository into multiple dumps. For this reason, the returned dumps are always sorted in most-recently-finished order to // prevent returning data from stale dumps. -func (s *store) FindClosestDumps(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string) (_ []shared.Dump, err error) { +func (s *store) FindClosestDumps(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string) (_ []types.Dump, err error) { ctx, trace, endObservation := s.operations.findClosestDumps.With(ctx, &err, observation.Args{ LogFields: []log.Field{ log.Int("repositoryID", repositoryID), @@ -94,7 +94,7 @@ ORDER BY u.finished_at DESC // FindClosestDumpsFromGraphFragment returns the set of dumps that can most accurately answer queries for the given repository, commit, // path, and optional indexer by only considering the given fragment of the full git graph. See FindClosestDumps for additional details. -func (s *store) FindClosestDumpsFromGraphFragment(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string, commitGraph *gitdomain.CommitGraph) (_ []shared.Dump, err error) { +func (s *store) FindClosestDumpsFromGraphFragment(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string, commitGraph *gitdomain.CommitGraph) (_ []types.Dump, err error) { ctx, trace, endObservation := s.operations.findClosestDumpsFromGraphFragment.With(ctx, &err, observation.Args{ LogFields: []log.Field{ log.Int("repositoryID", repositoryID), @@ -189,7 +189,7 @@ WHERE u.id IN (%s) AND %s var DefinitionDumpsLimit, _ = strconv.ParseInt(env.Get("PRECISE_CODE_INTEL_DEFINITION_DUMPS_LIMIT", "100", "The maximum number of dumps that can define the same package."), 10, 64) // GetDumpsWithDefinitionsForMonikers returns the set of dumps that define at least one of the given monikers. -func (s *store) GetDumpsWithDefinitionsForMonikers(ctx context.Context, monikers []precise.QualifiedMonikerData) (_ []shared.Dump, err error) { +func (s *store) GetDumpsWithDefinitionsForMonikers(ctx context.Context, monikers []precise.QualifiedMonikerData) (_ []types.Dump, err error) { ctx, trace, endObservation := s.operations.getDumpsWithDefinitionsForMonikers.With(ctx, &err, observation.Args{LogFields: []log.Field{ log.Int("numMonikers", len(monikers)), log.String("monikers", monikersToString(monikers)), @@ -270,7 +270,7 @@ WHERE u.id IN (SELECT id FROM canonical_uploads) ` // GetDumpsByIDs returns a set of dumps by identifiers. -func (s *store) GetDumpsByIDs(ctx context.Context, ids []int) (_ []shared.Dump, err error) { +func (s *store) GetDumpsByIDs(ctx context.Context, ids []int) (_ []types.Dump, err error) { ctx, trace, endObservation := s.operations.getDumpsByIDs.With(ctx, &err, observation.Args{LogFields: []log.Field{ log.Int("numIDs", len(ids)), log.String("ids", intsToString(ids)), diff --git a/internal/codeintel/uploads/internal/store/store_dumps_test.go b/internal/codeintel/uploads/internal/store/store_dumps_test.go index 00d4cd91496..3442a0b4135 100644 --- a/internal/codeintel/uploads/internal/store/store_dumps_test.go +++ b/internal/codeintel/uploads/internal/store/store_dumps_test.go @@ -15,7 +15,7 @@ import ( "github.com/sourcegraph/sourcegraph/cmd/frontend/globals" "github.com/sourcegraph/sourcegraph/internal/codeintel/commitgraph" - "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/database/dbutil" @@ -41,7 +41,7 @@ func TestGetDumpsByIDs(t *testing.T) { startedAt := uploadedAt.Add(time.Minute) finishedAt := uploadedAt.Add(time.Minute * 2) expectedAssociatedIndexID := 42 - expected1 := shared.Dump{ + expected1 := types.Dump{ ID: 1, Commit: makeCommit(1), Root: "sub/", @@ -57,7 +57,7 @@ func TestGetDumpsByIDs(t *testing.T) { IndexerVersion: "latest", AssociatedIndexID: &expectedAssociatedIndexID, } - expected2 := shared.Dump{ + expected2 := types.Dump{ ID: 2, Commit: makeCommit(2), Root: "other/", @@ -107,7 +107,7 @@ func TestFindClosestDumps(t *testing.T) { // | | | // +-- [3] -- 4 --+ +--- 8 - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(1)}, {ID: 2, Commit: makeCommit(3)}, {ID: 3, Commit: makeCommit(7)}, @@ -175,7 +175,7 @@ func TestFindClosestDumpsAlternateCommitGraph(t *testing.T) { // | // +-- 7 -- 8 - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(2)}, } insertUploads(t, db, uploads...) @@ -231,7 +231,7 @@ func TestFindClosestDumpsAlternateCommitGraphWithOverwrittenVisibleUploads(t *te // // 1 -- [2] -- 3 -- 4 -- [5] - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(2)}, {ID: 2, Commit: makeCommit(5)}, } @@ -284,7 +284,7 @@ func TestFindClosestDumpsDistinctRoots(t *testing.T) { // // [1] -- 2 - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(1), Root: "root1/"}, {ID: 2, Commit: makeCommit(1), Root: "root2/"}, } @@ -350,7 +350,7 @@ func TestFindClosestDumpsOverlappingRoots(t *testing.T) { // | 8 | 5 | root2/ | lsif-go | (overwrites root2/ at commit 2) // | 9 | 6 | root1/ | lsif-go | (overwrites root1/ at commit 2) - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(1), Indexer: "lsif-go", Root: "root3/"}, {ID: 2, Commit: makeCommit(1), Indexer: "scip-python", Root: "root4/"}, {ID: 3, Commit: makeCommit(2), Indexer: "lsif-go", Root: "root1/"}, @@ -414,7 +414,7 @@ func TestFindClosestDumpsIndexerName(t *testing.T) { // // [1] --+-- [2] --+-- [3] --+-- [4] --+-- 5 - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(1), Root: "root1/", Indexer: "idx1"}, {ID: 2, Commit: makeCommit(2), Root: "root2/", Indexer: "idx1"}, {ID: 3, Commit: makeCommit(3), Root: "root3/", Indexer: "idx1"}, @@ -503,7 +503,7 @@ func TestFindClosestDumpsIntersectingPath(t *testing.T) { // // [1] - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(1), Root: "web/src/", Indexer: "lsif-eslint"}, } insertUploads(t, db, uploads...) @@ -551,7 +551,7 @@ func TestFindClosestDumpsFromGraphFragment(t *testing.T) { // | || / // +-- [5] -- 6 --- || -----+ - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(1)}, {ID: 2, Commit: makeCommit(5)}, } @@ -639,7 +639,7 @@ func TestDefinitionDumps(t *testing.T) { uploadedAt := time.Unix(1587396557, 0).UTC() startedAt := uploadedAt.Add(time.Minute) finishedAt := uploadedAt.Add(time.Minute * 2) - expected1 := shared.Dump{ + expected1 := types.Dump{ ID: 1, Commit: makeCommit(1), Root: "sub/", @@ -654,7 +654,7 @@ func TestDefinitionDumps(t *testing.T) { Indexer: "lsif-go", IndexerVersion: "latest", } - expected2 := shared.Dump{ + expected2 := types.Dump{ ID: 2, Commit: makeCommit(2), Root: "other/", @@ -670,7 +670,7 @@ func TestDefinitionDumps(t *testing.T) { IndexerVersion: "1.2.3", AssociatedIndexID: nil, } - expected3 := shared.Dump{ + expected3 := types.Dump{ ID: 3, Commit: makeCommit(3), Root: "sub/", @@ -742,8 +742,8 @@ func TestDefinitionDumps(t *testing.T) { }) } -func dumpToUpload(expected shared.Dump) shared.Upload { - return shared.Upload{ +func dumpToUpload(expected types.Dump) types.Upload { + return types.Upload{ ID: expected.ID, Commit: expected.Commit, Root: expected.Root, @@ -763,7 +763,7 @@ func dumpToUpload(expected shared.Dump) shared.Upload { } } -func toCommitGraphView(uploads []shared.Upload) *commitgraph.CommitGraphView { +func toCommitGraphView(uploads []types.Upload) *commitgraph.CommitGraphView { commitGraphView := commitgraph.NewCommitGraphView() for _, upload := range uploads { commitGraphView.Add(commitgraph.UploadMeta{UploadID: upload.ID}, upload.Commit, fmt.Sprintf("%s:%s", upload.Root, upload.Indexer)) @@ -860,7 +860,7 @@ func testFindClosestDumps(t *testing.T, store Store, testCases []FindClosestDump testCase.indexer, ) - assertDumpIDs := func(t *testing.T, dumps []shared.Dump) { + assertDumpIDs := func(t *testing.T, dumps []types.Dump) { if len(testCase.anyOfIDs) > 0 { testAnyOf(t, dumps, testCase.anyOfIDs) return @@ -901,7 +901,7 @@ func testFindClosestDumps(t *testing.T, store Store, testCases []FindClosestDump } } -func testAnyOf(t *testing.T, dumps []shared.Dump, expectedIDs []int) { +func testAnyOf(t *testing.T, dumps []types.Dump, expectedIDs []int) { if len(dumps) != 1 { t.Errorf("unexpected nearest dump length. want=%d have=%d", 1, len(dumps)) return @@ -922,7 +922,7 @@ func testPresence(needle int, haystack []int) bool { return false } -func testAllOf(t *testing.T, dumps []shared.Dump, expectedIDs []int) { +func testAllOf(t *testing.T, dumps []types.Dump, expectedIDs []int) { if len(dumps) != len(expectedIDs) { t.Errorf("unexpected nearest dump length. want=%d have=%d", 1, len(dumps)) } diff --git a/internal/codeintel/uploads/internal/store/store_packages_test.go b/internal/codeintel/uploads/internal/store/store_packages_test.go index c2ac47a4656..7e2d877dc46 100644 --- a/internal/codeintel/uploads/internal/store/store_packages_test.go +++ b/internal/codeintel/uploads/internal/store/store_packages_test.go @@ -6,6 +6,7 @@ import ( "github.com/sourcegraph/log/logtest" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" @@ -20,7 +21,7 @@ func TestUpdatePackages(t *testing.T) { store := New(db, &observation.TestContext) // for foreign key relation - insertUploads(t, db, shared.Upload{ID: 42}) + insertUploads(t, db, types.Upload{ID: 42}) if err := store.UpdatePackages(context.Background(), 42, []precise.Package{ {Scheme: "s0", Name: "n0", Version: "v0"}, diff --git a/internal/codeintel/uploads/internal/store/store_references_test.go b/internal/codeintel/uploads/internal/store/store_references_test.go index 1ab4d7cf9e2..25309200092 100644 --- a/internal/codeintel/uploads/internal/store/store_references_test.go +++ b/internal/codeintel/uploads/internal/store/store_references_test.go @@ -6,7 +6,7 @@ import ( "github.com/sourcegraph/log/logtest" - "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" @@ -20,7 +20,7 @@ func TestUpdatePackageReferences(t *testing.T) { store := New(db, &observation.TestContext) // for foreign key relation - insertUploads(t, db, shared.Upload{ID: 42}) + insertUploads(t, db, types.Upload{ID: 42}) if err := store.UpdatePackageReferences(context.Background(), 42, []precise.PackageReference{ {Package: precise.Package{Scheme: "s0", Name: "n0", Version: "v0"}}, diff --git a/internal/codeintel/uploads/internal/store/store_repositories_test.go b/internal/codeintel/uploads/internal/store/store_repositories_test.go index 23042a096a6..50adb013bdb 100644 --- a/internal/codeintel/uploads/internal/store/store_repositories_test.go +++ b/internal/codeintel/uploads/internal/store/store_repositories_test.go @@ -11,7 +11,7 @@ import ( "github.com/keegancsmith/sqlf" "github.com/sourcegraph/log/logtest" - "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/dbtest" "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" @@ -334,8 +334,8 @@ func TestHasRepository(t *testing.T) { {52, false}, } - insertUploads(t, db, shared.Upload{ID: 1, RepositoryID: 50}) - insertUploads(t, db, shared.Upload{ID: 2, RepositoryID: 51, State: "deleted"}) + insertUploads(t, db, types.Upload{ID: 1, RepositoryID: 50}) + insertUploads(t, db, types.Upload{ID: 2, RepositoryID: 51, State: "deleted"}) for _, testCase := range testCases { name := fmt.Sprintf("repositoryID=%d", testCase.repositoryID) @@ -358,12 +358,12 @@ func TestSetRepositoriesForRetentionScan(t *testing.T) { store := New(db, &observation.TestContext) insertUploads(t, db, - shared.Upload{ID: 1, RepositoryID: 50, State: "completed"}, - shared.Upload{ID: 2, RepositoryID: 51, State: "completed"}, - shared.Upload{ID: 3, RepositoryID: 52, State: "completed"}, - shared.Upload{ID: 4, RepositoryID: 53, State: "completed"}, - shared.Upload{ID: 5, RepositoryID: 54, State: "errored"}, - shared.Upload{ID: 6, RepositoryID: 54, State: "deleted"}, + types.Upload{ID: 1, RepositoryID: 50, State: "completed"}, + types.Upload{ID: 2, RepositoryID: 51, State: "completed"}, + types.Upload{ID: 3, RepositoryID: 52, State: "completed"}, + types.Upload{ID: 4, RepositoryID: 53, State: "completed"}, + types.Upload{ID: 5, RepositoryID: 54, State: "errored"}, + types.Upload{ID: 6, RepositoryID: 54, State: "deleted"}, ) now := timeutil.Now() diff --git a/internal/codeintel/uploads/internal/store/store_uploads.go b/internal/codeintel/uploads/internal/store/store_uploads.go index 4fdba2c777d..929b6f4ee74 100644 --- a/internal/codeintel/uploads/internal/store/store_uploads.go +++ b/internal/codeintel/uploads/internal/store/store_uploads.go @@ -14,6 +14,7 @@ import ( "golang.org/x/sync/errgroup" "github.com/sourcegraph/sourcegraph/internal/codeintel/commitgraph" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" @@ -26,7 +27,7 @@ import ( ) // GetUploads returns a list of uploads and the total count of records matching the given conditions. -func (s *store) GetUploads(ctx context.Context, opts shared.GetUploadsOptions) (uploads []shared.Upload, totalCount int, err error) { +func (s *store) GetUploads(ctx context.Context, opts types.GetUploadsOptions) (uploads []types.Upload, totalCount int, err error) { ctx, trace, endObservation := s.operations.getUploads.With(ctx, &err, observation.Args{LogFields: buildLogFields(opts)}) defer endObservation(1, observation.Args{}) @@ -194,13 +195,13 @@ WHERE ` // GetUploadByID returns an upload by its identifier and boolean flag indicating its existence. -func (s *store) GetUploadByID(ctx context.Context, id int) (_ shared.Upload, _ bool, err error) { +func (s *store) GetUploadByID(ctx context.Context, id int) (_ types.Upload, _ bool, err error) { ctx, _, endObservation := s.operations.getUploadByID.With(ctx, &err, observation.Args{LogFields: []log.Field{log.Int("id", id)}}) defer endObservation(1, observation.Args{}) authzConds, err := database.AuthzQueryConds(ctx, database.NewDBWith(s.logger, s.db)) if err != nil { - return shared.Upload{}, false, err + return types.Upload{}, false, err } return scanFirstUpload(s.db.Query(ctx, sqlf.Sprintf(getUploadByIDQuery, id, authzConds))) @@ -240,7 +241,7 @@ WHERE repo.deleted_at IS NULL AND u.state != 'deleted' AND u.id = %s AND %s // GetUploadsByIDs returns an upload for each of the given identifiers. Not all given ids will necessarily // have a corresponding element in the returned list. -func (s *store) GetUploadsByIDs(ctx context.Context, ids ...int) (_ []shared.Upload, err error) { +func (s *store) GetUploadsByIDs(ctx context.Context, ids ...int) (_ []types.Upload, err error) { ctx, _, endObservation := s.operations.getUploadsByIDs.With(ctx, &err, observation.Args{LogFields: []log.Field{ log.String("ids", intsToString(ids)), }}) @@ -1898,7 +1899,7 @@ func nilTimeToString(t *time.Time) string { return t.String() } -func buildConditionsAndCte(opts shared.GetUploadsOptions) (*sqlf.Query, []*sqlf.Query, []cteDefinition) { +func buildConditionsAndCte(opts types.GetUploadsOptions) (*sqlf.Query, []*sqlf.Query, []cteDefinition) { conds := make([]*sqlf.Query, 0, 12) allowDeletedUploads := (opts.AllowDeletedUpload && opts.State == "") || opts.State == "deleted" @@ -2065,7 +2066,7 @@ func buildCTEPrefix(cteDefinitions []cteDefinition) *sqlf.Query { return sqlf.Sprintf("WITH\n%s", sqlf.Join(cteQueries, ",\n")) } -func buildLogFields(opts shared.GetUploadsOptions) []log.Field { +func buildLogFields(opts types.GetUploadsOptions) []log.Field { return []log.Field{ log.Int("repositoryID", opts.RepositoryID), log.String("state", opts.State), diff --git a/internal/codeintel/uploads/internal/store/store_uploads_test.go b/internal/codeintel/uploads/internal/store/store_uploads_test.go index bc0b93f3cb0..0ffe55db6b4 100644 --- a/internal/codeintel/uploads/internal/store/store_uploads_test.go +++ b/internal/codeintel/uploads/internal/store/store_uploads_test.go @@ -22,6 +22,7 @@ import ( "github.com/sourcegraph/sourcegraph/cmd/frontend/globals" "github.com/sourcegraph/sourcegraph/internal/codeintel/commitgraph" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" "github.com/sourcegraph/sourcegraph/internal/database" "github.com/sourcegraph/sourcegraph/internal/database/basestore" @@ -52,33 +53,33 @@ func TestGetUploads(t *testing.T) { failureMessage := "unlucky 333" insertUploads(t, db, - shared.Upload{ID: 1, Commit: makeCommit(3331), UploadedAt: t1, Root: "sub1/", State: "queued"}, - shared.Upload{ID: 2, UploadedAt: t2, FinishedAt: &t1, State: "errored", FailureMessage: &failureMessage, Indexer: "scip-typescript"}, - shared.Upload{ID: 3, Commit: makeCommit(3333), UploadedAt: t3, Root: "sub2/", State: "queued"}, - shared.Upload{ID: 4, UploadedAt: t4, State: "queued", RepositoryID: 51, RepositoryName: "foo bar x"}, - shared.Upload{ID: 5, Commit: makeCommit(3333), UploadedAt: t5, Root: "sub1/", State: "processing", Indexer: "scip-typescript"}, - shared.Upload{ID: 6, UploadedAt: t6, Root: "sub2/", State: "processing", RepositoryID: 52, RepositoryName: "foo bar y"}, - shared.Upload{ID: 7, UploadedAt: t7, FinishedAt: &t4, Root: "sub1/", Indexer: "scip-typescript"}, - shared.Upload{ID: 8, UploadedAt: t8, FinishedAt: &t4, Indexer: "scip-typescript"}, - shared.Upload{ID: 9, UploadedAt: t9, State: "queued"}, - shared.Upload{ID: 10, UploadedAt: t10, FinishedAt: &t6, Root: "sub1/", Indexer: "scip-typescript"}, - shared.Upload{ID: 11, UploadedAt: t11, FinishedAt: &t6, Root: "sub1/", Indexer: "scip-typescript"}, + types.Upload{ID: 1, Commit: makeCommit(3331), UploadedAt: t1, Root: "sub1/", State: "queued"}, + types.Upload{ID: 2, UploadedAt: t2, FinishedAt: &t1, State: "errored", FailureMessage: &failureMessage, Indexer: "scip-typescript"}, + types.Upload{ID: 3, Commit: makeCommit(3333), UploadedAt: t3, Root: "sub2/", State: "queued"}, + types.Upload{ID: 4, UploadedAt: t4, State: "queued", RepositoryID: 51, RepositoryName: "foo bar x"}, + types.Upload{ID: 5, Commit: makeCommit(3333), UploadedAt: t5, Root: "sub1/", State: "processing", Indexer: "scip-typescript"}, + types.Upload{ID: 6, UploadedAt: t6, Root: "sub2/", State: "processing", RepositoryID: 52, RepositoryName: "foo bar y"}, + types.Upload{ID: 7, UploadedAt: t7, FinishedAt: &t4, Root: "sub1/", Indexer: "scip-typescript"}, + types.Upload{ID: 8, UploadedAt: t8, FinishedAt: &t4, Indexer: "scip-typescript"}, + types.Upload{ID: 9, UploadedAt: t9, State: "queued"}, + types.Upload{ID: 10, UploadedAt: t10, FinishedAt: &t6, Root: "sub1/", Indexer: "scip-typescript"}, + types.Upload{ID: 11, UploadedAt: t11, FinishedAt: &t6, Root: "sub1/", Indexer: "scip-typescript"}, // Deleted duplicates - shared.Upload{ID: 12, Commit: makeCommit(3331), UploadedAt: t1, FinishedAt: &t1, Root: "sub1/", State: "deleted"}, - shared.Upload{ID: 13, UploadedAt: t2, FinishedAt: &t1, State: "deleted", FailureMessage: &failureMessage, Indexer: "scip-typescript"}, - shared.Upload{ID: 14, Commit: makeCommit(3333), UploadedAt: t3, FinishedAt: &t2, Root: "sub2/", State: "deleted"}, + types.Upload{ID: 12, Commit: makeCommit(3331), UploadedAt: t1, FinishedAt: &t1, Root: "sub1/", State: "deleted"}, + types.Upload{ID: 13, UploadedAt: t2, FinishedAt: &t1, State: "deleted", FailureMessage: &failureMessage, Indexer: "scip-typescript"}, + types.Upload{ID: 14, Commit: makeCommit(3333), UploadedAt: t3, FinishedAt: &t2, Root: "sub2/", State: "deleted"}, // deleted repo - shared.Upload{ID: 15, Commit: makeCommit(3334), UploadedAt: t4, State: "deleted", RepositoryID: 53, RepositoryName: "DELETED-barfoo"}, + types.Upload{ID: 15, Commit: makeCommit(3334), UploadedAt: t4, State: "deleted", RepositoryID: 53, RepositoryName: "DELETED-barfoo"}, // to-be hard deleted - shared.Upload{ID: 16, Commit: makeCommit(3333), UploadedAt: t4, FinishedAt: &t3, State: "deleted"}, - shared.Upload{ID: 17, Commit: makeCommit(3334), UploadedAt: t4, FinishedAt: &t5, State: "deleting"}, + types.Upload{ID: 16, Commit: makeCommit(3333), UploadedAt: t4, FinishedAt: &t3, State: "deleted"}, + types.Upload{ID: 17, Commit: makeCommit(3334), UploadedAt: t4, FinishedAt: &t5, State: "deleting"}, ) insertVisibleAtTip(t, db, 50, 2, 5, 7, 8) - updateUploads(t, db, shared.Upload{ + updateUploads(t, db, types.Upload{ ID: 17, State: "deleted", }) @@ -178,7 +179,7 @@ func TestGetUploads(t *testing.T) { ) t.Run(name, func(t *testing.T) { - uploads, totalCount, err := store.GetUploads(ctx, shared.GetUploadsOptions{ + uploads, totalCount, err := store.GetUploads(ctx, types.GetUploadsOptions{ RepositoryID: testCase.repositoryID, State: testCase.state, Term: testCase.term, @@ -237,7 +238,7 @@ func TestGetUploads(t *testing.T) { defer globals.SetPermissionsUserMapping(before) uploads, totalCount, err := store.GetUploads(ctx, - shared.GetUploadsOptions{ + types.GetUploadsOptions{ Limit: 1, }, ) @@ -265,7 +266,7 @@ func TestGetUploadByID(t *testing.T) { uploadedAt := time.Unix(1587396557, 0).UTC() startedAt := uploadedAt.Add(time.Minute) - expected := shared.Upload{ + expected := types.Upload{ ID: 1, Commit: makeCommit(1), Root: "sub/", @@ -327,7 +328,7 @@ func TestGetUploadByIDDeleted(t *testing.T) { uploadedAt := time.Unix(1587396557, 0).UTC() startedAt := uploadedAt.Add(time.Minute) - expected := shared.Upload{ + expected := types.Upload{ ID: 1, Commit: makeCommit(1), Root: "sub/", @@ -369,13 +370,13 @@ func TestGetQueuedUploadRank(t *testing.T) { t7 := t1.Add(+time.Minute * 5) insertUploads(t, db, - shared.Upload{ID: 1, UploadedAt: t1, State: "queued"}, - shared.Upload{ID: 2, UploadedAt: t2, State: "queued"}, - shared.Upload{ID: 3, UploadedAt: t3, State: "queued"}, - shared.Upload{ID: 4, UploadedAt: t4, State: "queued"}, - shared.Upload{ID: 5, UploadedAt: t5, State: "queued"}, - shared.Upload{ID: 6, UploadedAt: t6, State: "processing"}, - shared.Upload{ID: 7, UploadedAt: t1, State: "queued", ProcessAfter: &t7}, + types.Upload{ID: 1, UploadedAt: t1, State: "queued"}, + types.Upload{ID: 2, UploadedAt: t2, State: "queued"}, + types.Upload{ID: 3, UploadedAt: t3, State: "queued"}, + types.Upload{ID: 4, UploadedAt: t4, State: "queued"}, + types.Upload{ID: 5, UploadedAt: t5, State: "queued"}, + types.Upload{ID: 6, UploadedAt: t6, State: "processing"}, + types.Upload{ID: 7, UploadedAt: t1, State: "queued", ProcessAfter: &t7}, ) if upload, _, _ := store.GetUploadByID(context.Background(), 1); upload.Rank == nil || *upload.Rank != 1 { @@ -412,16 +413,16 @@ func TestGetUploadsByIDs(t *testing.T) { store := New(db, &observation.TestContext) insertUploads(t, db, - shared.Upload{ID: 1}, - shared.Upload{ID: 2}, - shared.Upload{ID: 3}, - shared.Upload{ID: 4}, - shared.Upload{ID: 5}, - shared.Upload{ID: 6}, - shared.Upload{ID: 7}, - shared.Upload{ID: 8}, - shared.Upload{ID: 9}, - shared.Upload{ID: 10}, + types.Upload{ID: 1}, + types.Upload{ID: 2}, + types.Upload{ID: 3}, + types.Upload{ID: 4}, + types.Upload{ID: 5}, + types.Upload{ID: 6}, + types.Upload{ID: 7}, + types.Upload{ID: 8}, + types.Upload{ID: 9}, + types.Upload{ID: 10}, ) t.Run("fetch", func(t *testing.T) { @@ -464,10 +465,10 @@ func TestDeleteUploadsWithoutRepository(t *testing.T) { db := database.NewDB(logger, dbtest.NewDB(logger, t)) store := New(db, &observation.TestContext) - var uploads []shared.Upload + var uploads []types.Upload for i := 0; i < 25; i++ { for j := 0; j < 10+i; j++ { - uploads = append(uploads, shared.Upload{ID: len(uploads) + 1, RepositoryID: 50 + i}) + uploads = append(uploads, types.Upload{ID: len(uploads) + 1, RepositoryID: 50 + i}) } } insertUploads(t, db, uploads...) @@ -550,7 +551,7 @@ func TestRecentUploadsSummary(t *testing.T) { r1 := 1 r2 := 2 - addDefaults := func(upload shared.Upload) shared.Upload { + addDefaults := func(upload types.Upload) types.Upload { upload.Commit = makeCommit(upload.ID) upload.RepositoryID = 50 upload.RepositoryName = "n-50" @@ -559,17 +560,17 @@ func TestRecentUploadsSummary(t *testing.T) { return upload } - uploads := []shared.Upload{ - addDefaults(shared.Upload{ID: 150, UploadedAt: t0, Root: "r1", Indexer: "i1", State: "queued", Rank: &r2}), // visible (group 1) - addDefaults(shared.Upload{ID: 151, UploadedAt: t1, Root: "r1", Indexer: "i1", State: "queued", Rank: &r1}), // visible (group 1) - addDefaults(shared.Upload{ID: 152, FinishedAt: &t2, Root: "r1", Indexer: "i1", State: "errored"}), // visible (group 1) - addDefaults(shared.Upload{ID: 153, FinishedAt: &t3, Root: "r1", Indexer: "i2", State: "completed"}), // visible (group 2) - addDefaults(shared.Upload{ID: 154, FinishedAt: &t4, Root: "r2", Indexer: "i1", State: "completed"}), // visible (group 3) - addDefaults(shared.Upload{ID: 155, FinishedAt: &t5, Root: "r2", Indexer: "i1", State: "errored"}), // shadowed - addDefaults(shared.Upload{ID: 156, FinishedAt: &t6, Root: "r2", Indexer: "i2", State: "completed"}), // visible (group 4) - addDefaults(shared.Upload{ID: 157, FinishedAt: &t7, Root: "r2", Indexer: "i2", State: "errored"}), // shadowed - addDefaults(shared.Upload{ID: 158, FinishedAt: &t8, Root: "r2", Indexer: "i2", State: "errored"}), // shadowed - addDefaults(shared.Upload{ID: 159, FinishedAt: &t9, Root: "r2", Indexer: "i2", State: "errored"}), // shadowed + uploads := []types.Upload{ + addDefaults(types.Upload{ID: 150, UploadedAt: t0, Root: "r1", Indexer: "i1", State: "queued", Rank: &r2}), // visible (group 1) + addDefaults(types.Upload{ID: 151, UploadedAt: t1, Root: "r1", Indexer: "i1", State: "queued", Rank: &r1}), // visible (group 1) + addDefaults(types.Upload{ID: 152, FinishedAt: &t2, Root: "r1", Indexer: "i1", State: "errored"}), // visible (group 1) + addDefaults(types.Upload{ID: 153, FinishedAt: &t3, Root: "r1", Indexer: "i2", State: "completed"}), // visible (group 2) + addDefaults(types.Upload{ID: 154, FinishedAt: &t4, Root: "r2", Indexer: "i1", State: "completed"}), // visible (group 3) + addDefaults(types.Upload{ID: 155, FinishedAt: &t5, Root: "r2", Indexer: "i1", State: "errored"}), // shadowed + addDefaults(types.Upload{ID: 156, FinishedAt: &t6, Root: "r2", Indexer: "i2", State: "completed"}), // visible (group 4) + addDefaults(types.Upload{ID: 157, FinishedAt: &t7, Root: "r2", Indexer: "i2", State: "errored"}), // shadowed + addDefaults(types.Upload{ID: 158, FinishedAt: &t8, Root: "r2", Indexer: "i2", State: "errored"}), // shadowed + addDefaults(types.Upload{ID: 159, FinishedAt: &t9, Root: "r2", Indexer: "i2", State: "errored"}), // shadowed } insertUploads(t, db, uploads...) @@ -579,10 +580,10 @@ func TestRecentUploadsSummary(t *testing.T) { } expected := []shared.UploadsWithRepositoryNamespace{ - {Root: "r1", Indexer: "i1", Uploads: []shared.Upload{uploads[0], uploads[1], uploads[2]}}, - {Root: "r1", Indexer: "i2", Uploads: []shared.Upload{uploads[3]}}, - {Root: "r2", Indexer: "i1", Uploads: []shared.Upload{uploads[4]}}, - {Root: "r2", Indexer: "i2", Uploads: []shared.Upload{uploads[6]}}, + {Root: "r1", Indexer: "i1", Uploads: []types.Upload{uploads[0], uploads[1], uploads[2]}}, + {Root: "r1", Indexer: "i2", Uploads: []types.Upload{uploads[3]}}, + {Root: "r2", Indexer: "i1", Uploads: []types.Upload{uploads[4]}}, + {Root: "r2", Indexer: "i2", Uploads: []types.Upload{uploads[6]}}, } if diff := cmp.Diff(expected, summary); diff != "" { t.Errorf("unexpected upload summary (-want +got):\n%s", diff) @@ -601,11 +602,11 @@ func TestDeleteUploadsStuckUploading(t *testing.T) { t5 := t1.Add(time.Minute * 4) insertUploads(t, db, - shared.Upload{ID: 1, Commit: makeCommit(1111), UploadedAt: t1, State: "queued"}, // not uploading - shared.Upload{ID: 2, Commit: makeCommit(1112), UploadedAt: t2, State: "uploading"}, // deleted - shared.Upload{ID: 3, Commit: makeCommit(1113), UploadedAt: t3, State: "uploading"}, // deleted - shared.Upload{ID: 4, Commit: makeCommit(1114), UploadedAt: t4, State: "completed"}, // old, not uploading - shared.Upload{ID: 5, Commit: makeCommit(1115), UploadedAt: t5, State: "uploading"}, // old + types.Upload{ID: 1, Commit: makeCommit(1111), UploadedAt: t1, State: "queued"}, // not uploading + types.Upload{ID: 2, Commit: makeCommit(1112), UploadedAt: t2, State: "uploading"}, // deleted + types.Upload{ID: 3, Commit: makeCommit(1113), UploadedAt: t3, State: "uploading"}, // deleted + types.Upload{ID: 4, Commit: makeCommit(1114), UploadedAt: t4, State: "completed"}, // old, not uploading + types.Upload{ID: 5, Commit: makeCommit(1115), UploadedAt: t5, State: "uploading"}, // old ) count, err := store.DeleteUploadsStuckUploading(context.Background(), t1.Add(time.Minute*3)) @@ -616,7 +617,7 @@ func TestDeleteUploadsStuckUploading(t *testing.T) { t.Errorf("unexpected count. want=%d have=%d", 2, count) } - uploads, totalCount, err := store.GetUploads(context.Background(), shared.GetUploadsOptions{Limit: 5}) + uploads, totalCount, err := store.GetUploads(context.Background(), types.GetUploadsOptions{Limit: 5}) if err != nil { t.Fatalf("unexpected error getting uploads: %s", err) } @@ -643,10 +644,10 @@ func TestHardDeleteUploadsByIDs(t *testing.T) { store := New(db, &observation.TestContext) insertUploads(t, db, - shared.Upload{ID: 51, State: "completed"}, - shared.Upload{ID: 52, State: "completed"}, - shared.Upload{ID: 53, State: "completed"}, - shared.Upload{ID: 54, State: "completed"}, + types.Upload{ID: 51, State: "completed"}, + types.Upload{ID: 52, State: "completed"}, + types.Upload{ID: 53, State: "completed"}, + types.Upload{ID: 54, State: "completed"}, ) insertPackages(t, store, []shared.Package{ {DumpID: 52, Scheme: "test", Name: "p1", Version: "1.2.3"}, @@ -755,12 +756,12 @@ func TestSourcedCommitsWithoutCommittedAt(t *testing.T) { now := time.Unix(1587396557, 0).UTC() insertUploads(t, db, - shared.Upload{ID: 1, RepositoryID: 50, Commit: makeCommit(1), State: "completed"}, - shared.Upload{ID: 2, RepositoryID: 50, Commit: makeCommit(1), State: "completed", Root: "sub/"}, - shared.Upload{ID: 3, RepositoryID: 51, Commit: makeCommit(4), State: "completed"}, - shared.Upload{ID: 4, RepositoryID: 51, Commit: makeCommit(5), State: "completed"}, - shared.Upload{ID: 5, RepositoryID: 52, Commit: makeCommit(7), State: "completed"}, - shared.Upload{ID: 6, RepositoryID: 52, Commit: makeCommit(8), State: "completed"}, + types.Upload{ID: 1, RepositoryID: 50, Commit: makeCommit(1), State: "completed"}, + types.Upload{ID: 2, RepositoryID: 50, Commit: makeCommit(1), State: "completed", Root: "sub/"}, + types.Upload{ID: 3, RepositoryID: 51, Commit: makeCommit(4), State: "completed"}, + types.Upload{ID: 4, RepositoryID: 51, Commit: makeCommit(5), State: "completed"}, + types.Upload{ID: 5, RepositoryID: 52, Commit: makeCommit(7), State: "completed"}, + types.Upload{ID: 6, RepositoryID: 52, Commit: makeCommit(8), State: "completed"}, ) sourcedCommits, err := store.SourcedCommitsWithoutCommittedAt(context.Background(), 5) @@ -803,13 +804,13 @@ func TestSoftDeleteExpiredUploads(t *testing.T) { store := New(db, &observation.TestContext) insertUploads(t, db, - shared.Upload{ID: 50, State: "completed"}, - shared.Upload{ID: 51, State: "completed"}, - shared.Upload{ID: 52, State: "completed"}, - shared.Upload{ID: 53, State: "completed"}, // referenced by 51, 52, 54, 55, 56 - shared.Upload{ID: 54, State: "completed"}, // referenced by 52 - shared.Upload{ID: 55, State: "completed"}, // referenced by 51 - shared.Upload{ID: 56, State: "completed"}, // referenced by 52, 53 + types.Upload{ID: 50, State: "completed"}, + types.Upload{ID: 51, State: "completed"}, + types.Upload{ID: 52, State: "completed"}, + types.Upload{ID: 53, State: "completed"}, // referenced by 51, 52, 54, 55, 56 + types.Upload{ID: 54, State: "completed"}, // referenced by 52 + types.Upload{ID: 55, State: "completed"}, // referenced by 51 + types.Upload{ID: 56, State: "completed"}, // referenced by 52, 53 ) insertPackages(t, store, []shared.Package{ {DumpID: 53, Scheme: "test", Name: "p1", Version: "1.2.3"}, @@ -885,7 +886,7 @@ func TestDeleteUploadByID(t *testing.T) { store := New(db, &observation.TestContext) insertUploads(t, db, - shared.Upload{ID: 1, RepositoryID: 50}, + types.Upload{ID: 1, RepositoryID: 50}, ) if found, err := store.DeleteUploadByID(context.Background(), 1); err != nil { @@ -923,7 +924,7 @@ func TestDeleteUploadByIDNotCompleted(t *testing.T) { store := New(db, &observation.TestContext) insertUploads(t, db, - shared.Upload{ID: 1, RepositoryID: 50, State: "uploading"}, + types.Upload{ID: 1, RepositoryID: 50, State: "uploading"}, ) if found, err := store.DeleteUploadByID(context.Background(), 1); err != nil { @@ -978,7 +979,7 @@ func TestUpdateUploadsVisibleToCommits(t *testing.T) { // | | | // +-- [3] -- 4 --+ +--- 8 - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(1)}, {ID: 2, Commit: makeCommit(3)}, {ID: 3, Commit: makeCommit(7)}, @@ -1039,7 +1040,7 @@ func TestUpdateUploadsVisibleToCommitsAlternateCommitGraph(t *testing.T) { // | // +-- 7 -- 8 - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(2)}, } insertUploads(t, db, uploads...) @@ -1088,7 +1089,7 @@ func TestUpdateUploadsVisibleToCommitsDistinctRoots(t *testing.T) { // // 1 -- [2] - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(2), Root: "root1/"}, {ID: 2, Commit: makeCommit(2), Root: "root2/"}, } @@ -1147,7 +1148,7 @@ func TestUpdateUploadsVisibleToCommitsOverlappingRoots(t *testing.T) { // | 8 | 5 | root2/ | lsif-go | (overwrites root2/ at commit 2) // | 9 | 6 | root1/ | lsif-go | (overwrites root1/ at commit 2) - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(1), Indexer: "lsif-go", Root: "root3/"}, {ID: 2, Commit: makeCommit(1), Indexer: "scip-python", Root: "root4/"}, {ID: 3, Commit: makeCommit(2), Indexer: "lsif-go", Root: "root1/"}, @@ -1206,7 +1207,7 @@ func TestUpdateUploadsVisibleToCommitsIndexerName(t *testing.T) { // // [1] -- [2] -- [3] -- [4] -- 5 - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(1), Root: "root1/", Indexer: "idx1"}, {ID: 2, Commit: makeCommit(2), Root: "root2/", Indexer: "idx1"}, {ID: 3, Commit: makeCommit(3), Root: "root3/", Indexer: "idx1"}, @@ -1258,7 +1259,7 @@ func TestUpdateUploadsVisibleToCommitsResetsDirtyFlag(t *testing.T) { db := database.NewDB(logger, dbtest.NewDB(logger, t)) store := New(db, &observation.TestContext) - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(1)}, {ID: 2, Commit: makeCommit(2)}, {ID: 3, Commit: makeCommit(3)}, @@ -1325,7 +1326,7 @@ func TestCalculateVisibleUploadsResetsDirtyFlagTransactionTimestamp(t *testing.T db := database.NewDB(logger, dbtest.NewDB(logger, t)) store := New(db, &observation.TestContext) - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(1)}, {ID: 2, Commit: makeCommit(2)}, {ID: 3, Commit: makeCommit(3)}, @@ -1375,7 +1376,7 @@ func TestCalculateVisibleUploadsNonDefaultBranches(t *testing.T) { // 09: tip of branch feat1 // 12: tip of branch feat2 - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(1)}, {ID: 2, Commit: makeCommit(3)}, {ID: 3, Commit: makeCommit(6)}, @@ -1468,7 +1469,7 @@ func TestCalculateVisibleUploadsNonDefaultBranchesWithCustomRetentionConfigurati // 09: tip of branch feat1 // 12: tip of branch feat2 - uploads := []shared.Upload{ + uploads := []types.Upload{ {ID: 1, Commit: makeCommit(1)}, {ID: 2, Commit: makeCommit(3)}, {ID: 3, Commit: makeCommit(6)}, @@ -1564,11 +1565,11 @@ func TestGetVisibleUploadsMatchingMonikers(t *testing.T) { store := New(db, &observation.TestContext) insertUploads(t, db, - shared.Upload{ID: 1, Commit: makeCommit(2), Root: "sub1/"}, - shared.Upload{ID: 2, Commit: makeCommit(3), Root: "sub2/"}, - shared.Upload{ID: 3, Commit: makeCommit(4), Root: "sub3/"}, - shared.Upload{ID: 4, Commit: makeCommit(3), Root: "sub4/"}, - shared.Upload{ID: 5, Commit: makeCommit(2), Root: "sub5/"}, + types.Upload{ID: 1, Commit: makeCommit(2), Root: "sub1/"}, + types.Upload{ID: 2, Commit: makeCommit(3), Root: "sub2/"}, + types.Upload{ID: 3, Commit: makeCommit(4), Root: "sub3/"}, + types.Upload{ID: 4, Commit: makeCommit(3), Root: "sub4/"}, + types.Upload{ID: 5, Commit: makeCommit(2), Root: "sub5/"}, ) insertNearestUploads(t, db, 50, map[string][]commitgraph.UploadMeta{ @@ -2086,7 +2087,7 @@ func getUploadsVisibleAtTip(t testing.TB, db database.DB, repositoryID int) []in return ids } -func assertCommitsVisibleFromUploads(t *testing.T, store Store, uploads []shared.Upload, expectedVisibleUploads map[string][]int) { +func assertCommitsVisibleFromUploads(t *testing.T, store Store, uploads []types.Upload, expectedVisibleUploads map[string][]int) { expectedVisibleCommits := map[int][]string{} for commit, uploadIDs := range expectedVisibleUploads { for _, uploadID := range uploadIDs { @@ -2173,8 +2174,7 @@ func readBenchmarkCommitGraph() (*gitdomain.CommitGraph, error) { return gitdomain.ParseCommitGraph(strings.Split(string(contents), "\n")), nil } -func readBenchmarkCommitGraphView() ([]shared.Upload, error) { - // contents, err := readBenchmarkFile("../../../commitgraph/testdata/uploads.txt.gz") +func readBenchmarkCommitGraphView() ([]types.Upload, error) { contents, err := readBenchmarkFile("../../../../codeintel/commitgraph/testdata/customer1/uploads.csv.gz") if err != nil { return nil, err @@ -2182,7 +2182,7 @@ func readBenchmarkCommitGraphView() ([]shared.Upload, error) { reader := csv.NewReader(bytes.NewReader(contents)) - var uploads []shared.Upload + var uploads []types.Upload for { record, err := reader.Read() if err != nil { @@ -2198,7 +2198,7 @@ func readBenchmarkCommitGraphView() ([]shared.Upload, error) { return nil, err } - uploads = append(uploads, shared.Upload{ + uploads = append(uploads, types.Upload{ ID: id, RepositoryID: 50, Commit: record[1], diff --git a/internal/codeintel/uploads/mocks_test.go b/internal/codeintel/uploads/mocks_test.go index 839d9dd19c0..ffadf7729d4 100644 --- a/internal/codeintel/uploads/mocks_test.go +++ b/internal/codeintel/uploads/mocks_test.go @@ -11,6 +11,8 @@ import ( "sync" "time" + api "github.com/sourcegraph/sourcegraph/internal/api" + types "github.com/sourcegraph/sourcegraph/internal/codeintel/types" store "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/internal/store" shared "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" gitserver "github.com/sourcegraph/sourcegraph/internal/gitserver" @@ -231,17 +233,17 @@ func NewMockStore() *MockStore { }, }, FindClosestDumpsFunc: &StoreFindClosestDumpsFunc{ - defaultHook: func(context.Context, int, string, string, bool, string) (r0 []shared.Dump, r1 error) { + defaultHook: func(context.Context, int, string, string, bool, string) (r0 []types.Dump, r1 error) { return }, }, FindClosestDumpsFromGraphFragmentFunc: &StoreFindClosestDumpsFromGraphFragmentFunc{ - defaultHook: func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) (r0 []shared.Dump, r1 error) { + defaultHook: func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) (r0 []types.Dump, r1 error) { return }, }, GetAuditLogsForUploadFunc: &StoreGetAuditLogsForUploadFunc{ - defaultHook: func(context.Context, int) (r0 []shared.UploadLog, r1 error) { + defaultHook: func(context.Context, int) (r0 []types.UploadLog, r1 error) { return }, }, @@ -261,12 +263,12 @@ func NewMockStore() *MockStore { }, }, GetDumpsByIDsFunc: &StoreGetDumpsByIDsFunc{ - defaultHook: func(context.Context, []int) (r0 []shared.Dump, r1 error) { + defaultHook: func(context.Context, []int) (r0 []types.Dump, r1 error) { return }, }, GetDumpsWithDefinitionsForMonikersFunc: &StoreGetDumpsWithDefinitionsForMonikersFunc{ - defaultHook: func(context.Context, []precise.QualifiedMonikerData) (r0 []shared.Dump, r1 error) { + defaultHook: func(context.Context, []precise.QualifiedMonikerData) (r0 []types.Dump, r1 error) { return }, }, @@ -301,7 +303,7 @@ func NewMockStore() *MockStore { }, }, GetUploadByIDFunc: &StoreGetUploadByIDFunc{ - defaultHook: func(context.Context, int) (r0 shared.Upload, r1 bool, r2 error) { + defaultHook: func(context.Context, int) (r0 types.Upload, r1 bool, r2 error) { return }, }, @@ -311,12 +313,12 @@ func NewMockStore() *MockStore { }, }, GetUploadsFunc: &StoreGetUploadsFunc{ - defaultHook: func(context.Context, shared.GetUploadsOptions) (r0 []shared.Upload, r1 int, r2 error) { + defaultHook: func(context.Context, types.GetUploadsOptions) (r0 []types.Upload, r1 int, r2 error) { return }, }, GetUploadsByIDsFunc: &StoreGetUploadsByIDsFunc{ - defaultHook: func(context.Context, ...int) (r0 []shared.Upload, r1 error) { + defaultHook: func(context.Context, ...int) (r0 []types.Upload, r1 error) { return }, }, @@ -478,17 +480,17 @@ func NewStrictMockStore() *MockStore { }, }, FindClosestDumpsFunc: &StoreFindClosestDumpsFunc{ - defaultHook: func(context.Context, int, string, string, bool, string) ([]shared.Dump, error) { + defaultHook: func(context.Context, int, string, string, bool, string) ([]types.Dump, error) { panic("unexpected invocation of MockStore.FindClosestDumps") }, }, FindClosestDumpsFromGraphFragmentFunc: &StoreFindClosestDumpsFromGraphFragmentFunc{ - defaultHook: func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]shared.Dump, error) { + defaultHook: func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]types.Dump, error) { panic("unexpected invocation of MockStore.FindClosestDumpsFromGraphFragment") }, }, GetAuditLogsForUploadFunc: &StoreGetAuditLogsForUploadFunc{ - defaultHook: func(context.Context, int) ([]shared.UploadLog, error) { + defaultHook: func(context.Context, int) ([]types.UploadLog, error) { panic("unexpected invocation of MockStore.GetAuditLogsForUpload") }, }, @@ -508,12 +510,12 @@ func NewStrictMockStore() *MockStore { }, }, GetDumpsByIDsFunc: &StoreGetDumpsByIDsFunc{ - defaultHook: func(context.Context, []int) ([]shared.Dump, error) { + defaultHook: func(context.Context, []int) ([]types.Dump, error) { panic("unexpected invocation of MockStore.GetDumpsByIDs") }, }, GetDumpsWithDefinitionsForMonikersFunc: &StoreGetDumpsWithDefinitionsForMonikersFunc{ - defaultHook: func(context.Context, []precise.QualifiedMonikerData) ([]shared.Dump, error) { + defaultHook: func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error) { panic("unexpected invocation of MockStore.GetDumpsWithDefinitionsForMonikers") }, }, @@ -548,7 +550,7 @@ func NewStrictMockStore() *MockStore { }, }, GetUploadByIDFunc: &StoreGetUploadByIDFunc{ - defaultHook: func(context.Context, int) (shared.Upload, bool, error) { + defaultHook: func(context.Context, int) (types.Upload, bool, error) { panic("unexpected invocation of MockStore.GetUploadByID") }, }, @@ -558,12 +560,12 @@ func NewStrictMockStore() *MockStore { }, }, GetUploadsFunc: &StoreGetUploadsFunc{ - defaultHook: func(context.Context, shared.GetUploadsOptions) ([]shared.Upload, int, error) { + defaultHook: func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { panic("unexpected invocation of MockStore.GetUploads") }, }, GetUploadsByIDsFunc: &StoreGetUploadsByIDsFunc{ - defaultHook: func(context.Context, ...int) ([]shared.Upload, error) { + defaultHook: func(context.Context, ...int) ([]types.Upload, error) { panic("unexpected invocation of MockStore.GetUploadsByIDs") }, }, @@ -1711,15 +1713,15 @@ func (c StoreDoneFuncCall) Results() []interface{} { // StoreFindClosestDumpsFunc describes the behavior when the // FindClosestDumps method of the parent MockStore instance is invoked. type StoreFindClosestDumpsFunc struct { - defaultHook func(context.Context, int, string, string, bool, string) ([]shared.Dump, error) - hooks []func(context.Context, int, string, string, bool, string) ([]shared.Dump, error) + defaultHook func(context.Context, int, string, string, bool, string) ([]types.Dump, error) + hooks []func(context.Context, int, string, string, bool, string) ([]types.Dump, error) history []StoreFindClosestDumpsFuncCall mutex sync.Mutex } // FindClosestDumps delegates to the next hook function in the queue and // stores the parameter and result values of this invocation. -func (m *MockStore) FindClosestDumps(v0 context.Context, v1 int, v2 string, v3 string, v4 bool, v5 string) ([]shared.Dump, error) { +func (m *MockStore) FindClosestDumps(v0 context.Context, v1 int, v2 string, v3 string, v4 bool, v5 string) ([]types.Dump, error) { r0, r1 := m.FindClosestDumpsFunc.nextHook()(v0, v1, v2, v3, v4, v5) m.FindClosestDumpsFunc.appendCall(StoreFindClosestDumpsFuncCall{v0, v1, v2, v3, v4, v5, r0, r1}) return r0, r1 @@ -1728,7 +1730,7 @@ func (m *MockStore) FindClosestDumps(v0 context.Context, v1 int, v2 string, v3 s // SetDefaultHook sets function that is called when the FindClosestDumps // method of the parent MockStore instance is invoked and the hook queue is // empty. -func (f *StoreFindClosestDumpsFunc) SetDefaultHook(hook func(context.Context, int, string, string, bool, string) ([]shared.Dump, error)) { +func (f *StoreFindClosestDumpsFunc) SetDefaultHook(hook func(context.Context, int, string, string, bool, string) ([]types.Dump, error)) { f.defaultHook = hook } @@ -1736,7 +1738,7 @@ func (f *StoreFindClosestDumpsFunc) SetDefaultHook(hook func(context.Context, in // FindClosestDumps method of the parent MockStore instance invokes the hook // at the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. -func (f *StoreFindClosestDumpsFunc) PushHook(hook func(context.Context, int, string, string, bool, string) ([]shared.Dump, error)) { +func (f *StoreFindClosestDumpsFunc) PushHook(hook func(context.Context, int, string, string, bool, string) ([]types.Dump, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -1744,20 +1746,20 @@ func (f *StoreFindClosestDumpsFunc) PushHook(hook func(context.Context, int, str // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreFindClosestDumpsFunc) SetDefaultReturn(r0 []shared.Dump, r1 error) { - f.SetDefaultHook(func(context.Context, int, string, string, bool, string) ([]shared.Dump, error) { +func (f *StoreFindClosestDumpsFunc) SetDefaultReturn(r0 []types.Dump, r1 error) { + f.SetDefaultHook(func(context.Context, int, string, string, bool, string) ([]types.Dump, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreFindClosestDumpsFunc) PushReturn(r0 []shared.Dump, r1 error) { - f.PushHook(func(context.Context, int, string, string, bool, string) ([]shared.Dump, error) { +func (f *StoreFindClosestDumpsFunc) PushReturn(r0 []types.Dump, r1 error) { + f.PushHook(func(context.Context, int, string, string, bool, string) ([]types.Dump, error) { return r0, r1 }) } -func (f *StoreFindClosestDumpsFunc) nextHook() func(context.Context, int, string, string, bool, string) ([]shared.Dump, error) { +func (f *StoreFindClosestDumpsFunc) nextHook() func(context.Context, int, string, string, bool, string) ([]types.Dump, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -1810,7 +1812,7 @@ type StoreFindClosestDumpsFuncCall struct { Arg5 string // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.Dump + Result0 []types.Dump // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error @@ -1832,15 +1834,15 @@ func (c StoreFindClosestDumpsFuncCall) Results() []interface{} { // the FindClosestDumpsFromGraphFragment method of the parent MockStore // instance is invoked. type StoreFindClosestDumpsFromGraphFragmentFunc struct { - defaultHook func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]shared.Dump, error) - hooks []func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]shared.Dump, error) + defaultHook func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]types.Dump, error) + hooks []func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]types.Dump, error) history []StoreFindClosestDumpsFromGraphFragmentFuncCall mutex sync.Mutex } // FindClosestDumpsFromGraphFragment delegates to the next hook function in // the queue and stores the parameter and result values of this invocation. -func (m *MockStore) FindClosestDumpsFromGraphFragment(v0 context.Context, v1 int, v2 string, v3 string, v4 bool, v5 string, v6 *gitdomain.CommitGraph) ([]shared.Dump, error) { +func (m *MockStore) FindClosestDumpsFromGraphFragment(v0 context.Context, v1 int, v2 string, v3 string, v4 bool, v5 string, v6 *gitdomain.CommitGraph) ([]types.Dump, error) { r0, r1 := m.FindClosestDumpsFromGraphFragmentFunc.nextHook()(v0, v1, v2, v3, v4, v5, v6) m.FindClosestDumpsFromGraphFragmentFunc.appendCall(StoreFindClosestDumpsFromGraphFragmentFuncCall{v0, v1, v2, v3, v4, v5, v6, r0, r1}) return r0, r1 @@ -1849,7 +1851,7 @@ func (m *MockStore) FindClosestDumpsFromGraphFragment(v0 context.Context, v1 int // SetDefaultHook sets function that is called when the // FindClosestDumpsFromGraphFragment method of the parent MockStore instance // is invoked and the hook queue is empty. -func (f *StoreFindClosestDumpsFromGraphFragmentFunc) SetDefaultHook(hook func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]shared.Dump, error)) { +func (f *StoreFindClosestDumpsFromGraphFragmentFunc) SetDefaultHook(hook func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]types.Dump, error)) { f.defaultHook = hook } @@ -1858,7 +1860,7 @@ func (f *StoreFindClosestDumpsFromGraphFragmentFunc) SetDefaultHook(hook func(co // invokes the hook at the front of the queue and discards it. After the // queue is empty, the default hook function is invoked for any future // action. -func (f *StoreFindClosestDumpsFromGraphFragmentFunc) PushHook(hook func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]shared.Dump, error)) { +func (f *StoreFindClosestDumpsFromGraphFragmentFunc) PushHook(hook func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]types.Dump, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -1866,20 +1868,20 @@ func (f *StoreFindClosestDumpsFromGraphFragmentFunc) PushHook(hook func(context. // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreFindClosestDumpsFromGraphFragmentFunc) SetDefaultReturn(r0 []shared.Dump, r1 error) { - f.SetDefaultHook(func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]shared.Dump, error) { +func (f *StoreFindClosestDumpsFromGraphFragmentFunc) SetDefaultReturn(r0 []types.Dump, r1 error) { + f.SetDefaultHook(func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]types.Dump, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreFindClosestDumpsFromGraphFragmentFunc) PushReturn(r0 []shared.Dump, r1 error) { - f.PushHook(func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]shared.Dump, error) { +func (f *StoreFindClosestDumpsFromGraphFragmentFunc) PushReturn(r0 []types.Dump, r1 error) { + f.PushHook(func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]types.Dump, error) { return r0, r1 }) } -func (f *StoreFindClosestDumpsFromGraphFragmentFunc) nextHook() func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]shared.Dump, error) { +func (f *StoreFindClosestDumpsFromGraphFragmentFunc) nextHook() func(context.Context, int, string, string, bool, string, *gitdomain.CommitGraph) ([]types.Dump, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -1937,7 +1939,7 @@ type StoreFindClosestDumpsFromGraphFragmentFuncCall struct { Arg6 *gitdomain.CommitGraph // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.Dump + Result0 []types.Dump // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error @@ -1958,15 +1960,15 @@ func (c StoreFindClosestDumpsFromGraphFragmentFuncCall) Results() []interface{} // StoreGetAuditLogsForUploadFunc describes the behavior when the // GetAuditLogsForUpload method of the parent MockStore instance is invoked. type StoreGetAuditLogsForUploadFunc struct { - defaultHook func(context.Context, int) ([]shared.UploadLog, error) - hooks []func(context.Context, int) ([]shared.UploadLog, error) + defaultHook func(context.Context, int) ([]types.UploadLog, error) + hooks []func(context.Context, int) ([]types.UploadLog, error) history []StoreGetAuditLogsForUploadFuncCall mutex sync.Mutex } // GetAuditLogsForUpload delegates to the next hook function in the queue // and stores the parameter and result values of this invocation. -func (m *MockStore) GetAuditLogsForUpload(v0 context.Context, v1 int) ([]shared.UploadLog, error) { +func (m *MockStore) GetAuditLogsForUpload(v0 context.Context, v1 int) ([]types.UploadLog, error) { r0, r1 := m.GetAuditLogsForUploadFunc.nextHook()(v0, v1) m.GetAuditLogsForUploadFunc.appendCall(StoreGetAuditLogsForUploadFuncCall{v0, v1, r0, r1}) return r0, r1 @@ -1975,7 +1977,7 @@ func (m *MockStore) GetAuditLogsForUpload(v0 context.Context, v1 int) ([]shared. // SetDefaultHook sets function that is called when the // GetAuditLogsForUpload method of the parent MockStore instance is invoked // and the hook queue is empty. -func (f *StoreGetAuditLogsForUploadFunc) SetDefaultHook(hook func(context.Context, int) ([]shared.UploadLog, error)) { +func (f *StoreGetAuditLogsForUploadFunc) SetDefaultHook(hook func(context.Context, int) ([]types.UploadLog, error)) { f.defaultHook = hook } @@ -1983,7 +1985,7 @@ func (f *StoreGetAuditLogsForUploadFunc) SetDefaultHook(hook func(context.Contex // GetAuditLogsForUpload method of the parent MockStore instance invokes the // hook at the front of the queue and discards it. After the queue is empty, // the default hook function is invoked for any future action. -func (f *StoreGetAuditLogsForUploadFunc) PushHook(hook func(context.Context, int) ([]shared.UploadLog, error)) { +func (f *StoreGetAuditLogsForUploadFunc) PushHook(hook func(context.Context, int) ([]types.UploadLog, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -1991,20 +1993,20 @@ func (f *StoreGetAuditLogsForUploadFunc) PushHook(hook func(context.Context, int // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreGetAuditLogsForUploadFunc) SetDefaultReturn(r0 []shared.UploadLog, r1 error) { - f.SetDefaultHook(func(context.Context, int) ([]shared.UploadLog, error) { +func (f *StoreGetAuditLogsForUploadFunc) SetDefaultReturn(r0 []types.UploadLog, r1 error) { + f.SetDefaultHook(func(context.Context, int) ([]types.UploadLog, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreGetAuditLogsForUploadFunc) PushReturn(r0 []shared.UploadLog, r1 error) { - f.PushHook(func(context.Context, int) ([]shared.UploadLog, error) { +func (f *StoreGetAuditLogsForUploadFunc) PushReturn(r0 []types.UploadLog, r1 error) { + f.PushHook(func(context.Context, int) ([]types.UploadLog, error) { return r0, r1 }) } -func (f *StoreGetAuditLogsForUploadFunc) nextHook() func(context.Context, int) ([]shared.UploadLog, error) { +func (f *StoreGetAuditLogsForUploadFunc) nextHook() func(context.Context, int) ([]types.UploadLog, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -2045,7 +2047,7 @@ type StoreGetAuditLogsForUploadFuncCall struct { Arg1 int // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.UploadLog + Result0 []types.UploadLog // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error @@ -2402,15 +2404,15 @@ func (c StoreGetDirtyRepositoriesFuncCall) Results() []interface{} { // StoreGetDumpsByIDsFunc describes the behavior when the GetDumpsByIDs // method of the parent MockStore instance is invoked. type StoreGetDumpsByIDsFunc struct { - defaultHook func(context.Context, []int) ([]shared.Dump, error) - hooks []func(context.Context, []int) ([]shared.Dump, error) + defaultHook func(context.Context, []int) ([]types.Dump, error) + hooks []func(context.Context, []int) ([]types.Dump, error) history []StoreGetDumpsByIDsFuncCall mutex sync.Mutex } // GetDumpsByIDs delegates to the next hook function in the queue and stores // the parameter and result values of this invocation. -func (m *MockStore) GetDumpsByIDs(v0 context.Context, v1 []int) ([]shared.Dump, error) { +func (m *MockStore) GetDumpsByIDs(v0 context.Context, v1 []int) ([]types.Dump, error) { r0, r1 := m.GetDumpsByIDsFunc.nextHook()(v0, v1) m.GetDumpsByIDsFunc.appendCall(StoreGetDumpsByIDsFuncCall{v0, v1, r0, r1}) return r0, r1 @@ -2418,7 +2420,7 @@ func (m *MockStore) GetDumpsByIDs(v0 context.Context, v1 []int) ([]shared.Dump, // SetDefaultHook sets function that is called when the GetDumpsByIDs method // of the parent MockStore instance is invoked and the hook queue is empty. -func (f *StoreGetDumpsByIDsFunc) SetDefaultHook(hook func(context.Context, []int) ([]shared.Dump, error)) { +func (f *StoreGetDumpsByIDsFunc) SetDefaultHook(hook func(context.Context, []int) ([]types.Dump, error)) { f.defaultHook = hook } @@ -2426,7 +2428,7 @@ func (f *StoreGetDumpsByIDsFunc) SetDefaultHook(hook func(context.Context, []int // GetDumpsByIDs method of the parent MockStore instance invokes the hook at // the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. -func (f *StoreGetDumpsByIDsFunc) PushHook(hook func(context.Context, []int) ([]shared.Dump, error)) { +func (f *StoreGetDumpsByIDsFunc) PushHook(hook func(context.Context, []int) ([]types.Dump, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -2434,20 +2436,20 @@ func (f *StoreGetDumpsByIDsFunc) PushHook(hook func(context.Context, []int) ([]s // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreGetDumpsByIDsFunc) SetDefaultReturn(r0 []shared.Dump, r1 error) { - f.SetDefaultHook(func(context.Context, []int) ([]shared.Dump, error) { +func (f *StoreGetDumpsByIDsFunc) SetDefaultReturn(r0 []types.Dump, r1 error) { + f.SetDefaultHook(func(context.Context, []int) ([]types.Dump, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreGetDumpsByIDsFunc) PushReturn(r0 []shared.Dump, r1 error) { - f.PushHook(func(context.Context, []int) ([]shared.Dump, error) { +func (f *StoreGetDumpsByIDsFunc) PushReturn(r0 []types.Dump, r1 error) { + f.PushHook(func(context.Context, []int) ([]types.Dump, error) { return r0, r1 }) } -func (f *StoreGetDumpsByIDsFunc) nextHook() func(context.Context, []int) ([]shared.Dump, error) { +func (f *StoreGetDumpsByIDsFunc) nextHook() func(context.Context, []int) ([]types.Dump, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -2488,7 +2490,7 @@ type StoreGetDumpsByIDsFuncCall struct { Arg1 []int // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.Dump + Result0 []types.Dump // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error @@ -2510,15 +2512,15 @@ func (c StoreGetDumpsByIDsFuncCall) Results() []interface{} { // the GetDumpsWithDefinitionsForMonikers method of the parent MockStore // instance is invoked. type StoreGetDumpsWithDefinitionsForMonikersFunc struct { - defaultHook func(context.Context, []precise.QualifiedMonikerData) ([]shared.Dump, error) - hooks []func(context.Context, []precise.QualifiedMonikerData) ([]shared.Dump, error) + defaultHook func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error) + hooks []func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error) history []StoreGetDumpsWithDefinitionsForMonikersFuncCall mutex sync.Mutex } // GetDumpsWithDefinitionsForMonikers delegates to the next hook function in // the queue and stores the parameter and result values of this invocation. -func (m *MockStore) GetDumpsWithDefinitionsForMonikers(v0 context.Context, v1 []precise.QualifiedMonikerData) ([]shared.Dump, error) { +func (m *MockStore) GetDumpsWithDefinitionsForMonikers(v0 context.Context, v1 []precise.QualifiedMonikerData) ([]types.Dump, error) { r0, r1 := m.GetDumpsWithDefinitionsForMonikersFunc.nextHook()(v0, v1) m.GetDumpsWithDefinitionsForMonikersFunc.appendCall(StoreGetDumpsWithDefinitionsForMonikersFuncCall{v0, v1, r0, r1}) return r0, r1 @@ -2527,7 +2529,7 @@ func (m *MockStore) GetDumpsWithDefinitionsForMonikers(v0 context.Context, v1 [] // SetDefaultHook sets function that is called when the // GetDumpsWithDefinitionsForMonikers method of the parent MockStore // instance is invoked and the hook queue is empty. -func (f *StoreGetDumpsWithDefinitionsForMonikersFunc) SetDefaultHook(hook func(context.Context, []precise.QualifiedMonikerData) ([]shared.Dump, error)) { +func (f *StoreGetDumpsWithDefinitionsForMonikersFunc) SetDefaultHook(hook func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error)) { f.defaultHook = hook } @@ -2536,7 +2538,7 @@ func (f *StoreGetDumpsWithDefinitionsForMonikersFunc) SetDefaultHook(hook func(c // instance invokes the hook at the front of the queue and discards it. // After the queue is empty, the default hook function is invoked for any // future action. -func (f *StoreGetDumpsWithDefinitionsForMonikersFunc) PushHook(hook func(context.Context, []precise.QualifiedMonikerData) ([]shared.Dump, error)) { +func (f *StoreGetDumpsWithDefinitionsForMonikersFunc) PushHook(hook func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -2544,20 +2546,20 @@ func (f *StoreGetDumpsWithDefinitionsForMonikersFunc) PushHook(hook func(context // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreGetDumpsWithDefinitionsForMonikersFunc) SetDefaultReturn(r0 []shared.Dump, r1 error) { - f.SetDefaultHook(func(context.Context, []precise.QualifiedMonikerData) ([]shared.Dump, error) { +func (f *StoreGetDumpsWithDefinitionsForMonikersFunc) SetDefaultReturn(r0 []types.Dump, r1 error) { + f.SetDefaultHook(func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreGetDumpsWithDefinitionsForMonikersFunc) PushReturn(r0 []shared.Dump, r1 error) { - f.PushHook(func(context.Context, []precise.QualifiedMonikerData) ([]shared.Dump, error) { +func (f *StoreGetDumpsWithDefinitionsForMonikersFunc) PushReturn(r0 []types.Dump, r1 error) { + f.PushHook(func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error) { return r0, r1 }) } -func (f *StoreGetDumpsWithDefinitionsForMonikersFunc) nextHook() func(context.Context, []precise.QualifiedMonikerData) ([]shared.Dump, error) { +func (f *StoreGetDumpsWithDefinitionsForMonikersFunc) nextHook() func(context.Context, []precise.QualifiedMonikerData) ([]types.Dump, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -2600,7 +2602,7 @@ type StoreGetDumpsWithDefinitionsForMonikersFuncCall struct { Arg1 []precise.QualifiedMonikerData // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.Dump + Result0 []types.Dump // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error @@ -3306,15 +3308,15 @@ func (c StoreGetStaleSourcedCommitsFuncCall) Results() []interface{} { // StoreGetUploadByIDFunc describes the behavior when the GetUploadByID // method of the parent MockStore instance is invoked. type StoreGetUploadByIDFunc struct { - defaultHook func(context.Context, int) (shared.Upload, bool, error) - hooks []func(context.Context, int) (shared.Upload, bool, error) + defaultHook func(context.Context, int) (types.Upload, bool, error) + hooks []func(context.Context, int) (types.Upload, bool, error) history []StoreGetUploadByIDFuncCall mutex sync.Mutex } // GetUploadByID delegates to the next hook function in the queue and stores // the parameter and result values of this invocation. -func (m *MockStore) GetUploadByID(v0 context.Context, v1 int) (shared.Upload, bool, error) { +func (m *MockStore) GetUploadByID(v0 context.Context, v1 int) (types.Upload, bool, error) { r0, r1, r2 := m.GetUploadByIDFunc.nextHook()(v0, v1) m.GetUploadByIDFunc.appendCall(StoreGetUploadByIDFuncCall{v0, v1, r0, r1, r2}) return r0, r1, r2 @@ -3322,7 +3324,7 @@ func (m *MockStore) GetUploadByID(v0 context.Context, v1 int) (shared.Upload, bo // SetDefaultHook sets function that is called when the GetUploadByID method // of the parent MockStore instance is invoked and the hook queue is empty. -func (f *StoreGetUploadByIDFunc) SetDefaultHook(hook func(context.Context, int) (shared.Upload, bool, error)) { +func (f *StoreGetUploadByIDFunc) SetDefaultHook(hook func(context.Context, int) (types.Upload, bool, error)) { f.defaultHook = hook } @@ -3330,7 +3332,7 @@ func (f *StoreGetUploadByIDFunc) SetDefaultHook(hook func(context.Context, int) // GetUploadByID method of the parent MockStore instance invokes the hook at // the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. -func (f *StoreGetUploadByIDFunc) PushHook(hook func(context.Context, int) (shared.Upload, bool, error)) { +func (f *StoreGetUploadByIDFunc) PushHook(hook func(context.Context, int) (types.Upload, bool, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -3338,20 +3340,20 @@ func (f *StoreGetUploadByIDFunc) PushHook(hook func(context.Context, int) (share // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreGetUploadByIDFunc) SetDefaultReturn(r0 shared.Upload, r1 bool, r2 error) { - f.SetDefaultHook(func(context.Context, int) (shared.Upload, bool, error) { +func (f *StoreGetUploadByIDFunc) SetDefaultReturn(r0 types.Upload, r1 bool, r2 error) { + f.SetDefaultHook(func(context.Context, int) (types.Upload, bool, error) { return r0, r1, r2 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreGetUploadByIDFunc) PushReturn(r0 shared.Upload, r1 bool, r2 error) { - f.PushHook(func(context.Context, int) (shared.Upload, bool, error) { +func (f *StoreGetUploadByIDFunc) PushReturn(r0 types.Upload, r1 bool, r2 error) { + f.PushHook(func(context.Context, int) (types.Upload, bool, error) { return r0, r1, r2 }) } -func (f *StoreGetUploadByIDFunc) nextHook() func(context.Context, int) (shared.Upload, bool, error) { +func (f *StoreGetUploadByIDFunc) nextHook() func(context.Context, int) (types.Upload, bool, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -3392,7 +3394,7 @@ type StoreGetUploadByIDFuncCall struct { Arg1 int // Result0 is the value of the 1st result returned from this method // invocation. - Result0 shared.Upload + Result0 types.Upload // Result1 is the value of the 2nd result returned from this method // invocation. Result1 bool @@ -3551,15 +3553,15 @@ func (c StoreGetUploadIDsWithReferencesFuncCall) Results() []interface{} { // StoreGetUploadsFunc describes the behavior when the GetUploads method of // the parent MockStore instance is invoked. type StoreGetUploadsFunc struct { - defaultHook func(context.Context, shared.GetUploadsOptions) ([]shared.Upload, int, error) - hooks []func(context.Context, shared.GetUploadsOptions) ([]shared.Upload, int, error) + defaultHook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) + hooks []func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) history []StoreGetUploadsFuncCall mutex sync.Mutex } // GetUploads delegates to the next hook function in the queue and stores // the parameter and result values of this invocation. -func (m *MockStore) GetUploads(v0 context.Context, v1 shared.GetUploadsOptions) ([]shared.Upload, int, error) { +func (m *MockStore) GetUploads(v0 context.Context, v1 types.GetUploadsOptions) ([]types.Upload, int, error) { r0, r1, r2 := m.GetUploadsFunc.nextHook()(v0, v1) m.GetUploadsFunc.appendCall(StoreGetUploadsFuncCall{v0, v1, r0, r1, r2}) return r0, r1, r2 @@ -3567,7 +3569,7 @@ func (m *MockStore) GetUploads(v0 context.Context, v1 shared.GetUploadsOptions) // SetDefaultHook sets function that is called when the GetUploads method of // the parent MockStore instance is invoked and the hook queue is empty. -func (f *StoreGetUploadsFunc) SetDefaultHook(hook func(context.Context, shared.GetUploadsOptions) ([]shared.Upload, int, error)) { +func (f *StoreGetUploadsFunc) SetDefaultHook(hook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error)) { f.defaultHook = hook } @@ -3575,7 +3577,7 @@ func (f *StoreGetUploadsFunc) SetDefaultHook(hook func(context.Context, shared.G // GetUploads method of the parent MockStore instance invokes the hook at // the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. -func (f *StoreGetUploadsFunc) PushHook(hook func(context.Context, shared.GetUploadsOptions) ([]shared.Upload, int, error)) { +func (f *StoreGetUploadsFunc) PushHook(hook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -3583,20 +3585,20 @@ func (f *StoreGetUploadsFunc) PushHook(hook func(context.Context, shared.GetUplo // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreGetUploadsFunc) SetDefaultReturn(r0 []shared.Upload, r1 int, r2 error) { - f.SetDefaultHook(func(context.Context, shared.GetUploadsOptions) ([]shared.Upload, int, error) { +func (f *StoreGetUploadsFunc) SetDefaultReturn(r0 []types.Upload, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { return r0, r1, r2 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreGetUploadsFunc) PushReturn(r0 []shared.Upload, r1 int, r2 error) { - f.PushHook(func(context.Context, shared.GetUploadsOptions) ([]shared.Upload, int, error) { +func (f *StoreGetUploadsFunc) PushReturn(r0 []types.Upload, r1 int, r2 error) { + f.PushHook(func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { return r0, r1, r2 }) } -func (f *StoreGetUploadsFunc) nextHook() func(context.Context, shared.GetUploadsOptions) ([]shared.Upload, int, error) { +func (f *StoreGetUploadsFunc) nextHook() func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -3634,10 +3636,10 @@ type StoreGetUploadsFuncCall struct { Arg0 context.Context // Arg1 is the value of the 2nd argument passed to this method // invocation. - Arg1 shared.GetUploadsOptions + Arg1 types.GetUploadsOptions // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.Upload + Result0 []types.Upload // Result1 is the value of the 2nd result returned from this method // invocation. Result1 int @@ -3661,15 +3663,15 @@ func (c StoreGetUploadsFuncCall) Results() []interface{} { // StoreGetUploadsByIDsFunc describes the behavior when the GetUploadsByIDs // method of the parent MockStore instance is invoked. type StoreGetUploadsByIDsFunc struct { - defaultHook func(context.Context, ...int) ([]shared.Upload, error) - hooks []func(context.Context, ...int) ([]shared.Upload, error) + defaultHook func(context.Context, ...int) ([]types.Upload, error) + hooks []func(context.Context, ...int) ([]types.Upload, error) history []StoreGetUploadsByIDsFuncCall mutex sync.Mutex } // GetUploadsByIDs delegates to the next hook function in the queue and // stores the parameter and result values of this invocation. -func (m *MockStore) GetUploadsByIDs(v0 context.Context, v1 ...int) ([]shared.Upload, error) { +func (m *MockStore) GetUploadsByIDs(v0 context.Context, v1 ...int) ([]types.Upload, error) { r0, r1 := m.GetUploadsByIDsFunc.nextHook()(v0, v1...) m.GetUploadsByIDsFunc.appendCall(StoreGetUploadsByIDsFuncCall{v0, v1, r0, r1}) return r0, r1 @@ -3678,7 +3680,7 @@ func (m *MockStore) GetUploadsByIDs(v0 context.Context, v1 ...int) ([]shared.Upl // SetDefaultHook sets function that is called when the GetUploadsByIDs // method of the parent MockStore instance is invoked and the hook queue is // empty. -func (f *StoreGetUploadsByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]shared.Upload, error)) { +func (f *StoreGetUploadsByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]types.Upload, error)) { f.defaultHook = hook } @@ -3686,7 +3688,7 @@ func (f *StoreGetUploadsByIDsFunc) SetDefaultHook(hook func(context.Context, ... // GetUploadsByIDs method of the parent MockStore instance invokes the hook // at the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. -func (f *StoreGetUploadsByIDsFunc) PushHook(hook func(context.Context, ...int) ([]shared.Upload, error)) { +func (f *StoreGetUploadsByIDsFunc) PushHook(hook func(context.Context, ...int) ([]types.Upload, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -3694,20 +3696,20 @@ func (f *StoreGetUploadsByIDsFunc) PushHook(hook func(context.Context, ...int) ( // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. -func (f *StoreGetUploadsByIDsFunc) SetDefaultReturn(r0 []shared.Upload, r1 error) { - f.SetDefaultHook(func(context.Context, ...int) ([]shared.Upload, error) { +func (f *StoreGetUploadsByIDsFunc) SetDefaultReturn(r0 []types.Upload, r1 error) { + f.SetDefaultHook(func(context.Context, ...int) ([]types.Upload, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. -func (f *StoreGetUploadsByIDsFunc) PushReturn(r0 []shared.Upload, r1 error) { - f.PushHook(func(context.Context, ...int) ([]shared.Upload, error) { +func (f *StoreGetUploadsByIDsFunc) PushReturn(r0 []types.Upload, r1 error) { + f.PushHook(func(context.Context, ...int) ([]types.Upload, error) { return r0, r1 }) } -func (f *StoreGetUploadsByIDsFunc) nextHook() func(context.Context, ...int) ([]shared.Upload, error) { +func (f *StoreGetUploadsByIDsFunc) nextHook() func(context.Context, ...int) ([]types.Upload, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -3748,7 +3750,7 @@ type StoreGetUploadsByIDsFuncCall struct { Arg1 []int // Result0 is the value of the 1st result returned from this method // invocation. - Result0 []shared.Upload + Result0 []types.Upload // Result1 is the value of the 2nd result returned from this method // invocation. Result1 error @@ -6235,6 +6237,9 @@ type MockGitserverClient struct { // CommitGraphFunc is an instance of a mock function object controlling // the behavior of the method CommitGraph. CommitGraphFunc *GitserverClientCommitGraphFunc + // ListTagsFunc is an instance of a mock function object controlling the + // behavior of the method ListTags. + ListTagsFunc *GitserverClientListTagsFunc // RefDescriptionsFunc is an instance of a mock function object // controlling the behavior of the method RefDescriptions. RefDescriptionsFunc *GitserverClientRefDescriptionsFunc @@ -6255,6 +6260,11 @@ func NewMockGitserverClient() *MockGitserverClient { return }, }, + ListTagsFunc: &GitserverClientListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) (r0 []*gitdomain.Tag, r1 error) { + return + }, + }, RefDescriptionsFunc: &GitserverClientRefDescriptionsFunc{ defaultHook: func(context.Context, int, ...string) (r0 map[string][]gitdomain.RefDescription, r1 error) { return @@ -6277,6 +6287,11 @@ func NewStrictMockGitserverClient() *MockGitserverClient { panic("unexpected invocation of MockGitserverClient.CommitGraph") }, }, + ListTagsFunc: &GitserverClientListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + panic("unexpected invocation of MockGitserverClient.ListTags") + }, + }, RefDescriptionsFunc: &GitserverClientRefDescriptionsFunc{ defaultHook: func(context.Context, int, ...string) (map[string][]gitdomain.RefDescription, error) { panic("unexpected invocation of MockGitserverClient.RefDescriptions") @@ -6296,6 +6311,9 @@ func NewMockGitserverClientFrom(i shared.GitserverClient) *MockGitserverClient { CommitGraphFunc: &GitserverClientCommitGraphFunc{ defaultHook: i.CommitGraph, }, + ListTagsFunc: &GitserverClientListTagsFunc{ + defaultHook: i.ListTags, + }, RefDescriptionsFunc: &GitserverClientRefDescriptionsFunc{ defaultHook: i.RefDescriptions, }, @@ -6530,6 +6548,124 @@ func (c GitserverClientCommitGraphFuncCall) Results() []interface{} { return []interface{}{c.Result0, c.Result1} } +// GitserverClientListTagsFunc describes the behavior when the ListTags +// method of the parent MockGitserverClient instance is invoked. +type GitserverClientListTagsFunc struct { + defaultHook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + hooks []func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + history []GitserverClientListTagsFuncCall + mutex sync.Mutex +} + +// ListTags delegates to the next hook function in the queue and stores the +// parameter and result values of this invocation. +func (m *MockGitserverClient) ListTags(v0 context.Context, v1 api.RepoName, v2 ...string) ([]*gitdomain.Tag, error) { + r0, r1 := m.ListTagsFunc.nextHook()(v0, v1, v2...) + m.ListTagsFunc.appendCall(GitserverClientListTagsFuncCall{v0, v1, v2, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the ListTags method of +// the parent MockGitserverClient instance is invoked and the hook queue is +// empty. +func (f *GitserverClientListTagsFunc) SetDefaultHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// ListTags method of the parent MockGitserverClient instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *GitserverClientListTagsFunc) PushHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *GitserverClientListTagsFunc) SetDefaultReturn(r0 []*gitdomain.Tag, r1 error) { + f.SetDefaultHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *GitserverClientListTagsFunc) PushReturn(r0 []*gitdomain.Tag, r1 error) { + f.PushHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +func (f *GitserverClientListTagsFunc) nextHook() func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *GitserverClientListTagsFunc) appendCall(r0 GitserverClientListTagsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of GitserverClientListTagsFuncCall objects +// describing the invocations of this function. +func (f *GitserverClientListTagsFunc) History() []GitserverClientListTagsFuncCall { + f.mutex.Lock() + history := make([]GitserverClientListTagsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// GitserverClientListTagsFuncCall is an object that describes an invocation +// of method ListTags on an instance of MockGitserverClient. +type GitserverClientListTagsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 api.RepoName + // Arg2 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg2 []string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []*gitdomain.Tag + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c GitserverClientListTagsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg2 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0, c.Arg1}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c GitserverClientListTagsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + // GitserverClientRefDescriptionsFunc describes the behavior when the // RefDescriptions method of the parent MockGitserverClient instance is // invoked. diff --git a/internal/codeintel/uploads/observability.go b/internal/codeintel/uploads/observability.go index 81f3e410f48..386f8cb1d5a 100644 --- a/internal/codeintel/uploads/observability.go +++ b/internal/codeintel/uploads/observability.go @@ -69,6 +69,9 @@ type operations struct { // Audit Logs getAuditLogsForUpload *observation.Operation deleteOldAuditLogs *observation.Operation + + // Tags + getListTags *observation.Operation } func newOperations(observationContext *observation.Context) *operations { @@ -148,5 +151,8 @@ func newOperations(observationContext *observation.Context) *operations { // Audit Logs getAuditLogsForUpload: op("GetAuditLogsForUpload"), deleteOldAuditLogs: op("DeleteOldAuditLogs"), + + // Tags + getListTags: op("GetListTags"), } } diff --git a/internal/codeintel/uploads/service.go b/internal/codeintel/uploads/service.go index 4284951bf62..9d3526c2942 100644 --- a/internal/codeintel/uploads/service.go +++ b/internal/codeintel/uploads/service.go @@ -10,6 +10,8 @@ import ( logger "github.com/sourcegraph/log" + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/internal/lsifstore" "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/internal/store" "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" @@ -43,9 +45,9 @@ type service interface { SetRepositoriesForRetentionScan(ctx context.Context, processDelay time.Duration, limit int) (_ []int, err error) // Uploads - GetUploads(ctx context.Context, opts shared.GetUploadsOptions) (uploads []shared.Upload, totalCount int, err error) - GetUploadByID(ctx context.Context, id int) (_ shared.Upload, _ bool, err error) - GetUploadsByIDs(ctx context.Context, ids ...int) (_ []shared.Upload, err error) + GetUploads(ctx context.Context, opts types.GetUploadsOptions) (uploads []types.Upload, totalCount int, err error) + GetUploadByID(ctx context.Context, id int) (_ types.Upload, _ bool, err error) + GetUploadsByIDs(ctx context.Context, ids ...int) (_ []types.Upload, err error) GetUploadIDsWithReferences(ctx context.Context, orderedMonikers []precise.QualifiedMonikerData, ignoreIDs []int, repositoryID int, commit string, limit int, offset int) (ids []int, recordsScanned int, totalCount int, err error) GetUploadDocumentsForPath(ctx context.Context, bundleID int, pathPattern string) ([]string, int, error) GetRecentUploadsSummary(ctx context.Context, repositoryID int) (upload []shared.UploadsWithRepositoryNamespace, err error) @@ -58,13 +60,13 @@ type service interface { DeleteUploadsStuckUploading(ctx context.Context, uploadedBefore time.Time) (_ int, err error) DeleteUploadsWithoutRepository(ctx context.Context, now time.Time) (_ map[int]int, err error) DeleteUploadByID(ctx context.Context, id int) (_ bool, err error) - InferClosestUploads(ctx context.Context, repositoryID int, commit, path string, exactPath bool, indexer string) ([]shared.Dump, error) + InferClosestUploads(ctx context.Context, repositoryID int, commit, path string, exactPath bool, indexer string) ([]types.Dump, error) // Dumps - FindClosestDumps(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string) (_ []shared.Dump, err error) - FindClosestDumpsFromGraphFragment(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string, commitGraph *gitdomain.CommitGraph) (_ []shared.Dump, err error) - GetDumpsWithDefinitionsForMonikers(ctx context.Context, monikers []precise.QualifiedMonikerData) (_ []shared.Dump, err error) - GetDumpsByIDs(ctx context.Context, ids []int) (_ []shared.Dump, err error) + FindClosestDumps(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string) (_ []types.Dump, err error) + FindClosestDumpsFromGraphFragment(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string, commitGraph *gitdomain.CommitGraph) (_ []types.Dump, err error) + GetDumpsWithDefinitionsForMonikers(ctx context.Context, monikers []precise.QualifiedMonikerData) (_ []types.Dump, err error) + GetDumpsByIDs(ctx context.Context, ids []int) (_ []types.Dump, err error) // Packages UpdatePackages(ctx context.Context, dumpID int, packages []precise.Package) (err error) @@ -73,8 +75,11 @@ type service interface { UpdatePackageReferences(ctx context.Context, dumpID int, references []precise.PackageReference) (err error) // Audit Logs - GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []shared.UploadLog, err error) + GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []types.UploadLog, err error) DeleteOldAuditLogs(ctx context.Context, maxAge time.Duration, now time.Time) (count int, err error) + + // Tags + GetListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) (_ []*gitdomain.Tag, err error) } type Service struct { @@ -321,7 +326,7 @@ func (s *Service) GetDirtyRepositories(ctx context.Context) (_ map[int]int, err return s.store.GetDirtyRepositories(ctx) } -func (s *Service) GetUploads(ctx context.Context, opts shared.GetUploadsOptions) (uploads []shared.Upload, totalCount int, err error) { +func (s *Service) GetUploads(ctx context.Context, opts types.GetUploadsOptions) (uploads []types.Upload, totalCount int, err error) { ctx, _, endObservation := s.operations.getUploads.With(ctx, &err, observation.Args{ LogFields: []log.Field{log.Int("repositoryID", opts.RepositoryID), log.String("state", opts.State), log.String("term", opts.Term)}, }) @@ -331,14 +336,14 @@ func (s *Service) GetUploads(ctx context.Context, opts shared.GetUploadsOptions) } // TODO: Not being used in the resolver layer -func (s *Service) GetUploadByID(ctx context.Context, id int) (_ shared.Upload, _ bool, err error) { +func (s *Service) GetUploadByID(ctx context.Context, id int) (_ types.Upload, _ bool, err error) { ctx, _, endObservation := s.operations.getUploadByID.With(ctx, &err, observation.Args{LogFields: []log.Field{log.Int("id", id)}}) defer endObservation(1, observation.Args{}) return s.store.GetUploadByID(ctx, id) } -func (s *Service) GetUploadsByIDs(ctx context.Context, ids ...int) (_ []shared.Upload, err error) { +func (s *Service) GetUploadsByIDs(ctx context.Context, ids ...int) (_ []types.Upload, err error) { ctx, _, endObservation := s.operations.getUploadsByIDs.With(ctx, &err, observation.Args{LogFields: []log.Field{log.String("ids", fmt.Sprintf("%v", ids))}}) defer endObservation(1, observation.Args{}) @@ -456,7 +461,8 @@ const numAncestors = 100 // the graph. This will not always produce the full set of visible commits - some responses may not contain // all results while a subsequent request made after the lsif_nearest_uploads has been updated to include // this commit will. -func (s *Service) InferClosestUploads(ctx context.Context, repositoryID int, commit, path string, exactPath bool, indexer string) (_ []shared.Dump, err error) { +// +func (s *Service) InferClosestUploads(ctx context.Context, repositoryID int, commit, path string, exactPath bool, indexer string) (_ []types.Dump, err error) { ctx, _, endObservation := s.operations.inferClosestUploads.With(ctx, &err, observation.Args{ LogFields: []log.Field{log.Int("repositoryID", repositoryID), log.String("commit", commit), log.String("path", path), log.Bool("exactPath", exactPath), log.String("indexer", indexer)}, }) @@ -511,7 +517,7 @@ func (s *Service) InferClosestUploads(ctx context.Context, repositoryID int, com return dumps, nil } -func (s *Service) FindClosestDumps(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string) (_ []shared.Dump, err error) { +func (s *Service) FindClosestDumps(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string) (_ []types.Dump, err error) { ctx, _, endObservation := s.operations.findClosestDumps.With(ctx, &err, observation.Args{ LogFields: []log.Field{ log.Int("repositoryID", repositoryID), log.String("commit", commit), log.String("path", path), @@ -523,7 +529,7 @@ func (s *Service) FindClosestDumps(ctx context.Context, repositoryID int, commit return s.store.FindClosestDumps(ctx, repositoryID, commit, path, rootMustEnclosePath, indexer) } -func (s *Service) FindClosestDumpsFromGraphFragment(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string, commitGraph *gitdomain.CommitGraph) (_ []shared.Dump, err error) { +func (s *Service) FindClosestDumpsFromGraphFragment(ctx context.Context, repositoryID int, commit, path string, rootMustEnclosePath bool, indexer string, commitGraph *gitdomain.CommitGraph) (_ []types.Dump, err error) { ctx, _, endObservation := s.operations.findClosestDumpsFromGraphFragment.With(ctx, &err, observation.Args{ LogFields: []log.Field{ log.Int("repositoryID", repositoryID), log.String("commit", commit), log.String("path", path), @@ -535,7 +541,7 @@ func (s *Service) FindClosestDumpsFromGraphFragment(ctx context.Context, reposit return s.store.FindClosestDumpsFromGraphFragment(ctx, repositoryID, commit, path, rootMustEnclosePath, indexer, commitGraph) } -func (s *Service) GetDumpsWithDefinitionsForMonikers(ctx context.Context, monikers []precise.QualifiedMonikerData) (_ []shared.Dump, err error) { +func (s *Service) GetDumpsWithDefinitionsForMonikers(ctx context.Context, monikers []precise.QualifiedMonikerData) (_ []types.Dump, err error) { ctx, _, endObservation := s.operations.getDumpsWithDefinitionsForMonikers.With(ctx, &err, observation.Args{ LogFields: []log.Field{log.String("monikers", fmt.Sprintf("%v", monikers))}, }) @@ -544,7 +550,7 @@ func (s *Service) GetDumpsWithDefinitionsForMonikers(ctx context.Context, monike return s.store.GetDumpsWithDefinitionsForMonikers(ctx, monikers) } -func (s *Service) GetDumpsByIDs(ctx context.Context, ids []int) (_ []shared.Dump, err error) { +func (s *Service) GetDumpsByIDs(ctx context.Context, ids []int) (_ []types.Dump, err error) { ctx, _, endObservation := s.operations.getDumpsByIDs.With(ctx, &err, observation.Args{ LogFields: []log.Field{log.Int("total_ids", len(ids)), log.String("ids", fmt.Sprintf("%v", ids))}, }) @@ -558,7 +564,7 @@ func (s *Service) HardDeleteExpiredUploads(ctx context.Context) (count int, err defer endObservation(1, observation.Args{}) const uploadsBatchSize = 100 - options := shared.GetUploadsOptions{ + options := types.GetUploadsOptions{ State: "deleted", Limit: uploadsBatchSize, AllowExpired: true, @@ -611,7 +617,7 @@ func (s *Service) UpdatePackageReferences(ctx context.Context, dumpID int, refer return s.store.UpdatePackageReferences(ctx, dumpID, references) } -func (s *Service) GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []shared.UploadLog, err error) { +func (s *Service) GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []types.UploadLog, err error) { ctx, _, endObservation := s.operations.getAuditLogsForUpload.With(ctx, &err, observation.Args{ LogFields: []log.Field{log.Int("uploadID", uploadID)}, }) @@ -717,7 +723,16 @@ func (s *Service) getCommitDate(ctx context.Context, repositoryID int, commit st return commitDateString, nil } -func uploadIDs(uploads []shared.Upload) []int { +func (s *Service) GetListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) (_ []*gitdomain.Tag, err error) { + ctx, _, endObservation := s.operations.getListTags.With(ctx, &err, observation.Args{ + LogFields: []log.Field{log.String("repo", string(repo)), log.String("commitObjs", fmt.Sprintf("%v", commitObjs))}, + }) + defer endObservation(1, observation.Args{}) + + return s.gitserverClient.ListTags(ctx, repo, commitObjs...) +} + +func uploadIDs(uploads []types.Upload) []int { ids := make([]int, 0, len(uploads)) for i := range uploads { ids = append(ids, uploads[i].ID) diff --git a/internal/codeintel/uploads/shared/iface.go b/internal/codeintel/uploads/shared/iface.go index 07a2290155c..b08cdf429b0 100644 --- a/internal/codeintel/uploads/shared/iface.go +++ b/internal/codeintel/uploads/shared/iface.go @@ -4,6 +4,7 @@ import ( "context" "time" + "github.com/sourcegraph/sourcegraph/internal/api" "github.com/sourcegraph/sourcegraph/internal/gitserver" "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" ) @@ -12,4 +13,5 @@ type GitserverClient interface { CommitGraph(ctx context.Context, repositoryID int, opts gitserver.CommitGraphOptions) (_ *gitdomain.CommitGraph, err error) RefDescriptions(ctx context.Context, repositoryID int, pointedAt ...string) (_ map[string][]gitdomain.RefDescription, err error) CommitDate(ctx context.Context, repositoryID int, commit string) (string, time.Time, bool, error) + ListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) (_ []*gitdomain.Tag, err error) } diff --git a/internal/codeintel/uploads/shared/types.go b/internal/codeintel/uploads/shared/types.go index 9c049184356..5787bd81616 100644 --- a/internal/codeintel/uploads/shared/types.go +++ b/internal/codeintel/uploads/shared/types.go @@ -2,61 +2,16 @@ package shared import ( "database/sql" + "database/sql/driver" + "encoding/json" "time" "github.com/sourcegraph/sourcegraph/internal/codeintel/stores/lsifstore" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" "github.com/sourcegraph/sourcegraph/internal/database/basestore" + "github.com/sourcegraph/sourcegraph/lib/errors" ) -// Upload is a subset of the lsif_uploads table and stores both processed and unprocessed -// records. -type Upload struct { - ID int - Commit string - Root string - VisibleAtTip bool - UploadedAt time.Time - State string - FailureMessage *string - StartedAt *time.Time - FinishedAt *time.Time - ProcessAfter *time.Time - NumResets int - NumFailures int - RepositoryID int - RepositoryName string - Indexer string - IndexerVersion string - NumParts int - UploadedParts []int - UploadSize *int64 - UncompressedSize *int64 - Rank *int - AssociatedIndexID *int -} - -// Dump is a subset of the lsif_uploads table (queried via the lsif_dumps_with_repository_name view) -// and stores only processed records. -type Dump struct { - ID int - Commit string - Root string - VisibleAtTip bool - UploadedAt time.Time - State string - FailureMessage *string - StartedAt *time.Time - FinishedAt *time.Time - ProcessAfter *time.Time - NumResets int - NumFailures int - RepositoryID int - RepositoryName string - Indexer string - IndexerVersion string - AssociatedIndexID *int -} - type SourcedCommits struct { RepositoryID int RepositoryName string @@ -105,12 +60,18 @@ type CursorAdjustedUpload struct { // current target path and position adjusted so that it matches the data within the // underlying index. type AdjustedUpload struct { - Upload Dump + Upload types.Dump AdjustedPath string AdjustedPosition lsifstore.Position AdjustedPathInBundle string } +// Range is an inclusive bounds within a file. +type Range struct { + Start Position + End Position +} + // Position is a unique position within a file. type Position struct { Line int @@ -206,7 +167,7 @@ func (s *sliceScanner) Close() error { type UploadsWithRepositoryNamespace struct { Root string Indexer string - Uploads []Upload + Uploads []types.Upload } type UploadLog struct { @@ -225,3 +186,71 @@ type UploadLog struct { Reason *string Operation string } + +// Index is a subset of the lsif_indexes table and stores both processed and unprocessed +// records. +type Index struct { + ID int `json:"id"` + Commit string `json:"commit"` + QueuedAt time.Time `json:"queuedAt"` + State string `json:"state"` + FailureMessage *string `json:"failureMessage"` + StartedAt *time.Time `json:"startedAt"` + FinishedAt *time.Time `json:"finishedAt"` + ProcessAfter *time.Time `json:"processAfter"` + NumResets int `json:"numResets"` + NumFailures int `json:"numFailures"` + RepositoryID int `json:"repositoryId"` + LocalSteps []string `json:"local_steps"` + RepositoryName string `json:"repositoryName"` + DockerSteps []DockerStep `json:"docker_steps"` + Root string `json:"root"` + Indexer string `json:"indexer"` + IndexerArgs []string `json:"indexer_args"` // TODO - convert this to `IndexCommand string` + Outfile string `json:"outfile"` + ExecutionLogs []ExecutionLogEntry `json:"execution_logs"` + Rank *int `json:"placeInQueue"` + AssociatedUploadID *int `json:"associatedUpload"` +} + +type DockerStep struct { + Root string `json:"root"` + Image string `json:"image"` + Commands []string `json:"commands"` +} + +func (s *DockerStep) Scan(value any) error { + b, ok := value.([]byte) + if !ok { + return errors.Errorf("value is not []byte: %T", value) + } + + return json.Unmarshal(b, &s) +} + +func (s DockerStep) Value() (driver.Value, error) { + return json.Marshal(s) +} + +// ExecutionLogEntry represents a command run by the executor. +type ExecutionLogEntry struct { + Key string `json:"key"` + Command []string `json:"command"` + StartTime time.Time `json:"startTime"` + ExitCode *int `json:"exitCode,omitempty"` + Out string `json:"out,omitempty"` + DurationMs *int `json:"durationMs,omitempty"` +} + +func (e *ExecutionLogEntry) Scan(value any) error { + b, ok := value.([]byte) + if !ok { + return errors.Errorf("value is not []byte: %T", value) + } + + return json.Unmarshal(b, &e) +} + +func (e ExecutionLogEntry) Value() (driver.Value, error) { + return json.Marshal(e) +} diff --git a/internal/codeintel/uploads/transport/graphql/commitgraph_resolver.go b/internal/codeintel/uploads/transport/graphql/commitgraph_resolver.go index 72465f82260..fccf9aaa6d5 100644 --- a/internal/codeintel/uploads/transport/graphql/commitgraph_resolver.go +++ b/internal/codeintel/uploads/transport/graphql/commitgraph_resolver.go @@ -3,16 +3,19 @@ package graphql import ( "context" "time" - - "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend" ) +type CodeIntelligenceCommitGraphResolver interface { + Stale(ctx context.Context) (bool, error) + UpdatedAt(ctx context.Context) (*DateTime, error) +} + type CommitGraphResolver struct { stale bool updatedAt *time.Time } -func NewCommitGraphResolver(stale bool, updatedAt *time.Time) *CommitGraphResolver { +func NewCommitGraphResolver(stale bool, updatedAt *time.Time) CodeIntelligenceCommitGraphResolver { return &CommitGraphResolver{ stale: stale, updatedAt: updatedAt, @@ -23,6 +26,6 @@ func (r *CommitGraphResolver) Stale(ctx context.Context) (bool, error) { return r.stale, nil } -func (r *CommitGraphResolver) UpdatedAt(ctx context.Context) (*graphqlbackend.DateTime, error) { - return graphqlbackend.DateTimeOrNil(r.updatedAt), nil +func (r *CommitGraphResolver) UpdatedAt(ctx context.Context) (*DateTime, error) { + return DateTimeOrNil(r.updatedAt), nil } diff --git a/internal/codeintel/uploads/transport/graphql/iface.go b/internal/codeintel/uploads/transport/graphql/iface.go new file mode 100644 index 00000000000..b83e9d96fc4 --- /dev/null +++ b/internal/codeintel/uploads/transport/graphql/iface.go @@ -0,0 +1,33 @@ +package graphql + +import ( + "context" + "time" + + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/database" + "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" +) + +type UploadService interface { + GetCommitGraphMetadata(ctx context.Context, repositoryID int) (stale bool, updatedAt *time.Time, err error) + GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []types.UploadLog, err error) + GetListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) (_ []*gitdomain.Tag, err error) + GetUploadDocumentsForPath(ctx context.Context, bundleID int, pathPattern string) (_ []string, _ int, err error) + GetUploads(ctx context.Context, opts types.GetUploadsOptions) (uploads []types.Upload, totalCount int, err error) + GetUploadsByIDs(ctx context.Context, ids ...int) (_ []types.Upload, err error) + DeleteUploadByID(ctx context.Context, id int) (_ bool, err error) +} + +type AutoIndexingService interface { + GetIndexByID(ctx context.Context, id int) (_ types.Index, _ bool, err error) + GetIndexes(ctx context.Context, opts types.GetIndexesOptions) (_ []types.Index, _ int, err error) + GetIndexesByIDs(ctx context.Context, ids ...int) (_ []types.Index, err error) + GetListTags(ctx context.Context, repo api.RepoName, commitObjs ...string) (_ []*gitdomain.Tag, err error) + GetUnsafeDB() database.DB +} + +type PolicyService interface { + GetRetentionPolicyOverview(ctx context.Context, upload types.Upload, matchesOnly bool, first int, after int64, query string, now time.Time) (matches []types.RetentionPolicyMatchCandidate, totalCount int, err error) +} diff --git a/internal/codeintel/uploads/transport/graphql/mocks_temp.go b/internal/codeintel/uploads/transport/graphql/mocks_temp.go new file mode 100644 index 00000000000..4ae8049aee2 --- /dev/null +++ b/internal/codeintel/uploads/transport/graphql/mocks_temp.go @@ -0,0 +1,1811 @@ +// Code generated by go-mockgen 1.3.4; DO NOT EDIT. +// +// This file was generated by running `sg generate` (or `go-mockgen`) at the root of +// this repository. To add additional mocks to this or another package, add a new entry +// to the mockgen.yaml file in the root of this repository. + +package graphql + +import ( + "context" + "sync" + "time" + + api "github.com/sourcegraph/sourcegraph/internal/api" + types "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + database "github.com/sourcegraph/sourcegraph/internal/database" + gitdomain "github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain" +) + +// MockAutoIndexingService is a mock implementation of the +// AutoIndexingService interface (from the package +// github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/transport/graphql) +// used for unit testing. +type MockAutoIndexingService struct { + // GetIndexByIDFunc is an instance of a mock function object controlling + // the behavior of the method GetIndexByID. + GetIndexByIDFunc *AutoIndexingServiceGetIndexByIDFunc + // GetIndexesFunc is an instance of a mock function object controlling + // the behavior of the method GetIndexes. + GetIndexesFunc *AutoIndexingServiceGetIndexesFunc + // GetIndexesByIDsFunc is an instance of a mock function object + // controlling the behavior of the method GetIndexesByIDs. + GetIndexesByIDsFunc *AutoIndexingServiceGetIndexesByIDsFunc + // GetListTagsFunc is an instance of a mock function object controlling + // the behavior of the method GetListTags. + GetListTagsFunc *AutoIndexingServiceGetListTagsFunc + // GetUnsafeDBFunc is an instance of a mock function object controlling + // the behavior of the method GetUnsafeDB. + GetUnsafeDBFunc *AutoIndexingServiceGetUnsafeDBFunc +} + +// NewMockAutoIndexingService creates a new mock of the AutoIndexingService +// interface. All methods return zero values for all results, unless +// overwritten. +func NewMockAutoIndexingService() *MockAutoIndexingService { + return &MockAutoIndexingService{ + GetIndexByIDFunc: &AutoIndexingServiceGetIndexByIDFunc{ + defaultHook: func(context.Context, int) (r0 types.Index, r1 bool, r2 error) { + return + }, + }, + GetIndexesFunc: &AutoIndexingServiceGetIndexesFunc{ + defaultHook: func(context.Context, types.GetIndexesOptions) (r0 []types.Index, r1 int, r2 error) { + return + }, + }, + GetIndexesByIDsFunc: &AutoIndexingServiceGetIndexesByIDsFunc{ + defaultHook: func(context.Context, ...int) (r0 []types.Index, r1 error) { + return + }, + }, + GetListTagsFunc: &AutoIndexingServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) (r0 []*gitdomain.Tag, r1 error) { + return + }, + }, + GetUnsafeDBFunc: &AutoIndexingServiceGetUnsafeDBFunc{ + defaultHook: func() (r0 database.DB) { + return + }, + }, + } +} + +// NewStrictMockAutoIndexingService creates a new mock of the +// AutoIndexingService interface. All methods panic on invocation, unless +// overwritten. +func NewStrictMockAutoIndexingService() *MockAutoIndexingService { + return &MockAutoIndexingService{ + GetIndexByIDFunc: &AutoIndexingServiceGetIndexByIDFunc{ + defaultHook: func(context.Context, int) (types.Index, bool, error) { + panic("unexpected invocation of MockAutoIndexingService.GetIndexByID") + }, + }, + GetIndexesFunc: &AutoIndexingServiceGetIndexesFunc{ + defaultHook: func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + panic("unexpected invocation of MockAutoIndexingService.GetIndexes") + }, + }, + GetIndexesByIDsFunc: &AutoIndexingServiceGetIndexesByIDsFunc{ + defaultHook: func(context.Context, ...int) ([]types.Index, error) { + panic("unexpected invocation of MockAutoIndexingService.GetIndexesByIDs") + }, + }, + GetListTagsFunc: &AutoIndexingServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + panic("unexpected invocation of MockAutoIndexingService.GetListTags") + }, + }, + GetUnsafeDBFunc: &AutoIndexingServiceGetUnsafeDBFunc{ + defaultHook: func() database.DB { + panic("unexpected invocation of MockAutoIndexingService.GetUnsafeDB") + }, + }, + } +} + +// NewMockAutoIndexingServiceFrom creates a new mock of the +// MockAutoIndexingService interface. All methods delegate to the given +// implementation, unless overwritten. +func NewMockAutoIndexingServiceFrom(i AutoIndexingService) *MockAutoIndexingService { + return &MockAutoIndexingService{ + GetIndexByIDFunc: &AutoIndexingServiceGetIndexByIDFunc{ + defaultHook: i.GetIndexByID, + }, + GetIndexesFunc: &AutoIndexingServiceGetIndexesFunc{ + defaultHook: i.GetIndexes, + }, + GetIndexesByIDsFunc: &AutoIndexingServiceGetIndexesByIDsFunc{ + defaultHook: i.GetIndexesByIDs, + }, + GetListTagsFunc: &AutoIndexingServiceGetListTagsFunc{ + defaultHook: i.GetListTags, + }, + GetUnsafeDBFunc: &AutoIndexingServiceGetUnsafeDBFunc{ + defaultHook: i.GetUnsafeDB, + }, + } +} + +// AutoIndexingServiceGetIndexByIDFunc describes the behavior when the +// GetIndexByID method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetIndexByIDFunc struct { + defaultHook func(context.Context, int) (types.Index, bool, error) + hooks []func(context.Context, int) (types.Index, bool, error) + history []AutoIndexingServiceGetIndexByIDFuncCall + mutex sync.Mutex +} + +// GetIndexByID delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetIndexByID(v0 context.Context, v1 int) (types.Index, bool, error) { + r0, r1, r2 := m.GetIndexByIDFunc.nextHook()(v0, v1) + m.GetIndexByIDFunc.appendCall(AutoIndexingServiceGetIndexByIDFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the GetIndexByID method +// of the parent MockAutoIndexingService instance is invoked and the hook +// queue is empty. +func (f *AutoIndexingServiceGetIndexByIDFunc) SetDefaultHook(hook func(context.Context, int) (types.Index, bool, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetIndexByID method of the parent MockAutoIndexingService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *AutoIndexingServiceGetIndexByIDFunc) PushHook(hook func(context.Context, int) (types.Index, bool, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetIndexByIDFunc) SetDefaultReturn(r0 types.Index, r1 bool, r2 error) { + f.SetDefaultHook(func(context.Context, int) (types.Index, bool, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetIndexByIDFunc) PushReturn(r0 types.Index, r1 bool, r2 error) { + f.PushHook(func(context.Context, int) (types.Index, bool, error) { + return r0, r1, r2 + }) +} + +func (f *AutoIndexingServiceGetIndexByIDFunc) nextHook() func(context.Context, int) (types.Index, bool, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetIndexByIDFunc) appendCall(r0 AutoIndexingServiceGetIndexByIDFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetIndexByIDFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetIndexByIDFunc) History() []AutoIndexingServiceGetIndexByIDFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetIndexByIDFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetIndexByIDFuncCall is an object that describes an +// invocation of method GetIndexByID on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetIndexByIDFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 types.Index + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 bool + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetIndexByIDFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetIndexByIDFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// AutoIndexingServiceGetIndexesFunc describes the behavior when the +// GetIndexes method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetIndexesFunc struct { + defaultHook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) + hooks []func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) + history []AutoIndexingServiceGetIndexesFuncCall + mutex sync.Mutex +} + +// GetIndexes delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetIndexes(v0 context.Context, v1 types.GetIndexesOptions) ([]types.Index, int, error) { + r0, r1, r2 := m.GetIndexesFunc.nextHook()(v0, v1) + m.GetIndexesFunc.appendCall(AutoIndexingServiceGetIndexesFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the GetIndexes method of +// the parent MockAutoIndexingService instance is invoked and the hook queue +// is empty. +func (f *AutoIndexingServiceGetIndexesFunc) SetDefaultHook(hook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetIndexes method of the parent MockAutoIndexingService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *AutoIndexingServiceGetIndexesFunc) PushHook(hook func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetIndexesFunc) SetDefaultReturn(r0 []types.Index, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetIndexesFunc) PushReturn(r0 []types.Index, r1 int, r2 error) { + f.PushHook(func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + return r0, r1, r2 + }) +} + +func (f *AutoIndexingServiceGetIndexesFunc) nextHook() func(context.Context, types.GetIndexesOptions) ([]types.Index, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetIndexesFunc) appendCall(r0 AutoIndexingServiceGetIndexesFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetIndexesFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetIndexesFunc) History() []AutoIndexingServiceGetIndexesFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetIndexesFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetIndexesFuncCall is an object that describes an +// invocation of method GetIndexes on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetIndexesFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 types.GetIndexesOptions + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Index + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetIndexesFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetIndexesFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// AutoIndexingServiceGetIndexesByIDsFunc describes the behavior when the +// GetIndexesByIDs method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetIndexesByIDsFunc struct { + defaultHook func(context.Context, ...int) ([]types.Index, error) + hooks []func(context.Context, ...int) ([]types.Index, error) + history []AutoIndexingServiceGetIndexesByIDsFuncCall + mutex sync.Mutex +} + +// GetIndexesByIDs delegates to the next hook function in the queue and +// stores the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetIndexesByIDs(v0 context.Context, v1 ...int) ([]types.Index, error) { + r0, r1 := m.GetIndexesByIDsFunc.nextHook()(v0, v1...) + m.GetIndexesByIDsFunc.appendCall(AutoIndexingServiceGetIndexesByIDsFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetIndexesByIDs +// method of the parent MockAutoIndexingService instance is invoked and the +// hook queue is empty. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]types.Index, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetIndexesByIDs method of the parent MockAutoIndexingService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) PushHook(hook func(context.Context, ...int) ([]types.Index, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) SetDefaultReturn(r0 []types.Index, r1 error) { + f.SetDefaultHook(func(context.Context, ...int) ([]types.Index, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) PushReturn(r0 []types.Index, r1 error) { + f.PushHook(func(context.Context, ...int) ([]types.Index, error) { + return r0, r1 + }) +} + +func (f *AutoIndexingServiceGetIndexesByIDsFunc) nextHook() func(context.Context, ...int) ([]types.Index, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetIndexesByIDsFunc) appendCall(r0 AutoIndexingServiceGetIndexesByIDsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetIndexesByIDsFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetIndexesByIDsFunc) History() []AutoIndexingServiceGetIndexesByIDsFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetIndexesByIDsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetIndexesByIDsFuncCall is an object that describes an +// invocation of method GetIndexesByIDs on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetIndexesByIDsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg1 []int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Index + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c AutoIndexingServiceGetIndexesByIDsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg1 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetIndexesByIDsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// AutoIndexingServiceGetListTagsFunc describes the behavior when the +// GetListTags method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetListTagsFunc struct { + defaultHook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + hooks []func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + history []AutoIndexingServiceGetListTagsFuncCall + mutex sync.Mutex +} + +// GetListTags delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetListTags(v0 context.Context, v1 api.RepoName, v2 ...string) ([]*gitdomain.Tag, error) { + r0, r1 := m.GetListTagsFunc.nextHook()(v0, v1, v2...) + m.GetListTagsFunc.appendCall(AutoIndexingServiceGetListTagsFuncCall{v0, v1, v2, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetListTags method +// of the parent MockAutoIndexingService instance is invoked and the hook +// queue is empty. +func (f *AutoIndexingServiceGetListTagsFunc) SetDefaultHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetListTags method of the parent MockAutoIndexingService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *AutoIndexingServiceGetListTagsFunc) PushHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetListTagsFunc) SetDefaultReturn(r0 []*gitdomain.Tag, r1 error) { + f.SetDefaultHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetListTagsFunc) PushReturn(r0 []*gitdomain.Tag, r1 error) { + f.PushHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +func (f *AutoIndexingServiceGetListTagsFunc) nextHook() func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetListTagsFunc) appendCall(r0 AutoIndexingServiceGetListTagsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetListTagsFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetListTagsFunc) History() []AutoIndexingServiceGetListTagsFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetListTagsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetListTagsFuncCall is an object that describes an +// invocation of method GetListTags on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetListTagsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 api.RepoName + // Arg2 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg2 []string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []*gitdomain.Tag + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c AutoIndexingServiceGetListTagsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg2 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0, c.Arg1}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetListTagsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// AutoIndexingServiceGetUnsafeDBFunc describes the behavior when the +// GetUnsafeDB method of the parent MockAutoIndexingService instance is +// invoked. +type AutoIndexingServiceGetUnsafeDBFunc struct { + defaultHook func() database.DB + hooks []func() database.DB + history []AutoIndexingServiceGetUnsafeDBFuncCall + mutex sync.Mutex +} + +// GetUnsafeDB delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockAutoIndexingService) GetUnsafeDB() database.DB { + r0 := m.GetUnsafeDBFunc.nextHook()() + m.GetUnsafeDBFunc.appendCall(AutoIndexingServiceGetUnsafeDBFuncCall{r0}) + return r0 +} + +// SetDefaultHook sets function that is called when the GetUnsafeDB method +// of the parent MockAutoIndexingService instance is invoked and the hook +// queue is empty. +func (f *AutoIndexingServiceGetUnsafeDBFunc) SetDefaultHook(hook func() database.DB) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUnsafeDB method of the parent MockAutoIndexingService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *AutoIndexingServiceGetUnsafeDBFunc) PushHook(hook func() database.DB) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *AutoIndexingServiceGetUnsafeDBFunc) SetDefaultReturn(r0 database.DB) { + f.SetDefaultHook(func() database.DB { + return r0 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *AutoIndexingServiceGetUnsafeDBFunc) PushReturn(r0 database.DB) { + f.PushHook(func() database.DB { + return r0 + }) +} + +func (f *AutoIndexingServiceGetUnsafeDBFunc) nextHook() func() database.DB { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *AutoIndexingServiceGetUnsafeDBFunc) appendCall(r0 AutoIndexingServiceGetUnsafeDBFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of AutoIndexingServiceGetUnsafeDBFuncCall +// objects describing the invocations of this function. +func (f *AutoIndexingServiceGetUnsafeDBFunc) History() []AutoIndexingServiceGetUnsafeDBFuncCall { + f.mutex.Lock() + history := make([]AutoIndexingServiceGetUnsafeDBFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// AutoIndexingServiceGetUnsafeDBFuncCall is an object that describes an +// invocation of method GetUnsafeDB on an instance of +// MockAutoIndexingService. +type AutoIndexingServiceGetUnsafeDBFuncCall struct { + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 database.DB +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c AutoIndexingServiceGetUnsafeDBFuncCall) Args() []interface{} { + return []interface{}{} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c AutoIndexingServiceGetUnsafeDBFuncCall) Results() []interface{} { + return []interface{}{c.Result0} +} + +// MockPolicyService is a mock implementation of the PolicyService interface +// (from the package +// github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/transport/graphql) +// used for unit testing. +type MockPolicyService struct { + // GetRetentionPolicyOverviewFunc is an instance of a mock function + // object controlling the behavior of the method + // GetRetentionPolicyOverview. + GetRetentionPolicyOverviewFunc *PolicyServiceGetRetentionPolicyOverviewFunc +} + +// NewMockPolicyService creates a new mock of the PolicyService interface. +// All methods return zero values for all results, unless overwritten. +func NewMockPolicyService() *MockPolicyService { + return &MockPolicyService{ + GetRetentionPolicyOverviewFunc: &PolicyServiceGetRetentionPolicyOverviewFunc{ + defaultHook: func(context.Context, types.Upload, bool, int, int64, string, time.Time) (r0 []types.RetentionPolicyMatchCandidate, r1 int, r2 error) { + return + }, + }, + } +} + +// NewStrictMockPolicyService creates a new mock of the PolicyService +// interface. All methods panic on invocation, unless overwritten. +func NewStrictMockPolicyService() *MockPolicyService { + return &MockPolicyService{ + GetRetentionPolicyOverviewFunc: &PolicyServiceGetRetentionPolicyOverviewFunc{ + defaultHook: func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + panic("unexpected invocation of MockPolicyService.GetRetentionPolicyOverview") + }, + }, + } +} + +// NewMockPolicyServiceFrom creates a new mock of the MockPolicyService +// interface. All methods delegate to the given implementation, unless +// overwritten. +func NewMockPolicyServiceFrom(i PolicyService) *MockPolicyService { + return &MockPolicyService{ + GetRetentionPolicyOverviewFunc: &PolicyServiceGetRetentionPolicyOverviewFunc{ + defaultHook: i.GetRetentionPolicyOverview, + }, + } +} + +// PolicyServiceGetRetentionPolicyOverviewFunc describes the behavior when +// the GetRetentionPolicyOverview method of the parent MockPolicyService +// instance is invoked. +type PolicyServiceGetRetentionPolicyOverviewFunc struct { + defaultHook func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) + hooks []func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) + history []PolicyServiceGetRetentionPolicyOverviewFuncCall + mutex sync.Mutex +} + +// GetRetentionPolicyOverview delegates to the next hook function in the +// queue and stores the parameter and result values of this invocation. +func (m *MockPolicyService) GetRetentionPolicyOverview(v0 context.Context, v1 types.Upload, v2 bool, v3 int, v4 int64, v5 string, v6 time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + r0, r1, r2 := m.GetRetentionPolicyOverviewFunc.nextHook()(v0, v1, v2, v3, v4, v5, v6) + m.GetRetentionPolicyOverviewFunc.appendCall(PolicyServiceGetRetentionPolicyOverviewFuncCall{v0, v1, v2, v3, v4, v5, v6, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the +// GetRetentionPolicyOverview method of the parent MockPolicyService +// instance is invoked and the hook queue is empty. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) SetDefaultHook(hook func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetRetentionPolicyOverview method of the parent MockPolicyService +// instance invokes the hook at the front of the queue and discards it. +// After the queue is empty, the default hook function is invoked for any +// future action. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) PushHook(hook func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) SetDefaultReturn(r0 []types.RetentionPolicyMatchCandidate, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) PushReturn(r0 []types.RetentionPolicyMatchCandidate, r1 int, r2 error) { + f.PushHook(func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + return r0, r1, r2 + }) +} + +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) nextHook() func(context.Context, types.Upload, bool, int, int64, string, time.Time) ([]types.RetentionPolicyMatchCandidate, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) appendCall(r0 PolicyServiceGetRetentionPolicyOverviewFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// PolicyServiceGetRetentionPolicyOverviewFuncCall objects describing the +// invocations of this function. +func (f *PolicyServiceGetRetentionPolicyOverviewFunc) History() []PolicyServiceGetRetentionPolicyOverviewFuncCall { + f.mutex.Lock() + history := make([]PolicyServiceGetRetentionPolicyOverviewFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// PolicyServiceGetRetentionPolicyOverviewFuncCall is an object that +// describes an invocation of method GetRetentionPolicyOverview on an +// instance of MockPolicyService. +type PolicyServiceGetRetentionPolicyOverviewFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 types.Upload + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 bool + // Arg3 is the value of the 4th argument passed to this method + // invocation. + Arg3 int + // Arg4 is the value of the 5th argument passed to this method + // invocation. + Arg4 int64 + // Arg5 is the value of the 6th argument passed to this method + // invocation. + Arg5 string + // Arg6 is the value of the 7th argument passed to this method + // invocation. + Arg6 time.Time + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.RetentionPolicyMatchCandidate + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c PolicyServiceGetRetentionPolicyOverviewFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2, c.Arg3, c.Arg4, c.Arg5, c.Arg6} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c PolicyServiceGetRetentionPolicyOverviewFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// MockUploadService is a mock implementation of the UploadService interface +// (from the package +// github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/transport/graphql) +// used for unit testing. +type MockUploadService struct { + // DeleteUploadByIDFunc is an instance of a mock function object + // controlling the behavior of the method DeleteUploadByID. + DeleteUploadByIDFunc *UploadServiceDeleteUploadByIDFunc + // GetAuditLogsForUploadFunc is an instance of a mock function object + // controlling the behavior of the method GetAuditLogsForUpload. + GetAuditLogsForUploadFunc *UploadServiceGetAuditLogsForUploadFunc + // GetCommitGraphMetadataFunc is an instance of a mock function object + // controlling the behavior of the method GetCommitGraphMetadata. + GetCommitGraphMetadataFunc *UploadServiceGetCommitGraphMetadataFunc + // GetListTagsFunc is an instance of a mock function object controlling + // the behavior of the method GetListTags. + GetListTagsFunc *UploadServiceGetListTagsFunc + // GetUploadDocumentsForPathFunc is an instance of a mock function + // object controlling the behavior of the method + // GetUploadDocumentsForPath. + GetUploadDocumentsForPathFunc *UploadServiceGetUploadDocumentsForPathFunc + // GetUploadsFunc is an instance of a mock function object controlling + // the behavior of the method GetUploads. + GetUploadsFunc *UploadServiceGetUploadsFunc + // GetUploadsByIDsFunc is an instance of a mock function object + // controlling the behavior of the method GetUploadsByIDs. + GetUploadsByIDsFunc *UploadServiceGetUploadsByIDsFunc +} + +// NewMockUploadService creates a new mock of the UploadService interface. +// All methods return zero values for all results, unless overwritten. +func NewMockUploadService() *MockUploadService { + return &MockUploadService{ + DeleteUploadByIDFunc: &UploadServiceDeleteUploadByIDFunc{ + defaultHook: func(context.Context, int) (r0 bool, r1 error) { + return + }, + }, + GetAuditLogsForUploadFunc: &UploadServiceGetAuditLogsForUploadFunc{ + defaultHook: func(context.Context, int) (r0 []types.UploadLog, r1 error) { + return + }, + }, + GetCommitGraphMetadataFunc: &UploadServiceGetCommitGraphMetadataFunc{ + defaultHook: func(context.Context, int) (r0 bool, r1 *time.Time, r2 error) { + return + }, + }, + GetListTagsFunc: &UploadServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) (r0 []*gitdomain.Tag, r1 error) { + return + }, + }, + GetUploadDocumentsForPathFunc: &UploadServiceGetUploadDocumentsForPathFunc{ + defaultHook: func(context.Context, int, string) (r0 []string, r1 int, r2 error) { + return + }, + }, + GetUploadsFunc: &UploadServiceGetUploadsFunc{ + defaultHook: func(context.Context, types.GetUploadsOptions) (r0 []types.Upload, r1 int, r2 error) { + return + }, + }, + GetUploadsByIDsFunc: &UploadServiceGetUploadsByIDsFunc{ + defaultHook: func(context.Context, ...int) (r0 []types.Upload, r1 error) { + return + }, + }, + } +} + +// NewStrictMockUploadService creates a new mock of the UploadService +// interface. All methods panic on invocation, unless overwritten. +func NewStrictMockUploadService() *MockUploadService { + return &MockUploadService{ + DeleteUploadByIDFunc: &UploadServiceDeleteUploadByIDFunc{ + defaultHook: func(context.Context, int) (bool, error) { + panic("unexpected invocation of MockUploadService.DeleteUploadByID") + }, + }, + GetAuditLogsForUploadFunc: &UploadServiceGetAuditLogsForUploadFunc{ + defaultHook: func(context.Context, int) ([]types.UploadLog, error) { + panic("unexpected invocation of MockUploadService.GetAuditLogsForUpload") + }, + }, + GetCommitGraphMetadataFunc: &UploadServiceGetCommitGraphMetadataFunc{ + defaultHook: func(context.Context, int) (bool, *time.Time, error) { + panic("unexpected invocation of MockUploadService.GetCommitGraphMetadata") + }, + }, + GetListTagsFunc: &UploadServiceGetListTagsFunc{ + defaultHook: func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + panic("unexpected invocation of MockUploadService.GetListTags") + }, + }, + GetUploadDocumentsForPathFunc: &UploadServiceGetUploadDocumentsForPathFunc{ + defaultHook: func(context.Context, int, string) ([]string, int, error) { + panic("unexpected invocation of MockUploadService.GetUploadDocumentsForPath") + }, + }, + GetUploadsFunc: &UploadServiceGetUploadsFunc{ + defaultHook: func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + panic("unexpected invocation of MockUploadService.GetUploads") + }, + }, + GetUploadsByIDsFunc: &UploadServiceGetUploadsByIDsFunc{ + defaultHook: func(context.Context, ...int) ([]types.Upload, error) { + panic("unexpected invocation of MockUploadService.GetUploadsByIDs") + }, + }, + } +} + +// NewMockUploadServiceFrom creates a new mock of the MockUploadService +// interface. All methods delegate to the given implementation, unless +// overwritten. +func NewMockUploadServiceFrom(i UploadService) *MockUploadService { + return &MockUploadService{ + DeleteUploadByIDFunc: &UploadServiceDeleteUploadByIDFunc{ + defaultHook: i.DeleteUploadByID, + }, + GetAuditLogsForUploadFunc: &UploadServiceGetAuditLogsForUploadFunc{ + defaultHook: i.GetAuditLogsForUpload, + }, + GetCommitGraphMetadataFunc: &UploadServiceGetCommitGraphMetadataFunc{ + defaultHook: i.GetCommitGraphMetadata, + }, + GetListTagsFunc: &UploadServiceGetListTagsFunc{ + defaultHook: i.GetListTags, + }, + GetUploadDocumentsForPathFunc: &UploadServiceGetUploadDocumentsForPathFunc{ + defaultHook: i.GetUploadDocumentsForPath, + }, + GetUploadsFunc: &UploadServiceGetUploadsFunc{ + defaultHook: i.GetUploads, + }, + GetUploadsByIDsFunc: &UploadServiceGetUploadsByIDsFunc{ + defaultHook: i.GetUploadsByIDs, + }, + } +} + +// UploadServiceDeleteUploadByIDFunc describes the behavior when the +// DeleteUploadByID method of the parent MockUploadService instance is +// invoked. +type UploadServiceDeleteUploadByIDFunc struct { + defaultHook func(context.Context, int) (bool, error) + hooks []func(context.Context, int) (bool, error) + history []UploadServiceDeleteUploadByIDFuncCall + mutex sync.Mutex +} + +// DeleteUploadByID delegates to the next hook function in the queue and +// stores the parameter and result values of this invocation. +func (m *MockUploadService) DeleteUploadByID(v0 context.Context, v1 int) (bool, error) { + r0, r1 := m.DeleteUploadByIDFunc.nextHook()(v0, v1) + m.DeleteUploadByIDFunc.appendCall(UploadServiceDeleteUploadByIDFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the DeleteUploadByID +// method of the parent MockUploadService instance is invoked and the hook +// queue is empty. +func (f *UploadServiceDeleteUploadByIDFunc) SetDefaultHook(hook func(context.Context, int) (bool, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// DeleteUploadByID method of the parent MockUploadService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *UploadServiceDeleteUploadByIDFunc) PushHook(hook func(context.Context, int) (bool, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadServiceDeleteUploadByIDFunc) SetDefaultReturn(r0 bool, r1 error) { + f.SetDefaultHook(func(context.Context, int) (bool, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadServiceDeleteUploadByIDFunc) PushReturn(r0 bool, r1 error) { + f.PushHook(func(context.Context, int) (bool, error) { + return r0, r1 + }) +} + +func (f *UploadServiceDeleteUploadByIDFunc) nextHook() func(context.Context, int) (bool, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadServiceDeleteUploadByIDFunc) appendCall(r0 UploadServiceDeleteUploadByIDFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadServiceDeleteUploadByIDFuncCall +// objects describing the invocations of this function. +func (f *UploadServiceDeleteUploadByIDFunc) History() []UploadServiceDeleteUploadByIDFuncCall { + f.mutex.Lock() + history := make([]UploadServiceDeleteUploadByIDFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadServiceDeleteUploadByIDFuncCall is an object that describes an +// invocation of method DeleteUploadByID on an instance of +// MockUploadService. +type UploadServiceDeleteUploadByIDFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 bool + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadServiceDeleteUploadByIDFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadServiceDeleteUploadByIDFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// UploadServiceGetAuditLogsForUploadFunc describes the behavior when the +// GetAuditLogsForUpload method of the parent MockUploadService instance is +// invoked. +type UploadServiceGetAuditLogsForUploadFunc struct { + defaultHook func(context.Context, int) ([]types.UploadLog, error) + hooks []func(context.Context, int) ([]types.UploadLog, error) + history []UploadServiceGetAuditLogsForUploadFuncCall + mutex sync.Mutex +} + +// GetAuditLogsForUpload delegates to the next hook function in the queue +// and stores the parameter and result values of this invocation. +func (m *MockUploadService) GetAuditLogsForUpload(v0 context.Context, v1 int) ([]types.UploadLog, error) { + r0, r1 := m.GetAuditLogsForUploadFunc.nextHook()(v0, v1) + m.GetAuditLogsForUploadFunc.appendCall(UploadServiceGetAuditLogsForUploadFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the +// GetAuditLogsForUpload method of the parent MockUploadService instance is +// invoked and the hook queue is empty. +func (f *UploadServiceGetAuditLogsForUploadFunc) SetDefaultHook(hook func(context.Context, int) ([]types.UploadLog, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetAuditLogsForUpload method of the parent MockUploadService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *UploadServiceGetAuditLogsForUploadFunc) PushHook(hook func(context.Context, int) ([]types.UploadLog, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadServiceGetAuditLogsForUploadFunc) SetDefaultReturn(r0 []types.UploadLog, r1 error) { + f.SetDefaultHook(func(context.Context, int) ([]types.UploadLog, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadServiceGetAuditLogsForUploadFunc) PushReturn(r0 []types.UploadLog, r1 error) { + f.PushHook(func(context.Context, int) ([]types.UploadLog, error) { + return r0, r1 + }) +} + +func (f *UploadServiceGetAuditLogsForUploadFunc) nextHook() func(context.Context, int) ([]types.UploadLog, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadServiceGetAuditLogsForUploadFunc) appendCall(r0 UploadServiceGetAuditLogsForUploadFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadServiceGetAuditLogsForUploadFuncCall +// objects describing the invocations of this function. +func (f *UploadServiceGetAuditLogsForUploadFunc) History() []UploadServiceGetAuditLogsForUploadFuncCall { + f.mutex.Lock() + history := make([]UploadServiceGetAuditLogsForUploadFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadServiceGetAuditLogsForUploadFuncCall is an object that describes an +// invocation of method GetAuditLogsForUpload on an instance of +// MockUploadService. +type UploadServiceGetAuditLogsForUploadFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.UploadLog + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadServiceGetAuditLogsForUploadFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadServiceGetAuditLogsForUploadFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// UploadServiceGetCommitGraphMetadataFunc describes the behavior when the +// GetCommitGraphMetadata method of the parent MockUploadService instance is +// invoked. +type UploadServiceGetCommitGraphMetadataFunc struct { + defaultHook func(context.Context, int) (bool, *time.Time, error) + hooks []func(context.Context, int) (bool, *time.Time, error) + history []UploadServiceGetCommitGraphMetadataFuncCall + mutex sync.Mutex +} + +// GetCommitGraphMetadata delegates to the next hook function in the queue +// and stores the parameter and result values of this invocation. +func (m *MockUploadService) GetCommitGraphMetadata(v0 context.Context, v1 int) (bool, *time.Time, error) { + r0, r1, r2 := m.GetCommitGraphMetadataFunc.nextHook()(v0, v1) + m.GetCommitGraphMetadataFunc.appendCall(UploadServiceGetCommitGraphMetadataFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the +// GetCommitGraphMetadata method of the parent MockUploadService instance is +// invoked and the hook queue is empty. +func (f *UploadServiceGetCommitGraphMetadataFunc) SetDefaultHook(hook func(context.Context, int) (bool, *time.Time, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetCommitGraphMetadata method of the parent MockUploadService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *UploadServiceGetCommitGraphMetadataFunc) PushHook(hook func(context.Context, int) (bool, *time.Time, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadServiceGetCommitGraphMetadataFunc) SetDefaultReturn(r0 bool, r1 *time.Time, r2 error) { + f.SetDefaultHook(func(context.Context, int) (bool, *time.Time, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadServiceGetCommitGraphMetadataFunc) PushReturn(r0 bool, r1 *time.Time, r2 error) { + f.PushHook(func(context.Context, int) (bool, *time.Time, error) { + return r0, r1, r2 + }) +} + +func (f *UploadServiceGetCommitGraphMetadataFunc) nextHook() func(context.Context, int) (bool, *time.Time, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadServiceGetCommitGraphMetadataFunc) appendCall(r0 UploadServiceGetCommitGraphMetadataFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadServiceGetCommitGraphMetadataFuncCall +// objects describing the invocations of this function. +func (f *UploadServiceGetCommitGraphMetadataFunc) History() []UploadServiceGetCommitGraphMetadataFuncCall { + f.mutex.Lock() + history := make([]UploadServiceGetCommitGraphMetadataFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadServiceGetCommitGraphMetadataFuncCall is an object that describes +// an invocation of method GetCommitGraphMetadata on an instance of +// MockUploadService. +type UploadServiceGetCommitGraphMetadataFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 bool + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 *time.Time + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadServiceGetCommitGraphMetadataFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadServiceGetCommitGraphMetadataFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// UploadServiceGetListTagsFunc describes the behavior when the GetListTags +// method of the parent MockUploadService instance is invoked. +type UploadServiceGetListTagsFunc struct { + defaultHook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + hooks []func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) + history []UploadServiceGetListTagsFuncCall + mutex sync.Mutex +} + +// GetListTags delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockUploadService) GetListTags(v0 context.Context, v1 api.RepoName, v2 ...string) ([]*gitdomain.Tag, error) { + r0, r1 := m.GetListTagsFunc.nextHook()(v0, v1, v2...) + m.GetListTagsFunc.appendCall(UploadServiceGetListTagsFuncCall{v0, v1, v2, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetListTags method +// of the parent MockUploadService instance is invoked and the hook queue is +// empty. +func (f *UploadServiceGetListTagsFunc) SetDefaultHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetListTags method of the parent MockUploadService instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *UploadServiceGetListTagsFunc) PushHook(hook func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadServiceGetListTagsFunc) SetDefaultReturn(r0 []*gitdomain.Tag, r1 error) { + f.SetDefaultHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadServiceGetListTagsFunc) PushReturn(r0 []*gitdomain.Tag, r1 error) { + f.PushHook(func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + return r0, r1 + }) +} + +func (f *UploadServiceGetListTagsFunc) nextHook() func(context.Context, api.RepoName, ...string) ([]*gitdomain.Tag, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadServiceGetListTagsFunc) appendCall(r0 UploadServiceGetListTagsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadServiceGetListTagsFuncCall objects +// describing the invocations of this function. +func (f *UploadServiceGetListTagsFunc) History() []UploadServiceGetListTagsFuncCall { + f.mutex.Lock() + history := make([]UploadServiceGetListTagsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadServiceGetListTagsFuncCall is an object that describes an +// invocation of method GetListTags on an instance of MockUploadService. +type UploadServiceGetListTagsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 api.RepoName + // Arg2 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg2 []string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []*gitdomain.Tag + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c UploadServiceGetListTagsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg2 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0, c.Arg1}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadServiceGetListTagsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} + +// UploadServiceGetUploadDocumentsForPathFunc describes the behavior when +// the GetUploadDocumentsForPath method of the parent MockUploadService +// instance is invoked. +type UploadServiceGetUploadDocumentsForPathFunc struct { + defaultHook func(context.Context, int, string) ([]string, int, error) + hooks []func(context.Context, int, string) ([]string, int, error) + history []UploadServiceGetUploadDocumentsForPathFuncCall + mutex sync.Mutex +} + +// GetUploadDocumentsForPath delegates to the next hook function in the +// queue and stores the parameter and result values of this invocation. +func (m *MockUploadService) GetUploadDocumentsForPath(v0 context.Context, v1 int, v2 string) ([]string, int, error) { + r0, r1, r2 := m.GetUploadDocumentsForPathFunc.nextHook()(v0, v1, v2) + m.GetUploadDocumentsForPathFunc.appendCall(UploadServiceGetUploadDocumentsForPathFuncCall{v0, v1, v2, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the +// GetUploadDocumentsForPath method of the parent MockUploadService instance +// is invoked and the hook queue is empty. +func (f *UploadServiceGetUploadDocumentsForPathFunc) SetDefaultHook(hook func(context.Context, int, string) ([]string, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUploadDocumentsForPath method of the parent MockUploadService instance +// invokes the hook at the front of the queue and discards it. After the +// queue is empty, the default hook function is invoked for any future +// action. +func (f *UploadServiceGetUploadDocumentsForPathFunc) PushHook(hook func(context.Context, int, string) ([]string, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadServiceGetUploadDocumentsForPathFunc) SetDefaultReturn(r0 []string, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, int, string) ([]string, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadServiceGetUploadDocumentsForPathFunc) PushReturn(r0 []string, r1 int, r2 error) { + f.PushHook(func(context.Context, int, string) ([]string, int, error) { + return r0, r1, r2 + }) +} + +func (f *UploadServiceGetUploadDocumentsForPathFunc) nextHook() func(context.Context, int, string) ([]string, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadServiceGetUploadDocumentsForPathFunc) appendCall(r0 UploadServiceGetUploadDocumentsForPathFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of +// UploadServiceGetUploadDocumentsForPathFuncCall objects describing the +// invocations of this function. +func (f *UploadServiceGetUploadDocumentsForPathFunc) History() []UploadServiceGetUploadDocumentsForPathFuncCall { + f.mutex.Lock() + history := make([]UploadServiceGetUploadDocumentsForPathFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadServiceGetUploadDocumentsForPathFuncCall is an object that +// describes an invocation of method GetUploadDocumentsForPath on an +// instance of MockUploadService. +type UploadServiceGetUploadDocumentsForPathFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 int + // Arg2 is the value of the 3rd argument passed to this method + // invocation. + Arg2 string + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []string + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadServiceGetUploadDocumentsForPathFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1, c.Arg2} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadServiceGetUploadDocumentsForPathFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// UploadServiceGetUploadsFunc describes the behavior when the GetUploads +// method of the parent MockUploadService instance is invoked. +type UploadServiceGetUploadsFunc struct { + defaultHook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) + hooks []func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) + history []UploadServiceGetUploadsFuncCall + mutex sync.Mutex +} + +// GetUploads delegates to the next hook function in the queue and stores +// the parameter and result values of this invocation. +func (m *MockUploadService) GetUploads(v0 context.Context, v1 types.GetUploadsOptions) ([]types.Upload, int, error) { + r0, r1, r2 := m.GetUploadsFunc.nextHook()(v0, v1) + m.GetUploadsFunc.appendCall(UploadServiceGetUploadsFuncCall{v0, v1, r0, r1, r2}) + return r0, r1, r2 +} + +// SetDefaultHook sets function that is called when the GetUploads method of +// the parent MockUploadService instance is invoked and the hook queue is +// empty. +func (f *UploadServiceGetUploadsFunc) SetDefaultHook(hook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUploads method of the parent MockUploadService instance invokes the +// hook at the front of the queue and discards it. After the queue is empty, +// the default hook function is invoked for any future action. +func (f *UploadServiceGetUploadsFunc) PushHook(hook func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadServiceGetUploadsFunc) SetDefaultReturn(r0 []types.Upload, r1 int, r2 error) { + f.SetDefaultHook(func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + return r0, r1, r2 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadServiceGetUploadsFunc) PushReturn(r0 []types.Upload, r1 int, r2 error) { + f.PushHook(func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + return r0, r1, r2 + }) +} + +func (f *UploadServiceGetUploadsFunc) nextHook() func(context.Context, types.GetUploadsOptions) ([]types.Upload, int, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadServiceGetUploadsFunc) appendCall(r0 UploadServiceGetUploadsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadServiceGetUploadsFuncCall objects +// describing the invocations of this function. +func (f *UploadServiceGetUploadsFunc) History() []UploadServiceGetUploadsFuncCall { + f.mutex.Lock() + history := make([]UploadServiceGetUploadsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadServiceGetUploadsFuncCall is an object that describes an invocation +// of method GetUploads on an instance of MockUploadService. +type UploadServiceGetUploadsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is the value of the 2nd argument passed to this method + // invocation. + Arg1 types.GetUploadsOptions + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Upload + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 int + // Result2 is the value of the 3rd result returned from this method + // invocation. + Result2 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. +func (c UploadServiceGetUploadsFuncCall) Args() []interface{} { + return []interface{}{c.Arg0, c.Arg1} +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadServiceGetUploadsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1, c.Result2} +} + +// UploadServiceGetUploadsByIDsFunc describes the behavior when the +// GetUploadsByIDs method of the parent MockUploadService instance is +// invoked. +type UploadServiceGetUploadsByIDsFunc struct { + defaultHook func(context.Context, ...int) ([]types.Upload, error) + hooks []func(context.Context, ...int) ([]types.Upload, error) + history []UploadServiceGetUploadsByIDsFuncCall + mutex sync.Mutex +} + +// GetUploadsByIDs delegates to the next hook function in the queue and +// stores the parameter and result values of this invocation. +func (m *MockUploadService) GetUploadsByIDs(v0 context.Context, v1 ...int) ([]types.Upload, error) { + r0, r1 := m.GetUploadsByIDsFunc.nextHook()(v0, v1...) + m.GetUploadsByIDsFunc.appendCall(UploadServiceGetUploadsByIDsFuncCall{v0, v1, r0, r1}) + return r0, r1 +} + +// SetDefaultHook sets function that is called when the GetUploadsByIDs +// method of the parent MockUploadService instance is invoked and the hook +// queue is empty. +func (f *UploadServiceGetUploadsByIDsFunc) SetDefaultHook(hook func(context.Context, ...int) ([]types.Upload, error)) { + f.defaultHook = hook +} + +// PushHook adds a function to the end of hook queue. Each invocation of the +// GetUploadsByIDs method of the parent MockUploadService instance invokes +// the hook at the front of the queue and discards it. After the queue is +// empty, the default hook function is invoked for any future action. +func (f *UploadServiceGetUploadsByIDsFunc) PushHook(hook func(context.Context, ...int) ([]types.Upload, error)) { + f.mutex.Lock() + f.hooks = append(f.hooks, hook) + f.mutex.Unlock() +} + +// SetDefaultReturn calls SetDefaultHook with a function that returns the +// given values. +func (f *UploadServiceGetUploadsByIDsFunc) SetDefaultReturn(r0 []types.Upload, r1 error) { + f.SetDefaultHook(func(context.Context, ...int) ([]types.Upload, error) { + return r0, r1 + }) +} + +// PushReturn calls PushHook with a function that returns the given values. +func (f *UploadServiceGetUploadsByIDsFunc) PushReturn(r0 []types.Upload, r1 error) { + f.PushHook(func(context.Context, ...int) ([]types.Upload, error) { + return r0, r1 + }) +} + +func (f *UploadServiceGetUploadsByIDsFunc) nextHook() func(context.Context, ...int) ([]types.Upload, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + if len(f.hooks) == 0 { + return f.defaultHook + } + + hook := f.hooks[0] + f.hooks = f.hooks[1:] + return hook +} + +func (f *UploadServiceGetUploadsByIDsFunc) appendCall(r0 UploadServiceGetUploadsByIDsFuncCall) { + f.mutex.Lock() + f.history = append(f.history, r0) + f.mutex.Unlock() +} + +// History returns a sequence of UploadServiceGetUploadsByIDsFuncCall +// objects describing the invocations of this function. +func (f *UploadServiceGetUploadsByIDsFunc) History() []UploadServiceGetUploadsByIDsFuncCall { + f.mutex.Lock() + history := make([]UploadServiceGetUploadsByIDsFuncCall, len(f.history)) + copy(history, f.history) + f.mutex.Unlock() + + return history +} + +// UploadServiceGetUploadsByIDsFuncCall is an object that describes an +// invocation of method GetUploadsByIDs on an instance of MockUploadService. +type UploadServiceGetUploadsByIDsFuncCall struct { + // Arg0 is the value of the 1st argument passed to this method + // invocation. + Arg0 context.Context + // Arg1 is a slice containing the values of the variadic arguments + // passed to this method invocation. + Arg1 []int + // Result0 is the value of the 1st result returned from this method + // invocation. + Result0 []types.Upload + // Result1 is the value of the 2nd result returned from this method + // invocation. + Result1 error +} + +// Args returns an interface slice containing the arguments of this +// invocation. The variadic slice argument is flattened in this array such +// that one positional argument and three variadic arguments would result in +// a slice of four, not two. +func (c UploadServiceGetUploadsByIDsFuncCall) Args() []interface{} { + trailing := []interface{}{} + for _, val := range c.Arg1 { + trailing = append(trailing, val) + } + + return append([]interface{}{c.Arg0}, trailing...) +} + +// Results returns an interface slice containing the results of this +// invocation. +func (c UploadServiceGetUploadsByIDsFuncCall) Results() []interface{} { + return []interface{}{c.Result0, c.Result1} +} diff --git a/internal/codeintel/uploads/transport/graphql/observability.go b/internal/codeintel/uploads/transport/graphql/observability.go index fba64764443..5d33bcb5a04 100644 --- a/internal/codeintel/uploads/transport/graphql/observability.go +++ b/internal/codeintel/uploads/transport/graphql/observability.go @@ -8,13 +8,13 @@ import ( ) type operations struct { - getIndexByID *observation.Operation - getUploadDocumentsForPath *observation.Operation - getCommitsVisibleToUpload *observation.Operation - getCommitGraphMetadata *observation.Operation - getAuditLogsForUpload *observation.Operation - getRecentUploadsSummary *observation.Operation - getLastUploadRetentionScanForRepository *observation.Operation + // LSIF Uploads + lsifUploadByID *observation.Operation + lsifUploadsByRepo *observation.Operation + deleteLsifUpload *observation.Operation + + // Commit Graph + commitGraph *observation.Operation } func newOperations(observationContext *observation.Context) *operations { @@ -34,12 +34,12 @@ func newOperations(observationContext *observation.Context) *operations { } return &operations{ - getIndexByID: op("GetIndexByID"), - getUploadDocumentsForPath: op("GetUploadDocumentsForPath"), - getCommitsVisibleToUpload: op("GetCommitsVisibleToUpload"), - getCommitGraphMetadata: op("GetCommitGraphMetadata"), - getAuditLogsForUpload: op("GetAuditLogsForUpload"), - getRecentUploadsSummary: op("GetRecentUploadsSummary"), - getLastUploadRetentionScanForRepository: op("GetLastUploadRetentionScanForRepository"), + // LSIF Uploads + lsifUploadByID: op("LSIFUploadByID"), + lsifUploadsByRepo: op("LSIFUploadsByRepo"), + deleteLsifUpload: op("DeleteLSIFUpload"), + + // Commit Graph + commitGraph: op("CommitGraph"), } } diff --git a/internal/codeintel/uploads/transport/graphql/resolver.go b/internal/codeintel/uploads/transport/graphql/resolver.go deleted file mode 100644 index c45648c1e9d..00000000000 --- a/internal/codeintel/uploads/transport/graphql/resolver.go +++ /dev/null @@ -1,119 +0,0 @@ -package graphql - -import ( - "context" - "fmt" - "time" - - "github.com/opentracing/opentracing-go/log" - - uploads "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads" - "github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/shared" - "github.com/sourcegraph/sourcegraph/internal/observation" -) - -type Resolver interface { - // Uploads - GetUploadsByIDs(ctx context.Context, ids ...int) (_ []shared.Upload, err error) - GetUploadDocumentsForPath(ctx context.Context, bundleID int, pathPattern string) ([]string, int, error) - GetCommitsVisibleToUpload(ctx context.Context, uploadID, limit int, token *string) (_ []string, nextToken *string, err error) - GetRecentUploadsSummary(ctx context.Context, repositoryID int) (upload []shared.UploadsWithRepositoryNamespace, err error) - GetLastUploadRetentionScanForRepository(ctx context.Context, repositoryID int) (_ *time.Time, err error) - DeleteUploadByID(ctx context.Context, id int) (_ bool, err error) - - // Audit Logs - GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []shared.UploadLog, err error) - - // Uploads Connection Factory - UploadsConnectionResolverFromFactory(opts shared.GetUploadsOptions) *UploadsResolver - - // Commit Graph Resolver Factory - CommitGraphResolverFromFactory(ctx context.Context, repositoryID int) *CommitGraphResolver -} -type resolver struct { - svc *uploads.Service - operations *operations -} - -func New(svc *uploads.Service, observationContext *observation.Context) Resolver { - return &resolver{ - svc: svc, - operations: newOperations(observationContext), - } -} - -func (r *resolver) GetUploadsByIDs(ctx context.Context, ids ...int) (_ []shared.Upload, err error) { - ctx, _, endObservation := r.operations.getIndexByID.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.String("ids", fmt.Sprintf("%v", ids))}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.GetUploadsByIDs(ctx, ids...) -} - -func (r *resolver) GetUploadDocumentsForPath(ctx context.Context, bundleID int, pathPattern string) (_ []string, _ int, err error) { - ctx, _, endObservation := r.operations.getUploadDocumentsForPath.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("bundleID", bundleID), log.String("pathPattern", pathPattern)}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.GetUploadDocumentsForPath(ctx, bundleID, pathPattern) -} - -func (r *resolver) GetCommitsVisibleToUpload(ctx context.Context, uploadID, limit int, token *string) (_ []string, _ *string, err error) { - ctx, _, endObservation := r.operations.getCommitsVisibleToUpload.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("uploadID", uploadID), log.Int("limit", limit), log.String("token", fmt.Sprintf("%v", token))}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.GetCommitsVisibleToUpload(ctx, uploadID, limit, token) -} - -func (r *resolver) GetRecentUploadsSummary(ctx context.Context, repositoryID int) (upload []shared.UploadsWithRepositoryNamespace, err error) { - ctx, _, endObservation := r.operations.getRecentUploadsSummary.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("repositoryID", repositoryID)}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.GetRecentUploadsSummary(ctx, repositoryID) -} - -func (r *resolver) GetLastUploadRetentionScanForRepository(ctx context.Context, repositoryID int) (_ *time.Time, err error) { - ctx, _, endObservation := r.operations.getLastUploadRetentionScanForRepository.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("repositoryID", repositoryID)}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.GetLastUploadRetentionScanForRepository(ctx, repositoryID) -} - -func (r *resolver) DeleteUploadByID(ctx context.Context, id int) (_ bool, err error) { - ctx, _, endObservation := r.operations.getIndexByID.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("id", id)}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.DeleteUploadByID(ctx, id) -} - -func (r *resolver) GetAuditLogsForUpload(ctx context.Context, uploadID int) (_ []shared.UploadLog, err error) { - ctx, _, endObservation := r.operations.getAuditLogsForUpload.With(ctx, &err, observation.Args{ - LogFields: []log.Field{log.Int("uploadID", uploadID)}, - }) - defer endObservation(1, observation.Args{}) - - return r.svc.GetAuditLogsForUpload(ctx, uploadID) -} - -func (r *resolver) UploadsConnectionResolverFromFactory(opts shared.GetUploadsOptions) *UploadsResolver { - return NewUploadsResolver(r.svc, opts) -} - -func (r *resolver) CommitGraphResolverFromFactory(ctx context.Context, repositoryID int) *CommitGraphResolver { - stale, updatedAt, err := r.svc.GetCommitGraphMetadata(ctx, repositoryID) - if err != nil { - return nil - } - - return NewCommitGraphResolver(stale, updatedAt) -} diff --git a/internal/codeintel/uploads/transport/graphql/root_resolver.go b/internal/codeintel/uploads/transport/graphql/root_resolver.go new file mode 100644 index 00000000000..cc9155334a9 --- /dev/null +++ b/internal/codeintel/uploads/transport/graphql/root_resolver.go @@ -0,0 +1,147 @@ +package graphql + +import ( + "context" + + "github.com/graph-gophers/graphql-go" + + "github.com/opentracing/opentracing-go/log" + + "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" + "github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers" + "github.com/sourcegraph/sourcegraph/internal/observation" +) + +type RootResolver interface { + CommitGraph(ctx context.Context, id graphql.ID) (CodeIntelligenceCommitGraphResolver, error) + LSIFUploadByID(ctx context.Context, id graphql.ID) (sharedresolvers.LSIFUploadResolver, error) + LSIFUploads(ctx context.Context, args *LSIFUploadsQueryArgs) (sharedresolvers.LSIFUploadConnectionResolver, error) + LSIFUploadsByRepo(ctx context.Context, args *LSIFRepositoryUploadsQueryArgs) (sharedresolvers.LSIFUploadConnectionResolver, error) + DeleteLSIFUpload(ctx context.Context, args *struct{ ID graphql.ID }) (*sharedresolvers.EmptyResponse, error) +} + +type rootResolver struct { + uploadSvc UploadService + autoindexSvc AutoIndexingService + policySvc PolicyService + operations *operations +} + +func NewRootResolver(uploadSvc UploadService, autoindexSvc AutoIndexingService, policySvc PolicyService, observationContext *observation.Context) RootResolver { + return &rootResolver{ + uploadSvc: uploadSvc, + autoindexSvc: autoindexSvc, + policySvc: policySvc, + operations: newOperations(observationContext), + } +} + +// 🚨 SECURITY: Only entrypoint is within the repository resolver so the user is already authenticated +func (r *rootResolver) CommitGraph(ctx context.Context, id graphql.ID) (_ CodeIntelligenceCommitGraphResolver, err error) { + ctx, _, endObservation := r.operations.commitGraph.With(ctx, &err, observation.Args{LogFields: []log.Field{ + log.String("repoID", string(id)), + }}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + repositoryID, err := unmarshalRepositoryID(id) + if err != nil { + return nil, err + } + + stale, updatedAt, err := r.uploadSvc.GetCommitGraphMetadata(ctx, int(repositoryID)) + if err != nil { + return nil, err + } + + return NewCommitGraphResolver(stale, updatedAt), nil +} + +// 🚨 SECURITY: dbstore layer handles authz for GetUploadByID +func (r *rootResolver) LSIFUploadByID(ctx context.Context, id graphql.ID) (_ sharedresolvers.LSIFUploadResolver, err error) { + ctx, traceErrs, endObservation := r.operations.lsifUploadByID.WithErrors(ctx, &err, observation.Args{LogFields: []log.Field{ + log.String("uploadID", string(id)), + }}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + uploadID, err := unmarshalLSIFUploadGQLID(id) + if err != nil { + return nil, err + } + + // Create a new prefetcher here as we only want to cache upload and index records in + // the same graphQL request, not across different request. + prefetcher := sharedresolvers.NewPrefetcher(r.autoindexSvc, r.uploadSvc) + + upload, exists, err := prefetcher.GetUploadByID(ctx, int(uploadID)) + if err != nil || !exists { + return nil, err + } + + return sharedresolvers.NewUploadResolver(r.uploadSvc, r.autoindexSvc, r.policySvc, upload, prefetcher, traceErrs), nil +} + +type LSIFUploadsQueryArgs struct { + ConnectionArgs + Query *string + State *string + IsLatestForRepo *bool + DependencyOf *graphql.ID + DependentOf *graphql.ID + After *string + IncludeDeleted *bool +} + +type LSIFRepositoryUploadsQueryArgs struct { + *LSIFUploadsQueryArgs + RepositoryID graphql.ID +} + +// 🚨 SECURITY: dbstore layer handles authz for GetUploads +func (r *rootResolver) LSIFUploads(ctx context.Context, args *LSIFUploadsQueryArgs) (_ sharedresolvers.LSIFUploadConnectionResolver, err error) { + // Delegate behavior to LSIFUploadsByRepo with no specified repository identifier + return r.LSIFUploadsByRepo(ctx, &LSIFRepositoryUploadsQueryArgs{LSIFUploadsQueryArgs: args}) +} + +func (r *rootResolver) LSIFUploadsByRepo(ctx context.Context, args *LSIFRepositoryUploadsQueryArgs) (_ sharedresolvers.LSIFUploadConnectionResolver, err error) { + ctx, traceErrs, endObservation := r.operations.lsifUploadsByRepo.WithErrors(ctx, &err, observation.Args{ + LogFields: []log.Field{ + log.String("repoID", string(args.RepositoryID)), + }, + }) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + opts, err := makeGetUploadsOptions(args) + if err != nil { + return nil, err + } + + // Create a new prefetcher here as we only want to cache upload and index records in + // the same graphQL request, not across different request. + prefetcher := sharedresolvers.NewPrefetcher(r.autoindexSvc, r.uploadSvc) + uploadsResolver := sharedresolvers.NewUploadsResolver(r.uploadSvc, opts) + + return sharedresolvers.NewUploadConnectionResolver(r.uploadSvc, r.autoindexSvc, r.policySvc, uploadsResolver, prefetcher, traceErrs), nil +} + +// 🚨 SECURITY: Only site admins may modify code intelligence upload data +func (r *rootResolver) DeleteLSIFUpload(ctx context.Context, args *struct{ ID graphql.ID }) (_ *sharedresolvers.EmptyResponse, err error) { + ctx, _, endObservation := r.operations.deleteLsifUpload.With(ctx, &err, observation.Args{LogFields: []log.Field{ + log.String("uploadID", string(args.ID)), + }}) + endObservation.OnCancel(ctx, 1, observation.Args{}) + + if err := backend.CheckCurrentUserIsSiteAdmin(ctx, r.autoindexSvc.GetUnsafeDB()); err != nil { + return nil, err + } + + uploadID, err := unmarshalLSIFUploadGQLID(args.ID) + if err != nil { + return nil, err + } + + if _, err := r.uploadSvc.DeleteUploadByID(ctx, int(uploadID)); err != nil { + return nil, err + } + + return &sharedresolvers.EmptyResponse{}, nil +} diff --git a/internal/codeintel/uploads/transport/graphql/root_resolver_test.go b/internal/codeintel/uploads/transport/graphql/root_resolver_test.go new file mode 100644 index 00000000000..4b5533a7c23 --- /dev/null +++ b/internal/codeintel/uploads/transport/graphql/root_resolver_test.go @@ -0,0 +1,61 @@ +package graphql + +import ( + "context" + "encoding/base64" + "testing" + + "github.com/graph-gophers/graphql-go" + "github.com/sourcegraph/log/logtest" + + "github.com/sourcegraph/sourcegraph/cmd/frontend/backend" + "github.com/sourcegraph/sourcegraph/internal/database" + "github.com/sourcegraph/sourcegraph/internal/observation" + "github.com/sourcegraph/sourcegraph/internal/types" +) + +func TestDeleteLSIFUpload(t *testing.T) { + users := database.NewStrictMockUserStore() + users.GetByCurrentAuthUserFunc.SetDefaultReturn(&types.User{SiteAdmin: true}, nil) + + db := database.NewMockDB() + db.UsersFunc.SetDefaultReturn(users) + + id := graphql.ID(base64.StdEncoding.EncodeToString([]byte("LSIFUpload:42"))) + + mockUploadService := NewMockUploadService() + mockPolicyService := NewMockPolicyService() + mockAutoIndexingService := NewMockAutoIndexingService() + mockAutoIndexingService.GetUnsafeDBFunc.SetDefaultReturn(db) + + rootResolver := NewRootResolver(mockUploadService, mockAutoIndexingService, mockPolicyService, &observation.TestContext) + + if _, err := rootResolver.DeleteLSIFUpload(context.Background(), &struct{ ID graphql.ID }{id}); err != nil { + t.Fatalf("unexpected error: %s", err) + } + + if len(mockUploadService.DeleteUploadByIDFunc.History()) != 1 { + t.Fatalf("unexpected call count. want=%d have=%d", 1, len(mockUploadService.DeleteUploadByIDFunc.History())) + } + + if val := mockUploadService.DeleteUploadByIDFunc.History()[0].Arg1; val != 42 { + t.Fatalf("unexpected upload id. want=%d have=%d", 42, val) + } +} + +func TestDeleteLSIFUploadUnauthenticated(t *testing.T) { + logger := logtest.Scoped(t) + db := database.NewDB(logger, nil) + + id := graphql.ID(base64.StdEncoding.EncodeToString([]byte("LSIFUpload:42"))) + mockUploadService := NewMockUploadService() + mockPolicyService := NewMockPolicyService() + mockAutoIndexingService := NewMockAutoIndexingService() + mockAutoIndexingService.GetUnsafeDBFunc.SetDefaultReturn(db) + + rootResolver := NewRootResolver(mockUploadService, mockAutoIndexingService, mockPolicyService, &observation.TestContext) + + if _, err := rootResolver.DeleteLSIFUpload(context.Background(), &struct{ ID graphql.ID }{id}); err != backend.ErrNotAuthenticated { + t.Errorf("unexpected error. want=%q have=%q", backend.ErrNotAuthenticated, err) + } +} diff --git a/internal/codeintel/uploads/transport/graphql/utils.go b/internal/codeintel/uploads/transport/graphql/utils.go new file mode 100644 index 00000000000..5519144067f --- /dev/null +++ b/internal/codeintel/uploads/transport/graphql/utils.go @@ -0,0 +1,261 @@ +package graphql + +import ( + "encoding/base64" + "encoding/json" + "strconv" + "strings" + "time" + + "github.com/graph-gophers/graphql-go" + "github.com/graph-gophers/graphql-go/relay" + + "github.com/sourcegraph/sourcegraph/internal/api" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" + "github.com/sourcegraph/sourcegraph/internal/database" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +// DateTime implements the DateTime GraphQL scalar type. +type DateTime struct{ time.Time } + +// DateTimeOrNil is a helper function that returns nil for time == nil and otherwise wraps time in +// DateTime. +func DateTimeOrNil(time *time.Time) *DateTime { + if time == nil { + return nil + } + return &DateTime{Time: *time} +} + +func (DateTime) ImplementsGraphQLType(name string) bool { + return name == "DateTime" +} + +func (v DateTime) MarshalJSON() ([]byte, error) { + return json.Marshal(v.Time.Format(time.RFC3339)) +} + +func (v *DateTime) UnmarshalGraphQL(input any) error { + s, ok := input.(string) + if !ok { + return errors.Errorf("invalid GraphQL DateTime scalar value input (got %T, expected string)", input) + } + t, err := time.Parse(time.RFC3339, s) + if err != nil { + return err + } + *v = DateTime{Time: t} + return nil +} + +func unmarshalLSIFUploadGQLID(id graphql.ID) (uploadID int64, err error) { + // First, try to unmarshal the ID as a string and then convert it to an + // integer. This is here to maintain backwards compatibility with the + // src-cli lsif upload command, which constructs its own relay identifier + // from a the string payload returned by the upload proxy. + var idString string + err = relay.UnmarshalSpec(id, &idString) + if err == nil { + uploadID, err = strconv.ParseInt(idString, 10, 64) + return + } + + // If it wasn't unmarshal-able as a string, it's a new-style int identifier + err = relay.UnmarshalSpec(id, &uploadID) + return uploadID, err +} + +func marshalLSIFUploadGQLID(uploadID int64) graphql.ID { + return relay.MarshalID("LSIFUpload", uploadID) +} + +func unmarshalRepositoryID(id graphql.ID) (repo api.RepoID, err error) { + err = relay.UnmarshalSpec(id, &repo) + return +} + +const DefaultUploadPageSize = 50 + +// makeGetUploadsOptions translates the given GraphQL arguments into options defined by the +// store.GetUploads operations. +func makeGetUploadsOptions(args *LSIFRepositoryUploadsQueryArgs) (types.GetUploadsOptions, error) { + repositoryID, err := resolveRepositoryID(args.RepositoryID) + if err != nil { + return types.GetUploadsOptions{}, err + } + + var dependencyOf int64 + if args.DependencyOf != nil { + dependencyOf, err = unmarshalLSIFUploadGQLID(*args.DependencyOf) + if err != nil { + return types.GetUploadsOptions{}, err + } + } + + var dependentOf int64 + if args.DependentOf != nil { + dependentOf, err = unmarshalLSIFUploadGQLID(*args.DependentOf) + if err != nil { + return types.GetUploadsOptions{}, err + } + } + + offset, err := decodeIntCursor(args.After) + if err != nil { + return types.GetUploadsOptions{}, err + } + + return types.GetUploadsOptions{ + RepositoryID: repositoryID, + State: strings.ToLower(derefString(args.State, "")), + Term: derefString(args.Query, ""), + VisibleAtTip: derefBool(args.IsLatestForRepo, false), + DependencyOf: int(dependencyOf), + DependentOf: int(dependentOf), + Limit: derefInt32(args.First, DefaultUploadPageSize), + Offset: offset, + AllowExpired: true, + AllowDeletedUpload: derefBool(args.IncludeDeleted, false), + }, nil +} + +// resolveRepositoryByID gets a repository's internal identifier from a GraphQL identifier. +func resolveRepositoryID(id graphql.ID) (int, error) { + if id == "" { + return 0, nil + } + + repoID, err := unmarshalRepositoryID(id) + if err != nil { + return 0, err + } + + return int(repoID), nil +} + +// derefString returns the underlying value in the given pointer. +// If the pointer is nil, the default value is returned. +func derefString(val *string, defaultValue string) string { + if val != nil { + return *val + } + return defaultValue +} + +// derefBool returns the underlying value in the given pointer. +// If the pointer is nil, the default value is returned. +func derefBool(val *bool, defaultValue bool) bool { + if val != nil { + return *val + } + return defaultValue +} + +// derefInt32 returns the underlying value in the given pointer. +// If the pointer is nil, the default value is returned. +func derefInt32(val *int32, defaultValue int) int { + if val != nil { + return int(*val) + } + return defaultValue +} + +// ConnectionArgs is the common set of arguments to GraphQL fields that return connections (lists). +type ConnectionArgs struct { + First *int32 // return the first n items +} + +// Set is a convenience method for setting the DB limit and offset in a DB XyzListOptions struct. +func (a ConnectionArgs) Set(o **database.LimitOffset) { + if a.First != nil { + *o = &database.LimitOffset{Limit: int(*a.First)} + } +} + +// GetFirst is a convenience method returning the value of First, defaulting to +// the type's zero value if nil. +func (a ConnectionArgs) GetFirst() int32 { + if a.First == nil { + return 0 + } + return *a.First +} + +type PageInfo struct { + endCursor *string + hasNextPage bool +} + +// HasNextPage returns a new PageInfo with the given hasNextPage value. +func HasNextPage(hasNextPage bool) *PageInfo { + return &PageInfo{hasNextPage: hasNextPage} +} + +// NextPageCursor returns a new PageInfo indicating there is a next page with +// the given end cursor. +func NextPageCursor(endCursor string) *PageInfo { + return &PageInfo{endCursor: &endCursor, hasNextPage: true} +} + +func (r *PageInfo) EndCursor() *string { return r.endCursor } +func (r *PageInfo) HasNextPage() bool { return r.hasNextPage } + +// EncodeCursor creates a PageInfo object from the given cursor. If the cursor is not +// defined, then an object indicating the end of the result set is returned. The cursor +// is base64 encoded for transfer, and should be decoded using the function decodeCursor. +func EncodeCursor(val *string) *PageInfo { + if val != nil { + return NextPageCursor(base64.StdEncoding.EncodeToString([]byte(*val))) + } + + return HasNextPage(false) +} + +// DecodeCursor decodes the given cursor value. It is assumed to be a value previously +// returned from the function encodeCursor. An empty string is returned if no cursor is +// supplied. Invalid cursors return errors. +func DecodeCursor(val *string) (string, error) { + if val == nil { + return "", nil + } + + decoded, err := base64.StdEncoding.DecodeString(*val) + if err != nil { + return "", err + } + + return string(decoded), nil +} + +// DecodeIntCursor decodes the given integer cursor value. It is assumed to be a value +// previously returned from the function encodeIntCursor. The zero value is returned if +// no cursor is supplied. Invalid cursors return errors. +func decodeIntCursor(val *string) (int, error) { + cursor, err := DecodeCursor(val) + if err != nil || cursor == "" { + return 0, err + } + + return strconv.Atoi(cursor) +} + +// strPtr creates a pointer to the given value. If the value is an +// empty string, a nil pointer is returned. +func strPtr(val string) *string { + if val == "" { + return nil + } + + return &val +} + +// intPtr creates a pointer to the given value. +func intPtr(val int32) *int32 { + return &val +} + +// intPtr creates a pointer to the given value. +func boolPtr(val bool) *bool { + return &val +} diff --git a/internal/codeintel/uploads/transport/graphql/utils_test.go b/internal/codeintel/uploads/transport/graphql/utils_test.go new file mode 100644 index 00000000000..8b211db8854 --- /dev/null +++ b/internal/codeintel/uploads/transport/graphql/utils_test.go @@ -0,0 +1,178 @@ +package graphql + +import ( + "encoding/base64" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/graph-gophers/graphql-go" + + "github.com/sourcegraph/sourcegraph/cmd/frontend/graphqlbackend/graphqlutil" + "github.com/sourcegraph/sourcegraph/internal/codeintel/types" +) + +func TestMakeGetUploadsOptions(t *testing.T) { + opts, err := makeGetUploadsOptions(&LSIFRepositoryUploadsQueryArgs{ + LSIFUploadsQueryArgs: &LSIFUploadsQueryArgs{ + ConnectionArgs: ConnectionArgs{ + First: intPtr(5), + }, + Query: strPtr("q"), + State: strPtr("s"), + IsLatestForRepo: boolPtr(true), + After: graphqlutil.EncodeIntCursor(intPtr(25)).EndCursor(), + }, + RepositoryID: graphql.ID(base64.StdEncoding.EncodeToString([]byte("Repo:50"))), + }) + if err != nil { + t.Fatalf("unexpected error making options: %s", err) + } + + expected := types.GetUploadsOptions{ + RepositoryID: 50, + State: "s", + Term: "q", + VisibleAtTip: true, + Limit: 5, + Offset: 25, + AllowExpired: true, + } + if diff := cmp.Diff(expected, opts); diff != "" { + t.Errorf("unexpected opts (-want +got):\n%s", diff) + } +} + +func TestMakeGetUploadsOptionsDefaults(t *testing.T) { + opts, err := makeGetUploadsOptions(&LSIFRepositoryUploadsQueryArgs{ + LSIFUploadsQueryArgs: &LSIFUploadsQueryArgs{}, + }) + if err != nil { + t.Fatalf("unexpected error making options: %s", err) + } + + expected := types.GetUploadsOptions{ + RepositoryID: 0, + State: "", + Term: "", + VisibleAtTip: false, + Limit: DefaultUploadPageSize, + Offset: 0, + AllowExpired: true, + } + if diff := cmp.Diff(expected, opts); diff != "" { + t.Errorf("unexpected opts (-want +got):\n%s", diff) + } +} + +func TestCursor(t *testing.T) { + expected := "test" + pageInfo := EncodeCursor(&expected) + + if !pageInfo.HasNextPage() { + t.Fatalf("expected next page") + } + if pageInfo.EndCursor() == nil { + t.Fatalf("unexpected nil cursor") + } + + value, err := DecodeCursor(pageInfo.EndCursor()) + if err != nil { + t.Fatalf("unexpected error decoding cursor: %s", err) + } + if value != expected { + t.Errorf("unexpected decoded cursor. want=%s have=%s", expected, value) + } +} + +func TestCursorEmpty(t *testing.T) { + pageInfo := EncodeCursor(nil) + + if pageInfo.HasNextPage() { + t.Errorf("unexpected next page") + } + if pageInfo.EndCursor() != nil { + t.Errorf("unexpected encoded cursor: %s", *pageInfo.EndCursor()) + } + + value, err := DecodeCursor(nil) + if err != nil { + t.Fatalf("unexpected error decoding cursor: %s", err) + } + if value != "" { + t.Errorf("unexpected decoded cursor: %s", value) + } +} + +func TestUploadID(t *testing.T) { + expected := int64(42) + value, err := unmarshalLSIFUploadGQLID(marshalLSIFUploadGQLID(expected)) + if err != nil { + t.Fatalf("unexpected error marshalling id: %s", err) + } + if value != expected { + t.Errorf("unexpected id. have=%d want=%d", expected, value) + } +} + +func TestUnmarshalUploadIDString(t *testing.T) { + expected := int64(42) + id := graphql.ID(base64.StdEncoding.EncodeToString([]byte(`LSIFUpload:"42"`))) + value, err := unmarshalLSIFUploadGQLID(id) + if err != nil { + t.Fatalf("unexpected error marshalling id: %s", err) + } + if value != expected { + t.Errorf("unexpected id. have=%d want=%d", expected, value) + } +} + +func TestDerefInt32(t *testing.T) { + expected := 42 + expected32 := int32(expected) + + if val := derefInt32(nil, expected); val != expected { + t.Errorf("unexpected value. want=%d have=%d", expected, val) + } + if val := derefInt32(&expected32, expected); val != expected { + t.Errorf("unexpected value. want=%d have=%d", expected, val) + } +} + +func TestDerefString(t *testing.T) { + expected := "foo" + + if val := derefString(nil, expected); val != expected { + t.Errorf("unexpected value. want=%s have=%s", expected, val) + } + if val := derefString(&expected, ""); val != expected { + t.Errorf("unexpected value. want=%s have=%s", expected, val) + } + if val := derefString(&expected, expected); val != expected { + t.Errorf("unexpected value. want=%s have=%s", expected, val) + } +} + +func TestDerefBool(t *testing.T) { + if val := derefBool(nil, true); !val { + t.Errorf("unexpected value. want=%v have=%v", true, val) + } + if val := derefBool(nil, false); val { + t.Errorf("unexpected value. want=%v have=%v", false, val) + } + + pVal := true + if val := derefBool(&pVal, true); !val { + t.Errorf("unexpected value. want=%v have=%v", true, val) + } + if val := derefBool(&pVal, false); !val { + t.Errorf("unexpected value. want=%v have=%v", false, val) + } + + pVal = false + if val := derefBool(&pVal, true); val { + t.Errorf("unexpected value. want=%v have=%v", true, val) + } + if val := derefBool(&pVal, false); val { + t.Errorf("unexpected value. want=%v have=%v", false, val) + } +} diff --git a/mockgen.temp.yaml b/mockgen.temp.yaml index 83374f006bb..da5e8a1e68d 100644 --- a/mockgen.temp.yaml +++ b/mockgen.temp.yaml @@ -10,22 +10,31 @@ path: github.com/prometheus/client_golang/api/prometheus/v1 interfaces: - API -- filename: enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/mocks_temp.go - path: github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers +- filename: internal/codeintel/sharedresolvers/mocks_temp.go + path: github.com/sourcegraph/sourcegraph/internal/codeintel/sharedresolvers interfaces: - - Resolver -- filename: enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/uploads/mocks_uploads.go + - UploadsService + - AutoIndexingService +- filename: internal/codeintel/uploads/transport/graphql/mocks_temp.go path: github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/transport/graphql interfaces: - - Resolver -- filename: enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/mocks_temps.go + - AutoIndexingService + - UploadService + - PolicyService +- filename: internal/codeintel/autoindexing/transport/graphql/mocks_temp.go path: github.com/sourcegraph/sourcegraph/internal/codeintel/autoindexing/transport/graphql interfaces: - - Resolver -- filename: enterprise/cmd/frontend/internal/codeintel/resolvers/mocks/transport/mocks_temp.go + - AutoIndexingService + - UploadsService + - PolicyService +- filename: internal/codeintel/codenav/transport/graphql/mocks_test.go path: github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/transport/graphql interfaces: - - GitBlobLSIFDataResolver + - GitBlobResolver + - AutoIndexingService + - UploadsService + - PolicyService + - GitserverClient - filename: enterprise/cmd/frontend/internal/registry/stores/dbmocks/mocks_temp.go path: github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/registry/stores interfaces: diff --git a/mockgen.test.yaml b/mockgen.test.yaml index 2fe6172208d..7ccca0e6142 100644 --- a/mockgen.test.yaml +++ b/mockgen.test.yaml @@ -45,10 +45,6 @@ path: github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/transport/http/auth interfaces: - GitHubClient -- filename: enterprise/cmd/frontend/internal/codeintel/resolvers/mocks_test.go - path: github.com/sourcegraph/sourcegraph/enterprise/cmd/frontend/internal/codeintel/resolvers - interfaces: - - DBStore - filename: enterprise/cmd/frontend/internal/executorqueue/handler/mocks_test.go path: github.com/sourcegraph/sourcegraph/internal/services/executors/store interfaces: