summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/after_commit_queue.rb2
-rw-r--r--lib/api/access_requests.rb20
-rw-r--r--lib/api/api.rb56
-rw-r--r--lib/api/api_guard.rb21
-rw-r--r--lib/api/applications.rb16
-rw-r--r--lib/api/avatar.rb8
-rw-r--r--lib/api/award_emoji.rb34
-rw-r--r--lib/api/badges.rb36
-rw-r--r--lib/api/boards.rb56
-rw-r--r--lib/api/boards_responses.rb10
-rw-r--r--lib/api/branches.rb74
-rw-r--r--lib/api/broadcast_messages.rb54
-rw-r--r--lib/api/circuit_breakers.rb24
-rw-r--r--lib/api/commit_statuses.rb75
-rw-r--r--lib/api/commits.rb186
-rw-r--r--lib/api/container_registry.rb65
-rw-r--r--lib/api/custom_attributes_endpoints.rb12
-rw-r--r--lib/api/deploy_keys.rb44
-rw-r--r--lib/api/deployments.rb20
-rw-r--r--lib/api/discussions.rb94
-rw-r--r--lib/api/entities.rb108
-rw-r--r--lib/api/environments.rb48
-rw-r--r--lib/api/events.rb30
-rw-r--r--lib/api/features.rb22
-rw-r--r--lib/api/files.rb62
-rw-r--r--lib/api/group_boards.rb56
-rw-r--r--lib/api/group_labels.rb34
-rw-r--r--lib/api/group_milestones.rb28
-rw-r--r--lib/api/group_variables.rb44
-rw-r--r--lib/api/groups.rb103
-rw-r--r--lib/api/helpers.rb111
-rw-r--r--lib/api/helpers/badges_helpers.rb10
-rw-r--r--lib/api/helpers/custom_attributes.rb4
-rw-r--r--lib/api/helpers/custom_validators.rb2
-rw-r--r--lib/api/helpers/headers_helpers.rb2
-rw-r--r--lib/api/helpers/internal_helpers.rb8
-rw-r--r--lib/api/helpers/label_helpers.rb8
-rw-r--r--lib/api/helpers/members_helpers.rb6
-rw-r--r--lib/api/helpers/notes_helpers.rb2
-rw-r--r--lib/api/helpers/pagination.rb62
-rw-r--r--lib/api/helpers/projects_helpers.rb40
-rw-r--r--lib/api/helpers/related_resources_helpers.rb2
-rw-r--r--lib/api/helpers/runner.rb16
-rw-r--r--lib/api/helpers/version.rb4
-rw-r--r--lib/api/import_github.rb18
-rw-r--r--lib/api/internal.rb38
-rw-r--r--lib/api/issues.rb174
-rw-r--r--lib/api/job_artifacts.rb56
-rw-r--r--lib/api/jobs.rb66
-rw-r--r--lib/api/keys.rb2
-rw-r--r--lib/api/labels.rb30
-rw-r--r--lib/api/lint.rb10
-rw-r--r--lib/api/markdown.rb4
-rw-r--r--lib/api/members.rb36
-rw-r--r--lib/api/merge_request_diffs.rb16
-rw-r--r--lib/api/merge_requests.rb192
-rw-r--r--lib/api/milestone_responses.rb20
-rw-r--r--lib/api/namespaces.rb8
-rw-r--r--lib/api/notes.rb34
-rw-r--r--lib/api/notification_settings.rb20
-rw-r--r--lib/api/pages_domains.rb32
-rw-r--r--lib/api/pagination_params.rb4
-rw-r--r--lib/api/pipeline_schedules.rb90
-rw-r--r--lib/api/pipelines.rb84
-rw-r--r--lib/api/project_clusters.rb70
-rw-r--r--lib/api/project_export.rb36
-rw-r--r--lib/api/project_hooks.rb16
-rw-r--r--lib/api/project_import.rb48
-rw-r--r--lib/api/project_milestones.rb50
-rw-r--r--lib/api/project_snapshots.rb8
-rw-r--r--lib/api/project_snippets.rb60
-rw-r--r--lib/api/project_statistics.rb4
-rw-r--r--lib/api/project_templates.rb24
-rw-r--r--lib/api/projects.rb170
-rw-r--r--lib/api/protected_branches.rb26
-rw-r--r--lib/api/protected_tags.rb38
-rw-r--r--lib/api/release/links.rb44
-rw-r--r--lib/api/releases.rb50
-rw-r--r--lib/api/repositories.rb94
-rw-r--r--lib/api/resource_label_events.rb10
-rw-r--r--lib/api/runner.rb234
-rw-r--r--lib/api/runners.rb88
-rw-r--r--lib/api/scope.rb2
-rw-r--r--lib/api/search.rb38
-rw-r--r--lib/api/services.rb373
-rw-r--r--lib/api/settings.rb164
-rw-r--r--lib/api/sidekiq_metrics.rb46
-rw-r--r--lib/api/snippets.rb84
-rw-r--r--lib/api/submodules.rb14
-rw-r--r--lib/api/subscriptions.rb28
-rw-r--r--lib/api/suggestions.rb6
-rw-r--r--lib/api/system_hooks.rb20
-rw-r--r--lib/api/tags.rb80
-rw-r--r--lib/api/templates.rb32
-rw-r--r--lib/api/time_tracking_endpoints.rb18
-rw-r--r--lib/api/todos.rb22
-rw-r--r--lib/api/triggers.rb63
-rw-r--r--lib/api/users.rb392
-rw-r--r--lib/api/variables.rb44
-rw-r--r--lib/api/version.rb8
-rw-r--r--lib/api/wikis.rb50
-rw-r--r--lib/backup/artifacts.rb4
-rw-r--r--lib/backup/builds.rb4
-rw-r--r--lib/backup/database.rb86
-rw-r--r--lib/backup/files.rb32
-rw-r--r--lib/backup/helper.rb25
-rw-r--r--lib/backup/lfs.rb4
-rw-r--r--lib/backup/manager.rb60
-rw-r--r--lib/backup/pages.rb4
-rw-r--r--lib/backup/registry.rb4
-rw-r--r--lib/backup/repository.rb12
-rw-r--r--lib/backup/uploads.rb4
-rw-r--r--lib/banzai/filter/absolute_link_filter.rb8
-rw-r--r--lib/banzai/filter/abstract_reference_filter.rb30
-rw-r--r--lib/banzai/filter/ascii_doc_post_processing_filter.rb4
-rw-r--r--lib/banzai/filter/autolink_filter.rb20
-rw-r--r--lib/banzai/filter/color_filter.rb8
-rw-r--r--lib/banzai/filter/commit_range_reference_filter.rb2
-rw-r--r--lib/banzai/filter/commit_reference_filter.rb14
-rw-r--r--lib/banzai/filter/commit_trailers_filter.rb14
-rw-r--r--lib/banzai/filter/emoji_filter.rb6
-rw-r--r--lib/banzai/filter/external_issue_reference_filter.rb2
-rw-r--r--lib/banzai/filter/external_link_filter.rb24
-rw-r--r--lib/banzai/filter/footnote_filter.rb10
-rw-r--r--lib/banzai/filter/front_matter_filter.rb6
-rw-r--r--lib/banzai/filter/gollum_tags_filter.rb20
-rw-r--r--lib/banzai/filter/html_entity_filter.rb2
-rw-r--r--lib/banzai/filter/image_lazy_load_filter.rb8
-rw-r--r--lib/banzai/filter/image_link_filter.rb12
-rw-r--r--lib/banzai/filter/inline_diff_filter.rb2
-rw-r--r--lib/banzai/filter/issuable_state_filter.rb2
-rw-r--r--lib/banzai/filter/label_reference_filter.rb20
-rw-r--r--lib/banzai/filter/markdown_engines/common_mark.rb8
-rw-r--r--lib/banzai/filter/math_filter.rb18
-rw-r--r--lib/banzai/filter/merge_request_reference_filter.rb14
-rw-r--r--lib/banzai/filter/mermaid_filter.rb2
-rw-r--r--lib/banzai/filter/milestone_reference_filter.rb6
-rw-r--r--lib/banzai/filter/plantuml_filter.rb3
-rw-r--r--lib/banzai/filter/project_reference_filter.rb8
-rw-r--r--lib/banzai/filter/reference_filter.rb22
-rw-r--r--lib/banzai/filter/relative_link_filter.rb38
-rw-r--r--lib/banzai/filter/sanitization_filter.rb72
-rw-r--r--lib/banzai/filter/set_direction_filter.rb2
-rw-r--r--lib/banzai/filter/snippet_reference_filter.rb2
-rw-r--r--lib/banzai/filter/spaced_link_filter.rb16
-rw-r--r--lib/banzai/filter/suggestion_filter.rb4
-rw-r--r--lib/banzai/filter/syntax_highlight_filter.rb10
-rw-r--r--lib/banzai/filter/table_of_contents_filter.rb22
-rw-r--r--lib/banzai/filter/task_list_filter.rb2
-rw-r--r--lib/banzai/filter/user_reference_filter.rb14
-rw-r--r--lib/banzai/filter/video_link_filter.rb38
-rw-r--r--lib/banzai/filter/wiki_link_filter.rb8
-rw-r--r--lib/banzai/filter/wiki_link_filter/rewriter.rb6
-rw-r--r--lib/banzai/issuable_extractor.rb14
-rw-r--r--lib/banzai/object_renderer.rb4
-rw-r--r--lib/banzai/pipeline/base_pipeline.rb2
-rw-r--r--lib/banzai/pipeline/broadcast_message_pipeline.rb1
-rw-r--r--lib/banzai/pipeline/description_pipeline.rb2
-rw-r--r--lib/banzai/pipeline/gfm_pipeline.rb8
-rw-r--r--lib/banzai/pipeline/post_process_pipeline.rb2
-rw-r--r--lib/banzai/pipeline/single_line_pipeline.rb4
-rw-r--r--lib/banzai/pipeline/wiki_pipeline.rb2
-rw-r--r--lib/banzai/querying.rb4
-rw-r--r--lib/banzai/redactor.rb20
-rw-r--r--lib/banzai/reference_extractor.rb2
-rw-r--r--lib/banzai/reference_parser/base_parser.rb14
-rw-r--r--lib/banzai/reference_parser/directly_addressed_user_parser.rb2
-rw-r--r--lib/banzai/reference_parser/issue_parser.rb8
-rw-r--r--lib/banzai/reference_parser/merge_request_parser.rb11
-rw-r--r--lib/banzai/reference_parser/user_parser.rb18
-rw-r--r--lib/banzai/renderer.rb4
-rw-r--r--lib/banzai/renderer/common_mark/html.rb4
-rw-r--r--lib/banzai/request_store_reference_cache.rb4
-rw-r--r--lib/banzai/suggestions_parser.rb2
-rw-r--r--lib/bitbucket/client.rb2
-rw-r--r--lib/bitbucket/collection.rb4
-rw-r--r--lib/bitbucket/connection.rb6
-rw-r--r--lib/bitbucket/page.rb6
-rw-r--r--lib/bitbucket/representation/comment.rb10
-rw-r--r--lib/bitbucket/representation/issue.rb22
-rw-r--r--lib/bitbucket/representation/pull_request.rb34
-rw-r--r--lib/bitbucket/representation/pull_request_comment.rb16
-rw-r--r--lib/bitbucket/representation/repo.rb18
-rw-r--r--lib/bitbucket/representation/user.rb2
-rw-r--r--lib/bitbucket_server/client.rb4
-rw-r--r--lib/bitbucket_server/collection.rb4
-rw-r--r--lib/bitbucket_server/connection.rb32
-rw-r--r--lib/bitbucket_server/page.rb6
-rw-r--r--lib/bitbucket_server/representation/activity.rb20
-rw-r--r--lib/bitbucket_server/representation/comment.rb22
-rw-r--r--lib/bitbucket_server/representation/pull_request.rb36
-rw-r--r--lib/bitbucket_server/representation/pull_request_comment.rb32
-rw-r--r--lib/bitbucket_server/representation/repo.rb20
-rw-r--r--lib/constraints/project_url_constrainer.rb2
-rw-r--r--lib/container_registry/blob.rb8
-rw-r--r--lib/container_registry/client.rb38
-rw-r--r--lib/container_registry/path.rb10
-rw-r--r--lib/container_registry/registry.rb2
-rw-r--r--lib/container_registry/tag.rb12
-rw-r--r--lib/declarative_policy.rb26
-rw-r--r--lib/declarative_policy/base.rb6
-rw-r--r--lib/declarative_policy/cache.rb4
-rw-r--r--lib/declarative_policy/condition.rb2
-rw-r--r--lib/declarative_policy/rule.rb24
-rw-r--r--lib/declarative_policy/runner.rb6
-rw-r--r--lib/event_filter.rb14
-rw-r--r--lib/expand_variables.rb5
-rw-r--r--lib/extracts_path.rb12
-rw-r--r--lib/feature.rb16
-rw-r--r--lib/file_size_validator.rb8
-rw-r--r--lib/flowdock/git.rb10
-rw-r--r--lib/flowdock/git/builder.rb17
-rw-r--r--lib/forever.rb2
-rw-r--r--lib/generators/rails/post_deployment_migration/post_deployment_migration_generator.rb4
-rw-r--r--lib/gitaly/server.rb2
-rw-r--r--lib/gitlab.rb20
-rw-r--r--lib/gitlab/access.rb18
-rw-r--r--lib/gitlab/action_rate_limiter.rb2
-rw-r--r--lib/gitlab/app_logger.rb2
-rw-r--r--lib/gitlab/asciidoc.rb18
-rw-r--r--lib/gitlab/audit_json_logger.rb2
-rw-r--r--lib/gitlab/auth.rb26
-rw-r--r--lib/gitlab/auth/activity.rb18
-rw-r--r--lib/gitlab/auth/blocked_user_tracker.rb1
-rw-r--r--lib/gitlab/auth/ip_rate_limiter.rb4
-rw-r--r--lib/gitlab/auth/ldap/access.rb12
-rw-r--r--lib/gitlab/auth/ldap/adapter.rb14
-rw-r--r--lib/gitlab/auth/ldap/auth_hash.rb2
-rw-r--r--lib/gitlab/auth/ldap/config.rb106
-rw-r--r--lib/gitlab/auth/ldap/dn.rb55
-rw-r--r--lib/gitlab/auth/ldap/person.rb12
-rw-r--r--lib/gitlab/auth/ldap/user.rb4
-rw-r--r--lib/gitlab/auth/o_auth/auth_hash.rb6
-rw-r--r--lib/gitlab/auth/o_auth/provider.rb18
-rw-r--r--lib/gitlab/auth/o_auth/user.rb19
-rw-r--r--lib/gitlab/auth/omniauth_identity_linker_base.rb10
-rw-r--r--lib/gitlab/auth/result.rb4
-rw-r--r--lib/gitlab/auth/saml/config.rb2
-rw-r--r--lib/gitlab/auth/saml/user.rb2
-rw-r--r--lib/gitlab/auth/unique_ips_limiter.rb2
-rw-r--r--lib/gitlab/auth/user_auth_finders.rb8
-rw-r--r--lib/gitlab/background_migration.rb6
-rw-r--r--lib/gitlab/background_migration/add_merge_request_diff_commits_count.rb3
-rw-r--r--lib/gitlab/background_migration/archive_legacy_traces.rb10
-rw-r--r--lib/gitlab/background_migration/backfill_project_fullpath_in_repo_config.rb20
-rw-r--r--lib/gitlab/background_migration/backfill_project_repositories.rb30
-rw-r--r--lib/gitlab/background_migration/create_fork_network_memberships_range.rb3
-rw-r--r--lib/gitlab/background_migration/create_gpg_key_subkeys_from_gpg_keys.rb7
-rw-r--r--lib/gitlab/background_migration/delete_conflicting_redirect_routes_range.rb1
-rw-r--r--lib/gitlab/background_migration/delete_diff_files.rb9
-rw-r--r--lib/gitlab/background_migration/deserialize_merge_request_diffs_and_commits.rb39
-rw-r--r--lib/gitlab/background_migration/digest_column.rb2
-rw-r--r--lib/gitlab/background_migration/encrypt_columns.rb4
-rw-r--r--lib/gitlab/background_migration/fill_file_store_job_artifact.rb3
-rw-r--r--lib/gitlab/background_migration/fill_file_store_lfs_object.rb3
-rw-r--r--lib/gitlab/background_migration/fill_store_upload.rb3
-rw-r--r--lib/gitlab/background_migration/fix_cross_project_label_links.rb45
-rw-r--r--lib/gitlab/background_migration/migrate_build_stage.rb21
-rw-r--r--lib/gitlab/background_migration/migrate_build_stage_id_reference.rb1
-rw-r--r--lib/gitlab/background_migration/migrate_events_to_push_event_payloads.rb19
-rw-r--r--lib/gitlab/background_migration/migrate_legacy_artifacts.rb1
-rw-r--r--lib/gitlab/background_migration/migrate_stage_index.rb1
-rw-r--r--lib/gitlab/background_migration/migrate_stage_status.rb45
-rw-r--r--lib/gitlab/background_migration/migrate_system_uploads_to_new_folder.rb5
-rw-r--r--lib/gitlab/background_migration/models/encrypt_columns/namespace.rb4
-rw-r--r--lib/gitlab/background_migration/models/encrypt_columns/project.rb4
-rw-r--r--lib/gitlab/background_migration/models/encrypt_columns/runner.rb4
-rw-r--r--lib/gitlab/background_migration/models/encrypt_columns/settings.rb6
-rw-r--r--lib/gitlab/background_migration/models/encrypt_columns/web_hook.rb14
-rw-r--r--lib/gitlab/background_migration/move_personal_snippet_files.rb15
-rw-r--r--lib/gitlab/background_migration/normalize_ldap_extern_uids_range.rb69
-rw-r--r--lib/gitlab/background_migration/populate_cluster_kubernetes_namespace_table.rb17
-rw-r--r--lib/gitlab/background_migration/populate_external_pipeline_source.rb17
-rw-r--r--lib/gitlab/background_migration/populate_fork_networks_range.rb108
-rw-r--r--lib/gitlab/background_migration/populate_merge_request_metrics_with_events_data.rb1
-rw-r--r--lib/gitlab/background_migration/populate_merge_request_metrics_with_events_data_improved.rb1
-rw-r--r--lib/gitlab/background_migration/populate_merge_requests_latest_merge_request_diff_id.rb3
-rw-r--r--lib/gitlab/background_migration/populate_untracked_uploads.rb46
-rw-r--r--lib/gitlab/background_migration/populate_untracked_uploads_dependencies.rb59
-rw-r--r--lib/gitlab/background_migration/prepare_untracked_uploads.rb29
-rw-r--r--lib/gitlab/background_migration/redact_links.rb11
-rw-r--r--lib/gitlab/background_migration/redact_links/redactable.rb9
-rw-r--r--lib/gitlab/background_migration/remove_restricted_todos.rb33
-rw-r--r--lib/gitlab/background_migration/schedule_diff_files_deletion.rb11
-rw-r--r--lib/gitlab/background_migration/set_confidential_note_events_on_services.rb7
-rw-r--r--lib/gitlab/background_migration/set_confidential_note_events_on_webhooks.rb7
-rw-r--r--lib/gitlab/badge/coverage/metadata.rb2
-rw-r--r--lib/gitlab/badge/coverage/report.rb2
-rw-r--r--lib/gitlab/badge/coverage/template.rb12
-rw-r--r--lib/gitlab/badge/pipeline/metadata.rb2
-rw-r--r--lib/gitlab/badge/pipeline/status.rb4
-rw-r--r--lib/gitlab/badge/pipeline/template.rb16
-rw-r--r--lib/gitlab/badge/template.rb2
-rw-r--r--lib/gitlab/bare_repository_import/importer.rb20
-rw-r--r--lib/gitlab/bare_repository_import/repository.rb12
-rw-r--r--lib/gitlab/bitbucket_import/importer.rb173
-rw-r--r--lib/gitlab/bitbucket_import/project_creator.rb4
-rw-r--r--lib/gitlab/bitbucket_server_import/importer.rb105
-rw-r--r--lib/gitlab/bitbucket_server_import/project_creator.rb4
-rw-r--r--lib/gitlab/blame.rb2
-rw-r--r--lib/gitlab/blob_helper.rb4
-rw-r--r--lib/gitlab/cache/ci/project_pipeline_status.rb10
-rw-r--r--lib/gitlab/cache/request_cache.rb4
-rw-r--r--lib/gitlab/changes_list.rb8
-rw-r--r--lib/gitlab/chat/command.rb8
-rw-r--r--lib/gitlab/chat/output.rb6
-rw-r--r--lib/gitlab/chat/responder/base.rb8
-rw-r--r--lib/gitlab/chat/responder/slack.rb10
-rw-r--r--lib/gitlab/chat_name_token.rb2
-rw-r--r--lib/gitlab/checks/base_checker.rb2
-rw-r--r--lib/gitlab/checks/branch_check.rb22
-rw-r--r--lib/gitlab/checks/diff_check.rb2
-rw-r--r--lib/gitlab/checks/lfs_check.rb4
-rw-r--r--lib/gitlab/checks/lfs_integrity.rb6
-rw-r--r--lib/gitlab/checks/post_push_message.rb2
-rw-r--r--lib/gitlab/checks/project_created.rb15
-rw-r--r--lib/gitlab/checks/project_moved.rb10
-rw-r--r--lib/gitlab/checks/tag_check.rb10
-rw-r--r--lib/gitlab/checks/timed_logger.rb2
-rw-r--r--lib/gitlab/ci/ansi2html.rb253
-rw-r--r--lib/gitlab/ci/build/artifacts/adapters/raw_stream.rb2
-rw-r--r--lib/gitlab/ci/build/artifacts/metadata.rb22
-rw-r--r--lib/gitlab/ci/build/artifacts/metadata/entry.rb4
-rw-r--r--lib/gitlab/ci/build/artifacts/path.rb12
-rw-r--r--lib/gitlab/ci/build/credentials/registry.rb2
-rw-r--r--lib/gitlab/ci/build/image.rb4
-rw-r--r--lib/gitlab/ci/build/policy.rb6
-rw-r--r--lib/gitlab/ci/build/policy/refs.rb6
-rw-r--r--lib/gitlab/ci/build/policy/variables.rb4
-rw-r--r--lib/gitlab/ci/build/step.rb10
-rw-r--r--lib/gitlab/ci/charts.rb6
-rw-r--r--lib/gitlab/ci/config/entry/artifacts.rb8
-rw-r--r--lib/gitlab/ci/config/entry/cache.rb10
-rw-r--r--lib/gitlab/ci/config/entry/environment.rb18
-rw-r--r--lib/gitlab/ci/config/entry/global.rb22
-rw-r--r--lib/gitlab/ci/config/entry/image.rb2
-rw-r--r--lib/gitlab/ci/config/entry/includes.rb4
-rw-r--r--lib/gitlab/ci/config/entry/job.rb92
-rw-r--r--lib/gitlab/ci/config/entry/jobs.rb4
-rw-r--r--lib/gitlab/ci/config/entry/key.rb2
-rw-r--r--lib/gitlab/ci/config/entry/policy.rb12
-rw-r--r--lib/gitlab/ci/config/entry/retry.rb34
-rw-r--r--lib/gitlab/ci/config/entry/stage.rb2
-rw-r--r--lib/gitlab/ci/config/extendable/entry.rb10
-rw-r--r--lib/gitlab/ci/config/external/file/base.rb2
-rw-r--r--lib/gitlab/ci/config/external/file/project.rb2
-rw-r--r--lib/gitlab/ci/config/external/file/template.rb2
-rw-r--r--lib/gitlab/ci/config/external/mapper.rb10
-rw-r--r--lib/gitlab/ci/cron_parser.rb6
-rw-r--r--lib/gitlab/ci/mask_secret.rb2
-rw-r--r--lib/gitlab/ci/model.rb2
-rw-r--r--lib/gitlab/ci/parsers.rb2
-rw-r--r--lib/gitlab/ci/parsers/test/junit.rb18
-rw-r--r--lib/gitlab/ci/pipeline/chain/command.rb4
-rw-r--r--lib/gitlab/ci/pipeline/chain/populate.rb4
-rw-r--r--lib/gitlab/ci/pipeline/chain/skip.rb2
-rw-r--r--lib/gitlab/ci/pipeline/chain/validate/abilities.rb4
-rw-r--r--lib/gitlab/ci/pipeline/chain/validate/repository.rb6
-rw-r--r--lib/gitlab/ci/pipeline/duration.rb8
-rw-r--r--lib/gitlab/ci/pipeline/expression/lexeme/null.rb2
-rw-r--r--lib/gitlab/ci/pipeline/expression/lexeme/pattern.rb6
-rw-r--r--lib/gitlab/ci/pipeline/expression/lexer.rb10
-rw-r--r--lib/gitlab/ci/pipeline/expression/statement.rb4
-rw-r--r--lib/gitlab/ci/pipeline/preloader.rb2
-rw-r--r--lib/gitlab/ci/pipeline/seed/stage.rb12
-rw-r--r--lib/gitlab/ci/reports/test_case.rb10
-rw-r--r--lib/gitlab/ci/reports/test_reports_comparer.rb2
-rw-r--r--lib/gitlab/ci/reports/test_suite.rb2
-rw-r--r--lib/gitlab/ci/reports/test_suite_comparer.rb12
-rw-r--r--lib/gitlab/ci/status/build/cancelable.rb6
-rw-r--r--lib/gitlab/ci/status/build/canceled.rb6
-rw-r--r--lib/gitlab/ci/status/build/common.rb6
-rw-r--r--lib/gitlab/ci/status/build/created.rb8
-rw-r--r--lib/gitlab/ci/status/build/erased.rb6
-rw-r--r--lib/gitlab/ci/status/build/factory.rb8
-rw-r--r--lib/gitlab/ci/status/build/failed.rb22
-rw-r--r--lib/gitlab/ci/status/build/failed_allowed.rb4
-rw-r--r--lib/gitlab/ci/status/build/manual.rb8
-rw-r--r--lib/gitlab/ci/status/build/pending.rb8
-rw-r--r--lib/gitlab/ci/status/build/play.rb8
-rw-r--r--lib/gitlab/ci/status/build/retryable.rb6
-rw-r--r--lib/gitlab/ci/status/build/scheduled.rb6
-rw-r--r--lib/gitlab/ci/status/build/skipped.rb6
-rw-r--r--lib/gitlab/ci/status/build/stop.rb8
-rw-r--r--lib/gitlab/ci/status/build/unschedule.rb8
-rw-r--r--lib/gitlab/ci/status/canceled.rb8
-rw-r--r--lib/gitlab/ci/status/created.rb8
-rw-r--r--lib/gitlab/ci/status/factory.rb4
-rw-r--r--lib/gitlab/ci/status/failed.rb8
-rw-r--r--lib/gitlab/ci/status/manual.rb8
-rw-r--r--lib/gitlab/ci/status/pending.rb8
-rw-r--r--lib/gitlab/ci/status/pipeline/blocked.rb4
-rw-r--r--lib/gitlab/ci/status/pipeline/delayed.rb4
-rw-r--r--lib/gitlab/ci/status/pipeline/factory.rb2
-rw-r--r--lib/gitlab/ci/status/running.rb8
-rw-r--r--lib/gitlab/ci/status/scheduled.rb8
-rw-r--r--lib/gitlab/ci/status/skipped.rb8
-rw-r--r--lib/gitlab/ci/status/stage/common.rb4
-rw-r--r--lib/gitlab/ci/status/success.rb8
-rw-r--r--lib/gitlab/ci/status/success_warning.rb8
-rw-r--r--lib/gitlab/ci/trace.rb49
-rw-r--r--lib/gitlab/ci/trace/chunked_io.rb12
-rw-r--r--lib/gitlab/ci/trace/section_parser.rb12
-rw-r--r--lib/gitlab/ci/trace/stream.rb10
-rw-r--r--lib/gitlab/ci/variables/collection.rb10
-rw-r--r--lib/gitlab/ci/variables/collection/item.rb6
-rw-r--r--lib/gitlab/ci/yaml_processor.rb62
-rw-r--r--lib/gitlab/cleanup/project_upload_file_finder.rb12
-rw-r--r--lib/gitlab/cleanup/project_uploads.rb14
-rw-r--r--lib/gitlab/cleanup/remote_uploads.rb21
-rw-r--r--lib/gitlab/closing_issue_extractor.rb2
-rw-r--r--lib/gitlab/cluster/lifecycle_events.rb2
-rw-r--r--lib/gitlab/cluster/puma_worker_killer_initializer.rb2
-rw-r--r--lib/gitlab/color_schemes.rb14
-rw-r--r--lib/gitlab/config/entry/attributable.rb2
-rw-r--r--lib/gitlab/config/entry/configurable.rb2
-rw-r--r--lib/gitlab/config/entry/factory.rb2
-rw-r--r--lib/gitlab/config/entry/legacy_validation_helpers.rb2
-rw-r--r--lib/gitlab/config/entry/node.rb10
-rw-r--r--lib/gitlab/config/entry/simplifiable.rb8
-rw-r--r--lib/gitlab/config/entry/validator.rb2
-rw-r--r--lib/gitlab/config/entry/validators.rb34
-rw-r--r--lib/gitlab/config/loader/yaml.rb2
-rw-r--r--lib/gitlab/conflict/file.rb32
-rw-r--r--lib/gitlab/conflict/file_collection.rb22
-rw-r--r--lib/gitlab/content_disposition.rb5
-rw-r--r--lib/gitlab/contributions_calendar.rb22
-rw-r--r--lib/gitlab/correlation_id.rb2
-rw-r--r--lib/gitlab/cross_project_access.rb24
-rw-r--r--lib/gitlab/crypto_helper.rb4
-rw-r--r--lib/gitlab/current_settings.rb10
-rw-r--r--lib/gitlab/cycle_analytics/base_event_fetcher.rb16
-rw-r--r--lib/gitlab/cycle_analytics/base_stage.rb4
-rw-r--r--lib/gitlab/cycle_analytics/code_event_fetcher.rb2
-rw-r--r--lib/gitlab/cycle_analytics/code_stage.rb2
-rw-r--r--lib/gitlab/cycle_analytics/issue_event_fetcher.rb2
-rw-r--r--lib/gitlab/cycle_analytics/issue_stage.rb4
-rw-r--r--lib/gitlab/cycle_analytics/permissions.rb2
-rw-r--r--lib/gitlab/cycle_analytics/plan_event_fetcher.rb12
-rw-r--r--lib/gitlab/cycle_analytics/plan_stage.rb4
-rw-r--r--lib/gitlab/cycle_analytics/production_stage.rb2
-rw-r--r--lib/gitlab/cycle_analytics/review_event_fetcher.rb2
-rw-r--r--lib/gitlab/cycle_analytics/review_stage.rb2
-rw-r--r--lib/gitlab/cycle_analytics/stage_summary.rb2
-rw-r--r--lib/gitlab/cycle_analytics/staging_event_fetcher.rb4
-rw-r--r--lib/gitlab/cycle_analytics/staging_stage.rb2
-rw-r--r--lib/gitlab/cycle_analytics/summary/base.rb4
-rw-r--r--lib/gitlab/cycle_analytics/summary/commit.rb2
-rw-r--r--lib/gitlab/cycle_analytics/summary/deploy.rb2
-rw-r--r--lib/gitlab/cycle_analytics/summary/issue.rb2
-rw-r--r--lib/gitlab/cycle_analytics/test_stage.rb2
-rw-r--r--lib/gitlab/cycle_analytics/updater.rb2
-rw-r--r--lib/gitlab/cycle_analytics/usage_data.rb14
-rw-r--r--lib/gitlab/danger/helper.rb17
-rw-r--r--lib/gitlab/danger/teammate.rb10
-rw-r--r--lib/gitlab/data_builder/build.rb10
-rw-r--r--lib/gitlab/data_builder/note.rb4
-rw-r--r--lib/gitlab/data_builder/pipeline.rb12
-rw-r--r--lib/gitlab/data_builder/push.rb18
-rw-r--r--lib/gitlab/data_builder/repository.rb20
-rw-r--r--lib/gitlab/data_builder/wiki_page.rb2
-rw-r--r--lib/gitlab/database.rb60
-rw-r--r--lib/gitlab/database/count.rb4
-rw-r--r--lib/gitlab/database/count/reltuples_count_strategy.rb8
-rw-r--r--lib/gitlab/database/count/tablesample_count_strategy.rb2
-rw-r--r--lib/gitlab/database/date_time.rb8
-rw-r--r--lib/gitlab/database/grant.rb14
-rw-r--r--lib/gitlab/database/median.rb57
-rw-r--r--lib/gitlab/database/migration_helpers.rb160
-rw-r--r--lib/gitlab/database/multi_threaded_migration.rb14
-rw-r--r--lib/gitlab/database/rename_reserved_paths_migration/v1/migration_classes.rb26
-rw-r--r--lib/gitlab/database/rename_reserved_paths_migration/v1/rename_base.rb32
-rw-r--r--lib/gitlab/database/rename_reserved_paths_migration/v1/rename_namespaces.rb16
-rw-r--r--lib/gitlab/database/rename_reserved_paths_migration/v1/rename_projects.rb12
-rw-r--r--lib/gitlab/database/sha_attribute.rb4
-rw-r--r--lib/gitlab/database/subquery.rb2
-rw-r--r--lib/gitlab/dependency_linker.rb2
-rw-r--r--lib/gitlab/dependency_linker/base_linker.rb2
-rw-r--r--lib/gitlab/dependency_linker/cartfile_linker.rb2
-rw-r--r--lib/gitlab/dependency_linker/gemfile_linker.rb4
-rw-r--r--lib/gitlab/dependency_linker/gemspec_linker.rb4
-rw-r--r--lib/gitlab/dependency_linker/godeps_json_linker.rb2
-rw-r--r--lib/gitlab/dependency_linker/json_linker.rb6
-rw-r--r--lib/gitlab/dependency_linker/package_json_linker.rb4
-rw-r--r--lib/gitlab/dependency_linker/podfile_linker.rb2
-rw-r--r--lib/gitlab/dependency_linker/podspec_json_linker.rb4
-rw-r--r--lib/gitlab/dependency_linker/podspec_linker.rb4
-rw-r--r--lib/gitlab/diff/diff_refs.rb8
-rw-r--r--lib/gitlab/diff/file.rb17
-rw-r--r--lib/gitlab/diff/file_collection/base.rb8
-rw-r--r--lib/gitlab/diff/file_collection/compare.rb4
-rw-r--r--lib/gitlab/diff/formatters/base_formatter.rb2
-rw-r--r--lib/gitlab/diff/formatters/text_formatter.rb4
-rw-r--r--lib/gitlab/diff/highlight.rb6
-rw-r--r--lib/gitlab/diff/highlight_cache.rb4
-rw-r--r--lib/gitlab/diff/image_point.rb2
-rw-r--r--lib/gitlab/diff/inline_diff.rb2
-rw-r--r--lib/gitlab/diff/inline_diff_markdown_marker.rb2
-rw-r--r--lib/gitlab/diff/inline_diff_marker.rb2
-rw-r--r--lib/gitlab/diff/line.rb18
-rw-r--r--lib/gitlab/diff/line_mapper.rb4
-rw-r--r--lib/gitlab/diff/lines_unfolder.rb12
-rw-r--r--lib/gitlab/diff/parallel_diff.rb6
-rw-r--r--lib/gitlab/diff/parser.rb22
-rw-r--r--lib/gitlab/diff/position.rb36
-rw-r--r--lib/gitlab/diff/position_tracer.rb22
-rw-r--r--lib/gitlab/discussions_diff/highlight_cache.rb6
-rw-r--r--lib/gitlab/downtime_check.rb4
-rw-r--r--lib/gitlab/downtime_check/message.rb4
-rw-r--r--lib/gitlab/ee_compat_check.rb81
-rw-r--r--lib/gitlab/email/attachment_uploader.rb6
-rw-r--r--lib/gitlab/email/handler.rb2
-rw-r--r--lib/gitlab/email/handler/base_handler.rb2
-rw-r--r--lib/gitlab/email/handler/create_issue_handler.rb11
-rw-r--r--lib/gitlab/email/handler/create_merge_request_handler.rb19
-rw-r--r--lib/gitlab/email/handler/create_note_handler.rb7
-rw-r--r--lib/gitlab/email/handler/reply_processing.rb8
-rw-r--r--lib/gitlab/email/handler/unsubscribe_handler.rb4
-rw-r--r--lib/gitlab/email/hook/additional_headers_interceptor.rb4
-rw-r--r--lib/gitlab/email/hook/delivery_metrics_observer.rb4
-rw-r--r--lib/gitlab/email/hook/email_template_interceptor.rb2
-rw-r--r--lib/gitlab/email/html_parser.rb6
-rw-r--r--lib/gitlab/email/message/repository_push.rb16
-rw-r--r--lib/gitlab/email/receiver.rb6
-rw-r--r--lib/gitlab/email/reply_parser.rb10
-rw-r--r--lib/gitlab/emoji.rb8
-rw-r--r--lib/gitlab/encoding_helper.rb8
-rw-r--r--lib/gitlab/environment.rb2
-rw-r--r--lib/gitlab/error_tracking/project.rb2
-rw-r--r--lib/gitlab/etag_caching/middleware.rb8
-rw-r--r--lib/gitlab/etag_caching/router.rb46
-rw-r--r--lib/gitlab/etag_caching/store.rb4
-rw-r--r--lib/gitlab/exclusive_lease.rb8
-rw-r--r--lib/gitlab/exclusive_lease_helpers.rb4
-rw-r--r--lib/gitlab/fake_application_settings.rb4
-rw-r--r--lib/gitlab/favicon.rb14
-rw-r--r--lib/gitlab/file_detector.rb30
-rw-r--r--lib/gitlab/file_finder.rb4
-rw-r--r--lib/gitlab/file_markdown_link_builder.rb2
-rw-r--r--lib/gitlab/file_type_detection.rb2
-rw-r--r--lib/gitlab/fogbugz_import/client.rb14
-rw-r--r--lib/gitlab/fogbugz_import/importer.rb140
-rw-r--r--lib/gitlab/fogbugz_import/project_creator.rb4
-rw-r--r--lib/gitlab/fogbugz_import/repository.rb8
-rw-r--r--lib/gitlab/gfm/reference_rewriter.rb2
-rw-r--r--lib/gitlab/gfm/uploads_rewriter.rb6
-rw-r--r--lib/gitlab/git.rb28
-rw-r--r--lib/gitlab/git/attributes_at_ref_parser.rb2
-rw-r--r--lib/gitlab/git/attributes_parser.rb14
-rw-r--r--lib/gitlab/git/blob.rb14
-rw-r--r--lib/gitlab/git/branch.rb2
-rw-r--r--lib/gitlab/git/bundle_file.rb4
-rw-r--r--lib/gitlab/git/commit.rb10
-rw-r--r--lib/gitlab/git/conflict/file.rb22
-rw-r--r--lib/gitlab/git/conflict/parser.rb20
-rw-r--r--lib/gitlab/git/conflict/resolver.rb4
-rw-r--r--lib/gitlab/git/diff.rb44
-rw-r--r--lib/gitlab/git/diff_collection.rb6
-rw-r--r--lib/gitlab/git/gitmodules_parser.rb4
-rw-r--r--lib/gitlab/git/lfs_pointer_file.rb4
-rw-r--r--lib/gitlab/git/merge_base.rb2
-rw-r--r--lib/gitlab/git/operation_service.rb4
-rw-r--r--lib/gitlab/git/patches/collection.rb4
-rw-r--r--lib/gitlab/git/path_helper.rb4
-rw-r--r--lib/gitlab/git/pre_receive_error.rb2
-rw-r--r--lib/gitlab/git/push.rb2
-rw-r--r--lib/gitlab/git/raw_diff_change.rb14
-rw-r--r--lib/gitlab/git/ref.rb16
-rw-r--r--lib/gitlab/git/remote_repository.rb12
-rw-r--r--lib/gitlab/git/repository.rb82
-rw-r--r--lib/gitlab/git/tag.rb2
-rw-r--r--lib/gitlab/git/tree.rb14
-rw-r--r--lib/gitlab/git/util.rb2
-rw-r--r--lib/gitlab/git/wiki.rb30
-rw-r--r--lib/gitlab/git_access.rb52
-rw-r--r--lib/gitlab/git_access_wiki.rb4
-rw-r--r--lib/gitlab/git_logger.rb2
-rw-r--r--lib/gitlab/git_post_receive.rb6
-rw-r--r--lib/gitlab/git_ref_validator.rb4
-rw-r--r--lib/gitlab/gitaly_client.rb71
-rw-r--r--lib/gitlab/gitaly_client/blobs_stitcher.rb20
-rw-r--r--lib/gitlab/gitaly_client/cleanup_service.rb4
-rw-r--r--lib/gitlab/gitaly_client/commit_service.rb44
-rw-r--r--lib/gitlab/gitaly_client/conflict_files_stitcher.rb6
-rw-r--r--lib/gitlab/gitaly_client/conflicts_service.rb4
-rw-r--r--lib/gitlab/gitaly_client/diff.rb2
-rw-r--r--lib/gitlab/gitaly_client/health_check_service.rb4
-rw-r--r--lib/gitlab/gitaly_client/object_pool_service.rb7
-rw-r--r--lib/gitlab/gitaly_client/operation_service.rb46
-rw-r--r--lib/gitlab/gitaly_client/ref_service.rb12
-rw-r--r--lib/gitlab/gitaly_client/remote_service.rb20
-rw-r--r--lib/gitlab/gitaly_client/repository_service.rb12
-rw-r--r--lib/gitlab/gitaly_client/storage_settings.rb8
-rw-r--r--lib/gitlab/gitaly_client/util.rb10
-rw-r--r--lib/gitlab/gitaly_client/wiki_file.rb2
-rw-r--r--lib/gitlab/gitaly_client/wiki_page.rb2
-rw-r--r--lib/gitlab/gitaly_client/wiki_service.rb10
-rw-r--r--lib/gitlab/github_import.rb4
-rw-r--r--lib/gitlab/github_import/caching.rb4
-rw-r--r--lib/gitlab/github_import/client.rb14
-rw-r--r--lib/gitlab/github_import/importer/diff_note_importer.rb6
-rw-r--r--lib/gitlab/github_import/importer/issue_importer.rb6
-rw-r--r--lib/gitlab/github_import/importer/issues_importer.rb2
-rw-r--r--lib/gitlab/github_import/importer/label_links_importer.rb2
-rw-r--r--lib/gitlab/github_import/importer/labels_importer.rb6
-rw-r--r--lib/gitlab/github_import/importer/lfs_objects_importer.rb2
-rw-r--r--lib/gitlab/github_import/importer/milestones_importer.rb6
-rw-r--r--lib/gitlab/github_import/importer/note_importer.rb2
-rw-r--r--lib/gitlab/github_import/importer/pull_request_importer.rb14
-rw-r--r--lib/gitlab/github_import/importer/pull_requests_importer.rb6
-rw-r--r--lib/gitlab/github_import/importer/releases_importer.rb2
-rw-r--r--lib/gitlab/github_import/importer/repository_importer.rb4
-rw-r--r--lib/gitlab/github_import/issuable_finder.rb4
-rw-r--r--lib/gitlab/github_import/label_finder.rb8
-rw-r--r--lib/gitlab/github_import/milestone_finder.rb8
-rw-r--r--lib/gitlab/github_import/page_counter.rb4
-rw-r--r--lib/gitlab/github_import/parallel_scheduling.rb4
-rw-r--r--lib/gitlab/github_import/representation/diff_note.rb14
-rw-r--r--lib/gitlab/github_import/representation/issue.rb12
-rw-r--r--lib/gitlab/github_import/representation/lfs_object.rb2
-rw-r--r--lib/gitlab/github_import/representation/note.rb12
-rw-r--r--lib/gitlab/github_import/representation/pull_request.rb14
-rw-r--r--lib/gitlab/github_import/sequential_importer.rb4
-rw-r--r--lib/gitlab/github_import/user_finder.rb6
-rw-r--r--lib/gitlab/gitlab_import/client.rb4
-rw-r--r--lib/gitlab/gitlab_import/importer.rb4
-rw-r--r--lib/gitlab/gl_id.rb2
-rw-r--r--lib/gitlab/gl_repository.rb4
-rw-r--r--lib/gitlab/gon_helper.rb12
-rw-r--r--lib/gitlab/google_code_import/importer.rb82
-rw-r--r--lib/gitlab/google_code_import/project_creator.rb2
-rw-r--r--lib/gitlab/gpg.rb14
-rw-r--r--lib/gitlab/gpg/commit.rb2
-rw-r--r--lib/gitlab/gpg/invalid_gpg_signature_updater.rb2
-rw-r--r--lib/gitlab/grape_logging/formatters/lograge_with_timestamp.rb6
-rw-r--r--lib/gitlab/grape_logging/loggers/correlation_id_logger.rb2
-rw-r--r--lib/gitlab/grape_logging/loggers/perf_logger.rb2
-rw-r--r--lib/gitlab/grape_logging/loggers/queue_duration_logger.rb4
-rw-r--r--lib/gitlab/grape_logging/loggers/route_logger.rb2
-rw-r--r--lib/gitlab/graphql/authorize/authorize_resource.rb12
-rw-r--r--lib/gitlab/graphql/authorize/instrumentation.rb2
-rw-r--r--lib/gitlab/graphql/expose_permissions.rb8
-rw-r--r--lib/gitlab/graphql/loaders/batch_model_loader.rb4
-rw-r--r--lib/gitlab/graphql/mount_mutation.rb2
-rw-r--r--lib/gitlab/graphql/present/instrumentation.rb2
-rw-r--r--lib/gitlab/graphs/commits.rb6
-rw-r--r--lib/gitlab/hashed_storage/rake_helper.rb12
-rw-r--r--lib/gitlab/health_checks/base_abstract_check.rb10
-rw-r--r--lib/gitlab/health_checks/db_check.rb8
-rw-r--r--lib/gitlab/health_checks/gitaly_check.rb6
-rw-r--r--lib/gitlab/health_checks/prometheus_text_format.rb2
-rw-r--r--lib/gitlab/health_checks/redis/cache_check.rb4
-rw-r--r--lib/gitlab/health_checks/redis/queues_check.rb4
-rw-r--r--lib/gitlab/health_checks/redis/redis_check.rb4
-rw-r--r--lib/gitlab/health_checks/redis/shared_state_check.rb4
-rw-r--r--lib/gitlab/health_checks/simple_abstract_check.rb2
-rw-r--r--lib/gitlab/highlight.rb4
-rw-r--r--lib/gitlab/hook_data/base_builder.rb6
-rw-r--r--lib/gitlab/hook_data/issuable_builder.rb7
-rw-r--r--lib/gitlab/hook_data/issue_builder.rb18
-rw-r--r--lib/gitlab/hook_data/merge_request_builder.rb6
-rw-r--r--lib/gitlab/hook_data/note_builder.rb2
-rw-r--r--lib/gitlab/hook_data/wiki_page_builder.rb4
-rw-r--r--lib/gitlab/http_io.rb14
-rw-r--r--lib/gitlab/i18n.rb44
-rw-r--r--lib/gitlab/i18n/metadata_entry.rb4
-rw-r--r--lib/gitlab/i18n/po_linter.rb47
-rw-r--r--lib/gitlab/i18n/translation_entry.rb10
-rw-r--r--lib/gitlab/identifier.rb6
-rw-r--r--lib/gitlab/import/database_helpers.rb2
-rw-r--r--lib/gitlab/import/logger.rb2
-rw-r--r--lib/gitlab/import_export.rb12
-rw-r--r--lib/gitlab/import_export/after_export_strategies/base_after_export_strategy.rb2
-rw-r--r--lib/gitlab/import_export/after_export_strategies/web_upload_strategy.rb16
-rw-r--r--lib/gitlab/import_export/after_export_strategy_builder.rb6
-rw-r--r--lib/gitlab/import_export/attribute_cleaner.rb8
-rw-r--r--lib/gitlab/import_export/attributes_finder.rb8
-rw-r--r--lib/gitlab/import_export/avatar_restorer.rb2
-rw-r--r--lib/gitlab/import_export/avatar_saver.rb2
-rw-r--r--lib/gitlab/import_export/command_line_util.rb16
-rw-r--r--lib/gitlab/import_export/file_importer.rb2
-rw-r--r--lib/gitlab/import_export/group_project_object_builder.rb20
-rw-r--r--lib/gitlab/import_export/hash_util.rb4
-rw-r--r--lib/gitlab/import_export/importer.rb12
-rw-r--r--lib/gitlab/import_export/json_hash_builder.rb8
-rw-r--r--lib/gitlab/import_export/lfs_restorer.rb2
-rw-r--r--lib/gitlab/import_export/lfs_saver.rb4
-rw-r--r--lib/gitlab/import_export/members_mapper.rb16
-rw-r--r--lib/gitlab/import_export/merge_request_parser.rb4
-rw-r--r--lib/gitlab/import_export/project_tree_restorer.rb22
-rw-r--r--lib/gitlab/import_export/project_tree_saver.rb6
-rw-r--r--lib/gitlab/import_export/relation_factory.rb113
-rw-r--r--lib/gitlab/import_export/relation_rename_service.rb2
-rw-r--r--lib/gitlab/import_export/shared.rb6
-rw-r--r--lib/gitlab/import_export/uploads_manager.rb8
-rw-r--r--lib/gitlab/import_export/version_checker.rb2
-rw-r--r--lib/gitlab/import_export/version_saver.rb2
-rw-r--r--lib/gitlab/import_sources.rb20
-rw-r--r--lib/gitlab/incoming_email.rb10
-rw-r--r--lib/gitlab/insecure_key_fingerprint.rb2
-rw-r--r--lib/gitlab/issuable_metadata.rb4
-rw-r--r--lib/gitlab/issuable_sorter.rb4
-rw-r--r--lib/gitlab/issues_labels.rb24
-rw-r--r--lib/gitlab/job_waiter.rb2
-rw-r--r--lib/gitlab/json_cache.rb2
-rw-r--r--lib/gitlab/kubernetes.rb72
-rw-r--r--lib/gitlab/kubernetes/cluster_role_binding.rb8
-rw-r--r--lib/gitlab/kubernetes/config_map.rb2
-rw-r--r--lib/gitlab/kubernetes/helm.rb12
-rw-r--r--lib/gitlab/kubernetes/helm/api.rb2
-rw-r--r--lib/gitlab/kubernetes/helm/certificate.rb7
-rw-r--r--lib/gitlab/kubernetes/helm/client_command.rb4
-rw-r--r--lib/gitlab/kubernetes/helm/init_command.rb16
-rw-r--r--lib/gitlab/kubernetes/helm/install_command.rb28
-rw-r--r--lib/gitlab/kubernetes/helm/pod.rb32
-rw-r--r--lib/gitlab/kubernetes/kube_client.rb12
-rw-r--r--lib/gitlab/kubernetes/logger.rb2
-rw-r--r--lib/gitlab/kubernetes/namespace.rb2
-rw-r--r--lib/gitlab/kubernetes/pod.rb10
-rw-r--r--lib/gitlab/kubernetes/role_binding.rb14
-rw-r--r--lib/gitlab/kubernetes/service_account.rb2
-rw-r--r--lib/gitlab/kubernetes/service_account_token.rb6
-rw-r--r--lib/gitlab/language_data.rb6
-rw-r--r--lib/gitlab/language_detection.rb20
-rw-r--r--lib/gitlab/legacy_github_import/base_formatter.rb2
-rw-r--r--lib/gitlab/legacy_github_import/branch_formatter.rb2
-rw-r--r--lib/gitlab/legacy_github_import/client.rb14
-rw-r--r--lib/gitlab/legacy_github_import/comment_formatter.rb4
-rw-r--r--lib/gitlab/legacy_github_import/importer.rb82
-rw-r--r--lib/gitlab/legacy_github_import/issuable_formatter.rb4
-rw-r--r--lib/gitlab/legacy_github_import/issue_formatter.rb2
-rw-r--r--lib/gitlab/legacy_github_import/label_formatter.rb2
-rw-r--r--lib/gitlab/legacy_github_import/milestone_formatter.rb6
-rw-r--r--lib/gitlab/legacy_github_import/project_creator.rb6
-rw-r--r--lib/gitlab/legacy_github_import/pull_request_formatter.rb8
-rw-r--r--lib/gitlab/legacy_github_import/release_formatter.rb4
-rw-r--r--lib/gitlab/legacy_github_import/user_formatter.rb8
-rw-r--r--lib/gitlab/lfs_token.rb10
-rw-r--r--lib/gitlab/logger.rb10
-rw-r--r--lib/gitlab/mail_room.rb18
-rw-r--r--lib/gitlab/manifest_import/manifest.rb20
-rw-r--r--lib/gitlab/manifest_import/project_creator.rb8
-rw-r--r--lib/gitlab/markup_helper.rb4
-rw-r--r--lib/gitlab/metrics/background_transaction.rb2
-rw-r--r--lib/gitlab/metrics/influx_db.rb32
-rw-r--r--lib/gitlab/metrics/instrumentation.rb4
-rw-r--r--lib/gitlab/metrics/method_call.rb8
-rw-r--r--lib/gitlab/metrics/metric.rb8
-rw-r--r--lib/gitlab/metrics/prometheus.rb2
-rw-r--r--lib/gitlab/metrics/rack_middleware.rb5
-rw-r--r--lib/gitlab/metrics/requests_rack_middleware.rb12
-rw-r--r--lib/gitlab/metrics/samplers/base_sampler.rb2
-rw-r--r--lib/gitlab/metrics/samplers/influx_sampler.rb8
-rw-r--r--lib/gitlab/metrics/samplers/ruby_sampler.rb14
-rw-r--r--lib/gitlab/metrics/samplers/unicorn_sampler.rb12
-rw-r--r--lib/gitlab/metrics/sidekiq_metrics_exporter.rb12
-rw-r--r--lib/gitlab/metrics/sidekiq_middleware.rb2
-rw-r--r--lib/gitlab/metrics/subscribers/action_view.rb14
-rw-r--r--lib/gitlab/metrics/subscribers/active_record.rb6
-rw-r--r--lib/gitlab/metrics/subscribers/rails_cache.rb8
-rw-r--r--lib/gitlab/metrics/system.rb6
-rw-r--r--lib/gitlab/metrics/transaction.rb20
-rw-r--r--lib/gitlab/metrics/web_transaction.rb28
-rw-r--r--lib/gitlab/middleware/basic_health_check.rb8
-rw-r--r--lib/gitlab/middleware/go.rb28
-rw-r--r--lib/gitlab/middleware/multipart.rb8
-rw-r--r--lib/gitlab/middleware/rails_queue_duration.rb4
-rw-r--r--lib/gitlab/middleware/read_only/controller.rb44
-rw-r--r--lib/gitlab/middleware/release_env.rb4
-rw-r--r--lib/gitlab/middleware/static.rb2
-rw-r--r--lib/gitlab/multi_collection_paginator.rb26
-rw-r--r--lib/gitlab/namespace_sanitizer.rb2
-rw-r--r--lib/gitlab/object_hierarchy.rb2
-rw-r--r--lib/gitlab/omniauth_initializer.rb26
-rw-r--r--lib/gitlab/optimistic_locking.rb2
-rw-r--r--lib/gitlab/otp_key_rotator.rb4
-rw-r--r--lib/gitlab/pages_client.rb12
-rw-r--r--lib/gitlab/patch/sprockets_base_file_digest_key.rb2
-rw-r--r--lib/gitlab/path_regex.rb8
-rw-r--r--lib/gitlab/performance_bar.rb2
-rw-r--r--lib/gitlab/performance_bar/peek_query_tracker.rb6
-rw-r--r--lib/gitlab/plugin.rb6
-rw-r--r--lib/gitlab/plugin_logger.rb2
-rw-r--r--lib/gitlab/polling_interval.rb2
-rw-r--r--lib/gitlab/popen.rb12
-rw-r--r--lib/gitlab/private_commit_email.rb2
-rw-r--r--lib/gitlab/profiler.rb27
-rw-r--r--lib/gitlab/profiler/total_time_flat_printer.rb2
-rw-r--r--lib/gitlab/project_authorizations/with_nested_groups.rb24
-rw-r--r--lib/gitlab/project_authorizations/without_nested_groups.rb2
-rw-r--r--lib/gitlab/project_search_results.rb22
-rw-r--r--lib/gitlab/project_service_logger.rb2
-rw-r--r--lib/gitlab/project_template.rb32
-rw-r--r--lib/gitlab/project_transfer.rb8
-rw-r--r--lib/gitlab/prometheus/additional_metrics_parser.rb2
-rw-r--r--lib/gitlab/prometheus/metric.rb2
-rw-r--r--lib/gitlab/prometheus/metric_group.rb4
-rw-r--r--lib/gitlab/prometheus/queries/deployment_query.rb2
-rw-r--r--lib/gitlab/prometheus/queries/environment_query.rb2
-rw-r--r--lib/gitlab/prometheus/queries/matched_metric_query.rb14
-rw-r--r--lib/gitlab/prometheus/queries/query_additional_metrics.rb14
-rw-r--r--lib/gitlab/prometheus/query_variables.rb4
-rw-r--r--lib/gitlab/prometheus_client.rb40
-rw-r--r--lib/gitlab/protocol_access.rb2
-rw-r--r--lib/gitlab/query_limiting.rb4
-rw-r--r--lib/gitlab/query_limiting/active_support_subscriber.rb2
-rw-r--r--lib/gitlab/query_limiting/middleware.rb16
-rw-r--r--lib/gitlab/query_limiting/transaction.rb2
-rw-r--r--lib/gitlab/quick_actions/command_definition.rb28
-rw-r--r--lib/gitlab/quick_actions/dsl.rb10
-rw-r--r--lib/gitlab/quick_actions/extractor.rb10
-rw-r--r--lib/gitlab/quick_actions/spend_time_and_date_separator.rb8
-rw-r--r--lib/gitlab/redis/cache.rb10
-rw-r--r--lib/gitlab/redis/queues.rb12
-rw-r--r--lib/gitlab/redis/shared_state.rb14
-rw-r--r--lib/gitlab/redis/wrapper.rb16
-rw-r--r--lib/gitlab/reference_extractor.rb8
-rw-r--r--lib/gitlab/repo_path.rb6
-rw-r--r--lib/gitlab/repository_cache_adapter.rb2
-rw-r--r--lib/gitlab/repository_check_logger.rb2
-rw-r--r--lib/gitlab/request_profiler.rb6
-rw-r--r--lib/gitlab/request_profiler/middleware.rb16
-rw-r--r--lib/gitlab/request_profiler/profile.rb6
-rw-r--r--lib/gitlab/route_map.rb20
-rw-r--r--lib/gitlab/routing.rb8
-rw-r--r--lib/gitlab/sanitizers/svg.rb4
-rw-r--r--lib/gitlab/sanitizers/svg/whitelist.rb160
-rw-r--r--lib/gitlab/search/found_blob.rb10
-rw-r--r--lib/gitlab/search/query.rb16
-rw-r--r--lib/gitlab/search_results.rb18
-rw-r--r--lib/gitlab/sentry.rb2
-rw-r--r--lib/gitlab/setup_helper.rb24
-rw-r--r--lib/gitlab/shard_health_cache.rb2
-rw-r--r--lib/gitlab/shell.rb60
-rw-r--r--lib/gitlab/sherlock.rb6
-rw-r--r--lib/gitlab/sherlock/collection.rb2
-rw-r--r--lib/gitlab/sherlock/file_sample.rb2
-rw-r--r--lib/gitlab/sherlock/line_profiler.rb6
-rw-r--r--lib/gitlab/sherlock/middleware.rb6
-rw-r--r--lib/gitlab/sherlock/query.rb6
-rw-r--r--lib/gitlab/sherlock/transaction.rb8
-rw-r--r--lib/gitlab/sidekiq_config.rb22
-rw-r--r--lib/gitlab/sidekiq_logger.rb2
-rw-r--r--lib/gitlab/sidekiq_logging/json_formatter.rb2
-rw-r--r--lib/gitlab/sidekiq_logging/structured_logger.rb36
-rw-r--r--lib/gitlab/sidekiq_middleware/arguments_logger.rb2
-rw-r--r--lib/gitlab/sidekiq_middleware/shutdown.rb18
-rw-r--r--lib/gitlab/sidekiq_status.rb8
-rw-r--r--lib/gitlab/sidekiq_status/client_middleware.rb4
-rw-r--r--lib/gitlab/sidekiq_status/server_middleware.rb2
-rw-r--r--lib/gitlab/sidekiq_versioning.rb2
-rw-r--r--lib/gitlab/slash_commands/command.rb6
-rw-r--r--lib/gitlab/slash_commands/deploy.rb6
-rw-r--r--lib/gitlab/slash_commands/help.rb2
-rw-r--r--lib/gitlab/slash_commands/issue_move.rb4
-rw-r--r--lib/gitlab/slash_commands/issue_new.rb2
-rw-r--r--lib/gitlab/slash_commands/presenters/base.rb6
-rw-r--r--lib/gitlab/slash_commands/presenters/help.rb2
-rw-r--r--lib/gitlab/slash_commands/presenters/issue_base.rb14
-rw-r--r--lib/gitlab/slash_commands/presenters/issue_move.rb25
-rw-r--r--lib/gitlab/slash_commands/presenters/issue_new.rb24
-rw-r--r--lib/gitlab/slash_commands/presenters/issue_search.rb16
-rw-r--r--lib/gitlab/slash_commands/presenters/issue_show.rb26
-rw-r--r--lib/gitlab/slash_commands/presenters/run.rb6
-rw-r--r--lib/gitlab/slash_commands/run.rb2
-rw-r--r--lib/gitlab/snippet_search_results.rb10
-rw-r--r--lib/gitlab/sql/glob.rb6
-rw-r--r--lib/gitlab/sql/pattern.rb4
-rw-r--r--lib/gitlab/sql/recursive_cte.rb2
-rw-r--r--lib/gitlab/sql/union.rb8
-rw-r--r--lib/gitlab/ssh_public_key.rb4
-rw-r--r--lib/gitlab/string_range_marker.rb8
-rw-r--r--lib/gitlab/task_helpers.rb40
-rw-r--r--lib/gitlab/tcp_checker.rb2
-rw-r--r--lib/gitlab/template/base_template.rb18
-rw-r--r--lib/gitlab/template/dockerfile_template.rb8
-rw-r--r--lib/gitlab/template/finders/global_template_finder.rb2
-rw-r--r--lib/gitlab/template/finders/repo_template_finder.rb2
-rw-r--r--lib/gitlab/template/gitignore_template.rb10
-rw-r--r--lib/gitlab/template/gitlab_ci_yml_template.rb14
-rw-r--r--lib/gitlab/template/issue_template.rb6
-rw-r--r--lib/gitlab/template/merge_request_template.rb6
-rw-r--r--lib/gitlab/testing/request_blocker_middleware.rb1
-rw-r--r--lib/gitlab/testing/request_inspector_middleware.rb14
-rw-r--r--lib/gitlab/themes.rb22
-rw-r--r--lib/gitlab/time_tracking_formatter.rb12
-rw-r--r--lib/gitlab/timeless.rb1
-rw-r--r--lib/gitlab/tracing.rb4
-rw-r--r--lib/gitlab/tracing/common.rb18
-rw-r--r--lib/gitlab/tracing/factory.rb2
-rw-r--r--lib/gitlab/tracing/grpc_interceptor.rb20
-rw-r--r--lib/gitlab/tracing/jaeger_factory.rb6
-rw-r--r--lib/gitlab/tracing/rack_middleware.rb14
-rw-r--r--lib/gitlab/tracing/rails/action_view_subscriber.rb28
-rw-r--r--lib/gitlab/tracing/rails/active_record_subscriber.rb22
-rw-r--r--lib/gitlab/tracing/sidekiq/client_middleware.rb9
-rw-r--r--lib/gitlab/tracing/sidekiq/server_middleware.rb9
-rw-r--r--lib/gitlab/tracing/sidekiq/sidekiq_common.rb12
-rw-r--r--lib/gitlab/tree_summary.rb6
-rw-r--r--lib/gitlab/untrusted_regexp.rb12
-rw-r--r--lib/gitlab/url_blocker.rb20
-rw-r--r--lib/gitlab/url_builder.rb4
-rw-r--r--lib/gitlab/url_sanitizer.rb14
-rw-r--r--lib/gitlab/usage_data.rb40
-rw-r--r--lib/gitlab/user_access.rb12
-rw-r--r--lib/gitlab/user_extractor.rb2
-rw-r--r--lib/gitlab/utils.rb36
-rw-r--r--lib/gitlab/utils/merge_hash.rb2
-rw-r--r--lib/gitlab/utils/override.rb20
-rw-r--r--lib/gitlab/utils/strong_memoize.rb2
-rw-r--r--lib/gitlab/verify/batch_verifier.rb8
-rw-r--r--lib/gitlab/verify/job_artifacts.rb2
-rw-r--r--lib/gitlab/verify/lfs_objects.rb2
-rw-r--r--lib/gitlab/verify/rake_task.rb10
-rw-r--r--lib/gitlab/verify/uploads.rb2
-rw-r--r--lib/gitlab/visibility_level.rb20
-rw-r--r--lib/gitlab/web_ide_commits_counter.rb2
-rw-r--r--lib/gitlab/webpack/dev_server_middleware.rb8
-rw-r--r--lib/gitlab/webpack/manifest.rb2
-rw-r--r--lib/gitlab/wiki_file_finder.rb2
-rw-r--r--lib/gitlab/workhorse.rb106
-rw-r--r--lib/google_api/auth.rb10
-rw-r--r--lib/google_api/cloud_platform/client.rb22
-rw-r--r--lib/haml_lint/inline_javascript.rb14
-rw-r--r--lib/json_web_token/hmac_token.rb6
-rw-r--r--lib/json_web_token/rsa_token.rb6
-rw-r--r--lib/json_web_token/token.rb4
-rw-r--r--lib/mattermost/client.rb4
-rw-r--r--lib/mattermost/command.rb4
-rw-r--r--lib/mattermost/session.rb19
-rw-r--r--lib/mattermost/team.rb4
-rw-r--r--lib/microsoft_teams/activity.rb8
-rw-r--r--lib/microsoft_teams/notifier.rb16
-rw-r--r--lib/milestone_array.rb24
-rw-r--r--lib/mysql_zero_date.rb2
-rw-r--r--lib/object_storage/direct_upload.rb26
-rw-r--r--lib/omni_auth/strategies/bitbucket.rb28
-rw-r--r--lib/omni_auth/strategies/jwt.rb24
-rw-r--r--lib/peek/views/gitaly.rb4
-rw-r--r--lib/peek/views/host.rb2
-rw-r--r--lib/peek/views/tracing.rb2
-rw-r--r--lib/quality/helm_client.rb28
-rw-r--r--lib/quality/kubernetes_client.rb12
-rw-r--r--lib/rouge/formatters/html_gitlab.rb2
-rw-r--r--lib/rspec_flaky/config.rb8
-rw-r--r--lib/rspec_flaky/flaky_example.rb7
-rw-r--r--lib/rspec_flaky/flaky_examples_collection.rb10
-rw-r--r--lib/rspec_flaky/listener.rb12
-rw-r--r--lib/rspec_flaky/report.rb12
-rw-r--r--lib/safe_zip/extract.rb8
-rw-r--r--lib/safe_zip/extract_params.rb4
-rw-r--r--lib/sentry/client.rb62
-rw-r--r--lib/static_model.rb2
-rw-r--r--lib/system_check/app/active_users_check.rb2
-rw-r--r--lib/system_check/app/database_config_exists_check.rb12
-rw-r--r--lib/system_check/app/git_config_check.rb20
-rw-r--r--lib/system_check/app/git_user_default_ssh_config_check.rb12
-rw-r--r--lib/system_check/app/git_version_check.rb8
-rw-r--r--lib/system_check/app/gitlab_config_exists_check.rb10
-rw-r--r--lib/system_check/app/gitlab_config_up_to_date_check.rb14
-rw-r--r--lib/system_check/app/init_script_exists_check.rb10
-rw-r--r--lib/system_check/app/init_script_up_to_date_check.rb12
-rw-r--r--lib/system_check/app/log_writable_check.rb6
-rw-r--r--lib/system_check/app/migrations_are_up_check.rb6
-rw-r--r--lib/system_check/app/orphaned_group_members_check.rb10
-rw-r--r--lib/system_check/app/projects_have_namespace_check.rb8
-rw-r--r--lib/system_check/app/redis_version_check.rb6
-rw-r--r--lib/system_check/app/ruby_version_check.rb4
-rw-r--r--lib/system_check/app/tmp_writable_check.rb6
-rw-r--r--lib/system_check/app/uploads_directory_exists_check.rb6
-rw-r--r--lib/system_check/app/uploads_path_permission_check.rb10
-rw-r--r--lib/system_check/app/uploads_path_tmp_permission_check.rb12
-rw-r--r--lib/system_check/base_check.rb8
-rw-r--r--lib/system_check/gitaly_check.rb4
-rw-r--r--lib/system_check/gitlab_shell_check.rb14
-rw-r--r--lib/system_check/helpers.rb22
-rw-r--r--lib/system_check/incoming_email/foreman_configured_check.rb8
-rw-r--r--lib/system_check/incoming_email/imap_authentication_check.rb8
-rw-r--r--lib/system_check/incoming_email/initd_configured_check.rb10
-rw-r--r--lib/system_check/incoming_email/mail_room_running_check.rb14
-rw-r--r--lib/system_check/incoming_email_check.rb8
-rw-r--r--lib/system_check/ldap_check.rb20
-rw-r--r--lib/system_check/orphans/namespace_check.rb6
-rw-r--r--lib/system_check/orphans/repository_check.rb8
-rw-r--r--lib/system_check/rake_task/app_task.rb4
-rw-r--r--lib/system_check/rake_task/gitaly_task.rb2
-rw-r--r--lib/system_check/rake_task/gitlab_shell_task.rb2
-rw-r--r--lib/system_check/rake_task/gitlab_task.rb4
-rw-r--r--lib/system_check/rake_task/incoming_email_task.rb2
-rw-r--r--lib/system_check/rake_task/ldap_task.rb2
-rw-r--r--lib/system_check/rake_task/orphans/namespace_task.rb2
-rw-r--r--lib/system_check/rake_task/orphans/repository_task.rb2
-rw-r--r--lib/system_check/rake_task/orphans_task.rb4
-rw-r--r--lib/system_check/rake_task/rake_task_helpers.rb2
-rw-r--r--lib/system_check/rake_task/sidekiq_task.rb2
-rw-r--r--lib/system_check/sidekiq_check.rb14
-rw-r--r--lib/system_check/simple_executor.rb16
-rw-r--r--lib/tasks/brakeman.rake8
-rw-r--r--lib/tasks/cache.rake4
-rw-r--r--lib/tasks/ci/cleanup.rake2
-rw-r--r--lib/tasks/config_lint.rake12
-rw-r--r--lib/tasks/dev.rake2
-rw-r--r--lib/tasks/downtime_check.rake12
-rw-r--r--lib/tasks/ee_compat_check.rake4
-rw-r--r--lib/tasks/eslint.rake6
-rw-r--r--lib/tasks/gemojione.rake86
-rw-r--r--lib/tasks/gettext.rake44
-rw-r--r--lib/tasks/gitlab/artifacts/check.rake2
-rw-r--r--lib/tasks/gitlab/artifacts/migrate.rake19
-rw-r--r--lib/tasks/gitlab/assets.rake22
-rw-r--r--lib/tasks/gitlab/backup.rake56
-rw-r--r--lib/tasks/gitlab/check.rake14
-rw-r--r--lib/tasks/gitlab/cleanup.rake33
-rw-r--r--lib/tasks/gitlab/db.rake26
-rw-r--r--lib/tasks/gitlab/dev.rake12
-rw-r--r--lib/tasks/gitlab/exclusive_lease.rake4
-rw-r--r--lib/tasks/gitlab/git.rake3
-rw-r--r--lib/tasks/gitlab/gitaly.rake13
-rw-r--r--lib/tasks/gitlab/helpers.rake2
-rw-r--r--lib/tasks/gitlab/import.rake2
-rw-r--r--lib/tasks/gitlab/import_export.rake10
-rw-r--r--lib/tasks/gitlab/info.rake22
-rw-r--r--lib/tasks/gitlab/ldap.rake24
-rw-r--r--lib/tasks/gitlab/lfs/check.rake2
-rw-r--r--lib/tasks/gitlab/lfs/migrate.rake15
-rw-r--r--lib/tasks/gitlab/list_repos.rake10
-rw-r--r--lib/tasks/gitlab/pages.rake2
-rw-r--r--lib/tasks/gitlab/setup.rake10
-rw-r--r--lib/tasks/gitlab/shell.rake53
-rw-r--r--lib/tasks/gitlab/storage.rake42
-rw-r--r--lib/tasks/gitlab/tcp_check.rake2
-rw-r--r--lib/tasks/gitlab/test.rake10
-rw-r--r--lib/tasks/gitlab/traces.rake19
-rw-r--r--lib/tasks/gitlab/track_deployment.rake4
-rw-r--r--lib/tasks/gitlab/two_factor.rake4
-rw-r--r--lib/tasks/gitlab/update_templates.rake6
-rw-r--r--lib/tasks/gitlab/uploads/check.rake2
-rw-r--r--lib/tasks/gitlab/uploads/migrate.rake34
-rw-r--r--lib/tasks/gitlab/web_hook.rake10
-rw-r--r--lib/tasks/gitlab/workhorse.rake4
-rw-r--r--lib/tasks/grape.rake2
-rw-r--r--lib/tasks/haml-lint.rake6
-rw-r--r--lib/tasks/import.rake26
-rw-r--r--lib/tasks/karma.rake18
-rw-r--r--lib/tasks/lint.rake16
-rw-r--r--lib/tasks/migrate/add_limits_mysql.rake12
-rw-r--r--lib/tasks/migrate/composite_primary_keys.rake8
-rw-r--r--lib/tasks/migrate/migrate_iids.rake60
-rw-r--r--lib/tasks/migrate/setup_postgresql.rake34
-rw-r--r--lib/tasks/plugins.rake4
-rw-r--r--lib/tasks/rubocop.rake2
-rw-r--r--lib/tasks/scss-lint.rake4
-rw-r--r--lib/tasks/services.rake78
-rw-r--r--lib/tasks/sidekiq.rake10
-rw-r--r--lib/tasks/spec.rake44
-rw-r--r--lib/tasks/tokens.rake10
-rw-r--r--lib/tasks/yarn.rake37
-rw-r--r--lib/unfold_form.rb2
-rw-r--r--lib/uploaded_file.rb8
-rw-r--r--lib/version_check.rb4
1060 files changed, 8550 insertions, 8427 deletions
diff --git a/lib/after_commit_queue.rb b/lib/after_commit_queue.rb
index 6fb7985f955..169adfd47ea 100644
--- a/lib/after_commit_queue.rb
+++ b/lib/after_commit_queue.rb
@@ -48,7 +48,7 @@ module AfterCommitQueue
def _run_after_commit_queue
while action = _after_commit_queue.pop
- self.instance_eval(&action)
+ instance_eval(&action)
end
end
diff --git a/lib/api/access_requests.rb b/lib/api/access_requests.rb
index ee8dc822098..b0c12ad7d56 100644
--- a/lib/api/access_requests.rb
+++ b/lib/api/access_requests.rb
@@ -14,7 +14,7 @@ module API
end
resource source_type.pluralize, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
desc "Gets a list of access requests for a #{source_type}." do
- detail 'This feature was introduced in GitLab 8.11.'
+ detail "This feature was introduced in GitLab 8.11."
success Entities::AccessRequester
end
params do
@@ -32,7 +32,7 @@ module API
# rubocop: enable CodeReuse/ActiveRecord
desc "Requests access for the authenticated user to a #{source_type}." do
- detail 'This feature was introduced in GitLab 8.11.'
+ detail "This feature was introduced in GitLab 8.11."
success Entities::AccessRequester
end
post ":id/access_requests" do
@@ -46,16 +46,16 @@ module API
end
end
- desc 'Approves an access request for the given user.' do
- detail 'This feature was introduced in GitLab 8.11.'
+ desc "Approves an access request for the given user." do
+ detail "This feature was introduced in GitLab 8.11."
success Entities::Member
end
params do
- requires :user_id, type: Integer, desc: 'The user ID of the access requester'
- optional :access_level, type: Integer, desc: 'A valid access level (defaults: `30`, developer access level)'
+ requires :user_id, type: Integer, desc: "The user ID of the access requester"
+ optional :access_level, type: Integer, desc: "A valid access level (defaults: `30`, developer access level)"
end
# rubocop: disable CodeReuse/ActiveRecord
- put ':id/access_requests/:user_id/approve' do
+ put ":id/access_requests/:user_id/approve" do
source = find_source(source_type, params[:id])
access_requester = source.requesters.find_by!(user_id: params[:user_id])
@@ -68,11 +68,11 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Denies an access request for the given user.' do
- detail 'This feature was introduced in GitLab 8.11.'
+ desc "Denies an access request for the given user." do
+ detail "This feature was introduced in GitLab 8.11."
end
params do
- requires :user_id, type: Integer, desc: 'The user ID of the access requester'
+ requires :user_id, type: Integer, desc: "The user ID of the access requester"
end
# rubocop: disable CodeReuse/ActiveRecord
delete ":id/access_requests/:user_id" do
diff --git a/lib/api/api.rb b/lib/api/api.rb
index bf8ddba6f0d..3b89a541ca5 100644
--- a/lib/api/api.rb
+++ b/lib/api/api.rb
@@ -7,61 +7,61 @@ module API
LOG_FILENAME = Rails.root.join("log", "api_json.log")
NO_SLASH_URL_PART_REGEX = %r{[^/]+}
- NAMESPACE_OR_PROJECT_REQUIREMENTS = { id: NO_SLASH_URL_PART_REGEX }.freeze
+ NAMESPACE_OR_PROJECT_REQUIREMENTS = {id: NO_SLASH_URL_PART_REGEX}.freeze
COMMIT_ENDPOINT_REQUIREMENTS = NAMESPACE_OR_PROJECT_REQUIREMENTS.merge(sha: NO_SLASH_URL_PART_REGEX).freeze
- USER_REQUIREMENTS = { user_id: NO_SLASH_URL_PART_REGEX }.freeze
+ USER_REQUIREMENTS = {user_id: NO_SLASH_URL_PART_REGEX}.freeze
insert_before Grape::Middleware::Error,
- GrapeLogging::Middleware::RequestLogger,
- logger: Logger.new(LOG_FILENAME),
- formatter: Gitlab::GrapeLogging::Formatters::LogrageWithTimestamp.new,
- include: [
- GrapeLogging::Loggers::FilterParameters.new,
- GrapeLogging::Loggers::ClientEnv.new,
- Gitlab::GrapeLogging::Loggers::RouteLogger.new,
- Gitlab::GrapeLogging::Loggers::UserLogger.new,
- Gitlab::GrapeLogging::Loggers::QueueDurationLogger.new,
- Gitlab::GrapeLogging::Loggers::PerfLogger.new,
- Gitlab::GrapeLogging::Loggers::CorrelationIdLogger.new
- ]
+ GrapeLogging::Middleware::RequestLogger,
+ logger: Logger.new(LOG_FILENAME),
+ formatter: Gitlab::GrapeLogging::Formatters::LogrageWithTimestamp.new,
+ include: [
+ GrapeLogging::Loggers::FilterParameters.new,
+ GrapeLogging::Loggers::ClientEnv.new,
+ Gitlab::GrapeLogging::Loggers::RouteLogger.new,
+ Gitlab::GrapeLogging::Loggers::UserLogger.new,
+ Gitlab::GrapeLogging::Loggers::QueueDurationLogger.new,
+ Gitlab::GrapeLogging::Loggers::PerfLogger.new,
+ Gitlab::GrapeLogging::Loggers::CorrelationIdLogger.new,
+ ]
allow_access_with_scope :api
prefix :api
- version 'v3', using: :path do
- route :any, '*path' do
- error!('API V3 is no longer supported. Use API V4 instead.', 410)
+ version "v3", using: :path do
+ route :any, "*path" do
+ error!("API V3 is no longer supported. Use API V4 instead.", 410)
end
end
- version 'v4', using: :path
+ version "v4", using: :path
before do
- header['X-Frame-Options'] = 'SAMEORIGIN'
- header['X-Content-Type-Options'] = 'nosniff'
+ header["X-Frame-Options"] = "SAMEORIGIN"
+ header["X-Content-Type-Options"] = "nosniff"
end
# The locale is set to the current user's locale when `current_user` is loaded
after { Gitlab::I18n.use_default_locale }
rescue_from Gitlab::Access::AccessDeniedError do
- rack_response({ 'message' => '403 Forbidden' }.to_json, 403)
+ rack_response({"message" => "403 Forbidden"}.to_json, 403)
end
rescue_from ActiveRecord::RecordNotFound do
- rack_response({ 'message' => '404 Not found' }.to_json, 404)
+ rack_response({"message" => "404 Not found"}.to_json, 404)
end
rescue_from ::Gitlab::ExclusiveLeaseHelpers::FailedToObtainLockError do
- rack_response({ 'message' => '409 Conflict: Resource lock' }.to_json, 409)
+ rack_response({"message" => "409 Conflict: Resource lock"}.to_json, 409)
end
rescue_from UploadedFile::InvalidPathError do |e|
- rack_response({ 'message' => e.message }.to_json, 400)
+ rack_response({"message" => e.message}.to_json, 400)
end
rescue_from ObjectStorage::RemoteStoreError do |e|
- rack_response({ 'message' => e.message }.to_json, 500)
+ rack_response({"message" => e.message}.to_json, 500)
end
# Retain 405 error rather than a 500 error for Grape 0.15.0+.
@@ -75,7 +75,7 @@ module API
end
rescue_from Gitlab::Auth::TooManyIps do |e|
- rack_response({ 'message' => '403 Forbidden' }.to_json, 403)
+ rack_response({"message" => "403 Forbidden"}.to_json, 403)
end
rescue_from :all do |exception|
@@ -168,8 +168,8 @@ module API
mount ::API::Version
mount ::API::Wikis
- route :any, '*path' do
- error!('404 Not Found', 404)
+ route :any, "*path" do
+ error!("404 Not Found", 404)
end
end
end
diff --git a/lib/api/api_guard.rb b/lib/api/api_guard.rb
index af9b519ed9e..2deb50e287b 100644
--- a/lib/api/api_guard.rb
+++ b/lib/api/api_guard.rb
@@ -2,7 +2,7 @@
# Guard API with OAuth 2.0 Access Token
-require 'rack/oauth2'
+require "rack/oauth2"
module API
module APIGuard
@@ -10,7 +10,7 @@ module API
included do |base|
# OAuth2 Resource Server Authentication
- use Rack::OAuth2::Server::Resource::Bearer, 'The API' do |request|
+ use Rack::OAuth2::Server::Resource::Bearer, "The API" do |request|
# The authenticator only fetches the raw token string
# Must yield access token to store it in the env
@@ -95,7 +95,7 @@ module API
Gitlab::Auth::ExpiredError,
Gitlab::Auth::RevokedError,
Gitlab::Auth::ImpersonationDisabled,
- Gitlab::Auth::InsufficientScopeError]
+ Gitlab::Auth::InsufficientScopeError,]
base.__send__(:rescue_from, *error_classes, oauth2_bearer_token_error_handler) # rubocop:disable GitlabSecurity/PublicSend
end
@@ -110,22 +110,26 @@ module API
when Gitlab::Auth::TokenNotFoundError
Rack::OAuth2::Server::Resource::Bearer::Unauthorized.new(
:invalid_token,
- "Bad Access Token.")
+ "Bad Access Token."
+ )
when Gitlab::Auth::ExpiredError
Rack::OAuth2::Server::Resource::Bearer::Unauthorized.new(
:invalid_token,
- "Token is expired. You can either do re-authorization or token refresh.")
+ "Token is expired. You can either do re-authorization or token refresh."
+ )
when Gitlab::Auth::RevokedError
Rack::OAuth2::Server::Resource::Bearer::Unauthorized.new(
:invalid_token,
- "Token was revoked. You have to re-authorize from the user.")
+ "Token was revoked. You have to re-authorize from the user."
+ )
when Gitlab::Auth::ImpersonationDisabled
Rack::OAuth2::Server::Resource::Bearer::Unauthorized.new(
:invalid_token,
- "Token is an impersonation token but impersonation was disabled.")
+ "Token is an impersonation token but impersonation was disabled."
+ )
when Gitlab::Auth::InsufficientScopeError
# FIXME: ForbiddenError (inherited from Bearer::Forbidden of Rack::Oauth2)
@@ -133,7 +137,8 @@ module API
Rack::OAuth2::Server::Resource::Bearer::Forbidden.new(
:insufficient_scope,
Rack::OAuth2::Server::Resource::ErrorMethods::DEFAULT_DESCRIPTION[:insufficient_scope],
- { scope: e.scopes })
+ {scope: e.scopes}
+ )
end
response.finish
diff --git a/lib/api/applications.rb b/lib/api/applications.rb
index 92717e04543..7d150196a6c 100644
--- a/lib/api/applications.rb
+++ b/lib/api/applications.rb
@@ -6,14 +6,14 @@ module API
before { authenticated_as_admin! }
resource :applications do
- desc 'Create a new application' do
- detail 'This feature was introduced in GitLab 10.5'
+ desc "Create a new application" do
+ detail "This feature was introduced in GitLab 10.5"
success Entities::ApplicationWithSecret
end
params do
- requires :name, type: String, desc: 'Application name'
- requires :redirect_uri, type: String, desc: 'Application redirect URI'
- requires :scopes, type: String, desc: 'Application scopes'
+ requires :name, type: String, desc: "Application name"
+ requires :redirect_uri, type: String, desc: "Application redirect URI"
+ requires :scopes, type: String, desc: "Application scopes"
end
post do
application = Doorkeeper::Application.new(declared_params)
@@ -25,7 +25,7 @@ module API
end
end
- desc 'Get applications' do
+ desc "Get applications" do
success Entities::Application
end
get do
@@ -33,8 +33,8 @@ module API
present applications, with: Entities::Application
end
- desc 'Delete an application'
- delete ':id' do
+ desc "Delete an application"
+ delete ":id" do
application = ApplicationsFinder.new(params).execute
application.destroy
diff --git a/lib/api/avatar.rb b/lib/api/avatar.rb
index 0f14d003065..d05481c7a4f 100644
--- a/lib/api/avatar.rb
+++ b/lib/api/avatar.rb
@@ -3,15 +3,15 @@
module API
class Avatar < Grape::API
resource :avatar do
- desc 'Return avatar url for a user' do
+ desc "Return avatar url for a user" do
success Entities::Avatar
end
params do
- requires :email, type: String, desc: 'Public email address of the user'
- optional :size, type: Integer, desc: 'Single pixel dimension for Gravatar images'
+ requires :email, type: String, desc: "Public email address of the user"
+ optional :size, type: Integer, desc: "Single pixel dimension for Gravatar images"
end
get do
- forbidden!('Unauthorized access') unless can?(current_user, :read_users_list)
+ forbidden!("Unauthorized access") unless can?(current_user, :read_users_list)
user = User.find_by_public_email(params[:email])
user ||= User.new(email: params[:email])
diff --git a/lib/api/award_emoji.rb b/lib/api/award_emoji.rb
index a1851ba3627..a47948b1a29 100644
--- a/lib/api/award_emoji.rb
+++ b/lib/api/award_emoji.rb
@@ -6,13 +6,13 @@ module API
before { authenticate! }
AWARDABLES = [
- { type: 'issue', find_by: :iid },
- { type: 'merge_request', find_by: :iid },
- { type: 'snippet', find_by: :id }
+ {type: "issue", find_by: :iid},
+ {type: "merge_request", find_by: :iid},
+ {type: "snippet", find_by: :id},
].freeze
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
AWARDABLES.each do |awardable_params|
@@ -25,11 +25,11 @@ module API
[
":id/#{awardable_string}/:#{awardable_id_string}/award_emoji",
- ":id/#{awardable_string}/:#{awardable_id_string}/notes/:note_id/award_emoji"
+ ":id/#{awardable_string}/:#{awardable_id_string}/notes/:note_id/award_emoji",
].each do |endpoint|
- desc 'Get a list of project +awardable+ award emoji' do
- detail 'This feature was introduced in 8.9'
+ desc "Get a list of project +awardable+ award emoji" do
+ detail "This feature was introduced in 8.9"
success Entities::AwardEmoji
end
params do
@@ -44,12 +44,12 @@ module API
end
end
- desc 'Get a specific award emoji' do
- detail 'This feature was introduced in 8.9'
+ desc "Get a specific award emoji" do
+ detail "This feature was introduced in 8.9"
success Entities::AwardEmoji
end
params do
- requires :award_id, type: Integer, desc: 'The ID of the award'
+ requires :award_id, type: Integer, desc: "The ID of the award"
end
get "#{endpoint}/:award_id" do
if can_read_awardable?
@@ -59,15 +59,15 @@ module API
end
end
- desc 'Award a new Emoji' do
- detail 'This feature was introduced in 8.9'
+ desc "Award a new Emoji" do
+ detail "This feature was introduced in 8.9"
success Entities::AwardEmoji
end
params do
- requires :name, type: String, desc: 'The name of a award_emoji (without colons)'
+ requires :name, type: String, desc: "The name of a award_emoji (without colons)"
end
post endpoint do
- not_found!('Award Emoji') unless can_read_awardable? && can_award_awardable?
+ not_found!("Award Emoji") unless can_read_awardable? && can_award_awardable?
award = awardable.create_award_emoji(params[:name], current_user)
@@ -78,12 +78,12 @@ module API
end
end
- desc 'Delete a +awardables+ award emoji' do
- detail 'This feature was introduced in 8.9'
+ desc "Delete a +awardables+ award emoji" do
+ detail "This feature was introduced in 8.9"
success Entities::AwardEmoji
end
params do
- requires :award_id, type: Integer, desc: 'The ID of an award emoji'
+ requires :award_id, type: Integer, desc: "The ID of an award emoji"
end
delete "#{endpoint}/:award_id" do
award = awardable.award_emoji.find(params[:award_id])
diff --git a/lib/api/badges.rb b/lib/api/badges.rb
index ba554e00a16..b512e2fa1da 100644
--- a/lib/api/badges.rb
+++ b/lib/api/badges.rb
@@ -24,7 +24,7 @@ module API
end
resource source_type.pluralize, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
desc "Gets a list of #{source_type} badges viewable by the authenticated user." do
- detail 'This feature was introduced in GitLab 10.6.'
+ detail "This feature was introduced in GitLab 10.6."
success Entities::Badge
end
params do
@@ -37,12 +37,12 @@ module API
end
desc "Preview a badge from a #{source_type}." do
- detail 'This feature was introduced in GitLab 10.6.'
+ detail "This feature was introduced in GitLab 10.6."
success Entities::BasicBadgeDetails
end
params do
- requires :link_url, type: String, desc: 'URL of the badge link'
- requires :image_url, type: String, desc: 'URL of the badge image'
+ requires :link_url, type: String, desc: "URL of the badge link"
+ requires :image_url, type: String, desc: "URL of the badge image"
end
get ":id/badges/render" do
authenticate!
@@ -50,7 +50,7 @@ module API
source = find_source_if_admin(source_type)
badge = ::Badges::BuildService.new(declared_params(include_missing: false))
- .execute(source)
+ .execute(source)
if badge.valid?
present_badges(source, badge, with: Entities::BasicBadgeDetails)
@@ -60,11 +60,11 @@ module API
end
desc "Gets a badge of a #{source_type}." do
- detail 'This feature was introduced in GitLab 10.6.'
+ detail "This feature was introduced in GitLab 10.6."
success Entities::Badge
end
params do
- requires :badge_id, type: Integer, desc: 'The badge ID'
+ requires :badge_id, type: Integer, desc: "The badge ID"
end
get ":id/badges/:badge_id" do
source = find_source(source_type, params[:id])
@@ -74,12 +74,12 @@ module API
end
desc "Adds a badge to a #{source_type}." do
- detail 'This feature was introduced in GitLab 10.6.'
+ detail "This feature was introduced in GitLab 10.6."
success Entities::Badge
end
params do
- requires :link_url, type: String, desc: 'URL of the badge link'
- requires :image_url, type: String, desc: 'URL of the badge image'
+ requires :link_url, type: String, desc: "URL of the badge link"
+ requires :image_url, type: String, desc: "URL of the badge image"
end
post ":id/badges" do
source = find_source_if_admin(source_type)
@@ -94,18 +94,18 @@ module API
end
desc "Updates a badge of a #{source_type}." do
- detail 'This feature was introduced in GitLab 10.6.'
+ detail "This feature was introduced in GitLab 10.6."
success Entities::Badge
end
params do
- optional :link_url, type: String, desc: 'URL of the badge link'
- optional :image_url, type: String, desc: 'URL of the badge image'
+ optional :link_url, type: String, desc: "URL of the badge link"
+ optional :image_url, type: String, desc: "URL of the badge image"
end
put ":id/badges/:badge_id" do
source = find_source_if_admin(source_type)
badge = ::Badges::UpdateService.new(declared_params(include_missing: false))
- .execute(find_badge(source))
+ .execute(find_badge(source))
if badge.valid?
present_badges(source, badge)
@@ -114,18 +114,18 @@ module API
end
end
- desc 'Removes a badge from a project or group.' do
- detail 'This feature was introduced in GitLab 10.6.'
+ desc "Removes a badge from a project or group." do
+ detail "This feature was introduced in GitLab 10.6."
end
params do
- requires :badge_id, type: Integer, desc: 'The badge ID'
+ requires :badge_id, type: Integer, desc: "The badge ID"
end
delete ":id/badges/:badge_id" do
source = find_source_if_admin(source_type)
badge = find_badge(source)
if badge.is_a?(GroupBadge) && source.is_a?(Project)
- error!('To delete a Group badge please use the Group endpoint', 403)
+ error!("To delete a Group badge please use the Group endpoint", 403)
end
destroy_conditionally!(badge)
diff --git a/lib/api/boards.rb b/lib/api/boards.rb
index b7c77730afb..ee7c2123e13 100644
--- a/lib/api/boards.rb
+++ b/lib/api/boards.rb
@@ -14,68 +14,68 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- segment ':id/boards' do
- desc 'Get all project boards' do
- detail 'This feature was introduced in 8.13'
+ segment ":id/boards" do
+ desc "Get all project boards" do
+ detail "This feature was introduced in 8.13"
success Entities::Board
end
params do
use :pagination
end
- get '/' do
+ get "/" do
authorize!(:read_board, user_project)
present paginate(board_parent.boards), with: Entities::Board
end
- desc 'Find a project board' do
- detail 'This feature was introduced in 10.4'
+ desc "Find a project board" do
+ detail "This feature was introduced in 10.4"
success Entities::Board
end
- get '/:board_id' do
+ get "/:board_id" do
authorize!(:read_board, user_project)
present board, with: Entities::Board
end
end
params do
- requires :board_id, type: Integer, desc: 'The ID of a board'
+ requires :board_id, type: Integer, desc: "The ID of a board"
end
- segment ':id/boards/:board_id' do
- desc 'Get the lists of a project board' do
- detail 'Does not include `done` list. This feature was introduced in 8.13'
+ segment ":id/boards/:board_id" do
+ desc "Get the lists of a project board" do
+ detail "Does not include `done` list. This feature was introduced in 8.13"
success Entities::List
end
params do
use :pagination
end
- get '/lists' do
+ get "/lists" do
authorize!(:read_board, user_project)
present paginate(board_lists), with: Entities::List
end
- desc 'Get a list of a project board' do
- detail 'This feature was introduced in 8.13'
+ desc "Get a list of a project board" do
+ detail "This feature was introduced in 8.13"
success Entities::List
end
params do
- requires :list_id, type: Integer, desc: 'The ID of a list'
+ requires :list_id, type: Integer, desc: "The ID of a list"
end
- get '/lists/:list_id' do
+ get "/lists/:list_id" do
authorize!(:read_board, user_project)
present board_lists.find(params[:list_id]), with: Entities::List
end
- desc 'Create a new board list' do
- detail 'This feature was introduced in 8.13'
+ desc "Create a new board list" do
+ detail "This feature was introduced in 8.13"
success Entities::List
end
params do
use :list_creation_params
end
- post '/lists' do
+ post "/lists" do
authorize_list_type_resource!
authorize!(:admin_list, user_project)
@@ -83,15 +83,15 @@ module API
create_list
end
- desc 'Moves a board list to a new position' do
- detail 'This feature was introduced in 8.13'
+ desc "Moves a board list to a new position" do
+ detail "This feature was introduced in 8.13"
success Entities::List
end
params do
- requires :list_id, type: Integer, desc: 'The ID of a list'
- requires :position, type: Integer, desc: 'The position of the list'
+ requires :list_id, type: Integer, desc: "The ID of a list"
+ requires :position, type: Integer, desc: "The position of the list"
end
- put '/lists/:list_id' do
+ put "/lists/:list_id" do
list = board_lists.find(params[:list_id])
authorize!(:admin_list, user_project)
@@ -99,12 +99,12 @@ module API
move_list(list)
end
- desc 'Delete a board list' do
- detail 'This feature was introduced in 8.13'
+ desc "Delete a board list" do
+ detail "This feature was introduced in 8.13"
success Entities::List
end
params do
- requires :list_id, type: Integer, desc: 'The ID of a board list'
+ requires :list_id, type: Integer, desc: "The ID of a board list"
end
delete "/lists/:list_id" do
authorize!(:admin_list, user_project)
diff --git a/lib/api/boards_responses.rb b/lib/api/boards_responses.rb
index 86d9b24802f..0c0643ad9e1 100644
--- a/lib/api/boards_responses.rb
+++ b/lib/api/boards_responses.rb
@@ -33,12 +33,12 @@ module API
def move_list(list)
move_list_service =
- ::Boards::Lists::MoveService.new(board_parent, current_user, { position: params[:position].to_i })
+ ::Boards::Lists::MoveService.new(board_parent, current_user, {position: params[:position].to_i})
if move_list_service.execute(list)
present list, with: Entities::List
else
- render_api_error!({ error: "List could not be moved!" }, 400)
+ render_api_error!({error: "List could not be moved!"}, 400)
end
end
@@ -46,7 +46,7 @@ module API
destroy_conditionally!(list) do |list|
service = ::Boards::Lists::DestroyService.new(board_parent, current_user)
unless service.execute(list)
- render_api_error!({ error: 'List could not be deleted!' }, 400)
+ render_api_error!({error: "List could not be deleted!"}, 400)
end
end
end
@@ -54,13 +54,13 @@ module API
# rubocop: disable CodeReuse/ActiveRecord
def authorize_list_type_resource!
unless available_labels_for(board_parent).exists?(params[:label_id])
- render_api_error!({ error: 'Label not found!' }, 400)
+ render_api_error!({error: "Label not found!"}, 400)
end
end
# rubocop: enable CodeReuse/ActiveRecord
params :list_creation_params do
- requires :label_id, type: Integer, desc: 'The ID of an existing label'
+ requires :label_id, type: Integer, desc: "The ID of an existing label"
end
end
end
diff --git a/lib/api/branches.rb b/lib/api/branches.rb
index 07f529b01bb..f0be2a78ab6 100644
--- a/lib/api/branches.rb
+++ b/lib/api/branches.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'mime/types'
+require "mime/types"
module API
class Branches < Grape::API
@@ -12,24 +12,24 @@ module API
helpers do
params :filter_params do
- optional :search, type: String, desc: 'Return list of branches matching the search criteria'
- optional :sort, type: String, desc: 'Return list of branches sorted by the given field'
+ optional :search, type: String, desc: "Return list of branches matching the search criteria"
+ optional :sort, type: String, desc: "Return list of branches sorted by the given field"
end
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get a project repository branches' do
+ desc "Get a project repository branches" do
success Entities::Branch
end
params do
use :pagination
use :filter_params
end
- get ':id/repository/branches' do
- Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42329')
+ get ":id/repository/branches" do
+ Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42329")
repository = user_project.repository
@@ -46,12 +46,12 @@ module API
)
end
- resource ':id/repository/branches/:branch', requirements: BRANCH_ENDPOINT_REQUIREMENTS do
- desc 'Get a single branch' do
+ resource ":id/repository/branches/:branch", requirements: BRANCH_ENDPOINT_REQUIREMENTS do
+ desc "Get a single branch" do
success Entities::Branch
end
params do
- requires :branch, type: String, desc: 'The name of the branch'
+ requires :branch, type: String, desc: "The name of the branch"
end
head do
user_project.repository.branch_exists?(params[:branch]) ? status(204) : status(404)
@@ -67,16 +67,16 @@ module API
# Note: The internal data model moved from `developers_can_{merge,push}` to `allowed_to_{merge,push}`
# in `gitlab-org/gitlab-ce!5081`. The API interface has not been changed (to maintain compatibility),
# but it works with the changed data model to infer `developers_can_merge` and `developers_can_push`.
- desc 'Protect a single branch' do
+ desc "Protect a single branch" do
success Entities::Branch
end
params do
- requires :branch, type: String, desc: 'The name of the branch', allow_blank: false
- optional :developers_can_push, type: Boolean, desc: 'Flag if developers can push to that branch'
- optional :developers_can_merge, type: Boolean, desc: 'Flag if developers can merge to that branch'
+ requires :branch, type: String, desc: "The name of the branch", allow_blank: false
+ optional :developers_can_push, type: Boolean, desc: "Flag if developers can push to that branch"
+ optional :developers_can_merge, type: Boolean, desc: "Flag if developers can merge to that branch"
end
# rubocop: disable CodeReuse/ActiveRecord
- put ':id/repository/branches/:branch/protect', requirements: BRANCH_ENDPOINT_REQUIREMENTS do
+ put ":id/repository/branches/:branch/protect", requirements: BRANCH_ENDPOINT_REQUIREMENTS do
authorize_admin_project
branch = find_branch!(params[:branch])
@@ -86,16 +86,16 @@ module API
protected_branch_params = {
name: branch.name,
developers_can_push: params[:developers_can_push],
- developers_can_merge: params[:developers_can_merge]
+ developers_can_merge: params[:developers_can_merge],
}
service_args = [user_project, current_user, protected_branch_params]
protected_branch = if protected_branch
- ::ProtectedBranches::LegacyApiUpdateService.new(*service_args).execute(protected_branch)
- else
- ::ProtectedBranches::LegacyApiCreateService.new(*service_args).execute
- end
+ ::ProtectedBranches::LegacyApiUpdateService.new(*service_args).execute(protected_branch)
+ else
+ ::ProtectedBranches::LegacyApiCreateService.new(*service_args).execute
+ end
if protected_branch.valid?
present branch, with: Entities::Branch, current_user: current_user, project: user_project
@@ -106,14 +106,14 @@ module API
# rubocop: enable CodeReuse/ActiveRecord
# Note: This API will be deprecated in favor of the protected branches API.
- desc 'Unprotect a single branch' do
+ desc "Unprotect a single branch" do
success Entities::Branch
end
params do
- requires :branch, type: String, desc: 'The name of the branch', allow_blank: false
+ requires :branch, type: String, desc: "The name of the branch", allow_blank: false
end
# rubocop: disable CodeReuse/ActiveRecord
- put ':id/repository/branches/:branch/unprotect', requirements: BRANCH_ENDPOINT_REQUIREMENTS do
+ put ":id/repository/branches/:branch/unprotect", requirements: BRANCH_ENDPOINT_REQUIREMENTS do
authorize_admin_project
branch = find_branch!(params[:branch])
@@ -124,34 +124,34 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Create branch' do
+ desc "Create branch" do
success Entities::Branch
end
params do
- requires :branch, type: String, desc: 'The name of the branch', allow_blank: false
- requires :ref, type: String, desc: 'Create branch from commit sha or existing branch', allow_blank: false
+ requires :branch, type: String, desc: "The name of the branch", allow_blank: false
+ requires :ref, type: String, desc: "Create branch from commit sha or existing branch", allow_blank: false
end
- post ':id/repository/branches' do
+ post ":id/repository/branches" do
authorize_push_project
result = CreateBranchService.new(user_project, current_user)
- .execute(params[:branch], params[:ref])
+ .execute(params[:branch], params[:ref])
if result[:status] == :success
present result[:branch],
- with: Entities::Branch,
- current_user: current_user,
- project: user_project
+ with: Entities::Branch,
+ current_user: current_user,
+ project: user_project
else
render_api_error!(result[:message], 400)
end
end
- desc 'Delete a branch'
+ desc "Delete a branch"
params do
- requires :branch, type: String, desc: 'The name of the branch', allow_blank: false
+ requires :branch, type: String, desc: "The name of the branch", allow_blank: false
end
- delete ':id/repository/branches/:branch', requirements: BRANCH_ENDPOINT_REQUIREMENTS do
+ delete ":id/repository/branches/:branch", requirements: BRANCH_ENDPOINT_REQUIREMENTS do
authorize_push_project
branch = find_branch!(params[:branch])
@@ -160,7 +160,7 @@ module API
destroy_conditionally!(commit, last_updated: commit.authored_date) do
result = DeleteBranchService.new(user_project, current_user)
- .execute(params[:branch])
+ .execute(params[:branch])
if result[:status] != :success
render_api_error!(result[:message], result[:return_code])
@@ -168,8 +168,8 @@ module API
end
end
- desc 'Delete all merged branches'
- delete ':id/repository/merged_branches' do
+ desc "Delete all merged branches"
+ delete ":id/repository/merged_branches" do
DeleteMergedBranchesService.new(user_project, current_user).async_execute
accepted!
diff --git a/lib/api/broadcast_messages.rb b/lib/api/broadcast_messages.rb
index 19148758fc5..2855e2e5fac 100644
--- a/lib/api/broadcast_messages.rb
+++ b/lib/api/broadcast_messages.rb
@@ -14,8 +14,8 @@ module API
end
end
- desc 'Get all broadcast messages' do
- detail 'This feature was introduced in GitLab 8.12.'
+ desc "Get all broadcast messages" do
+ detail "This feature was introduced in GitLab 8.12."
success Entities::BroadcastMessage
end
params do
@@ -27,16 +27,16 @@ module API
present paginate(messages), with: Entities::BroadcastMessage
end
- desc 'Create a broadcast message' do
- detail 'This feature was introduced in GitLab 8.12.'
+ desc "Create a broadcast message" do
+ detail "This feature was introduced in GitLab 8.12."
success Entities::BroadcastMessage
end
params do
- requires :message, type: String, desc: 'Message to display'
- optional :starts_at, type: DateTime, desc: 'Starting time', default: -> { Time.zone.now }
- optional :ends_at, type: DateTime, desc: 'Ending time', default: -> { 1.hour.from_now }
- optional :color, type: String, desc: 'Background color'
- optional :font, type: String, desc: 'Foreground color'
+ requires :message, type: String, desc: "Message to display"
+ optional :starts_at, type: DateTime, desc: "Starting time", default: -> { Time.zone.now }
+ optional :ends_at, type: DateTime, desc: "Ending time", default: -> { 1.hour.from_now }
+ optional :color, type: String, desc: "Background color"
+ optional :font, type: String, desc: "Foreground color"
end
post do
message = BroadcastMessage.create(declared_params(include_missing: false))
@@ -48,32 +48,32 @@ module API
end
end
- desc 'Get a specific broadcast message' do
- detail 'This feature was introduced in GitLab 8.12.'
+ desc "Get a specific broadcast message" do
+ detail "This feature was introduced in GitLab 8.12."
success Entities::BroadcastMessage
end
params do
- requires :id, type: Integer, desc: 'Broadcast message ID'
+ requires :id, type: Integer, desc: "Broadcast message ID"
end
- get ':id' do
+ get ":id" do
message = find_message
present message, with: Entities::BroadcastMessage
end
- desc 'Update a broadcast message' do
- detail 'This feature was introduced in GitLab 8.12.'
+ desc "Update a broadcast message" do
+ detail "This feature was introduced in GitLab 8.12."
success Entities::BroadcastMessage
end
params do
- requires :id, type: Integer, desc: 'Broadcast message ID'
- optional :message, type: String, desc: 'Message to display'
- optional :starts_at, type: DateTime, desc: 'Starting time'
- optional :ends_at, type: DateTime, desc: 'Ending time'
- optional :color, type: String, desc: 'Background color'
- optional :font, type: String, desc: 'Foreground color'
- end
- put ':id' do
+ requires :id, type: Integer, desc: "Broadcast message ID"
+ optional :message, type: String, desc: "Message to display"
+ optional :starts_at, type: DateTime, desc: "Starting time"
+ optional :ends_at, type: DateTime, desc: "Ending time"
+ optional :color, type: String, desc: "Background color"
+ optional :font, type: String, desc: "Foreground color"
+ end
+ put ":id" do
message = find_message
if message.update(declared_params(include_missing: false))
@@ -83,14 +83,14 @@ module API
end
end
- desc 'Delete a broadcast message' do
- detail 'This feature was introduced in GitLab 8.12.'
+ desc "Delete a broadcast message" do
+ detail "This feature was introduced in GitLab 8.12."
success Entities::BroadcastMessage
end
params do
- requires :id, type: Integer, desc: 'Broadcast message ID'
+ requires :id, type: Integer, desc: "Broadcast message ID"
end
- delete ':id' do
+ delete ":id" do
message = find_message
destroy_conditionally!(message)
diff --git a/lib/api/circuit_breakers.rb b/lib/api/circuit_breakers.rb
index da756daadcc..202fe410918 100644
--- a/lib/api/circuit_breakers.rb
+++ b/lib/api/circuit_breakers.rb
@@ -7,28 +7,28 @@ module API
resource :circuit_breakers do
params do
requires :type,
- type: String,
- desc: "The type of circuitbreaker",
- values: ['repository_storage']
+ type: String,
+ desc: "The type of circuitbreaker",
+ values: ["repository_storage"]
end
- resource ':type' do
- namespace '', requirements: { type: 'repository_storage' } do
- desc 'Get all git storages' do
- detail 'This feature was introduced in GitLab 9.5'
+ resource ":type" do
+ namespace "", requirements: {type: "repository_storage"} do
+ desc "Get all git storages" do
+ detail "This feature was introduced in GitLab 9.5"
end
get do
present []
end
- desc 'Get all failing git storages' do
- detail 'This feature was introduced in GitLab 9.5'
+ desc "Get all failing git storages" do
+ detail "This feature was introduced in GitLab 9.5"
end
- get 'failing' do
+ get "failing" do
present []
end
- desc 'Reset all storage failures and open circuitbreaker' do
- detail 'This feature was introduced in GitLab 9.5'
+ desc "Reset all storage failures and open circuitbreaker" do
+ detail "This feature was introduced in GitLab 9.5"
end
delete do
end
diff --git a/lib/api/commit_statuses.rb b/lib/api/commit_statuses.rb
index 08b4f8db8b0..205c8e0ff6a 100644
--- a/lib/api/commit_statuses.rb
+++ b/lib/api/commit_statuses.rb
@@ -1,11 +1,11 @@
# frozen_string_literal: true
-require 'mime/types'
+require "mime/types"
module API
class CommitStatuses < Grape::API
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
include PaginationParams
@@ -16,18 +16,18 @@ module API
success Entities::CommitStatus
end
params do
- requires :sha, type: String, desc: 'The commit hash'
- optional :ref, type: String, desc: 'The ref'
- optional :stage, type: String, desc: 'The stage'
- optional :name, type: String, desc: 'The name'
- optional :all, type: String, desc: 'Show all statuses, default: false'
+ requires :sha, type: String, desc: "The commit hash"
+ optional :ref, type: String, desc: "The ref"
+ optional :stage, type: String, desc: "The stage"
+ optional :name, type: String, desc: "The name"
+ optional :all, type: String, desc: "Show all statuses, default: false"
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/repository/commits/:sha/statuses' do
+ get ":id/repository/commits/:sha/statuses" do
authorize!(:read_commit_status, user_project)
- not_found!('Commit') unless user_project.commit(params[:sha])
+ not_found!("Commit") unless user_project.commit(params[:sha])
pipelines = user_project.ci_pipelines.where(sha: params[:sha])
statuses = ::CommitStatus.where(pipeline: pipelines)
@@ -39,26 +39,26 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Post status to a commit' do
+ desc "Post status to a commit" do
success Entities::CommitStatus
end
params do
- requires :sha, type: String, desc: 'The commit hash'
- requires :state, type: String, desc: 'The state of the status',
- values: %w(pending running success failed canceled)
- optional :ref, type: String, desc: 'The ref'
- optional :target_url, type: String, desc: 'The target URL to associate with this status'
- optional :description, type: String, desc: 'A short description of the status'
+ requires :sha, type: String, desc: "The commit hash"
+ requires :state, type: String, desc: "The state of the status",
+ values: %w[pending running success failed canceled]
+ optional :ref, type: String, desc: "The ref"
+ optional :target_url, type: String, desc: "The target URL to associate with this status"
+ optional :description, type: String, desc: "A short description of the status"
optional :name, type: String, desc: 'A string label to differentiate this status from the status of other systems. Default: "default"'
optional :context, type: String, desc: 'A string label to differentiate this status from the status of other systems. Default: "default"'
- optional :coverage, type: Float, desc: 'The total code coverage'
+ optional :coverage, type: Float, desc: "The total code coverage"
end
# rubocop: disable CodeReuse/ActiveRecord
- post ':id/statuses/:sha' do
+ post ":id/statuses/:sha" do
authorize! :create_commit_status, user_project
commit = @project.commit(params[:sha])
- not_found! 'Commit' unless commit
+ not_found! "Commit" unless commit
# Since the CommitStatus is attached to Ci::Pipeline (in the future Pipeline)
# We need to always have the pipeline object
@@ -69,19 +69,18 @@ module API
ref = params[:ref]
ref ||= @project.repository.branch_names_contains(commit.sha).first
- not_found! 'References for commit' unless ref
+ not_found! "References for commit" unless ref
- name = params[:name] || params[:context] || 'default'
+ name = params[:name] || params[:context] || "default"
pipeline = @project.pipeline_for(ref, commit.sha)
- unless pipeline
- pipeline = @project.ci_pipelines.create!(
- source: :external,
- sha: commit.sha,
- ref: ref,
- user: current_user,
- protected: @project.protected_for?(ref))
- end
+ pipeline ||= @project.ci_pipelines.create!(
+ source: :external,
+ sha: commit.sha,
+ ref: ref,
+ user: current_user,
+ protected: @project.protected_for?(ref)
+ )
status = GenericCommitStatus.running_or_pending.find_or_initialize_by(
project: @project,
@@ -100,23 +99,25 @@ module API
begin
case params[:state]
- when 'pending'
+ when "pending"
status.enqueue!
- when 'running'
+ when "running"
status.enqueue
status.run!
- when 'success'
+ when "success"
status.success!
- when 'failed'
+ when "failed"
status.drop!(:api_failure)
- when 'canceled'
+ when "canceled"
status.cancel!
else
- render_api_error!('invalid state', 400)
+ render_api_error!("invalid state", 400)
end
- MergeRequest.where(source_project: @project, source_branch: ref)
- .update_all(head_pipeline_id: pipeline.id) if pipeline.latest?
+ if pipeline.latest?
+ MergeRequest.where(source_project: @project, source_branch: ref)
+ .update_all(head_pipeline_id: pipeline.id)
+ end
present status, with: Entities::CommitStatus
rescue StateMachines::InvalidTransition => e
diff --git a/lib/api/commits.rb b/lib/api/commits.rb
index 8defc59224d..a38d476b122 100644
--- a/lib/api/commits.rb
+++ b/lib/api/commits.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'mime/types'
+require "mime/types"
module API
class Commits < Grape::API
@@ -21,37 +21,37 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get a project repository commits' do
+ desc "Get a project repository commits" do
success Entities::Commit
end
params do
- optional :ref_name, type: String, desc: 'The name of a repository branch or tag, if not given the default branch is used'
- optional :since, type: DateTime, desc: 'Only commits after or on this date will be returned'
- optional :until, type: DateTime, desc: 'Only commits before or on this date will be returned'
- optional :path, type: String, desc: 'The file path'
- optional :all, type: Boolean, desc: 'Every commit will be returned'
- optional :with_stats, type: Boolean, desc: 'Stats about each commit will be added to the response'
+ optional :ref_name, type: String, desc: "The name of a repository branch or tag, if not given the default branch is used"
+ optional :since, type: DateTime, desc: "Only commits after or on this date will be returned"
+ optional :until, type: DateTime, desc: "Only commits before or on this date will be returned"
+ optional :path, type: String, desc: "The file path"
+ optional :all, type: Boolean, desc: "Every commit will be returned"
+ optional :with_stats, type: Boolean, desc: "Stats about each commit will be added to the response"
use :pagination
end
- get ':id/repository/commits' do
+ get ":id/repository/commits" do
path = params[:path]
before = params[:until]
after = params[:since]
- ref = params[:ref_name] || user_project.try(:default_branch) || 'master' unless params[:all]
+ ref = params[:ref_name] || user_project.try(:default_branch) || "master" unless params[:all]
offset = (params[:page] - 1) * params[:per_page]
all = params[:all]
with_stats = params[:with_stats]
commits = user_project.repository.commits(ref,
- path: path,
- limit: params[:per_page],
- offset: offset,
- before: before,
- after: after,
- all: all)
+ path: path,
+ limit: params[:per_page],
+ offset: offset,
+ before: before,
+ after: after,
+ all: all)
commit_count =
if all || path || before || after
@@ -68,39 +68,39 @@ module API
present paginate(paginated_commits), with: serializer
end
- desc 'Commit multiple file changes as one commit' do
+ desc "Commit multiple file changes as one commit" do
success Entities::CommitDetail
- detail 'This feature was introduced in GitLab 8.13'
+ detail "This feature was introduced in GitLab 8.13"
end
params do
- requires :branch, type: String, desc: 'Name of the branch to commit into. To create a new branch, also provide `start_branch`.', allow_blank: false
- requires :commit_message, type: String, desc: 'Commit message'
- requires :actions, type: Array, desc: 'Actions to perform in commit' do
- requires :action, type: String, desc: 'The action to perform, `create`, `delete`, `move`, `update`, `chmod`', values: %w[create update move delete chmod].freeze
- requires :file_path, type: String, desc: 'Full path to the file. Ex. `lib/class.rb`'
- given action: ->(action) { action == 'move' } do
- requires :previous_path, type: String, desc: 'Original full path to the file being moved. Ex. `lib/class1.rb`'
+ requires :branch, type: String, desc: "Name of the branch to commit into. To create a new branch, also provide `start_branch`.", allow_blank: false
+ requires :commit_message, type: String, desc: "Commit message"
+ requires :actions, type: Array, desc: "Actions to perform in commit" do
+ requires :action, type: String, desc: "The action to perform, `create`, `delete`, `move`, `update`, `chmod`", values: %w[create update move delete chmod].freeze
+ requires :file_path, type: String, desc: "Full path to the file. Ex. `lib/class.rb`"
+ given action: ->(action) { action == "move" } do
+ requires :previous_path, type: String, desc: "Original full path to the file being moved. Ex. `lib/class1.rb`"
end
given action: ->(action) { %w[create move].include? action } do
- optional :content, type: String, desc: 'File content'
+ optional :content, type: String, desc: "File content"
end
- given action: ->(action) { action == 'update' } do
- requires :content, type: String, desc: 'File content'
+ given action: ->(action) { action == "update" } do
+ requires :content, type: String, desc: "File content"
end
- optional :encoding, type: String, desc: '`text` or `base64`', default: 'text', values: %w[text base64]
+ optional :encoding, type: String, desc: "`text` or `base64`", default: "text", values: %w[text base64]
given action: ->(action) { %w[update move delete].include? action } do
- optional :last_commit_id, type: String, desc: 'Last known file commit id'
+ optional :last_commit_id, type: String, desc: "Last known file commit id"
end
- given action: ->(action) { action == 'chmod' } do
- requires :execute_filemode, type: Boolean, desc: 'When `true/false` enables/disables the execute flag on the file.'
+ given action: ->(action) { action == "chmod" } do
+ requires :execute_filemode, type: Boolean, desc: "When `true/false` enables/disables the execute flag on the file."
end
end
- optional :start_branch, type: String, desc: 'Name of the branch to start the new commit from'
- optional :author_email, type: String, desc: 'Author email for commit'
- optional :author_name, type: String, desc: 'Author name for commit'
- optional :stats, type: Boolean, default: true, desc: 'Include commit stats'
+ optional :start_branch, type: String, desc: "Name of the branch to start the new commit from"
+ optional :author_email, type: String, desc: "Author email for commit"
+ optional :author_name, type: String, desc: "Author name for commit"
+ optional :stats, type: Boolean, default: true, desc: "Include commit stats"
end
- post ':id/repository/commits' do
+ post ":id/repository/commits" do
authorize_push_to_branch!(params[:branch])
attrs = declared_params
@@ -120,33 +120,33 @@ module API
end
end
- desc 'Get a specific commit of a project' do
+ desc "Get a specific commit of a project" do
success Entities::CommitDetail
- failure [[404, 'Commit Not Found']]
+ failure [[404, "Commit Not Found"]]
end
params do
- requires :sha, type: String, desc: 'A commit sha, or the name of a branch or tag'
- optional :stats, type: Boolean, default: true, desc: 'Include commit stats'
+ requires :sha, type: String, desc: "A commit sha, or the name of a branch or tag"
+ optional :stats, type: Boolean, default: true, desc: "Include commit stats"
end
- get ':id/repository/commits/:sha', requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
+ get ":id/repository/commits/:sha", requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
commit = user_project.commit(params[:sha])
- not_found! 'Commit' unless commit
+ not_found! "Commit" unless commit
present commit, with: Entities::CommitDetail, stats: params[:stats]
end
- desc 'Get the diff for a specific commit of a project' do
- failure [[404, 'Commit Not Found']]
+ desc "Get the diff for a specific commit of a project" do
+ failure [[404, "Commit Not Found"]]
end
params do
- requires :sha, type: String, desc: 'A commit sha, or the name of a branch or tag'
+ requires :sha, type: String, desc: "A commit sha, or the name of a branch or tag"
use :pagination
end
- get ':id/repository/commits/:sha/diff', requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
+ get ":id/repository/commits/:sha/diff", requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
commit = user_project.commit(params[:sha])
- not_found! 'Commit' unless commit
+ not_found! "Commit" unless commit
raw_diffs = ::Kaminari.paginate_array(commit.raw_diffs.to_a)
@@ -155,43 +155,43 @@ module API
desc "Get a commit's comments" do
success Entities::CommitNote
- failure [[404, 'Commit Not Found']]
+ failure [[404, "Commit Not Found"]]
end
params do
use :pagination
- requires :sha, type: String, desc: 'A commit sha, or the name of a branch or tag'
+ requires :sha, type: String, desc: "A commit sha, or the name of a branch or tag"
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/repository/commits/:sha/comments', requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
+ get ":id/repository/commits/:sha/comments", requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
commit = user_project.commit(params[:sha])
- not_found! 'Commit' unless commit
+ not_found! "Commit" unless commit
notes = commit.notes.order(:created_at)
present paginate(notes), with: Entities::CommitNote
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Cherry pick commit into a branch' do
- detail 'This feature was introduced in GitLab 8.15'
+ desc "Cherry pick commit into a branch" do
+ detail "This feature was introduced in GitLab 8.15"
success Entities::Commit
end
params do
- requires :sha, type: String, desc: 'A commit sha, or the name of a branch or tag to be cherry picked'
- requires :branch, type: String, desc: 'The name of the branch', allow_blank: false
+ requires :sha, type: String, desc: "A commit sha, or the name of a branch or tag to be cherry picked"
+ requires :branch, type: String, desc: "The name of the branch", allow_blank: false
end
- post ':id/repository/commits/:sha/cherry_pick', requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
+ post ":id/repository/commits/:sha/cherry_pick", requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
authorize_push_to_branch!(params[:branch])
commit = user_project.commit(params[:sha])
- not_found!('Commit') unless commit
+ not_found!("Commit") unless commit
find_branch!(params[:branch])
commit_params = {
commit: commit,
start_branch: params[:branch],
- branch_name: params[:branch]
+ branch_name: params[:branch],
}
result = ::Commits::CherryPickService
@@ -206,26 +206,26 @@ module API
end
end
- desc 'Revert a commit in a branch' do
- detail 'This feature was introduced in GitLab 11.5'
+ desc "Revert a commit in a branch" do
+ detail "This feature was introduced in GitLab 11.5"
success Entities::Commit
end
params do
- requires :sha, type: String, desc: 'Commit SHA to revert'
- requires :branch, type: String, desc: 'Target branch name', allow_blank: false
+ requires :sha, type: String, desc: "Commit SHA to revert"
+ requires :branch, type: String, desc: "Target branch name", allow_blank: false
end
- post ':id/repository/commits/:sha/revert', requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
+ post ":id/repository/commits/:sha/revert", requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
authorize_push_to_branch!(params[:branch])
commit = user_project.commit(params[:sha])
- not_found!('Commit') unless commit
+ not_found!("Commit") unless commit
find_branch!(params[:branch])
commit_params = {
commit: commit,
start_branch: params[:branch],
- branch_name: params[:branch]
+ branch_name: params[:branch],
}
result = ::Commits::RevertService
@@ -240,47 +240,47 @@ module API
end
end
- desc 'Get all references a commit is pushed to' do
- detail 'This feature was introduced in GitLab 10.6'
+ desc "Get all references a commit is pushed to" do
+ detail "This feature was introduced in GitLab 10.6"
success Entities::BasicRef
end
params do
- requires :sha, type: String, desc: 'A commit sha'
- optional :type, type: String, values: %w[branch tag all], default: 'all', desc: 'Scope'
+ requires :sha, type: String, desc: "A commit sha"
+ optional :type, type: String, values: %w[branch tag all], default: "all", desc: "Scope"
use :pagination
end
- get ':id/repository/commits/:sha/refs', requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
+ get ":id/repository/commits/:sha/refs", requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
commit = user_project.commit(params[:sha])
- not_found!('Commit') unless commit
+ not_found!("Commit") unless commit
refs = []
- refs.concat(user_project.repository.branch_names_contains(commit.id).map {|name| { type: 'branch', name: name }}) unless params[:type] == 'tag'
- refs.concat(user_project.repository.tag_names_contains(commit.id).map {|name| { type: 'tag', name: name }}) unless params[:type] == 'branch'
+ refs.concat(user_project.repository.branch_names_contains(commit.id).map {|name| {type: "branch", name: name}}) unless params[:type] == "tag"
+ refs.concat(user_project.repository.tag_names_contains(commit.id).map {|name| {type: "tag", name: name}}) unless params[:type] == "branch"
refs = Kaminari.paginate_array(refs)
present paginate(refs), with: Entities::BasicRef
end
- desc 'Post comment to commit' do
+ desc "Post comment to commit" do
success Entities::CommitNote
end
params do
- requires :sha, type: String, desc: 'A commit sha, or the name of a branch or tag on which to post a comment'
- requires :note, type: String, desc: 'The text of the comment'
- optional :path, type: String, desc: 'The file path'
+ requires :sha, type: String, desc: "A commit sha, or the name of a branch or tag on which to post a comment"
+ requires :note, type: String, desc: "The text of the comment"
+ optional :path, type: String, desc: "The file path"
given :path do
- requires :line, type: Integer, desc: 'The line number'
- requires :line_type, type: String, values: %w[new old], default: 'new', desc: 'The type of the line'
+ requires :line, type: Integer, desc: "The line number"
+ requires :line_type, type: String, values: %w[new old], default: "new", desc: "The type of the line"
end
end
- post ':id/repository/commits/:sha/comments', requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
+ post ":id/repository/commits/:sha/comments", requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
commit = user_project.commit(params[:sha])
- not_found! 'Commit' unless commit
+ not_found! "Commit" unless commit
opts = {
note: params[:note],
- noteable_type: 'Commit',
- commit_id: commit.id
+ noteable_type: "Commit",
+ commit_id: commit.id,
}
if params[:path]
@@ -310,16 +310,16 @@ module API
end
end
- desc 'Get Merge Requests associated with a commit' do
+ desc "Get Merge Requests associated with a commit" do
success Entities::MergeRequestBasic
end
params do
- requires :sha, type: String, desc: 'A commit sha, or the name of a branch or tag on which to find Merge Requests'
+ requires :sha, type: String, desc: "A commit sha, or the name of a branch or tag on which to find Merge Requests"
use :pagination
end
- get ':id/repository/commits/:sha/merge_requests', requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
+ get ":id/repository/commits/:sha/merge_requests", requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
commit = user_project.commit(params[:sha])
- not_found! 'Commit' unless commit
+ not_found! "Commit" unless commit
present paginate(commit.merge_requests), with: Entities::MergeRequestBasic
end
@@ -328,14 +328,14 @@ module API
success Entities::CommitSignature
end
params do
- requires :sha, type: String, desc: 'A commit sha, or the name of a branch or tag'
+ requires :sha, type: String, desc: "A commit sha, or the name of a branch or tag"
end
- get ':id/repository/commits/:sha/signature', requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
+ get ":id/repository/commits/:sha/signature", requirements: API::COMMIT_ENDPOINT_REQUIREMENTS do
commit = user_project.commit(params[:sha])
- not_found! 'Commit' unless commit
+ not_found! "Commit" unless commit
signature = commit.signature
- not_found! 'GPG Signature' unless signature
+ not_found! "GPG Signature" unless signature
present signature, with: Entities::CommitSignature
end
diff --git a/lib/api/container_registry.rb b/lib/api/container_registry.rb
index e4493910196..3e387d05e47 100644
--- a/lib/api/container_registry.rb
+++ b/lib/api/container_registry.rb
@@ -5,35 +5,36 @@ module API
include PaginationParams
REGISTRY_ENDPOINT_REQUIREMENTS = API::NAMESPACE_OR_PROJECT_REQUIREMENTS.merge(
- tag_name: API::NO_SLASH_URL_PART_REGEX)
+ tag_name: API::NO_SLASH_URL_PART_REGEX
+ )
- before { error!('404 Not Found', 404) unless Feature.enabled?(:container_registry_api, user_project, default_enabled: true) }
+ before { error!("404 Not Found", 404) unless Feature.enabled?(:container_registry_api, user_project, default_enabled: true) }
before { authorize_read_container_images! }
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get a project container repositories' do
- detail 'This feature was introduced in GitLab 11.8.'
+ desc "Get a project container repositories" do
+ detail "This feature was introduced in GitLab 11.8."
success Entities::ContainerRegistry::Repository
end
params do
use :pagination
end
- get ':id/registry/repositories' do
+ get ":id/registry/repositories" do
repositories = user_project.container_repositories.ordered
present paginate(repositories), with: Entities::ContainerRegistry::Repository
end
- desc 'Delete repository' do
- detail 'This feature was introduced in GitLab 11.8.'
+ desc "Delete repository" do
+ detail "This feature was introduced in GitLab 11.8."
end
params do
- requires :repository_id, type: Integer, desc: 'The ID of the repository'
+ requires :repository_id, type: Integer, desc: "The ID of the repository"
end
- delete ':id/registry/repositories/:repository_id', requirements: REGISTRY_ENDPOINT_REQUIREMENTS do
+ delete ":id/registry/repositories/:repository_id", requirements: REGISTRY_ENDPOINT_REQUIREMENTS do
authorize_admin_container_image!
DeleteContainerRepositoryWorker.perform_async(current_user.id, repository.id)
@@ -41,31 +42,31 @@ module API
status :accepted
end
- desc 'Get a list of repositories tags' do
- detail 'This feature was introduced in GitLab 11.8.'
+ desc "Get a list of repositories tags" do
+ detail "This feature was introduced in GitLab 11.8."
success Entities::ContainerRegistry::Tag
end
params do
- requires :repository_id, type: Integer, desc: 'The ID of the repository'
+ requires :repository_id, type: Integer, desc: "The ID of the repository"
use :pagination
end
- get ':id/registry/repositories/:repository_id/tags', requirements: REGISTRY_ENDPOINT_REQUIREMENTS do
+ get ":id/registry/repositories/:repository_id/tags", requirements: REGISTRY_ENDPOINT_REQUIREMENTS do
authorize_read_container_image!
tags = Kaminari.paginate_array(repository.tags)
present paginate(tags), with: Entities::ContainerRegistry::Tag
end
- desc 'Delete repository tags (in bulk)' do
- detail 'This feature was introduced in GitLab 11.8.'
+ desc "Delete repository tags (in bulk)" do
+ detail "This feature was introduced in GitLab 11.8."
end
params do
- requires :repository_id, type: Integer, desc: 'The ID of the repository'
- requires :name_regex, type: String, desc: 'The tag name regexp to delete, specify .* to delete all'
- optional :keep_n, type: Integer, desc: 'Keep n of latest tags with matching name'
- optional :older_than, type: String, desc: 'Delete older than: 1h, 1d, 1month'
+ requires :repository_id, type: Integer, desc: "The ID of the repository"
+ requires :name_regex, type: String, desc: "The tag name regexp to delete, specify .* to delete all"
+ optional :keep_n, type: Integer, desc: "Keep n of latest tags with matching name"
+ optional :older_than, type: String, desc: "Delete older than: 1h, 1d, 1month"
end
- delete ':id/registry/repositories/:repository_id/tags', requirements: REGISTRY_ENDPOINT_REQUIREMENTS do
+ delete ":id/registry/repositories/:repository_id/tags", requirements: REGISTRY_ENDPOINT_REQUIREMENTS do
authorize_admin_container_image!
CleanupContainerRepositoryWorker.perform_async(current_user.id, repository.id,
@@ -74,29 +75,29 @@ module API
status :accepted
end
- desc 'Get a details about repository tag' do
- detail 'This feature was introduced in GitLab 11.8.'
+ desc "Get a details about repository tag" do
+ detail "This feature was introduced in GitLab 11.8."
success Entities::ContainerRegistry::TagDetails
end
params do
- requires :repository_id, type: Integer, desc: 'The ID of the repository'
- requires :tag_name, type: String, desc: 'The name of the tag'
+ requires :repository_id, type: Integer, desc: "The ID of the repository"
+ requires :tag_name, type: String, desc: "The name of the tag"
end
- get ':id/registry/repositories/:repository_id/tags/:tag_name', requirements: REGISTRY_ENDPOINT_REQUIREMENTS do
+ get ":id/registry/repositories/:repository_id/tags/:tag_name", requirements: REGISTRY_ENDPOINT_REQUIREMENTS do
authorize_read_container_image!
validate_tag!
present tag, with: Entities::ContainerRegistry::TagDetails
end
- desc 'Delete repository tag' do
- detail 'This feature was introduced in GitLab 11.8.'
+ desc "Delete repository tag" do
+ detail "This feature was introduced in GitLab 11.8."
end
params do
- requires :repository_id, type: Integer, desc: 'The ID of the repository'
- requires :tag_name, type: String, desc: 'The name of the tag'
+ requires :repository_id, type: Integer, desc: "The ID of the repository"
+ requires :tag_name, type: String, desc: "The name of the tag"
end
- delete ':id/registry/repositories/:repository_id/tags/:tag_name', requirements: REGISTRY_ENDPOINT_REQUIREMENTS do
+ delete ":id/registry/repositories/:repository_id/tags/:tag_name", requirements: REGISTRY_ENDPOINT_REQUIREMENTS do
authorize_destroy_container_image!
validate_tag!
@@ -136,7 +137,7 @@ module API
end
def validate_tag!
- not_found!('Tag') unless tag.valid?
+ not_found!("Tag") unless tag.valid?
end
end
end
diff --git a/lib/api/custom_attributes_endpoints.rb b/lib/api/custom_attributes_endpoints.rb
index 2149e04451e..d697d8b9f88 100644
--- a/lib/api/custom_attributes_endpoints.rb
+++ b/lib/api/custom_attributes_endpoints.rb
@@ -12,14 +12,14 @@ module API
helpers do
params :custom_attributes_key do
- requires :key, type: String, desc: 'The key of the custom attribute'
+ requires :key, type: String, desc: "The key of the custom attribute"
end
end
desc "Get all custom attributes on a #{attributable_name}" do
success Entities::CustomAttribute
end
- get ':id/custom_attributes' do
+ get ":id/custom_attributes" do
resource = public_send(attributable_finder, params[:id]) # rubocop:disable GitlabSecurity/PublicSend
authorize! :read_custom_attribute
@@ -33,7 +33,7 @@ module API
use :custom_attributes_key
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/custom_attributes/:key' do
+ get ":id/custom_attributes/:key" do
resource = public_send(attributable_finder, params[:id]) # rubocop:disable GitlabSecurity/PublicSend
authorize! :read_custom_attribute
@@ -46,10 +46,10 @@ module API
desc "Set a custom attribute on a #{attributable_name}"
params do
use :custom_attributes_key
- requires :value, type: String, desc: 'The value of the custom attribute'
+ requires :value, type: String, desc: "The value of the custom attribute"
end
# rubocop: disable CodeReuse/ActiveRecord
- put ':id/custom_attributes/:key' do
+ put ":id/custom_attributes/:key" do
resource = public_send(attributable_finder, params[:id]) # rubocop:disable GitlabSecurity/PublicSend
authorize! :update_custom_attribute
@@ -71,7 +71,7 @@ module API
use :custom_attributes_key
end
# rubocop: disable CodeReuse/ActiveRecord
- delete ':id/custom_attributes/:key' do
+ delete ":id/custom_attributes/:key" do
resource = public_send(attributable_finder, params[:id]) # rubocop:disable GitlabSecurity/PublicSend
authorize! :update_custom_attribute
diff --git a/lib/api/deploy_keys.rb b/lib/api/deploy_keys.rb
index df6d2721977..32256c726ec 100644
--- a/lib/api/deploy_keys.rb
+++ b/lib/api/deploy_keys.rb
@@ -18,7 +18,7 @@ module API
# rubocop: enable CodeReuse/ActiveRecord
end
- desc 'Return all deploy keys'
+ desc "Return all deploy keys"
params do
use :pagination
end
@@ -29,7 +29,7 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of the project'
+ requires :id, type: String, desc: "The ID of the project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
before { authorize_admin_project }
@@ -48,11 +48,11 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get single deploy key' do
+ desc "Get single deploy key" do
success Entities::DeployKeysProject
end
params do
- requires :key_id, type: Integer, desc: 'The ID of the deploy key'
+ requires :key_id, type: Integer, desc: "The ID of the deploy key"
end
get ":id/deploy_keys/:key_id" do
key = find_by_deploy_key(user_project, params[:key_id])
@@ -60,12 +60,12 @@ module API
present key, with: Entities::DeployKeysProject
end
- desc 'Add new deploy key to a project' do
+ desc "Add new deploy key to a project" do
success Entities::DeployKeysProject
end
params do
- requires :key, type: String, desc: 'The new deploy key'
- requires :title, type: String, desc: 'The name of the deploy key'
+ requires :key, type: String, desc: "The new deploy key"
+ requires :title, type: String, desc: "The name of the deploy key"
optional :can_push, type: Boolean, desc: "Can deploy key push to the project's repository"
end
# rubocop: disable CodeReuse/ActiveRecord
@@ -74,8 +74,8 @@ module API
# Check for an existing key joined to this project
deploy_key_project = user_project.deploy_keys_projects
- .joins(:deploy_key)
- .find_by(keys: { key: params[:key] })
+ .joins(:deploy_key)
+ .find_by(keys: {key: params[:key]})
if deploy_key_project
present deploy_key_project, with: Entities::DeployKeysProject
@@ -103,12 +103,12 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Update an existing deploy key for a project' do
+ desc "Update an existing deploy key for a project" do
success Entities::SSHKey
end
params do
- requires :key_id, type: Integer, desc: 'The ID of the deploy key'
- optional :title, type: String, desc: 'The name of the deploy key'
+ requires :key_id, type: Integer, desc: "The ID of the deploy key"
+ optional :title, type: String, desc: "The name of the deploy key"
optional :can_push, type: Boolean, desc: "Can deploy key push to the project's repository"
at_least_one_of :title, :can_push
end
@@ -121,8 +121,8 @@ module API
title = params[:title] || deploy_keys_project.deploy_key.title
result = deploy_keys_project.update(can_push: can_push,
- deploy_key_attributes: { id: params[:key_id],
- title: title })
+ deploy_key_attributes: {id: params[:key_id],
+ title: title,})
if result
present deploy_keys_project, with: Entities::DeployKeysProject
@@ -131,34 +131,34 @@ module API
end
end
- desc 'Enable a deploy key for a project' do
- detail 'This feature was added in GitLab 8.11'
+ desc "Enable a deploy key for a project" do
+ detail "This feature was added in GitLab 8.11"
success Entities::SSHKey
end
params do
- requires :key_id, type: Integer, desc: 'The ID of the deploy key'
+ requires :key_id, type: Integer, desc: "The ID of the deploy key"
end
post ":id/deploy_keys/:key_id/enable" do
key = ::Projects::EnableDeployKeyService.new(user_project,
- current_user, declared_params).execute
+ current_user, declared_params).execute
if key
present key, with: Entities::SSHKey
else
- not_found!('Deploy Key')
+ not_found!("Deploy Key")
end
end
- desc 'Delete deploy key for a project' do
+ desc "Delete deploy key for a project" do
success Key
end
params do
- requires :key_id, type: Integer, desc: 'The ID of the deploy key'
+ requires :key_id, type: Integer, desc: "The ID of the deploy key"
end
# rubocop: disable CodeReuse/ActiveRecord
delete ":id/deploy_keys/:key_id" do
deploy_key_project = user_project.deploy_keys_projects.find_by(deploy_key_id: params[:key_id])
- not_found!('Deploy Key') unless deploy_key_project
+ not_found!("Deploy Key") unless deploy_key_project
destroy_conditionally!(deploy_key_project)
end
diff --git a/lib/api/deployments.rb b/lib/api/deployments.rb
index eb45df31ff9..6deb89a6809 100644
--- a/lib/api/deployments.rb
+++ b/lib/api/deployments.rb
@@ -8,34 +8,34 @@ module API
before { authenticate! }
params do
- requires :id, type: String, desc: 'The project ID'
+ requires :id, type: String, desc: "The project ID"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get all deployments of the project' do
- detail 'This feature was introduced in GitLab 8.11.'
+ desc "Get all deployments of the project" do
+ detail "This feature was introduced in GitLab 8.11."
success Entities::Deployment
end
params do
use :pagination
- optional :order_by, type: String, values: %w[id iid created_at ref], default: 'id', desc: 'Return deployments ordered by `id` or `iid` or `created_at` or `ref`'
- optional :sort, type: String, values: %w[asc desc], default: 'asc', desc: 'Sort by asc (ascending) or desc (descending)'
+ optional :order_by, type: String, values: %w[id iid created_at ref], default: "id", desc: "Return deployments ordered by `id` or `iid` or `created_at` or `ref`"
+ optional :sort, type: String, values: %w[asc desc], default: "asc", desc: "Sort by asc (ascending) or desc (descending)"
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/deployments' do
+ get ":id/deployments" do
authorize! :read_deployment, user_project
present paginate(user_project.deployments.order(params[:order_by] => params[:sort])), with: Entities::Deployment
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Gets a specific deployment' do
- detail 'This feature was introduced in GitLab 8.11.'
+ desc "Gets a specific deployment" do
+ detail "This feature was introduced in GitLab 8.11."
success Entities::Deployment
end
params do
- requires :deployment_id, type: Integer, desc: 'The deployment ID'
+ requires :deployment_id, type: Integer, desc: "The deployment ID"
end
- get ':id/deployments/:deployment_id' do
+ get ":id/deployments/:deployment_id" do
authorize! :read_deployment, user_project
deployment = user_project.deployments.find(params[:deployment_id])
diff --git a/lib/api/discussions.rb b/lib/api/discussions.rb
index 91eb6a23701..06d9c53c2ab 100644
--- a/lib/api/discussions.rb
+++ b/lib/api/discussions.rb
@@ -22,7 +22,7 @@ module API
success Entities::Discussion
end
params do
- requires :noteable_id, types: [Integer, String], desc: 'The ID of the noteable'
+ requires :noteable_id, types: [Integer, String], desc: "The ID of the noteable"
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
@@ -45,8 +45,8 @@ module API
success Entities::Discussion
end
params do
- requires :discussion_id, type: String, desc: 'The ID of a discussion'
- requires :noteable_id, types: [Integer, String], desc: 'The ID of the noteable'
+ requires :discussion_id, type: String, desc: "The ID of a discussion"
+ requires :noteable_id, types: [Integer, String], desc: "The ID of the noteable"
end
get ":id/#{noteables_path}/:noteable_id/discussions/:discussion_id" do
noteable = find_noteable(parent_type, noteables_str, params[:noteable_id])
@@ -65,36 +65,36 @@ module API
success Entities::Discussion
end
params do
- requires :noteable_id, types: [Integer, String], desc: 'The ID of the noteable'
- requires :body, type: String, desc: 'The content of a note'
- optional :created_at, type: String, desc: 'The creation date of the note'
+ requires :noteable_id, types: [Integer, String], desc: "The ID of the noteable"
+ requires :body, type: String, desc: "The content of a note"
+ optional :created_at, type: String, desc: "The creation date of the note"
optional :position, type: Hash do
- requires :base_sha, type: String, desc: 'Base commit SHA in the source branch'
- requires :start_sha, type: String, desc: 'SHA referencing commit in target branch'
- requires :head_sha, type: String, desc: 'SHA referencing HEAD of this merge request'
- requires :position_type, type: String, desc: 'Type of the position reference', values: %w(text image)
- optional :new_path, type: String, desc: 'File path after change'
- optional :new_line, type: Integer, desc: 'Line number after change'
- optional :old_path, type: String, desc: 'File path before change'
- optional :old_line, type: Integer, desc: 'Line number before change'
- optional :width, type: Integer, desc: 'Width of the image'
- optional :height, type: Integer, desc: 'Height of the image'
- optional :x, type: Integer, desc: 'X coordinate in the image'
- optional :y, type: Integer, desc: 'Y coordinate in the image'
+ requires :base_sha, type: String, desc: "Base commit SHA in the source branch"
+ requires :start_sha, type: String, desc: "SHA referencing commit in target branch"
+ requires :head_sha, type: String, desc: "SHA referencing HEAD of this merge request"
+ requires :position_type, type: String, desc: "Type of the position reference", values: %w[text image]
+ optional :new_path, type: String, desc: "File path after change"
+ optional :new_line, type: Integer, desc: "Line number after change"
+ optional :old_path, type: String, desc: "File path before change"
+ optional :old_line, type: Integer, desc: "Line number before change"
+ optional :width, type: Integer, desc: "Width of the image"
+ optional :height, type: Integer, desc: "Height of the image"
+ optional :x, type: Integer, desc: "X coordinate in the image"
+ optional :y, type: Integer, desc: "Y coordinate in the image"
end
end
post ":id/#{noteables_path}/:noteable_id/discussions" do
noteable = find_noteable(parent_type, noteables_str, params[:noteable_id])
- type = params[:position] ? 'DiffNote' : 'DiscussionNote'
+ type = params[:position] ? "DiffNote" : "DiscussionNote"
id_key = noteable.is_a?(Commit) ? :commit_id : :noteable_id
opts = {
- note: params[:body],
- created_at: params[:created_at],
- type: type,
- noteable_type: noteables_str.classify,
- position: params[:position],
- id_key => noteable.id
+ :note => params[:body],
+ :created_at => params[:created_at],
+ :type => type,
+ :noteable_type => noteables_str.classify,
+ :position => params[:position],
+ id_key => noteable.id,
}
note = create_note(noteable, opts)
@@ -110,8 +110,8 @@ module API
success Entities::Discussion
end
params do
- requires :discussion_id, type: String, desc: 'The ID of a discussion'
- requires :noteable_id, types: [Integer, String], desc: 'The ID of the noteable'
+ requires :discussion_id, type: String, desc: "The ID of a discussion"
+ requires :noteable_id, types: [Integer, String], desc: "The ID of the noteable"
end
get ":id/#{noteables_path}/:noteable_id/discussions/:discussion_id/notes" do
noteable = find_noteable(parent_type, noteables_str, params[:noteable_id])
@@ -128,10 +128,10 @@ module API
success Entities::Note
end
params do
- requires :noteable_id, types: [Integer, String], desc: 'The ID of the noteable'
- requires :discussion_id, type: String, desc: 'The ID of a discussion'
- requires :body, type: String, desc: 'The content of a note'
- optional :created_at, type: String, desc: 'The creation date of the note'
+ requires :noteable_id, types: [Integer, String], desc: "The ID of the noteable"
+ requires :discussion_id, type: String, desc: "The ID of a discussion"
+ requires :body, type: String, desc: "The content of a note"
+ optional :created_at, type: String, desc: "The creation date of the note"
end
post ":id/#{noteables_path}/:noteable_id/discussions/:discussion_id/notes" do
noteable = find_noteable(parent_type, noteables_str, params[:noteable_id])
@@ -142,9 +142,9 @@ module API
opts = {
note: params[:body],
- type: 'DiscussionNote',
+ type: "DiscussionNote",
in_reply_to_discussion_id: params[:discussion_id],
- created_at: params[:created_at]
+ created_at: params[:created_at],
}
note = create_note(noteable, opts)
@@ -159,9 +159,9 @@ module API
success Entities::Note
end
params do
- requires :noteable_id, types: [Integer, String], desc: 'The ID of the noteable'
- requires :discussion_id, type: String, desc: 'The ID of a discussion'
- requires :note_id, type: Integer, desc: 'The ID of a note'
+ requires :noteable_id, types: [Integer, String], desc: "The ID of the noteable"
+ requires :discussion_id, type: String, desc: "The ID of a discussion"
+ requires :note_id, type: Integer, desc: "The ID of a note"
end
get ":id/#{noteables_path}/:noteable_id/discussions/:discussion_id/notes/:note_id" do
noteable = find_noteable(parent_type, noteables_str, params[:noteable_id])
@@ -173,11 +173,11 @@ module API
success Entities::Note
end
params do
- requires :noteable_id, types: [Integer, String], desc: 'The ID of the noteable'
- requires :discussion_id, type: String, desc: 'The ID of a discussion'
- requires :note_id, type: Integer, desc: 'The ID of a note'
- optional :body, type: String, desc: 'The content of a note'
- optional :resolved, type: Boolean, desc: 'Mark note resolved/unresolved'
+ requires :noteable_id, types: [Integer, String], desc: "The ID of the noteable"
+ requires :discussion_id, type: String, desc: "The ID of a discussion"
+ requires :note_id, type: Integer, desc: "The ID of a note"
+ optional :body, type: String, desc: "The content of a note"
+ optional :resolved, type: Boolean, desc: "Mark note resolved/unresolved"
exactly_one_of :body, :resolved
end
put ":id/#{noteables_path}/:noteable_id/discussions/:discussion_id/notes/:note_id" do
@@ -194,9 +194,9 @@ module API
success Entities::Note
end
params do
- requires :noteable_id, types: [Integer, String], desc: 'The ID of the noteable'
- requires :discussion_id, type: String, desc: 'The ID of a discussion'
- requires :note_id, type: Integer, desc: 'The ID of a note'
+ requires :noteable_id, types: [Integer, String], desc: "The ID of the noteable"
+ requires :discussion_id, type: String, desc: "The ID of a discussion"
+ requires :note_id, type: Integer, desc: "The ID of a note"
end
delete ":id/#{noteables_path}/:noteable_id/discussions/:discussion_id/notes/:note_id" do
noteable = find_noteable(parent_type, noteables_str, params[:noteable_id])
@@ -209,9 +209,9 @@ module API
success Entities::Discussion
end
params do
- requires :noteable_id, types: [Integer, String], desc: 'The ID of the noteable'
- requires :discussion_id, type: String, desc: 'The ID of a discussion'
- requires :resolved, type: Boolean, desc: 'Mark discussion resolved/unresolved'
+ requires :noteable_id, types: [Integer, String], desc: "The ID of the noteable"
+ requires :discussion_id, type: String, desc: "The ID of a discussion"
+ requires :resolved, type: Boolean, desc: "Mark discussion resolved/unresolved"
end
put ":id/#{noteables_path}/:noteable_id/discussions/:discussion_id" do
noteable = find_noteable(parent_type, noteables_str, params[:noteable_id])
diff --git a/lib/api/entities.rb b/lib/api/entities.rb
index 18f15632f2b..b01f65709bb 100644
--- a/lib/api/entities.rb
+++ b/lib/api/entities.rb
@@ -21,7 +21,7 @@ module API
expose :link do
expose :file_path, as: :url
expose :markdown do |_entity|
- self.markdown_link
+ markdown_link
end
end
@@ -46,7 +46,7 @@ module API
end
expose :avatar_path, if: ->(user, options) { options.fetch(:only_path, false) && user.avatar_path }
- expose :custom_attributes, using: 'API::Entities::CustomAttribute', if: :with_custom_attributes
+ expose :custom_attributes, using: "API::Entities::CustomAttribute", if: :with_custom_attributes
expose :web_url do |user, options|
Gitlab::Routing.url_helpers.user_url(user)
@@ -176,7 +176,7 @@ module API
end
end
- expose :license, with: 'API::Entities::LicenseBasic', if: :license do |project|
+ expose :license, with: "API::Entities::LicenseBasic", if: :license do |project|
project.repository.license
end
@@ -186,8 +186,8 @@ module API
expose :star_count, :forks_count
expose :last_activity_at
- expose :namespace, using: 'API::Entities::NamespaceBasic'
- expose :custom_attributes, using: 'API::Entities::CustomAttribute', if: :with_custom_attributes
+ expose :namespace, using: "API::Entities::NamespaceBasic"
+ expose :custom_attributes, using: "API::Entities::CustomAttribute", if: :with_custom_attributes
# rubocop: disable CodeReuse/ActiveRecord
def self.preload_relation(projects_relation, options = {})
@@ -196,8 +196,8 @@ module API
# N+1 is solved then by using `subject.tags.map(&:name)`
# MR describing the solution: https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/20555
projects_relation.preload(:project_feature, :route)
- .preload(:import_state, :tags)
- .preload(namespace: [:route, :owner])
+ .preload(:import_state, :tags)
+ .preload(namespace: [:route, :owner])
end
# rubocop: enable CodeReuse/ActiveRecord
end
@@ -210,11 +210,11 @@ module API
expose_url(api_v4_projects_path(id: project.id))
end
- expose :issues, if: -> (project, options) { issues_available?(project, options) } do |project|
+ expose :issues, if: ->(project, options) { issues_available?(project, options) } do |project|
expose_url(api_v4_projects_issues_path(id: project.id))
end
- expose :merge_requests, if: -> (project, options) { mrs_available?(project, options) } do |project|
+ expose :merge_requests, if: ->(project, options) { mrs_available?(project, options) } do |project|
expose_url(api_v4_projects_merge_requests_path(id: project.id))
end
@@ -271,7 +271,7 @@ module API
expose :printing_merge_request_link_enabled
expose :merge_method
- expose :statistics, using: 'API::Entities::ProjectStatistics', if: :statistics
+ expose :statistics, using: "API::Entities::ProjectStatistics", if: :statistics
# rubocop: disable CodeReuse/ActiveRecord
def self.preload_relation(projects_relation, options = {})
@@ -280,10 +280,10 @@ module API
# N+1 is solved then by using `subject.tags.map(&:name)`
# MR describing the solution: https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/20555
super(projects_relation).preload(:group)
- .preload(project_group_links: { group: :route },
- fork_network: :root_project,
- fork_network_member: :forked_from_project,
- forked_from_project: [:route, :forks, :tags, namespace: :route])
+ .preload(project_group_links: {group: :route},
+ fork_network: :root_project,
+ fork_network_member: :forked_from_project,
+ forked_from_project: [:route, :forks, :tags, namespace: :route])
end
# rubocop: enable CodeReuse/ActiveRecord
@@ -342,10 +342,10 @@ module API
expose :parent_id
end
- expose :custom_attributes, using: 'API::Entities::CustomAttribute', if: :with_custom_attributes
+ expose :custom_attributes, using: "API::Entities::CustomAttribute", if: :with_custom_attributes
expose :statistics, if: :statistics do
- with_options format_with: -> (value) { value.to_i } do
+ with_options format_with: ->(value) { value.to_i } do
expose :storage_size
expose :repository_size
expose :lfs_objects_size
@@ -359,7 +359,7 @@ module API
projects = GroupProjectsFinder.new(
group: group,
current_user: options[:current_user],
- options: { only_owned: true }
+ options: {only_owned: true}
).execute
Entities::Project.prepare_relation(projects)
@@ -369,7 +369,7 @@ module API
projects = GroupProjectsFinder.new(
group: group,
current_user: options[:current_user],
- options: { only_shared: true }
+ options: {only_shared: true}
).execute
Entities::Project.prepare_relation(projects)
@@ -400,7 +400,7 @@ module API
class CommitDetail < Commit
expose :stats, using: Entities::CommitStats, if: :stats
expose :status
- expose :last_pipeline, using: 'API::Entities::PipelineBasic'
+ expose :last_pipeline, using: "API::Entities::PipelineBasic"
expose :project_id
end
@@ -521,8 +521,8 @@ module API
class Milestone < Grape::Entity
expose :id, :iid
- expose :project_id, if: -> (entity, options) { entity&.project_id }
- expose :group_id, if: -> (entity, options) { entity&.group_id }
+ expose :project_id, if: ->(entity, options) { entity&.project_id }
+ expose :group_id, if: ->(entity, options) { entity&.group_id }
expose :title, :description
expose :state, :created_at, :updated_at
expose :due_date
@@ -559,7 +559,7 @@ module API
Gitlab::UrlBuilder.build(issue)
end
- expose :time_stats, using: 'API::Entities::IssuableTimeStats' do |issue|
+ expose :time_stats, using: "API::Entities::IssuableTimeStats" do |issue|
issue
end
end
@@ -648,10 +648,10 @@ module API
merge_request.metrics&.latest_closed_at
end
- expose :title_html, if: -> (_, options) { options[:render_html] } do |entity|
+ expose :title_html, if: ->(_, options) { options[:render_html] } do |entity|
MarkupHelper.markdown_field(entity, :title)
end
- expose :description_html, if: -> (_, options) { options[:render_html] } do |entity|
+ expose :description_html, if: ->(_, options) { options[:render_html] } do |entity|
MarkupHelper.markdown_field(entity, :description)
end
expose :target_branch, :source_branch
@@ -681,15 +681,15 @@ module API
expose :discussion_locked
expose :should_remove_source_branch?, as: :should_remove_source_branch
expose :force_remove_source_branch?, as: :force_remove_source_branch
- expose :allow_collaboration, if: -> (merge_request, _) { merge_request.for_fork? }
+ expose :allow_collaboration, if: ->(merge_request, _) { merge_request.for_fork? }
# Deprecated
- expose :allow_collaboration, as: :allow_maintainer_to_push, if: -> (merge_request, _) { merge_request.for_fork? }
+ expose :allow_collaboration, as: :allow_maintainer_to_push, if: ->(merge_request, _) { merge_request.for_fork? }
expose :web_url do |merge_request|
Gitlab::UrlBuilder.build(merge_request)
end
- expose :time_stats, using: 'API::Entities::IssuableTimeStats' do |merge_request|
+ expose :time_stats, using: "API::Entities::IssuableTimeStats" do |merge_request|
merge_request
end
@@ -705,19 +705,19 @@ module API
merge_request.merge_request_diff.real_size
end
- expose :latest_build_started_at, if: -> (_, options) { build_available?(options) } do |merge_request, _options|
+ expose :latest_build_started_at, if: ->(_, options) { build_available?(options) } do |merge_request, _options|
merge_request.metrics&.latest_build_started_at
end
- expose :latest_build_finished_at, if: -> (_, options) { build_available?(options) } do |merge_request, _options|
+ expose :latest_build_finished_at, if: ->(_, options) { build_available?(options) } do |merge_request, _options|
merge_request.metrics&.latest_build_finished_at
end
- expose :first_deployed_to_production_at, if: -> (_, options) { build_available?(options) } do |merge_request, _options|
+ expose :first_deployed_to_production_at, if: ->(_, options) { build_available?(options) } do |merge_request, _options|
merge_request.metrics&.first_deployed_to_production_at
end
- expose :pipeline, using: Entities::PipelineBasic, if: -> (_, options) { build_available?(options) } do |merge_request, _options|
+ expose :pipeline, using: Entities::PipelineBasic, if: ->(_, options) { build_available?(options) } do |merge_request, _options|
merge_request.metrics&.pipeline
end
@@ -725,9 +725,9 @@ module API
# Allow the status of a rebase to be determined
expose :merge_error
- expose :rebase_in_progress?, as: :rebase_in_progress, if: -> (_, options) { options[:include_rebase_in_progress] }
+ expose :rebase_in_progress?, as: :rebase_in_progress, if: ->(_, options) { options[:include_rebase_in_progress] }
- expose :diverged_commits_count, as: :diverged_commits_count, if: -> (_, options) { options[:include_diverged_commits_count] }
+ expose :diverged_commits_count, as: :diverged_commits_count, if: ->(_, options) { options[:include_diverged_commits_count] }
def build_available?(options)
options[:project]&.feature_available?(:builds, options[:current_user])
@@ -783,7 +783,7 @@ module API
class Note < Grape::Entity
# Only Issue and MergeRequest have iid
- NOTEABLE_TYPES_WITH_IID = %w(Issue MergeRequest).freeze
+ NOTEABLE_TYPES_WITH_IID = %w[Issue MergeRequest].freeze
expose :id
expose :type
@@ -842,7 +842,7 @@ module API
class CommitStatus < Grape::Entity
expose :id, :sha, :ref, :status, :name, :target_url, :description,
- :created_at, :started_at, :finished_at, :allow_failure, :coverage
+ :created_at, :started_at, :finished_at, :allow_failure, :coverage
expose :author, using: Entities::UserBasic
end
@@ -862,7 +862,7 @@ module API
expose :push_event_payload,
as: :push_data,
using: PushEventPayload,
- if: -> (event, _) { event.push? }
+ if: ->(event, _) { event.push? }
expose :author_username do |event, options|
event.author&.username
@@ -875,8 +875,8 @@ module API
class Todo < Grape::Entity
expose :id
- expose :project, using: Entities::ProjectIdentity, if: -> (todo, _) { todo.project_id }
- expose :group, using: 'API::Entities::NamespaceBasic', if: -> (todo, _) { todo.group_id }
+ expose :project, using: Entities::ProjectIdentity, if: ->(todo, _) { todo.project_id }
+ expose :group, using: "API::Entities::NamespaceBasic", if: ->(todo, _) { todo.group_id }
expose :author, using: Entities::UserBasic
expose :action_name
expose :target_type
@@ -909,12 +909,12 @@ module API
end
class Namespace < NamespaceBasic
- expose :members_count_with_descendants, if: -> (namespace, opts) { expose_members_count_with_descendants?(namespace, opts) } do |namespace, _|
+ expose :members_count_with_descendants, if: ->(namespace, opts) { expose_members_count_with_descendants?(namespace, opts) } do |namespace, _|
namespace.users_with_descendants.count
end
def expose_members_count_with_descendants?(namespace, opts)
- namespace.kind == 'group' && Ability.allowed?(opts[:current_user], :admin_group, namespace)
+ namespace.kind == "group" && Ability.allowed?(opts[:current_user], :admin_group, namespace)
end
end
@@ -987,10 +987,10 @@ module API
# MySQL doesn't support LIMIT inside an IN subquery
if Gitlab::Database.mysql?
- project_ids = relation.pluck('projects.id')
+ project_ids = relation.pluck("projects.id")
namespace_ids = relation.pluck(:namespace_id)
else
- project_ids = relation.select('projects.id')
+ project_ids = relation.select("projects.id")
namespace_ids = relation.select(:namespace_id)
end
@@ -1135,7 +1135,7 @@ module API
MarkupHelper.markdown_field(entity, :description)
end
expose :created_at
- expose :author, using: Entities::UserBasic, if: -> (release, _) { release.author.present? }
+ expose :author, using: Entities::UserBasic, if: ->(release, _) { release.author.present? }
expose :commit, using: Entities::Commit
expose :assets do
@@ -1229,7 +1229,7 @@ module API
class Job < JobBasic
# artifacts_file is included in job_artifacts, but kept for backward compatibility (remove in api/v5)
- expose :artifacts_file, using: JobArtifactFile, if: -> (job, opts) { job.artifacts? }
+ expose :artifacts_file, using: JobArtifactFile, if: ->(job, opts) { job.artifacts? }
expose :job_artifacts, as: :artifacts, using: JobArtifact
expose :runner, with: Runner
expose :artifacts_expire_at
@@ -1251,7 +1251,7 @@ module API
class Variable < Grape::Entity
expose :key, :value
- expose :protected?, as: :protected, if: -> (entity, _) { entity.respond_to?(:protected?) }
+ expose :protected?, as: :protected, if: ->(entity, _) { entity.respond_to?(:protected?) }
end
class Pipeline < PipelineBasic
@@ -1293,15 +1293,15 @@ module API
class LicenseBasic < Grape::Entity
expose :key, :name, :nickname
expose :url, as: :html_url
- expose(:source_url) { |license| license.meta['source'] }
+ expose(:source_url) { |license| license.meta["source"] }
end
class License < LicenseBasic
expose :popular?, as: :popular
- expose(:description) { |license| license.meta['description'] }
- expose(:conditions) { |license| license.meta['conditions'] }
- expose(:permissions) { |license| license.meta['permissions'] }
- expose(:limitations) { |license| license.meta['limitations'] }
+ expose(:description) { |license| license.meta["description"] }
+ expose(:conditions) { |license| license.meta["conditions"] }
+ expose(:permissions) { |license| license.meta["permissions"] }
+ expose(:limitations) { |license| license.meta["limitations"] }
expose :content
end
@@ -1348,7 +1348,7 @@ module API
expose :name
expose :state
expose :gates, using: FeatureGate do |model|
- model.gates.map do |gate|
+ model.gates.map { |gate|
value = model.gate_values[gate.key]
# By default all gate values are populated. Only show relevant ones.
@@ -1356,8 +1356,8 @@ module API
next
end
- { key: gate.key, value: value }
- end.compact
+ {key: gate.key, value: value}
+ }.compact
end
end
@@ -1532,7 +1532,7 @@ module API
class Badge < BasicBadgeDetails
expose :id
expose :kind do |badge|
- badge.type == 'ProjectBadge' ? 'project' : 'group'
+ badge.type == "ProjectBadge" ? "project" : "group"
end
end
diff --git a/lib/api/environments.rb b/lib/api/environments.rb
index 0278c6c54a5..b5dd47def3f 100644
--- a/lib/api/environments.rb
+++ b/lib/api/environments.rb
@@ -9,32 +9,32 @@ module API
before { authenticate! }
params do
- requires :id, type: String, desc: 'The project ID'
+ requires :id, type: String, desc: "The project ID"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get all environments of the project' do
- detail 'This feature was introduced in GitLab 8.11.'
+ desc "Get all environments of the project" do
+ detail "This feature was introduced in GitLab 8.11."
success Entities::Environment
end
params do
use :pagination
end
- get ':id/environments' do
+ get ":id/environments" do
authorize! :read_environment, user_project
present paginate(user_project.environments), with: Entities::Environment
end
- desc 'Creates a new environment' do
- detail 'This feature was introduced in GitLab 8.11.'
+ desc "Creates a new environment" do
+ detail "This feature was introduced in GitLab 8.11."
success Entities::Environment
end
params do
- requires :name, type: String, desc: 'The name of the environment to be created'
- optional :external_url, type: String, desc: 'URL on which this deployment is viewable'
- optional :slug, absence: { message: "is automatically generated and cannot be changed" }
+ requires :name, type: String, desc: "The name of the environment to be created"
+ optional :external_url, type: String, desc: "URL on which this deployment is viewable"
+ optional :slug, absence: {message: "is automatically generated and cannot be changed"}
end
- post ':id/environments' do
+ post ":id/environments" do
authorize! :create_environment, user_project
environment = user_project.environments.create(declared_params)
@@ -46,17 +46,17 @@ module API
end
end
- desc 'Updates an existing environment' do
- detail 'This feature was introduced in GitLab 8.11.'
+ desc "Updates an existing environment" do
+ detail "This feature was introduced in GitLab 8.11."
success Entities::Environment
end
params do
- requires :environment_id, type: Integer, desc: 'The environment ID'
- optional :name, type: String, desc: 'The new environment name'
- optional :external_url, type: String, desc: 'The new URL on which this deployment is viewable'
- optional :slug, absence: { message: "is automatically generated and cannot be changed" }
+ requires :environment_id, type: Integer, desc: "The environment ID"
+ optional :name, type: String, desc: "The new environment name"
+ optional :external_url, type: String, desc: "The new URL on which this deployment is viewable"
+ optional :slug, absence: {message: "is automatically generated and cannot be changed"}
end
- put ':id/environments/:environment_id' do
+ put ":id/environments/:environment_id" do
authorize! :update_environment, user_project
environment = user_project.environments.find(params[:environment_id])
@@ -69,14 +69,14 @@ module API
end
end
- desc 'Deletes an existing environment' do
- detail 'This feature was introduced in GitLab 8.11.'
+ desc "Deletes an existing environment" do
+ detail "This feature was introduced in GitLab 8.11."
success Entities::Environment
end
params do
- requires :environment_id, type: Integer, desc: 'The environment ID'
+ requires :environment_id, type: Integer, desc: "The environment ID"
end
- delete ':id/environments/:environment_id' do
+ delete ":id/environments/:environment_id" do
authorize! :update_environment, user_project
environment = user_project.environments.find(params[:environment_id])
@@ -84,13 +84,13 @@ module API
destroy_conditionally!(environment)
end
- desc 'Stops an existing environment' do
+ desc "Stops an existing environment" do
success Entities::Environment
end
params do
- requires :environment_id, type: Integer, desc: 'The environment ID'
+ requires :environment_id, type: Integer, desc: "The environment ID"
end
- post ':id/environments/:environment_id/stop' do
+ post ":id/environments/:environment_id/stop" do
authorize! :read_environment, user_project
environment = user_project.environments.find(params[:environment_id])
diff --git a/lib/api/events.rb b/lib/api/events.rb
index b98aa9f31e1..0dcd2d0396b 100644
--- a/lib/api/events.rb
+++ b/lib/api/events.rb
@@ -7,15 +7,15 @@ module API
helpers do
params :event_filter_params do
- optional :action, type: String, values: Event.actions, desc: 'Event action to filter on'
- optional :target_type, type: String, values: Event.target_types, desc: 'Event target type to filter on'
- optional :before, type: Date, desc: 'Include only events created before this date'
- optional :after, type: Date, desc: 'Include only events created after this date'
+ optional :action, type: String, values: Event.actions, desc: "Event action to filter on"
+ optional :target_type, type: String, values: Event.target_types, desc: "Event target type to filter on"
+ optional :before, type: Date, desc: "Include only events created before this date"
+ optional :after, type: Date, desc: "Include only events created after this date"
end
params :sort_params do
- optional :sort, type: String, values: %w[asc desc], default: 'desc',
- desc: 'Return events sorted in ascending and descending order'
+ optional :sort, type: String, values: %w[asc desc], default: "desc",
+ desc: "Return events sorted in ascending and descending order"
end
def present_events(events)
@@ -30,10 +30,10 @@ module API
end
resource :events do
- allow_access_with_scope :read_user, if: -> (request) { request.get? }
+ allow_access_with_scope :read_user, if: ->(request) { request.get? }
desc "List currently authenticated user's events" do
- detail 'This feature was introduced in GitLab 9.3.'
+ detail "This feature was introduced in GitLab 9.3."
success Entities::Event
end
params do
@@ -52,13 +52,13 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID or Username of the user'
+ requires :id, type: String, desc: "The ID or Username of the user"
end
resource :users do
- allow_access_with_scope :read_user, if: -> (request) { request.get? }
+ allow_access_with_scope :read_user, if: ->(request) { request.get? }
- desc 'Get the contribution events of a specified user' do
- detail 'This feature was introduced in GitLab 8.13.'
+ desc "Get the contribution events of a specified user" do
+ detail "This feature was introduced in GitLab 8.13."
success Entities::Event
end
params do
@@ -67,9 +67,9 @@ module API
use :sort_params
end
- get ':id/events' do
+ get ":id/events" do
user = find_user(params[:id])
- not_found!('User') unless user
+ not_found!("User") unless user
events = find_events(user)
@@ -78,7 +78,7 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
desc "List a Project's visible events" do
diff --git a/lib/api/features.rb b/lib/api/features.rb
index 4dc1834c644..3beccec88bf 100644
--- a/lib/api/features.rb
+++ b/lib/api/features.rb
@@ -7,9 +7,9 @@ module API
helpers do
def gate_value(params)
case params[:value]
- when 'true'
+ when "true"
true
- when '0', 'false'
+ when "0", "false"
false
else
params[:value].to_i
@@ -26,7 +26,7 @@ module API
end
resource :features do
- desc 'Get a list of all features' do
+ desc "Get a list of all features" do
success Entities::Feature
end
get do
@@ -35,17 +35,17 @@ module API
present features, with: Entities::Feature, current_user: current_user
end
- desc 'Set the gate value for the given feature' do
+ desc "Set the gate value for the given feature" do
success Entities::Feature
end
params do
- requires :value, type: String, desc: '`true` or `false` to enable/disable, an integer for percentage of time'
- optional :feature_group, type: String, desc: 'A Feature group name'
- optional :user, type: String, desc: 'A GitLab username'
+ requires :value, type: String, desc: "`true` or `false` to enable/disable, an integer for percentage of time"
+ optional :feature_group, type: String, desc: "A Feature group name"
+ optional :user, type: String, desc: "A GitLab username"
optional :group, type: String, desc: "A GitLab group's path, such as 'gitlab-org'"
- optional :project, type: String, desc: 'A projects path, like gitlab-org/gitlab-ce'
+ optional :project, type: String, desc: "A projects path, like gitlab-org/gitlab-ce"
end
- post ':name' do
+ post ":name" do
feature = Feature.get(params[:name])
targets = gate_targets(params)
value = gate_value(params)
@@ -70,8 +70,8 @@ module API
present feature, with: Entities::Feature, current_user: current_user
end
- desc 'Remove the gate value for the given feature'
- delete ':name' do
+ desc "Remove the gate value for the given feature"
+ delete ":name" do
Feature.get(params[:name]).remove
status 204
diff --git a/lib/api/files.rb b/lib/api/files.rb
index ca59d330e1c..c40fd29490e 100644
--- a/lib/api/files.rb
+++ b/lib/api/files.rb
@@ -22,7 +22,7 @@ module API
file_content_encoding: attrs[:encoding],
author_email: attrs[:author_email],
author_name: attrs[:author_name],
- last_commit_sha: attrs[:last_commit_id]
+ last_commit_sha: attrs[:last_commit_id],
}
end
@@ -30,19 +30,19 @@ module API
authorize! :download_code, user_project
@commit = user_project.commit(params[:ref])
- not_found!('Commit') unless @commit
+ not_found!("Commit") unless @commit
@repo = user_project.repository
@blob = @repo.blob_at(@commit.sha, params[:file_path])
- not_found!('File') unless @blob
+ not_found!("File") unless @blob
@blob.load_all_data!
end
def commit_response(attrs)
{
file_path: attrs[:file_path],
- branch: attrs[:branch]
+ branch: attrs[:branch],
}
end
@@ -56,37 +56,37 @@ module API
ref: params[:ref],
blob_id: @blob.id,
commit_id: @commit.id,
- last_commit_id: @repo.last_commit_id_for_path(@commit.sha, params[:file_path])
+ last_commit_id: @repo.last_commit_id_for_path(@commit.sha, params[:file_path]),
}
end
params :simple_file_params do
- requires :file_path, type: String, desc: 'The url encoded path to the file. Ex. lib%2Fclass%2Erb'
- requires :branch, type: String, desc: 'Name of the branch to commit into. To create a new branch, also provide `start_branch`.', allow_blank: false
- requires :commit_message, type: String, allow_blank: false, desc: 'Commit message'
- optional :start_branch, type: String, desc: 'Name of the branch to start the new commit from'
- optional :author_email, type: String, desc: 'The email of the author'
- optional :author_name, type: String, desc: 'The name of the author'
+ requires :file_path, type: String, desc: "The url encoded path to the file. Ex. lib%2Fclass%2Erb"
+ requires :branch, type: String, desc: "Name of the branch to commit into. To create a new branch, also provide `start_branch`.", allow_blank: false
+ requires :commit_message, type: String, allow_blank: false, desc: "Commit message"
+ optional :start_branch, type: String, desc: "Name of the branch to start the new commit from"
+ optional :author_email, type: String, desc: "The email of the author"
+ optional :author_name, type: String, desc: "The name of the author"
end
params :extended_file_params do
use :simple_file_params
- requires :content, type: String, desc: 'File content'
- optional :encoding, type: String, values: %w[base64], desc: 'File encoding'
- optional :last_commit_id, type: String, desc: 'Last known commit id for this file'
+ requires :content, type: String, desc: "File content"
+ optional :encoding, type: String, values: %w[base64], desc: "File encoding"
+ optional :last_commit_id, type: String, desc: "Last known commit id for this file"
end
end
params do
- requires :id, type: String, desc: 'The project ID'
+ requires :id, type: String, desc: "The project ID"
end
resource :projects, requirements: FILE_ENDPOINT_REQUIREMENTS do
- allow_access_with_scope :read_repository, if: -> (request) { request.get? || request.head? }
+ allow_access_with_scope :read_repository, if: ->(request) { request.get? || request.head? }
- desc 'Get raw file metadata from repository'
+ desc "Get raw file metadata from repository"
params do
- requires :file_path, type: String, desc: 'The url encoded path to the file. Ex. lib%2Fclass%2Erb'
- requires :ref, type: String, desc: 'The name of branch, tag or commit', allow_blank: false
+ requires :file_path, type: String, desc: "The url encoded path to the file. Ex. lib%2Fclass%2Erb"
+ requires :ref, type: String, desc: "The name of branch, tag or commit", allow_blank: false
end
head ":id/repository/files/:file_path/raw", requirements: FILE_ENDPOINT_REQUIREMENTS do
assign_file_vars!
@@ -94,10 +94,10 @@ module API
set_http_headers(blob_data)
end
- desc 'Get raw file contents from the repository'
+ desc "Get raw file contents from the repository"
params do
- requires :file_path, type: String, desc: 'The url encoded path to the file. Ex. lib%2Fclass%2Erb'
- requires :ref, type: String, desc: 'The name of branch, tag commit', allow_blank: false
+ requires :file_path, type: String, desc: "The url encoded path to the file. Ex. lib%2Fclass%2Erb"
+ requires :ref, type: String, desc: "The name of branch, tag commit", allow_blank: false
end
get ":id/repository/files/:file_path/raw", requirements: FILE_ENDPOINT_REQUIREMENTS do
assign_file_vars!
@@ -107,10 +107,10 @@ module API
send_git_blob @repo, @blob
end
- desc 'Get file metadata from repository'
+ desc "Get file metadata from repository"
params do
- requires :file_path, type: String, desc: 'The url encoded path to the file. Ex. lib%2Fclass%2Erb'
- requires :ref, type: String, desc: 'The name of branch, tag or commit', allow_blank: false
+ requires :file_path, type: String, desc: "The url encoded path to the file. Ex. lib%2Fclass%2Erb"
+ requires :ref, type: String, desc: "The name of branch, tag or commit", allow_blank: false
end
head ":id/repository/files/:file_path", requirements: FILE_ENDPOINT_REQUIREMENTS do
assign_file_vars!
@@ -118,10 +118,10 @@ module API
set_http_headers(blob_data)
end
- desc 'Get a file from the repository'
+ desc "Get a file from the repository"
params do
- requires :file_path, type: String, desc: 'The url encoded path to the file. Ex. lib%2Fclass%2Erb'
- requires :ref, type: String, desc: 'The name of branch, tag or commit', allow_blank: false
+ requires :file_path, type: String, desc: "The url encoded path to the file. Ex. lib%2Fclass%2Erb"
+ requires :ref, type: String, desc: "The name of branch, tag or commit", allow_blank: false
end
get ":id/repository/files/:file_path", requirements: FILE_ENDPOINT_REQUIREMENTS do
assign_file_vars!
@@ -133,7 +133,7 @@ module API
data.merge(content: Base64.strict_encode64(@blob.data))
end
- desc 'Create new file in repository'
+ desc "Create new file in repository"
params do
use :extended_file_params
end
@@ -151,7 +151,7 @@ module API
end
end
- desc 'Update existing file in repository'
+ desc "Update existing file in repository"
params do
use :extended_file_params
end
@@ -175,7 +175,7 @@ module API
end
end
- desc 'Delete an existing file in repository'
+ desc "Delete an existing file in repository"
params do
use :simple_file_params
end
diff --git a/lib/api/group_boards.rb b/lib/api/group_boards.rb
index 9a20ee8c8b9..0479b877e35 100644
--- a/lib/api/group_boards.rb
+++ b/lib/api/group_boards.rb
@@ -16,65 +16,65 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a group'
+ requires :id, type: String, desc: "The ID of a group"
end
resource :groups, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- segment ':id/boards' do
- desc 'Find a group board' do
- detail 'This feature was introduced in 10.6'
+ segment ":id/boards" do
+ desc "Find a group board" do
+ detail "This feature was introduced in 10.6"
success ::API::Entities::Board
end
- get '/:board_id' do
+ get "/:board_id" do
present board, with: ::API::Entities::Board
end
- desc 'Get all group boards' do
- detail 'This feature was introduced in 10.6'
+ desc "Get all group boards" do
+ detail "This feature was introduced in 10.6"
success Entities::Board
end
params do
use :pagination
end
- get '/' do
+ get "/" do
present paginate(board_parent.boards), with: Entities::Board
end
end
params do
- requires :board_id, type: Integer, desc: 'The ID of a board'
+ requires :board_id, type: Integer, desc: "The ID of a board"
end
- segment ':id/boards/:board_id' do
- desc 'Get the lists of a group board' do
- detail 'Does not include backlog and closed lists. This feature was introduced in 10.6'
+ segment ":id/boards/:board_id" do
+ desc "Get the lists of a group board" do
+ detail "Does not include backlog and closed lists. This feature was introduced in 10.6"
success Entities::List
end
params do
use :pagination
end
- get '/lists' do
+ get "/lists" do
present paginate(board_lists), with: Entities::List
end
- desc 'Get a list of a group board' do
- detail 'This feature was introduced in 10.6'
+ desc "Get a list of a group board" do
+ detail "This feature was introduced in 10.6"
success Entities::List
end
params do
- requires :list_id, type: Integer, desc: 'The ID of a list'
+ requires :list_id, type: Integer, desc: "The ID of a list"
end
- get '/lists/:list_id' do
+ get "/lists/:list_id" do
present board_lists.find(params[:list_id]), with: Entities::List
end
- desc 'Create a new board list' do
- detail 'This feature was introduced in 10.6'
+ desc "Create a new board list" do
+ detail "This feature was introduced in 10.6"
success Entities::List
end
params do
use :list_creation_params
end
- post '/lists' do
+ post "/lists" do
authorize_list_type_resource!
authorize!(:admin_list, user_group)
@@ -82,15 +82,15 @@ module API
create_list
end
- desc 'Moves a board list to a new position' do
- detail 'This feature was introduced in 10.6'
+ desc "Moves a board list to a new position" do
+ detail "This feature was introduced in 10.6"
success Entities::List
end
params do
- requires :list_id, type: Integer, desc: 'The ID of a list'
- requires :position, type: Integer, desc: 'The position of the list'
+ requires :list_id, type: Integer, desc: "The ID of a list"
+ requires :position, type: Integer, desc: "The position of the list"
end
- put '/lists/:list_id' do
+ put "/lists/:list_id" do
list = board_lists.find(params[:list_id])
authorize!(:admin_list, user_group)
@@ -98,12 +98,12 @@ module API
move_list(list)
end
- desc 'Delete a board list' do
- detail 'This feature was introduced in 10.6'
+ desc "Delete a board list" do
+ detail "This feature was introduced in 10.6"
success Entities::List
end
params do
- requires :list_id, type: Integer, desc: 'The ID of a board list'
+ requires :list_id, type: Integer, desc: "The ID of a board list"
end
delete "/lists/:list_id" do
authorize!(:admin_list, user_group)
diff --git a/lib/api/group_labels.rb b/lib/api/group_labels.rb
index 0dbc5f45a68..a78db7efe59 100644
--- a/lib/api/group_labels.rb
+++ b/lib/api/group_labels.rb
@@ -8,54 +8,54 @@ module API
before { authenticate! }
params do
- requires :id, type: String, desc: 'The ID of a group'
+ requires :id, type: String, desc: "The ID of a group"
end
resource :groups, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get all labels of the group' do
- detail 'This feature was added in GitLab 11.8'
+ desc "Get all labels of the group" do
+ detail "This feature was added in GitLab 11.8"
success Entities::GroupLabel
end
params do
use :pagination
end
- get ':id/labels' do
+ get ":id/labels" do
get_labels(user_group, Entities::GroupLabel)
end
- desc 'Create a new label' do
- detail 'This feature was added in GitLab 11.8'
+ desc "Create a new label" do
+ detail "This feature was added in GitLab 11.8"
success Entities::GroupLabel
end
params do
use :label_create_params
end
- post ':id/labels' do
+ post ":id/labels" do
create_label(user_group, Entities::GroupLabel)
end
- desc 'Update an existing label. At least one optional parameter is required.' do
- detail 'This feature was added in GitLab 11.8'
+ desc "Update an existing label. At least one optional parameter is required." do
+ detail "This feature was added in GitLab 11.8"
success Entities::GroupLabel
end
params do
- requires :name, type: String, desc: 'The name of the label to be updated'
- optional :new_name, type: String, desc: 'The new name of the label'
+ requires :name, type: String, desc: "The name of the label to be updated"
+ optional :new_name, type: String, desc: "The new name of the label"
optional :color, type: String, desc: "The new color of the label given in 6-digit hex notation with leading '#' sign (e.g. #FFAABB) or one of the allowed CSS color names"
- optional :description, type: String, desc: 'The new description of label'
+ optional :description, type: String, desc: "The new description of label"
at_least_one_of :new_name, :color, :description
end
- put ':id/labels' do
+ put ":id/labels" do
update_label(user_group, Entities::GroupLabel)
end
- desc 'Delete an existing label' do
- detail 'This feature was added in GitLab 11.8'
+ desc "Delete an existing label" do
+ detail "This feature was added in GitLab 11.8"
success Entities::GroupLabel
end
params do
- requires :name, type: String, desc: 'The name of the label to be deleted'
+ requires :name, type: String, desc: "The name of the label to be deleted"
end
- delete ':id/labels' do
+ delete ":id/labels" do
delete_label(user_group)
end
end
diff --git a/lib/api/group_milestones.rb b/lib/api/group_milestones.rb
index d4287e4a7c4..1fa7889840f 100644
--- a/lib/api/group_milestones.rb
+++ b/lib/api/group_milestones.rb
@@ -10,10 +10,10 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a group'
+ requires :id, type: String, desc: "The ID of a group"
end
resource :groups, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get a list of group milestones' do
+ desc "Get a list of group milestones" do
success Entities::Milestone
end
params do
@@ -23,11 +23,11 @@ module API
list_milestones_for(user_group)
end
- desc 'Get a single group milestone' do
+ desc "Get a single group milestone" do
success Entities::Milestone
end
params do
- requires :milestone_id, type: Integer, desc: 'The ID of a group milestone'
+ requires :milestone_id, type: Integer, desc: "The ID of a group milestone"
end
get ":id/milestones/:milestone_id" do
authorize! :read_group, user_group
@@ -35,11 +35,11 @@ module API
get_milestone_for(user_group)
end
- desc 'Create a new group milestone' do
+ desc "Create a new group milestone" do
success Entities::Milestone
end
params do
- requires :title, type: String, desc: 'The title of the milestone'
+ requires :title, type: String, desc: "The title of the milestone"
use :optional_params
end
post ":id/milestones" do
@@ -48,7 +48,7 @@ module API
create_milestone_for(user_group)
end
- desc 'Update an existing group milestone' do
+ desc "Update an existing group milestone" do
success Entities::Milestone
end
params do
@@ -60,7 +60,7 @@ module API
update_milestone_for(user_group)
end
- desc 'Remove a project milestone'
+ desc "Remove a project milestone"
delete ":id/milestones/:milestone_id" do
authorize! :admin_milestone, user_group
@@ -70,26 +70,26 @@ module API
status(204)
end
- desc 'Get all issues for a single group milestone' do
+ desc "Get all issues for a single group milestone" do
success Entities::IssueBasic
end
params do
- requires :milestone_id, type: Integer, desc: 'The ID of a group milestone'
+ requires :milestone_id, type: Integer, desc: "The ID of a group milestone"
use :pagination
end
get ":id/milestones/:milestone_id/issues" do
milestone_issuables_for(user_group, :issue)
end
- desc 'Get all merge requests for a single group milestone' do
- detail 'This feature was introduced in GitLab 9.'
+ desc "Get all merge requests for a single group milestone" do
+ detail "This feature was introduced in GitLab 9."
success Entities::MergeRequestBasic
end
params do
- requires :milestone_id, type: Integer, desc: 'The ID of a group milestone'
+ requires :milestone_id, type: Integer, desc: "The ID of a group milestone"
use :pagination
end
- get ':id/milestones/:milestone_id/merge_requests' do
+ get ":id/milestones/:milestone_id/merge_requests" do
milestone_issuables_for(user_group, :merge_request)
end
end
diff --git a/lib/api/group_variables.rb b/lib/api/group_variables.rb
index 3f048e0dc56..a45353a907b 100644
--- a/lib/api/group_variables.rb
+++ b/lib/api/group_variables.rb
@@ -8,47 +8,47 @@ module API
before { authorize! :admin_build, user_group }
params do
- requires :id, type: String, desc: 'The ID of a group'
+ requires :id, type: String, desc: "The ID of a group"
end
resource :groups, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get group-level variables' do
+ desc "Get group-level variables" do
success Entities::Variable
end
params do
use :pagination
end
- get ':id/variables' do
+ get ":id/variables" do
variables = user_group.variables
present paginate(variables), with: Entities::Variable
end
- desc 'Get a specific variable from a group' do
+ desc "Get a specific variable from a group" do
success Entities::Variable
end
params do
- requires :key, type: String, desc: 'The key of the variable'
+ requires :key, type: String, desc: "The key of the variable"
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/variables/:key' do
+ get ":id/variables/:key" do
key = params[:key]
variable = user_group.variables.find_by(key: key)
- break not_found!('GroupVariable') unless variable
+ break not_found!("GroupVariable") unless variable
present variable, with: Entities::Variable
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Create a new variable in a group' do
+ desc "Create a new variable in a group" do
success Entities::Variable
end
params do
- requires :key, type: String, desc: 'The key of the variable'
- requires :value, type: String, desc: 'The value of the variable'
- optional :protected, type: String, desc: 'Whether the variable is protected'
+ requires :key, type: String, desc: "The key of the variable"
+ requires :value, type: String, desc: "The value of the variable"
+ optional :protected, type: String, desc: "Whether the variable is protected"
end
- post ':id/variables' do
+ post ":id/variables" do
variable_params = declared_params(include_missing: false)
variable = user_group.variables.create(variable_params)
@@ -60,19 +60,19 @@ module API
end
end
- desc 'Update an existing variable from a group' do
+ desc "Update an existing variable from a group" do
success Entities::Variable
end
params do
- optional :key, type: String, desc: 'The key of the variable'
- optional :value, type: String, desc: 'The value of the variable'
- optional :protected, type: String, desc: 'Whether the variable is protected'
+ optional :key, type: String, desc: "The key of the variable"
+ optional :value, type: String, desc: "The value of the variable"
+ optional :protected, type: String, desc: "Whether the variable is protected"
end
# rubocop: disable CodeReuse/ActiveRecord
- put ':id/variables/:key' do
+ put ":id/variables/:key" do
variable = user_group.variables.find_by(key: params[:key])
- break not_found!('GroupVariable') unless variable
+ break not_found!("GroupVariable") unless variable
variable_params = declared_params(include_missing: false).except(:key)
@@ -84,16 +84,16 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Delete an existing variable from a group' do
+ desc "Delete an existing variable from a group" do
success Entities::Variable
end
params do
- requires :key, type: String, desc: 'The key of the variable'
+ requires :key, type: String, desc: "The key of the variable"
end
# rubocop: disable CodeReuse/ActiveRecord
- delete ':id/variables/:key' do
+ delete ":id/variables/:key" do
variable = user_group.variables.find_by(key: params[:key])
- not_found!('GroupVariable') unless variable
+ not_found!("GroupVariable") unless variable
destroy_conditionally!(variable)
end
diff --git a/lib/api/groups.rb b/lib/api/groups.rb
index 64958ff982a..c8042326cab 100644
--- a/lib/api/groups.rb
+++ b/lib/api/groups.rb
@@ -9,15 +9,16 @@ module API
helpers do
params :optional_params_ce do
- optional :description, type: String, desc: 'The description of the group'
+ optional :description, type: String, desc: "The description of the group"
optional :visibility, type: String,
values: Gitlab::VisibilityLevel.string_values,
default: Gitlab::VisibilityLevel.string_level(
- Gitlab::CurrentSettings.current_application_settings.default_group_visibility),
- desc: 'The visibility of the group'
- optional :lfs_enabled, type: Boolean, desc: 'Enable/disable LFS for the projects in this group'
- optional :request_access_enabled, type: Boolean, desc: 'Allow users to request member access'
- optional :share_with_group_lock, type: Boolean, desc: 'Prevent sharing a project with another group within this group'
+ Gitlab::CurrentSettings.current_application_settings.default_group_visibility
+ ),
+ desc: "The visibility of the group"
+ optional :lfs_enabled, type: Boolean, desc: "Enable/disable LFS for the projects in this group"
+ optional :request_access_enabled, type: Boolean, desc: "Allow users to request member access"
+ optional :share_with_group_lock, type: Boolean, desc: "Prevent sharing a project with another group within this group"
end
params :optional_params do
@@ -25,18 +26,18 @@ module API
end
params :statistics_params do
- optional :statistics, type: Boolean, default: false, desc: 'Include project statistics'
+ optional :statistics, type: Boolean, default: false, desc: "Include project statistics"
end
params :group_list_params do
use :statistics_params
- optional :skip_groups, type: Array[Integer], desc: 'Array of group ids to exclude from list'
- optional :all_available, type: Boolean, desc: 'Show all group that you have access to'
- optional :search, type: String, desc: 'Search for a specific group'
- optional :owned, type: Boolean, default: false, desc: 'Limit by owned by authenticated user'
- optional :order_by, type: String, values: %w[name path id], default: 'name', desc: 'Order by name, path or id'
- optional :sort, type: String, values: %w[asc desc], default: 'asc', desc: 'Sort by asc (ascending) or desc (descending)'
- optional :min_access_level, type: Integer, values: Gitlab::Access.all_values, desc: 'Minimum access level of authenticated user'
+ optional :skip_groups, type: Array[Integer], desc: "Array of group ids to exclude from list"
+ optional :all_available, type: Boolean, desc: "Show all group that you have access to"
+ optional :search, type: String, desc: "Search for a specific group"
+ optional :owned, type: Boolean, default: false, desc: "Limit by owned by authenticated user"
+ optional :order_by, type: String, values: %w[name path id], default: "name", desc: "Order by name, path or id"
+ optional :sort, type: String, values: %w[asc desc], default: "asc", desc: "Sort by asc (ascending) or desc (descending)"
+ optional :min_access_level, type: Integer, values: Gitlab::Access.all_values, desc: "Minimum access level of authenticated user"
use :pagination
end
@@ -50,7 +51,7 @@ module API
groups = GroupsFinder.new(current_user, find_params).execute
groups = groups.search(params[:search]) if params[:search].present?
groups = groups.where.not(id: params[:skip_groups]) if params[:skip_groups].present?
- order_options = { params[:order_by] => params[:sort] }
+ order_options = {params[:order_by] => params[:sort]}
order_options["id"] ||= "asc"
groups = groups.reorder(order_options)
@@ -62,7 +63,7 @@ module API
group = find_group!(params[:id])
options = {
only_owned: !params[:with_shared],
- include_subgroups: params[:include_subgroups]
+ include_subgroups: params[:include_subgroups],
}
projects = GroupProjectsFinder.new(
@@ -81,7 +82,7 @@ module API
options = {
with: Entities::Group,
current_user: current_user,
- statistics: params[:statistics] && current_user.admin?
+ statistics: params[:statistics] && current_user.admin?,
}
groups = groups.with_statistics if options[:statistics]
@@ -94,7 +95,7 @@ module API
resource :groups do
include CustomAttributesEndpoints
- desc 'Get a groups list' do
+ desc "Get a groups list" do
success Entities::Group
end
params do
@@ -106,15 +107,15 @@ module API
present_groups params, groups
end
- desc 'Create a group. Available only for users who can create groups.' do
+ desc "Create a group. Available only for users who can create groups." do
success Entities::Group
end
params do
- requires :name, type: String, desc: 'The name of the group'
- requires :path, type: String, desc: 'The path of the group'
+ requires :name, type: String, desc: "The name of the group"
+ requires :path, type: String, desc: "The path of the group"
if ::Group.supports_nested_objects?
- optional :parent_id, type: Integer, desc: 'The parent group id for creating nested group'
+ optional :parent_id, type: Integer, desc: "The parent group id for creating nested group"
end
use :optional_params
@@ -138,18 +139,18 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a group'
+ requires :id, type: String, desc: "The ID of a group"
end
resource :groups, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Update a group. Available only for users who can administrate groups.' do
+ desc "Update a group. Available only for users who can administrate groups." do
success Entities::Group
end
params do
- optional :name, type: String, desc: 'The name of the group'
- optional :path, type: String, desc: 'The path of the group'
+ optional :name, type: String, desc: "The name of the group"
+ optional :path, type: String, desc: "The path of the group"
use :optional_params
end
- put ':id' do
+ put ":id" do
group = find_group!(params[:id])
authorize! :admin_group, group
@@ -160,19 +161,19 @@ module API
end
end
- desc 'Get a single group, with containing projects.' do
+ desc "Get a single group, with containing projects." do
success Entities::GroupDetail
end
params do
use :with_custom_attributes
- optional :with_projects, type: Boolean, default: true, desc: 'Omit project details'
+ optional :with_projects, type: Boolean, default: true, desc: "Omit project details"
end
get ":id" do
group = find_group!(params[:id])
options = {
with: params[:with_projects] ? Entities::GroupDetail : Entities::Group,
- current_user: current_user
+ current_user: current_user,
}
group, options = with_custom_attributes(group, options)
@@ -180,12 +181,12 @@ module API
present group, options
end
- desc 'Remove a group.'
+ desc "Remove a group."
delete ":id" do
group = find_group!(params[:id])
authorize! :admin_group, group
- Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/46285')
+ Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/46285")
destroy_conditionally!(group) do |group|
::Groups::DestroyService.new(group, current_user).async_execute
end
@@ -193,26 +194,26 @@ module API
accepted!
end
- desc 'Get a list of projects in this group.' do
+ desc "Get a list of projects in this group." do
success Entities::Project
end
params do
- optional :archived, type: Boolean, default: false, desc: 'Limit by archived status'
+ optional :archived, type: Boolean, default: false, desc: "Limit by archived status"
optional :visibility, type: String, values: Gitlab::VisibilityLevel.string_values,
- desc: 'Limit by visibility'
- optional :search, type: String, desc: 'Return list of authorized projects matching the search criteria'
+ desc: "Limit by visibility"
+ optional :search, type: String, desc: "Return list of authorized projects matching the search criteria"
optional :order_by, type: String, values: %w[id name path created_at updated_at last_activity_at],
- default: 'created_at', desc: 'Return projects ordered by field'
- optional :sort, type: String, values: %w[asc desc], default: 'desc',
- desc: 'Return projects sorted in ascending and descending order'
+ default: "created_at", desc: "Return projects ordered by field"
+ optional :sort, type: String, values: %w[asc desc], default: "desc",
+ desc: "Return projects sorted in ascending and descending order"
optional :simple, type: Boolean, default: false,
- desc: 'Return only the ID, URL, name, and path of each project'
- optional :owned, type: Boolean, default: false, desc: 'Limit by owned by authenticated user'
- optional :starred, type: Boolean, default: false, desc: 'Limit by starred status'
- optional :with_issues_enabled, type: Boolean, default: false, desc: 'Limit by enabled issues feature'
- optional :with_merge_requests_enabled, type: Boolean, default: false, desc: 'Limit by enabled merge requests feature'
- optional :with_shared, type: Boolean, default: true, desc: 'Include projects shared to this group'
- optional :include_subgroups, type: Boolean, default: false, desc: 'Includes projects in subgroups of this group'
+ desc: "Return only the ID, URL, name, and path of each project"
+ optional :owned, type: Boolean, default: false, desc: "Limit by owned by authenticated user"
+ optional :starred, type: Boolean, default: false, desc: "Limit by starred status"
+ optional :with_issues_enabled, type: Boolean, default: false, desc: "Limit by enabled issues feature"
+ optional :with_merge_requests_enabled, type: Boolean, default: false, desc: "Limit by enabled merge requests feature"
+ optional :with_shared, type: Boolean, default: true, desc: "Include projects shared to this group"
+ optional :include_subgroups, type: Boolean, default: false, desc: "Includes projects in subgroups of this group"
use :pagination
use :with_custom_attributes
@@ -222,7 +223,7 @@ module API
options = {
with: params[:simple] ? Entities::BasicProjectDetails : Entities::Project,
- current_user: current_user
+ current_user: current_user,
}
projects, options = with_custom_attributes(projects, options)
@@ -230,7 +231,7 @@ module API
present options[:with].prepare_relation(projects), options
end
- desc 'Get a list of subgroups in this group.' do
+ desc "Get a list of subgroups in this group." do
success Entities::Group
end
params do
@@ -242,13 +243,13 @@ module API
present_groups params, groups
end
- desc 'Transfer a project to the group namespace. Available only for admin.' do
+ desc "Transfer a project to the group namespace. Available only for admin." do
success Entities::GroupDetail
end
params do
- requires :project_id, type: String, desc: 'The ID or path of the project'
+ requires :project_id, type: String, desc: "The ID or path of the project"
end
- post ":id/projects/:project_id", requirements: { project_id: /.+/ } do
+ post ":id/projects/:project_id", requirements: {project_id: /.+/} do
authenticated_as_admin!
group = find_group!(params[:id])
project = find_project!(params[:project_id])
diff --git a/lib/api/helpers.rb b/lib/api/helpers.rb
index 54cd4cd9cdb..596c7e8b534 100644
--- a/lib/api/helpers.rb
+++ b/lib/api/helpers.rb
@@ -5,20 +5,24 @@ module API
include Gitlab::Utils
include Helpers::Pagination
- SUDO_HEADER = "HTTP_SUDO".freeze
+ SUDO_HEADER = "HTTP_SUDO"
SUDO_PARAM = :sudo
- API_USER_ENV = 'gitlab.api.user'.freeze
+ API_USER_ENV = "gitlab.api.user"
def declared_params(options = {})
- options = { include_parent_namespaces: false }.merge(options)
+ options = {include_parent_namespaces: false}.merge(options)
declared(params, options).to_h.symbolize_keys
end
def check_unmodified_since!(last_modified)
- if_unmodified_since = Time.parse(headers['If-Unmodified-Since']) rescue nil
+ if_unmodified_since = begin
+ Time.parse(headers["If-Unmodified-Since"])
+ rescue
+ nil
+ end
if if_unmodified_since && last_modified && last_modified > if_unmodified_since
- render_api_error!('412 Precondition Failed', 412)
+ render_api_error!("412 Precondition Failed", 412)
end
end
@@ -59,7 +63,7 @@ module API
# rubocop:enable Gitlab/ModuleWithInstanceVariables
def save_current_user_in_env(user)
- env[API_USER_ENV] = { user_id: user.id, username: user.username }
+ env[API_USER_ENV] = {user_id: user.id, username: user.username}
end
def sudo?
@@ -81,16 +85,17 @@ module API
def wiki_page
page = ProjectWiki.new(user_project, current_user).find_page(params[:slug])
- page || not_found!('Wiki Page')
+ page || not_found!("Wiki Page")
end
def available_labels_for(label_parent, include_ancestor_groups: true)
- search_params = { include_ancestor_groups: include_ancestor_groups }
+ search_params = {include_ancestor_groups: include_ancestor_groups}
if label_parent.is_a?(Project)
search_params[:project_id] = label_parent.id
else
- search_params.merge!(group_id: label_parent.id, only_group_labels: true)
+ search_params[:group_id] = label_parent.id
+ search_params[:only_group_labels] = true
end
LabelsFinder.new(current_user, search_params).execute
@@ -118,13 +123,13 @@ module API
if can?(current_user, :read_project, project)
project
else
- not_found!('Project')
+ not_found!("Project")
end
end
# rubocop: disable CodeReuse/ActiveRecord
def find_group(id)
- if id.to_s =~ /^\d+$/
+ if /^\d+$/.match?(id.to_s)
Group.find_by(id: id)
else
Group.find_by_full_path(id)
@@ -138,13 +143,13 @@ module API
if can?(current_user, :read_group, group)
group
else
- not_found!('Group')
+ not_found!("Group")
end
end
# rubocop: disable CodeReuse/ActiveRecord
def find_namespace(id)
- if id.to_s =~ /^\d+$/
+ if /^\d+$/.match?(id.to_s)
Namespace.find_by(id: id)
else
Namespace.find_by_full_path(id)
@@ -158,15 +163,15 @@ module API
if can?(current_user, :read_namespace, namespace)
namespace
else
- not_found!('Namespace')
+ not_found!("Namespace")
end
end
def find_branch!(branch_name)
if Gitlab::GitRefValidator.validate(branch_name)
- user_project.repository.find_branch(branch_name) || not_found!('Branch')
+ user_project.repository.find_branch(branch_name) || not_found!("Branch")
else
- render_api_error!('The branch refname is invalid', 400)
+ render_api_error!("The branch refname is invalid", 400)
end
end
@@ -187,7 +192,7 @@ module API
end
def find_project_snippet(id)
- finder_params = { project: user_project }
+ finder_params = {project: user_project}
SnippetsFinder.new(current_user, finder_params).find(id)
end
@@ -212,7 +217,7 @@ module API
end
def authenticate_by_gitlab_shell_token!
- input = params['secret_token'].try(:chomp)
+ input = params["secret_token"].try(:chomp)
unless Devise.secure_compare(secret_token, input)
unauthorized!
end
@@ -249,8 +254,8 @@ module API
end
def require_gitlab_workhorse!
- unless env['HTTP_GITLAB_WORKHORSE'].present?
- forbidden!('Request should be executed via GitLab Workhorse')
+ unless env["HTTP_GITLAB_WORKHORSE"].present?
+ forbidden!("Request should be executed via GitLab Workhorse")
end
end
@@ -300,72 +305,72 @@ module API
end
def order_options_with_tie_breaker
- order_options = { params[:order_by] => params[:sort] }
- order_options['id'] ||= 'desc'
+ order_options = {params[:order_by] => params[:sort]}
+ order_options["id"] ||= "desc"
order_options
end
# error helpers
def forbidden!(reason = nil)
- message = ['403 Forbidden']
+ message = ["403 Forbidden"]
message << " - #{reason}" if reason
- render_api_error!(message.join(' '), 403)
+ render_api_error!(message.join(" "), 403)
end
def bad_request!(attribute)
message = ["400 (Bad request)"]
message << "\"" + attribute.to_s + "\" not given" if attribute
- render_api_error!(message.join(' '), 400)
+ render_api_error!(message.join(" "), 400)
end
def not_found!(resource = nil)
message = ["404"]
message << resource if resource
message << "Not Found"
- render_api_error!(message.join(' '), 404)
+ render_api_error!(message.join(" "), 404)
end
def unauthorized!
- render_api_error!('401 Unauthorized', 401)
+ render_api_error!("401 Unauthorized", 401)
end
def not_allowed!
- render_api_error!('405 Method Not Allowed', 405)
+ render_api_error!("405 Method Not Allowed", 405)
end
def conflict!(message = nil)
- render_api_error!(message || '409 Conflict', 409)
+ render_api_error!(message || "409 Conflict", 409)
end
def file_to_large!
- render_api_error!('413 Request Entity Too Large', 413)
+ render_api_error!("413 Request Entity Too Large", 413)
end
def not_modified!
- render_api_error!('304 Not Modified', 304)
+ render_api_error!("304 Not Modified", 304)
end
def no_content!
- render_api_error!('204 No Content', 204)
+ render_api_error!("204 No Content", 204)
end
def accepted!
- render_api_error!('202 Accepted', 202)
+ render_api_error!("202 Accepted", 202)
end
def render_validation_error!(model)
if model.errors.any?
- render_api_error!(model.errors.messages || '400 Bad Request', 400)
+ render_api_error!(model.errors.messages || "400 Bad Request", 400)
end
end
def render_spam_error!
- render_api_error!({ error: 'Spam detected' }, 400)
+ render_api_error!({error: "Spam detected"}, 400)
end
def render_api_error!(message, status)
- error!({ 'message' => message }, status, header)
+ error!({"message" => message}, status, header)
end
def handle_api_exception(exception)
@@ -389,10 +394,10 @@ module API
if Rails.env.test?
message
else
- '500 Internal Server Error'
+ "500 Internal Server Error"
end
- rack_response({ 'message' => response_message }.to_json, 500)
+ rack_response({"message" => response_message}.to_json, 500)
end
# project helpers
@@ -404,7 +409,7 @@ module API
# rubocop: enable CodeReuse/ActiveRecord
def project_finder_params
- finder_params = { without_deleted: true }
+ finder_params = {without_deleted: true}
finder_params[:owned] = true if params[:owned].present?
finder_params[:non_public] = true if params[:membership].present?
finder_params[:starred] = true if params[:starred].present?
@@ -419,16 +424,16 @@ module API
# file helpers
- def present_disk_file!(path, filename, content_type = 'application/octet-stream')
+ def present_disk_file!(path, filename, content_type = "application/octet-stream")
filename ||= File.basename(path)
- header['Content-Disposition'] = ::Gitlab::ContentDisposition.format(disposition: 'attachment', filename: filename)
- header['Content-Transfer-Encoding'] = 'binary'
+ header["Content-Disposition"] = ::Gitlab::ContentDisposition.format(disposition: "attachment", filename: filename)
+ header["Content-Transfer-Encoding"] = "binary"
content_type content_type
# Support download acceleration
- case headers['X-Sendfile-Type']
- when 'X-Sendfile'
- header['X-Sendfile'] = path
+ case headers["X-Sendfile-Type"]
+ when "X-Sendfile"
+ header["X-Sendfile"] = path
body
else
file path
@@ -469,11 +474,11 @@ module API
unauthorized! unless initial_current_user
unless initial_current_user.admin?
- forbidden!('Must be admin to use sudo')
+ forbidden!("Must be admin to use sudo")
end
unless access_token
- forbidden!('Must be authenticated using an OAuth or Personal Access Token to use sudo')
+ forbidden!("Must be authenticated using an OAuth or Personal Access Token to use sudo")
end
validate_access_token!(scopes: [:sudo])
@@ -493,9 +498,9 @@ module API
end
def send_git_blob(repository, blob)
- env['api.format'] = :txt
- content_type 'text/plain'
- header['Content-Disposition'] = ::Gitlab::ContentDisposition.format(disposition: 'inline', filename: blob.name)
+ env["api.format"] = :txt
+ content_type "text/plain"
+ header["Content-Disposition"] = ::Gitlab::ContentDisposition.format(disposition: "inline", filename: blob.name)
# Let Workhorse examine the content and determine the better content disposition
header[Gitlab::Workhorse::DETECT_HEADER] = "true"
@@ -515,8 +520,8 @@ module API
# `request`. We workaround this by defining methods that returns the right
# values.
def define_params_for_grape_middleware
- self.define_singleton_method(:request) { ActionDispatch::Request.new(env) }
- self.define_singleton_method(:params) { request.params.symbolize_keys }
+ define_singleton_method(:request) { ActionDispatch::Request.new(env) }
+ define_singleton_method(:params) { request.params.symbolize_keys }
end
# We could get a Grape or a standard Ruby exception. We should only report anything that
@@ -528,7 +533,7 @@ module API
end
def archived_param
- return 'only' if params[:archived]
+ return "only" if params[:archived]
params[:archived]
end
diff --git a/lib/api/helpers/badges_helpers.rb b/lib/api/helpers/badges_helpers.rb
index 46ce5b4e7b5..2f63a6ac37e 100644
--- a/lib/api/helpers/badges_helpers.rb
+++ b/lib/api/helpers/badges_helpers.rb
@@ -18,12 +18,12 @@ module API
def badge_source_params(source)
project = if source.is_a?(Project)
- source
- else
- GroupProjectsFinder.new(group: source, current_user: current_user).execute.first
- end
+ source
+ else
+ GroupProjectsFinder.new(group: source, current_user: current_user).execute.first
+ end
- { project: project }
+ {project: project}
end
end
end
diff --git a/lib/api/helpers/custom_attributes.rb b/lib/api/helpers/custom_attributes.rb
index 88208226c40..7e5775f115c 100644
--- a/lib/api/helpers/custom_attributes.rb
+++ b/lib/api/helpers/custom_attributes.rb
@@ -8,10 +8,10 @@ module API
included do
helpers do
params :with_custom_attributes do
- optional :with_custom_attributes, type: Boolean, default: false, desc: 'Include custom attributes in the response'
+ optional :with_custom_attributes, type: Boolean, default: false, desc: "Include custom attributes in the response"
optional :custom_attributes, type: Hash,
- desc: 'Filter with custom attributes'
+ desc: "Filter with custom attributes"
end
# rubocop: disable CodeReuse/ActiveRecord
diff --git a/lib/api/helpers/custom_validators.rb b/lib/api/helpers/custom_validators.rb
index 1058f4e8a5e..6c62501cbc9 100644
--- a/lib/api/helpers/custom_validators.rb
+++ b/lib/api/helpers/custom_validators.rb
@@ -16,7 +16,7 @@ module API
value = params[attr_name]
return if value.is_a?(Integer) ||
- [IssuableFinder::FILTER_NONE, IssuableFinder::FILTER_ANY].include?(value.to_s.downcase)
+ [IssuableFinder::FILTER_NONE, IssuableFinder::FILTER_ANY].include?(value.to_s.downcase)
raise Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)],
message: "should be an integer, 'None' or 'Any'"
diff --git a/lib/api/helpers/headers_helpers.rb b/lib/api/helpers/headers_helpers.rb
index 7553af9d156..3af44a230b3 100644
--- a/lib/api/helpers/headers_helpers.rb
+++ b/lib/api/helpers/headers_helpers.rb
@@ -9,7 +9,7 @@ module API
raise ArgumentError.new("Header value should be a string")
end
- header "X-Gitlab-#{key.to_s.split('_').collect(&:capitalize).join('-')}", value.to_s
+ header "X-Gitlab-#{key.to_s.split("_").collect(&:capitalize).join("-")}", value.to_s
end
end
end
diff --git a/lib/api/helpers/internal_helpers.rb b/lib/api/helpers/internal_helpers.rb
index fe78049af87..1e5e22417c9 100644
--- a/lib/api/helpers/internal_helpers.rb
+++ b/lib/api/helpers/internal_helpers.rb
@@ -19,7 +19,7 @@ module API
[
:read_project,
:download_code,
- :push_code
+ :push_code,
]
end
@@ -34,7 +34,7 @@ module API
def log_user_activity(actor)
commands = Gitlab::GitAccess::DOWNLOAD_COMMANDS
- ::Users::ActivityService.new(actor, 'Git SSH').execute if commands.include?(params[:action])
+ ::Users::ActivityService.new(actor, "Git SSH").execute if commands.include?(params[:action])
end
def merge_request_urls
@@ -44,7 +44,7 @@ module API
def redis_ping
result = Gitlab::Redis::SharedState.with { |redis| redis.ping }
- result == 'PONG'
+ result == "PONG"
rescue => e
Rails.logger.warn("GitLab: An unexpected error occurred in pinging to Redis: #{e}")
false
@@ -106,7 +106,7 @@ module API
{
repository: repository.gitaly_repository,
address: Gitlab::GitalyClient.address(project.repository_storage),
- token: Gitlab::GitalyClient.token(project.repository_storage)
+ token: Gitlab::GitalyClient.token(project.repository_storage),
}
end
end
diff --git a/lib/api/helpers/label_helpers.rb b/lib/api/helpers/label_helpers.rb
index c11e7d614ab..69cdc25aa00 100644
--- a/lib/api/helpers/label_helpers.rb
+++ b/lib/api/helpers/label_helpers.rb
@@ -6,16 +6,16 @@ module API
extend Grape::API::Helpers
params :label_create_params do
- requires :name, type: String, desc: 'The name of the label to be created'
+ requires :name, type: String, desc: "The name of the label to be created"
requires :color, type: String, desc: "The color of the label given in 6-digit hex notation with leading '#' sign (e.g. #FFAABB) or one of the allowed CSS color names"
- optional :description, type: String, desc: 'The description of label to be created'
+ optional :description, type: String, desc: "The description of label to be created"
end
def find_label(parent, id, include_ancestor_groups: true)
labels = available_labels_for(parent, include_ancestor_groups: include_ancestor_groups)
label = labels.find_by_id(id) || labels.find_by_title(id)
- label || not_found!('Label')
+ label || not_found!("Label")
end
def get_labels(parent, entity)
@@ -26,7 +26,7 @@ module API
authorize! :admin_label, parent
label = available_labels_for(parent).find_by_title(params[:name])
- conflict!('Label already exists') if label
+ conflict!("Label already exists") if label
priority = params.delete(:priority)
label_params = declared_params(include_missing: false)
diff --git a/lib/api/helpers/members_helpers.rb b/lib/api/helpers/members_helpers.rb
index 73d58ee7f37..93b14278fb4 100644
--- a/lib/api/helpers/members_helpers.rb
+++ b/lib/api/helpers/members_helpers.rb
@@ -14,7 +14,7 @@ module API
end
def find_all_members(source_type, source)
- members = source_type == 'project' ? find_all_members_for_project(source) : find_all_members_for_group(source)
+ members = source_type == "project" ? find_all_members_for_project(source) : find_all_members_for_group(source)
members.non_invite
.non_request
end
@@ -28,7 +28,7 @@ module API
.compact
Member.includes(:user)
.joins(user: :project_authorizations)
- .where(project_authorizations: { project_id: project.id })
+ .where(project_authorizations: {project_id: project.id})
.where(source_id: source_ids)
end
# rubocop: enable CodeReuse/ActiveRecord
@@ -38,7 +38,7 @@ module API
source_ids = group.self_and_ancestors.pluck(:id)
Member.includes(:user)
.where(source_id: source_ids)
- .where(source_type: 'Namespace')
+ .where(source_type: "Namespace")
end
# rubocop: enable CodeReuse/ActiveRecord
end
diff --git a/lib/api/helpers/notes_helpers.rb b/lib/api/helpers/notes_helpers.rb
index 216b2c45741..0d8aeb30d6a 100644
--- a/lib/api/helpers/notes_helpers.rb
+++ b/lib/api/helpers/notes_helpers.rb
@@ -9,7 +9,7 @@ module API
authorize! :admin_note, note
opts = {
- note: params[:body]
+ note: params[:body],
}
parent = noteable_parent(noteable)
project = parent if parent.is_a?(Project)
diff --git a/lib/api/helpers/pagination.rb b/lib/api/helpers/pagination.rb
index d00e61678b5..a125020d6eb 100644
--- a/lib/api/helpers/pagination.rb
+++ b/lib/api/helpers/pagination.rb
@@ -4,11 +4,11 @@ module API
module Helpers
module Pagination
def paginate(relation)
- strategy = if params[:pagination] == 'keyset' && Feature.enabled?('api_keyset_pagination')
- KeysetPaginationStrategy
- else
- DefaultPaginationStrategy
- end
+ strategy = if params[:pagination] == "keyset" && Feature.enabled?("api_keyset_pagination")
+ KeysetPaginationStrategy
+ else
+ DefaultPaginationStrategy
+ end
strategy.new(self).paginate(relation)
end
@@ -66,12 +66,12 @@ module API
# Sort direction (`:asc` or `:desc`)
def sort
@sort ||= if order_by_primary_key?
- # Default order is by id DESC
- :desc
- else
- # API defaults to DESC order if param `sort` not present
- request_context.params[:sort]&.to_sym || :desc
- end
+ # Default order is by id DESC
+ :desc
+ else
+ # API defaults to DESC order if param `sort` not present
+ request_context.params[:sort]&.to_sym || :desc
+ end
end
# Do we only sort by primary key?
@@ -100,9 +100,9 @@ module API
# All values present in request parameters that correspond to #keys.
def values
- @values ||= keys.map do |key|
+ @values ||= keys.map { |key|
request_context.params["ks_prev_#{key}".to_sym]
- end
+ }
end
# All keys relevant to pagination.
@@ -151,30 +151,30 @@ module API
return nil if fields.empty?
- placeholder = fields.map { '?' }
+ placeholder = fields.map { "?" }
comp = if pagination.sort_ascending?
- '>'
- else
- '<'
- end
+ ">"
+ else
+ "<"
+ end
[
# Row value comparison:
# (A, B) < (a, b) <=> (A < a) OR (A = a AND B < b)
# <=> A <= a AND ((A < a) OR (A = a AND B < b))
- "(#{fields.keys.join(',')}) #{comp} (#{placeholder.join(',')})",
- *fields.values
+ "(#{fields.keys.join(",")}) #{comp} (#{placeholder.join(",")})",
+ *fields.values,
]
end
def add_default_pagination_headers
- header 'X-Per-Page', per_page.to_s
+ header "X-Per-Page", per_page.to_s
end
def add_navigation_links(next_page_params)
- header 'X-Next-Page', page_href(next_page_params)
- header 'Link', link_for('next', next_page_params)
+ header "X-Next-Page", page_href(next_page_params)
+ header "Link", link_for("next", next_page_params)
end
def link_for(rel, next_page_params)
@@ -220,16 +220,16 @@ module API
end
def add_pagination_headers(paginated_data)
- header 'X-Per-Page', paginated_data.limit_value.to_s
- header 'X-Page', paginated_data.current_page.to_s
- header 'X-Next-Page', paginated_data.next_page.to_s
- header 'X-Prev-Page', paginated_data.prev_page.to_s
- header 'Link', pagination_links(paginated_data)
+ header "X-Per-Page", paginated_data.limit_value.to_s
+ header "X-Page", paginated_data.current_page.to_s
+ header "X-Next-Page", paginated_data.next_page.to_s
+ header "X-Prev-Page", paginated_data.prev_page.to_s
+ header "Link", pagination_links(paginated_data)
return if data_without_counts?(paginated_data)
- header 'X-Total', paginated_data.total_count.to_s
- header 'X-Total-Pages', total_pages(paginated_data).to_s
+ header "X-Total", paginated_data.total_count.to_s
+ header "X-Total-Pages", total_pages(paginated_data).to_s
end
def pagination_links(paginated_data)
@@ -239,7 +239,7 @@ module API
links << %(<#{page_href(page: 1)}>; rel="first")
links << %(<#{page_href(page: total_pages(paginated_data))}>; rel="last") unless data_without_counts?(paginated_data)
- end.join(', ')
+ end.join(", ")
end
def total_pages(paginated_data)
diff --git a/lib/api/helpers/projects_helpers.rb b/lib/api/helpers/projects_helpers.rb
index e6a72b949f9..07eb7f4a5d7 100644
--- a/lib/api/helpers/projects_helpers.rb
+++ b/lib/api/helpers/projects_helpers.rb
@@ -8,26 +8,26 @@ module API
included do
helpers do
params :optional_project_params_ce do
- optional :description, type: String, desc: 'The description of the project'
- optional :ci_config_path, type: String, desc: 'The path to CI config file. Defaults to `.gitlab-ci.yml`'
- optional :issues_enabled, type: Boolean, desc: 'Flag indication if the issue tracker is enabled'
- optional :merge_requests_enabled, type: Boolean, desc: 'Flag indication if merge requests are enabled'
- optional :wiki_enabled, type: Boolean, desc: 'Flag indication if the wiki is enabled'
- optional :jobs_enabled, type: Boolean, desc: 'Flag indication if jobs are enabled'
- optional :snippets_enabled, type: Boolean, desc: 'Flag indication if snippets are enabled'
- optional :shared_runners_enabled, type: Boolean, desc: 'Flag indication if shared runners are enabled for that project'
- optional :resolve_outdated_diff_discussions, type: Boolean, desc: 'Automatically resolve merge request diffs discussions on lines changed with a push'
- optional :container_registry_enabled, type: Boolean, desc: 'Flag indication if the container registry is enabled for that project'
- optional :lfs_enabled, type: Boolean, desc: 'Flag indication if Git LFS is enabled for that project'
- optional :visibility, type: String, values: Gitlab::VisibilityLevel.string_values, desc: 'The visibility of the project.'
- optional :public_builds, type: Boolean, desc: 'Perform public builds'
- optional :request_access_enabled, type: Boolean, desc: 'Allow users to request member access'
- optional :only_allow_merge_if_pipeline_succeeds, type: Boolean, desc: 'Only allow to merge if builds succeed'
- optional :only_allow_merge_if_all_discussions_are_resolved, type: Boolean, desc: 'Only allow to merge if all discussions are resolved'
- optional :tag_list, type: Array[String], desc: 'The list of tags for a project'
- optional :avatar, type: File, desc: 'Avatar image for project'
- optional :printing_merge_request_link_enabled, type: Boolean, desc: 'Show link to create/view merge request when pushing from the command line'
- optional :merge_method, type: String, values: %w(ff rebase_merge merge), desc: 'The merge method used when merging merge requests'
+ optional :description, type: String, desc: "The description of the project"
+ optional :ci_config_path, type: String, desc: "The path to CI config file. Defaults to `.gitlab-ci.yml`"
+ optional :issues_enabled, type: Boolean, desc: "Flag indication if the issue tracker is enabled"
+ optional :merge_requests_enabled, type: Boolean, desc: "Flag indication if merge requests are enabled"
+ optional :wiki_enabled, type: Boolean, desc: "Flag indication if the wiki is enabled"
+ optional :jobs_enabled, type: Boolean, desc: "Flag indication if jobs are enabled"
+ optional :snippets_enabled, type: Boolean, desc: "Flag indication if snippets are enabled"
+ optional :shared_runners_enabled, type: Boolean, desc: "Flag indication if shared runners are enabled for that project"
+ optional :resolve_outdated_diff_discussions, type: Boolean, desc: "Automatically resolve merge request diffs discussions on lines changed with a push"
+ optional :container_registry_enabled, type: Boolean, desc: "Flag indication if the container registry is enabled for that project"
+ optional :lfs_enabled, type: Boolean, desc: "Flag indication if Git LFS is enabled for that project"
+ optional :visibility, type: String, values: Gitlab::VisibilityLevel.string_values, desc: "The visibility of the project."
+ optional :public_builds, type: Boolean, desc: "Perform public builds"
+ optional :request_access_enabled, type: Boolean, desc: "Allow users to request member access"
+ optional :only_allow_merge_if_pipeline_succeeds, type: Boolean, desc: "Only allow to merge if builds succeed"
+ optional :only_allow_merge_if_all_discussions_are_resolved, type: Boolean, desc: "Only allow to merge if all discussions are resolved"
+ optional :tag_list, type: Array[String], desc: "The list of tags for a project"
+ optional :avatar, type: File, desc: "Avatar image for project"
+ optional :printing_merge_request_link_enabled, type: Boolean, desc: "Show link to create/view merge request when pushing from the command line"
+ optional :merge_method, type: String, values: %w[ff rebase_merge merge], desc: "The merge method used when merging merge requests"
optional :initialize_with_readme, type: Boolean, desc: "Initialize a project with a README.md"
end
diff --git a/lib/api/helpers/related_resources_helpers.rb b/lib/api/helpers/related_resources_helpers.rb
index 793ae11b41d..7c4934da73b 100644
--- a/lib/api/helpers/related_resources_helpers.rb
+++ b/lib/api/helpers/related_resources_helpers.rb
@@ -20,7 +20,7 @@ module API
# Using a blank component at the beginning of the join we ensure
# that the resulted path will start with '/'. If the resulted path
# does not start with '/', URI::Generic#build will fail
- path_with_script_name = File.join('', [script_name, path].select(&:present?))
+ path_with_script_name = File.join("", [script_name, path].select(&:present?))
URI::Generic.build(scheme: protocol, host: host, port: port, path: path_with_script_name).to_s
end
diff --git a/lib/api/helpers/runner.rb b/lib/api/helpers/runner.rb
index ff73a49d5e8..4afa8183d89 100644
--- a/lib/api/helpers/runner.rb
+++ b/lib/api/helpers/runner.rb
@@ -3,12 +3,12 @@
module API
module Helpers
module Runner
- JOB_TOKEN_HEADER = 'HTTP_JOB_TOKEN'.freeze
+ JOB_TOKEN_HEADER = "HTTP_JOB_TOKEN"
JOB_TOKEN_PARAM = :token
def runner_registration_token_valid?
ActiveSupport::SecurityUtils.variable_size_secure_compare(params[:token],
- Gitlab::CurrentSettings.runners_registration_token)
+ Gitlab::CurrentSettings.runners_registration_token)
end
def authenticate_runner!
@@ -19,14 +19,14 @@ module API
end
def get_runner_details_from_request
- return get_runner_ip unless params['info'].present?
+ return get_runner_ip unless params["info"].present?
- attributes_for_keys(%w(name version revision platform architecture), params['info'])
+ attributes_for_keys(%w[name version revision platform architecture], params["info"])
.merge(get_runner_ip)
end
def get_runner_ip
- { ip_address: env["action_dispatch.remote_ip"].to_s || request.ip }
+ {ip_address: env["action_dispatch.remote_ip"].to_s || request.ip}
end
def current_runner
@@ -39,8 +39,8 @@ module API
yield if block_given?
project = job.project
- forbidden!('Project has been deleted!') if project.nil? || project.pending_delete?
- forbidden!('Job has been erased!') if job.erased?
+ forbidden!("Project has been deleted!") if project.nil? || project.pending_delete?
+ forbidden!("Job has been erased!") if job.erased?
end
def authenticate_job!
@@ -63,7 +63,7 @@ module API
end
def job_forbidden!(job, reason)
- header 'Job-Status', job.status
+ header "Job-Status", job.status
forbidden!(reason)
end
end
diff --git a/lib/api/helpers/version.rb b/lib/api/helpers/version.rb
index 7f53094e90c..2a80d5e71f5 100644
--- a/lib/api/helpers/version.rb
+++ b/lib/api/helpers/version.rb
@@ -9,12 +9,12 @@ module API
@version = version.to_s
unless API.versions.include?(version)
- raise ArgumentError, 'Unknown API version!'
+ raise ArgumentError, "Unknown API version!"
end
end
def root_path
- File.join('/', API.prefix.to_s, @version)
+ File.join("/", API.prefix.to_s, @version)
end
def root_url
diff --git a/lib/api/import_github.rb b/lib/api/import_github.rb
index bb4e536cf57..1638a9914b3 100644
--- a/lib/api/import_github.rb
+++ b/lib/api/import_github.rb
@@ -10,7 +10,7 @@ module API
end
def access_params
- { github_access_token: params[:personal_access_token] }
+ {github_access_token: params[:personal_access_token]}
end
def client_options
@@ -22,24 +22,24 @@ module API
end
end
- desc 'Import a GitHub project' do
- detail 'This feature was introduced in GitLab 11.3.4.'
+ desc "Import a GitHub project" do
+ detail "This feature was introduced in GitLab 11.3.4."
success Entities::ProjectEntity
end
params do
- requires :personal_access_token, type: String, desc: 'GitHub personal access token'
- requires :repo_id, type: Integer, desc: 'GitHub repository ID'
- optional :new_name, type: String, desc: 'New repo name'
- requires :target_namespace, type: String, desc: 'Namespace to import repo into'
+ requires :personal_access_token, type: String, desc: "GitHub personal access token"
+ requires :repo_id, type: Integer, desc: "GitHub repository ID"
+ optional :new_name, type: String, desc: "New repo name"
+ requires :target_namespace, type: String, desc: "Namespace to import repo into"
end
- post 'import/github' do
+ post "import/github" do
result = Import::GithubService.new(client, current_user, params).execute(access_params, provider)
if result[:status] == :success
present ProjectSerializer.new.represent(result[:project])
else
status result[:http_status]
- { errors: result[:message] }
+ {errors: result[:message]}
end
end
end
diff --git a/lib/api/internal.rb b/lib/api/internal.rb
index 70b32f7d758..88183d7f10a 100644
--- a/lib/api/internal.rb
+++ b/lib/api/internal.rb
@@ -8,16 +8,16 @@ module API
helpers ::API::Helpers::InternalHelpers
helpers ::Gitlab::Identifier
- UNKNOWN_CHECK_RESULT_ERROR = 'Unknown check result'.freeze
+ UNKNOWN_CHECK_RESULT_ERROR = "Unknown check result"
helpers do
def response_with_status(code: 200, success: true, message: nil, **extra_options)
status code
- { status: success, message: message }.merge(extra_options).compact
+ {status: success, message: message}.merge(extra_options).compact
end
end
- namespace 'internal' do
+ namespace "internal" do
# Check if git command is allowed for project
#
# Params:
@@ -84,9 +84,9 @@ module API
# This repository_path is a bogus value but gitlab-shell still requires
# its presence. https://gitlab.com/gitlab-org/gitlab-shell/issues/135
- repository_path: '/',
+ repository_path: "/",
- gitaly: gitaly_payload(params[:action])
+ gitaly: gitaly_payload(params[:action]),
}
# Custom option for git-receive-pack command
@@ -131,9 +131,9 @@ module API
#
# rubocop: disable CodeReuse/ActiveRecord
get "/authorized_keys" do
- fingerprint = params.fetch(:fingerprint) do
+ fingerprint = params.fetch(:fingerprint) {
Gitlab::InsecureKeyFingerprint.new(params.fetch(:key)).fingerprint
- end
+ }
key = Key.find_by(fingerprint: fingerprint)
not_found!("Key") if key.nil?
present key, with: Entities::SSHKey
@@ -163,7 +163,7 @@ module API
api_version: API.version,
gitlab_version: Gitlab::VERSION,
gitlab_rev: Gitlab.revision,
- redis: redis_ping
+ redis: redis_ping,
}
end
@@ -184,7 +184,7 @@ module API
end
# rubocop: disable CodeReuse/ActiveRecord
- post '/two_factor_recovery_codes' do
+ post "/two_factor_recovery_codes" do
status 200
if params[:key_id]
@@ -193,28 +193,28 @@ module API
if key
key.update_last_used_at
else
- break { 'success' => false, 'message' => 'Could not find the given key' }
+ break {"success" => false, "message" => "Could not find the given key"}
end
if key.is_a?(DeployKey)
- break { success: false, message: 'Deploy keys cannot be used to retrieve recovery codes' }
+ break {success: false, message: "Deploy keys cannot be used to retrieve recovery codes"}
end
user = key.user
unless user
- break { success: false, message: 'Could not find a user for the given key' }
+ break {success: false, message: "Could not find a user for the given key"}
end
elsif params[:user_id]
user = User.find_by(id: params[:user_id])
unless user
- break { success: false, message: 'Could not find the given user' }
+ break {success: false, message: "Could not find the given user"}
end
end
unless user.two_factor_enabled?
- break { success: false, message: 'Two-factor authentication is not enabled for this user' }
+ break {success: false, message: "Two-factor authentication is not enabled for this user"}
end
codes = nil
@@ -223,16 +223,16 @@ module API
codes = user.generate_otp_backup_codes!
end
- { success: true, recovery_codes: codes }
+ {success: true, recovery_codes: codes}
end
# rubocop: enable CodeReuse/ActiveRecord
- post '/pre_receive' do
+ post "/pre_receive" do
status 200
reference_counter_increased = Gitlab::ReferenceCounter.new(params[:gl_repository]).increase
- { reference_counter_increased: reference_counter_increased }
+ {reference_counter_increased: reference_counter_increased}
end
post "/notify_post_receive" do
@@ -249,7 +249,7 @@ module API
# end
end
- post '/post_receive' do
+ post "/post_receive" do
status 200
PostReceive.perform_async(params[:gl_repository], params[:identifier],
@@ -260,7 +260,7 @@ module API
output = {
merge_request_urls: merge_request_urls,
broadcast_message: broadcast_message,
- reference_counter_decreased: reference_counter_decreased
+ reference_counter_decreased: reference_counter_decreased,
}
project = Gitlab::GlRepository.parse(params[:gl_repository]).first
diff --git a/lib/api/issues.rb b/lib/api/issues.rb
index f43f4d961d6..a942c510c33 100644
--- a/lib/api/issues.rb
+++ b/lib/api/issues.rb
@@ -34,40 +34,40 @@ module API
# rubocop: enable CodeReuse/ActiveRecord
params :issues_params do
- optional :labels, type: String, desc: 'Comma-separated list of label names'
- optional :milestone, type: String, desc: 'Milestone title'
- optional :order_by, type: String, values: %w[created_at updated_at], default: 'created_at',
- desc: 'Return issues ordered by `created_at` or `updated_at` fields.'
- optional :sort, type: String, values: %w[asc desc], default: 'desc',
- desc: 'Return issues sorted in `asc` or `desc` order.'
- optional :milestone, type: String, desc: 'Return issues for a specific milestone'
- optional :iids, type: Array[Integer], desc: 'The IID array of issues'
- optional :search, type: String, desc: 'Search issues for text present in the title, description, or any combination of these'
- optional :in, type: String, desc: '`title`, `description`, or a string joining them with comma'
- optional :created_after, type: DateTime, desc: 'Return issues created after the specified time'
- optional :created_before, type: DateTime, desc: 'Return issues created before the specified time'
- optional :updated_after, type: DateTime, desc: 'Return issues updated after the specified time'
- optional :updated_before, type: DateTime, desc: 'Return issues updated before the specified time'
- optional :author_id, type: Integer, desc: 'Return issues which are authored by the user with the given ID'
+ optional :labels, type: String, desc: "Comma-separated list of label names"
+ optional :milestone, type: String, desc: "Milestone title"
+ optional :order_by, type: String, values: %w[created_at updated_at], default: "created_at",
+ desc: "Return issues ordered by `created_at` or `updated_at` fields."
+ optional :sort, type: String, values: %w[asc desc], default: "desc",
+ desc: "Return issues sorted in `asc` or `desc` order."
+ optional :milestone, type: String, desc: "Return issues for a specific milestone"
+ optional :iids, type: Array[Integer], desc: "The IID array of issues"
+ optional :search, type: String, desc: "Search issues for text present in the title, description, or any combination of these"
+ optional :in, type: String, desc: "`title`, `description`, or a string joining them with comma"
+ optional :created_after, type: DateTime, desc: "Return issues created after the specified time"
+ optional :created_before, type: DateTime, desc: "Return issues created before the specified time"
+ optional :updated_after, type: DateTime, desc: "Return issues updated after the specified time"
+ optional :updated_before, type: DateTime, desc: "Return issues updated before the specified time"
+ optional :author_id, type: Integer, desc: "Return issues which are authored by the user with the given ID"
optional :assignee_id, types: [Integer, String], integer_none_any: true,
- desc: 'Return issues which are assigned to the user with the given ID'
+ desc: "Return issues which are assigned to the user with the given ID"
optional :scope, type: String, values: %w[created-by-me assigned-to-me created_by_me assigned_to_me all],
- desc: 'Return issues for the given scope: `created_by_me`, `assigned_to_me` or `all`'
- optional :my_reaction_emoji, type: String, desc: 'Return issues reacted by the authenticated user by the given emoji'
- optional :confidential, type: Boolean, desc: 'Filter confidential or public issues'
+ desc: "Return issues for the given scope: `created_by_me`, `assigned_to_me` or `all`"
+ optional :my_reaction_emoji, type: String, desc: "Return issues reacted by the authenticated user by the given emoji"
+ optional :confidential, type: Boolean, desc: "Filter confidential or public issues"
use :pagination
use :issues_params_ee
end
params :issue_params do
- optional :description, type: String, desc: 'The description of an issue'
- optional :assignee_ids, type: Array[Integer], desc: 'The array of user IDs to assign issue'
- optional :assignee_id, type: Integer, desc: '[Deprecated] The ID of a user to assign issue'
- optional :milestone_id, type: Integer, desc: 'The ID of a milestone to assign issue'
- optional :labels, type: String, desc: 'Comma-separated list of label names'
- optional :due_date, type: String, desc: 'Date string in the format YEAR-MONTH-DAY'
- optional :confidential, type: Boolean, desc: 'Boolean parameter if the issue should be confidential'
+ optional :description, type: String, desc: "The description of an issue"
+ optional :assignee_ids, type: Array[Integer], desc: "The array of user IDs to assign issue"
+ optional :assignee_id, type: Integer, desc: "[Deprecated] The ID of a user to assign issue"
+ optional :milestone_id, type: Integer, desc: "The ID of a milestone to assign issue"
+ optional :labels, type: String, desc: "Comma-separated list of label names"
+ optional :due_date, type: String, desc: "Date string in the format YEAR-MONTH-DAY"
+ optional :confidential, type: Boolean, desc: "Boolean parameter if the issue should be confidential"
optional :discussion_locked, type: Boolean, desc: " Boolean parameter indicating if the issue's discussion is locked"
use :issue_params_ee
@@ -79,20 +79,20 @@ module API
success Entities::IssueBasic
end
params do
- optional :state, type: String, values: %w[opened closed all], default: 'all',
- desc: 'Return opened, closed, or all issues'
+ optional :state, type: String, values: %w[opened closed all], default: "all",
+ desc: "Return opened, closed, or all issues"
use :issues_params
- optional :scope, type: String, values: %w[created-by-me assigned-to-me created_by_me assigned_to_me all], default: 'created_by_me',
- desc: 'Return issues for the given scope: `created_by_me`, `assigned_to_me` or `all`'
+ optional :scope, type: String, values: %w[created-by-me assigned-to-me created_by_me assigned_to_me all], default: "created_by_me",
+ desc: "Return issues for the given scope: `created_by_me`, `assigned_to_me` or `all`"
end
get do
- authenticate! unless params[:scope] == 'all'
+ authenticate! unless params[:scope] == "all"
issues = paginate(find_issues)
options = {
with: Entities::IssueBasic,
current_user: current_user,
- issuable_metadata: issuable_meta_data(issues, 'Issue')
+ issuable_metadata: issuable_meta_data(issues, "Issue"),
}
present issues, options
@@ -100,15 +100,15 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a group'
+ requires :id, type: String, desc: "The ID of a group"
end
resource :groups, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get a list of group issues' do
+ desc "Get a list of group issues" do
success Entities::IssueBasic
end
params do
- optional :state, type: String, values: %w[opened closed all], default: 'all',
- desc: 'Return opened, closed, or all issues'
+ optional :state, type: String, values: %w[opened closed all], default: "all",
+ desc: "Return opened, closed, or all issues"
use :issues_params
end
get ":id/issues" do
@@ -119,7 +119,7 @@ module API
options = {
with: Entities::IssueBasic,
current_user: current_user,
- issuable_metadata: issuable_meta_data(issues, 'Issue')
+ issuable_metadata: issuable_meta_data(issues, "Issue"),
}
present issues, options
@@ -127,17 +127,17 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
include TimeTrackingEndpoints
- desc 'Get a list of project issues' do
+ desc "Get a list of project issues" do
success Entities::IssueBasic
end
params do
- optional :state, type: String, values: %w[opened closed all], default: 'all',
- desc: 'Return opened, closed, or all issues'
+ optional :state, type: String, values: %w[opened closed all], default: "all",
+ desc: "Return opened, closed, or all issues"
use :issues_params
end
get ":id/issues" do
@@ -149,41 +149,41 @@ module API
with: Entities::IssueBasic,
current_user: current_user,
project: user_project,
- issuable_metadata: issuable_meta_data(issues, 'Issue')
+ issuable_metadata: issuable_meta_data(issues, "Issue"),
}
present issues, options
end
- desc 'Get a single project issue' do
+ desc "Get a single project issue" do
success Entities::Issue
end
params do
- requires :issue_iid, type: Integer, desc: 'The internal ID of a project issue'
+ requires :issue_iid, type: Integer, desc: "The internal ID of a project issue"
end
get ":id/issues/:issue_iid", as: :api_v4_project_issue do
issue = find_project_issue(params[:issue_iid])
present issue, with: Entities::Issue, current_user: current_user, project: user_project
end
- desc 'Create a new project issue' do
+ desc "Create a new project issue" do
success Entities::Issue
end
params do
- requires :title, type: String, desc: 'The title of an issue'
+ requires :title, type: String, desc: "The title of an issue"
optional :created_at, type: DateTime,
- desc: 'Date time when the issue was created. Available only for admins and project owners.'
+ desc: "Date time when the issue was created. Available only for admins and project owners."
optional :merge_request_to_resolve_discussions_of, type: Integer,
- desc: 'The IID of a merge request for which to resolve discussions'
+ desc: "The IID of a merge request for which to resolve discussions"
optional :discussion_to_resolve, type: String,
- desc: 'The ID of a discussion to resolve, also pass `merge_request_to_resolve_discussions_of`'
+ desc: "The ID of a discussion to resolve, also pass `merge_request_to_resolve_discussions_of`"
optional :iid, type: Integer,
- desc: 'The internal ID of a project issue. Available only for admins and project owners.'
+ desc: "The internal ID of a project issue. Available only for admins and project owners."
use :issue_params
end
- post ':id/issues' do
- Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42320')
+ post ":id/issues" do
+ Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42320")
authorize! :create_issue, user_project
@@ -195,11 +195,11 @@ module API
issue_params = convert_parameters_from_legacy_format(issue_params)
issue = ::Issues::CreateService.new(user_project,
- current_user,
- issue_params.merge(request: request, api: true)).execute
+ current_user,
+ issue_params.merge(request: request, api: true)).execute
if issue.spam?
- render_api_error!({ error: 'Spam detected' }, 400)
+ render_api_error!({error: "Spam detected"}, 400)
end
if issue.valid?
@@ -209,22 +209,22 @@ module API
end
end
- desc 'Update an existing issue' do
+ desc "Update an existing issue" do
success Entities::Issue
end
params do
- requires :issue_iid, type: Integer, desc: 'The internal ID of a project issue'
- optional :title, type: String, desc: 'The title of an issue'
+ requires :issue_iid, type: Integer, desc: "The internal ID of a project issue"
+ optional :title, type: String, desc: "The title of an issue"
optional :updated_at, type: DateTime,
- desc: 'Date time when the issue was updated. Available only for admins and project owners.'
- optional :state_event, type: String, values: %w[reopen close], desc: 'State of the issue'
+ desc: "Date time when the issue was updated. Available only for admins and project owners."
+ optional :state_event, type: String, values: %w[reopen close], desc: "State of the issue"
use :issue_params
at_least_one_of :title, :description, :assignee_ids, :assignee_id, :milestone_id, :discussion_locked,
- :labels, :created_at, :due_date, :confidential, :state_event
+ :labels, :created_at, :due_date, :confidential, :state_event
end
# rubocop: disable CodeReuse/ActiveRecord
- put ':id/issues/:issue_iid' do
- Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42322')
+ put ":id/issues/:issue_iid" do
+ Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42322")
issue = user_project.issues.find_by!(iid: params.delete(:issue_iid))
authorize! :update_issue, issue
@@ -239,8 +239,8 @@ module API
update_params = convert_parameters_from_legacy_format(update_params)
issue = ::Issues::UpdateService.new(user_project,
- current_user,
- update_params).execute(issue)
+ current_user,
+ update_params).execute(issue)
render_spam_error! if issue.spam?
@@ -252,22 +252,22 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Move an existing issue' do
+ desc "Move an existing issue" do
success Entities::Issue
end
params do
- requires :issue_iid, type: Integer, desc: 'The internal ID of a project issue'
- requires :to_project_id, type: Integer, desc: 'The ID of the new project'
+ requires :issue_iid, type: Integer, desc: "The internal ID of a project issue"
+ requires :to_project_id, type: Integer, desc: "The ID of the new project"
end
# rubocop: disable CodeReuse/ActiveRecord
- post ':id/issues/:issue_iid/move' do
- Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42323')
+ post ":id/issues/:issue_iid/move" do
+ Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42323")
issue = user_project.issues.find_by(iid: params[:issue_iid])
- not_found!('Issue') unless issue
+ not_found!("Issue") unless issue
new_project = Project.find_by(id: params[:to_project_id])
- not_found!('Project') unless new_project
+ not_found!("Project") unless new_project
begin
issue = ::Issues::MoveService.new(user_project, current_user).execute(issue, new_project)
@@ -278,14 +278,14 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Delete a project issue'
+ desc "Delete a project issue"
params do
- requires :issue_iid, type: Integer, desc: 'The internal ID of a project issue'
+ requires :issue_iid, type: Integer, desc: "The internal ID of a project issue"
end
# rubocop: disable CodeReuse/ActiveRecord
delete ":id/issues/:issue_iid" do
issue = user_project.issues.find_by(iid: params[:issue_iid])
- not_found!('Issue') unless issue
+ not_found!("Issue") unless issue
authorize!(:destroy_issue, issue)
@@ -295,13 +295,13 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'List merge requests that are related to the issue' do
+ desc "List merge requests that are related to the issue" do
success Entities::MergeRequestBasic
end
params do
- requires :issue_iid, type: Integer, desc: 'The internal ID of a project issue'
+ requires :issue_iid, type: Integer, desc: "The internal ID of a project issue"
end
- get ':id/issues/:issue_iid/related_merge_requests' do
+ get ":id/issues/:issue_iid/related_merge_requests" do
issue = find_project_issue(params[:issue_iid])
merge_requests = ::Issues::ReferencedMergeRequestsService.new(user_project, current_user)
@@ -314,14 +314,14 @@ module API
project: user_project
end
- desc 'List merge requests closing issue' do
+ desc "List merge requests closing issue" do
success Entities::MergeRequestBasic
end
params do
- requires :issue_iid, type: Integer, desc: 'The internal ID of a project issue'
+ requires :issue_iid, type: Integer, desc: "The internal ID of a project issue"
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/issues/:issue_iid/closed_by' do
+ get ":id/issues/:issue_iid/closed_by" do
issue = find_project_issue(params[:issue_iid])
merge_request_ids = MergeRequestsClosingIssues.where(issue_id: issue).select(:merge_request_id)
@@ -331,31 +331,31 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'List participants for an issue' do
+ desc "List participants for an issue" do
success Entities::UserBasic
end
params do
- requires :issue_iid, type: Integer, desc: 'The internal ID of a project issue'
+ requires :issue_iid, type: Integer, desc: "The internal ID of a project issue"
end
- get ':id/issues/:issue_iid/participants' do
+ get ":id/issues/:issue_iid/participants" do
issue = find_project_issue(params[:issue_iid])
participants = ::Kaminari.paginate_array(issue.participants)
present paginate(participants), with: Entities::UserBasic, current_user: current_user, project: user_project
end
- desc 'Get the user agent details for an issue' do
+ desc "Get the user agent details for an issue" do
success Entities::UserAgentDetail
end
params do
- requires :issue_iid, type: Integer, desc: 'The internal ID of a project issue'
+ requires :issue_iid, type: Integer, desc: "The internal ID of a project issue"
end
get ":id/issues/:issue_iid/user_agent_detail" do
authenticated_as_admin!
issue = find_project_issue(params[:issue_iid])
- break not_found!('UserAgentDetail') unless issue.user_agent_detail
+ break not_found!("UserAgentDetail") unless issue.user_agent_detail
present issue.user_agent_detail, with: Entities::UserAgentDetail
end
diff --git a/lib/api/job_artifacts.rb b/lib/api/job_artifacts.rb
index 933bd067e26..d100f2c431a 100644
--- a/lib/api/job_artifacts.rb
+++ b/lib/api/job_artifacts.rb
@@ -12,19 +12,19 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Download the artifacts archive from a job' do
- detail 'This feature was introduced in GitLab 8.10'
+ desc "Download the artifacts archive from a job" do
+ detail "This feature was introduced in GitLab 8.10"
end
params do
- requires :ref_name, type: String, desc: 'The ref from repository'
- requires :job, type: String, desc: 'The name for the job'
+ requires :ref_name, type: String, desc: "The ref from repository"
+ requires :job, type: String, desc: "The name for the job"
end
route_setting :authentication, job_token_allowed: true
- get ':id/jobs/artifacts/:ref_name/download',
- requirements: { ref_name: /.+/ } do
+ get ":id/jobs/artifacts/:ref_name/download",
+ requirements: {ref_name: /.+/} do
authorize_download_artifacts!
latest_build = user_project.latest_successful_build_for!(params[:job], params[:ref_name])
@@ -32,37 +32,37 @@ module API
present_carrierwave_file!(latest_build.artifacts_file)
end
- desc 'Download a specific file from artifacts archive from a ref' do
- detail 'This feature was introduced in GitLab 11.5'
+ desc "Download a specific file from artifacts archive from a ref" do
+ detail "This feature was introduced in GitLab 11.5"
end
params do
- requires :ref_name, type: String, desc: 'The ref from repository'
- requires :job, type: String, desc: 'The name for the job'
- requires :artifact_path, type: String, desc: 'Artifact path'
+ requires :ref_name, type: String, desc: "The ref from repository"
+ requires :job, type: String, desc: "The name for the job"
+ requires :artifact_path, type: String, desc: "Artifact path"
end
- get ':id/jobs/artifacts/:ref_name/raw/*artifact_path',
- format: false,
- requirements: { ref_name: /.+/ } do
+ get ":id/jobs/artifacts/:ref_name/raw/*artifact_path",
+ format: false,
+ requirements: {ref_name: /.+/} do
authorize_download_artifacts!
build = user_project.latest_successful_build_for!(params[:job], params[:ref_name])
path = Gitlab::Ci::Build::Artifacts::Path
- .new(params[:artifact_path])
+ .new(params[:artifact_path])
bad_request! unless path.valid?
send_artifacts_entry(build, path)
end
- desc 'Download the artifacts archive from a job' do
- detail 'This feature was introduced in GitLab 8.5'
+ desc "Download the artifacts archive from a job" do
+ detail "This feature was introduced in GitLab 8.5"
end
params do
- requires :job_id, type: Integer, desc: 'The ID of a job'
+ requires :job_id, type: Integer, desc: "The ID of a job"
end
route_setting :authentication, job_token_allowed: true
- get ':id/jobs/:job_id/artifacts' do
+ get ":id/jobs/:job_id/artifacts" do
authorize_download_artifacts!
build = find_build!(params[:job_id])
@@ -70,14 +70,14 @@ module API
present_carrierwave_file!(build.artifacts_file)
end
- desc 'Download a specific file from artifacts archive' do
- detail 'This feature was introduced in GitLab 10.0'
+ desc "Download a specific file from artifacts archive" do
+ detail "This feature was introduced in GitLab 10.0"
end
params do
- requires :job_id, type: Integer, desc: 'The ID of a job'
- requires :artifact_path, type: String, desc: 'Artifact path'
+ requires :job_id, type: Integer, desc: "The ID of a job"
+ requires :artifact_path, type: String, desc: "Artifact path"
end
- get ':id/jobs/:job_id/artifacts/*artifact_path', format: false do
+ get ":id/jobs/:job_id/artifacts/*artifact_path", format: false do
authorize_read_builds!
build = find_build!(params[:job_id])
@@ -91,13 +91,13 @@ module API
send_artifacts_entry(build, path)
end
- desc 'Keep the artifacts to prevent them from being deleted' do
+ desc "Keep the artifacts to prevent them from being deleted" do
success Entities::Job
end
params do
- requires :job_id, type: Integer, desc: 'The ID of a job'
+ requires :job_id, type: Integer, desc: "The ID of a job"
end
- post ':id/jobs/:job_id/artifacts/keep' do
+ post ":id/jobs/:job_id/artifacts/keep" do
authorize_update_builds!
build = find_build!(params[:job_id])
diff --git a/lib/api/jobs.rb b/lib/api/jobs.rb
index 59f0dbe8a9b..b30242bda9b 100644
--- a/lib/api/jobs.rb
+++ b/lib/api/jobs.rb
@@ -7,12 +7,12 @@ module API
before { authenticate! }
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
helpers do
params :optional_scope do
- optional :scope, types: [String, Array[String]], desc: 'The scope of builds to show',
+ optional :scope, types: [String, Array[String]], desc: "The scope of builds to show",
values: ::CommitStatus::AVAILABLE_STATUSES,
coerce_with: ->(scope) {
case scope
@@ -23,13 +23,13 @@ module API
when ::Array
scope
else
- ['unknown']
+ ["unknown"]
end
}
end
end
- desc 'Get a projects jobs' do
+ desc "Get a projects jobs" do
success Entities::Job
end
params do
@@ -37,10 +37,10 @@ module API
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/jobs' do
+ get ":id/jobs" do
authorize_read_builds!
- builds = user_project.builds.order('id DESC')
+ builds = user_project.builds.order("id DESC")
builds = filter_builds(builds, params[:scope])
builds = builds.preload(:user, :job_artifacts_archive, :job_artifacts, :runner, pipeline: :project)
@@ -48,16 +48,16 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get pipeline jobs' do
+ desc "Get pipeline jobs" do
success Entities::Job
end
params do
- requires :pipeline_id, type: Integer, desc: 'The pipeline ID'
+ requires :pipeline_id, type: Integer, desc: "The pipeline ID"
use :optional_scope
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/pipelines/:pipeline_id/jobs' do
+ get ":id/pipelines/:pipeline_id/jobs" do
authorize!(:read_pipeline, user_project)
pipeline = user_project.ci_pipelines.find(params[:pipeline_id])
authorize!(:read_build, pipeline)
@@ -70,13 +70,13 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get a specific job of a project' do
+ desc "Get a specific job of a project" do
success Entities::Job
end
params do
- requires :job_id, type: Integer, desc: 'The ID of a job'
+ requires :job_id, type: Integer, desc: "The ID of a job"
end
- get ':id/jobs/:job_id' do
+ get ":id/jobs/:job_id" do
authorize_read_builds!
build = find_build!(params[:job_id])
@@ -87,30 +87,30 @@ module API
# TODO: We should use `present_disk_file!` and leave this implementation for backward compatibility (when build trace
# is saved in the DB instead of file). But before that, we need to consider how to replace the value of
# `runners_token` with some mask (like `xxxxxx`) when sending trace file directly by workhorse.
- desc 'Get a trace of a specific job of a project'
+ desc "Get a trace of a specific job of a project"
params do
- requires :job_id, type: Integer, desc: 'The ID of a job'
+ requires :job_id, type: Integer, desc: "The ID of a job"
end
- get ':id/jobs/:job_id/trace' do
+ get ":id/jobs/:job_id/trace" do
authorize_read_builds!
build = find_build!(params[:job_id])
- header 'Content-Disposition', "infile; filename=\"#{build.id}.log\""
- content_type 'text/plain'
- env['api.format'] = :binary
+ header "Content-Disposition", "infile; filename=\"#{build.id}.log\""
+ content_type "text/plain"
+ env["api.format"] = :binary
trace = build.trace.raw
body trace
end
- desc 'Cancel a specific job of a project' do
+ desc "Cancel a specific job of a project" do
success Entities::Job
end
params do
- requires :job_id, type: Integer, desc: 'The ID of a job'
+ requires :job_id, type: Integer, desc: "The ID of a job"
end
- post ':id/jobs/:job_id/cancel' do
+ post ":id/jobs/:job_id/cancel" do
authorize_update_builds!
build = find_build!(params[:job_id])
@@ -121,47 +121,47 @@ module API
present build, with: Entities::Job
end
- desc 'Retry a specific build of a project' do
+ desc "Retry a specific build of a project" do
success Entities::Job
end
params do
- requires :job_id, type: Integer, desc: 'The ID of a build'
+ requires :job_id, type: Integer, desc: "The ID of a build"
end
- post ':id/jobs/:job_id/retry' do
+ post ":id/jobs/:job_id/retry" do
authorize_update_builds!
build = find_build!(params[:job_id])
authorize!(:update_build, build)
- break forbidden!('Job is not retryable') unless build.retryable?
+ break forbidden!("Job is not retryable") unless build.retryable?
build = Ci::Build.retry(build, current_user)
present build, with: Entities::Job
end
- desc 'Erase job (remove artifacts and the trace)' do
+ desc "Erase job (remove artifacts and the trace)" do
success Entities::Job
end
params do
- requires :job_id, type: Integer, desc: 'The ID of a build'
+ requires :job_id, type: Integer, desc: "The ID of a build"
end
- post ':id/jobs/:job_id/erase' do
+ post ":id/jobs/:job_id/erase" do
authorize_update_builds!
build = find_build!(params[:job_id])
authorize!(:erase_build, build)
- break forbidden!('Job is not erasable!') unless build.erasable?
+ break forbidden!("Job is not erasable!") unless build.erasable?
build.erase(erased_by: current_user)
present build, with: Entities::Job
end
- desc 'Trigger a actionable job (manual, delayed, etc)' do
+ desc "Trigger a actionable job (manual, delayed, etc)" do
success Entities::Job
- detail 'This feature was added in GitLab 8.11'
+ detail "This feature was added in GitLab 8.11"
end
params do
- requires :job_id, type: Integer, desc: 'The ID of a Job'
+ requires :job_id, type: Integer, desc: "The ID of a Job"
end
post ":id/jobs/:job_id/play" do
authorize_read_builds!
@@ -186,7 +186,7 @@ module API
available_statuses = ::CommitStatus::AVAILABLE_STATUSES
unknown = scope - available_statuses
- render_api_error!('Scope contains invalid value(s)', 400) unless unknown.empty?
+ render_api_error!("Scope contains invalid value(s)", 400) unless unknown.empty?
builds.where(status: available_statuses && scope)
end
diff --git a/lib/api/keys.rb b/lib/api/keys.rb
index d5280a0035d..404417bbdca 100644
--- a/lib/api/keys.rb
+++ b/lib/api/keys.rb
@@ -6,7 +6,7 @@ module API
before { authenticate! }
resource :keys do
- desc 'Get single ssh key by id. Only available to admin users' do
+ desc "Get single ssh key by id. Only available to admin users" do
success Entities::SSHKeyWithUser
end
get ":id" do
diff --git a/lib/api/labels.rb b/lib/api/labels.rb
index d729d3ee625..84d48d74263 100644
--- a/lib/api/labels.rb
+++ b/lib/api/labels.rb
@@ -8,52 +8,52 @@ module API
before { authenticate! }
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get all labels of the project' do
+ desc "Get all labels of the project" do
success Entities::ProjectLabel
end
params do
use :pagination
end
- get ':id/labels' do
+ get ":id/labels" do
get_labels(user_project, Entities::ProjectLabel)
end
- desc 'Create a new label' do
+ desc "Create a new label" do
success Entities::ProjectLabel
end
params do
use :label_create_params
- optional :priority, type: Integer, desc: 'The priority of the label', allow_blank: true
+ optional :priority, type: Integer, desc: "The priority of the label", allow_blank: true
end
- post ':id/labels' do
+ post ":id/labels" do
create_label(user_project, Entities::ProjectLabel)
end
- desc 'Update an existing label. At least one optional parameter is required.' do
+ desc "Update an existing label. At least one optional parameter is required." do
success Entities::ProjectLabel
end
params do
- requires :name, type: String, desc: 'The name of the label to be updated'
- optional :new_name, type: String, desc: 'The new name of the label'
+ requires :name, type: String, desc: "The name of the label to be updated"
+ optional :new_name, type: String, desc: "The new name of the label"
optional :color, type: String, desc: "The new color of the label given in 6-digit hex notation with leading '#' sign (e.g. #FFAABB) or one of the allowed CSS color names"
- optional :description, type: String, desc: 'The new description of label'
- optional :priority, type: Integer, desc: 'The priority of the label', allow_blank: true
+ optional :description, type: String, desc: "The new description of label"
+ optional :priority, type: Integer, desc: "The priority of the label", allow_blank: true
at_least_one_of :new_name, :color, :description, :priority
end
- put ':id/labels' do
+ put ":id/labels" do
update_label(user_project, Entities::ProjectLabel)
end
- desc 'Delete an existing label' do
+ desc "Delete an existing label" do
success Entities::ProjectLabel
end
params do
- requires :name, type: String, desc: 'The name of the label to be deleted'
+ requires :name, type: String, desc: "The name of the label to be deleted"
end
- delete ':id/labels' do
+ delete ":id/labels" do
delete_label(user_project)
end
end
diff --git a/lib/api/lint.rb b/lib/api/lint.rb
index a7672021db0..a5995d6dcb3 100644
--- a/lib/api/lint.rb
+++ b/lib/api/lint.rb
@@ -3,20 +3,20 @@
module API
class Lint < Grape::API
namespace :ci do
- desc 'Validation of .gitlab-ci.yml content'
+ desc "Validation of .gitlab-ci.yml content"
params do
- requires :content, type: String, desc: 'Content of .gitlab-ci.yml'
+ requires :content, type: String, desc: "Content of .gitlab-ci.yml"
end
- post '/lint' do
+ post "/lint" do
error = Gitlab::Ci::YamlProcessor.validation_message(params[:content],
user: current_user)
status 200
if error.blank?
- { status: 'valid', errors: [] }
+ {status: "valid", errors: []}
else
- { status: 'invalid', errors: [error] }
+ {status: "invalid", errors: [error]}
end
end
end
diff --git a/lib/api/markdown.rb b/lib/api/markdown.rb
index de77bef43ce..41bddc820fb 100644
--- a/lib/api/markdown.rb
+++ b/lib/api/markdown.rb
@@ -12,7 +12,7 @@ module API
detail "This feature was introduced in GitLab 11.0."
end
post do
- context = { only_path: false, current_user: current_user }
+ context = {only_path: false, current_user: current_user}
context[:pipeline] = params[:gfm] ? :full : :plain_markdown
if params[:project]
@@ -25,7 +25,7 @@ module API
context[:skip_project_check] = true
end
- { html: Banzai.render_and_post_process(params[:text], context) }
+ {html: Banzai.render_and_post_process(params[:text], context)}
end
end
end
diff --git a/lib/api/members.rb b/lib/api/members.rb
index 461ffe71a62..e12be5cd0bc 100644
--- a/lib/api/members.rb
+++ b/lib/api/members.rb
@@ -13,11 +13,11 @@ module API
requires :id, type: String, desc: "The #{source_type} ID"
end
resource source_type.pluralize, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Gets a list of group or project members viewable by the authenticated user.' do
+ desc "Gets a list of group or project members viewable by the authenticated user." do
success Entities::Member
end
params do
- optional :query, type: String, desc: 'A query string to search for members'
+ optional :query, type: String, desc: "A query string to search for members"
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
@@ -32,11 +32,11 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Gets a list of group or project members viewable by the authenticated user, including those who gained membership through ancestor group.' do
+ desc "Gets a list of group or project members viewable by the authenticated user, including those who gained membership through ancestor group." do
success Entities::Member
end
params do
- optional :query, type: String, desc: 'A query string to search for members'
+ optional :query, type: String, desc: "A query string to search for members"
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
@@ -51,11 +51,11 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Gets a member of a group or project.' do
+ desc "Gets a member of a group or project." do
success Entities::Member
end
params do
- requires :user_id, type: Integer, desc: 'The user ID of the member'
+ requires :user_id, type: Integer, desc: "The user ID of the member"
end
# rubocop: disable CodeReuse/ActiveRecord
get ":id/members/:user_id" do
@@ -68,13 +68,13 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Adds a member to a group or project.' do
+ desc "Adds a member to a group or project." do
success Entities::Member
end
params do
- requires :user_id, type: Integer, desc: 'The user ID of the new member'
- requires :access_level, type: Integer, desc: 'A valid access level (defaults: `30`, developer access level)'
- optional :expires_at, type: DateTime, desc: 'Date string in the format YEAR-MONTH-DAY'
+ requires :user_id, type: Integer, desc: "The user ID of the new member"
+ requires :access_level, type: Integer, desc: "A valid access level (defaults: `30`, developer access level)"
+ optional :expires_at, type: DateTime, desc: "Date string in the format YEAR-MONTH-DAY"
end
# rubocop: disable CodeReuse/ActiveRecord
post ":id/members" do
@@ -82,10 +82,10 @@ module API
authorize_admin_source!(source_type, source)
member = source.members.find_by(user_id: params[:user_id])
- conflict!('Member already exists') if member
+ conflict!("Member already exists") if member
user = User.find_by_id(params[:user_id])
- not_found!('User') unless user
+ not_found!("User") unless user
member = source.add_user(user, params[:access_level], current_user: current_user, expires_at: params[:expires_at])
@@ -99,13 +99,13 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Updates a member of a group or project.' do
+ desc "Updates a member of a group or project." do
success Entities::Member
end
params do
- requires :user_id, type: Integer, desc: 'The user ID of the new member'
- requires :access_level, type: Integer, desc: 'A valid access level'
- optional :expires_at, type: DateTime, desc: 'Date string in the format YEAR-MONTH-DAY'
+ requires :user_id, type: Integer, desc: "The user ID of the new member"
+ requires :access_level, type: Integer, desc: "A valid access level"
+ optional :expires_at, type: DateTime, desc: "Date string in the format YEAR-MONTH-DAY"
end
# rubocop: disable CodeReuse/ActiveRecord
put ":id/members/:user_id" do
@@ -126,9 +126,9 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Removes a user from a group or project.'
+ desc "Removes a user from a group or project."
params do
- requires :user_id, type: Integer, desc: 'The user ID of the member'
+ requires :user_id, type: Integer, desc: "The user ID of the member"
end
# rubocop: disable CodeReuse/ActiveRecord
delete ":id/members/:user_id" do
diff --git a/lib/api/merge_request_diffs.rb b/lib/api/merge_request_diffs.rb
index 6ad30aa56e0..ba7e442a4a3 100644
--- a/lib/api/merge_request_diffs.rb
+++ b/lib/api/merge_request_diffs.rb
@@ -8,16 +8,16 @@ module API
before { authenticate! }
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get a list of merge request diff versions' do
- detail 'This feature was introduced in GitLab 8.12.'
+ desc "Get a list of merge request diff versions" do
+ detail "This feature was introduced in GitLab 8.12."
success Entities::MergeRequestDiff
end
params do
- requires :merge_request_iid, type: Integer, desc: 'The IID of a merge request'
+ requires :merge_request_iid, type: Integer, desc: "The IID of a merge request"
use :pagination
end
get ":id/merge_requests/:merge_request_iid/versions" do
@@ -26,14 +26,14 @@ module API
present paginate(merge_request.merge_request_diffs.order_id_desc), with: Entities::MergeRequestDiff
end
- desc 'Get a single merge request diff version' do
- detail 'This feature was introduced in GitLab 8.12.'
+ desc "Get a single merge request diff version" do
+ detail "This feature was introduced in GitLab 8.12."
success Entities::MergeRequestDiffFull
end
params do
- requires :merge_request_iid, type: Integer, desc: 'The IID of a merge request'
- requires :version_id, type: Integer, desc: 'The ID of a merge request diff version'
+ requires :merge_request_iid, type: Integer, desc: "The IID of a merge request"
+ requires :version_id, type: Integer, desc: "The ID of a merge request diff version"
end
get ":id/merge_requests/:merge_request_iid/versions/:version_id" do
diff --git a/lib/api/merge_requests.rb b/lib/api/merge_requests.rb
index 44f1e81caf2..71a61f38864 100644
--- a/lib/api/merge_requests.rb
+++ b/lib/api/merge_requests.rb
@@ -38,11 +38,11 @@ module API
args[:scope] = args[:scope].underscore if args[:scope]
merge_requests = MergeRequestsFinder.new(current_user, args).execute
- .reorder(order_options_with_tie_breaker)
+ .reorder(order_options_with_tie_breaker)
merge_requests = paginate(merge_requests)
- .preload(:source_project, :target_project)
+ .preload(:source_project, :target_project)
- return merge_requests if args[:view] == 'simple'
+ return merge_requests if args[:view] == "simple"
merge_requests
.preload(:notes, :author, :assignee, :milestone, :latest_merge_request_diff, :labels, :timelogs, metrics: [:latest_closed_by, :merged_by])
@@ -63,19 +63,19 @@ module API
end
def serializer_options_for(merge_requests)
- options = { with: Entities::MergeRequestBasic, current_user: current_user }
+ options = {with: Entities::MergeRequestBasic, current_user: current_user}
- if params[:view] == 'simple'
+ if params[:view] == "simple"
options[:with] = Entities::MergeRequestSimple
else
- options[:issuable_metadata] = issuable_meta_data(merge_requests, 'MergeRequest')
+ options[:issuable_metadata] = issuable_meta_data(merge_requests, "MergeRequest")
end
options
end
def authorize_push_to_merge_request!(merge_request)
- forbidden!('Source branch does not exist') unless
+ forbidden!("Source branch does not exist") unless
merge_request.source_branch_exists?
user_access = Gitlab::UserAccess.new(
@@ -83,50 +83,50 @@ module API
project: merge_request.source_project
)
- forbidden!('Cannot push to source branch') unless
+ forbidden!("Cannot push to source branch") unless
user_access.can_push_to_branch?(merge_request.source_branch)
end
params :merge_requests_params do
- optional :state, type: String, values: %w[opened closed locked merged all], default: 'all',
- desc: 'Return opened, closed, locked, merged, or all merge requests'
- optional :order_by, type: String, values: %w[created_at updated_at], default: 'created_at',
- desc: 'Return merge requests ordered by `created_at` or `updated_at` fields.'
- optional :sort, type: String, values: %w[asc desc], default: 'desc',
- desc: 'Return merge requests sorted in `asc` or `desc` order.'
- optional :milestone, type: String, desc: 'Return merge requests for a specific milestone'
- optional :labels, type: String, desc: 'Comma-separated list of label names'
- optional :created_after, type: DateTime, desc: 'Return merge requests created after the specified time'
- optional :created_before, type: DateTime, desc: 'Return merge requests created before the specified time'
- optional :updated_after, type: DateTime, desc: 'Return merge requests updated after the specified time'
- optional :updated_before, type: DateTime, desc: 'Return merge requests updated before the specified time'
- optional :view, type: String, values: %w[simple], desc: 'If simple, returns the `iid`, URL, title, description, and basic state of merge request'
- optional :author_id, type: Integer, desc: 'Return merge requests which are authored by the user with the given ID'
+ optional :state, type: String, values: %w[opened closed locked merged all], default: "all",
+ desc: "Return opened, closed, locked, merged, or all merge requests"
+ optional :order_by, type: String, values: %w[created_at updated_at], default: "created_at",
+ desc: "Return merge requests ordered by `created_at` or `updated_at` fields."
+ optional :sort, type: String, values: %w[asc desc], default: "desc",
+ desc: "Return merge requests sorted in `asc` or `desc` order."
+ optional :milestone, type: String, desc: "Return merge requests for a specific milestone"
+ optional :labels, type: String, desc: "Comma-separated list of label names"
+ optional :created_after, type: DateTime, desc: "Return merge requests created after the specified time"
+ optional :created_before, type: DateTime, desc: "Return merge requests created before the specified time"
+ optional :updated_after, type: DateTime, desc: "Return merge requests updated after the specified time"
+ optional :updated_before, type: DateTime, desc: "Return merge requests updated before the specified time"
+ optional :view, type: String, values: %w[simple], desc: "If simple, returns the `iid`, URL, title, description, and basic state of merge request"
+ optional :author_id, type: Integer, desc: "Return merge requests which are authored by the user with the given ID"
optional :assignee_id, types: [Integer, String], integer_none_any: true,
- desc: 'Return merge requests which are assigned to the user with the given ID'
+ desc: "Return merge requests which are assigned to the user with the given ID"
optional :scope, type: String, values: %w[created-by-me assigned-to-me created_by_me assigned_to_me all],
- desc: 'Return merge requests for the given scope: `created_by_me`, `assigned_to_me` or `all`'
- optional :my_reaction_emoji, type: String, desc: 'Return issues reacted by the authenticated user by the given emoji'
- optional :source_branch, type: String, desc: 'Return merge requests with the given source branch'
- optional :target_branch, type: String, desc: 'Return merge requests with the given target branch'
- optional :search, type: String, desc: 'Search merge requests for text present in the title, description, or any combination of these'
- optional :in, type: String, desc: '`title`, `description`, or a string joining them with comma'
- optional :wip, type: String, values: %w[yes no], desc: 'Search merge requests for WIP in the title'
+ desc: "Return merge requests for the given scope: `created_by_me`, `assigned_to_me` or `all`"
+ optional :my_reaction_emoji, type: String, desc: "Return issues reacted by the authenticated user by the given emoji"
+ optional :source_branch, type: String, desc: "Return merge requests with the given source branch"
+ optional :target_branch, type: String, desc: "Return merge requests with the given target branch"
+ optional :search, type: String, desc: "Search merge requests for text present in the title, description, or any combination of these"
+ optional :in, type: String, desc: "`title`, `description`, or a string joining them with comma"
+ optional :wip, type: String, values: %w[yes no], desc: "Search merge requests for WIP in the title"
use :pagination
end
end
resource :merge_requests do
- desc 'List merge requests' do
+ desc "List merge requests" do
success Entities::MergeRequestBasic
end
params do
use :merge_requests_params
- optional :scope, type: String, values: %w[created-by-me assigned-to-me created_by_me assigned_to_me all], default: 'created_by_me',
- desc: 'Return merge requests for the given scope: `created_by_me`, `assigned_to_me` or `all`'
+ optional :scope, type: String, values: %w[created-by-me assigned-to-me created_by_me assigned_to_me all], default: "created_by_me",
+ desc: "Return merge requests for the given scope: `created_by_me`, `assigned_to_me` or `all`"
end
get do
- authenticate! unless params[:scope] == 'all'
+ authenticate! unless params[:scope] == "all"
merge_requests = find_merge_requests
present merge_requests, serializer_options_for(merge_requests)
@@ -134,10 +134,10 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a group'
+ requires :id, type: String, desc: "The ID of a group"
end
resource :groups, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get a list of group merge requests' do
+ desc "Get a list of group merge requests" do
success Entities::MergeRequestBasic
end
params do
@@ -153,7 +153,7 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
include TimeTrackingEndpoints
@@ -176,25 +176,25 @@ module API
end
params :optional_params do
- optional :description, type: String, desc: 'The description of the merge request'
- optional :assignee_id, type: Integer, desc: 'The ID of a user to assign the merge request'
- optional :milestone_id, type: Integer, desc: 'The ID of a milestone to assign the merge request'
- optional :labels, type: String, desc: 'Comma-separated list of label names'
- optional :remove_source_branch, type: Boolean, desc: 'Delete source branch when merging'
- optional :allow_collaboration, type: Boolean, desc: 'Allow commits from members who can merge to the target branch'
- optional :allow_maintainer_to_push, type: Boolean, as: :allow_collaboration, desc: '[deprecated] See allow_collaboration'
- optional :squash, type: Grape::API::Boolean, desc: 'When true, the commits will be squashed into a single commit on merge'
+ optional :description, type: String, desc: "The description of the merge request"
+ optional :assignee_id, type: Integer, desc: "The ID of a user to assign the merge request"
+ optional :milestone_id, type: Integer, desc: "The ID of a milestone to assign the merge request"
+ optional :labels, type: String, desc: "Comma-separated list of label names"
+ optional :remove_source_branch, type: Boolean, desc: "Delete source branch when merging"
+ optional :allow_collaboration, type: Boolean, desc: "Allow commits from members who can merge to the target branch"
+ optional :allow_maintainer_to_push, type: Boolean, as: :allow_collaboration, desc: "[deprecated] See allow_collaboration"
+ optional :squash, type: Grape::API::Boolean, desc: "When true, the commits will be squashed into a single commit on merge"
use :optional_params_ee
end
end
- desc 'List merge requests' do
+ desc "List merge requests" do
success Entities::MergeRequestBasic
end
params do
use :merge_requests_params
- optional :iids, type: Array[Integer], desc: 'The IID array of merge requests'
+ optional :iids, type: Array[Integer], desc: "The IID array of merge requests"
end
get ":id/merge_requests" do
authorize! :read_merge_request, user_project
@@ -207,19 +207,19 @@ module API
present merge_requests, options
end
- desc 'Create a merge request' do
+ desc "Create a merge request" do
success Entities::MergeRequest
end
params do
- requires :title, type: String, desc: 'The title of the merge request'
- requires :source_branch, type: String, desc: 'The source branch'
- requires :target_branch, type: String, desc: 'The target branch'
+ requires :title, type: String, desc: "The title of the merge request"
+ requires :source_branch, type: String, desc: "The source branch"
+ requires :target_branch, type: String, desc: "The target branch"
optional :target_project_id, type: Integer,
- desc: 'The target project of the merge request defaults to the :id of the project'
+ desc: "The target project of the merge request defaults to the :id of the project"
use :optional_params
end
post ":id/merge_requests" do
- Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42316')
+ Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42316")
authorize! :create_merge_request_from, user_project
@@ -235,9 +235,9 @@ module API
end
end
- desc 'Delete a merge request'
+ desc "Delete a merge request"
params do
- requires :merge_request_iid, type: Integer, desc: 'The IID of a merge request'
+ requires :merge_request_iid, type: Integer, desc: "The IID of a merge request"
end
delete ":id/merge_requests/:merge_request_iid" do
merge_request = find_project_merge_request(params[:merge_request_iid])
@@ -250,15 +250,15 @@ module API
end
params do
- requires :merge_request_iid, type: Integer, desc: 'The IID of a merge request'
- optional :render_html, type: Boolean, desc: 'Returns the description and title rendered HTML'
- optional :include_diverged_commits_count, type: Boolean, desc: 'Returns the commits count behind the target branch'
- optional :include_rebase_in_progress, type: Boolean, desc: 'Returns whether a rebase operation is ongoing '
+ requires :merge_request_iid, type: Integer, desc: "The IID of a merge request"
+ optional :render_html, type: Boolean, desc: "Returns the description and title rendered HTML"
+ optional :include_diverged_commits_count, type: Boolean, desc: "Returns the commits count behind the target branch"
+ optional :include_rebase_in_progress, type: Boolean, desc: "Returns whether a rebase operation is ongoing "
end
- desc 'Get a single merge request' do
+ desc "Get a single merge request" do
success Entities::MergeRequest
end
- get ':id/merge_requests/:merge_request_iid' do
+ get ":id/merge_requests/:merge_request_iid" do
merge_request = find_merge_request_with_access(params[:merge_request_iid])
present merge_request,
@@ -270,59 +270,59 @@ module API
include_rebase_in_progress: params[:include_rebase_in_progress]
end
- desc 'Get the participants of a merge request' do
+ desc "Get the participants of a merge request" do
success Entities::UserBasic
end
- get ':id/merge_requests/:merge_request_iid/participants' do
+ get ":id/merge_requests/:merge_request_iid/participants" do
merge_request = find_merge_request_with_access(params[:merge_request_iid])
participants = ::Kaminari.paginate_array(merge_request.participants)
present paginate(participants), with: Entities::UserBasic
end
- desc 'Get the commits of a merge request' do
+ desc "Get the commits of a merge request" do
success Entities::Commit
end
- get ':id/merge_requests/:merge_request_iid/commits' do
+ get ":id/merge_requests/:merge_request_iid/commits" do
merge_request = find_merge_request_with_access(params[:merge_request_iid])
commits = ::Kaminari.paginate_array(merge_request.commits)
present paginate(commits), with: Entities::Commit
end
- desc 'Show the merge request changes' do
+ desc "Show the merge request changes" do
success Entities::MergeRequestChanges
end
- get ':id/merge_requests/:merge_request_iid/changes' do
+ get ":id/merge_requests/:merge_request_iid/changes" do
merge_request = find_merge_request_with_access(params[:merge_request_iid])
present merge_request, with: Entities::MergeRequestChanges, current_user: current_user, project: user_project
end
- desc 'Get the merge request pipelines' do
+ desc "Get the merge request pipelines" do
success Entities::PipelineBasic
end
- get ':id/merge_requests/:merge_request_iid/pipelines' do
+ get ":id/merge_requests/:merge_request_iid/pipelines" do
pipelines = merge_request_pipelines_with_access
present paginate(pipelines), with: Entities::PipelineBasic
end
- desc 'Update a merge request' do
+ desc "Update a merge request" do
success Entities::MergeRequest
end
params do
- optional :title, type: String, allow_blank: false, desc: 'The title of the merge request'
- optional :target_branch, type: String, allow_blank: false, desc: 'The target branch'
+ optional :title, type: String, allow_blank: false, desc: "The title of the merge request"
+ optional :target_branch, type: String, allow_blank: false, desc: "The target branch"
optional :state_event, type: String, values: %w[close reopen],
- desc: 'Status of the merge request'
- optional :discussion_locked, type: Boolean, desc: 'Whether the MR discussion is locked'
+ desc: "Status of the merge request"
+ optional :discussion_locked, type: Boolean, desc: "Whether the MR discussion is locked"
use :optional_params
at_least_one_of(*::API::MergeRequests.update_params_at_least_one_of)
end
- put ':id/merge_requests/:merge_request_iid' do
- Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42318')
+ put ":id/merge_requests/:merge_request_iid" do
+ Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42318")
merge_request = find_merge_request_with_access(params.delete(:merge_request_iid), :update_merge_request)
@@ -338,21 +338,21 @@ module API
end
end
- desc 'Merge a merge request' do
+ desc "Merge a merge request" do
success Entities::MergeRequest
end
params do
- optional :merge_commit_message, type: String, desc: 'Custom merge commit message'
- optional :squash_commit_message, type: String, desc: 'Custom squash commit message'
+ optional :merge_commit_message, type: String, desc: "Custom merge commit message"
+ optional :squash_commit_message, type: String, desc: "Custom squash commit message"
optional :should_remove_source_branch, type: Boolean,
- desc: 'When true, the source branch will be deleted if possible'
+ desc: "When true, the source branch will be deleted if possible"
optional :merge_when_pipeline_succeeds, type: Boolean,
- desc: 'When true, this merge request will be merged when the pipeline succeeds'
- optional :sha, type: String, desc: 'When present, must have the HEAD SHA of the source branch'
- optional :squash, type: Grape::API::Boolean, desc: 'When true, the commits will be squashed into a single commit on merge'
+ desc: "When true, this merge request will be merged when the pipeline succeeds"
+ optional :sha, type: String, desc: "When present, must have the HEAD SHA of the source branch"
+ optional :squash, type: Grape::API::Boolean, desc: "When true, the commits will be squashed into a single commit on merge"
end
- put ':id/merge_requests/:merge_request_iid/merge' do
- Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42317')
+ put ":id/merge_requests/:merge_request_iid/merge" do
+ Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42317")
merge_request = find_project_merge_request(params[:merge_request_iid])
merge_when_pipeline_succeeds = to_boolean(params[:merge_when_pipeline_succeeds])
@@ -363,7 +363,7 @@ module API
not_allowed! unless merge_request.mergeable_state?(skip_ci_check: merge_when_pipeline_succeeds)
- render_api_error!('Branch cannot be merged', 406) unless merge_request.mergeable?(skip_ci_check: merge_when_pipeline_succeeds)
+ render_api_error!("Branch cannot be merged", 406) unless merge_request.mergeable?(skip_ci_check: merge_when_pipeline_succeeds)
check_sha_param!(params, merge_request)
@@ -388,17 +388,17 @@ module API
present merge_request, with: Entities::MergeRequest, current_user: current_user, project: user_project
end
- desc 'Merge a merge request to its default temporary merge ref path'
+ desc "Merge a merge request to its default temporary merge ref path"
params do
- optional :merge_commit_message, type: String, desc: 'Custom merge commit message'
+ optional :merge_commit_message, type: String, desc: "Custom merge commit message"
end
- put ':id/merge_requests/:merge_request_iid/merge_to_ref' do
+ put ":id/merge_requests/:merge_request_iid/merge_to_ref" do
merge_request = find_project_merge_request(params[:merge_request_iid])
authorize! :admin_merge_request, user_project
merge_params = {
- commit_message: params[:merge_commit_message]
+ commit_message: params[:merge_commit_message],
}
result = ::MergeRequests::MergeToRefService
@@ -416,7 +416,7 @@ module API
desc 'Cancel merge if "Merge When Pipeline Succeeds" is enabled' do
success Entities::MergeRequest
end
- post ':id/merge_requests/:merge_request_iid/cancel_merge_when_pipeline_succeeds' do
+ post ":id/merge_requests/:merge_request_iid/cancel_merge_when_pipeline_succeeds" do
merge_request = find_project_merge_request(params[:merge_request_iid])
unauthorized! unless merge_request.can_cancel_merge_when_pipeline_succeeds?(current_user)
@@ -426,10 +426,10 @@ module API
.cancel(merge_request)
end
- desc 'Rebase the merge request against its target branch' do
- detail 'This feature was added in GitLab 11.6'
+ desc "Rebase the merge request against its target branch" do
+ detail "This feature was added in GitLab 11.6"
end
- put ':id/merge_requests/:merge_request_iid/rebase' do
+ put ":id/merge_requests/:merge_request_iid/rebase" do
merge_request = find_project_merge_request(params[:merge_request_iid])
authorize_push_to_merge_request!(merge_request)
@@ -439,13 +439,13 @@ module API
status :accepted
end
- desc 'List issues that will be closed on merge' do
+ desc "List issues that will be closed on merge" do
success Entities::MRNote
end
params do
use :pagination
end
- get ':id/merge_requests/:merge_request_iid/closes_issues' do
+ get ":id/merge_requests/:merge_request_iid/closes_issues" do
merge_request = find_merge_request_with_access(params[:merge_request_iid])
issues = ::Kaminari.paginate_array(merge_request.visible_closing_issues_for(current_user))
issues = paginate(issues)
diff --git a/lib/api/milestone_responses.rb b/lib/api/milestone_responses.rb
index a0ca39b69d4..d2e31a1b57c 100644
--- a/lib/api/milestone_responses.rb
+++ b/lib/api/milestone_responses.rb
@@ -7,24 +7,24 @@ module API
included do
helpers do
params :optional_params do
- optional :description, type: String, desc: 'The description of the milestone'
- optional :due_date, type: String, desc: 'The due date of the milestone. The ISO 8601 date format (%Y-%m-%d)'
- optional :start_date, type: String, desc: 'The start date of the milestone. The ISO 8601 date format (%Y-%m-%d)'
+ optional :description, type: String, desc: "The description of the milestone"
+ optional :due_date, type: String, desc: "The due date of the milestone. The ISO 8601 date format (%Y-%m-%d)"
+ optional :start_date, type: String, desc: "The start date of the milestone. The ISO 8601 date format (%Y-%m-%d)"
end
params :list_params do
- optional :state, type: String, values: %w[active closed all], default: 'all',
+ optional :state, type: String, values: %w[active closed all], default: "all",
desc: 'Return "active", "closed", or "all" milestones'
- optional :iids, type: Array[Integer], desc: 'The IIDs of the milestones'
- optional :search, type: String, desc: 'The search criteria for the title or description of the milestone'
+ optional :iids, type: Array[Integer], desc: "The IIDs of the milestones"
+ optional :search, type: String, desc: "The search criteria for the title or description of the milestone"
use :pagination
end
params :update_params do
- requires :milestone_id, type: Integer, desc: 'The milestone ID number'
- optional :title, type: String, desc: 'The title of the milestone'
+ requires :milestone_id, type: Integer, desc: "The milestone ID number"
+ optional :title, type: String, desc: "The title of the milestone"
optional :state_event, type: String, values: %w[close activate],
- desc: 'The state event of the milestone '
+ desc: "The state event of the milestone "
use :optional_params
at_least_one_of :title, :description, :start_date, :due_date, :state_event
end
@@ -78,7 +78,7 @@ module API
end
def build_finder_params(milestone, parent)
- finder_params = { milestone_title: milestone.title, sort: 'label_priority' }
+ finder_params = {milestone_title: milestone.title, sort: "label_priority"}
if parent.is_a?(Group)
finder_params.merge(group_id: parent.id)
diff --git a/lib/api/namespaces.rb b/lib/api/namespaces.rb
index 3cc09f6ac3f..4e743b74468 100644
--- a/lib/api/namespaces.rb
+++ b/lib/api/namespaces.rb
@@ -18,7 +18,7 @@ module API
end
resource :namespaces do
- desc 'Get a namespaces list' do
+ desc "Get a namespaces list" do
success Entities::Namespace
end
params do
@@ -32,18 +32,18 @@ module API
namespaces = namespaces.search(params[:search]) if params[:search].present?
- options = { with: Entities::Namespace, current_user: current_user }
+ options = {with: Entities::Namespace, current_user: current_user}
present paginate(namespaces), options.reverse_merge(custom_namespace_present_options)
end
- desc 'Get a namespace by ID' do
+ desc "Get a namespace by ID" do
success Entities::Namespace
end
params do
requires :id, type: String, desc: "Namespace's ID or path"
end
- get ':id', requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
+ get ":id", requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
present user_namespace, with: Entities::Namespace, current_user: current_user
end
end
diff --git a/lib/api/notes.rb b/lib/api/notes.rb
index f7bd092ce50..2b4bcbc9aa2 100644
--- a/lib/api/notes.rb
+++ b/lib/api/notes.rb
@@ -23,11 +23,11 @@ module API
success Entities::Note
end
params do
- requires :noteable_id, type: Integer, desc: 'The ID of the noteable'
- optional :order_by, type: String, values: %w[created_at updated_at], default: 'created_at',
- desc: 'Return notes ordered by `created_at` or `updated_at` fields.'
- optional :sort, type: String, values: %w[asc desc], default: 'desc',
- desc: 'Return notes sorted in `asc` or `desc` order.'
+ requires :noteable_id, type: Integer, desc: "The ID of the noteable"
+ optional :order_by, type: String, values: %w[created_at updated_at], default: "created_at",
+ desc: "Return notes ordered by `created_at` or `updated_at` fields."
+ optional :sort, type: String, values: %w[asc desc], default: "desc",
+ desc: "Return notes sorted in `asc` or `desc` order."
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
@@ -45,7 +45,7 @@ module API
# mismatch between the pagination headers info and the actual notes
# array returned, but this is really a edge-case.
paginate(raw_notes)
- .reject { |n| n.cross_reference_not_visible_for?(current_user) }
+ .reject { |n| n.cross_reference_not_visible_for?(current_user) }
present notes, with: Entities::Note
end
# rubocop: enable CodeReuse/ActiveRecord
@@ -54,8 +54,8 @@ module API
success Entities::Note
end
params do
- requires :note_id, type: Integer, desc: 'The ID of a note'
- requires :noteable_id, type: Integer, desc: 'The ID of the noteable'
+ requires :note_id, type: Integer, desc: "The ID of a note"
+ requires :noteable_id, type: Integer, desc: "The ID of the noteable"
end
get ":id/#{noteables_str}/:noteable_id/notes/:note_id" do
noteable = find_noteable(parent_type, noteables_str, params[:noteable_id])
@@ -66,9 +66,9 @@ module API
success Entities::Note
end
params do
- requires :noteable_id, type: Integer, desc: 'The ID of the noteable'
- requires :body, type: String, desc: 'The content of a note'
- optional :created_at, type: String, desc: 'The creation date of the note'
+ requires :noteable_id, type: Integer, desc: "The ID of the noteable"
+ requires :body, type: String, desc: "The content of a note"
+ optional :created_at, type: String, desc: "The creation date of the note"
end
post ":id/#{noteables_str}/:noteable_id/notes" do
noteable = find_noteable(parent_type, noteables_str, params[:noteable_id])
@@ -77,7 +77,7 @@ module API
note: params[:body],
noteable_type: noteables_str.classify,
noteable_id: noteable.id,
- created_at: params[:created_at]
+ created_at: params[:created_at],
}
note = create_note(noteable, opts)
@@ -93,9 +93,9 @@ module API
success Entities::Note
end
params do
- requires :noteable_id, type: Integer, desc: 'The ID of the noteable'
- requires :note_id, type: Integer, desc: 'The ID of a note'
- requires :body, type: String, desc: 'The content of a note'
+ requires :noteable_id, type: Integer, desc: "The ID of the noteable"
+ requires :note_id, type: Integer, desc: "The ID of a note"
+ requires :body, type: String, desc: "The content of a note"
end
put ":id/#{noteables_str}/:noteable_id/notes/:note_id" do
noteable = find_noteable(parent_type, noteables_str, params[:noteable_id])
@@ -107,8 +107,8 @@ module API
success Entities::Note
end
params do
- requires :noteable_id, type: Integer, desc: 'The ID of the noteable'
- requires :note_id, type: Integer, desc: 'The ID of a note'
+ requires :noteable_id, type: Integer, desc: "The ID of the noteable"
+ requires :note_id, type: Integer, desc: "The ID of a note"
end
delete ":id/#{noteables_str}/:noteable_id/notes/:note_id" do
noteable = find_noteable(parent_type, noteables_str, params[:noteable_id])
diff --git a/lib/api/notification_settings.rb b/lib/api/notification_settings.rb
index 8cb46bd3ad6..9ebe5e912cb 100644
--- a/lib/api/notification_settings.rb
+++ b/lib/api/notification_settings.rb
@@ -8,8 +8,8 @@ module API
helpers ::API::Helpers::MembersHelpers
resource :notification_settings do
- desc 'Get global notification level settings and email, defaults to Participate' do
- detail 'This feature was introduced in GitLab 8.12'
+ desc "Get global notification level settings and email, defaults to Participate" do
+ detail "This feature was introduced in GitLab 8.12"
success Entities::GlobalNotificationSetting
end
get do
@@ -18,15 +18,15 @@ module API
present notification_setting, with: Entities::GlobalNotificationSetting
end
- desc 'Update global notification level settings and email, defaults to Participate' do
- detail 'This feature was introduced in GitLab 8.12'
+ desc "Update global notification level settings and email, defaults to Participate" do
+ detail "This feature was introduced in GitLab 8.12"
success Entities::GlobalNotificationSetting
end
params do
- optional :level, type: String, desc: 'The global notification level'
- optional :notification_email, type: String, desc: 'The email address to send notifications'
+ optional :level, type: String, desc: "The global notification level"
+ optional :notification_email, type: String, desc: "The email address to send notifications"
NotificationSetting.email_events.each do |event|
- optional event, type: Boolean, desc: 'Enable/disable this notification'
+ optional event, type: Boolean, desc: "Enable/disable this notification"
end
end
put do
@@ -60,7 +60,7 @@ module API
end
resource source_type.pluralize, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
desc "Get #{source_type} level notification level settings, defaults to Global" do
- detail 'This feature was introduced in GitLab 8.12'
+ detail "This feature was introduced in GitLab 8.12"
success Entities::NotificationSetting
end
get ":id/notification_settings" do
@@ -72,13 +72,13 @@ module API
end
desc "Update #{source_type} level notification level settings, defaults to Global" do
- detail 'This feature was introduced in GitLab 8.12'
+ detail "This feature was introduced in GitLab 8.12"
success Entities::NotificationSetting
end
params do
optional :level, type: String, desc: "The #{source_type} notification level"
NotificationSetting.email_events(source_class).each do |event|
- optional event, type: Boolean, desc: 'Enable/disable this notification'
+ optional event, type: Boolean, desc: "Enable/disable this notification"
end
end
put ":id/notification_settings" do
diff --git a/lib/api/pages_domains.rb b/lib/api/pages_domains.rb
index 78442f465bd..05e1363ab16 100644
--- a/lib/api/pages_domains.rb
+++ b/lib/api/pages_domains.rb
@@ -17,7 +17,7 @@ module API
helpers do
# rubocop: disable CodeReuse/ActiveRecord
def find_pages_domain!
- user_project.pages_domains.find_by(domain: params[:domain]) || not_found!('PagesDomain')
+ user_project.pages_domains.find_by(domain: params[:domain]) || not_found!("PagesDomain")
end
# rubocop: enable CodeReuse/ActiveRecord
@@ -28,7 +28,7 @@ module API
def normalize_params_file_to_string
params.each do |k, v|
if v.is_a?(Hash) && v.key?(:tempfile)
- params[k] = v[:tempfile].to_a.join('')
+ params[k] = v[:tempfile].to_a.join("")
end
end
end
@@ -52,14 +52,14 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
before do
require_pages_enabled!
end
- desc 'Get all pages domains' do
+ desc "Get all pages domains" do
success Entities::PagesDomain
end
params do
@@ -73,11 +73,11 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get a single pages domain' do
+ desc "Get a single pages domain" do
success Entities::PagesDomain
end
params do
- requires :domain, type: String, desc: 'The domain'
+ requires :domain, type: String, desc: "The domain"
end
get ":id/pages/domains/:domain", requirements: PAGES_DOMAINS_ENDPOINT_REQUIREMENTS do
authorize! :read_pages, user_project
@@ -85,13 +85,13 @@ module API
present pages_domain, with: Entities::PagesDomain
end
- desc 'Create a new pages domain' do
+ desc "Create a new pages domain" do
success Entities::PagesDomain
end
params do
- requires :domain, type: String, desc: 'The domain'
- optional :certificate, allow_blank: false, types: [File, String], desc: 'The certificate'
- optional :key, allow_blank: false, types: [File, String], desc: 'The key'
+ requires :domain, type: String, desc: "The domain"
+ optional :certificate, allow_blank: false, types: [File, String], desc: "The certificate"
+ optional :key, allow_blank: false, types: [File, String], desc: "The key"
all_or_none_of :certificate, :key
end
post ":id/pages/domains" do
@@ -107,11 +107,11 @@ module API
end
end
- desc 'Updates a pages domain'
+ desc "Updates a pages domain"
params do
- requires :domain, type: String, desc: 'The domain'
- optional :certificate, allow_blank: false, types: [File, String], desc: 'The certificate'
- optional :key, allow_blank: false, types: [File, String], desc: 'The key'
+ requires :domain, type: String, desc: "The domain"
+ optional :certificate, allow_blank: false, types: [File, String], desc: "The certificate"
+ optional :key, allow_blank: false, types: [File, String], desc: "The key"
end
put ":id/pages/domains/:domain", requirements: PAGES_DOMAINS_ENDPOINT_REQUIREMENTS do
authorize! :update_pages, user_project
@@ -130,9 +130,9 @@ module API
end
end
- desc 'Delete a pages domain'
+ desc "Delete a pages domain"
params do
- requires :domain, type: String, desc: 'The domain'
+ requires :domain, type: String, desc: "The domain"
end
delete ":id/pages/domains/:domain", requirements: PAGES_DOMAINS_ENDPOINT_REQUIREMENTS do
authorize! :update_pages, user_project
diff --git a/lib/api/pagination_params.rb b/lib/api/pagination_params.rb
index ae03595eb25..1fe0d7fb3f0 100644
--- a/lib/api/pagination_params.rb
+++ b/lib/api/pagination_params.rb
@@ -17,8 +17,8 @@ module API
included do
helpers do
params :pagination do
- optional :page, type: Integer, default: 1, desc: 'Current page number'
- optional :per_page, type: Integer, default: 20, desc: 'Number of items per page'
+ optional :page, type: Integer, default: 1, desc: "Current page number"
+ optional :per_page, type: Integer, default: 20, desc: "Number of items per page"
end
end
end
diff --git a/lib/api/pipeline_schedules.rb b/lib/api/pipeline_schedules.rb
index c86b50d3736..687b1bd5af5 100644
--- a/lib/api/pipeline_schedules.rb
+++ b/lib/api/pipeline_schedules.rb
@@ -7,19 +7,19 @@ module API
before { authenticate! }
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get all pipeline schedules' do
+ desc "Get all pipeline schedules" do
success Entities::PipelineSchedule
end
params do
use :pagination
optional :scope, type: String, values: %w[active inactive],
- desc: 'The scope of pipeline schedules'
+ desc: "The scope of pipeline schedules"
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/pipeline_schedules' do
+ get ":id/pipeline_schedules" do
authorize! :read_pipeline_schedule, user_project
schedules = PipelineSchedulesFinder.new(user_project).execute(scope: params[:scope])
@@ -28,27 +28,27 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get a single pipeline schedule' do
+ desc "Get a single pipeline schedule" do
success Entities::PipelineScheduleDetails
end
params do
- requires :pipeline_schedule_id, type: Integer, desc: 'The pipeline schedule id'
+ requires :pipeline_schedule_id, type: Integer, desc: "The pipeline schedule id"
end
- get ':id/pipeline_schedules/:pipeline_schedule_id' do
+ get ":id/pipeline_schedules/:pipeline_schedule_id" do
present pipeline_schedule, with: Entities::PipelineScheduleDetails
end
- desc 'Create a new pipeline schedule' do
+ desc "Create a new pipeline schedule" do
success Entities::PipelineScheduleDetails
end
params do
- requires :description, type: String, desc: 'The description of pipeline schedule'
- requires :ref, type: String, desc: 'The branch/tag name will be triggered', allow_blank: false
- requires :cron, type: String, desc: 'The cron'
- optional :cron_timezone, type: String, default: 'UTC', desc: 'The timezone'
- optional :active, type: Boolean, default: true, desc: 'The activation of pipeline schedule'
+ requires :description, type: String, desc: "The description of pipeline schedule"
+ requires :ref, type: String, desc: "The branch/tag name will be triggered", allow_blank: false
+ requires :cron, type: String, desc: "The cron"
+ optional :cron_timezone, type: String, default: "UTC", desc: "The timezone"
+ optional :active, type: Boolean, default: true, desc: "The activation of pipeline schedule"
end
- post ':id/pipeline_schedules' do
+ post ":id/pipeline_schedules" do
authorize! :create_pipeline_schedule, user_project
pipeline_schedule = Ci::CreatePipelineScheduleService
@@ -62,18 +62,18 @@ module API
end
end
- desc 'Edit a pipeline schedule' do
+ desc "Edit a pipeline schedule" do
success Entities::PipelineScheduleDetails
end
params do
- requires :pipeline_schedule_id, type: Integer, desc: 'The pipeline schedule id'
- optional :description, type: String, desc: 'The description of pipeline schedule'
- optional :ref, type: String, desc: 'The branch/tag name will be triggered'
- optional :cron, type: String, desc: 'The cron'
- optional :cron_timezone, type: String, desc: 'The timezone'
- optional :active, type: Boolean, desc: 'The activation of pipeline schedule'
- end
- put ':id/pipeline_schedules/:pipeline_schedule_id' do
+ requires :pipeline_schedule_id, type: Integer, desc: "The pipeline schedule id"
+ optional :description, type: String, desc: "The description of pipeline schedule"
+ optional :ref, type: String, desc: "The branch/tag name will be triggered"
+ optional :cron, type: String, desc: "The cron"
+ optional :cron_timezone, type: String, desc: "The timezone"
+ optional :active, type: Boolean, desc: "The activation of pipeline schedule"
+ end
+ put ":id/pipeline_schedules/:pipeline_schedule_id" do
authorize! :update_pipeline_schedule, pipeline_schedule
if pipeline_schedule.update(declared_params(include_missing: false))
@@ -83,13 +83,13 @@ module API
end
end
- desc 'Take ownership of a pipeline schedule' do
+ desc "Take ownership of a pipeline schedule" do
success Entities::PipelineScheduleDetails
end
params do
- requires :pipeline_schedule_id, type: Integer, desc: 'The pipeline schedule id'
+ requires :pipeline_schedule_id, type: Integer, desc: "The pipeline schedule id"
end
- post ':id/pipeline_schedules/:pipeline_schedule_id/take_ownership' do
+ post ":id/pipeline_schedules/:pipeline_schedule_id/take_ownership" do
authorize! :update_pipeline_schedule, pipeline_schedule
if pipeline_schedule.own!(current_user)
@@ -99,27 +99,27 @@ module API
end
end
- desc 'Delete a pipeline schedule' do
+ desc "Delete a pipeline schedule" do
success Entities::PipelineScheduleDetails
end
params do
- requires :pipeline_schedule_id, type: Integer, desc: 'The pipeline schedule id'
+ requires :pipeline_schedule_id, type: Integer, desc: "The pipeline schedule id"
end
- delete ':id/pipeline_schedules/:pipeline_schedule_id' do
+ delete ":id/pipeline_schedules/:pipeline_schedule_id" do
authorize! :admin_pipeline_schedule, pipeline_schedule
destroy_conditionally!(pipeline_schedule)
end
- desc 'Create a new pipeline schedule variable' do
+ desc "Create a new pipeline schedule variable" do
success Entities::Variable
end
params do
- requires :pipeline_schedule_id, type: Integer, desc: 'The pipeline schedule id'
- requires :key, type: String, desc: 'The key of the variable'
- requires :value, type: String, desc: 'The value of the variable'
+ requires :pipeline_schedule_id, type: Integer, desc: "The pipeline schedule id"
+ requires :key, type: String, desc: "The key of the variable"
+ requires :value, type: String, desc: "The value of the variable"
end
- post ':id/pipeline_schedules/:pipeline_schedule_id/variables' do
+ post ":id/pipeline_schedules/:pipeline_schedule_id/variables" do
authorize! :update_pipeline_schedule, pipeline_schedule
variable_params = declared_params(include_missing: false)
@@ -131,15 +131,15 @@ module API
end
end
- desc 'Edit a pipeline schedule variable' do
+ desc "Edit a pipeline schedule variable" do
success Entities::Variable
end
params do
- requires :pipeline_schedule_id, type: Integer, desc: 'The pipeline schedule id'
- requires :key, type: String, desc: 'The key of the variable'
- optional :value, type: String, desc: 'The value of the variable'
+ requires :pipeline_schedule_id, type: Integer, desc: "The pipeline schedule id"
+ requires :key, type: String, desc: "The key of the variable"
+ optional :value, type: String, desc: "The value of the variable"
end
- put ':id/pipeline_schedules/:pipeline_schedule_id/variables/:key' do
+ put ":id/pipeline_schedules/:pipeline_schedule_id/variables/:key" do
authorize! :update_pipeline_schedule, pipeline_schedule
if pipeline_schedule_variable.update(declared_params(include_missing: false))
@@ -149,14 +149,14 @@ module API
end
end
- desc 'Delete a pipeline schedule variable' do
+ desc "Delete a pipeline schedule variable" do
success Entities::Variable
end
params do
- requires :pipeline_schedule_id, type: Integer, desc: 'The pipeline schedule id'
- requires :key, type: String, desc: 'The key of the variable'
+ requires :pipeline_schedule_id, type: Integer, desc: "The pipeline schedule id"
+ requires :key, type: String, desc: "The key of the variable"
end
- delete ':id/pipeline_schedules/:pipeline_schedule_id/variables/:key' do
+ delete ":id/pipeline_schedules/:pipeline_schedule_id/variables/:key" do
authorize! :admin_pipeline_schedule, pipeline_schedule
status :accepted
@@ -173,7 +173,7 @@ module API
.preload(:owner, :last_pipeline)
.find_by(id: params.delete(:pipeline_schedule_id)).tap do |pipeline_schedule|
unless can?(current_user, :read_pipeline_schedule, pipeline_schedule)
- not_found!('Pipeline Schedule')
+ not_found!("Pipeline Schedule")
end
end
end
@@ -184,7 +184,7 @@ module API
@pipeline_schedule_variable ||=
pipeline_schedule.variables.find_by(key: params[:key]).tap do |pipeline_schedule_variable|
unless pipeline_schedule_variable
- not_found!('Pipeline Schedule Variable')
+ not_found!("Pipeline Schedule Variable")
end
end
end
diff --git a/lib/api/pipelines.rb b/lib/api/pipelines.rb
index ac8fe98e55e..4c79cd6feaa 100644
--- a/lib/api/pipelines.rb
+++ b/lib/api/pipelines.rb
@@ -7,47 +7,47 @@ module API
before { authenticate! }
params do
- requires :id, type: String, desc: 'The project ID'
+ requires :id, type: String, desc: "The project ID"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get all Pipelines of the project' do
- detail 'This feature was introduced in GitLab 8.11.'
+ desc "Get all Pipelines of the project" do
+ detail "This feature was introduced in GitLab 8.11."
success Entities::PipelineBasic
end
params do
use :pagination
optional :scope, type: String, values: %w[running pending finished branches tags],
- desc: 'The scope of pipelines'
+ desc: "The scope of pipelines"
optional :status, type: String, values: HasStatus::AVAILABLE_STATUSES,
- desc: 'The status of pipelines'
- optional :ref, type: String, desc: 'The ref of pipelines'
- optional :sha, type: String, desc: 'The sha of pipelines'
- optional :yaml_errors, type: Boolean, desc: 'Returns pipelines with invalid configurations'
- optional :name, type: String, desc: 'The name of the user who triggered pipelines'
- optional :username, type: String, desc: 'The username of the user who triggered pipelines'
- optional :order_by, type: String, values: PipelinesFinder::ALLOWED_INDEXED_COLUMNS, default: 'id',
- desc: 'Order pipelines'
- optional :sort, type: String, values: %w[asc desc], default: 'desc',
- desc: 'Sort pipelines'
- end
- get ':id/pipelines' do
+ desc: "The status of pipelines"
+ optional :ref, type: String, desc: "The ref of pipelines"
+ optional :sha, type: String, desc: "The sha of pipelines"
+ optional :yaml_errors, type: Boolean, desc: "Returns pipelines with invalid configurations"
+ optional :name, type: String, desc: "The name of the user who triggered pipelines"
+ optional :username, type: String, desc: "The username of the user who triggered pipelines"
+ optional :order_by, type: String, values: PipelinesFinder::ALLOWED_INDEXED_COLUMNS, default: "id",
+ desc: "Order pipelines"
+ optional :sort, type: String, values: %w[asc desc], default: "desc",
+ desc: "Sort pipelines"
+ end
+ get ":id/pipelines" do
authorize! :read_pipeline, user_project
pipelines = PipelinesFinder.new(user_project, current_user, params).execute
present paginate(pipelines), with: Entities::PipelineBasic
end
- desc 'Create a new pipeline' do
- detail 'This feature was introduced in GitLab 8.14'
+ desc "Create a new pipeline" do
+ detail "This feature was introduced in GitLab 8.14"
success Entities::Pipeline
end
params do
- requires :ref, type: String, desc: 'Reference'
- optional :variables, Array, desc: 'Array of variables available in the pipeline'
+ requires :ref, type: String, desc: "Reference"
+ optional :variables, Array, desc: "Array of variables available in the pipeline"
end
# rubocop: disable CodeReuse/ActiveRecord
- post ':id/pipeline' do
- Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42124')
+ post ":id/pipeline" do
+ Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42124")
authorize! :create_pipeline, user_project
@@ -56,9 +56,9 @@ module API
.except(:variables)
new_pipeline = Ci::CreatePipelineService.new(user_project,
- current_user,
- pipeline_params)
- .execute(:api, ignore_skip_ci: true, save_on_errors: false)
+ current_user,
+ pipeline_params)
+ .execute(:api, ignore_skip_ci: true, save_on_errors: false)
if new_pipeline.persisted?
present new_pipeline, with: Entities::Pipeline
@@ -68,27 +68,27 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Gets a specific pipeline for the project' do
- detail 'This feature was introduced in GitLab 8.11'
+ desc "Gets a specific pipeline for the project" do
+ detail "This feature was introduced in GitLab 8.11"
success Entities::Pipeline
end
params do
- requires :pipeline_id, type: Integer, desc: 'The pipeline ID'
+ requires :pipeline_id, type: Integer, desc: "The pipeline ID"
end
- get ':id/pipelines/:pipeline_id' do
+ get ":id/pipelines/:pipeline_id" do
authorize! :read_pipeline, pipeline
present pipeline, with: Entities::Pipeline
end
- desc 'Deletes a pipeline' do
- detail 'This feature was introduced in GitLab 11.6'
- http_codes [[204, 'Pipeline was deleted'], [403, 'Forbidden']]
+ desc "Deletes a pipeline" do
+ detail "This feature was introduced in GitLab 11.6"
+ http_codes [[204, "Pipeline was deleted"], [403, "Forbidden"]]
end
params do
- requires :pipeline_id, type: Integer, desc: 'The pipeline ID'
+ requires :pipeline_id, type: Integer, desc: "The pipeline ID"
end
- delete ':id/pipelines/:pipeline_id' do
+ delete ":id/pipelines/:pipeline_id" do
authorize! :destroy_pipeline, pipeline
destroy_conditionally!(pipeline) do
@@ -96,14 +96,14 @@ module API
end
end
- desc 'Retry builds in the pipeline' do
- detail 'This feature was introduced in GitLab 8.11.'
+ desc "Retry builds in the pipeline" do
+ detail "This feature was introduced in GitLab 8.11."
success Entities::Pipeline
end
params do
- requires :pipeline_id, type: Integer, desc: 'The pipeline ID'
+ requires :pipeline_id, type: Integer, desc: "The pipeline ID"
end
- post ':id/pipelines/:pipeline_id/retry' do
+ post ":id/pipelines/:pipeline_id/retry" do
authorize! :update_pipeline, pipeline
pipeline.retry_failed(current_user)
@@ -111,14 +111,14 @@ module API
present pipeline, with: Entities::Pipeline
end
- desc 'Cancel all builds in the pipeline' do
- detail 'This feature was introduced in GitLab 8.11.'
+ desc "Cancel all builds in the pipeline" do
+ detail "This feature was introduced in GitLab 8.11."
success Entities::Pipeline
end
params do
- requires :pipeline_id, type: Integer, desc: 'The pipeline ID'
+ requires :pipeline_id, type: Integer, desc: "The pipeline ID"
end
- post ':id/pipelines/:pipeline_id/cancel' do
+ post ":id/pipelines/:pipeline_id/cancel" do
authorize! :update_pipeline, pipeline
pipeline.cancel_running
diff --git a/lib/api/project_clusters.rb b/lib/api/project_clusters.rb
index c96261a7b57..5bcbb095584 100644
--- a/lib/api/project_clusters.rb
+++ b/lib/api/project_clusters.rb
@@ -17,53 +17,53 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of the project'
+ requires :id, type: String, desc: "The ID of the project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get all clusters from the project' do
- detail 'This feature was introduced in GitLab 11.7.'
+ desc "Get all clusters from the project" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::Cluster
end
params do
use :pagination
end
- get ':id/clusters' do
+ get ":id/clusters" do
authorize! :read_cluster, user_project
present paginate(clusters_for_current_user), with: Entities::Cluster
end
- desc 'Get specific cluster for the project' do
- detail 'This feature was introduced in GitLab 11.7.'
+ desc "Get specific cluster for the project" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::ClusterProject
end
params do
- requires :cluster_id, type: Integer, desc: 'The cluster ID'
+ requires :cluster_id, type: Integer, desc: "The cluster ID"
end
- get ':id/clusters/:cluster_id' do
+ get ":id/clusters/:cluster_id" do
authorize! :read_cluster, cluster
present cluster, with: Entities::ClusterProject
end
- desc 'Adds an existing cluster' do
- detail 'This feature was introduced in GitLab 11.7.'
+ desc "Adds an existing cluster" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::ClusterProject
end
params do
- requires :name, type: String, desc: 'Cluster name'
- optional :enabled, type: Boolean, default: true, desc: 'Determines if cluster is active or not, defaults to true'
- requires :platform_kubernetes_attributes, type: Hash, desc: %q(Platform Kubernetes data) do
- requires :api_url, type: String, allow_blank: false, desc: 'URL to access the Kubernetes API'
- requires :token, type: String, desc: 'Token to authenticate against Kubernetes'
- optional :ca_cert, type: String, desc: 'TLS certificate (needed if API is using a self-signed TLS certificate)'
- optional :namespace, type: String, desc: 'Unique namespace related to Project'
- optional :authorization_type, type: String, values: Clusters::Platforms::Kubernetes.authorization_types.keys, default: 'rbac', desc: 'Cluster authorization type, defaults to RBAC'
+ requires :name, type: String, desc: "Cluster name"
+ optional :enabled, type: Boolean, default: true, desc: "Determines if cluster is active or not, defaults to true"
+ requires :platform_kubernetes_attributes, type: Hash, desc: "Platform Kubernetes data" do
+ requires :api_url, type: String, allow_blank: false, desc: "URL to access the Kubernetes API"
+ requires :token, type: String, desc: "Token to authenticate against Kubernetes"
+ optional :ca_cert, type: String, desc: "TLS certificate (needed if API is using a self-signed TLS certificate)"
+ optional :namespace, type: String, desc: "Unique namespace related to Project"
+ optional :authorization_type, type: String, values: Clusters::Platforms::Kubernetes.authorization_types.keys, default: "rbac", desc: "Cluster authorization type, defaults to RBAC"
end
use :create_params_ee
end
- post ':id/clusters/user' do
- authorize! :add_cluster, user_project, 'Instance does not support multiple Kubernetes clusters'
+ post ":id/clusters/user" do
+ authorize! :add_cluster, user_project, "Instance does not support multiple Kubernetes clusters"
user_cluster = ::Clusters::CreateService
.new(current_user, create_cluster_user_params)
@@ -76,22 +76,22 @@ module API
end
end
- desc 'Update an existing cluster' do
- detail 'This feature was introduced in GitLab 11.7.'
+ desc "Update an existing cluster" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::ClusterProject
end
params do
- requires :cluster_id, type: Integer, desc: 'The cluster ID'
- optional :name, type: String, desc: 'Cluster name'
- optional :platform_kubernetes_attributes, type: Hash, desc: %q(Platform Kubernetes data) do
- optional :api_url, type: String, desc: 'URL to access the Kubernetes API'
- optional :token, type: String, desc: 'Token to authenticate against Kubernetes'
- optional :ca_cert, type: String, desc: 'TLS certificate (needed if API is using a self-signed TLS certificate)'
- optional :namespace, type: String, desc: 'Unique namespace related to Project'
+ requires :cluster_id, type: Integer, desc: "The cluster ID"
+ optional :name, type: String, desc: "Cluster name"
+ optional :platform_kubernetes_attributes, type: Hash, desc: "Platform Kubernetes data" do
+ optional :api_url, type: String, desc: "URL to access the Kubernetes API"
+ optional :token, type: String, desc: "Token to authenticate against Kubernetes"
+ optional :ca_cert, type: String, desc: "TLS certificate (needed if API is using a self-signed TLS certificate)"
+ optional :namespace, type: String, desc: "Unique namespace related to Project"
end
use :update_params_ee
end
- put ':id/clusters/:cluster_id' do
+ put ":id/clusters/:cluster_id" do
authorize! :update_cluster, cluster
update_service = Clusters::UpdateService.new(current_user, update_cluster_params)
@@ -103,14 +103,14 @@ module API
end
end
- desc 'Remove a cluster' do
- detail 'This feature was introduced in GitLab 11.7.'
+ desc "Remove a cluster" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::ClusterProject
end
params do
- requires :cluster_id, type: Integer, desc: 'The Cluster ID'
+ requires :cluster_id, type: Integer, desc: "The Cluster ID"
end
- delete ':id/clusters/:cluster_id' do
+ delete ":id/clusters/:cluster_id" do
authorize! :admin_cluster, cluster
destroy_conditionally!(cluster)
@@ -130,7 +130,7 @@ module API
declared_params.merge({
provider_type: :user,
platform_type: :kubernetes,
- clusterable: user_project
+ clusterable: user_project,
})
end
diff --git a/lib/api/project_export.rb b/lib/api/project_export.rb
index e34ed0bdb44..8bd5813416e 100644
--- a/lib/api/project_export.rb
+++ b/lib/api/project_export.rb
@@ -8,47 +8,47 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
- resource :projects, requirements: { id: %r{[^/]+} } do
- desc 'Get export status' do
- detail 'This feature was introduced in GitLab 10.6.'
+ resource :projects, requirements: {id: %r{[^/]+}} do
+ desc "Get export status" do
+ detail "This feature was introduced in GitLab 10.6."
success Entities::ProjectExportStatus
end
- get ':id/export' do
+ get ":id/export" do
present user_project, with: Entities::ProjectExportStatus
end
- desc 'Download export' do
- detail 'This feature was introduced in GitLab 10.6.'
+ desc "Download export" do
+ detail "This feature was introduced in GitLab 10.6."
end
- get ':id/export/download' do
+ get ":id/export/download" do
if user_project.export_file_exists?
present_carrierwave_file!(user_project.export_file)
else
- render_api_error!('404 Not found or has expired', 404)
+ render_api_error!("404 Not found or has expired", 404)
end
end
- desc 'Start export' do
- detail 'This feature was introduced in GitLab 10.6.'
+ desc "Start export" do
+ detail "This feature was introduced in GitLab 10.6."
end
params do
- optional :description, type: String, desc: 'Override the project description'
+ optional :description, type: String, desc: "Override the project description"
optional :upload, type: Hash do
- optional :url, type: String, desc: 'The URL to upload the project'
- optional :http_method, type: String, default: 'PUT', desc: 'HTTP method to upload the exported project'
+ optional :url, type: String, desc: "The URL to upload the project"
+ optional :http_method, type: String, default: "PUT", desc: "HTTP method to upload the exported project"
end
end
- post ':id/export' do
+ post ":id/export" do
project_export_params = declared_params(include_missing: false)
after_export_params = project_export_params.delete(:upload) || {}
export_strategy = if after_export_params[:url].present?
- params = after_export_params.slice(:url, :http_method).symbolize_keys
+ params = after_export_params.slice(:url, :http_method).symbolize_keys
- Gitlab::ImportExport::AfterExportStrategies::WebUploadStrategy.new(params)
- end
+ Gitlab::ImportExport::AfterExportStrategies::WebUploadStrategy.new(params)
+ end
if export_strategy&.invalid?
render_validation_error!(export_strategy)
diff --git a/lib/api/project_hooks.rb b/lib/api/project_hooks.rb
index 0e7576c9243..e4a0a8b90bd 100644
--- a/lib/api/project_hooks.rb
+++ b/lib/api/project_hooks.rb
@@ -27,10 +27,10 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get project hooks' do
+ desc "Get project hooks" do
success Entities::ProjectHook
end
params do
@@ -40,18 +40,18 @@ module API
present paginate(user_project.hooks), with: Entities::ProjectHook
end
- desc 'Get a project hook' do
+ desc "Get a project hook" do
success Entities::ProjectHook
end
params do
- requires :hook_id, type: Integer, desc: 'The ID of a project hook'
+ requires :hook_id, type: Integer, desc: "The ID of a project hook"
end
get ":id/hooks/:hook_id" do
hook = user_project.hooks.find(params[:hook_id])
present hook, with: Entities::ProjectHook
end
- desc 'Add hook to project' do
+ desc "Add hook to project" do
success Entities::ProjectHook
end
params do
@@ -72,7 +72,7 @@ module API
end
end
- desc 'Update an existing project hook' do
+ desc "Update an existing project hook" do
success Entities::ProjectHook
end
params do
@@ -94,11 +94,11 @@ module API
end
end
- desc 'Deletes project hook' do
+ desc "Deletes project hook" do
success Entities::ProjectHook
end
params do
- requires :hook_id, type: Integer, desc: 'The ID of the hook to delete'
+ requires :hook_id, type: Integer, desc: "The ID of the hook to delete"
end
delete ":id/hooks/:hook_id" do
hook = user_project.hooks.find(params.delete(:hook_id))
diff --git a/lib/api/project_import.rb b/lib/api/project_import.rb
index c64ec2fcc95..8aeec7299b6 100644
--- a/lib/api/project_import.rb
+++ b/lib/api/project_import.rb
@@ -11,50 +11,50 @@ module API
end
def file_is_valid?
- import_params[:file] && import_params[:file]['tempfile'].respond_to?(:read)
+ import_params[:file] && import_params[:file]["tempfile"].respond_to?(:read)
end
def validate_file!
- render_api_error!('The file is invalid', 400) unless file_is_valid?
+ render_api_error!("The file is invalid", 400) unless file_is_valid?
end
end
before do
- forbidden! unless Gitlab::CurrentSettings.import_sources.include?('gitlab_project')
+ forbidden! unless Gitlab::CurrentSettings.import_sources.include?("gitlab_project")
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
params do
- requires :path, type: String, desc: 'The new project path and name'
- requires :file, type: File, desc: 'The project export file to be imported'
+ requires :path, type: String, desc: "The new project path and name"
+ requires :file, type: File, desc: "The project export file to be imported"
optional :namespace, type: String, desc: "The ID or name of the namespace that the project will be imported into. Defaults to the current user's namespace."
- optional :overwrite, type: Boolean, default: false, desc: 'If there is a project in the same namespace and with the same name overwrite it'
+ optional :overwrite, type: Boolean, default: false, desc: "If there is a project in the same namespace and with the same name overwrite it"
optional :override_params,
- type: Hash,
- desc: 'New project params to override values in the export' do
+ type: Hash,
+ desc: "New project params to override values in the export" do
use :optional_project_params
end
end
- desc 'Create a new project import' do
- detail 'This feature was introduced in GitLab 10.6.'
+ desc "Create a new project import" do
+ detail "This feature was introduced in GitLab 10.6."
success Entities::ProjectImportStatus
end
- post 'import' do
+ post "import" do
validate_file!
- Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42437')
+ Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42437")
namespace = if import_params[:namespace]
- find_namespace!(import_params[:namespace])
- else
- current_user.namespace
- end
+ find_namespace!(import_params[:namespace])
+ else
+ current_user.namespace
+ end
project_params = {
- path: import_params[:path],
- namespace_id: namespace.id,
- file: import_params[:file]['tempfile'],
- overwrite: import_params[:overwrite]
+ path: import_params[:path],
+ namespace_id: namespace.id,
+ file: import_params[:file]["tempfile"],
+ overwrite: import_params[:overwrite],
}
override_params = import_params.delete(:override_params)
@@ -69,13 +69,13 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
- desc 'Get a project export status' do
- detail 'This feature was introduced in GitLab 10.6.'
+ desc "Get a project export status" do
+ detail "This feature was introduced in GitLab 10.6."
success Entities::ProjectImportStatus
end
- get ':id/import' do
+ get ":id/import" do
present user_project, with: Entities::ProjectImportStatus
end
end
diff --git a/lib/api/project_milestones.rb b/lib/api/project_milestones.rb
index ca24742b7a3..8a31cf1d6f5 100644
--- a/lib/api/project_milestones.rb
+++ b/lib/api/project_milestones.rb
@@ -10,10 +10,10 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get a list of project milestones' do
+ desc "Get a list of project milestones" do
success Entities::Milestone
end
params do
@@ -25,11 +25,11 @@ module API
list_milestones_for(user_project)
end
- desc 'Get a single project milestone' do
+ desc "Get a single project milestone" do
success Entities::Milestone
end
params do
- requires :milestone_id, type: Integer, desc: 'The ID of a project milestone'
+ requires :milestone_id, type: Integer, desc: "The ID of a project milestone"
end
get ":id/milestones/:milestone_id" do
authorize! :read_milestone, user_project
@@ -37,11 +37,11 @@ module API
get_milestone_for(user_project)
end
- desc 'Create a new project milestone' do
+ desc "Create a new project milestone" do
success Entities::Milestone
end
params do
- requires :title, type: String, desc: 'The title of the milestone'
+ requires :title, type: String, desc: "The title of the milestone"
use :optional_params
end
post ":id/milestones" do
@@ -50,7 +50,7 @@ module API
create_milestone_for(user_project)
end
- desc 'Update an existing project milestone' do
+ desc "Update an existing project milestone" do
success Entities::Milestone
end
params do
@@ -62,7 +62,7 @@ module API
update_milestone_for(user_project)
end
- desc 'Remove a project milestone'
+ desc "Remove a project milestone"
delete ":id/milestones/:milestone_id" do
authorize! :admin_milestone, user_project
@@ -72,11 +72,11 @@ module API
status(204)
end
- desc 'Get all issues for a single project milestone' do
+ desc "Get all issues for a single project milestone" do
success Entities::IssueBasic
end
params do
- requires :milestone_id, type: Integer, desc: 'The ID of a project milestone'
+ requires :milestone_id, type: Integer, desc: "The ID of a project milestone"
use :pagination
end
get ":id/milestones/:milestone_id/issues" do
@@ -85,35 +85,33 @@ module API
milestone_issuables_for(user_project, :issue)
end
- desc 'Get all merge requests for a single project milestone' do
- detail 'This feature was introduced in GitLab 9.'
+ desc "Get all merge requests for a single project milestone" do
+ detail "This feature was introduced in GitLab 9."
success Entities::MergeRequestBasic
end
params do
- requires :milestone_id, type: Integer, desc: 'The ID of a project milestone'
+ requires :milestone_id, type: Integer, desc: "The ID of a project milestone"
use :pagination
end
- get ':id/milestones/:milestone_id/merge_requests' do
+ get ":id/milestones/:milestone_id/merge_requests" do
authorize! :read_milestone, user_project
milestone_issuables_for(user_project, :merge_request)
end
- desc 'Promote a milestone to group milestone' do
- detail 'This feature was introduced in GitLab 11.9'
+ desc "Promote a milestone to group milestone" do
+ detail "This feature was introduced in GitLab 11.9"
end
- post ':id/milestones/:milestone_id/promote' do
- begin
- authorize! :admin_milestone, user_project
- authorize! :admin_milestone, user_project.group
+ post ":id/milestones/:milestone_id/promote" do
+ authorize! :admin_milestone, user_project
+ authorize! :admin_milestone, user_project.group
- milestone = user_project.milestones.find(params[:milestone_id])
- Milestones::PromoteService.new(user_project, current_user).execute(milestone)
+ milestone = user_project.milestones.find(params[:milestone_id])
+ Milestones::PromoteService.new(user_project, current_user).execute(milestone)
- status(200)
- rescue Milestones::PromoteService::PromoteMilestoneError => error
- render_api_error!(error.message, 400)
- end
+ status(200)
+ rescue Milestones::PromoteService::PromoteMilestoneError => error
+ render_api_error!(error.message, 400)
end
end
end
diff --git a/lib/api/project_snapshots.rb b/lib/api/project_snapshots.rb
index 175fbb2ce92..92835cb65ae 100644
--- a/lib/api/project_snapshots.rb
+++ b/lib/api/project_snapshots.rb
@@ -7,13 +7,13 @@ module API
before { authorize_read_git_snapshot! }
resource :projects do
- desc 'Download a (possibly inconsistent) snapshot of a repository' do
- detail 'This feature was introduced in GitLab 10.7'
+ desc "Download a (possibly inconsistent) snapshot of a repository" do
+ detail "This feature was introduced in GitLab 10.7"
end
params do
- optional :wiki, type: Boolean, desc: 'Set to true to receive the wiki repository'
+ optional :wiki, type: Boolean, desc: "Set to true to receive the wiki repository"
end
- get ':id/snapshot' do
+ get ":id/snapshot" do
send_git_snapshot(snapshot_repository)
end
end
diff --git a/lib/api/project_snippets.rb b/lib/api/project_snippets.rb
index a607df411a6..416cc7bc084 100644
--- a/lib/api/project_snippets.rb
+++ b/lib/api/project_snippets.rb
@@ -7,7 +7,7 @@ module API
before { authenticate! }
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
helpers do
@@ -24,7 +24,7 @@ module API
end
end
- desc 'Get all project snippets' do
+ desc "Get all project snippets" do
success Entities::ProjectSnippet
end
params do
@@ -34,28 +34,28 @@ module API
present paginate(snippets_for_current_user), with: Entities::ProjectSnippet
end
- desc 'Get a single project snippet' do
+ desc "Get a single project snippet" do
success Entities::ProjectSnippet
end
params do
- requires :snippet_id, type: Integer, desc: 'The ID of a project snippet'
+ requires :snippet_id, type: Integer, desc: "The ID of a project snippet"
end
get ":id/snippets/:snippet_id" do
snippet = snippets_for_current_user.find(params[:snippet_id])
present snippet, with: Entities::ProjectSnippet
end
- desc 'Create a new project snippet' do
+ desc "Create a new project snippet" do
success Entities::ProjectSnippet
end
params do
- requires :title, type: String, desc: 'The title of the snippet'
- requires :file_name, type: String, desc: 'The file name of the snippet'
- requires :code, type: String, allow_blank: false, desc: 'The content of the snippet'
- optional :description, type: String, desc: 'The description of a snippet'
+ requires :title, type: String, desc: "The title of the snippet"
+ requires :file_name, type: String, desc: "The file name of the snippet"
+ requires :code, type: String, allow_blank: false, desc: "The content of the snippet"
+ optional :description, type: String, desc: "The description of a snippet"
requires :visibility, type: String,
values: Gitlab::VisibilityLevel.string_values,
- desc: 'The visibility of the snippet'
+ desc: "The visibility of the snippet"
end
post ":id/snippets" do
authorize! :create_project_snippet, user_project
@@ -73,24 +73,24 @@ module API
end
end
- desc 'Update an existing project snippet' do
+ desc "Update an existing project snippet" do
success Entities::ProjectSnippet
end
params do
- requires :snippet_id, type: Integer, desc: 'The ID of a project snippet'
- optional :title, type: String, desc: 'The title of the snippet'
- optional :file_name, type: String, desc: 'The file name of the snippet'
- optional :code, type: String, allow_blank: false, desc: 'The content of the snippet'
- optional :description, type: String, desc: 'The description of a snippet'
+ requires :snippet_id, type: Integer, desc: "The ID of a project snippet"
+ optional :title, type: String, desc: "The title of the snippet"
+ optional :file_name, type: String, desc: "The file name of the snippet"
+ optional :code, type: String, allow_blank: false, desc: "The content of the snippet"
+ optional :description, type: String, desc: "The description of a snippet"
optional :visibility, type: String,
values: Gitlab::VisibilityLevel.string_values,
- desc: 'The visibility of the snippet'
+ desc: "The visibility of the snippet"
at_least_one_of :title, :file_name, :code, :visibility_level
end
# rubocop: disable CodeReuse/ActiveRecord
put ":id/snippets/:snippet_id" do
snippet = snippets_for_current_user.find_by(id: params.delete(:snippet_id))
- not_found!('Snippet') unless snippet
+ not_found!("Snippet") unless snippet
authorize! :update_project_snippet, snippet
@@ -100,7 +100,7 @@ module API
snippet_params[:content] = snippet_params.delete(:code) if snippet_params[:code].present?
UpdateSnippetService.new(user_project, current_user, snippet,
- snippet_params).execute
+ snippet_params).execute
render_spam_error! if snippet.spam?
@@ -112,14 +112,14 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Delete a project snippet'
+ desc "Delete a project snippet"
params do
- requires :snippet_id, type: Integer, desc: 'The ID of a project snippet'
+ requires :snippet_id, type: Integer, desc: "The ID of a project snippet"
end
# rubocop: disable CodeReuse/ActiveRecord
delete ":id/snippets/:snippet_id" do
snippet = snippets_for_current_user.find_by(id: params[:snippet_id])
- not_found!('Snippet') unless snippet
+ not_found!("Snippet") unless snippet
authorize! :admin_project_snippet, snippet
@@ -127,26 +127,26 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get a raw project snippet'
+ desc "Get a raw project snippet"
params do
- requires :snippet_id, type: Integer, desc: 'The ID of a project snippet'
+ requires :snippet_id, type: Integer, desc: "The ID of a project snippet"
end
# rubocop: disable CodeReuse/ActiveRecord
get ":id/snippets/:snippet_id/raw" do
snippet = snippets_for_current_user.find_by(id: params[:snippet_id])
- not_found!('Snippet') unless snippet
+ not_found!("Snippet") unless snippet
- env['api.format'] = :txt
- content_type 'text/plain'
+ env["api.format"] = :txt
+ content_type "text/plain"
present snippet.content
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get the user agent details for a project snippet' do
+ desc "Get the user agent details for a project snippet" do
success Entities::UserAgentDetail
end
params do
- requires :snippet_id, type: Integer, desc: 'The ID of a project snippet'
+ requires :snippet_id, type: Integer, desc: "The ID of a project snippet"
end
# rubocop: disable CodeReuse/ActiveRecord
get ":id/snippets/:snippet_id/user_agent_detail" do
@@ -154,7 +154,7 @@ module API
snippet = Snippet.find_by!(id: params[:snippet_id], project_id: params[:id])
- break not_found!('UserAgentDetail') unless snippet.user_agent_detail
+ break not_found!("UserAgentDetail") unless snippet.user_agent_detail
present snippet.user_agent_detail, with: Entities::UserAgentDetail
end
diff --git a/lib/api/project_statistics.rb b/lib/api/project_statistics.rb
index 2f73785f72d..6cf765ea7b8 100644
--- a/lib/api/project_statistics.rb
+++ b/lib/api/project_statistics.rb
@@ -9,10 +9,10 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get the list of project fetch statistics for the last 30 days'
+ desc "Get the list of project fetch statistics for the last 30 days"
get ":id/statistics" do
statistic_finder = ::Projects::DailyStatisticsFinder.new(user_project)
diff --git a/lib/api/project_templates.rb b/lib/api/project_templates.rb
index 119902a189c..ed2cb991eab 100644
--- a/lib/api/project_templates.rb
+++ b/lib/api/project_templates.rb
@@ -9,17 +9,17 @@ module API
before { authenticate_non_get! }
params do
- requires :id, type: String, desc: 'The ID of a project'
- requires :type, type: String, values: TEMPLATE_TYPES, desc: 'The type (dockerfiles|gitignores|gitlab_ci_ymls|licenses) of the template'
+ requires :id, type: String, desc: "The ID of a project"
+ requires :type, type: String, values: TEMPLATE_TYPES, desc: "The type (dockerfiles|gitignores|gitlab_ci_ymls|licenses) of the template"
end
resource :projects do
- desc 'Get a list of templates available to this project' do
- detail 'This endpoint was introduced in GitLab 11.4'
+ desc "Get a list of templates available to this project" do
+ detail "This endpoint was introduced in GitLab 11.4"
end
params do
use :pagination
end
- get ':id/templates/:type' do
+ get ":id/templates/:type" do
templates = TemplateFinder
.build(params[:type], user_project)
.execute
@@ -27,24 +27,24 @@ module API
present paginate(::Kaminari.paginate_array(templates)), with: Entities::TemplatesList
end
- desc 'Download a template available to this project' do
- detail 'This endpoint was introduced in GitLab 11.4'
+ desc "Download a template available to this project" do
+ detail "This endpoint was introduced in GitLab 11.4"
end
params do
- requires :name, type: String, desc: 'The name of the template'
+ requires :name, type: String, desc: "The name of the template"
- optional :project, type: String, desc: 'The project name to use when expanding placeholders in the template. Only affects licenses'
- optional :fullname, type: String, desc: 'The full name of the copyright holder to use when expanding placeholders in the template. Only affects licenses'
+ optional :project, type: String, desc: "The project name to use when expanding placeholders in the template. Only affects licenses"
+ optional :fullname, type: String, desc: "The full name of the copyright holder to use when expanding placeholders in the template. Only affects licenses"
end
# The regex is needed to ensure a period (e.g. agpl-3.0)
# isn't confused with a format type. We also need to allow encoded
# values (e.g. C%2B%2B for C++), so allow % and + as well.
- get ':id/templates/:type/:name', requirements: { name: /[\w%.+-]+/ } do
+ get ":id/templates/:type/:name", requirements: {name: /[\w%.+-]+/} do
template = TemplateFinder
.build(params[:type], user_project, name: params[:name])
.execute
- not_found!('Template') unless template.present?
+ not_found!("Template") unless template.present?
template.resolve!(
project_name: params[:project].presence,
diff --git a/lib/api/projects.rb b/lib/api/projects.rb
index b23fe6cd4e7..3be654dcdc7 100644
--- a/lib/api/projects.rb
+++ b/lib/api/projects.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_dependency 'declarative_policy'
+require_dependency "declarative_policy"
module API
class Projects < Grape::API
@@ -59,13 +59,13 @@ module API
:tag_list,
:visibility,
:wiki_enabled,
- :avatar
+ :avatar,
]
end
helpers do
params :statistics_params do
- optional :statistics, type: Boolean, default: false, desc: 'Include project statistics'
+ optional :statistics, type: Boolean, default: false, desc: "Include project statistics"
end
params :collection_params do
@@ -74,35 +74,35 @@ module API
use :pagination
optional :simple, type: Boolean, default: false,
- desc: 'Return only the ID, URL, name, and path of each project'
+ desc: "Return only the ID, URL, name, and path of each project"
end
params :sort_params do
optional :order_by, type: String, values: %w[id name path created_at updated_at last_activity_at],
- default: 'created_at', desc: 'Return projects ordered by field'
- optional :sort, type: String, values: %w[asc desc], default: 'desc',
- desc: 'Return projects sorted in ascending and descending order'
+ default: "created_at", desc: "Return projects ordered by field"
+ optional :sort, type: String, values: %w[asc desc], default: "desc",
+ desc: "Return projects sorted in ascending and descending order"
end
params :filter_params do
- optional :archived, type: Boolean, desc: 'Limit by archived status'
+ optional :archived, type: Boolean, desc: "Limit by archived status"
optional :visibility, type: String, values: Gitlab::VisibilityLevel.string_values,
- desc: 'Limit by visibility'
- optional :search, type: String, desc: 'Return list of projects matching the search criteria'
- optional :owned, type: Boolean, default: false, desc: 'Limit by owned by authenticated user'
- optional :starred, type: Boolean, default: false, desc: 'Limit by starred status'
- optional :membership, type: Boolean, default: false, desc: 'Limit by projects that the current user is a member of'
- optional :with_issues_enabled, type: Boolean, default: false, desc: 'Limit by enabled issues feature'
- optional :with_merge_requests_enabled, type: Boolean, default: false, desc: 'Limit by enabled merge requests feature'
- optional :with_programming_language, type: String, desc: 'Limit to repositories which use the given programming language'
- optional :min_access_level, type: Integer, values: Gitlab::Access.all_values, desc: 'Limit by minimum access level of authenticated user'
+ desc: "Limit by visibility"
+ optional :search, type: String, desc: "Return list of projects matching the search criteria"
+ optional :owned, type: Boolean, default: false, desc: "Limit by owned by authenticated user"
+ optional :starred, type: Boolean, default: false, desc: "Limit by starred status"
+ optional :membership, type: Boolean, default: false, desc: "Limit by projects that the current user is a member of"
+ optional :with_issues_enabled, type: Boolean, default: false, desc: "Limit by enabled issues feature"
+ optional :with_merge_requests_enabled, type: Boolean, default: false, desc: "Limit by enabled merge requests feature"
+ optional :with_programming_language, type: String, desc: "Limit to repositories which use the given programming language"
+ optional :min_access_level, type: Integer, values: Gitlab::Access.all_values, desc: "Limit by minimum access level of authenticated user"
use :optional_filter_params_ee
end
params :create_params do
- optional :namespace_id, type: Integer, desc: 'Namespace ID for the new project. Default to the user namespace.'
- optional :import_url, type: String, desc: 'URL from which the project is imported'
+ optional :namespace_id, type: Integer, desc: "Namespace ID for the new project. Default to the user namespace."
+ optional :import_url, type: String, desc: "URL from which the project is imported"
end
def load_projects
@@ -133,18 +133,18 @@ module API
end
resource :users, requirements: API::USER_REQUIREMENTS do
- desc 'Get a user projects' do
+ desc "Get a user projects" do
success Entities::BasicProjectDetails
end
params do
- requires :user_id, type: String, desc: 'The ID or username of the user'
+ requires :user_id, type: String, desc: "The ID or username of the user"
use :collection_params
use :statistics_params
use :with_custom_attributes
end
get ":user_id/projects" do
user = find_user(params[:user_id])
- not_found!('User') unless user
+ not_found!("User") unless user
params[:user] = user
@@ -155,7 +155,7 @@ module API
resource :projects do
include CustomAttributesEndpoints
- desc 'Get a list of visible projects for authenticated user' do
+ desc "Get a list of visible projects for authenticated user" do
success Entities::BasicProjectDetails
end
params do
@@ -167,12 +167,12 @@ module API
present_projects load_projects
end
- desc 'Create new project' do
+ desc "Create new project" do
success Entities::Project
end
params do
- optional :name, type: String, desc: 'The name of the project'
- optional :path, type: String, desc: 'The path of the repository'
+ optional :name, type: String, desc: "The name of the project"
+ optional :path, type: String, desc: "The path of the repository"
at_least_one_of :name, :path
use :optional_project_params
use :create_params
@@ -194,14 +194,14 @@ module API
end
end
- desc 'Create new project for a specified user. Only available to admin users.' do
+ desc "Create new project for a specified user. Only available to admin users." do
success Entities::Project
end
params do
- requires :name, type: String, desc: 'The name of the project'
- requires :user_id, type: Integer, desc: 'The ID of a user'
- optional :path, type: String, desc: 'The path of the repository'
- optional :default_branch, type: String, desc: 'The default branch of the project'
+ requires :name, type: String, desc: "The name of the project"
+ requires :user_id, type: Integer, desc: "The ID of a user"
+ optional :path, type: String, desc: "The path of the repository"
+ optional :default_branch, type: String, desc: "The default branch of the project"
use :optional_project_params
use :create_params
end
@@ -209,7 +209,7 @@ module API
post "user/:user_id" do
authenticated_as_admin!
user = User.find_by(id: params.delete(:user_id))
- not_found!('User') unless user
+ not_found!("User") unless user
attrs = declared_params(include_missing: false)
attrs = translate_params_for_compatibility(attrs)
@@ -226,10 +226,10 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get a single project' do
+ desc "Get a single project" do
success Entities::ProjectWithAccess
end
params do
@@ -237,7 +237,7 @@ module API
use :with_custom_attributes
optional :license, type: Boolean, default: false,
- desc: 'Include project license data'
+ desc: "Include project license data"
end
get ":id" do
options = {
@@ -245,7 +245,7 @@ module API
current_user: current_user,
user_can_admin_project: can?(current_user, :admin_project, user_project),
statistics: params[:statistics],
- license: params[:license]
+ license: params[:license],
}
project, options = with_custom_attributes(user_project, options)
@@ -253,16 +253,16 @@ module API
present project, options
end
- desc 'Fork new project for the current user or provided namespace.' do
+ desc "Fork new project for the current user or provided namespace." do
success Entities::Project
end
params do
- optional :namespace, type: String, desc: 'The ID or name of the namespace that the project will be forked into'
- optional :path, type: String, desc: 'The path that will be assigned to the fork'
- optional :name, type: String, desc: 'The name that will be assigned to the fork'
+ optional :namespace, type: String, desc: "The ID or name of the namespace that the project will be forked into"
+ optional :path, type: String, desc: "The path that will be assigned to the fork"
+ optional :name, type: String, desc: "The name that will be assigned to the fork"
end
- post ':id/fork' do
- Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42284')
+ post ":id/fork" do
+ Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42284")
fork_params = declared_params(include_missing: false)
namespace_id = fork_params[:namespace]
@@ -271,7 +271,7 @@ module API
fork_params[:namespace] = find_namespace(namespace_id)
unless fork_params[:namespace] && can?(current_user, :create_projects, fork_params[:namespace])
- not_found!('Target Namespace')
+ not_found!("Target Namespace")
end
end
@@ -285,38 +285,38 @@ module API
end
end
- desc 'List forks of this project' do
+ desc "List forks of this project" do
success Entities::Project
end
params do
use :collection_params
use :with_custom_attributes
end
- get ':id/forks' do
+ get ":id/forks" do
forks = ForkProjectsFinder.new(user_project, params: project_finder_params, current_user: current_user).execute
present_projects forks
end
- desc 'Check pages access of this project'
- get ':id/pages_access' do
+ desc "Check pages access of this project"
+ get ":id/pages_access" do
authorize! :read_pages_content, user_project unless user_project.public_pages?
status 200
end
- desc 'Update an existing project' do
+ desc "Update an existing project" do
success Entities::Project
end
params do
- optional :name, type: String, desc: 'The name of the project'
- optional :default_branch, type: String, desc: 'The default branch of the project'
- optional :path, type: String, desc: 'The path of the repository'
+ optional :name, type: String, desc: "The name of the project"
+ optional :default_branch, type: String, desc: "The default branch of the project"
+ optional :path, type: String, desc: "The path of the repository"
use :optional_project_params
at_least_one_of(*::API::Projects.update_params_at_least_one_of)
end
- put ':id' do
+ put ":id" do
authorize_admin_project
attrs = declared_params(include_missing: false)
authorize! :rename_project, user_project if attrs[:name].present?
@@ -336,10 +336,10 @@ module API
end
end
- desc 'Archive a project' do
+ desc "Archive a project" do
success Entities::Project
end
- post ':id/archive' do
+ post ":id/archive" do
authorize!(:archive_project, user_project)
::Projects::UpdateService.new(user_project, current_user, archived: true).execute
@@ -347,10 +347,10 @@ module API
present user_project, with: Entities::Project
end
- desc 'Unarchive a project' do
+ desc "Unarchive a project" do
success Entities::Project
end
- post ':id/unarchive' do
+ post ":id/unarchive" do
authorize!(:archive_project, user_project)
::Projects::UpdateService.new(@project, current_user, archived: false).execute
@@ -358,10 +358,10 @@ module API
present user_project, with: Entities::Project
end
- desc 'Star a project' do
+ desc "Star a project" do
success Entities::Project
end
- post ':id/star' do
+ post ":id/star" do
if current_user.starred?(user_project)
not_modified!
else
@@ -372,10 +372,10 @@ module API
end
end
- desc 'Unstar a project' do
+ desc "Unstar a project" do
success Entities::Project
end
- post ':id/unstar' do
+ post ":id/unstar" do
if current_user.starred?(user_project)
current_user.toggle_star(user_project)
user_project.reload
@@ -386,8 +386,8 @@ module API
end
end
- desc 'Get languages in project repository'
- get ':id/languages' do
+ desc "Get languages in project repository"
+ get ":id/languages" do
if user_project.repository_languages.present?
user_project.repository_languages.map { |l| [l.name, l.share] }.to_h
else
@@ -395,7 +395,7 @@ module API
end
end
- desc 'Remove a project'
+ desc "Remove a project"
delete ":id" do
authorize! :remove_project, user_project
@@ -406,9 +406,9 @@ module API
accepted!
end
- desc 'Mark this project as forked from another'
+ desc "Mark this project as forked from another"
params do
- requires :forked_from_id, type: String, desc: 'The ID of the project it was forked from'
+ requires :forked_from_id, type: String, desc: "The ID of the project it was forked from"
end
post ":id/fork/:forked_from_id" do
authorize! :admin_project, user_project
@@ -426,31 +426,31 @@ module API
end
end
- desc 'Remove a forked_from relationship'
+ desc "Remove a forked_from relationship"
delete ":id/fork" do
authorize! :remove_fork_project, user_project
- result = destroy_conditionally!(user_project) do
+ result = destroy_conditionally!(user_project) {
::Projects::UnlinkForkService.new(user_project, current_user).execute
- end
+ }
result ? status(204) : not_modified!
end
- desc 'Share the project with a group' do
+ desc "Share the project with a group" do
success Entities::ProjectGroupLink
end
params do
- requires :group_id, type: Integer, desc: 'The ID of a group'
- requires :group_access, type: Integer, values: Gitlab::Access.values, desc: 'The group access level'
- optional :expires_at, type: Date, desc: 'Share expiration date'
+ requires :group_id, type: Integer, desc: "The ID of a group"
+ requires :group_access, type: Integer, values: Gitlab::Access.values, desc: "The group access level"
+ optional :expires_at, type: Date, desc: "Share expiration date"
end
post ":id/share" do
authorize! :admin_project, user_project
group = Group.find_by_id(params[:group_id])
unless group && can?(current_user, :read_group, group)
- not_found!('Group')
+ not_found!("Group")
end
unless user_project.allowed_to_share_with_group?
@@ -467,45 +467,45 @@ module API
end
params do
- requires :group_id, type: Integer, desc: 'The ID of the group'
+ requires :group_id, type: Integer, desc: "The ID of the group"
end
# rubocop: disable CodeReuse/ActiveRecord
delete ":id/share/:group_id" do
authorize! :admin_project, user_project
link = user_project.project_group_links.find_by(group_id: params[:group_id])
- not_found!('Group Link') unless link
+ not_found!("Group Link") unless link
destroy_conditionally!(link)
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Upload a file'
+ desc "Upload a file"
params do
- requires :file, type: File, desc: 'The file to be uploaded'
+ requires :file, type: File, desc: "The file to be uploaded"
end
post ":id/uploads" do
UploadService.new(user_project, params[:file]).execute.to_h
end
- desc 'Get the users list of a project' do
+ desc "Get the users list of a project" do
success Entities::UserBasic
end
params do
- optional :search, type: String, desc: 'Return list of users matching the search criteria'
+ optional :search, type: String, desc: "Return list of users matching the search criteria"
use :pagination
end
- get ':id/users' do
+ get ":id/users" do
users = DeclarativePolicy.subject_scope { user_project.team.users }
users = users.search(params[:search]) if params[:search].present?
present paginate(users), with: Entities::UserBasic
end
- desc 'Start the housekeeping task for a project' do
- detail 'This feature was introduced in GitLab 9.0.'
+ desc "Start the housekeeping task for a project" do
+ detail "This feature was introduced in GitLab 9.0."
end
- post ':id/housekeeping' do
+ post ":id/housekeeping" do
authorize_admin_project
begin
@@ -515,9 +515,9 @@ module API
end
end
- desc 'Transfer a project to a new namespace'
+ desc "Transfer a project to a new namespace"
params do
- requires :namespace, type: String, desc: 'The ID or path of the new namespace'
+ requires :namespace, type: String, desc: "The ID or path of the new namespace"
end
put ":id/transfer" do
authorize! :change_namespace, user_project
diff --git a/lib/api/protected_branches.rb b/lib/api/protected_branches.rb
index 5af43448727..b562ea7d529 100644
--- a/lib/api/protected_branches.rb
+++ b/lib/api/protected_branches.rb
@@ -9,7 +9,7 @@ module API
before { authorize_admin_project }
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
desc "Get a project's protected branches" do
@@ -19,41 +19,41 @@ module API
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/protected_branches' do
+ get ":id/protected_branches" do
protected_branches = user_project.protected_branches.preload(:push_access_levels, :merge_access_levels)
present paginate(protected_branches), with: Entities::ProtectedBranch, project: user_project
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get a single protected branch' do
+ desc "Get a single protected branch" do
success Entities::ProtectedBranch
end
params do
- requires :name, type: String, desc: 'The name of the branch or wildcard'
+ requires :name, type: String, desc: "The name of the branch or wildcard"
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/protected_branches/:name', requirements: BRANCH_ENDPOINT_REQUIREMENTS do
+ get ":id/protected_branches/:name", requirements: BRANCH_ENDPOINT_REQUIREMENTS do
protected_branch = user_project.protected_branches.find_by!(name: params[:name])
present protected_branch, with: Entities::ProtectedBranch, project: user_project
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Protect a single branch or wildcard' do
+ desc "Protect a single branch or wildcard" do
success Entities::ProtectedBranch
end
params do
- requires :name, type: String, desc: 'The name of the protected branch'
+ requires :name, type: String, desc: "The name of the protected branch"
optional :push_access_level, type: Integer,
values: ProtectedBranch::PushAccessLevel.allowed_access_levels,
- desc: 'Access levels allowed to push (defaults: `40`, maintainer access level)'
+ desc: "Access levels allowed to push (defaults: `40`, maintainer access level)"
optional :merge_access_level, type: Integer,
values: ProtectedBranch::MergeAccessLevel.allowed_access_levels,
- desc: 'Access levels allowed to merge (defaults: `40`, maintainer access level)'
+ desc: "Access levels allowed to merge (defaults: `40`, maintainer access level)"
end
# rubocop: disable CodeReuse/ActiveRecord
- post ':id/protected_branches' do
+ post ":id/protected_branches" do
protected_branch = user_project.protected_branches.find_by(name: params[:name])
if protected_branch
conflict!("Protected branch '#{params[:name]}' already exists")
@@ -71,12 +71,12 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Unprotect a single branch'
+ desc "Unprotect a single branch"
params do
- requires :name, type: String, desc: 'The name of the protected branch'
+ requires :name, type: String, desc: "The name of the protected branch"
end
# rubocop: disable CodeReuse/ActiveRecord
- delete ':id/protected_branches/:name', requirements: BRANCH_ENDPOINT_REQUIREMENTS do
+ delete ":id/protected_branches/:name", requirements: BRANCH_ENDPOINT_REQUIREMENTS do
protected_branch = user_project.protected_branches.find_by!(name: params[:name])
destroy_conditionally!(protected_branch) do
diff --git a/lib/api/protected_tags.rb b/lib/api/protected_tags.rb
index ee13473c848..8ef1beab610 100644
--- a/lib/api/protected_tags.rb
+++ b/lib/api/protected_tags.rb
@@ -9,58 +9,58 @@ module API
before { authorize_admin_project }
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
desc "Get a project's protected tags" do
- detail 'This feature was introduced in GitLab 11.3.'
+ detail "This feature was introduced in GitLab 11.3."
success Entities::ProtectedTag
end
params do
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/protected_tags' do
+ get ":id/protected_tags" do
protected_tags = user_project.protected_tags.preload(:create_access_levels)
present paginate(protected_tags), with: Entities::ProtectedTag, project: user_project
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get a single protected tag' do
- detail 'This feature was introduced in GitLab 11.3.'
+ desc "Get a single protected tag" do
+ detail "This feature was introduced in GitLab 11.3."
success Entities::ProtectedTag
end
params do
- requires :name, type: String, desc: 'The name of the tag or wildcard'
+ requires :name, type: String, desc: "The name of the tag or wildcard"
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/protected_tags/:name', requirements: TAG_ENDPOINT_REQUIREMENTS do
+ get ":id/protected_tags/:name", requirements: TAG_ENDPOINT_REQUIREMENTS do
protected_tag = user_project.protected_tags.find_by!(name: params[:name])
present protected_tag, with: Entities::ProtectedTag, project: user_project
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Protect a single tag or wildcard' do
- detail 'This feature was introduced in GitLab 11.3.'
+ desc "Protect a single tag or wildcard" do
+ detail "This feature was introduced in GitLab 11.3."
success Entities::ProtectedTag
end
params do
- requires :name, type: String, desc: 'The name of the protected tag'
+ requires :name, type: String, desc: "The name of the protected tag"
optional :create_access_level, type: Integer, default: Gitlab::Access::MAINTAINER,
values: ProtectedTag::CreateAccessLevel.allowed_access_levels,
- desc: 'Access levels allowed to create (defaults: `40`, maintainer access level)'
+ desc: "Access levels allowed to create (defaults: `40`, maintainer access level)"
end
- post ':id/protected_tags' do
+ post ":id/protected_tags" do
protected_tags_params = {
name: params[:name],
- create_access_levels_attributes: [{ access_level: params[:create_access_level] }]
+ create_access_levels_attributes: [{access_level: params[:create_access_level]}],
}
protected_tag = ::ProtectedTags::CreateService.new(user_project,
- current_user,
- protected_tags_params).execute
+ current_user,
+ protected_tags_params).execute
if protected_tag.persisted?
present protected_tag, with: Entities::ProtectedTag, project: user_project
@@ -69,14 +69,14 @@ module API
end
end
- desc 'Unprotect a single tag' do
- detail 'This feature was introduced in GitLab 11.3.'
+ desc "Unprotect a single tag" do
+ detail "This feature was introduced in GitLab 11.3."
end
params do
- requires :name, type: String, desc: 'The name of the protected tag'
+ requires :name, type: String, desc: "The name of the protected tag"
end
# rubocop: disable CodeReuse/ActiveRecord
- delete ':id/protected_tags/:name', requirements: TAG_ENDPOINT_REQUIREMENTS do
+ delete ":id/protected_tags/:name", requirements: TAG_ENDPOINT_REQUIREMENTS do
protected_tag = user_project.protected_tags.find_by!(name: params[:name])
destroy_conditionally!(protected_tag)
diff --git a/lib/api/release/links.rb b/lib/api/release/links.rb
index e3072684ef7..f1a70f2a4bc 100644
--- a/lib/api/release/links.rb
+++ b/lib/api/release/links.rb
@@ -9,36 +9,36 @@ module API
.merge(tag_name: API::NO_SLASH_URL_PART_REGEX)
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
- resource 'projects/:id', requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
+ resource "projects/:id", requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
params do
- requires :tag_name, type: String, desc: 'The name of the tag', as: :tag
+ requires :tag_name, type: String, desc: "The name of the tag", as: :tag
end
- resource 'releases/:tag_name', requirements: RELEASE_ENDPOINT_REQUIREMETS do
+ resource "releases/:tag_name", requirements: RELEASE_ENDPOINT_REQUIREMETS do
resource :assets do
- desc 'Get a list of links of a release' do
- detail 'This feature was introduced in GitLab 11.7.'
+ desc "Get a list of links of a release" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::Releases::Link
end
params do
use :pagination
end
- get 'links' do
+ get "links" do
authorize! :read_release, release
present paginate(release.links.sorted), with: Entities::Releases::Link
end
- desc 'Create a link of a release' do
- detail 'This feature was introduced in GitLab 11.7.'
+ desc "Create a link of a release" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::Releases::Link
end
params do
- requires :name, type: String, desc: 'The name of the link'
- requires :url, type: String, desc: 'The URL of the link'
+ requires :name, type: String, desc: "The name of the link"
+ requires :url, type: String, desc: "The URL of the link"
end
- post 'links' do
+ post "links" do
authorize! :create_release, release
new_link = release.links.create(declared_params(include_missing: false))
@@ -51,11 +51,11 @@ module API
end
params do
- requires :link_id, type: String, desc: 'The id of the link'
+ requires :link_id, type: String, desc: "The id of the link"
end
- resource 'links/:link_id' do
- desc 'Get a link detail of a release' do
- detail 'This feature was introduced in GitLab 11.7.'
+ resource "links/:link_id" do
+ desc "Get a link detail of a release" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::Releases::Link
end
get do
@@ -64,13 +64,13 @@ module API
present link, with: Entities::Releases::Link
end
- desc 'Update a link of a release' do
- detail 'This feature was introduced in GitLab 11.7.'
+ desc "Update a link of a release" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::Releases::Link
end
params do
- optional :name, type: String, desc: 'The name of the link'
- optional :url, type: String, desc: 'The URL of the link'
+ optional :name, type: String, desc: "The name of the link"
+ optional :url, type: String, desc: "The URL of the link"
at_least_one_of :name, :url
end
put do
@@ -83,8 +83,8 @@ module API
end
end
- desc 'Delete a link of a release' do
- detail 'This feature was introduced in GitLab 11.7.'
+ desc "Delete a link of a release" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::Releases::Link
end
delete do
diff --git a/lib/api/releases.rb b/lib/api/releases.rb
index cb85028f22c..b608c237cff 100644
--- a/lib/api/releases.rb
+++ b/lib/api/releases.rb
@@ -10,44 +10,44 @@ module API
before { authorize_read_releases! }
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get a project releases' do
- detail 'This feature was introduced in GitLab 11.7.'
+ desc "Get a project releases" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::Release
end
params do
use :pagination
end
- get ':id/releases' do
+ get ":id/releases" do
releases = ::ReleasesFinder.new(user_project, current_user).execute
present paginate(releases), with: Entities::Release
end
- desc 'Get a single project release' do
- detail 'This feature was introduced in GitLab 11.7.'
+ desc "Get a single project release" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::Release
end
params do
- requires :tag_name, type: String, desc: 'The name of the tag', as: :tag
+ requires :tag_name, type: String, desc: "The name of the tag", as: :tag
end
- get ':id/releases/:tag_name', requirements: RELEASE_ENDPOINT_REQUIREMETS do
+ get ":id/releases/:tag_name", requirements: RELEASE_ENDPOINT_REQUIREMETS do
authorize_read_release!
present release, with: Entities::Release
end
- desc 'Create a new release' do
- detail 'This feature was introduced in GitLab 11.7.'
+ desc "Create a new release" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::Release
end
params do
- requires :tag_name, type: String, desc: 'The name of the tag', as: :tag
- requires :name, type: String, desc: 'The name of the release'
- requires :description, type: String, desc: 'The release notes'
- optional :ref, type: String, desc: 'The commit sha or branch name'
+ requires :tag_name, type: String, desc: "The name of the tag", as: :tag
+ requires :name, type: String, desc: "The name of the release"
+ requires :description, type: String, desc: "The release notes"
+ optional :ref, type: String, desc: "The commit sha or branch name"
optional :assets, type: Hash do
optional :links, type: Array do
requires :name, type: String
@@ -55,7 +55,7 @@ module API
end
end
end
- post ':id/releases' do
+ post ":id/releases" do
authorize_create_release!
result = ::Releases::CreateService
@@ -69,16 +69,16 @@ module API
end
end
- desc 'Update a release' do
- detail 'This feature was introduced in GitLab 11.7.'
+ desc "Update a release" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::Release
end
params do
- requires :tag_name, type: String, desc: 'The name of the tag', as: :tag
- optional :name, type: String, desc: 'The name of the release'
- optional :description, type: String, desc: 'Release notes with markdown support'
+ requires :tag_name, type: String, desc: "The name of the tag", as: :tag
+ optional :name, type: String, desc: "The name of the release"
+ optional :description, type: String, desc: "Release notes with markdown support"
end
- put ':id/releases/:tag_name', requirements: RELEASE_ENDPOINT_REQUIREMETS do
+ put ":id/releases/:tag_name", requirements: RELEASE_ENDPOINT_REQUIREMETS do
authorize_update_release!
result = ::Releases::UpdateService
@@ -92,14 +92,14 @@ module API
end
end
- desc 'Delete a release' do
- detail 'This feature was introduced in GitLab 11.7.'
+ desc "Delete a release" do
+ detail "This feature was introduced in GitLab 11.7."
success Entities::Release
end
params do
- requires :tag_name, type: String, desc: 'The name of the tag', as: :tag
+ requires :tag_name, type: String, desc: "The name of the tag", as: :tag
end
- delete ':id/releases/:tag_name', requirements: RELEASE_ENDPOINT_REQUIREMETS do
+ delete ":id/releases/:tag_name", requirements: RELEASE_ENDPOINT_REQUIREMETS do
authorize_destroy_release!
result = ::Releases::DestroyService
diff --git a/lib/api/repositories.rb b/lib/api/repositories.rb
index 32e05d84491..2545236b3fa 100644
--- a/lib/api/repositories.rb
+++ b/lib/api/repositories.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'mime/types'
+require "mime/types"
module API
class Repositories < Grape::API
@@ -9,7 +9,7 @@ module API
before { authorize! :download_code, user_project }
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
helpers do
@@ -30,120 +30,116 @@ module API
@blob = Gitlab::Git::Blob.raw(@repo, params[:sha])
@blob.load_all_data!(@repo)
rescue
- not_found! 'Blob'
+ not_found! "Blob"
end
- not_found! 'Blob' unless @blob
+ not_found! "Blob" unless @blob
end
end
- desc 'Get a project repository tree' do
+ desc "Get a project repository tree" do
success Entities::TreeObject
end
params do
- optional :ref, type: String, desc: 'The name of a repository branch or tag, if not given the default branch is used'
- optional :path, type: String, desc: 'The path of the tree'
- optional :recursive, type: Boolean, default: false, desc: 'Used to get a recursive tree'
+ optional :ref, type: String, desc: "The name of a repository branch or tag, if not given the default branch is used"
+ optional :path, type: String, desc: "The path of the tree"
+ optional :recursive, type: Boolean, default: false, desc: "Used to get a recursive tree"
use :pagination
end
- get ':id/repository/tree' do
- ref = params[:ref] || user_project.try(:default_branch) || 'master'
+ get ":id/repository/tree" do
+ ref = params[:ref] || user_project.try(:default_branch) || "master"
path = params[:path] || nil
commit = user_project.commit(ref)
- not_found!('Tree') unless commit
+ not_found!("Tree") unless commit
tree = user_project.repository.tree(commit.id, path, recursive: params[:recursive])
entries = ::Kaminari.paginate_array(tree.sorted_entries)
present paginate(entries), with: Entities::TreeObject
end
- desc 'Get raw blob contents from the repository'
+ desc "Get raw blob contents from the repository"
params do
- requires :sha, type: String, desc: 'The commit hash'
+ requires :sha, type: String, desc: "The commit hash"
end
- get ':id/repository/blobs/:sha/raw' do
+ get ":id/repository/blobs/:sha/raw" do
assign_blob_vars!
send_git_blob @repo, @blob
end
- desc 'Get a blob from the repository'
+ desc "Get a blob from the repository"
params do
- requires :sha, type: String, desc: 'The commit hash'
+ requires :sha, type: String, desc: "The commit hash"
end
- get ':id/repository/blobs/:sha' do
+ get ":id/repository/blobs/:sha" do
assign_blob_vars!
{
size: @blob.size,
encoding: "base64",
content: Base64.strict_encode64(@blob.data),
- sha: @blob.id
+ sha: @blob.id,
}
end
- desc 'Get an archive of the repository'
+ desc "Get an archive of the repository"
params do
- optional :sha, type: String, desc: 'The commit sha of the archive to be downloaded'
- optional :format, type: String, desc: 'The archive format'
- end
- get ':id/repository/archive', requirements: { format: Gitlab::PathRegex.archive_formats_regex } do
- begin
- send_git_archive user_project.repository, ref: params[:sha], format: params[:format], append_sha: true
- rescue
- not_found!('File')
- end
+ optional :sha, type: String, desc: "The commit sha of the archive to be downloaded"
+ optional :format, type: String, desc: "The archive format"
+ end
+ get ":id/repository/archive", requirements: {format: Gitlab::PathRegex.archive_formats_regex} do
+ send_git_archive user_project.repository, ref: params[:sha], format: params[:format], append_sha: true
+ rescue
+ not_found!("File")
end
- desc 'Compare two branches, tags, or commits' do
+ desc "Compare two branches, tags, or commits" do
success Entities::Compare
end
params do
- requires :from, type: String, desc: 'The commit, branch name, or tag name to start comparison'
- requires :to, type: String, desc: 'The commit, branch name, or tag name to stop comparison'
- optional :straight, type: Boolean, desc: 'Comparison method, `true` for direct comparison between `from` and `to` (`from`..`to`), `false` to compare using merge base (`from`...`to`)', default: false
+ requires :from, type: String, desc: "The commit, branch name, or tag name to start comparison"
+ requires :to, type: String, desc: "The commit, branch name, or tag name to stop comparison"
+ optional :straight, type: Boolean, desc: "Comparison method, `true` for direct comparison between `from` and `to` (`from`..`to`), `false` to compare using merge base (`from`...`to`)", default: false
end
- get ':id/repository/compare' do
+ get ":id/repository/compare" do
compare = Gitlab::Git::Compare.new(user_project.repository.raw_repository, params[:from], params[:to], straight: params[:straight])
present compare, with: Entities::Compare
end
- desc 'Get repository contributors' do
+ desc "Get repository contributors" do
success Entities::Contributor
end
params do
use :pagination
- optional :order_by, type: String, values: %w[email name commits], default: 'commits', desc: 'Return contributors ordered by `name` or `email` or `commits`'
- optional :sort, type: String, values: %w[asc desc], default: 'asc', desc: 'Sort by asc (ascending) or desc (descending)'
- end
- get ':id/repository/contributors' do
- begin
- contributors = ::Kaminari.paginate_array(user_project.repository.contributors(order_by: params[:order_by], sort: params[:sort]))
- present paginate(contributors), with: Entities::Contributor
- rescue
- not_found!
- end
+ optional :order_by, type: String, values: %w[email name commits], default: "commits", desc: "Return contributors ordered by `name` or `email` or `commits`"
+ optional :sort, type: String, values: %w[asc desc], default: "asc", desc: "Sort by asc (ascending) or desc (descending)"
+ end
+ get ":id/repository/contributors" do
+ contributors = ::Kaminari.paginate_array(user_project.repository.contributors(order_by: params[:order_by], sort: params[:sort]))
+ present paginate(contributors), with: Entities::Contributor
+ rescue
+ not_found!
end
- desc 'Get the common ancestor between commits' do
+ desc "Get the common ancestor between commits" do
success Entities::Commit
end
params do
requires :refs, type: Array[String]
end
- get ':id/repository/merge_base' do
+ get ":id/repository/merge_base" do
refs = params[:refs]
if refs.size < 2
- render_api_error!('Provide at least 2 refs', 400)
+ render_api_error!("Provide at least 2 refs", 400)
end
merge_base = Gitlab::Git::MergeBase.new(user_project.repository, refs)
if merge_base.unknown_refs.any?
- ref_noun = 'ref'.pluralize(merge_base.unknown_refs.size)
- message = "Could not find #{ref_noun}: #{merge_base.unknown_refs.join(', ')}"
+ ref_noun = "ref".pluralize(merge_base.unknown_refs.size)
+ message = "Could not find #{ref_noun}: #{merge_base.unknown_refs.join(", ")}"
render_api_error!(message, 400)
end
diff --git a/lib/api/resource_label_events.rb b/lib/api/resource_label_events.rb
index 0c328f7268e..b2934eb29e1 100644
--- a/lib/api/resource_label_events.rb
+++ b/lib/api/resource_label_events.rb
@@ -19,10 +19,10 @@ module API
resource parent_type.pluralize.to_sym, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
desc "Get a list of #{eventable_type.to_s.downcase} resource label events" do
success Entities::ResourceLabelEvent
- detail 'This feature was introduced in 11.3'
+ detail "This feature was introduced in 11.3"
end
params do
- requires :eventable_id, types: [Integer, String], desc: 'The ID of the eventable'
+ requires :eventable_id, types: [Integer, String], desc: "The ID of the eventable"
use :pagination
end
@@ -37,11 +37,11 @@ module API
desc "Get a single #{eventable_type.to_s.downcase} resource label event" do
success Entities::ResourceLabelEvent
- detail 'This feature was introduced in 11.3'
+ detail "This feature was introduced in 11.3"
end
params do
- requires :event_id, type: String, desc: 'The ID of a resource label event'
- requires :eventable_id, types: [Integer, String], desc: 'The ID of the eventable'
+ requires :event_id, type: String, desc: "The ID of a resource label event"
+ requires :eventable_id, types: [Integer, String], desc: "The ID of the eventable"
end
get ":id/#{eventables_str}/:eventable_id/resource_label_events/:event_id" do
eventable = find_noteable(parent_type, eventables_str, params[:eventable_id])
diff --git a/lib/api/runner.rb b/lib/api/runner.rb
index c60d25b88cb..b97db592fad 100644
--- a/lib/api/runner.rb
+++ b/lib/api/runner.rb
@@ -5,21 +5,21 @@ module API
helpers ::API::Helpers::Runner
resource :runners do
- desc 'Registers a new Runner' do
+ desc "Registers a new Runner" do
success Entities::RunnerRegistrationDetails
- http_codes [[201, 'Runner was created'], [403, 'Forbidden']]
+ http_codes [[201, "Runner was created"], [403, "Forbidden"]]
end
params do
- requires :token, type: String, desc: 'Registration token'
- optional :description, type: String, desc: %q(Runner's description)
- optional :info, type: Hash, desc: %q(Runner's metadata)
- optional :active, type: Boolean, desc: 'Should Runner be active'
- optional :locked, type: Boolean, desc: 'Should Runner be locked for current project'
- optional :run_untagged, type: Boolean, desc: 'Should Runner handle untagged jobs'
- optional :tag_list, type: Array[String], desc: %q(List of Runner's tags)
- optional :maximum_timeout, type: Integer, desc: 'Maximum timeout set when this Runner will handle the job'
+ requires :token, type: String, desc: "Registration token"
+ optional :description, type: String, desc: "Runner's description"
+ optional :info, type: Hash, desc: "Runner's metadata"
+ optional :active, type: Boolean, desc: "Should Runner be active"
+ optional :locked, type: Boolean, desc: "Should Runner be locked for current project"
+ optional :run_untagged, type: Boolean, desc: "Should Runner handle untagged jobs"
+ optional :tag_list, type: Array[String], desc: "List of Runner's tags"
+ optional :maximum_timeout, type: Integer, desc: "Maximum timeout set when this Runner will handle the job"
end
- post '/' do
+ post "/" do
attributes = attributes_for_keys([:description, :active, :locked, :run_untagged, :tag_list, :maximum_timeout])
.merge(get_runner_details_from_request)
@@ -46,13 +46,13 @@ module API
end
end
- desc 'Deletes a registered Runner' do
- http_codes [[204, 'Runner was deleted'], [403, 'Forbidden']]
+ desc "Deletes a registered Runner" do
+ http_codes [[204, "Runner was deleted"], [403, "Forbidden"]]
end
params do
- requires :token, type: String, desc: %q(Runner's authentication token)
+ requires :token, type: String, desc: "Runner's authentication token"
end
- delete '/' do
+ delete "/" do
authenticate_runner!
runner = Ci::Runner.find_by_token(params[:token])
@@ -60,55 +60,55 @@ module API
destroy_conditionally!(runner)
end
- desc 'Validates authentication credentials' do
- http_codes [[200, 'Credentials are valid'], [403, 'Forbidden']]
+ desc "Validates authentication credentials" do
+ http_codes [[200, "Credentials are valid"], [403, "Forbidden"]]
end
params do
- requires :token, type: String, desc: %q(Runner's authentication token)
+ requires :token, type: String, desc: "Runner's authentication token"
end
- post '/verify' do
+ post "/verify" do
authenticate_runner!
status 200
end
end
resource :jobs do
- desc 'Request a job' do
+ desc "Request a job" do
success Entities::JobRequest::Response
- http_codes [[201, 'Job was scheduled'],
- [204, 'No job for Runner'],
- [403, 'Forbidden']]
+ http_codes [[201, "Job was scheduled"],
+ [204, "No job for Runner"],
+ [403, "Forbidden"],]
end
params do
- requires :token, type: String, desc: %q(Runner's authentication token)
- optional :last_update, type: String, desc: %q(Runner's queue last_update token)
- optional :info, type: Hash, desc: %q(Runner's metadata) do
- optional :name, type: String, desc: %q(Runner's name)
- optional :version, type: String, desc: %q(Runner's version)
- optional :revision, type: String, desc: %q(Runner's revision)
- optional :platform, type: String, desc: %q(Runner's platform)
- optional :architecture, type: String, desc: %q(Runner's architecture)
- optional :executor, type: String, desc: %q(Runner's executor)
- optional :features, type: Hash, desc: %q(Runner's features)
+ requires :token, type: String, desc: "Runner's authentication token"
+ optional :last_update, type: String, desc: "Runner's queue last_update token"
+ optional :info, type: Hash, desc: "Runner's metadata" do
+ optional :name, type: String, desc: "Runner's name"
+ optional :version, type: String, desc: "Runner's version"
+ optional :revision, type: String, desc: "Runner's revision"
+ optional :platform, type: String, desc: "Runner's platform"
+ optional :architecture, type: String, desc: "Runner's architecture"
+ optional :executor, type: String, desc: "Runner's executor"
+ optional :features, type: Hash, desc: "Runner's features"
end
- optional :session, type: Hash, desc: %q(Runner's session data) do
- optional :url, type: String, desc: %q(Session's url)
- optional :certificate, type: String, desc: %q(Session's certificate)
- optional :authorization, type: String, desc: %q(Session's authorization)
+ optional :session, type: Hash, desc: "Runner's session data" do
+ optional :url, type: String, desc: "Session's url"
+ optional :certificate, type: String, desc: "Session's certificate"
+ optional :authorization, type: String, desc: "Session's authorization"
end
end
- post '/request' do
+ post "/request" do
authenticate_runner!
unless current_runner.active?
- header 'X-GitLab-Last-Update', current_runner.ensure_runner_queue_value
+ header "X-GitLab-Last-Update", current_runner.ensure_runner_queue_value
break no_content!
end
runner_params = declared_params(include_missing: false)
if current_runner.runner_queue_value_latest?(runner_params[:last_update])
- header 'X-GitLab-Last-Update', runner_params[:last_update]
+ header "X-GitLab-Last-Update", runner_params[:last_update]
Gitlab::Metrics.add_event(:build_not_found_cached)
break no_content!
end
@@ -122,7 +122,7 @@ module API
present Ci::BuildRunnerPresenter.new(result.build), with: Entities::JobRequest::Response
else
Gitlab::Metrics.add_event(:build_not_found)
- header 'X-GitLab-Last-Update', new_update
+ header "X-GitLab-Last-Update", new_update
no_content!
end
else
@@ -132,51 +132,51 @@ module API
end
end
- desc 'Updates a job' do
- http_codes [[200, 'Job was updated'], [403, 'Forbidden']]
+ desc "Updates a job" do
+ http_codes [[200, "Job was updated"], [403, "Forbidden"]]
end
params do
- requires :token, type: String, desc: %q(Runners's authentication token)
- requires :id, type: Integer, desc: %q(Job's ID)
- optional :trace, type: String, desc: %q(Job's full trace)
- optional :state, type: String, desc: %q(Job's status: success, failed)
- optional :failure_reason, type: String, desc: %q(Job's failure_reason)
+ requires :token, type: String, desc: "Runners's authentication token"
+ requires :id, type: Integer, desc: "Job's ID"
+ optional :trace, type: String, desc: "Job's full trace"
+ optional :state, type: String, desc: "Job's status: success, failed"
+ optional :failure_reason, type: String, desc: "Job's failure_reason"
end
- put '/:id' do
+ put "/:id" do
job = authenticate_job!
- job_forbidden!(job, 'Job is not running') unless job.running?
+ job_forbidden!(job, "Job is not running") unless job.running?
job.trace.set(params[:trace]) if params[:trace]
Gitlab::Metrics.add_event(:update_build)
case params[:state].to_s
- when 'running'
+ when "running"
job.touch if job.needs_touch?
- when 'success'
+ when "success"
job.success!
- when 'failed'
+ when "failed"
job.drop!(params[:failure_reason] || :unknown_failure)
end
end
- desc 'Appends a patch to the job trace' do
- http_codes [[202, 'Trace was patched'],
- [400, 'Missing Content-Range header'],
- [403, 'Forbidden'],
- [416, 'Range not satisfiable']]
+ desc "Appends a patch to the job trace" do
+ http_codes [[202, "Trace was patched"],
+ [400, "Missing Content-Range header"],
+ [403, "Forbidden"],
+ [416, "Range not satisfiable"],]
end
params do
- requires :id, type: Integer, desc: %q(Job's ID)
- optional :token, type: String, desc: %q(Job's authentication token)
+ requires :id, type: Integer, desc: "Job's ID"
+ optional :token, type: String, desc: "Job's authentication token"
end
- patch '/:id/trace' do
+ patch "/:id/trace" do
job = authenticate_job!
- job_forbidden!(job, 'Job is not running') unless job.running?
+ job_forbidden!(job, "Job is not running") unless job.running?
- error!('400 Missing header Content-Range', 400) unless request.headers.key?('Content-Range')
- content_range = request.headers['Content-Range']
- content_range = content_range.split('-')
+ error!("400 Missing header Content-Range", 400) unless request.headers.key?("Content-Range")
+ content_range = request.headers["Content-Range"]
+ content_range = content_range.split("-")
# TODO:
# it seems that `Content-Range` as formatted by runner is wrong,
@@ -191,32 +191,32 @@ module API
stream_size = job.trace.append(body_data, body_start)
unless stream_size == body_end
- break error!('416 Range Not Satisfiable', 416, { 'Range' => "0-#{stream_size}" })
+ break error!("416 Range Not Satisfiable", 416, {"Range" => "0-#{stream_size}"})
end
status 202
- header 'Job-Status', job.status
- header 'Range', "0-#{stream_size}"
+ header "Job-Status", job.status
+ header "Range", "0-#{stream_size}"
end
- desc 'Authorize artifacts uploading for job' do
- http_codes [[200, 'Upload allowed'],
- [403, 'Forbidden'],
- [405, 'Artifacts support not enabled'],
- [413, 'File too large']]
+ desc "Authorize artifacts uploading for job" do
+ http_codes [[200, "Upload allowed"],
+ [403, "Forbidden"],
+ [405, "Artifacts support not enabled"],
+ [413, "File too large"],]
end
params do
- requires :id, type: Integer, desc: %q(Job's ID)
- optional :token, type: String, desc: %q(Job's authentication token)
- optional :filesize, type: Integer, desc: %q(Artifacts filesize)
+ requires :id, type: Integer, desc: "Job's ID"
+ optional :token, type: String, desc: "Job's authentication token"
+ optional :filesize, type: Integer, desc: "Artifacts filesize"
end
- post '/:id/artifacts/authorize' do
+ post "/:id/artifacts/authorize" do
not_allowed! unless Gitlab.config.artifacts.enabled
require_gitlab_workhorse!
Gitlab::Workhorse.verify_api_request!(headers)
job = authenticate_job!
- forbidden!('Job is not running') unless job.running?
+ forbidden!("Job is not running") unless job.running?
if params[:filesize]
file_size = params[:filesize].to_i
@@ -228,55 +228,56 @@ module API
JobArtifactUploader.workhorse_authorize(has_length: false, maximum_size: max_artifacts_size)
end
- desc 'Upload artifacts for job' do
+ desc "Upload artifacts for job" do
success Entities::JobRequest::Response
- http_codes [[201, 'Artifact uploaded'],
- [400, 'Bad request'],
- [403, 'Forbidden'],
- [405, 'Artifacts support not enabled'],
- [413, 'File too large']]
+ http_codes [[201, "Artifact uploaded"],
+ [400, "Bad request"],
+ [403, "Forbidden"],
+ [405, "Artifacts support not enabled"],
+ [413, "File too large"],]
end
params do
- requires :id, type: Integer, desc: %q(Job's ID)
- optional :token, type: String, desc: %q(Job's authentication token)
- optional :expire_in, type: String, desc: %q(Specify when artifacts should expire)
- optional :artifact_type, type: String, desc: %q(The type of artifact),
- default: 'archive', values: Ci::JobArtifact.file_types.keys
- optional :artifact_format, type: String, desc: %q(The format of artifact),
- default: 'zip', values: Ci::JobArtifact.file_formats.keys
- optional 'file.path', type: String, desc: %q(path to locally stored body (generated by Workhorse))
- optional 'file.name', type: String, desc: %q(real filename as send in Content-Disposition (generated by Workhorse))
- optional 'file.type', type: String, desc: %q(real content type as send in Content-Type (generated by Workhorse))
- optional 'file.size', type: Integer, desc: %q(real size of file (generated by Workhorse))
- optional 'file.sha256', type: String, desc: %q(sha256 checksum of the file (generated by Workhorse))
- optional 'metadata.path', type: String, desc: %q(path to locally stored body (generated by Workhorse))
- optional 'metadata.name', type: String, desc: %q(filename (generated by Workhorse))
- optional 'metadata.size', type: Integer, desc: %q(real size of metadata (generated by Workhorse))
- optional 'metadata.sha256', type: String, desc: %q(sha256 checksum of metadata (generated by Workhorse))
+ requires :id, type: Integer, desc: "Job's ID"
+ optional :token, type: String, desc: "Job's authentication token"
+ optional :expire_in, type: String, desc: "Specify when artifacts should expire"
+ optional :artifact_type, type: String, desc: "The type of artifact",
+ default: "archive", values: Ci::JobArtifact.file_types.keys
+ optional :artifact_format, type: String, desc: "The format of artifact",
+ default: "zip", values: Ci::JobArtifact.file_formats.keys
+ optional "file.path", type: String, desc: "path to locally stored body (generated by Workhorse)"
+ optional "file.name", type: String, desc: "real filename as send in Content-Disposition (generated by Workhorse)"
+ optional "file.type", type: String, desc: "real content type as send in Content-Type (generated by Workhorse)"
+ optional "file.size", type: Integer, desc: "real size of file (generated by Workhorse)"
+ optional "file.sha256", type: String, desc: "sha256 checksum of the file (generated by Workhorse)"
+ optional "metadata.path", type: String, desc: "path to locally stored body (generated by Workhorse)"
+ optional "metadata.name", type: String, desc: "filename (generated by Workhorse)"
+ optional "metadata.size", type: Integer, desc: "real size of metadata (generated by Workhorse)"
+ optional "metadata.sha256", type: String, desc: "sha256 checksum of metadata (generated by Workhorse)"
end
- post '/:id/artifacts' do
+ post "/:id/artifacts" do
not_allowed! unless Gitlab.config.artifacts.enabled
require_gitlab_workhorse!
job = authenticate_job!
- forbidden!('Job is not running!') unless job.running?
+ forbidden!("Job is not running!") unless job.running?
artifacts = UploadedFile.from_params(params, :file, JobArtifactUploader.workhorse_local_upload_path)
metadata = UploadedFile.from_params(params, :metadata, JobArtifactUploader.workhorse_local_upload_path)
- bad_request!('Missing artifacts file!') unless artifacts
+ bad_request!("Missing artifacts file!") unless artifacts
file_to_large! unless artifacts.size < max_artifacts_size
- expire_in = params['expire_in'] ||
+ expire_in = params["expire_in"] ||
Gitlab::CurrentSettings.current_application_settings.default_artifacts_expire_in
job.job_artifacts.build(
project: job.project,
file: artifacts,
- file_type: params['artifact_type'],
- file_format: params['artifact_format'],
+ file_type: params["artifact_type"],
+ file_format: params["artifact_format"],
file_sha256: artifacts.sha256,
- expire_in: expire_in)
+ expire_in: expire_in
+ )
if metadata
job.job_artifacts.build(
@@ -285,7 +286,8 @@ module API
file_type: :metadata,
file_format: :gzip,
file_sha256: metadata.sha256,
- expire_in: expire_in)
+ expire_in: expire_in
+ )
end
if job.update(artifacts_expire_in: expire_in)
@@ -295,17 +297,17 @@ module API
end
end
- desc 'Download the artifacts file for job' do
- http_codes [[200, 'Upload allowed'],
- [403, 'Forbidden'],
- [404, 'Artifact not found']]
+ desc "Download the artifacts file for job" do
+ http_codes [[200, "Upload allowed"],
+ [403, "Forbidden"],
+ [404, "Artifact not found"],]
end
params do
- requires :id, type: Integer, desc: %q(Job's ID)
- optional :token, type: String, desc: %q(Job's authentication token)
- optional :direct_download, default: false, type: Boolean, desc: %q(Perform direct download from remote storage instead of proxying artifacts)
+ requires :id, type: Integer, desc: "Job's ID"
+ optional :token, type: String, desc: "Job's authentication token"
+ optional :direct_download, default: false, type: Boolean, desc: "Perform direct download from remote storage instead of proxying artifacts"
end
- get '/:id/artifacts' do
+ get "/:id/artifacts" do
job = authenticate_job!
present_carrierwave_file!(job.artifacts_file, supports_direct_download: params[:direct_download])
diff --git a/lib/api/runners.rb b/lib/api/runners.rb
index f3fea463e7f..1e99fbabcc8 100644
--- a/lib/api/runners.rb
+++ b/lib/api/runners.rb
@@ -7,17 +7,17 @@ module API
before { authenticate! }
resource :runners do
- desc 'Get runners available for user' do
+ desc "Get runners available for user" do
success Entities::Runner
end
params do
optional :scope, type: String, values: Ci::Runner::AVAILABLE_STATUSES,
- desc: 'The scope of specific runners to show'
+ desc: "The scope of specific runners to show"
optional :type, type: String, values: Ci::Runner::AVAILABLE_TYPES,
- desc: 'The type of the runners to show'
+ desc: "The type of the runners to show"
optional :status, type: String, values: Ci::Runner::AVAILABLE_STATUSES,
- desc: 'The status of the runners to show'
- optional :tag_list, type: Array[String], desc: 'The tags of the runners to show'
+ desc: "The status of the runners to show"
+ optional :tag_list, type: Array[String], desc: "The tags of the runners to show"
use :pagination
end
get do
@@ -30,20 +30,20 @@ module API
present paginate(runners), with: Entities::Runner
end
- desc 'Get all runners - shared and specific' do
+ desc "Get all runners - shared and specific" do
success Entities::Runner
end
params do
optional :scope, type: String, values: Ci::Runner::AVAILABLE_SCOPES,
- desc: 'The scope of specific runners to show'
+ desc: "The scope of specific runners to show"
optional :type, type: String, values: Ci::Runner::AVAILABLE_TYPES,
- desc: 'The type of the runners to show'
+ desc: "The type of the runners to show"
optional :status, type: String, values: Ci::Runner::AVAILABLE_STATUSES,
- desc: 'The status of the runners to show'
- optional :tag_list, type: Array[String], desc: 'The tags of the runners to show'
+ desc: "The status of the runners to show"
+ optional :tag_list, type: Array[String], desc: "The tags of the runners to show"
use :pagination
end
- get 'all' do
+ get "all" do
authenticated_as_admin!
runners = Ci::Runner.all
@@ -59,9 +59,9 @@ module API
success Entities::RunnerDetails
end
params do
- requires :id, type: Integer, desc: 'The ID of the runner'
+ requires :id, type: Integer, desc: "The ID of the runner"
end
- get ':id' do
+ get ":id" do
runner = get_runner(params[:id])
authenticate_show_runner!(runner)
@@ -72,18 +72,18 @@ module API
success Entities::RunnerDetails
end
params do
- requires :id, type: Integer, desc: 'The ID of the runner'
- optional :description, type: String, desc: 'The description of the runner'
- optional :active, type: Boolean, desc: 'The state of a runner'
- optional :tag_list, type: Array[String], desc: 'The list of tags for a runner'
- optional :run_untagged, type: Boolean, desc: 'Flag indicating the runner can execute untagged jobs'
- optional :locked, type: Boolean, desc: 'Flag indicating the runner is locked'
+ requires :id, type: Integer, desc: "The ID of the runner"
+ optional :description, type: String, desc: "The description of the runner"
+ optional :active, type: Boolean, desc: "The state of a runner"
+ optional :tag_list, type: Array[String], desc: "The list of tags for a runner"
+ optional :run_untagged, type: Boolean, desc: "Flag indicating the runner can execute untagged jobs"
+ optional :locked, type: Boolean, desc: "Flag indicating the runner is locked"
optional :access_level, type: String, values: Ci::Runner.access_levels.keys,
- desc: 'The access_level of the runner'
- optional :maximum_timeout, type: Integer, desc: 'Maximum timeout set when this Runner will handle the job'
+ desc: "The access_level of the runner"
+ optional :maximum_timeout, type: Integer, desc: "Maximum timeout set when this Runner will handle the job"
at_least_one_of :description, :active, :tag_list, :run_untagged, :locked, :access_level, :maximum_timeout
end
- put ':id' do
+ put ":id" do
runner = get_runner(params.delete(:id))
authenticate_update_runner!(runner)
update_service = Ci::UpdateRunnerService.new(runner)
@@ -95,13 +95,13 @@ module API
end
end
- desc 'Remove a runner' do
+ desc "Remove a runner" do
success Entities::Runner
end
params do
- requires :id, type: Integer, desc: 'The ID of the runner'
+ requires :id, type: Integer, desc: "The ID of the runner"
end
- delete ':id' do
+ delete ":id" do
runner = get_runner(params[:id])
authenticate_delete_runner!(runner)
@@ -109,15 +109,15 @@ module API
destroy_conditionally!(runner)
end
- desc 'List jobs running on a runner' do
+ desc "List jobs running on a runner" do
success Entities::JobBasicWithProject
end
params do
- requires :id, type: Integer, desc: 'The ID of the runner'
- optional :status, type: String, desc: 'Status of the job', values: Ci::Build::AVAILABLE_STATUSES
+ requires :id, type: Integer, desc: "The ID of the runner"
+ optional :status, type: String, desc: "Status of the job", values: Ci::Build::AVAILABLE_STATUSES
use :pagination
end
- get ':id/jobs' do
+ get ":id/jobs" do
runner = get_runner(params[:id])
authenticate_list_runners_jobs!(runner)
@@ -128,25 +128,25 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
before { authorize_admin_project }
- desc 'Get runners available for project' do
+ desc "Get runners available for project" do
success Entities::Runner
end
params do
optional :scope, type: String, values: Ci::Runner::AVAILABLE_SCOPES,
- desc: 'The scope of specific runners to show'
+ desc: "The scope of specific runners to show"
optional :type, type: String, values: Ci::Runner::AVAILABLE_TYPES,
- desc: 'The type of the runners to show'
+ desc: "The type of the runners to show"
optional :status, type: String, values: Ci::Runner::AVAILABLE_STATUSES,
- desc: 'The status of the runners to show'
- optional :tag_list, type: Array[String], desc: 'The tags of the runners to show'
+ desc: "The status of the runners to show"
+ optional :tag_list, type: Array[String], desc: "The tags of the runners to show"
use :pagination
end
- get ':id/runners' do
+ get ":id/runners" do
runners = Ci::Runner.owned_or_instance_wide(user_project.id)
runners = filter_runners(runners, params[:scope])
runners = filter_runners(runners, params[:type], allowed_scopes: Ci::Runner::AVAILABLE_TYPES)
@@ -156,13 +156,13 @@ module API
present paginate(runners), with: Entities::Runner
end
- desc 'Enable a runner for a project' do
+ desc "Enable a runner for a project" do
success Entities::Runner
end
params do
- requires :runner_id, type: Integer, desc: 'The ID of the runner'
+ requires :runner_id, type: Integer, desc: "The ID of the runner"
end
- post ':id/runners' do
+ post ":id/runners" do
runner = get_runner(params[:runner_id])
authenticate_enable_runner!(runner)
@@ -177,12 +177,12 @@ module API
success Entities::Runner
end
params do
- requires :runner_id, type: Integer, desc: 'The ID of the runner'
+ requires :runner_id, type: Integer, desc: "The ID of the runner"
end
# rubocop: disable CodeReuse/ActiveRecord
- delete ':id/runners/:runner_id' do
+ delete ":id/runners/:runner_id" do
runner_project = user_project.runner_projects.find_by(runner_id: params[:runner_id])
- not_found!('Runner') unless runner_project
+ not_found!("Runner") unless runner_project
runner = runner_project.runner
forbidden!("Only one project associated with the runner. Please remove the runner instead") if runner.projects.count == 1
@@ -197,7 +197,7 @@ module API
return runners unless scope.present?
unless allowed_scopes.include?(scope)
- render_api_error!('Scope contains invalid value', 400)
+ render_api_error!("Scope contains invalid value", 400)
end
# Support deprecated scopes
@@ -210,7 +210,7 @@ module API
def get_runner(id)
runner = Ci::Runner.find(id)
- not_found!('Runner') unless runner
+ not_found!("Runner") unless runner
runner
end
diff --git a/lib/api/scope.rb b/lib/api/scope.rb
index 707775e5d15..1f290185480 100644
--- a/lib/api/scope.rb
+++ b/lib/api/scope.rb
@@ -13,7 +13,7 @@ module API
# Are the `scopes` passed in sufficient to adequately authorize the passed
# request for the scope represented by the current instance of this class?
def sufficient?(scopes, request)
- scopes.include?(self.name) && verify_if_condition(request)
+ scopes.include?(name) && verify_if_condition(request)
end
private
diff --git a/lib/api/search.rb b/lib/api/search.rb
index f5db692afe5..cb03f880d81 100644
--- a/lib/api/search.rb
+++ b/lib/api/search.rb
@@ -17,7 +17,7 @@ module API
blobs: Entities::Blob,
wiki_blobs: Entities::Blob,
snippet_titles: Entities::Snippet,
- snippet_blobs: Entities::Snippet
+ snippet_blobs: Entities::Snippet,
}.freeze
def search(additional_params = {})
@@ -26,7 +26,7 @@ module API
search: params[:search],
snippets: snippets?,
page: params[:page],
- per_page: params[:per_page]
+ per_page: params[:per_page],
}.merge(additional_params)
results = SearchService.new(current_user, search_params).search_objects
@@ -39,7 +39,7 @@ module API
end
def snippets?
- %w(snippet_blobs snippet_titles).include?(params[:scope]).to_s
+ %w[snippet_blobs snippet_titles].include?(params[:scope]).to_s
end
def entity
@@ -48,16 +48,16 @@ module API
end
resource :search do
- desc 'Search on GitLab' do
- detail 'This feature was introduced in GitLab 10.5.'
+ desc "Search on GitLab" do
+ detail "This feature was introduced in GitLab 10.5."
end
params do
- requires :search, type: String, desc: 'The expression it should be searched for'
+ requires :search, type: String, desc: "The expression it should be searched for"
requires :scope,
type: String,
desc: 'The scope of search, available scopes:
projects, issues, merge_requests, milestones, snippet_titles, snippet_blobs',
- values: %w(projects issues merge_requests milestones snippet_titles snippet_blobs)
+ values: %w[projects issues merge_requests milestones snippet_titles snippet_blobs]
use :pagination
end
get do
@@ -66,39 +66,39 @@ module API
end
resource :groups, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Search on GitLab' do
- detail 'This feature was introduced in GitLab 10.5.'
+ desc "Search on GitLab" do
+ detail "This feature was introduced in GitLab 10.5."
end
params do
- requires :id, type: String, desc: 'The ID of a group'
- requires :search, type: String, desc: 'The expression it should be searched for'
+ requires :id, type: String, desc: "The ID of a group"
+ requires :search, type: String, desc: "The expression it should be searched for"
requires :scope,
type: String,
desc: 'The scope of search, available scopes:
projects, issues, merge_requests, milestones',
- values: %w(projects issues merge_requests milestones)
+ values: %w[projects issues merge_requests milestones]
use :pagination
end
- get ':id/(-/)search' do
+ get ":id/(-/)search" do
present search(group_id: user_group.id), with: entity
end
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Search on GitLab' do
- detail 'This feature was introduced in GitLab 10.5.'
+ desc "Search on GitLab" do
+ detail "This feature was introduced in GitLab 10.5."
end
params do
- requires :id, type: String, desc: 'The ID of a project'
- requires :search, type: String, desc: 'The expression it should be searched for'
+ requires :id, type: String, desc: "The ID of a project"
+ requires :search, type: String, desc: "The expression it should be searched for"
requires :scope,
type: String,
desc: 'The scope of search, available scopes:
issues, merge_requests, milestones, notes, wiki_blobs, commits, blobs',
- values: %w(issues merge_requests milestones notes wiki_blobs commits blobs)
+ values: %w[issues merge_requests milestones notes wiki_blobs commits blobs]
use :pagination
end
- get ':id/(-/)search' do
+ get ":id/(-/)search" do
present search(project_id: user_project.id), with: entity
end
end
diff --git a/lib/api/services.rb b/lib/api/services.rb
index bda6be51553..60a37802ca5 100644
--- a/lib/api/services.rb
+++ b/lib/api/services.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
module API
class Services < Grape::API
CHAT_NOTIFICATION_SETTINGS = [
@@ -6,20 +7,20 @@ module API
required: true,
name: :webhook,
type: String,
- desc: 'The chat webhook'
+ desc: "The chat webhook",
},
{
required: false,
name: :username,
type: String,
- desc: 'The chat username'
+ desc: "The chat username",
},
{
required: false,
name: :channel,
type: String,
- desc: 'The default chat channel'
- }
+ desc: "The default chat channel",
+ },
].freeze
CHAT_NOTIFICATION_FLAGS = [
@@ -27,14 +28,14 @@ module API
required: false,
name: :notify_only_broken_pipelines,
type: Boolean,
- desc: 'Send notifications for broken pipelines'
+ desc: "Send notifications for broken pipelines",
},
{
required: false,
name: :notify_only_default_branch,
type: Boolean,
- desc: 'Send notifications only for the default branch'
- }
+ desc: "Send notifications only for the default branch",
+ },
].freeze
CHAT_NOTIFICATION_CHANNELS = [
@@ -42,50 +43,50 @@ module API
required: false,
name: :push_channel,
type: String,
- desc: 'The name of the channel to receive push_events notifications'
+ desc: "The name of the channel to receive push_events notifications",
},
{
required: false,
name: :issue_channel,
type: String,
- desc: 'The name of the channel to receive issues_events notifications'
+ desc: "The name of the channel to receive issues_events notifications",
},
{
required: false,
name: :confidential_issue_channel,
type: String,
- desc: 'The name of the channel to receive confidential_issues_events notifications'
+ desc: "The name of the channel to receive confidential_issues_events notifications",
},
{
required: false,
name: :merge_request_channel,
type: String,
- desc: 'The name of the channel to receive merge_requests_events notifications'
+ desc: "The name of the channel to receive merge_requests_events notifications",
},
{
required: false,
name: :note_channel,
type: String,
- desc: 'The name of the channel to receive note_events notifications'
+ desc: "The name of the channel to receive note_events notifications",
},
{
required: false,
name: :tag_push_channel,
type: String,
- desc: 'The name of the channel to receive tag_push_events notifications'
+ desc: "The name of the channel to receive tag_push_events notifications",
},
{
required: false,
name: :pipeline_channel,
type: String,
- desc: 'The name of the channel to receive pipeline_events notifications'
+ desc: "The name of the channel to receive pipeline_events notifications",
},
{
required: false,
name: :wiki_page_channel,
type: String,
- desc: 'The name of the channel to receive wiki_page_events notifications'
- }
+ desc: "The name of the channel to receive wiki_page_events notifications",
+ },
].freeze
CHAT_NOTIFICATION_EVENTS = [
@@ -93,571 +94,571 @@ module API
required: false,
name: :push_events,
type: Boolean,
- desc: 'Enable notifications for push_events'
+ desc: "Enable notifications for push_events",
},
{
required: false,
name: :issues_events,
type: Boolean,
- desc: 'Enable notifications for issues_events'
+ desc: "Enable notifications for issues_events",
},
{
required: false,
name: :confidential_issues_events,
type: Boolean,
- desc: 'Enable notifications for confidential_issues_events'
+ desc: "Enable notifications for confidential_issues_events",
},
{
required: false,
name: :merge_requests_events,
type: Boolean,
- desc: 'Enable notifications for merge_requests_events'
+ desc: "Enable notifications for merge_requests_events",
},
{
required: false,
name: :note_events,
type: Boolean,
- desc: 'Enable notifications for note_events'
+ desc: "Enable notifications for note_events",
},
{
required: false,
name: :tag_push_events,
type: Boolean,
- desc: 'Enable notifications for tag_push_events'
+ desc: "Enable notifications for tag_push_events",
},
{
required: false,
name: :pipeline_events,
type: Boolean,
- desc: 'Enable notifications for pipeline_events'
+ desc: "Enable notifications for pipeline_events",
},
{
required: false,
name: :wiki_page_events,
type: Boolean,
- desc: 'Enable notifications for wiki_page_events'
- }
+ desc: "Enable notifications for wiki_page_events",
+ },
].freeze
services = {
- 'asana' => [
+ "asana" => [
{
required: true,
name: :api_key,
type: String,
- desc: 'User API token'
+ desc: "User API token",
},
{
required: false,
name: :restrict_to_branch,
type: String,
- desc: 'Comma-separated list of branches which will be automatically inspected. Leave blank to include all branches'
- }
+ desc: "Comma-separated list of branches which will be automatically inspected. Leave blank to include all branches",
+ },
],
- 'assembla' => [
+ "assembla" => [
{
required: true,
name: :token,
type: String,
- desc: 'The authentication token'
+ desc: "The authentication token",
},
{
required: false,
name: :subdomain,
type: String,
- desc: 'Subdomain setting'
- }
+ desc: "Subdomain setting",
+ },
],
- 'bamboo' => [
+ "bamboo" => [
{
required: true,
name: :bamboo_url,
type: String,
- desc: 'Bamboo root URL like https://bamboo.example.com'
+ desc: "Bamboo root URL like https://bamboo.example.com",
},
{
required: true,
name: :build_key,
type: String,
- desc: 'Bamboo build plan key like'
+ desc: "Bamboo build plan key like",
},
{
required: true,
name: :username,
type: String,
- desc: 'A user with API access, if applicable'
+ desc: "A user with API access, if applicable",
},
{
required: true,
name: :password,
type: String,
- desc: 'Passord of the user'
- }
+ desc: "Passord of the user",
+ },
],
- 'bugzilla' => [
+ "bugzilla" => [
{
required: true,
name: :new_issue_url,
type: String,
- desc: 'New issue URL'
+ desc: "New issue URL",
},
{
required: true,
name: :issues_url,
type: String,
- desc: 'Issues URL'
+ desc: "Issues URL",
},
{
required: true,
name: :project_url,
type: String,
- desc: 'Project URL'
+ desc: "Project URL",
},
{
required: false,
name: :description,
type: String,
- desc: 'Description'
+ desc: "Description",
},
{
required: false,
name: :title,
type: String,
- desc: 'Title'
- }
+ desc: "Title",
+ },
],
- 'buildkite' => [
+ "buildkite" => [
{
required: true,
name: :token,
type: String,
- desc: 'Buildkite project GitLab token'
+ desc: "Buildkite project GitLab token",
},
{
required: true,
name: :project_url,
type: String,
- desc: 'The buildkite project URL'
+ desc: "The buildkite project URL",
},
{
required: false,
name: :enable_ssl_verification,
type: Boolean,
- desc: 'Enable SSL verification for communication'
- }
+ desc: "Enable SSL verification for communication",
+ },
],
- 'campfire' => [
+ "campfire" => [
{
required: true,
name: :token,
type: String,
- desc: 'Campfire token'
+ desc: "Campfire token",
},
{
required: false,
name: :subdomain,
type: String,
- desc: 'Campfire subdomain'
+ desc: "Campfire subdomain",
},
{
required: false,
name: :room,
type: String,
- desc: 'Campfire room'
- }
+ desc: "Campfire room",
+ },
],
- 'custom-issue-tracker' => [
+ "custom-issue-tracker" => [
{
required: true,
name: :new_issue_url,
type: String,
- desc: 'New issue URL'
+ desc: "New issue URL",
},
{
required: true,
name: :issues_url,
type: String,
- desc: 'Issues URL'
+ desc: "Issues URL",
},
{
required: true,
name: :project_url,
type: String,
- desc: 'Project URL'
+ desc: "Project URL",
},
{
required: false,
name: :description,
type: String,
- desc: 'Description'
+ desc: "Description",
},
{
required: false,
name: :title,
type: String,
- desc: 'Title'
- }
+ desc: "Title",
+ },
],
- 'discord' => [
+ "discord" => [
{
required: true,
name: :webhook,
type: String,
- desc: 'Discord webhook. e.g. https://discordapp.com/api/webhooks/…'
- }
+ desc: "Discord webhook. e.g. https://discordapp.com/api/webhooks/…",
+ },
],
- 'drone-ci' => [
+ "drone-ci" => [
{
required: true,
name: :token,
type: String,
- desc: 'Drone CI token'
+ desc: "Drone CI token",
},
{
required: true,
name: :drone_url,
type: String,
- desc: 'Drone CI URL'
+ desc: "Drone CI URL",
},
{
required: false,
name: :enable_ssl_verification,
type: Boolean,
- desc: 'Enable SSL verification for communication'
- }
+ desc: "Enable SSL verification for communication",
+ },
],
- 'emails-on-push' => [
+ "emails-on-push" => [
{
required: true,
name: :recipients,
type: String,
- desc: 'Comma-separated list of recipient email addresses'
+ desc: "Comma-separated list of recipient email addresses",
},
{
required: false,
name: :disable_diffs,
type: Boolean,
- desc: 'Disable code diffs'
+ desc: "Disable code diffs",
},
{
required: false,
name: :send_from_committer_email,
type: Boolean,
- desc: 'Send from committer'
- }
+ desc: "Send from committer",
+ },
],
- 'external-wiki' => [
+ "external-wiki" => [
{
required: true,
name: :external_wiki_url,
type: String,
- desc: 'The URL of the external Wiki'
- }
+ desc: "The URL of the external Wiki",
+ },
],
- 'flowdock' => [
+ "flowdock" => [
{
required: true,
name: :token,
type: String,
- desc: 'Flowdock token'
- }
+ desc: "Flowdock token",
+ },
],
- 'hangouts-chat' => [
+ "hangouts-chat" => [
{
required: true,
name: :webhook,
type: String,
- desc: 'The Hangouts Chat webhook. e.g. https://chat.googleapis.com/v1/spaces…'
+ desc: "The Hangouts Chat webhook. e.g. https://chat.googleapis.com/v1/spaces…",
},
- CHAT_NOTIFICATION_EVENTS
+ CHAT_NOTIFICATION_EVENTS,
].flatten,
- 'irker' => [
+ "irker" => [
{
required: true,
name: :recipients,
type: String,
- desc: 'Recipients/channels separated by whitespaces'
+ desc: "Recipients/channels separated by whitespaces",
},
{
required: false,
name: :default_irc_uri,
type: String,
- desc: 'Default: irc://irc.network.net:6697'
+ desc: "Default: irc://irc.network.net:6697",
},
{
required: false,
name: :server_host,
type: String,
- desc: 'Server host. Default localhost'
+ desc: "Server host. Default localhost",
},
{
required: false,
name: :server_port,
type: Integer,
- desc: 'Server port. Default 6659'
+ desc: "Server port. Default 6659",
},
{
required: false,
name: :colorize_messages,
type: Boolean,
- desc: 'Colorize messages'
- }
+ desc: "Colorize messages",
+ },
],
- 'jira' => [
+ "jira" => [
{
required: true,
name: :url,
type: String,
- desc: 'The base URL to the JIRA instance web interface which is being linked to this GitLab project. E.g., https://jira.example.com'
+ desc: "The base URL to the JIRA instance web interface which is being linked to this GitLab project. E.g., https://jira.example.com",
},
{
required: false,
name: :api_url,
type: String,
- desc: 'The base URL to the JIRA instance API. Web URL value will be used if not set. E.g., https://jira-api.example.com'
+ desc: "The base URL to the JIRA instance API. Web URL value will be used if not set. E.g., https://jira-api.example.com",
},
{
required: true,
name: :username,
type: String,
- desc: 'The username of the user created to be used with GitLab/JIRA'
+ desc: "The username of the user created to be used with GitLab/JIRA",
},
{
required: true,
name: :password,
type: String,
- desc: 'The password of the user created to be used with GitLab/JIRA'
+ desc: "The password of the user created to be used with GitLab/JIRA",
},
{
required: false,
name: :jira_issue_transition_id,
type: String,
- desc: 'The ID of a transition that moves issues to a closed state. You can find this number under the JIRA workflow administration (**Administration > Issues > Workflows**) by selecting **View** under **Operations** of the desired workflow of your project. The ID of each state can be found inside the parenthesis of each transition name under the **Transitions (id)** column ([see screenshot][trans]). By default, this ID is set to `2`'
- }
+ desc: "The ID of a transition that moves issues to a closed state. You can find this number under the JIRA workflow administration (**Administration > Issues > Workflows**) by selecting **View** under **Operations** of the desired workflow of your project. The ID of each state can be found inside the parenthesis of each transition name under the **Transitions (id)** column ([see screenshot][trans]). By default, this ID is set to `2`",
+ },
],
- 'kubernetes' => [
+ "kubernetes" => [
{
required: true,
name: :namespace,
type: String,
- desc: 'The Kubernetes namespace to use'
+ desc: "The Kubernetes namespace to use",
},
{
required: true,
name: :api_url,
type: String,
- desc: 'The URL to the Kubernetes cluster API, e.g., https://kubernetes.example.com'
+ desc: "The URL to the Kubernetes cluster API, e.g., https://kubernetes.example.com",
},
{
required: true,
name: :token,
type: String,
- desc: 'The service token to authenticate against the Kubernetes cluster with'
+ desc: "The service token to authenticate against the Kubernetes cluster with",
},
{
required: false,
name: :ca_pem,
type: String,
- desc: 'A custom certificate authority bundle to verify the Kubernetes cluster with (PEM format)'
- }
+ desc: "A custom certificate authority bundle to verify the Kubernetes cluster with (PEM format)",
+ },
],
- 'mattermost-slash-commands' => [
+ "mattermost-slash-commands" => [
{
required: true,
name: :token,
type: String,
- desc: 'The Mattermost token'
- }
+ desc: "The Mattermost token",
+ },
],
- 'slack-slash-commands' => [
+ "slack-slash-commands" => [
{
required: true,
name: :token,
type: String,
- desc: 'The Slack token'
- }
+ desc: "The Slack token",
+ },
],
- 'packagist' => [
+ "packagist" => [
{
required: true,
name: :username,
type: String,
- desc: 'The username'
+ desc: "The username",
},
{
required: true,
name: :token,
type: String,
- desc: 'The Packagist API token'
+ desc: "The Packagist API token",
},
{
required: false,
name: :server,
type: String,
- desc: 'The server'
- }
+ desc: "The server",
+ },
],
- 'pipelines-email' => [
+ "pipelines-email" => [
{
required: true,
name: :recipients,
type: String,
- desc: 'Comma-separated list of recipient email addresses'
+ desc: "Comma-separated list of recipient email addresses",
},
{
required: false,
name: :notify_only_broken_pipelines,
type: Boolean,
- desc: 'Notify only broken pipelines'
- }
+ desc: "Notify only broken pipelines",
+ },
],
- 'pivotaltracker' => [
+ "pivotaltracker" => [
{
required: true,
name: :token,
type: String,
- desc: 'The Pivotaltracker token'
+ desc: "The Pivotaltracker token",
},
{
required: false,
name: :restrict_to_branch,
type: String,
- desc: 'Comma-separated list of branches which will be automatically inspected. Leave blank to include all branches.'
- }
+ desc: "Comma-separated list of branches which will be automatically inspected. Leave blank to include all branches.",
+ },
],
- 'prometheus' => [
+ "prometheus" => [
{
required: true,
name: :api_url,
type: String,
- desc: 'Prometheus API Base URL, like http://prometheus.example.com/'
- }
+ desc: "Prometheus API Base URL, like http://prometheus.example.com/",
+ },
],
- 'pushover' => [
+ "pushover" => [
{
required: true,
name: :api_key,
type: String,
- desc: 'The application key'
+ desc: "The application key",
},
{
required: true,
name: :user_key,
type: String,
- desc: 'The user key'
+ desc: "The user key",
},
{
required: true,
name: :priority,
type: String,
- desc: 'The priority'
+ desc: "The priority",
},
{
required: true,
name: :device,
type: String,
- desc: 'Leave blank for all active devices'
+ desc: "Leave blank for all active devices",
},
{
required: true,
name: :sound,
type: String,
- desc: 'The sound of the notification'
- }
+ desc: "The sound of the notification",
+ },
],
- 'redmine' => [
+ "redmine" => [
{
required: true,
name: :new_issue_url,
type: String,
- desc: 'The new issue URL'
+ desc: "The new issue URL",
},
{
required: true,
name: :project_url,
type: String,
- desc: 'The project URL'
+ desc: "The project URL",
},
{
required: true,
name: :issues_url,
type: String,
- desc: 'The issues URL'
+ desc: "The issues URL",
},
{
required: false,
name: :description,
type: String,
- desc: 'The description of the tracker'
- }
+ desc: "The description of the tracker",
+ },
],
- 'youtrack' => [
+ "youtrack" => [
{
required: true,
name: :project_url,
type: String,
- desc: 'The project URL'
+ desc: "The project URL",
},
{
required: true,
name: :issues_url,
type: String,
- desc: 'The issues URL'
+ desc: "The issues URL",
},
{
required: false,
name: :description,
type: String,
- desc: 'The description of the tracker'
- }
+ desc: "The description of the tracker",
+ },
],
- 'slack' => [
+ "slack" => [
CHAT_NOTIFICATION_SETTINGS,
CHAT_NOTIFICATION_FLAGS,
CHAT_NOTIFICATION_CHANNELS,
- CHAT_NOTIFICATION_EVENTS
+ CHAT_NOTIFICATION_EVENTS,
].flatten,
- 'microsoft-teams' => [
+ "microsoft-teams" => [
{
required: true,
name: :webhook,
type: String,
- desc: 'The Microsoft Teams webhook. e.g. https://outlook.office.com/webhook/…'
- }
+ desc: "The Microsoft Teams webhook. e.g. https://outlook.office.com/webhook/…",
+ },
],
- 'mattermost' => [
+ "mattermost" => [
CHAT_NOTIFICATION_SETTINGS,
CHAT_NOTIFICATION_FLAGS,
CHAT_NOTIFICATION_CHANNELS,
- CHAT_NOTIFICATION_EVENTS
+ CHAT_NOTIFICATION_EVENTS,
].flatten,
- 'teamcity' => [
+ "teamcity" => [
{
required: true,
name: :teamcity_url,
type: String,
- desc: 'TeamCity root URL like https://teamcity.example.com'
+ desc: "TeamCity root URL like https://teamcity.example.com",
},
{
required: true,
name: :build_type,
type: String,
- desc: 'Build configuration ID'
+ desc: "Build configuration ID",
},
{
required: true,
name: :username,
type: String,
- desc: 'A user with permissions to trigger a manual build'
+ desc: "A user with permissions to trigger a manual build",
},
{
required: true,
name: :password,
type: String,
- desc: 'The password of the user'
- }
- ]
+ desc: "The password of the user",
+ },
+ ],
}
service_classes = [
@@ -689,25 +690,25 @@ module API
SlackService,
MattermostService,
MicrosoftTeamsService,
- TeamcityService
+ TeamcityService,
]
if Rails.env.development?
- services['mock-ci'] = [
+ services["mock-ci"] = [
{
required: true,
name: :mock_service_url,
type: String,
- desc: 'URL to the mock service'
- }
+ desc: "URL to the mock service",
+ },
]
- services['mock-deployment'] = []
- services['mock-monitoring'] = []
+ services["mock-deployment"] = []
+ services["mock-monitoring"] = []
service_classes += [
MockCiService,
MockDeploymentService,
- MockMonitoringService
+ MockMonitoringService,
]
end
@@ -721,30 +722,30 @@ module API
required: false,
name: event_name.to_sym,
type: String,
- desc: service.event_description(event_name)
+ desc: service.event_description(event_name),
}
end
end
TRIGGER_SERVICES = {
- 'mattermost-slash-commands' => [
+ "mattermost-slash-commands" => [
{
name: :token,
type: String,
- desc: 'The Mattermost token'
- }
+ desc: "The Mattermost token",
+ },
],
- 'slack-slash-commands' => [
+ "slack-slash-commands" => [
{
name: :token,
type: String,
- desc: 'The Slack token'
- }
- ]
+ desc: "The Slack token",
+ },
+ ],
}.freeze
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
before { authenticate! }
@@ -776,34 +777,34 @@ module API
if service.update(service_params)
present service, with: Entities::ProjectService
else
- render_api_error!('400 Bad Request', 400)
+ render_api_error!("400 Bad Request", 400)
end
end
end
desc "Delete a service for project"
params do
- requires :service_slug, type: String, values: SERVICES.keys, desc: 'The name of the service'
+ requires :service_slug, type: String, values: SERVICES.keys, desc: "The name of the service"
end
delete ":id/services/:service_slug" do
service = user_project.find_or_initialize_service(params[:service_slug].underscore)
destroy_conditionally!(service) do
- attrs = service_attributes(service).inject({}) do |hash, key|
+ attrs = service_attributes(service).inject({}) { |hash, key|
hash.merge!(key => nil)
- end
+ }
unless service.update(attrs.merge(active: false))
- render_api_error!('400 Bad Request', 400)
+ render_api_error!("400 Bad Request", 400)
end
end
end
- desc 'Get the service settings for project' do
+ desc "Get the service settings for project" do
success Entities::ProjectService
end
params do
- requires :service_slug, type: String, values: SERVICES.keys, desc: 'The name of the service'
+ requires :service_slug, type: String, values: SERVICES.keys, desc: "The name of the service"
end
get ":id/services/:service_slug" do
service = user_project.find_or_initialize_service(params[:service_slug].underscore)
@@ -823,11 +824,11 @@ module API
end
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
desc "Trigger a slash command for #{service_slug}" do
- detail 'Added in GitLab 8.13'
+ detail "Added in GitLab 8.13"
end
params do
settings.each do |setting|
@@ -838,7 +839,7 @@ module API
project = find_project(params[:id])
# This is not accurate, but done to prevent leakage of the project names
- not_found!('Service') unless project
+ not_found!("Service") unless project
service = slash_command_service(project, service_slug, params)
result = service.try(:trigger, params)
@@ -847,7 +848,7 @@ module API
status result[:status] || 200
present result
else
- not_found!('Service')
+ not_found!("Service")
end
end
end
diff --git a/lib/api/settings.rb b/lib/api/settings.rb
index b16faffe335..08dee0a1047 100644
--- a/lib/api/settings.rb
+++ b/lib/api/settings.rb
@@ -11,123 +11,123 @@ module API
end
end
- desc 'Get the current application settings' do
+ desc "Get the current application settings" do
success Entities::ApplicationSetting
end
get "application/settings" do
present current_settings, with: Entities::ApplicationSetting
end
- desc 'Modify application settings' do
+ desc "Modify application settings" do
success Entities::ApplicationSetting
end
params do
- optional :admin_notification_email, type: String, desc: 'Abuse reports will be sent to this address if it is set. Abuse reports are always available in the admin area.'
- optional :after_sign_up_text, type: String, desc: 'Text shown after sign up'
- optional :after_sign_out_path, type: String, desc: 'We will redirect users to this page after they sign out'
- optional :akismet_enabled, type: Boolean, desc: 'Helps prevent bots from creating issues'
+ optional :admin_notification_email, type: String, desc: "Abuse reports will be sent to this address if it is set. Abuse reports are always available in the admin area."
+ optional :after_sign_up_text, type: String, desc: "Text shown after sign up"
+ optional :after_sign_out_path, type: String, desc: "We will redirect users to this page after they sign out"
+ optional :akismet_enabled, type: Boolean, desc: "Helps prevent bots from creating issues"
given akismet_enabled: ->(val) { val } do
- requires :akismet_api_key, type: String, desc: 'Generate API key at http://www.akismet.com'
+ requires :akismet_api_key, type: String, desc: "Generate API key at http://www.akismet.com"
end
- optional :clientside_sentry_enabled, type: Boolean, desc: 'Sentry can also be used for reporting and logging clientside exceptions. https://sentry.io/for/javascript/'
+ optional :clientside_sentry_enabled, type: Boolean, desc: "Sentry can also be used for reporting and logging clientside exceptions. https://sentry.io/for/javascript/"
given clientside_sentry_enabled: ->(val) { val } do
- requires :clientside_sentry_dsn, type: String, desc: 'Clientside Sentry Data Source Name'
+ requires :clientside_sentry_dsn, type: String, desc: "Clientside Sentry Data Source Name"
end
- optional :container_registry_token_expire_delay, type: Integer, desc: 'Authorization token duration (minutes)'
+ optional :container_registry_token_expire_delay, type: Integer, desc: "Authorization token duration (minutes)"
optional :default_artifacts_expire_in, type: String, desc: "Set the default expiration time for each job's artifacts"
- optional :default_branch_protection, type: Integer, values: Gitlab::Access.protection_values, desc: 'Determine if developers can push to master'
- optional :default_group_visibility, type: String, values: Gitlab::VisibilityLevel.string_values, desc: 'The default group visibility'
- optional :default_project_visibility, type: String, values: Gitlab::VisibilityLevel.string_values, desc: 'The default project visibility'
- optional :default_projects_limit, type: Integer, desc: 'The maximum number of personal projects'
- optional :default_snippet_visibility, type: String, values: Gitlab::VisibilityLevel.string_values, desc: 'The default snippet visibility'
- optional :disabled_oauth_sign_in_sources, type: Array[String], desc: 'Disable certain OAuth sign-in sources'
- optional :domain_blacklist_enabled, type: Boolean, desc: 'Enable domain blacklist for sign ups'
+ optional :default_branch_protection, type: Integer, values: Gitlab::Access.protection_values, desc: "Determine if developers can push to master"
+ optional :default_group_visibility, type: String, values: Gitlab::VisibilityLevel.string_values, desc: "The default group visibility"
+ optional :default_project_visibility, type: String, values: Gitlab::VisibilityLevel.string_values, desc: "The default project visibility"
+ optional :default_projects_limit, type: Integer, desc: "The maximum number of personal projects"
+ optional :default_snippet_visibility, type: String, values: Gitlab::VisibilityLevel.string_values, desc: "The default snippet visibility"
+ optional :disabled_oauth_sign_in_sources, type: Array[String], desc: "Disable certain OAuth sign-in sources"
+ optional :domain_blacklist_enabled, type: Boolean, desc: "Enable domain blacklist for sign ups"
given domain_blacklist_enabled: ->(val) { val } do
- requires :domain_blacklist, type: String, desc: 'Users with e-mail addresses that match these domain(s) will NOT be able to sign-up. Wildcards allowed. Use separate lines for multiple entries. Ex: domain.com, *.domain.com'
- end
- optional :domain_whitelist, type: String, desc: 'ONLY users with e-mail addresses that match these domain(s) will be able to sign-up. Wildcards allowed. Use separate lines for multiple entries. Ex: domain.com, *.domain.com'
- optional :email_author_in_body, type: Boolean, desc: 'Some email servers do not support overriding the email sender name. Enable this option to include the name of the author of the issue, merge request or comment in the email body instead.'
- optional :enabled_git_access_protocol, type: String, values: %w[ssh http nil], desc: 'Allow only the selected protocols to be used for Git access.'
- optional :gitaly_timeout_default, type: Integer, desc: 'Default Gitaly timeout, in seconds. Set to 0 to disable timeouts.'
- optional :gitaly_timeout_fast, type: Integer, desc: 'Gitaly fast operation timeout, in seconds. Set to 0 to disable timeouts.'
- optional :gitaly_timeout_medium, type: Integer, desc: 'Medium Gitaly timeout, in seconds. Set to 0 to disable timeouts.'
- optional :gravatar_enabled, type: Boolean, desc: 'Flag indicating if the Gravatar service is enabled'
- optional :help_page_hide_commercial_content, type: Boolean, desc: 'Hide marketing-related entries from help'
- optional :help_page_support_url, type: String, desc: 'Alternate support URL for help page'
- optional :help_page_text, type: String, desc: 'Custom text displayed on the help page'
- optional :home_page_url, type: String, desc: 'We will redirect non-logged in users to this page'
- optional :housekeeping_enabled, type: Boolean, desc: 'Enable automatic repository housekeeping (git repack, git gc)'
+ requires :domain_blacklist, type: String, desc: "Users with e-mail addresses that match these domain(s) will NOT be able to sign-up. Wildcards allowed. Use separate lines for multiple entries. Ex: domain.com, *.domain.com"
+ end
+ optional :domain_whitelist, type: String, desc: "ONLY users with e-mail addresses that match these domain(s) will be able to sign-up. Wildcards allowed. Use separate lines for multiple entries. Ex: domain.com, *.domain.com"
+ optional :email_author_in_body, type: Boolean, desc: "Some email servers do not support overriding the email sender name. Enable this option to include the name of the author of the issue, merge request or comment in the email body instead."
+ optional :enabled_git_access_protocol, type: String, values: %w[ssh http nil], desc: "Allow only the selected protocols to be used for Git access."
+ optional :gitaly_timeout_default, type: Integer, desc: "Default Gitaly timeout, in seconds. Set to 0 to disable timeouts."
+ optional :gitaly_timeout_fast, type: Integer, desc: "Gitaly fast operation timeout, in seconds. Set to 0 to disable timeouts."
+ optional :gitaly_timeout_medium, type: Integer, desc: "Medium Gitaly timeout, in seconds. Set to 0 to disable timeouts."
+ optional :gravatar_enabled, type: Boolean, desc: "Flag indicating if the Gravatar service is enabled"
+ optional :help_page_hide_commercial_content, type: Boolean, desc: "Hide marketing-related entries from help"
+ optional :help_page_support_url, type: String, desc: "Alternate support URL for help page"
+ optional :help_page_text, type: String, desc: "Custom text displayed on the help page"
+ optional :home_page_url, type: String, desc: "We will redirect non-logged in users to this page"
+ optional :housekeeping_enabled, type: Boolean, desc: "Enable automatic repository housekeeping (git repack, git gc)"
given housekeeping_enabled: ->(val) { val } do
requires :housekeeping_bitmaps_enabled, type: Boolean, desc: "Creating pack file bitmaps makes housekeeping take a little longer but bitmaps should accelerate 'git clone' performance."
requires :housekeeping_full_repack_period, type: Integer, desc: "Number of Git pushes after which a full 'git repack' is run."
requires :housekeeping_gc_period, type: Integer, desc: "Number of Git pushes after which 'git gc' is run."
requires :housekeeping_incremental_repack_period, type: Integer, desc: "Number of Git pushes after which an incremental 'git repack' is run."
end
- optional :html_emails_enabled, type: Boolean, desc: 'By default GitLab sends emails in HTML and plain text formats so mail clients can choose what format to use. Disable this option if you only want to send emails in plain text format.'
+ optional :html_emails_enabled, type: Boolean, desc: "By default GitLab sends emails in HTML and plain text formats so mail clients can choose what format to use. Disable this option if you only want to send emails in plain text format."
optional :import_sources, type: Array[String], values: %w[github bitbucket gitlab google_code fogbugz git gitlab_project manifest],
- desc: 'Enabled sources for code import during project creation. OmniAuth must be configured for GitHub, Bitbucket, and GitLab.com'
+ desc: "Enabled sources for code import during project creation. OmniAuth must be configured for GitHub, Bitbucket, and GitLab.com"
optional :max_artifacts_size, type: Integer, desc: "Set the maximum file size for each job's artifacts"
- optional :max_attachment_size, type: Integer, desc: 'Maximum attachment size in MB'
- optional :max_pages_size, type: Integer, desc: 'Maximum size of pages in MB'
- optional :metrics_enabled, type: Boolean, desc: 'Enable the InfluxDB metrics'
+ optional :max_attachment_size, type: Integer, desc: "Maximum attachment size in MB"
+ optional :max_pages_size, type: Integer, desc: "Maximum size of pages in MB"
+ optional :metrics_enabled, type: Boolean, desc: "Enable the InfluxDB metrics"
given metrics_enabled: ->(val) { val } do
- requires :metrics_host, type: String, desc: 'The InfluxDB host'
- requires :metrics_method_call_threshold, type: Integer, desc: 'A method call is only tracked when it takes longer to complete than the given amount of milliseconds.'
- requires :metrics_packet_size, type: Integer, desc: 'The amount of points to store in a single UDP packet'
- requires :metrics_pool_size, type: Integer, desc: 'The amount of InfluxDB connections to open'
- requires :metrics_port, type: Integer, desc: 'The UDP port to use for connecting to InfluxDB'
- requires :metrics_sample_interval, type: Integer, desc: 'The sampling interval in seconds'
- requires :metrics_timeout, type: Integer, desc: 'The amount of seconds after which an InfluxDB connection will time out'
- end
- optional :password_authentication_enabled, type: Boolean, desc: 'Flag indicating if password authentication is enabled for the web interface' # support legacy names, can be removed in v5
- optional :password_authentication_enabled_for_web, type: Boolean, desc: 'Flag indicating if password authentication is enabled for the web interface'
+ requires :metrics_host, type: String, desc: "The InfluxDB host"
+ requires :metrics_method_call_threshold, type: Integer, desc: "A method call is only tracked when it takes longer to complete than the given amount of milliseconds."
+ requires :metrics_packet_size, type: Integer, desc: "The amount of points to store in a single UDP packet"
+ requires :metrics_pool_size, type: Integer, desc: "The amount of InfluxDB connections to open"
+ requires :metrics_port, type: Integer, desc: "The UDP port to use for connecting to InfluxDB"
+ requires :metrics_sample_interval, type: Integer, desc: "The sampling interval in seconds"
+ requires :metrics_timeout, type: Integer, desc: "The amount of seconds after which an InfluxDB connection will time out"
+ end
+ optional :password_authentication_enabled, type: Boolean, desc: "Flag indicating if password authentication is enabled for the web interface" # support legacy names, can be removed in v5
+ optional :password_authentication_enabled_for_web, type: Boolean, desc: "Flag indicating if password authentication is enabled for the web interface"
mutually_exclusive :password_authentication_enabled_for_web, :password_authentication_enabled, :signin_enabled
- optional :password_authentication_enabled_for_git, type: Boolean, desc: 'Flag indicating if password authentication is enabled for Git over HTTP(S)'
- optional :performance_bar_allowed_group_id, type: String, desc: 'Deprecated: Use :performance_bar_allowed_group_path instead. Path of the group that is allowed to toggle the performance bar.' # support legacy names, can be removed in v6
- optional :performance_bar_allowed_group_path, type: String, desc: 'Path of the group that is allowed to toggle the performance bar.'
- optional :performance_bar_enabled, type: String, desc: 'Deprecated: Pass `performance_bar_allowed_group_path: nil` instead. Allow enabling the performance.' # support legacy names, can be removed in v6
- optional :plantuml_enabled, type: Boolean, desc: 'Enable PlantUML'
+ optional :password_authentication_enabled_for_git, type: Boolean, desc: "Flag indicating if password authentication is enabled for Git over HTTP(S)"
+ optional :performance_bar_allowed_group_id, type: String, desc: "Deprecated: Use :performance_bar_allowed_group_path instead. Path of the group that is allowed to toggle the performance bar." # support legacy names, can be removed in v6
+ optional :performance_bar_allowed_group_path, type: String, desc: "Path of the group that is allowed to toggle the performance bar."
+ optional :performance_bar_enabled, type: String, desc: "Deprecated: Pass `performance_bar_allowed_group_path: nil` instead. Allow enabling the performance." # support legacy names, can be removed in v6
+ optional :plantuml_enabled, type: Boolean, desc: "Enable PlantUML"
given plantuml_enabled: ->(val) { val } do
- requires :plantuml_url, type: String, desc: 'The PlantUML server URL'
+ requires :plantuml_url, type: String, desc: "The PlantUML server URL"
end
- optional :polling_interval_multiplier, type: BigDecimal, desc: 'Interval multiplier used by endpoints that perform polling. Set to 0 to disable polling.'
- optional :project_export_enabled, type: Boolean, desc: 'Enable project export'
- optional :prometheus_metrics_enabled, type: Boolean, desc: 'Enable Prometheus metrics'
- optional :recaptcha_enabled, type: Boolean, desc: 'Helps prevent bots from creating accounts'
+ optional :polling_interval_multiplier, type: BigDecimal, desc: "Interval multiplier used by endpoints that perform polling. Set to 0 to disable polling."
+ optional :project_export_enabled, type: Boolean, desc: "Enable project export"
+ optional :prometheus_metrics_enabled, type: Boolean, desc: "Enable Prometheus metrics"
+ optional :recaptcha_enabled, type: Boolean, desc: "Helps prevent bots from creating accounts"
given recaptcha_enabled: ->(val) { val } do
- requires :recaptcha_site_key, type: String, desc: 'Generate site key at http://www.google.com/recaptcha'
- requires :recaptcha_private_key, type: String, desc: 'Generate private key at http://www.google.com/recaptcha'
+ requires :recaptcha_site_key, type: String, desc: "Generate site key at http://www.google.com/recaptcha"
+ requires :recaptcha_private_key, type: String, desc: "Generate private key at http://www.google.com/recaptcha"
end
optional :repository_checks_enabled, type: Boolean, desc: "GitLab will periodically run 'git fsck' in all project and wiki repositories to look for silent disk corruption issues."
- optional :repository_storages, type: Array[String], desc: 'Storage paths for new projects'
- optional :require_two_factor_authentication, type: Boolean, desc: 'Require all users to set up Two-factor authentication'
+ optional :repository_storages, type: Array[String], desc: "Storage paths for new projects"
+ optional :require_two_factor_authentication, type: Boolean, desc: "Require all users to set up Two-factor authentication"
given require_two_factor_authentication: ->(val) { val } do
- requires :two_factor_grace_period, type: Integer, desc: 'Amount of time (in hours) that users are allowed to skip forced configuration of two-factor authentication'
+ requires :two_factor_grace_period, type: Integer, desc: "Amount of time (in hours) that users are allowed to skip forced configuration of two-factor authentication"
end
- optional :restricted_visibility_levels, type: Array[String], desc: 'Selected levels cannot be used by non-admin users for groups, projects or snippets. If the public level is restricted, user profiles are only visible to logged in users.'
- optional :send_user_confirmation_email, type: Boolean, desc: 'Send confirmation email on sign-up'
- optional :sentry_enabled, type: Boolean, desc: 'Sentry is an error reporting and logging tool which is currently not shipped with GitLab, get it here: https://getsentry.com'
+ optional :restricted_visibility_levels, type: Array[String], desc: "Selected levels cannot be used by non-admin users for groups, projects or snippets. If the public level is restricted, user profiles are only visible to logged in users."
+ optional :send_user_confirmation_email, type: Boolean, desc: "Send confirmation email on sign-up"
+ optional :sentry_enabled, type: Boolean, desc: "Sentry is an error reporting and logging tool which is currently not shipped with GitLab, get it here: https://getsentry.com"
given sentry_enabled: ->(val) { val } do
- requires :sentry_dsn, type: String, desc: 'Sentry Data Source Name'
+ requires :sentry_dsn, type: String, desc: "Sentry Data Source Name"
end
- optional :session_expire_delay, type: Integer, desc: 'Session duration in minutes. GitLab restart is required to apply changes.'
- optional :shared_runners_enabled, type: Boolean, desc: 'Enable shared runners for new projects'
+ optional :session_expire_delay, type: Integer, desc: "Session duration in minutes. GitLab restart is required to apply changes."
+ optional :shared_runners_enabled, type: Boolean, desc: "Enable shared runners for new projects"
given shared_runners_enabled: ->(val) { val } do
- requires :shared_runners_text, type: String, desc: 'Shared runners text '
- end
- optional :sign_in_text, type: String, desc: 'The sign in text of the GitLab application'
- optional :signin_enabled, type: Boolean, desc: 'Flag indicating if password authentication is enabled for the web interface' # support legacy names, can be removed in v5
- optional :signup_enabled, type: Boolean, desc: 'Flag indicating if sign up is enabled'
- optional :terminal_max_session_time, type: Integer, desc: 'Maximum time for web terminal websocket connection (in seconds). Set to 0 for unlimited time.'
- optional :usage_ping_enabled, type: Boolean, desc: 'Every week GitLab will report license usage back to GitLab, Inc.'
- optional :instance_statistics_visibility_private, type: Boolean, desc: 'When set to `true` Instance statistics will only be available to admins'
+ requires :shared_runners_text, type: String, desc: "Shared runners text "
+ end
+ optional :sign_in_text, type: String, desc: "The sign in text of the GitLab application"
+ optional :signin_enabled, type: Boolean, desc: "Flag indicating if password authentication is enabled for the web interface" # support legacy names, can be removed in v5
+ optional :signup_enabled, type: Boolean, desc: "Flag indicating if sign up is enabled"
+ optional :terminal_max_session_time, type: Integer, desc: "Maximum time for web terminal websocket connection (in seconds). Set to 0 for unlimited time."
+ optional :usage_ping_enabled, type: Boolean, desc: "Every week GitLab will report license usage back to GitLab, Inc."
+ optional :instance_statistics_visibility_private, type: Boolean, desc: "When set to `true` Instance statistics will only be available to admins"
optional :local_markdown_version, type: Integer, desc: "Local markdown version, increase this value when any cached markdown should be invalidated"
ApplicationSetting::SUPPORTED_KEY_TYPES.each do |type|
optional :"#{type}_key_restriction",
- type: Integer,
- values: KeyRestrictionValidator.supported_key_restrictions(type),
- desc: "Restrictions on the complexity of uploaded #{type.upcase} keys. A value of #{ApplicationSetting::FORBIDDEN_KEY_VALUE} disables all #{type.upcase} keys."
+ type: Integer,
+ values: KeyRestrictionValidator.supported_key_restrictions(type),
+ desc: "Restrictions on the complexity of uploaded #{type.upcase} keys. A value of #{ApplicationSetting::FORBIDDEN_KEY_VALUE} disables all #{type.upcase} keys."
end
optional_attributes = ::ApplicationSettingsHelper.visible_attributes << :performance_bar_allowed_group_id
@@ -139,20 +139,20 @@ module API
attrs = declared_params(include_missing: false)
# support legacy names, can be removed in v6
- if attrs.has_key?(:performance_bar_allowed_group_id)
+ if attrs.key?(:performance_bar_allowed_group_id)
attrs[:performance_bar_allowed_group_path] = attrs.delete(:performance_bar_allowed_group_id)
end
# support legacy names, can be removed in v6
- if attrs.has_key?(:performance_bar_enabled)
+ if attrs.key?(:performance_bar_enabled)
performance_bar_enabled = attrs.delete(:performance_bar_allowed_group_id)
attrs[:performance_bar_allowed_group_path] = nil unless performance_bar_enabled
end
# support legacy names, can be removed in v5
- if attrs.has_key?(:signin_enabled)
+ if attrs.key?(:signin_enabled)
attrs[:password_authentication_enabled_for_web] = attrs.delete(:signin_enabled)
- elsif attrs.has_key?(:password_authentication_enabled)
+ elsif attrs.key?(:password_authentication_enabled)
attrs[:password_authentication_enabled_for_web] = attrs.delete(:password_authentication_enabled)
end
diff --git a/lib/api/sidekiq_metrics.rb b/lib/api/sidekiq_metrics.rb
index daa9598a204..a8fd2a01b13 100644
--- a/lib/api/sidekiq_metrics.rb
+++ b/lib/api/sidekiq_metrics.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'sidekiq/api'
+require "sidekiq/api"
module API
class SidekiqMetrics < Grape::API
@@ -11,7 +11,7 @@ module API
Sidekiq::Queue.all.each_with_object({}) do |queue, hash|
hash[queue.name] = {
backlog: queue.size,
- latency: queue.latency.to_i
+ latency: queue.latency.to_i,
}
end
end
@@ -19,14 +19,14 @@ module API
def process_metrics
Sidekiq::ProcessSet.new.map do |process|
{
- hostname: process['hostname'],
- pid: process['pid'],
- tag: process['tag'],
- started_at: Time.at(process['started_at']),
- queues: process['queues'],
- labels: process['labels'],
- concurrency: process['concurrency'],
- busy: process['busy']
+ hostname: process["hostname"],
+ pid: process["pid"],
+ tag: process["tag"],
+ started_at: Time.at(process["started_at"]),
+ queues: process["queues"],
+ labels: process["labels"],
+ concurrency: process["concurrency"],
+ busy: process["busy"],
}
end
end
@@ -36,29 +36,29 @@ module API
{
processed: stats.processed,
failed: stats.failed,
- enqueued: stats.enqueued
+ enqueued: stats.enqueued,
}
end
end
- desc 'Get the Sidekiq queue metrics'
- get 'sidekiq/queue_metrics' do
- { queues: queue_metrics }
+ desc "Get the Sidekiq queue metrics"
+ get "sidekiq/queue_metrics" do
+ {queues: queue_metrics}
end
- desc 'Get the Sidekiq process metrics'
- get 'sidekiq/process_metrics' do
- { processes: process_metrics }
+ desc "Get the Sidekiq process metrics"
+ get "sidekiq/process_metrics" do
+ {processes: process_metrics}
end
- desc 'Get the Sidekiq job statistics'
- get 'sidekiq/job_stats' do
- { jobs: job_stats }
+ desc "Get the Sidekiq job statistics"
+ get "sidekiq/job_stats" do
+ {jobs: job_stats}
end
- desc 'Get the Sidekiq Compound metrics. Includes queue, process, and job statistics'
- get 'sidekiq/compound_metrics' do
- { queues: queue_metrics, processes: process_metrics, jobs: job_stats }
+ desc "Get the Sidekiq Compound metrics. Includes queue, process, and job statistics"
+ get "sidekiq/compound_metrics" do
+ {queues: queue_metrics, processes: process_metrics, jobs: job_stats}
end
end
end
diff --git a/lib/api/snippets.rb b/lib/api/snippets.rb
index 326d55afd0e..62e1e9aef2d 100644
--- a/lib/api/snippets.rb
+++ b/lib/api/snippets.rb
@@ -18,8 +18,8 @@ module API
end
end
- desc 'Get a snippets list for authenticated user' do
- detail 'This feature was introduced in GitLab 8.15.'
+ desc "Get a snippets list for authenticated user" do
+ detail "This feature was introduced in GitLab 8.15."
success Entities::PersonalSnippet
end
params do
@@ -29,42 +29,42 @@ module API
present paginate(snippets_for_current_user), with: Entities::PersonalSnippet
end
- desc 'List all public snippets current_user has access to' do
- detail 'This feature was introduced in GitLab 8.15.'
+ desc "List all public snippets current_user has access to" do
+ detail "This feature was introduced in GitLab 8.15."
success Entities::PersonalSnippet
end
params do
use :pagination
end
- get 'public' do
+ get "public" do
present paginate(public_snippets), with: Entities::PersonalSnippet
end
- desc 'Get a single snippet' do
- detail 'This feature was introduced in GitLab 8.15.'
+ desc "Get a single snippet" do
+ detail "This feature was introduced in GitLab 8.15."
success Entities::PersonalSnippet
end
params do
- requires :id, type: Integer, desc: 'The ID of a snippet'
+ requires :id, type: Integer, desc: "The ID of a snippet"
end
- get ':id' do
+ get ":id" do
snippet = snippets_for_current_user.find(params[:id])
present snippet, with: Entities::PersonalSnippet
end
- desc 'Create new snippet' do
- detail 'This feature was introduced in GitLab 8.15.'
+ desc "Create new snippet" do
+ detail "This feature was introduced in GitLab 8.15."
success Entities::PersonalSnippet
end
params do
- requires :title, type: String, desc: 'The title of a snippet'
- requires :file_name, type: String, desc: 'The name of a snippet file'
- requires :content, type: String, desc: 'The content of a snippet'
- optional :description, type: String, desc: 'The description of a snippet'
+ requires :title, type: String, desc: "The title of a snippet"
+ requires :file_name, type: String, desc: "The name of a snippet file"
+ requires :content, type: String, desc: "The content of a snippet"
+ optional :description, type: String, desc: "The description of a snippet"
optional :visibility, type: String,
values: Gitlab::VisibilityLevel.string_values,
- default: 'internal',
- desc: 'The visibility of the snippet'
+ default: "internal",
+ desc: "The visibility of the snippet"
end
post do
attrs = declared_params(include_missing: false).merge(request: request, api: true)
@@ -79,25 +79,25 @@ module API
end
end
- desc 'Update an existing snippet' do
- detail 'This feature was introduced in GitLab 8.15.'
+ desc "Update an existing snippet" do
+ detail "This feature was introduced in GitLab 8.15."
success Entities::PersonalSnippet
end
params do
- requires :id, type: Integer, desc: 'The ID of a snippet'
- optional :title, type: String, desc: 'The title of a snippet'
- optional :file_name, type: String, desc: 'The name of a snippet file'
- optional :content, type: String, desc: 'The content of a snippet'
- optional :description, type: String, desc: 'The description of a snippet'
+ requires :id, type: Integer, desc: "The ID of a snippet"
+ optional :title, type: String, desc: "The title of a snippet"
+ optional :file_name, type: String, desc: "The name of a snippet file"
+ optional :content, type: String, desc: "The content of a snippet"
+ optional :description, type: String, desc: "The description of a snippet"
optional :visibility, type: String,
values: Gitlab::VisibilityLevel.string_values,
- desc: 'The visibility of the snippet'
+ desc: "The visibility of the snippet"
at_least_one_of :title, :file_name, :content, :visibility
end
# rubocop: disable CodeReuse/ActiveRecord
- put ':id' do
+ put ":id" do
snippet = snippets_for_current_user.find_by(id: params.delete(:id))
- break not_found!('Snippet') unless snippet
+ break not_found!("Snippet") unless snippet
authorize! :update_personal_snippet, snippet
@@ -115,17 +115,17 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Remove snippet' do
- detail 'This feature was introduced in GitLab 8.15.'
+ desc "Remove snippet" do
+ detail "This feature was introduced in GitLab 8.15."
success Entities::PersonalSnippet
end
params do
- requires :id, type: Integer, desc: 'The ID of a snippet'
+ requires :id, type: Integer, desc: "The ID of a snippet"
end
# rubocop: disable CodeReuse/ActiveRecord
- delete ':id' do
+ delete ":id" do
snippet = snippets_for_current_user.find_by(id: params.delete(:id))
- break not_found!('Snippet') unless snippet
+ break not_found!("Snippet") unless snippet
authorize! :destroy_personal_snippet, snippet
@@ -133,29 +133,29 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get a raw snippet' do
- detail 'This feature was introduced in GitLab 8.15.'
+ desc "Get a raw snippet" do
+ detail "This feature was introduced in GitLab 8.15."
end
params do
- requires :id, type: Integer, desc: 'The ID of a snippet'
+ requires :id, type: Integer, desc: "The ID of a snippet"
end
# rubocop: disable CodeReuse/ActiveRecord
get ":id/raw" do
snippet = snippets_for_current_user.find_by(id: params.delete(:id))
- break not_found!('Snippet') unless snippet
+ break not_found!("Snippet") unless snippet
- env['api.format'] = :txt
- content_type 'text/plain'
- header['Content-Disposition'] = 'attachment'
+ env["api.format"] = :txt
+ content_type "text/plain"
+ header["Content-Disposition"] = "attachment"
present snippet.content
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get the user agent details for a snippet' do
+ desc "Get the user agent details for a snippet" do
success Entities::UserAgentDetail
end
params do
- requires :id, type: Integer, desc: 'The ID of a snippet'
+ requires :id, type: Integer, desc: "The ID of a snippet"
end
# rubocop: disable CodeReuse/ActiveRecord
get ":id/user_agent_detail" do
@@ -163,7 +163,7 @@ module API
snippet = Snippet.find_by!(id: params[:id])
- break not_found!('UserAgentDetail') unless snippet.user_agent_detail
+ break not_found!("UserAgentDetail") unless snippet.user_agent_detail
present snippet.user_agent_detail, with: Entities::UserAgentDetail
end
diff --git a/lib/api/submodules.rb b/lib/api/submodules.rb
index 72d7d994102..a76c6a832db 100644
--- a/lib/api/submodules.rb
+++ b/lib/api/submodules.rb
@@ -10,23 +10,23 @@ module API
submodule: attrs[:submodule],
commit_sha: attrs[:commit_sha],
branch_name: attrs[:branch],
- commit_message: attrs[:commit_message]
+ commit_message: attrs[:commit_message],
}
end
end
params do
- requires :id, type: String, desc: 'The project ID'
+ requires :id, type: String, desc: "The project ID"
end
resource :projects, requirements: Files::FILE_ENDPOINT_REQUIREMENTS do
- desc 'Update existing submodule reference in repository' do
+ desc "Update existing submodule reference in repository" do
success Entities::Commit
end
params do
- requires :submodule, type: String, desc: 'Url encoded full path to submodule.'
- requires :commit_sha, type: String, desc: 'Commit sha to update the submodule to.'
- requires :branch, type: String, desc: 'Name of the branch to commit into.'
- optional :commit_message, type: String, desc: 'Commit message. If no message is provided a default one will be set.'
+ requires :submodule, type: String, desc: "Url encoded full path to submodule."
+ requires :commit_sha, type: String, desc: "Commit sha to update the submodule to."
+ requires :branch, type: String, desc: "Name of the branch to commit into."
+ optional :commit_message, type: String, desc: "Commit message. If no message is provided a default one will be set."
end
put ":id/repository/submodules/:submodule", requirements: Files::FILE_ENDPOINT_REQUIREMENTS do
authorize! :push_code, user_project
diff --git a/lib/api/subscriptions.rb b/lib/api/subscriptions.rb
index dfb54446ddf..c36e52cfd79 100644
--- a/lib/api/subscriptions.rb
+++ b/lib/api/subscriptions.rb
@@ -8,29 +8,29 @@ module API
subscribables = [
{
- type: 'merge_requests',
+ type: "merge_requests",
entity: Entities::MergeRequest,
source: Project,
- finder: ->(id) { find_merge_request_with_access(id, :update_merge_request) }
+ finder: ->(id) { find_merge_request_with_access(id, :update_merge_request) },
},
{
- type: 'issues',
+ type: "issues",
entity: Entities::Issue,
source: Project,
- finder: ->(id) { find_project_issue(id) }
+ finder: ->(id) { find_project_issue(id) },
},
{
- type: 'labels',
+ type: "labels",
entity: Entities::ProjectLabel,
source: Project,
- finder: ->(id) { find_label(user_project, id) }
+ finder: ->(id) { find_label(user_project, id) },
},
{
- type: 'labels',
+ type: "labels",
entity: Entities::GroupLabel,
source: Group,
- finder: ->(id) { find_label(user_group, id) }
- }
+ finder: ->(id) { find_label(user_group, id) },
+ },
]
subscribables.each do |subscribable|
@@ -38,10 +38,10 @@ module API
params do
requires :id, type: String, desc: "The #{source_type} ID"
- requires :subscribable_id, type: String, desc: 'The ID of a resource'
+ requires :subscribable_id, type: String, desc: "The ID of a resource"
end
resource source_type.pluralize, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Subscribe to a resource' do
+ desc "Subscribe to a resource" do
success subscribable[:entity]
end
post ":id/#{subscribable[:type]}/:subscribable_id/subscribe" do
@@ -56,7 +56,7 @@ module API
end
end
- desc 'Unsubscribe from a resource' do
+ desc "Unsubscribe from a resource" do
success subscribable[:entity]
end
post ":id/#{subscribable[:type]}/:subscribable_id/unsubscribe" do
@@ -78,10 +78,8 @@ module API
helpers do
def parent_resource(source_type)
case source_type
- when 'project'
+ when "project"
user_project
- else
- nil
end
end
end
diff --git a/lib/api/suggestions.rb b/lib/api/suggestions.rb
index d008d1b9e97..92713b54230 100644
--- a/lib/api/suggestions.rb
+++ b/lib/api/suggestions.rb
@@ -5,13 +5,13 @@ module API
before { authenticate! }
resource :suggestions do
- desc 'Apply suggestion patch in the Merge Request it was created' do
+ desc "Apply suggestion patch in the Merge Request it was created" do
success Entities::Suggestion
end
params do
- requires :id, type: String, desc: 'The suggestion ID'
+ requires :id, type: String, desc: "The suggestion ID"
end
- put ':id/apply' do
+ put ":id/apply" do
suggestion = Suggestion.find_by_id(params[:id])
not_found! unless suggestion
diff --git a/lib/api/system_hooks.rb b/lib/api/system_hooks.rb
index 51fae0e54aa..ff4e903ed3c 100644
--- a/lib/api/system_hooks.rb
+++ b/lib/api/system_hooks.rb
@@ -10,7 +10,7 @@ module API
end
resource :hooks do
- desc 'Get the list of system hooks' do
+ desc "Get the list of system hooks" do
success Entities::Hook
end
params do
@@ -20,12 +20,12 @@ module API
present paginate(SystemHook.all), with: Entities::Hook
end
- desc 'Create a new system hook' do
+ desc "Create a new system hook" do
success Entities::Hook
end
params do
requires :url, type: String, desc: "The URL to send the request to"
- optional :token, type: String, desc: 'The token used to validate payloads'
+ optional :token, type: String, desc: "The token used to validate payloads"
optional :push_events, type: Boolean, desc: "Trigger hook on push events"
optional :tag_push_events, type: Boolean, desc: "Trigger hook on tag push events"
optional :merge_requests_events, type: Boolean, desc: "Trigger hook on tag push events"
@@ -41,9 +41,9 @@ module API
end
end
- desc 'Test a hook'
+ desc "Test a hook"
params do
- requires :id, type: Integer, desc: 'The ID of the system hook'
+ requires :id, type: Integer, desc: "The ID of the system hook"
end
get ":id" do
hook = SystemHook.find(params[:id])
@@ -53,22 +53,22 @@ module API
path: "ruby",
project_id: 1,
owner_name: "Someone",
- owner_email: "example@gitlabhq.com"
+ owner_email: "example@gitlabhq.com",
}
- hook.execute(data, 'system_hooks')
+ hook.execute(data, "system_hooks")
data
end
- desc 'Delete a hook' do
+ desc "Delete a hook" do
success Entities::Hook
end
params do
- requires :id, type: Integer, desc: 'The ID of the system hook'
+ requires :id, type: Integer, desc: "The ID of the system hook"
end
# rubocop: disable CodeReuse/ActiveRecord
delete ":id" do
hook = SystemHook.find_by(id: params[:id])
- not_found!('System hook') unless hook
+ not_found!("System hook") unless hook
destroy_conditionally!(hook)
end
diff --git a/lib/api/tags.rb b/lib/api/tags.rb
index f5359fd316c..6644f70056d 100644
--- a/lib/api/tags.rb
+++ b/lib/api/tags.rb
@@ -9,52 +9,52 @@ module API
before { authorize! :download_code, user_project }
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get a project repository tags' do
+ desc "Get a project repository tags" do
success Entities::Tag
end
params do
- optional :sort, type: String, values: %w[asc desc], default: 'desc',
- desc: 'Return tags sorted in updated by `asc` or `desc` order.'
- optional :order_by, type: String, values: %w[name updated], default: 'updated',
- desc: 'Return tags ordered by `name` or `updated` fields.'
- optional :search, type: String, desc: 'Return list of tags matching the search criteria'
+ optional :sort, type: String, values: %w[asc desc], default: "desc",
+ desc: "Return tags sorted in updated by `asc` or `desc` order."
+ optional :order_by, type: String, values: %w[name updated], default: "updated",
+ desc: "Return tags ordered by `name` or `updated` fields."
+ optional :search, type: String, desc: "Return list of tags matching the search criteria"
use :pagination
end
- get ':id/repository/tags' do
+ get ":id/repository/tags" do
tags = ::TagsFinder.new(user_project.repository,
- sort: "#{params[:order_by]}_#{params[:sort]}",
- search: params[:search]).execute
+ sort: "#{params[:order_by]}_#{params[:sort]}",
+ search: params[:search]).execute
present paginate(::Kaminari.paginate_array(tags)), with: Entities::Tag, project: user_project
end
- desc 'Get a single repository tag' do
+ desc "Get a single repository tag" do
success Entities::Tag
end
params do
- requires :tag_name, type: String, desc: 'The name of the tag'
+ requires :tag_name, type: String, desc: "The name of the tag"
end
- get ':id/repository/tags/:tag_name', requirements: TAG_ENDPOINT_REQUIREMENTS do
+ get ":id/repository/tags/:tag_name", requirements: TAG_ENDPOINT_REQUIREMENTS do
tag = user_project.repository.find_tag(params[:tag_name])
- not_found!('Tag') unless tag
+ not_found!("Tag") unless tag
present tag, with: Entities::Tag, project: user_project
end
- desc 'Create a new repository tag' do
- detail 'This optional release_description parameter was deprecated in GitLab 11.7.'
+ desc "Create a new repository tag" do
+ detail "This optional release_description parameter was deprecated in GitLab 11.7."
success Entities::Tag
end
params do
- requires :tag_name, type: String, desc: 'The name of the tag'
- requires :ref, type: String, desc: 'The commit sha or branch name'
- optional :message, type: String, desc: 'Specifying a message creates an annotated tag'
- optional :release_description, type: String, desc: 'Specifying release notes stored in the GitLab database (deprecated in GitLab 11.7)'
+ requires :tag_name, type: String, desc: "The name of the tag"
+ requires :ref, type: String, desc: "The commit sha or branch name"
+ optional :message, type: String, desc: "Specifying a message creates an annotated tag"
+ optional :release_description, type: String, desc: "Specifying release notes stored in the GitLab database (deprecated in GitLab 11.7)"
end
- post ':id/repository/tags' do
+ post ":id/repository/tags" do
authorize_push_project
result = ::Tags::CreateService.new(user_project, current_user)
@@ -66,7 +66,7 @@ module API
release_create_params = {
tag: params[:tag_name],
name: params[:tag_name], # Name can be specified in new API
- description: params[:release_description]
+ description: params[:release_description],
}
::Releases::CreateService
@@ -75,28 +75,28 @@ module API
end
present result[:tag],
- with: Entities::Tag,
- project: user_project
+ with: Entities::Tag,
+ project: user_project
else
render_api_error!(result[:message], 400)
end
end
- desc 'Delete a repository tag'
+ desc "Delete a repository tag"
params do
- requires :tag_name, type: String, desc: 'The name of the tag'
+ requires :tag_name, type: String, desc: "The name of the tag"
end
- delete ':id/repository/tags/:tag_name', requirements: TAG_ENDPOINT_REQUIREMENTS do
+ delete ":id/repository/tags/:tag_name", requirements: TAG_ENDPOINT_REQUIREMENTS do
authorize_push_project
tag = user_project.repository.find_tag(params[:tag_name])
- not_found!('Tag') unless tag
+ not_found!("Tag") unless tag
commit = user_project.repository.commit(tag.dereferenced_target)
destroy_conditionally!(commit, last_updated: commit.authored_date) do
result = ::Tags::DestroyService.new(user_project, current_user)
- .execute(params[:tag_name])
+ .execute(params[:tag_name])
if result[:status] != :success
render_api_error!(result[:message], result[:return_code])
@@ -104,25 +104,25 @@ module API
end
end
- desc 'Add a release note to a tag' do
- detail 'This feature was deprecated in GitLab 11.7.'
+ desc "Add a release note to a tag" do
+ detail "This feature was deprecated in GitLab 11.7."
success Entities::TagRelease
end
params do
- requires :tag_name, type: String, desc: 'The name of the tag', as: :tag
- requires :description, type: String, desc: 'Release notes with markdown support'
+ requires :tag_name, type: String, desc: "The name of the tag", as: :tag
+ requires :description, type: String, desc: "Release notes with markdown support"
end
- post ':id/repository/tags/:tag_name/release', requirements: TAG_ENDPOINT_REQUIREMENTS do
+ post ":id/repository/tags/:tag_name/release", requirements: TAG_ENDPOINT_REQUIREMENTS do
authorize_create_release!
##
# Legacy API does not support tag auto creation.
- not_found!('Tag') unless user_project.repository.find_tag(params[:tag])
+ not_found!("Tag") unless user_project.repository.find_tag(params[:tag])
release_create_params = {
tag: params[:tag],
name: params[:tag], # Name can be specified in new API
- description: params[:description]
+ description: params[:description],
}
result = ::Releases::CreateService
@@ -137,14 +137,14 @@ module API
end
desc "Update a tag's release note" do
- detail 'This feature was deprecated in GitLab 11.7.'
+ detail "This feature was deprecated in GitLab 11.7."
success Entities::TagRelease
end
params do
- requires :tag_name, type: String, desc: 'The name of the tag', as: :tag
- requires :description, type: String, desc: 'Release notes with markdown support'
+ requires :tag_name, type: String, desc: "The name of the tag", as: :tag
+ requires :description, type: String, desc: "Release notes with markdown support"
end
- put ':id/repository/tags/:tag_name/release', requirements: TAG_ENDPOINT_REQUIREMENTS do
+ put ":id/repository/tags/:tag_name/release", requirements: TAG_ENDPOINT_REQUIREMENTS do
authorize_update_release!
result = ::Releases::UpdateService
diff --git a/lib/api/templates.rb b/lib/api/templates.rb
index 51f357d9477..c4b1c4f2d52 100644
--- a/lib/api/templates.rb
+++ b/lib/api/templates.rb
@@ -6,14 +6,14 @@ module API
GLOBAL_TEMPLATE_TYPES = {
gitignores: {
- gitlab_version: 8.8
+ gitlab_version: 8.8,
},
gitlab_ci_ymls: {
- gitlab_version: 8.9
+ gitlab_version: 8.9,
},
dockerfiles: {
- gitlab_version: 8.15
- }
+ gitlab_version: 8.15,
+ },
}.freeze
helpers do
@@ -23,12 +23,12 @@ module API
end
end
- desc 'Get the list of the available license template' do
- detail 'This feature was introduced in GitLab 8.7.'
+ desc "Get the list of the available license template" do
+ detail "This feature was introduced in GitLab 8.7."
success ::API::Entities::License
end
params do
- optional :popular, type: Boolean, desc: 'If passed, returns only popular licenses'
+ optional :popular, type: Boolean, desc: "If passed, returns only popular licenses"
use :pagination
end
get "templates/licenses" do
@@ -40,17 +40,17 @@ module API
present paginate(::Kaminari.paginate_array(templates)), with: ::API::Entities::License
end
- desc 'Get the text for a specific license' do
- detail 'This feature was introduced in GitLab 8.7.'
+ desc "Get the text for a specific license" do
+ detail "This feature was introduced in GitLab 8.7."
success ::API::Entities::License
end
params do
- requires :name, type: String, desc: 'The name of the template'
+ requires :name, type: String, desc: "The name of the template"
end
- get "templates/licenses/:name", requirements: { name: /[\w\.-]+/ } do
+ get "templates/licenses/:name", requirements: {name: /[\w\.-]+/} do
template = TemplateFinder.build(:licenses, nil, name: params[:name]).execute
- not_found!('License') unless template.present?
+ not_found!("License") unless template.present?
template.resolve!(
project_name: params[:project].presence,
@@ -63,7 +63,7 @@ module API
GLOBAL_TEMPLATE_TYPES.each do |template_type, properties|
gitlab_version = properties[:gitlab_version]
- desc 'Get the list of the available template' do
+ desc "Get the list of the available template" do
detail "This feature was introduced in GitLab #{gitlab_version}."
success Entities::TemplatesList
end
@@ -75,14 +75,14 @@ module API
present paginate(templates), with: Entities::TemplatesList
end
- desc 'Get the text for a specific template present in local filesystem' do
+ desc "Get the text for a specific template present in local filesystem" do
detail "This feature was introduced in GitLab #{gitlab_version}."
success Entities::Template
end
params do
- requires :name, type: String, desc: 'The name of the template'
+ requires :name, type: String, desc: "The name of the template"
end
- get "templates/#{template_type}/:name", requirements: { name: /[\w\.-]+/ } do
+ get "templates/#{template_type}/:name", requirements: {name: /[\w\.-]+/} do
finder = TemplateFinder.build(template_type, nil, name: declared(params)[:name])
new_template = finder.execute
diff --git a/lib/api/time_tracking_endpoints.rb b/lib/api/time_tracking_endpoints.rb
index 93fe06bec27..9a65801855d 100644
--- a/lib/api/time_tracking_endpoints.rb
+++ b/lib/api/time_tracking_endpoints.rb
@@ -7,7 +7,7 @@ module API
included do
helpers do
def issuable_name
- declared_params.key?(:issue_iid) ? 'issue' : 'merge_request'
+ declared_params.key?(:issue_iid) ? "issue" : "merge_request"
end
def issuable_key
@@ -25,9 +25,9 @@ module API
def load_issuable
@issuable ||= begin
case issuable_name
- when 'issue'
+ when "issue"
find_project_issue(params.delete(issuable_key))
- when 'merge_request'
+ when "merge_request"
find_project_merge_request(params.delete(issuable_key))
end
end
@@ -46,18 +46,18 @@ module API
end
def update_service
- issuable_name == 'issue' ? ::Issues::UpdateService : ::MergeRequests::UpdateService
+ issuable_name == "issue" ? ::Issues::UpdateService : ::MergeRequests::UpdateService
end
end
- issuable_name = name.end_with?('Issues') ? 'issue' : 'merge_request'
+ issuable_name = name.end_with?("Issues") ? "issue" : "merge_request"
issuable_collection_name = issuable_name.pluralize
issuable_key = "#{issuable_name}_iid".to_sym
desc "Set a time estimate for a project #{issuable_name}"
params do
requires issuable_key, type: Integer, desc: "The ID of a project #{issuable_name}"
- requires :duration, type: String, desc: 'The duration to be parsed'
+ requires :duration, type: String, desc: "The duration to be parsed"
end
post ":id/#{issuable_collection_name}/:#{issuable_key}/time_estimate" do
authorize! update_issuable_key, load_issuable
@@ -80,14 +80,14 @@ module API
desc "Add spent time for a project #{issuable_name}"
params do
requires issuable_key, type: Integer, desc: "The ID of a project #{issuable_name}"
- requires :duration, type: String, desc: 'The duration to be parsed'
+ requires :duration, type: String, desc: "The duration to be parsed"
end
post ":id/#{issuable_collection_name}/:#{issuable_key}/add_spent_time" do
authorize! update_issuable_key, load_issuable
update_issuable(spend_time: {
duration: Gitlab::TimeTrackingFormatter.parse(params.delete(:duration)),
- user_id: current_user.id
+ user_id: current_user.id,
})
end
@@ -99,7 +99,7 @@ module API
authorize! update_issuable_key, load_issuable
status :ok
- update_issuable(spend_time: { duration: :reset, user_id: current_user.id })
+ update_issuable(spend_time: {duration: :reset, user_id: current_user.id})
end
desc "Show time stats for a project #{issuable_name}"
diff --git a/lib/api/todos.rb b/lib/api/todos.rb
index 64ac8ece56c..99aad6eb964 100644
--- a/lib/api/todos.rb
+++ b/lib/api/todos.rb
@@ -7,22 +7,22 @@ module API
before { authenticate! }
ISSUABLE_TYPES = {
- 'merge_requests' => ->(iid) { find_merge_request_with_access(iid) },
- 'issues' => ->(iid) { find_project_issue(iid) }
+ "merge_requests" => ->(iid) { find_merge_request_with_access(iid) },
+ "issues" => ->(iid) { find_project_issue(iid) },
}.freeze
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
ISSUABLE_TYPES.each do |type, finder|
type_id_str = "#{type.singularize}_iid".to_sym
- desc 'Create a todo on an issuable' do
+ desc "Create a todo on an issuable" do
success Entities::Todo
end
params do
- requires type_id_str, type: Integer, desc: 'The IID of an issuable'
+ requires type_id_str, type: Integer, desc: "The IID of an issuable"
end
post ":id/#{type}/:#{type_id_str}/todo" do
issuable = instance_exec(params[type_id_str], &finder)
@@ -44,7 +44,7 @@ module API
end
end
- desc 'Get a todo list' do
+ desc "Get a todo list" do
success Entities::Todo
end
params do
@@ -54,21 +54,21 @@ module API
present paginate(find_todos), with: Entities::Todo, current_user: current_user
end
- desc 'Mark a todo as done' do
+ desc "Mark a todo as done" do
success Entities::Todo
end
params do
- requires :id, type: Integer, desc: 'The ID of the todo being marked as done'
+ requires :id, type: Integer, desc: "The ID of the todo being marked as done"
end
- post ':id/mark_as_done' do
+ post ":id/mark_as_done" do
TodoService.new.mark_todos_as_done_by_ids(params[:id], current_user)
todo = current_user.todos.find(params[:id])
present todo, with: Entities::Todo, current_user: current_user
end
- desc 'Mark all todos as done'
- post '/mark_as_done' do
+ desc "Mark all todos as done"
+ post "/mark_as_done" do
todos = find_todos
TodoService.new.mark_todos_as_done(todos, current_user)
diff --git a/lib/api/triggers.rb b/lib/api/triggers.rb
index 8fc7c7361e1..6754fc13ec1 100644
--- a/lib/api/triggers.rb
+++ b/lib/api/triggers.rb
@@ -5,24 +5,24 @@ module API
include PaginationParams
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Trigger a GitLab project pipeline' do
+ desc "Trigger a GitLab project pipeline" do
success Entities::Pipeline
end
params do
- requires :ref, type: String, desc: 'The commit sha or name of a branch or tag', allow_blank: false
- requires :token, type: String, desc: 'The unique token of trigger'
- optional :variables, type: Hash, desc: 'The list of variables to be injected into build'
+ requires :ref, type: String, desc: "The commit sha or name of a branch or tag", allow_blank: false
+ requires :token, type: String, desc: "The unique token of trigger"
+ optional :variables, type: Hash, desc: "The list of variables to be injected into build"
end
- post ":id/(ref/:ref/)trigger/pipeline", requirements: { ref: /.+/ } do
- Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42283')
+ post ":id/(ref/:ref/)trigger/pipeline", requirements: {ref: /.+/} do
+ Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42283")
# validate variables
params[:variables] = params[:variables].to_h
unless params[:variables].all? { |key, value| key.is_a?(String) && value.is_a?(String) }
- render_api_error!('variables needs to be a map of key-valued strings', 400)
+ render_api_error!("variables needs to be a map of key-valued strings", 400)
end
project = find_project(params[:id])
@@ -38,14 +38,14 @@ module API
end
end
- desc 'Get triggers list' do
+ desc "Get triggers list" do
success Entities::Trigger
end
params do
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/triggers' do
+ get ":id/triggers" do
authenticate!
authorize! :admin_build, user_project
@@ -55,34 +55,35 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get specific trigger of a project' do
+ desc "Get specific trigger of a project" do
success Entities::Trigger
end
params do
- requires :trigger_id, type: Integer, desc: 'The trigger ID'
+ requires :trigger_id, type: Integer, desc: "The trigger ID"
end
- get ':id/triggers/:trigger_id' do
+ get ":id/triggers/:trigger_id" do
authenticate!
authorize! :admin_build, user_project
trigger = user_project.triggers.find(params.delete(:trigger_id))
- break not_found!('Trigger') unless trigger
+ break not_found!("Trigger") unless trigger
present trigger, with: Entities::Trigger, current_user: current_user
end
- desc 'Create a trigger' do
+ desc "Create a trigger" do
success Entities::Trigger
end
params do
- requires :description, type: String, desc: 'The trigger description'
+ requires :description, type: String, desc: "The trigger description"
end
- post ':id/triggers' do
+ post ":id/triggers" do
authenticate!
authorize! :admin_build, user_project
trigger = user_project.triggers.create(
- declared_params(include_missing: false).merge(owner: current_user))
+ declared_params(include_missing: false).merge(owner: current_user)
+ )
if trigger.valid?
present trigger, with: Entities::Trigger, current_user: current_user
@@ -91,19 +92,19 @@ module API
end
end
- desc 'Update a trigger' do
+ desc "Update a trigger" do
success Entities::Trigger
end
params do
- requires :trigger_id, type: Integer, desc: 'The trigger ID'
- optional :description, type: String, desc: 'The trigger description'
+ requires :trigger_id, type: Integer, desc: "The trigger ID"
+ optional :description, type: String, desc: "The trigger description"
end
- put ':id/triggers/:trigger_id' do
+ put ":id/triggers/:trigger_id" do
authenticate!
authorize! :admin_build, user_project
trigger = user_project.triggers.find(params.delete(:trigger_id))
- break not_found!('Trigger') unless trigger
+ break not_found!("Trigger") unless trigger
if trigger.update(declared_params(include_missing: false))
present trigger, with: Entities::Trigger, current_user: current_user
@@ -112,18 +113,18 @@ module API
end
end
- desc 'Take ownership of trigger' do
+ desc "Take ownership of trigger" do
success Entities::Trigger
end
params do
- requires :trigger_id, type: Integer, desc: 'The trigger ID'
+ requires :trigger_id, type: Integer, desc: "The trigger ID"
end
- post ':id/triggers/:trigger_id/take_ownership' do
+ post ":id/triggers/:trigger_id/take_ownership" do
authenticate!
authorize! :admin_build, user_project
trigger = user_project.triggers.find(params.delete(:trigger_id))
- break not_found!('Trigger') unless trigger
+ break not_found!("Trigger") unless trigger
if trigger.update(owner: current_user)
status :ok
@@ -133,18 +134,18 @@ module API
end
end
- desc 'Delete a trigger' do
+ desc "Delete a trigger" do
success Entities::Trigger
end
params do
- requires :trigger_id, type: Integer, desc: 'The trigger ID'
+ requires :trigger_id, type: Integer, desc: "The trigger ID"
end
- delete ':id/triggers/:trigger_id' do
+ delete ":id/triggers/:trigger_id" do
authenticate!
authorize! :admin_build, user_project
trigger = user_project.triggers.find(params.delete(:trigger_id))
- break not_found!('Trigger') unless trigger
+ break not_found!("Trigger") unless trigger
destroy_conditionally!(trigger)
end
diff --git a/lib/api/users.rb b/lib/api/users.rb
index 7d88880d412..4c0da1ca72f 100644
--- a/lib/api/users.rb
+++ b/lib/api/users.rb
@@ -6,9 +6,9 @@ module API
include APIGuard
include Helpers::CustomAttributes
- allow_access_with_scope :read_user, if: -> (request) { request.get? }
+ allow_access_with_scope :read_user, if: ->(request) { request.get? }
- resource :users, requirements: { uid: /[0-9]*/, id: /[0-9]*/ } do
+ resource :users, requirements: {uid: /[0-9]*/, id: /[0-9]*/} do
include CustomAttributesEndpoints
before do
@@ -19,7 +19,7 @@ module API
# rubocop: disable CodeReuse/ActiveRecord
def find_user_by_id(params)
id = params[:user_id] || params[:id]
- User.find_by(id: id) || not_found!('User')
+ User.find_by(id: id) || not_found!("User")
end
# rubocop: enable CodeReuse/ActiveRecord
@@ -34,47 +34,47 @@ module API
# rubocop: enable CodeReuse/ActiveRecord
params :optional_attributes do
- optional :skype, type: String, desc: 'The Skype username'
- optional :linkedin, type: String, desc: 'The LinkedIn username'
- optional :twitter, type: String, desc: 'The Twitter username'
- optional :website_url, type: String, desc: 'The website of the user'
- optional :organization, type: String, desc: 'The organization of the user'
- optional :projects_limit, type: Integer, desc: 'The number of projects a user can create'
- optional :extern_uid, type: String, desc: 'The external authentication provider UID'
- optional :provider, type: String, desc: 'The external provider'
- optional :bio, type: String, desc: 'The biography of the user'
- optional :location, type: String, desc: 'The location of the user'
- optional :public_email, type: String, desc: 'The public email of the user'
- optional :admin, type: Boolean, desc: 'Flag indicating the user is an administrator'
- optional :can_create_group, type: Boolean, desc: 'Flag indicating the user can create groups'
- optional :external, type: Boolean, desc: 'Flag indicating the user is an external user'
- optional :avatar, type: File, desc: 'Avatar image for user'
- optional :private_profile, type: Boolean, desc: 'Flag indicating the user has a private profile'
+ optional :skype, type: String, desc: "The Skype username"
+ optional :linkedin, type: String, desc: "The LinkedIn username"
+ optional :twitter, type: String, desc: "The Twitter username"
+ optional :website_url, type: String, desc: "The website of the user"
+ optional :organization, type: String, desc: "The organization of the user"
+ optional :projects_limit, type: Integer, desc: "The number of projects a user can create"
+ optional :extern_uid, type: String, desc: "The external authentication provider UID"
+ optional :provider, type: String, desc: "The external provider"
+ optional :bio, type: String, desc: "The biography of the user"
+ optional :location, type: String, desc: "The location of the user"
+ optional :public_email, type: String, desc: "The public email of the user"
+ optional :admin, type: Boolean, desc: "Flag indicating the user is an administrator"
+ optional :can_create_group, type: Boolean, desc: "Flag indicating the user can create groups"
+ optional :external, type: Boolean, desc: "Flag indicating the user is an external user"
+ optional :avatar, type: File, desc: "Avatar image for user"
+ optional :private_profile, type: Boolean, desc: "Flag indicating the user has a private profile"
all_or_none_of :extern_uid, :provider
end
params :sort_params do
optional :order_by, type: String, values: %w[id name username created_at updated_at],
- default: 'id', desc: 'Return users ordered by a field'
- optional :sort, type: String, values: %w[asc desc], default: 'desc',
- desc: 'Return users sorted in ascending and descending order'
+ default: "id", desc: "Return users ordered by a field"
+ optional :sort, type: String, values: %w[asc desc], default: "desc",
+ desc: "Return users sorted in ascending and descending order"
end
end
- desc 'Get the list of users' do
+ desc "Get the list of users" do
success Entities::UserBasic
end
params do
# CE
- optional :username, type: String, desc: 'Get a single user with a specific username'
- optional :extern_uid, type: String, desc: 'Get a single user with a specific external authentication provider UID'
- optional :provider, type: String, desc: 'The external provider'
- optional :search, type: String, desc: 'Search for a username'
- optional :active, type: Boolean, default: false, desc: 'Filters only active users'
- optional :external, type: Boolean, default: false, desc: 'Filters only external users'
- optional :blocked, type: Boolean, default: false, desc: 'Filters only blocked users'
- optional :created_after, type: DateTime, desc: 'Return users created after the specified time'
- optional :created_before, type: DateTime, desc: 'Return users created before the specified time'
+ optional :username, type: String, desc: "Get a single user with a specific username"
+ optional :extern_uid, type: String, desc: "Get a single user with a specific external authentication provider UID"
+ optional :provider, type: String, desc: "The external provider"
+ optional :search, type: String, desc: "Search for a username"
+ optional :active, type: Boolean, default: false, desc: "Filters only active users"
+ optional :external, type: Boolean, default: false, desc: "Filters only external users"
+ optional :blocked, type: Boolean, default: false, desc: "Filters only blocked users"
+ optional :created_after, type: DateTime, desc: "Return users created after the specified time"
+ optional :created_before, type: DateTime, desc: "Return users created before the specified time"
all_or_none_of :extern_uid, :provider
use :sort_params
@@ -105,26 +105,26 @@ module API
entity = current_user&.admin? ? Entities::UserWithAdmin : Entities::UserBasic
users = users.preload(:identities, :u2f_registrations) if entity == Entities::UserWithAdmin
- users, options = with_custom_attributes(users, { with: entity, current_user: current_user })
+ users, options = with_custom_attributes(users, {with: entity, current_user: current_user})
present paginate(users), options
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get a single user' do
+ desc "Get a single user" do
success Entities::User
end
params do
- requires :id, type: Integer, desc: 'The ID of the user'
+ requires :id, type: Integer, desc: "The ID of the user"
use :with_custom_attributes
end
# rubocop: disable CodeReuse/ActiveRecord
get ":id" do
user = User.find_by(id: params[:id])
- not_found!('User') unless user && can?(current_user, :read_user, user)
+ not_found!("User") unless user && can?(current_user, :read_user, user)
- opts = { with: current_user&.admin? ? Entities::UserWithAdmin : Entities::User, current_user: current_user }
+ opts = {with: current_user&.admin? ? Entities::UserWithAdmin : Entities::User, current_user: current_user}
user, opts = with_custom_attributes(user, opts)
present user, opts
@@ -133,26 +133,26 @@ module API
desc "Get the status of a user"
params do
- requires :user_id, type: String, desc: 'The ID or username of the user'
+ requires :user_id, type: String, desc: "The ID or username of the user"
end
get ":user_id/status", requirements: API::USER_REQUIREMENTS do
user = find_user(params[:user_id])
- not_found!('User') unless user && can?(current_user, :read_user, user)
+ not_found!("User") unless user && can?(current_user, :read_user, user)
present user.status || {}, with: Entities::UserStatus
end
- desc 'Create a user. Available only for admins.' do
+ desc "Create a user. Available only for admins." do
success Entities::UserPublic
end
params do
- requires :email, type: String, desc: 'The email of the user'
- optional :password, type: String, desc: 'The password of the new user'
- optional :reset_password, type: Boolean, desc: 'Flag indicating the user will be sent a password reset token'
- optional :skip_confirmation, type: Boolean, desc: 'Flag indicating the account is confirmed'
+ requires :email, type: String, desc: "The email of the user"
+ optional :password, type: String, desc: "The password of the new user"
+ optional :reset_password, type: Boolean, desc: "Flag indicating the user will be sent a password reset token"
+ optional :skip_confirmation, type: Boolean, desc: "Flag indicating the account is confirmed"
at_least_one_of :password, :reset_password
- requires :name, type: String, desc: 'The name of the user'
- requires :username, type: String, desc: 'The username of the user'
+ requires :name, type: String, desc: "The name of the user"
+ requires :username, type: String, desc: "The username of the user"
use :optional_attributes
end
post do
@@ -164,11 +164,11 @@ module API
if user.persisted?
present user, with: Entities::UserPublic, current_user: current_user
else
- conflict!('Email has already been taken') if User
+ conflict!("Email has already been taken") if User
.by_any_email(user.email.downcase)
.any?
- conflict!('Username has already been taken') if User
+ conflict!("Username has already been taken") if User
.by_username(user.username)
.any?
@@ -176,16 +176,16 @@ module API
end
end
- desc 'Update a user. Available only for admins.' do
+ desc "Update a user. Available only for admins." do
success Entities::UserPublic
end
params do
- requires :id, type: Integer, desc: 'The ID of the user'
- optional :email, type: String, desc: 'The email of the user'
- optional :password, type: String, desc: 'The password of the new user'
- optional :skip_reconfirmation, type: Boolean, desc: 'Flag indicating the account skips the confirmation by email'
- optional :name, type: String, desc: 'The name of the user'
- optional :username, type: String, desc: 'The username of the user'
+ requires :id, type: Integer, desc: "The ID of the user"
+ optional :email, type: String, desc: "The email of the user"
+ optional :password, type: String, desc: "The password of the new user"
+ optional :skip_reconfirmation, type: Boolean, desc: "Flag indicating the account skips the confirmation by email"
+ optional :name, type: String, desc: "The name of the user"
+ optional :username, type: String, desc: "The username of the user"
use :optional_attributes
end
# rubocop: disable CodeReuse/ActiveRecord
@@ -193,15 +193,15 @@ module API
authenticated_as_admin!
user = User.find_by(id: params.delete(:id))
- not_found!('User') unless user
+ not_found!("User") unless user
- conflict!('Email has already been taken') if params[:email] &&
- User.by_any_email(params[:email].downcase)
- .where.not(id: user.id).count > 0
+ conflict!("Email has already been taken") if params[:email] &&
+ User.by_any_email(params[:email].downcase)
+ .where.not(id: user.id).count > 0
- conflict!('Username has already been taken') if params[:username] &&
- User.by_username(params[:username])
- .where.not(id: user.id).count > 0
+ conflict!("Username has already been taken") if params[:username] &&
+ User.by_username(params[:username])
+ .where.not(id: user.id).count > 0
user_params = declared_params(include_missing: false)
identity_attrs = user_params.slice(:provider, :extern_uid)
@@ -229,20 +229,20 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Add an SSH key to a specified user. Available only for admins.' do
+ desc "Add an SSH key to a specified user. Available only for admins." do
success Entities::SSHKey
end
params do
- requires :id, type: Integer, desc: 'The ID of the user'
- requires :key, type: String, desc: 'The new SSH key'
- requires :title, type: String, desc: 'The title of the new SSH key'
+ requires :id, type: Integer, desc: "The ID of the user"
+ requires :key, type: String, desc: "The new SSH key"
+ requires :title, type: String, desc: "The title of the new SSH key"
end
# rubocop: disable CodeReuse/ActiveRecord
post ":id/keys" do
authenticated_as_admin!
user = User.find_by(id: params.delete(:id))
- not_found!('User') unless user
+ not_found!("User") unless user
key = user.keys.new(declared_params(include_missing: false))
@@ -254,57 +254,57 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get the SSH keys of a specified user.' do
+ desc "Get the SSH keys of a specified user." do
success Entities::SSHKey
end
params do
- requires :id, type: Integer, desc: 'The ID of the user'
+ requires :id, type: Integer, desc: "The ID of the user"
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/keys' do
+ get ":id/keys" do
user = User.find_by(id: params[:id])
- not_found!('User') unless user && can?(current_user, :read_user, user)
+ not_found!("User") unless user && can?(current_user, :read_user, user)
present paginate(user.keys), with: Entities::SSHKey
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Delete an existing SSH key from a specified user. Available only for admins.' do
+ desc "Delete an existing SSH key from a specified user. Available only for admins." do
success Entities::SSHKey
end
params do
- requires :id, type: Integer, desc: 'The ID of the user'
- requires :key_id, type: Integer, desc: 'The ID of the SSH key'
+ requires :id, type: Integer, desc: "The ID of the user"
+ requires :key_id, type: Integer, desc: "The ID of the SSH key"
end
# rubocop: disable CodeReuse/ActiveRecord
- delete ':id/keys/:key_id' do
+ delete ":id/keys/:key_id" do
authenticated_as_admin!
user = User.find_by(id: params[:id])
- not_found!('User') unless user
+ not_found!("User") unless user
key = user.keys.find_by(id: params[:key_id])
- not_found!('Key') unless key
+ not_found!("Key") unless key
destroy_conditionally!(key)
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Add a GPG key to a specified user. Available only for admins.' do
- detail 'This feature was added in GitLab 10.0'
+ desc "Add a GPG key to a specified user. Available only for admins." do
+ detail "This feature was added in GitLab 10.0"
success Entities::GPGKey
end
params do
- requires :id, type: Integer, desc: 'The ID of the user'
- requires :key, type: String, desc: 'The new GPG key'
+ requires :id, type: Integer, desc: "The ID of the user"
+ requires :key, type: String, desc: "The new GPG key"
end
# rubocop: disable CodeReuse/ActiveRecord
- post ':id/gpg_keys' do
+ post ":id/gpg_keys" do
authenticated_as_admin!
user = User.find_by(id: params.delete(:id))
- not_found!('User') unless user
+ not_found!("User") unless user
key = user.gpg_keys.new(declared_params(include_missing: false))
@@ -316,83 +316,83 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get the GPG keys of a specified user. Available only for admins.' do
- detail 'This feature was added in GitLab 10.0'
+ desc "Get the GPG keys of a specified user. Available only for admins." do
+ detail "This feature was added in GitLab 10.0"
success Entities::GPGKey
end
params do
- requires :id, type: Integer, desc: 'The ID of the user'
+ requires :id, type: Integer, desc: "The ID of the user"
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/gpg_keys' do
+ get ":id/gpg_keys" do
authenticated_as_admin!
user = User.find_by(id: params[:id])
- not_found!('User') unless user
+ not_found!("User") unless user
present paginate(user.gpg_keys), with: Entities::GPGKey
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Delete an existing GPG key from a specified user. Available only for admins.' do
- detail 'This feature was added in GitLab 10.0'
+ desc "Delete an existing GPG key from a specified user. Available only for admins." do
+ detail "This feature was added in GitLab 10.0"
end
params do
- requires :id, type: Integer, desc: 'The ID of the user'
- requires :key_id, type: Integer, desc: 'The ID of the GPG key'
+ requires :id, type: Integer, desc: "The ID of the user"
+ requires :key_id, type: Integer, desc: "The ID of the GPG key"
end
# rubocop: disable CodeReuse/ActiveRecord
- delete ':id/gpg_keys/:key_id' do
+ delete ":id/gpg_keys/:key_id" do
authenticated_as_admin!
user = User.find_by(id: params[:id])
- not_found!('User') unless user
+ not_found!("User") unless user
key = user.gpg_keys.find_by(id: params[:key_id])
- not_found!('GPG Key') unless key
+ not_found!("GPG Key") unless key
status 204
key.destroy
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Revokes an existing GPG key from a specified user. Available only for admins.' do
- detail 'This feature was added in GitLab 10.0'
+ desc "Revokes an existing GPG key from a specified user. Available only for admins." do
+ detail "This feature was added in GitLab 10.0"
end
params do
- requires :id, type: Integer, desc: 'The ID of the user'
- requires :key_id, type: Integer, desc: 'The ID of the GPG key'
+ requires :id, type: Integer, desc: "The ID of the user"
+ requires :key_id, type: Integer, desc: "The ID of the GPG key"
end
# rubocop: disable CodeReuse/ActiveRecord
- post ':id/gpg_keys/:key_id/revoke' do
+ post ":id/gpg_keys/:key_id/revoke" do
authenticated_as_admin!
user = User.find_by(id: params[:id])
- not_found!('User') unless user
+ not_found!("User") unless user
key = user.gpg_keys.find_by(id: params[:key_id])
- not_found!('GPG Key') unless key
+ not_found!("GPG Key") unless key
key.revoke
status :accepted
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Add an email address to a specified user. Available only for admins.' do
+ desc "Add an email address to a specified user. Available only for admins." do
success Entities::Email
end
params do
- requires :id, type: Integer, desc: 'The ID of the user'
- requires :email, type: String, desc: 'The email of the user'
- optional :skip_confirmation, type: Boolean, desc: 'Skip confirmation of email and assume it is verified'
+ requires :id, type: Integer, desc: "The ID of the user"
+ requires :email, type: String, desc: "The email of the user"
+ optional :skip_confirmation, type: Boolean, desc: "Skip confirmation of email and assume it is verified"
end
# rubocop: disable CodeReuse/ActiveRecord
post ":id/emails" do
authenticated_as_admin!
user = User.find_by(id: params.delete(:id))
- not_found!('User') unless user
+ not_found!("User") unless user
email = Emails::CreateService.new(current_user, declared_params(include_missing: false).merge(user: user)).execute
@@ -404,38 +404,38 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get the emails addresses of a specified user. Available only for admins.' do
+ desc "Get the emails addresses of a specified user. Available only for admins." do
success Entities::Email
end
params do
- requires :id, type: Integer, desc: 'The ID of the user'
+ requires :id, type: Integer, desc: "The ID of the user"
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/emails' do
+ get ":id/emails" do
authenticated_as_admin!
user = User.find_by(id: params[:id])
- not_found!('User') unless user
+ not_found!("User") unless user
present paginate(user.emails), with: Entities::Email
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Delete an email address of a specified user. Available only for admins.' do
+ desc "Delete an email address of a specified user. Available only for admins." do
success Entities::Email
end
params do
- requires :id, type: Integer, desc: 'The ID of the user'
- requires :email_id, type: Integer, desc: 'The ID of the email'
+ requires :id, type: Integer, desc: "The ID of the user"
+ requires :email_id, type: Integer, desc: "The ID of the email"
end
# rubocop: disable CodeReuse/ActiveRecord
- delete ':id/emails/:email_id' do
+ delete ":id/emails/:email_id" do
authenticated_as_admin!
user = User.find_by(id: params[:id])
- not_found!('User') unless user
+ not_found!("User") unless user
email = user.emails.find_by(id: params[:email_id])
- not_found!('Email') unless email
+ not_found!("Email") unless email
destroy_conditionally!(email) do |email|
Emails::DestroyService.new(current_user, user: user).execute(email)
@@ -443,21 +443,21 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Delete a user. Available only for admins.' do
+ desc "Delete a user. Available only for admins." do
success Entities::Email
end
params do
- requires :id, type: Integer, desc: 'The ID of the user'
+ requires :id, type: Integer, desc: "The ID of the user"
optional :hard_delete, type: Boolean, desc: "Whether to remove a user's contributions"
end
# rubocop: disable CodeReuse/ActiveRecord
delete ":id" do
- Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42279')
+ Gitlab::QueryLimiting.whitelist("https://gitlab.com/gitlab-org/gitlab-ce/issues/42279")
authenticated_as_admin!
user = User.find_by(id: params[:id])
- not_found!('User') unless user
+ not_found!("User") unless user
destroy_conditionally!(user) do
user.delete_async(deleted_by: current_user, params: params)
@@ -465,36 +465,36 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Block a user. Available only for admins.'
+ desc "Block a user. Available only for admins."
params do
- requires :id, type: Integer, desc: 'The ID of the user'
+ requires :id, type: Integer, desc: "The ID of the user"
end
# rubocop: disable CodeReuse/ActiveRecord
- post ':id/block' do
+ post ":id/block" do
authenticated_as_admin!
user = User.find_by(id: params[:id])
- not_found!('User') unless user
+ not_found!("User") unless user
if !user.ldap_blocked?
user.block
else
- forbidden!('LDAP blocked users cannot be modified by the API')
+ forbidden!("LDAP blocked users cannot be modified by the API")
end
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Unblock a user. Available only for admins.'
+ desc "Unblock a user. Available only for admins."
params do
- requires :id, type: Integer, desc: 'The ID of the user'
+ requires :id, type: Integer, desc: "The ID of the user"
end
# rubocop: disable CodeReuse/ActiveRecord
- post ':id/unblock' do
+ post ":id/unblock" do
authenticated_as_admin!
user = User.find_by(id: params[:id])
- not_found!('User') unless user
+ not_found!("User") unless user
if user.ldap_blocked?
- forbidden!('LDAP blocked users cannot be unblocked by the API')
+ forbidden!("LDAP blocked users cannot be unblocked by the API")
else
user.activate
end
@@ -502,41 +502,41 @@ module API
# rubocop: enable CodeReuse/ActiveRecord
params do
- requires :user_id, type: Integer, desc: 'The ID of the user'
+ requires :user_id, type: Integer, desc: "The ID of the user"
end
- segment ':user_id' do
+ segment ":user_id" do
resource :impersonation_tokens do
helpers do
def finder(options = {})
user = find_user_by_id(params)
- PersonalAccessTokensFinder.new({ user: user, impersonation: true }.merge(options))
+ PersonalAccessTokensFinder.new({user: user, impersonation: true}.merge(options))
end
def find_impersonation_token
- finder.find_by_id(declared_params[:impersonation_token_id]) || not_found!('Impersonation Token')
+ finder.find_by_id(declared_params[:impersonation_token_id]) || not_found!("Impersonation Token")
end
end
before { authenticated_as_admin! }
- desc 'Retrieve impersonation tokens. Available only for admins.' do
- detail 'This feature was introduced in GitLab 9.0'
+ desc "Retrieve impersonation tokens. Available only for admins." do
+ detail "This feature was introduced in GitLab 9.0"
success Entities::ImpersonationToken
end
params do
use :pagination
- optional :state, type: String, default: 'all', values: %w[all active inactive], desc: 'Filters (all|active|inactive) impersonation_tokens'
+ optional :state, type: String, default: "all", values: %w[all active inactive], desc: "Filters (all|active|inactive) impersonation_tokens"
end
get { present paginate(finder(declared_params(include_missing: false)).execute), with: Entities::ImpersonationToken }
- desc 'Create a impersonation token. Available only for admins.' do
- detail 'This feature was introduced in GitLab 9.0'
+ desc "Create a impersonation token. Available only for admins." do
+ detail "This feature was introduced in GitLab 9.0"
success Entities::ImpersonationTokenWithToken
end
params do
- requires :name, type: String, desc: 'The name of the impersonation token'
- optional :expires_at, type: Date, desc: 'The expiration date in the format YEAR-MONTH-DAY of the impersonation token'
- optional :scopes, type: Array, desc: 'The array of scopes of the impersonation token'
+ requires :name, type: String, desc: "The name of the impersonation token"
+ optional :expires_at, type: Date, desc: "The expiration date in the format YEAR-MONTH-DAY of the impersonation token"
+ optional :scopes, type: Array, desc: "The array of scopes of the impersonation token"
end
post do
impersonation_token = finder.build(declared_params(include_missing: false))
@@ -548,24 +548,24 @@ module API
end
end
- desc 'Retrieve impersonation token. Available only for admins.' do
- detail 'This feature was introduced in GitLab 9.0'
+ desc "Retrieve impersonation token. Available only for admins." do
+ detail "This feature was introduced in GitLab 9.0"
success Entities::ImpersonationToken
end
params do
- requires :impersonation_token_id, type: Integer, desc: 'The ID of the impersonation token'
+ requires :impersonation_token_id, type: Integer, desc: "The ID of the impersonation token"
end
- get ':impersonation_token_id' do
+ get ":impersonation_token_id" do
present find_impersonation_token, with: Entities::ImpersonationToken
end
- desc 'Revoke a impersonation token. Available only for admins.' do
- detail 'This feature was introduced in GitLab 9.0'
+ desc "Revoke a impersonation token. Available only for admins." do
+ detail "This feature was introduced in GitLab 9.0"
end
params do
- requires :impersonation_token_id, type: Integer, desc: 'The ID of the impersonation token'
+ requires :impersonation_token_id, type: Integer, desc: "The ID of the impersonation token"
end
- delete ':impersonation_token_id' do
+ delete ":impersonation_token_id" do
token = find_impersonation_token
destroy_conditionally!(token) do
@@ -583,8 +583,8 @@ module API
# Enabling /user endpoint for the v3 version to allow oauth
# authentication through this endpoint.
- version %w(v3 v4), using: :path do
- desc 'Get the currently authenticated user' do
+ version %w[v3 v4], using: :path do
+ desc "Get the currently authenticated user" do
success Entities::UserPublic
end
get do
@@ -609,27 +609,27 @@ module API
present paginate(current_user.keys), with: Entities::SSHKey
end
- desc 'Get a single key owned by currently authenticated user' do
+ desc "Get a single key owned by currently authenticated user" do
success Entities::SSHKey
end
params do
- requires :key_id, type: Integer, desc: 'The ID of the SSH key'
+ requires :key_id, type: Integer, desc: "The ID of the SSH key"
end
# rubocop: disable CodeReuse/ActiveRecord
get "keys/:key_id" do
key = current_user.keys.find_by(id: params[:key_id])
- not_found!('Key') unless key
+ not_found!("Key") unless key
present key, with: Entities::SSHKey
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Add a new SSH key to the currently authenticated user' do
+ desc "Add a new SSH key to the currently authenticated user" do
success Entities::SSHKey
end
params do
- requires :key, type: String, desc: 'The new SSH key'
- requires :title, type: String, desc: 'The title of the new SSH key'
+ requires :key, type: String, desc: "The new SSH key"
+ requires :title, type: String, desc: "The title of the new SSH key"
end
post "keys" do
key = current_user.keys.new(declared_params)
@@ -641,56 +641,56 @@ module API
end
end
- desc 'Delete an SSH key from the currently authenticated user' do
+ desc "Delete an SSH key from the currently authenticated user" do
success Entities::SSHKey
end
params do
- requires :key_id, type: Integer, desc: 'The ID of the SSH key'
+ requires :key_id, type: Integer, desc: "The ID of the SSH key"
end
# rubocop: disable CodeReuse/ActiveRecord
delete "keys/:key_id" do
key = current_user.keys.find_by(id: params[:key_id])
- not_found!('Key') unless key
+ not_found!("Key") unless key
destroy_conditionally!(key)
end
# rubocop: enable CodeReuse/ActiveRecord
desc "Get the currently authenticated user's GPG keys" do
- detail 'This feature was added in GitLab 10.0'
+ detail "This feature was added in GitLab 10.0"
success Entities::GPGKey
end
params do
use :pagination
end
- get 'gpg_keys' do
+ get "gpg_keys" do
present paginate(current_user.gpg_keys), with: Entities::GPGKey
end
- desc 'Get a single GPG key owned by currently authenticated user' do
- detail 'This feature was added in GitLab 10.0'
+ desc "Get a single GPG key owned by currently authenticated user" do
+ detail "This feature was added in GitLab 10.0"
success Entities::GPGKey
end
params do
- requires :key_id, type: Integer, desc: 'The ID of the GPG key'
+ requires :key_id, type: Integer, desc: "The ID of the GPG key"
end
# rubocop: disable CodeReuse/ActiveRecord
- get 'gpg_keys/:key_id' do
+ get "gpg_keys/:key_id" do
key = current_user.gpg_keys.find_by(id: params[:key_id])
- not_found!('GPG Key') unless key
+ not_found!("GPG Key") unless key
present key, with: Entities::GPGKey
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Add a new GPG key to the currently authenticated user' do
- detail 'This feature was added in GitLab 10.0'
+ desc "Add a new GPG key to the currently authenticated user" do
+ detail "This feature was added in GitLab 10.0"
success Entities::GPGKey
end
params do
- requires :key, type: String, desc: 'The new GPG key'
+ requires :key, type: String, desc: "The new GPG key"
end
- post 'gpg_keys' do
+ post "gpg_keys" do
key = current_user.gpg_keys.new(declared_params)
if key.save
@@ -700,32 +700,32 @@ module API
end
end
- desc 'Revoke a GPG key owned by currently authenticated user' do
- detail 'This feature was added in GitLab 10.0'
+ desc "Revoke a GPG key owned by currently authenticated user" do
+ detail "This feature was added in GitLab 10.0"
end
params do
- requires :key_id, type: Integer, desc: 'The ID of the GPG key'
+ requires :key_id, type: Integer, desc: "The ID of the GPG key"
end
# rubocop: disable CodeReuse/ActiveRecord
- post 'gpg_keys/:key_id/revoke' do
+ post "gpg_keys/:key_id/revoke" do
key = current_user.gpg_keys.find_by(id: params[:key_id])
- not_found!('GPG Key') unless key
+ not_found!("GPG Key") unless key
key.revoke
status :accepted
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Delete a GPG key from the currently authenticated user' do
- detail 'This feature was added in GitLab 10.0'
+ desc "Delete a GPG key from the currently authenticated user" do
+ detail "This feature was added in GitLab 10.0"
end
params do
- requires :key_id, type: Integer, desc: 'The ID of the SSH key'
+ requires :key_id, type: Integer, desc: "The ID of the SSH key"
end
# rubocop: disable CodeReuse/ActiveRecord
- delete 'gpg_keys/:key_id' do
+ delete "gpg_keys/:key_id" do
key = current_user.gpg_keys.find_by(id: params[:key_id])
- not_found!('GPG Key') unless key
+ not_found!("GPG Key") unless key
status 204
key.destroy
@@ -742,26 +742,26 @@ module API
present paginate(current_user.emails), with: Entities::Email
end
- desc 'Get a single email address owned by the currently authenticated user' do
+ desc "Get a single email address owned by the currently authenticated user" do
success Entities::Email
end
params do
- requires :email_id, type: Integer, desc: 'The ID of the email'
+ requires :email_id, type: Integer, desc: "The ID of the email"
end
# rubocop: disable CodeReuse/ActiveRecord
get "emails/:email_id" do
email = current_user.emails.find_by(id: params[:email_id])
- not_found!('Email') unless email
+ not_found!("Email") unless email
present email, with: Entities::Email
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Add new email address to the currently authenticated user' do
+ desc "Add new email address to the currently authenticated user" do
success Entities::Email
end
params do
- requires :email, type: String, desc: 'The new email'
+ requires :email, type: String, desc: "The new email"
end
post "emails" do
email = Emails::CreateService.new(current_user, declared_params.merge(user: current_user)).execute
@@ -773,14 +773,14 @@ module API
end
end
- desc 'Delete an email address from the currently authenticated user'
+ desc "Delete an email address from the currently authenticated user"
params do
- requires :email_id, type: Integer, desc: 'The ID of the email'
+ requires :email_id, type: Integer, desc: "The ID of the email"
end
# rubocop: disable CodeReuse/ActiveRecord
delete "emails/:email_id" do
email = current_user.emails.find_by(id: params[:email_id])
- not_found!('Email') unless email
+ not_found!("Email") unless email
destroy_conditionally!(email) do |email|
Emails::DestroyService.new(current_user, user: current_user).execute(email)
@@ -788,9 +788,9 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Get a list of user activities'
+ desc "Get a list of user activities"
params do
- optional :from, type: DateTime, default: 6.months.ago, desc: 'Date string in the format YEAR-MONTH-DAY'
+ optional :from, type: DateTime, default: 6.months.ago, desc: "Date string in the format YEAR-MONTH-DAY"
use :pagination
end
# rubocop: disable CodeReuse/ActiveRecord
@@ -805,7 +805,7 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Set the status of the current user' do
+ desc "Set the status of the current user" do
success Entities::UserStatus
end
params do
@@ -822,10 +822,10 @@ module API
end
end
- desc 'get the status of the current user' do
+ desc "get the status of the current user" do
success Entities::UserStatus
end
- get 'status' do
+ get "status" do
present current_user.status || {}, with: Entities::UserStatus
end
end
diff --git a/lib/api/variables.rb b/lib/api/variables.rb
index 148deb86c4c..2972125085a 100644
--- a/lib/api/variables.rb
+++ b/lib/api/variables.rb
@@ -8,47 +8,47 @@ module API
before { authorize! :admin_build, user_project }
params do
- requires :id, type: String, desc: 'The ID of a project'
+ requires :id, type: String, desc: "The ID of a project"
end
resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
- desc 'Get project variables' do
+ desc "Get project variables" do
success Entities::Variable
end
params do
use :pagination
end
- get ':id/variables' do
+ get ":id/variables" do
variables = user_project.variables
present paginate(variables), with: Entities::Variable
end
- desc 'Get a specific variable from a project' do
+ desc "Get a specific variable from a project" do
success Entities::Variable
end
params do
- requires :key, type: String, desc: 'The key of the variable'
+ requires :key, type: String, desc: "The key of the variable"
end
# rubocop: disable CodeReuse/ActiveRecord
- get ':id/variables/:key' do
+ get ":id/variables/:key" do
key = params[:key]
variable = user_project.variables.find_by(key: key)
- break not_found!('Variable') unless variable
+ break not_found!("Variable") unless variable
present variable, with: Entities::Variable
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Create a new variable in a project' do
+ desc "Create a new variable in a project" do
success Entities::Variable
end
params do
- requires :key, type: String, desc: 'The key of the variable'
- requires :value, type: String, desc: 'The value of the variable'
- optional :protected, type: String, desc: 'Whether the variable is protected'
+ requires :key, type: String, desc: "The key of the variable"
+ requires :value, type: String, desc: "The value of the variable"
+ optional :protected, type: String, desc: "Whether the variable is protected"
end
- post ':id/variables' do
+ post ":id/variables" do
variable_params = declared_params(include_missing: false)
variable = user_project.variables.create(variable_params)
@@ -60,19 +60,19 @@ module API
end
end
- desc 'Update an existing variable from a project' do
+ desc "Update an existing variable from a project" do
success Entities::Variable
end
params do
- optional :key, type: String, desc: 'The key of the variable'
- optional :value, type: String, desc: 'The value of the variable'
- optional :protected, type: String, desc: 'Whether the variable is protected'
+ optional :key, type: String, desc: "The key of the variable"
+ optional :value, type: String, desc: "The value of the variable"
+ optional :protected, type: String, desc: "Whether the variable is protected"
end
# rubocop: disable CodeReuse/ActiveRecord
- put ':id/variables/:key' do
+ put ":id/variables/:key" do
variable = user_project.variables.find_by(key: params[:key])
- break not_found!('Variable') unless variable
+ break not_found!("Variable") unless variable
variable_params = declared_params(include_missing: false).except(:key)
@@ -84,16 +84,16 @@ module API
end
# rubocop: enable CodeReuse/ActiveRecord
- desc 'Delete an existing variable from a project' do
+ desc "Delete an existing variable from a project" do
success Entities::Variable
end
params do
- requires :key, type: String, desc: 'The key of the variable'
+ requires :key, type: String, desc: "The key of the variable"
end
# rubocop: disable CodeReuse/ActiveRecord
- delete ':id/variables/:key' do
+ delete ":id/variables/:key" do
variable = user_project.variables.find_by(key: params[:key])
- not_found!('Variable') unless variable
+ not_found!("Variable") unless variable
# Variables don't have any timestamp. Therfore, destroy unconditionally.
status 204
diff --git a/lib/api/version.rb b/lib/api/version.rb
index 74cd857f447..e770153caf7 100644
--- a/lib/api/version.rb
+++ b/lib/api/version.rb
@@ -4,11 +4,11 @@ module API
class Version < Grape::API
before { authenticate! }
- desc 'Get the version information of the GitLab instance.' do
- detail 'This feature was introduced in GitLab 8.13.'
+ desc "Get the version information of the GitLab instance." do
+ detail "This feature was introduced in GitLab 8.13."
end
- get '/version' do
- { version: Gitlab::VERSION, revision: Gitlab.revision }
+ get "/version" do
+ {version: Gitlab::VERSION, revision: Gitlab.revision}
end
end
end
diff --git a/lib/api/wikis.rb b/lib/api/wikis.rb
index 994074ddc67..9dd7916c480 100644
--- a/lib/api/wikis.rb
+++ b/lib/api/wikis.rb
@@ -7,7 +7,7 @@ module API
{
file_name: attrs[:file][:filename],
file_content: attrs[:file][:tempfile].read,
- branch_name: attrs[:branch]
+ branch_name: attrs[:branch],
}
end
@@ -15,48 +15,48 @@ module API
optional :format,
type: String,
values: ProjectWiki::MARKUPS.values.map(&:to_s),
- default: 'markdown',
- desc: 'Format of a wiki page. Available formats are markdown, rdoc, and asciidoc'
+ default: "markdown",
+ desc: "Format of a wiki page. Available formats are markdown, rdoc, and asciidoc"
end
end
WIKI_ENDPOINT_REQUIREMENTS = API::NAMESPACE_OR_PROJECT_REQUIREMENTS.merge(slug: API::NO_SLASH_URL_PART_REGEX)
resource :projects, requirements: WIKI_ENDPOINT_REQUIREMENTS do
- desc 'Get a list of wiki pages' do
+ desc "Get a list of wiki pages" do
success Entities::WikiPageBasic
end
params do
optional :with_content, type: Boolean, default: false, desc: "Include pages' content"
end
- get ':id/wikis' do
+ get ":id/wikis" do
authorize! :read_wiki, user_project
entity = params[:with_content] ? Entities::WikiPage : Entities::WikiPageBasic
present user_project.wiki.pages, with: entity
end
- desc 'Get a wiki page' do
+ desc "Get a wiki page" do
success Entities::WikiPage
end
params do
- requires :slug, type: String, desc: 'The slug of a wiki page'
+ requires :slug, type: String, desc: "The slug of a wiki page"
end
- get ':id/wikis/:slug' do
+ get ":id/wikis/:slug" do
authorize! :read_wiki, user_project
present wiki_page, with: Entities::WikiPage
end
- desc 'Create a wiki page' do
+ desc "Create a wiki page" do
success Entities::WikiPage
end
params do
- requires :title, type: String, desc: 'Title of a wiki page'
- requires :content, type: String, desc: 'Content of a wiki page'
+ requires :title, type: String, desc: "Title of a wiki page"
+ requires :content, type: String, desc: "Content of a wiki page"
use :common_wiki_page_params
end
- post ':id/wikis' do
+ post ":id/wikis" do
authorize! :create_wiki, user_project
page = WikiPages::CreateService.new(user_project, current_user, params).execute
@@ -68,16 +68,16 @@ module API
end
end
- desc 'Update a wiki page' do
+ desc "Update a wiki page" do
success Entities::WikiPage
end
params do
- optional :title, type: String, desc: 'Title of a wiki page'
- optional :content, type: String, desc: 'Content of a wiki page'
+ optional :title, type: String, desc: "Title of a wiki page"
+ optional :content, type: String, desc: "Content of a wiki page"
use :common_wiki_page_params
at_least_one_of :content, :title, :format
end
- put ':id/wikis/:slug' do
+ put ":id/wikis/:slug" do
authorize! :create_wiki, user_project
page = WikiPages::UpdateService.new(user_project, current_user, params).execute(wiki_page)
@@ -89,31 +89,31 @@ module API
end
end
- desc 'Delete a wiki page'
+ desc "Delete a wiki page"
params do
- requires :slug, type: String, desc: 'The slug of a wiki page'
+ requires :slug, type: String, desc: "The slug of a wiki page"
end
- delete ':id/wikis/:slug' do
+ delete ":id/wikis/:slug" do
authorize! :admin_wiki, user_project
status 204
WikiPages::DestroyService.new(user_project, current_user).execute(wiki_page)
end
- desc 'Upload an attachment to the wiki repository' do
- detail 'This feature was introduced in GitLab 11.3.'
+ desc "Upload an attachment to the wiki repository" do
+ detail "This feature was introduced in GitLab 11.3."
success Entities::WikiAttachment
end
params do
- requires :file, type: ::API::Validations::Types::SafeFile, desc: 'The attachment file to be uploaded'
- optional :branch, type: String, desc: 'The name of the branch'
+ requires :file, type: ::API::Validations::Types::SafeFile, desc: "The attachment file to be uploaded"
+ optional :branch, type: String, desc: "The name of the branch"
end
post ":id/wikis/attachments" do
authorize! :create_wiki, user_project
result = ::Wikis::CreateAttachmentService.new(user_project,
- current_user,
- commit_params(declared_params(include_missing: false))).execute
+ current_user,
+ commit_params(declared_params(include_missing: false))).execute
if result[:status] == :success
status(201)
diff --git a/lib/backup/artifacts.rb b/lib/backup/artifacts.rb
index 33658ae225f..fbc058b54bc 100644
--- a/lib/backup/artifacts.rb
+++ b/lib/backup/artifacts.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'backup/files'
+require "backup/files"
module Backup
class Artifacts < Files
@@ -9,7 +9,7 @@ module Backup
def initialize(progress)
@progress = progress
- super('artifacts', JobArtifactUploader.root)
+ super("artifacts", JobArtifactUploader.root)
end
end
end
diff --git a/lib/backup/builds.rb b/lib/backup/builds.rb
index 5e795a449de..766a35972f5 100644
--- a/lib/backup/builds.rb
+++ b/lib/backup/builds.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'backup/files'
+require "backup/files"
module Backup
class Builds < Files
@@ -9,7 +9,7 @@ module Backup
def initialize(progress)
@progress = progress
- super('builds', Settings.gitlab_ci.builds_path)
+ super("builds", Settings.gitlab_ci.builds_path)
end
end
end
diff --git a/lib/backup/database.rb b/lib/backup/database.rb
index e6bf3d1856f..b35fe4142eb 100644
--- a/lib/backup/database.rb
+++ b/lib/backup/database.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'yaml'
+require "yaml"
module Backup
class Database
@@ -9,26 +9,26 @@ module Backup
def initialize(progress)
@progress = progress
- @config = YAML.load_file(File.join(Rails.root, 'config', 'database.yml'))[Rails.env]
- @db_file_name = File.join(Gitlab.config.backup.path, 'db', 'database.sql.gz')
+ @config = YAML.load_file(File.join(Rails.root, "config", "database.yml"))[Rails.env]
+ @db_file_name = File.join(Gitlab.config.backup.path, "db", "database.sql.gz")
end
def dump
FileUtils.mkdir_p(File.dirname(db_file_name))
FileUtils.rm_f(db_file_name)
compress_rd, compress_wr = IO.pipe
- compress_pid = spawn(*%w(gzip -1 -c), in: compress_rd, out: [db_file_name, 'w', 0600])
+ compress_pid = spawn("gzip", "-1", "-c", in: compress_rd, out: [db_file_name, "w", 0o600])
compress_rd.close
dump_pid =
case config["adapter"]
when /^mysql/ then
- progress.print "Dumping MySQL database #{config['database']} ... "
+ progress.print "Dumping MySQL database #{config["database"]} ... "
# Workaround warnings from MySQL 5.6 about passwords on cmd line
- ENV['MYSQL_PWD'] = config["password"].to_s if config["password"]
- spawn('mysqldump', *mysql_args, config['database'], out: compress_wr)
+ ENV["MYSQL_PWD"] = config["password"].to_s if config["password"]
+ spawn("mysqldump", *mysql_args, config["database"], out: compress_wr)
when "postgresql" then
- progress.print "Dumping PostgreSQL database #{config['database']} ... "
+ progress.print "Dumping PostgreSQL database #{config["database"]} ... "
pg_env
pgsql_args = ["--clean"] # Pass '--clean' to include 'DROP TABLE' statements in the DB dump.
if Gitlab.config.backup.pg_schema
@@ -36,88 +36,88 @@ module Backup
pgsql_args << Gitlab.config.backup.pg_schema
end
- spawn('pg_dump', *pgsql_args, config['database'], out: compress_wr)
+ spawn("pg_dump", *pgsql_args, config["database"], out: compress_wr)
end
compress_wr.close
- success = [compress_pid, dump_pid].all? do |pid|
+ success = [compress_pid, dump_pid].all? { |pid|
Process.waitpid(pid)
$?.success?
- end
+ }
report_success(success)
- raise Backup::Error, 'Backup failed' unless success
+ raise Backup::Error, "Backup failed" unless success
end
def restore
decompress_rd, decompress_wr = IO.pipe
- decompress_pid = spawn(*%w(gzip -cd), out: decompress_wr, in: db_file_name)
+ decompress_pid = spawn("gzip", "-cd", out: decompress_wr, in: db_file_name)
decompress_wr.close
restore_pid =
case config["adapter"]
when /^mysql/ then
- progress.print "Restoring MySQL database #{config['database']} ... "
+ progress.print "Restoring MySQL database #{config["database"]} ... "
# Workaround warnings from MySQL 5.6 about passwords on cmd line
- ENV['MYSQL_PWD'] = config["password"].to_s if config["password"]
- spawn('mysql', *mysql_args, config['database'], in: decompress_rd)
+ ENV["MYSQL_PWD"] = config["password"].to_s if config["password"]
+ spawn("mysql", *mysql_args, config["database"], in: decompress_rd)
when "postgresql" then
- progress.print "Restoring PostgreSQL database #{config['database']} ... "
+ progress.print "Restoring PostgreSQL database #{config["database"]} ... "
pg_env
- spawn('psql', config['database'], in: decompress_rd)
+ spawn("psql", config["database"], in: decompress_rd)
end
decompress_rd.close
- success = [decompress_pid, restore_pid].all? do |pid|
+ success = [decompress_pid, restore_pid].all? { |pid|
Process.waitpid(pid)
$?.success?
- end
+ }
report_success(success)
- abort Backup::Error, 'Restore failed' unless success
+ abort Backup::Error, "Restore failed" unless success
end
protected
def mysql_args
args = {
- 'host' => '--host',
- 'port' => '--port',
- 'socket' => '--socket',
- 'username' => '--user',
- 'encoding' => '--default-character-set',
+ "host" => "--host",
+ "port" => "--port",
+ "socket" => "--socket",
+ "username" => "--user",
+ "encoding" => "--default-character-set",
# SSL
- 'sslkey' => '--ssl-key',
- 'sslcert' => '--ssl-cert',
- 'sslca' => '--ssl-ca',
- 'sslcapath' => '--ssl-capath',
- 'sslcipher' => '--ssl-cipher'
+ "sslkey" => "--ssl-key",
+ "sslcert" => "--ssl-cert",
+ "sslca" => "--ssl-ca",
+ "sslcapath" => "--ssl-capath",
+ "sslcipher" => "--ssl-cipher",
}
args.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact
end
def pg_env
args = {
- 'username' => 'PGUSER',
- 'host' => 'PGHOST',
- 'port' => 'PGPORT',
- 'password' => 'PGPASSWORD',
+ "username" => "PGUSER",
+ "host" => "PGHOST",
+ "port" => "PGPORT",
+ "password" => "PGPASSWORD",
# SSL
- 'sslmode' => 'PGSSLMODE',
- 'sslkey' => 'PGSSLKEY',
- 'sslcert' => 'PGSSLCERT',
- 'sslrootcert' => 'PGSSLROOTCERT',
- 'sslcrl' => 'PGSSLCRL',
- 'sslcompression' => 'PGSSLCOMPRESSION'
+ "sslmode" => "PGSSLMODE",
+ "sslkey" => "PGSSLKEY",
+ "sslcert" => "PGSSLCERT",
+ "sslrootcert" => "PGSSLROOTCERT",
+ "sslcrl" => "PGSSLCRL",
+ "sslcompression" => "PGSSLCOMPRESSION",
}
args.each { |opt, arg| ENV[arg] = config[opt].to_s if config[opt] }
end
def report_success(success)
if success
- progress.puts '[DONE]'.color(:green)
+ progress.puts "[DONE]".color(:green)
else
- progress.puts '[FAILED]'.color(:red)
+ progress.puts "[FAILED]".color(:red)
end
end
end
diff --git a/lib/backup/files.rb b/lib/backup/files.rb
index 2bac84846c5..03b41c17d78 100644
--- a/lib/backup/files.rb
+++ b/lib/backup/files.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'open3'
-require_relative 'helper'
+require "open3"
+require_relative "helper"
module Backup
class Files
@@ -12,9 +12,9 @@ module Backup
def initialize(name, app_files_dir)
@name = name
@app_files_dir = File.realpath(app_files_dir)
- @files_parent_dir = File.realpath(File.join(@app_files_dir, '..'))
- @backup_files_dir = File.join(Gitlab.config.backup.path, File.basename(@app_files_dir) )
- @backup_tarball = File.join(Gitlab.config.backup.path, name + '.tar.gz')
+ @files_parent_dir = File.realpath(File.join(@app_files_dir, ".."))
+ @backup_files_dir = File.join(Gitlab.config.backup.path, File.basename(@app_files_dir))
+ @backup_tarball = File.join(Gitlab.config.backup.path, name + ".tar.gz")
end
# Copy files from public/files to backup/files
@@ -22,34 +22,34 @@ module Backup
FileUtils.mkdir_p(Gitlab.config.backup.path)
FileUtils.rm_f(backup_tarball)
- if ENV['STRATEGY'] == 'copy'
- cmd = %W(rsync -a --exclude=lost+found #{app_files_dir} #{Gitlab.config.backup.path})
+ if ENV["STRATEGY"] == "copy"
+ cmd = %W[rsync -a --exclude=lost+found #{app_files_dir} #{Gitlab.config.backup.path}]
output, status = Gitlab::Popen.popen(cmd)
unless status.zero?
puts output
- raise Backup::Error, 'Backup failed'
+ raise Backup::Error, "Backup failed"
end
- run_pipeline!([%W(#{tar} --exclude=lost+found -C #{@backup_files_dir} -cf - .), %w(gzip -c -1)], out: [backup_tarball, 'w', 0600])
+ run_pipeline!([%W[#{tar} --exclude=lost+found -C #{@backup_files_dir} -cf - .], %w[gzip -c -1]], out: [backup_tarball, "w", 0o600])
FileUtils.rm_rf(@backup_files_dir)
else
- run_pipeline!([%W(#{tar} --exclude=lost+found -C #{app_files_dir} -cf - .), %w(gzip -c -1)], out: [backup_tarball, 'w', 0600])
+ run_pipeline!([%W[#{tar} --exclude=lost+found -C #{app_files_dir} -cf - .], %w[gzip -c -1]], out: [backup_tarball, "w", 0o600])
end
end
def restore
backup_existing_files_dir
- run_pipeline!([%w(gzip -cd), %W(#{tar} --unlink-first --recursive-unlink -C #{app_files_dir} -xf -)], in: backup_tarball)
+ run_pipeline!([%w[gzip -cd], %W[#{tar} --unlink-first --recursive-unlink -C #{app_files_dir} -xf -]], in: backup_tarball)
end
def tar
- if system(*%w[gtar --version], out: '/dev/null')
+ if system("gtar", "--version", out: "/dev/null")
# It looks like we can get GNU tar by running 'gtar'
- 'gtar'
+ "gtar"
else
- 'tar'
+ "tar"
end
end
@@ -58,7 +58,7 @@ module Backup
if File.exist?(app_files_dir)
# Move all files in the existing repos directory except . and .. to
# repositories.old.<timestamp> directory
- FileUtils.mkdir_p(timestamped_files_path, mode: 0700)
+ FileUtils.mkdir_p(timestamped_files_path, mode: 0o700)
files = Dir.glob(File.join(app_files_dir, "*"), File::FNM_DOTMATCH) - [File.join(app_files_dir, "."), File.join(app_files_dir, "..")]
begin
FileUtils.mv(files, timestamped_files_path)
@@ -78,7 +78,7 @@ module Backup
return if status.compact.all?(&:success?)
regex = /^g?tar: \.: Cannot mkdir: No such file or directory$/
- raise Backup::Error, 'Backup failed' unless err_r.read =~ regex
+ raise Backup::Error, "Backup failed" unless err_r.read =~ regex
end
end
end
diff --git a/lib/backup/helper.rb b/lib/backup/helper.rb
index 22f00aef569..fd3fe1b47f9 100644
--- a/lib/backup/helper.rb
+++ b/lib/backup/helper.rb
@@ -4,13 +4,12 @@ module Backup
module Helper
def access_denied_error(path)
message = <<~EOS
-
- ### NOTICE ###
- As part of restore, the task tried to move existing content from #{path}.
- However, it seems that directory contains files/folders that are not owned
- by the user #{Gitlab.config.gitlab.user}. To proceed, please move the files
- or folders inside #{path} to a secure location so that #{path} is empty and
- run restore task again.
+ ### NOTICE ###
+ As part of restore, the task tried to move existing content from #{path}.
+ However, it seems that directory contains files/folders that are not owned
+ by the user #{Gitlab.config.gitlab.user}. To proceed, please move the files
+ or folders inside #{path} to a secure location so that #{path} is empty and
+ run restore task again.
EOS
raise message
@@ -18,13 +17,11 @@ module Backup
def resource_busy_error(path)
message = <<~EOS
-
- ### NOTICE ###
- As part of restore, the task tried to rename `#{path}` before restoring.
- This could not be completed, perhaps `#{path}` is a mountpoint?
-
- To complete the restore, please move the contents of `#{path}` to a
- different location and run the restore task again.
+ ### NOTICE ###
+ As part of restore, the task tried to rename `#{path}` before restoring.
+ This could not be completed, perhaps `#{path}` is a mountpoint?
+ To complete the restore, please move the contents of `#{path}` to a
+ different location and run the restore task again.
EOS
raise message
diff --git a/lib/backup/lfs.rb b/lib/backup/lfs.rb
index 0dfe56e214f..689e8093b58 100644
--- a/lib/backup/lfs.rb
+++ b/lib/backup/lfs.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'backup/files'
+require "backup/files"
module Backup
class Lfs < Files
@@ -9,7 +9,7 @@ module Backup
def initialize(progress)
@progress = progress
- super('lfs', Settings.lfs.storage_path)
+ super("lfs", Settings.lfs.storage_path)
end
end
end
diff --git a/lib/backup/manager.rb b/lib/backup/manager.rb
index 06b0338b1ed..52fbbbda382 100644
--- a/lib/backup/manager.rb
+++ b/lib/backup/manager.rb
@@ -4,7 +4,7 @@ module Backup
class Manager
ARCHIVES_TO_BACKUP = %w[uploads builds artifacts pages lfs registry].freeze
FOLDERS_TO_BACKUP = %w[repositories db].freeze
- FILE_NAME_SUFFIX = '_gitlab_backup.tar'.freeze
+ FILE_NAME_SUFFIX = "_gitlab_backup.tar"
attr_reader :progress
@@ -18,18 +18,18 @@ module Backup
Dir.chdir(backup_path) do
File.open("#{backup_path}/backup_information.yml", "w+") do |file|
- file << backup_information.to_yaml.gsub(/^---\n/, '')
+ file << backup_information.to_yaml.gsub(/^---\n/, "")
end
# create archive
progress.print "Creating backup archive: #{tar_file} ... "
# Set file permissions on open to prevent chmod races.
- tar_system_options = { out: [tar_file, 'w', Gitlab.config.backup.archive_permissions] }
- if Kernel.system('tar', '-cf', '-', *backup_contents, tar_system_options)
+ tar_system_options = {out: [tar_file, "w", Gitlab.config.backup.archive_permissions]}
+ if Kernel.system("tar", "-cf", "-", *backup_contents, tar_system_options)
progress.puts "done".color(:green)
else
puts "creating archive #{tar_file} failed".color(:red)
- raise Backup::Error, 'Backup failed'
+ raise Backup::Error, "Backup failed"
end
upload
@@ -55,7 +55,7 @@ module Backup
progress.puts "done".color(:green)
else
puts "uploading backup to #{remote_directory} failed".color(:red)
- raise Backup::Error, 'Backup failed'
+ raise Backup::Error, "Backup failed"
end
end
@@ -69,7 +69,7 @@ module Backup
progress.puts "done".color(:green)
else
puts "deleting tmp directory '#{dir}' failed".color(:red)
- raise Backup::Error, 'Backup failed'
+ raise Backup::Error, "Backup failed"
end
end
end
@@ -118,35 +118,35 @@ module Backup
progress.puts "Please make sure that file name ends with #{FILE_NAME_SUFFIX}"
exit 1
elsif backup_file_list.many? && ENV["BACKUP"].nil?
- progress.puts 'Found more than one backup:'
+ progress.puts "Found more than one backup:"
# print list of available backups
progress.puts " " + available_timestamps.join("\n ")
- progress.puts 'Please specify which one you want to restore:'
- progress.puts 'rake gitlab:backup:restore BACKUP=timestamp_of_backup'
+ progress.puts "Please specify which one you want to restore:"
+ progress.puts "rake gitlab:backup:restore BACKUP=timestamp_of_backup"
exit 1
end
- tar_file = if ENV['BACKUP'].present?
- "#{ENV['BACKUP']}#{FILE_NAME_SUFFIX}"
- else
- backup_file_list.first
- end
+ tar_file = if ENV["BACKUP"].present?
+ "#{ENV["BACKUP"]}#{FILE_NAME_SUFFIX}"
+ else
+ backup_file_list.first
+ end
unless File.exist?(tar_file)
progress.puts "The backup file #{tar_file} does not exist!"
exit 1
end
- progress.print 'Unpacking backup ... '
+ progress.print "Unpacking backup ... "
- unless Kernel.system(*%W(tar -xf #{tar_file}))
- progress.puts 'unpacking backup failed'.color(:red)
- exit 1
+ if Kernel.system("tar", "-xf", tar_file.to_s)
+ progress.puts "done".color(:green)
else
- progress.puts 'done'.color(:green)
+ progress.puts "unpacking backup failed".color(:red)
+ exit 1
end
- ENV["VERSION"] = "#{settings[:db_version]}" if settings[:db_version].to_i > 0
+ ENV["VERSION"] = settings[:db_version].to_s if settings[:db_version].to_i > 0
# restoring mismatching backups can lead to unexpected problems
if settings[:gitlab_version] != Gitlab::VERSION
@@ -164,12 +164,12 @@ module Backup
end
def tar_version
- tar_version, _ = Gitlab::Popen.popen(%w(tar --version))
- tar_version.dup.force_encoding('locale').split("\n").first
+ tar_version, _ = Gitlab::Popen.popen(%w[tar --version])
+ tar_version.dup.force_encoding("locale").split("\n").first
end
def skipped?(item)
- settings[:skipped] && settings[:skipped].include?(item) || disabled_features.include?(item)
+ settings[:skipped]&.include?(item) || disabled_features.include?(item)
end
private
@@ -183,7 +183,7 @@ module Backup
end
def available_timestamps
- @backup_file_list.map {|item| item.gsub("#{FILE_NAME_SUFFIX}", "")}
+ @backup_file_list.map {|item| item.gsub(FILE_NAME_SUFFIX.to_s, "")}
end
def connect_to_remote_directory(connection_settings)
@@ -205,8 +205,8 @@ module Backup
end
def remote_target
- if ENV['DIRECTORY']
- File.join(ENV['DIRECTORY'], tar_file)
+ if ENV["DIRECTORY"]
+ File.join(ENV["DIRECTORY"], tar_file)
else
tar_file
end
@@ -226,7 +226,7 @@ module Backup
def disabled_features
features = []
- features << 'registry' unless Gitlab.config.registry.enabled
+ features << "registry" unless Gitlab.config.registry.enabled
features
end
@@ -235,7 +235,7 @@ module Backup
end
def tar_file
- @tar_file ||= "#{backup_information[:backup_created_at].strftime('%s_%Y_%m_%d_')}#{backup_information[:gitlab_version]}#{FILE_NAME_SUFFIX}"
+ @tar_file ||= "#{backup_information[:backup_created_at].strftime("%s_%Y_%m_%d_")}#{backup_information[:gitlab_version]}#{FILE_NAME_SUFFIX}"
end
def backup_information
@@ -245,7 +245,7 @@ module Backup
gitlab_version: Gitlab::VERSION,
tar_version: tar_version,
installation_type: Gitlab::INSTALLATION_TYPE,
- skipped: ENV["SKIP"]
+ skipped: ENV["SKIP"],
}
end
end
diff --git a/lib/backup/pages.rb b/lib/backup/pages.rb
index a4be728df08..10a915cfd41 100644
--- a/lib/backup/pages.rb
+++ b/lib/backup/pages.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'backup/files'
+require "backup/files"
module Backup
class Pages < Files
@@ -9,7 +9,7 @@ module Backup
def initialize(progress)
@progress = progress
- super('pages', Gitlab.config.pages.path)
+ super("pages", Gitlab.config.pages.path)
end
end
end
diff --git a/lib/backup/registry.rb b/lib/backup/registry.rb
index d16ed2facf1..1fdacccea26 100644
--- a/lib/backup/registry.rb
+++ b/lib/backup/registry.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'backup/files'
+require "backup/files"
module Backup
class Registry < Files
@@ -9,7 +9,7 @@ module Backup
def initialize(progress)
@progress = progress
- super('registry', Settings.registry.path)
+ super("registry", Settings.registry.path)
end
end
end
diff --git a/lib/backup/repository.rb b/lib/backup/repository.rb
index 22ed1d8e7b4..76763b4a0f3 100644
--- a/lib/backup/repository.rb
+++ b/lib/backup/repository.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'yaml'
+require "yaml"
module Backup
class Repository
@@ -54,7 +54,7 @@ module Backup
backup_custom_hooks(project)
rescue => e
- progress_warn(project, e, 'Failed to backup repo')
+ progress_warn(project, e, "Failed to backup repo")
end
def backup_custom_hooks(project)
@@ -125,7 +125,7 @@ module Backup
protected
def path_to_bundle(project)
- File.join(backup_repos_path, project.disk_path + '.bundle')
+ File.join(backup_repos_path, project.disk_path + ".bundle")
end
def project_backup_path(project)
@@ -137,13 +137,13 @@ module Backup
end
def backup_repos_path
- File.join(Gitlab.config.backup.path, 'repositories')
+ File.join(Gitlab.config.backup.path, "repositories")
end
def prepare
FileUtils.rm_rf(backup_repos_path)
FileUtils.mkdir_p(Gitlab.config.backup.path)
- FileUtils.mkdir(backup_repos_path, mode: 0700)
+ FileUtils.mkdir(backup_repos_path, mode: 0o700)
end
private
@@ -167,7 +167,7 @@ module Backup
progress.puts " - Object pool #{pool.disk_path}..."
pool.source_project ||= pool.member_projects.first.root_of_fork_network
- pool.state = 'none'
+ pool.state = "none"
pool.save
pool.schedule
diff --git a/lib/backup/uploads.rb b/lib/backup/uploads.rb
index 9577df2634a..72c6e823026 100644
--- a/lib/backup/uploads.rb
+++ b/lib/backup/uploads.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'backup/files'
+require "backup/files"
module Backup
class Uploads < Files
@@ -9,7 +9,7 @@ module Backup
def initialize(progress)
@progress = progress
- super('uploads', Rails.root.join('public/uploads'))
+ super("uploads", Rails.root.join("public/uploads"))
end
end
end
diff --git a/lib/banzai/filter/absolute_link_filter.rb b/lib/banzai/filter/absolute_link_filter.rb
index a9bdb004c4b..84eeb1d43e0 100644
--- a/lib/banzai/filter/absolute_link_filter.rb
+++ b/lib/banzai/filter/absolute_link_filter.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'uri'
+require "uri"
module Banzai
module Filter
@@ -9,8 +9,8 @@ module Banzai
def call
return doc unless context[:only_path] == false
- doc.search('a.gfm').each do |el|
- process_link_attr el.attribute('href')
+ doc.search("a.gfm").each do |el|
+ process_link_attr el.attribute("href")
end
doc
@@ -20,7 +20,7 @@ module Banzai
def process_link_attr(html_attr)
return if html_attr.blank?
- return if html_attr.value.start_with?('//')
+ return if html_attr.value.start_with?("//")
uri = URI(html_attr.value)
html_attr.value = absolute_link_attr(uri) if uri.relative?
diff --git a/lib/banzai/filter/abstract_reference_filter.rb b/lib/banzai/filter/abstract_reference_filter.rb
index 4764f8e1e19..c727d0fd97d 100644
--- a/lib/banzai/filter/abstract_reference_filter.rb
+++ b/lib/banzai/filter/abstract_reference_filter.rb
@@ -133,7 +133,7 @@ module Banzai
next
end
- if link =~ link_pattern_anchor
+ if link&.match?(link_pattern_anchor)
replace_link_node_with_href(node, link) do
object_link_filter(link, link_pattern, link_content: inner_html, link_reference: true)
end
@@ -161,10 +161,10 @@ module Banzai
def object_link_filter(text, pattern, link_content: nil, link_reference: false)
references_in(text, pattern) do |match, id, project_ref, namespace_ref, matches|
parent_path = if parent_type == :group
- full_group_path(namespace_ref)
- else
- full_project_path(namespace_ref, project_ref)
- end
+ full_group_path(namespace_ref)
+ else
+ full_project_path(namespace_ref, project_ref)
+ end
parent = from_ref_cached(parent_path)
@@ -182,8 +182,8 @@ module Banzai
klass = reference_class(object_sym)
data = data_attributes_for(link_content || match, parent, object,
- link_content: !!link_content,
- link_reference: link_reference)
+ link_content: !!link_content,
+ link_reference: link_reference)
url =
if matches.names.include?("url") && matches[:url]
@@ -207,11 +207,11 @@ module Banzai
object_parent_type = parent.is_a?(Group) ? :group : :project
data_attribute(
- original: text,
- link: link_content,
- link_reference: link_reference,
+ :original => text,
+ :link => link_content,
+ :link_reference => link_reference,
object_parent_type => parent.id,
- object_sym => object.id
+ object_sym => object.id
)
end
@@ -256,10 +256,10 @@ module Banzai
nodes.each do |node|
node.to_html.scan(regex) do
path = if parent_type == :project
- full_project_path($~[:namespace], $~[:project])
- else
- full_group_path($~[:group])
- end
+ full_project_path($~[:namespace], $~[:project])
+ else
+ full_group_path($~[:group])
+ end
symbol = $~[object_sym]
refs[path] << symbol if object_class.reference_valid?(symbol)
diff --git a/lib/banzai/filter/ascii_doc_post_processing_filter.rb b/lib/banzai/filter/ascii_doc_post_processing_filter.rb
index 88439f06b5f..1df44ff21da 100644
--- a/lib/banzai/filter/ascii_doc_post_processing_filter.rb
+++ b/lib/banzai/filter/ascii_doc_post_processing_filter.rb
@@ -4,8 +4,8 @@ module Banzai
module Filter
class AsciiDocPostProcessingFilter < HTML::Pipeline::Filter
def call
- doc.search('[data-math-style]').each do |node|
- node.set_attribute('class', 'code math js-render-math')
+ doc.search("[data-math-style]").each do |node|
+ node.set_attribute("class", "code math js-render-math")
end
doc
diff --git a/lib/banzai/filter/autolink_filter.rb b/lib/banzai/filter/autolink_filter.rb
index 086adf59d2b..cad13eabdfb 100644
--- a/lib/banzai/filter/autolink_filter.rb
+++ b/lib/banzai/filter/autolink_filter.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'uri'
+require "uri"
module Banzai
module Filter
@@ -36,20 +36,20 @@ module Banzai
LINK_PATTERN = %r{([a-z][a-z0-9\+\.-]+://[^\s>]+)(?<!\?|!|\.|,|:)}
# Text matching LINK_PATTERN inside these elements will not be linked
- IGNORE_PARENTS = %w(a code kbd pre script style).to_set
+ IGNORE_PARENTS = %w[a code kbd pre script style].to_set
# The XPath query to use for finding text nodes to parse.
- TEXT_QUERY = %Q(descendant-or-self::text()[
- not(#{IGNORE_PARENTS.map { |p| "ancestor::#{p}" }.join(' or ')})
+ TEXT_QUERY = %(descendant-or-self::text()[
+ not(#{IGNORE_PARENTS.map { |p| "ancestor::#{p}" }.join(" or ")})
and contains(., '://')
- ]).freeze
+ ])
PUNCTUATION_PAIRS = {
"'" => "'",
'"' => '"',
- ')' => '(',
- ']' => '[',
- '}' => '{'
+ ")" => "(",
+ "]" => "[",
+ "}" => "{",
}.freeze
def call
@@ -92,8 +92,8 @@ module Banzai
# Remove any trailing HTML entities and store them for appending
# outside the link element. The entity must be marked HTML safe in
# order to be output literally rather than escaped.
- match.gsub!(/((?:&[\w#]+;)+)\z/, '')
- dropped = ($1 || '').html_safe
+ match.gsub!(/((?:&[\w#]+;)+)\z/, "")
+ dropped = ($1 || "").html_safe
# To match the behaviour of Rinku, if the matched link ends with a
# closing part of a matched pair of punctuation, we remove that trailing
diff --git a/lib/banzai/filter/color_filter.rb b/lib/banzai/filter/color_filter.rb
index 6d9bdb9cbd3..0204bd87773 100644
--- a/lib/banzai/filter/color_filter.rb
+++ b/lib/banzai/filter/color_filter.rb
@@ -5,10 +5,10 @@ module Banzai
# HTML filter that renders `color` followed by a color "chip".
#
class ColorFilter < HTML::Pipeline::Filter
- COLOR_CHIP_CLASS = 'gfm-color_chip'.freeze
+ COLOR_CHIP_CLASS = "gfm-color_chip"
def call
- doc.css('code').each do |node|
+ doc.css("code").each do |node|
color = ColorParser.parse(node.content)
node << color_chip(color) if color
end
@@ -19,8 +19,8 @@ module Banzai
private
def color_chip(color)
- checkerboard = doc.document.create_element('span', class: COLOR_CHIP_CLASS)
- chip = doc.document.create_element('span', style: inline_styles(color: color))
+ checkerboard = doc.document.create_element("span", class: COLOR_CHIP_CLASS)
+ chip = doc.document.create_element("span", style: inline_styles(color: color))
checkerboard << chip
end
diff --git a/lib/banzai/filter/commit_range_reference_filter.rb b/lib/banzai/filter/commit_range_reference_filter.rb
index d6b46236a49..926860a9bc4 100644
--- a/lib/banzai/filter/commit_range_reference_filter.rb
+++ b/lib/banzai/filter/commit_range_reference_filter.rb
@@ -35,7 +35,7 @@ module Banzai
def url_for_object(range, project)
h = Gitlab::Routing.url_helpers
h.project_compare_url(project,
- range.to_param.merge(only_path: context[:only_path]))
+ range.to_param.merge(only_path: context[:only_path]))
end
def object_link_title(range, matches)
diff --git a/lib/banzai/filter/commit_reference_filter.rb b/lib/banzai/filter/commit_reference_filter.rb
index c3e5ac41cb8..39b18873d5b 100644
--- a/lib/banzai/filter/commit_reference_filter.rb
+++ b/lib/banzai/filter/commit_reference_filter.rb
@@ -21,7 +21,7 @@ module Banzai
def find_object(project, id)
return unless project.is_a?(Project)
- if project && project.valid_repo?
+ if project&.valid_repo?
# n+1: https://gitlab.com/gitlab-org/gitlab-ce/issues/43894
Gitlab::GitalyClient.allow_n_plus_1_calls { project.commit(id) }
end
@@ -43,13 +43,13 @@ module Banzai
if referenced_merge_request_commit_shas.include?(commit.id)
h.diffs_project_merge_request_url(project,
- noteable,
- commit_id: commit.id,
- only_path: only_path?)
+ noteable,
+ commit_id: commit.id,
+ only_path: only_path?)
else
h.project_commit_url(project,
- commit,
- only_path: only_path?)
+ commit,
+ only_path: only_path?)
end
end
@@ -57,7 +57,7 @@ module Banzai
extras = super
path = matches[:path] if matches.names.include?("path")
- if path == '/builds'
+ if path == "/builds"
extras.unshift "builds"
end
diff --git a/lib/banzai/filter/commit_trailers_filter.rb b/lib/banzai/filter/commit_trailers_filter.rb
index f49c4b403db..d675d29730a 100644
--- a/lib/banzai/filter/commit_trailers_filter.rb
+++ b/lib/banzai/filter/commit_trailers_filter.rb
@@ -27,7 +27,7 @@ module Banzai
FILTER_REGEXP = /(?<trailer>^\s*#{TRAILER_REGEXP}\s*#{AUTHOR_REGEXP}\s+#{MAIL_REGEXP}$)/mi.freeze
def call
- doc.xpath('descendant-or-self::text()').each do |node|
+ doc.xpath("descendant-or-self::text()").each do |node|
content = node.to_html
next unless content.match(FILTER_REGEXP)
@@ -81,13 +81,13 @@ module Banzai
def link_to_user(user, name:, email:, trailer:)
wrapper = link_wrapper(data: {
trailer: trailer,
- user: user.try(:id)
+ user: user.try(:id),
})
avatar = user_avatar_without_link(
user: user,
user_email: email,
- css_class: 'avatar-inline',
+ css_class: "avatar-inline",
has_tooltip: false
)
@@ -118,7 +118,7 @@ module Banzai
data_attributes = data_attributes_from_hash(data)
doc.document.create_element(
- 'span',
+ "span",
data_attributes
)
end
@@ -131,7 +131,7 @@ module Banzai
title: title
)
- link = doc.document.create_element('a', attributes)
+ link = doc.document.create_element("a", attributes)
if content.html_safe?
link << content
@@ -144,9 +144,9 @@ module Banzai
def data_attributes_from_hash(data = {})
data.reject! {|_, value| value.nil?}
- data.map do |key, value|
+ data.map { |key, value|
[%(data-#{key.to_s.dasherize}), value]
- end.to_h
+ }.to_h
end
end
end
diff --git a/lib/banzai/filter/emoji_filter.rb b/lib/banzai/filter/emoji_filter.rb
index fa1690f73ad..cfa90295dca 100644
--- a/lib/banzai/filter/emoji_filter.rb
+++ b/lib/banzai/filter/emoji_filter.rb
@@ -7,14 +7,14 @@ module Banzai
#
# Based on HTML::Pipeline::EmojiFilter
class EmojiFilter < HTML::Pipeline::Filter
- IGNORED_ANCESTOR_TAGS = %w(pre code tt).to_set
+ IGNORED_ANCESTOR_TAGS = %w[pre code tt].to_set
def call
doc.search(".//text()").each do |node|
content = node.to_html
next if has_ancestor?(node, IGNORED_ANCESTOR_TAGS)
- next unless content.include?(':') || node.text.match(emoji_unicode_pattern)
+ next unless content.include?(":") || node.text.match(emoji_unicode_pattern)
html = emoji_unicode_element_unicode_filter(content)
html = emoji_name_element_unicode_filter(html)
@@ -46,7 +46,7 @@ module Banzai
def emoji_unicode_element_unicode_filter(text)
text.gsub(emoji_unicode_pattern) do |moji|
emoji_info = Gitlab::Emoji.emojis_by_moji[moji]
- Gitlab::Emoji.gl_emoji_tag(emoji_info['name'])
+ Gitlab::Emoji.gl_emoji_tag(emoji_info["name"])
end
end
diff --git a/lib/banzai/filter/external_issue_reference_filter.rb b/lib/banzai/filter/external_issue_reference_filter.rb
index 8159dcfed72..ac8449cb4df 100644
--- a/lib/banzai/filter/external_issue_reference_filter.rb
+++ b/lib/banzai/filter/external_issue_reference_filter.rb
@@ -42,7 +42,7 @@ module Banzai
elsif element_node?(node)
yield_valid_link(node) do |link, inner_html|
- if link =~ ref_start_pattern
+ if link&.match?(ref_start_pattern)
replace_link_node_with_href(node, link) do
issue_link_filter(link, link_content: inner_html)
end
diff --git a/lib/banzai/filter/external_link_filter.rb b/lib/banzai/filter/external_link_filter.rb
index 61ee3eac216..4357826b633 100644
--- a/lib/banzai/filter/external_link_filter.rb
+++ b/lib/banzai/filter/external_link_filter.rb
@@ -4,9 +4,9 @@ module Banzai
module Filter
# HTML Filter to modify the attributes of external links
class ExternalLinkFilter < HTML::Pipeline::Filter
- SCHEMES = ['http', 'https', nil].freeze
- RTLO = "\u202E".freeze
- ENCODED_RTLO = '%E2%80%AE'.freeze
+ SCHEMES = ["http", "https", nil].freeze
+ RTLO = "\u202E"
+ ENCODED_RTLO = "%E2%80%AE"
def call
links.each do |node|
@@ -14,10 +14,10 @@ module Banzai
# such as on `mailto:` links. Since we've been using it, do an
# initial parse for validity and then use Addressable
# for IDN support, etc
- uri = uri_strict(node['href'].to_s)
+ uri = uri_strict(node["href"].to_s)
if uri
- node.set_attribute('href', uri.to_s)
- addressable_uri = addressable_uri(node['href'])
+ node.set_attribute("href", uri.to_s)
+ addressable_uri = addressable_uri(node["href"])
else
addressable_uri = nil
end
@@ -72,7 +72,7 @@ module Banzai
return unless uri
return unless context[:emailable_links]
- unencoded_uri_str = Addressable::URI.unencode(node['href'])
+ unencoded_uri_str = Addressable::URI.unencode(node["href"])
if unencoded_uri_str == node.content && idn?(uri)
node.content = uri.normalize
@@ -95,20 +95,20 @@ module Banzai
# as this is an indicator of a malicious link
def add_malicious_tooltip!(uri, node)
if idn?(uri) || has_encoded_rtlo?(uri)
- node.add_class('has-tooltip')
- node.set_attribute('title', uri.normalize)
+ node.add_class("has-tooltip")
+ node.set_attribute("title", uri.normalize)
end
end
def add_nofollow!(uri, node)
if SCHEMES.include?(uri&.scheme)
- node.set_attribute('rel', 'nofollow noreferrer noopener')
- node.set_attribute('target', '_blank')
+ node.set_attribute("rel", "nofollow noreferrer noopener")
+ node.set_attribute("target", "_blank")
end
end
def idn?(uri)
- uri&.normalized_host&.start_with?('xn--')
+ uri&.normalized_host&.start_with?("xn--")
end
def has_encoded_rtlo?(uri)
diff --git a/lib/banzai/filter/footnote_filter.rb b/lib/banzai/filter/footnote_filter.rb
index de133774dfa..0f69ecee7f8 100644
--- a/lib/banzai/filter/footnote_filter.rb
+++ b/lib/banzai/filter/footnote_filter.rb
@@ -17,8 +17,8 @@ module Banzai
#
class FootnoteFilter < HTML::Pipeline::Filter
INTEGER_PATTERN = /\A\d+\z/.freeze
- FOOTNOTE_ID_PREFIX = 'fn'.freeze
- FOOTNOTE_LINK_ID_PREFIX = 'fnref'.freeze
+ FOOTNOTE_ID_PREFIX = "fn"
+ FOOTNOTE_LINK_ID_PREFIX = "fnref"
FOOTNOTE_LI_REFERENCE_PATTERN = /\A#{FOOTNOTE_ID_PREFIX}\d+\z/.freeze
FOOTNOTE_LINK_REFERENCE_PATTERN = /\A#{FOOTNOTE_LINK_ID_PREFIX}\d+\z/.freeze
FOOTNOTE_START_NUMBER = 1
@@ -31,7 +31,7 @@ module Banzai
rand_suffix = "-#{random_number}"
modified_footnotes = {}
- doc.css('sup > a[id]').each do |link_node|
+ doc.css("sup > a[id]").each do |link_node|
ref_num = link_node[:id].delete_prefix(FOOTNOTE_LINK_ID_PREFIX)
footnote_node = doc.at_css("li[id=#{fn_id(ref_num)}]")
@@ -40,7 +40,7 @@ module Banzai
link_node[:id] += rand_suffix
# Sanitization stripped off class - add it back in
- link_node.parent.append_class('footnote-ref')
+ link_node.parent.append_class("footnote-ref")
unless modified_footnotes[ref_num]
footnote_node[:id] += rand_suffix
@@ -48,7 +48,7 @@ module Banzai
if backref_node
backref_node[:href] += rand_suffix
- backref_node.append_class('footnote-backref')
+ backref_node.append_class("footnote-backref")
end
modified_footnotes[ref_num] = true
diff --git a/lib/banzai/filter/front_matter_filter.rb b/lib/banzai/filter/front_matter_filter.rb
index a27d18facd1..67d684e4fd1 100644
--- a/lib/banzai/filter/front_matter_filter.rb
+++ b/lib/banzai/filter/front_matter_filter.rb
@@ -4,9 +4,9 @@ module Banzai
module Filter
class FrontMatterFilter < HTML::Pipeline::Filter
DELIM_LANG = {
- '---' => 'yaml',
- '+++' => 'toml',
- ';;;' => 'json'
+ "---" => "yaml",
+ "+++" => "toml",
+ ";;;" => "json",
}.freeze
DELIM = Regexp.union(DELIM_LANG.keys)
diff --git a/lib/banzai/filter/gollum_tags_filter.rb b/lib/banzai/filter/gollum_tags_filter.rb
index 0c1bbd2d250..65255ea3b6b 100644
--- a/lib/banzai/filter/gollum_tags_filter.rb
+++ b/lib/banzai/filter/gollum_tags_filter.rb
@@ -59,7 +59,7 @@ module Banzai
ALLOWED_IMAGE_EXTENSIONS = /.+(jpg|png|gif|svg|bmp)\z/i.freeze
# Do not perform linking inside these tags.
- IGNORED_ANCESTOR_TAGS = %w(pre code tt).to_set
+ IGNORED_ANCESTOR_TAGS = %w[pre code tt].to_set
def call
doc.search(".//text()").each do |node|
@@ -91,7 +91,7 @@ module Banzai
# Replace an entire `[[<em>TOC</em>]]` node with the result generated by
# TableOfContentsFilter
def process_toc_tag(node)
- node.parent.parent.replace(result[:toc].presence || '')
+ node.parent.parent.replace(result[:toc].presence || "")
end
# Process a single tag into its final HTML form.
@@ -100,7 +100,7 @@ module Banzai
#
# Returns the String HTML version of the tag.
def process_tag(tag)
- parts = tag.split('|')
+ parts = tag.split("|")
return if parts.size.zero?
@@ -125,14 +125,14 @@ module Banzai
end
if path
- content_tag(:img, nil, data: { src: path }, class: 'gfm')
+ content_tag(:img, nil, data: {src: path}, class: "gfm")
end
end
def toc_tag?(node)
- node.content == 'TOC' &&
- node.parent.name == 'em' &&
- node.parent.parent.text == '[[TOC]]'
+ node.content == "TOC" &&
+ node.parent.name == "em" &&
+ node.parent.parent.text == "[[TOC]]"
end
def image?(path)
@@ -140,7 +140,7 @@ module Banzai
end
def url?(path)
- path.start_with?(*%w(http https))
+ path.start_with?("http", "https")
end
# Attempt to process the tag as a page link tag.
@@ -163,7 +163,7 @@ module Banzai
::File.join(project_wiki_base_path, reference)
end
- content_tag(:a, name || reference, href: href, class: 'gfm')
+ content_tag(:a, name || reference, href: href, class: "gfm")
end
def project_wiki
@@ -171,7 +171,7 @@ module Banzai
end
def project_wiki_base_path
- project_wiki && project_wiki.wiki_base_path
+ project_wiki&.wiki_base_path
end
# Ensure that a :project_wiki key exists in context
diff --git a/lib/banzai/filter/html_entity_filter.rb b/lib/banzai/filter/html_entity_filter.rb
index 406c2d3c96b..8ef93478bc4 100644
--- a/lib/banzai/filter/html_entity_filter.rb
+++ b/lib/banzai/filter/html_entity_filter.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'erb'
+require "erb"
module Banzai
module Filter
diff --git a/lib/banzai/filter/image_lazy_load_filter.rb b/lib/banzai/filter/image_lazy_load_filter.rb
index d8b9eb29cf5..6e542d13ac8 100644
--- a/lib/banzai/filter/image_lazy_load_filter.rb
+++ b/lib/banzai/filter/image_lazy_load_filter.rb
@@ -7,10 +7,10 @@ module Banzai
# so they can be lazy loaded.
class ImageLazyLoadFilter < HTML::Pipeline::Filter
def call
- doc.xpath('descendant-or-self::img').each do |img|
- img.add_class('lazy')
- img['data-src'] = img['src']
- img['src'] = LazyImageTagHelper.placeholder_image
+ doc.xpath("descendant-or-self::img").each do |img|
+ img.add_class("lazy")
+ img["data-src"] = img["src"]
+ img["src"] = LazyImageTagHelper.placeholder_image
end
doc
diff --git a/lib/banzai/filter/image_link_filter.rb b/lib/banzai/filter/image_link_filter.rb
index 01237303c27..f1059da3ec4 100644
--- a/lib/banzai/filter/image_link_filter.rb
+++ b/lib/banzai/filter/image_link_filter.rb
@@ -9,13 +9,13 @@ module Banzai
# a new node (a link to the image source), copy the image as a child
# of the anchor, and then replace the img with the link-wrapped version.
def call
- doc.xpath('descendant-or-self::img[not(ancestor::a)]').each do |img|
+ doc.xpath("descendant-or-self::img[not(ancestor::a)]").each do |img|
link = doc.document.create_element(
- 'a',
- class: 'no-attachment-icon',
- href: img['data-src'] || img['src'],
- target: '_blank',
- rel: 'noopener noreferrer'
+ "a",
+ class: "no-attachment-icon",
+ href: img["data-src"] || img["src"],
+ target: "_blank",
+ rel: "noopener noreferrer"
)
link.children = img.clone
diff --git a/lib/banzai/filter/inline_diff_filter.rb b/lib/banzai/filter/inline_diff_filter.rb
index 5a1c0bee32d..23481911b19 100644
--- a/lib/banzai/filter/inline_diff_filter.rb
+++ b/lib/banzai/filter/inline_diff_filter.rb
@@ -4,7 +4,7 @@
module Banzai
module Filter
class InlineDiffFilter < HTML::Pipeline::Filter
- IGNORED_ANCESTOR_TAGS = %w(pre code tt).to_set
+ IGNORED_ANCESTOR_TAGS = %w[pre code tt].to_set
def call
doc.search(".//text()").each do |node|
diff --git a/lib/banzai/filter/issuable_state_filter.rb b/lib/banzai/filter/issuable_state_filter.rb
index 8e2358694d4..db1a9634d14 100644
--- a/lib/banzai/filter/issuable_state_filter.rb
+++ b/lib/banzai/filter/issuable_state_filter.rb
@@ -8,7 +8,7 @@ module Banzai
#
# This filter supports cross-project references.
class IssuableStateFilter < HTML::Pipeline::Filter
- VISIBLE_STATES = %w(closed merged).freeze
+ VISIBLE_STATES = %w[closed merged].freeze
def call
return doc unless context[:issuable_state_filter_enabled]
diff --git a/lib/banzai/filter/label_reference_filter.rb b/lib/banzai/filter/label_reference_filter.rb
index f90a35952e5..9061bce1937 100644
--- a/lib/banzai/filter/label_reference_filter.rb
+++ b/lib/banzai/filter/label_reference_filter.rb
@@ -44,13 +44,13 @@ module Banzai
def find_labels(parent)
params = if parent.is_a?(Group)
- { group_id: parent.id,
- include_ancestor_groups: true,
- only_group_labels: true }
- else
- { project: parent,
- include_ancestor_groups: true }
- end
+ {group_id: parent.id,
+ include_ancestor_groups: true,
+ only_group_labels: true,}
+ else
+ {project: parent,
+ include_ancestor_groups: true,}
+ end
LabelsFinder.new(nil, params).execute(skip_authorization: true)
end
@@ -64,9 +64,9 @@ module Banzai
# Returns a Hash.
def label_params(id, name)
if name
- { name: name.tr('"', '') }
+ {name: name.tr('"', "")}
else
- { id: id.to_i }
+ {id: id.to_i}
end
end
@@ -81,7 +81,7 @@ module Banzai
end
def object_link_text(object, matches)
- label_suffix = ''
+ label_suffix = ""
if project || full_path_ref?(matches)
project_path = full_project_path(matches[:namespace], matches[:project])
diff --git a/lib/banzai/filter/markdown_engines/common_mark.rb b/lib/banzai/filter/markdown_engines/common_mark.rb
index d3af776db05..a74bfe85e90 100644
--- a/lib/banzai/filter/markdown_engines/common_mark.rb
+++ b/lib/banzai/filter/markdown_engines/common_mark.rb
@@ -14,13 +14,13 @@ module Banzai
:autolink, # provides support for automatically converting URLs to anchor tags.
:strikethrough, # provides support for strikethroughs.
:table, # provides support for tables.
- :tagfilter # strips out several "unsafe" HTML tags from being used: https://github.github.com/gfm/#disallowed-raw-html-extension-
+ :tagfilter, # strips out several "unsafe" HTML tags from being used: https://github.github.com/gfm/#disallowed-raw-html-extension-
].freeze
PARSE_OPTIONS = [
:FOOTNOTES, # parse footnotes.
:STRIKETHROUGH_DOUBLE_TILDE, # parse strikethroughs by double tildes (as redcarpet does).
- :VALIDATE_UTF8 # replace illegal sequences with the replacement character U+FFFD.
+ :VALIDATE_UTF8, # replace illegal sequences with the replacement character U+FFFD.
].freeze
# The `:GITHUB_PRE_LANG` option is not used intentionally because
@@ -29,11 +29,11 @@ module Banzai
# If in the future the syntax is about to be made GitHub-compatible, please, add `:GITHUB_PRE_LANG` render option below
# and remove `code_block` method from `lib/banzai/renderer/common_mark/html.rb`.
RENDER_OPTIONS = [
- :DEFAULT # default rendering system. Nothing special.
+ :DEFAULT, # default rendering system. Nothing special.
].freeze
RENDER_OPTIONS_SOURCEPOS = RENDER_OPTIONS + [
- :SOURCEPOS # enable embedding of source position information
+ :SOURCEPOS, # enable embedding of source position information
].freeze
def initialize(context)
diff --git a/lib/banzai/filter/math_filter.rb b/lib/banzai/filter/math_filter.rb
index 8dd5a8979c8..7199f2fb7da 100644
--- a/lib/banzai/filter/math_filter.rb
+++ b/lib/banzai/filter/math_filter.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'uri'
+require "uri"
# Generated HTML is transformed back to GFM by:
# - app/assets/javascripts/behaviors/markdown/marks/math.js
@@ -11,17 +11,17 @@ module Banzai
#
class MathFilter < HTML::Pipeline::Filter
# Attribute indicating inline or display math.
- STYLE_ATTRIBUTE = 'data-math-style'.freeze
+ STYLE_ATTRIBUTE = "data-math-style"
# Class used for tagging elements that should be rendered
- TAG_CLASS = 'js-render-math'.freeze
+ TAG_CLASS = "js-render-math"
- INLINE_CLASSES = "code math #{TAG_CLASS}".freeze
+ INLINE_CLASSES = "code math #{TAG_CLASS}"
- DOLLAR_SIGN = '$'.freeze
+ DOLLAR_SIGN = "$"
def call
- doc.css('code').each do |code|
+ doc.css("code").each do |code|
closing = code.next
opening = code.previous
@@ -33,14 +33,14 @@ module Banzai
opening.content.last == DOLLAR_SIGN
code[:class] = INLINE_CLASSES
- code[STYLE_ATTRIBUTE] = 'inline'
+ code[STYLE_ATTRIBUTE] = "inline"
closing.content = closing.content[1..-1]
opening.content = opening.content[0..-2]
end
end
- doc.css('pre.code.math').each do |el|
- el[STYLE_ATTRIBUTE] = 'display'
+ doc.css("pre.code.math").each do |el|
+ el[STYLE_ATTRIBUTE] = "display"
el[:class] += " #{TAG_CLASS}"
end
diff --git a/lib/banzai/filter/merge_request_reference_filter.rb b/lib/banzai/filter/merge_request_reference_filter.rb
index 7098767b583..87388f5bfd7 100644
--- a/lib/banzai/filter/merge_request_reference_filter.rb
+++ b/lib/banzai/filter/merge_request_reference_filter.rb
@@ -16,7 +16,7 @@ module Banzai
def url_for_object(mr, project)
h = Gitlab::Routing.url_helpers
h.project_merge_request_url(project, mr,
- only_path: context[:only_path])
+ only_path: context[:only_path])
end
def object_link_title(object, matches)
@@ -36,11 +36,11 @@ module Banzai
path = matches[:path] if matches.names.include?("path")
case path
- when '/diffs'
+ when "/diffs"
extras.unshift "diffs"
- when '/commits'
+ when "/commits"
extras.unshift "commits"
- when '/builds'
+ when "/builds"
extras.unshift "builds"
end
@@ -64,12 +64,12 @@ module Banzai
end
def object_link_commit(object, matches)
- return unless matches.names.include?('query') && query = matches[:query]
+ return unless matches.names.include?("query") && query = matches[:query]
# Removes leading "?". CGI.parse expects "arg1&arg2&arg3"
- params = CGI.parse(query.sub(/^\?/, ''))
+ params = CGI.parse(query.sub(/^\?/, ""))
- return unless commit_sha = params['commit_id']&.first
+ return unless commit_sha = params["commit_id"]&.first
if commit = find_commit_by_sha(object, commit_sha)
Commit.from_hash(commit.to_hash, object.project)
diff --git a/lib/banzai/filter/mermaid_filter.rb b/lib/banzai/filter/mermaid_filter.rb
index f0adb83af8a..1bffa87b302 100644
--- a/lib/banzai/filter/mermaid_filter.rb
+++ b/lib/banzai/filter/mermaid_filter.rb
@@ -5,7 +5,7 @@ module Banzai
module Filter
class MermaidFilter < HTML::Pipeline::Filter
def call
- doc.css('pre[lang="mermaid"] > code').add_class('js-render-mermaid')
+ doc.css('pre[lang="mermaid"] > code').add_class("js-render-mermaid")
doc
end
diff --git a/lib/banzai/filter/milestone_reference_filter.rb b/lib/banzai/filter/milestone_reference_filter.rb
index fce042e8946..8cb2712527c 100644
--- a/lib/banzai/filter/milestone_reference_filter.rb
+++ b/lib/banzai/filter/milestone_reference_filter.rb
@@ -77,9 +77,9 @@ module Banzai
def milestone_params(iid, name)
if name
- { name: name.tr('"', '') }
+ {name: name.tr('"', "")}
else
- { iid: iid.to_i }
+ {iid: iid.to_i}
end
end
@@ -90,7 +90,7 @@ module Banzai
end
def milestone_finder_params(parent, find_by_iid)
- { order: nil, state: 'all' }.tap do |params|
+ {order: nil, state: "all"}.tap do |params|
params[:project_ids] = parent.id if project_context?(parent)
# We don't support IID lookups because IIDs can clash between
diff --git a/lib/banzai/filter/plantuml_filter.rb b/lib/banzai/filter/plantuml_filter.rb
index caba8955bac..c0efa11d420 100644
--- a/lib/banzai/filter/plantuml_filter.rb
+++ b/lib/banzai/filter/plantuml_filter.rb
@@ -15,7 +15,8 @@ module Banzai
doc.css('pre > code[lang="plantuml"]').each do |node|
img_tag = Nokogiri::HTML::DocumentFragment.parse(
- Asciidoctor::PlantUml::Processor.plantuml_content(node.content, {}))
+ Asciidoctor::PlantUml::Processor.plantuml_content(node.content, {})
+ )
node.parent.replace(img_tag)
end
diff --git a/lib/banzai/filter/project_reference_filter.rb b/lib/banzai/filter/project_reference_filter.rb
index 83cf45097ed..5f8e9ad729d 100644
--- a/lib/banzai/filter/project_reference_filter.rb
+++ b/lib/banzai/filter/project_reference_filter.rb
@@ -34,7 +34,7 @@ module Banzai
end
elsif element_node?(node)
yield_valid_link(node) do |link, inner_html|
- if link =~ ref_pattern_start
+ if link&.match?(ref_pattern_start)
replace_link_node_with_href(node, link) do
project_link_filter(link, link_content: inner_html)
end
@@ -73,9 +73,9 @@ module Banzai
# corresponding Project objects.
def projects_hash
@projects ||= Project.eager_load(:route, namespace: [:route])
- .where_full_path_in(projects)
- .index_by(&:full_path)
- .transform_keys(&:downcase)
+ .where_full_path_in(projects)
+ .index_by(&:full_path)
+ .transform_keys(&:downcase)
end
# Returns all projects referenced in the current document.
diff --git a/lib/banzai/filter/reference_filter.rb b/lib/banzai/filter/reference_filter.rb
index 42f9b3a689c..f9670ae442a 100644
--- a/lib/banzai/filter/reference_filter.rb
+++ b/lib/banzai/filter/reference_filter.rb
@@ -35,12 +35,12 @@ module Banzai
attributes = attributes.reject { |_, v| v.nil? }
attributes[:reference_type] ||= self.class.reference_type
- attributes[:container] ||= 'body'
- attributes[:placement] ||= 'bottom'
+ attributes[:container] ||= "body"
+ attributes[:placement] ||= "bottom"
attributes.delete(:original) if context[:no_original_data]
- attributes.map do |key, value|
- %Q(data-#{key.to_s.dasherize}="#{escape_once(value)}")
- end.join(' ')
+ attributes.map { |key, value|
+ %(data-#{key.to_s.dasherize}="#{escape_once(value)}")
+ }.join(" ")
end
def escape_once(html)
@@ -49,10 +49,10 @@ module Banzai
def ignore_ancestor_query
@ignore_ancestor_query ||= begin
- parents = %w(pre code a style)
- parents << 'blockquote' if context[:ignore_blockquotes]
+ parents = %w[pre code a style]
+ parents << "blockquote" if context[:ignore_blockquotes]
- parents.map { |n| "ancestor::#{n}" }.join(' or ')
+ parents.map { |n| "ancestor::#{n}" }.join(" or ")
end
end
@@ -91,7 +91,7 @@ module Banzai
def each_node
return to_enum(__method__) unless block_given?
- query = %Q{descendant-or-self::text()[not(#{ignore_ancestor_query})]
+ query = %{descendant-or-self::text()[not(#{ignore_ancestor_query})]
| descendant-or-self::a[
not(contains(concat(" ", @class, " "), " gfm ")) and not(@href = "")
]}
@@ -108,10 +108,10 @@ module Banzai
# Yields the link's URL and inner HTML whenever the node is a valid <a> tag.
def yield_valid_link(node)
- link = CGI.unescape(node.attr('href').to_s)
+ link = CGI.unescape(node.attr("href").to_s)
inner_html = node.inner_html
- return unless link.force_encoding('UTF-8').valid_encoding?
+ return unless link.force_encoding("UTF-8").valid_encoding?
yield link, inner_html
end
diff --git a/lib/banzai/filter/relative_link_filter.rb b/lib/banzai/filter/relative_link_filter.rb
index 2745905c5ff..740babe76be 100644
--- a/lib/banzai/filter/relative_link_filter.rb
+++ b/lib/banzai/filter/relative_link_filter.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'uri'
+require "uri"
module Banzai
module Filter
@@ -20,13 +20,13 @@ module Banzai
@uri_types = {}
clear_memoization(:linkable_files)
- doc.search('a:not(.gfm)').each do |el|
- process_link_attr el.attribute('href')
+ doc.search("a:not(.gfm)").each do |el|
+ process_link_attr el.attribute("href")
end
- doc.css('img, video').each do |el|
- process_link_attr el.attribute('src')
- process_link_attr el.attribute('data-src')
+ doc.css("img, video").each do |el|
+ process_link_attr el.attribute("src")
+ process_link_attr el.attribute("data-src")
end
doc
@@ -42,9 +42,9 @@ module Banzai
def process_link_attr(html_attr)
return if html_attr.blank?
- return if html_attr.value.start_with?('//')
+ return if html_attr.value.start_with?("//")
- if html_attr.value.start_with?('/uploads/')
+ if html_attr.value.start_with?("/uploads/")
process_link_to_upload_attr(html_attr)
elsif linkable_files?
process_link_to_repository_attr(html_attr)
@@ -55,7 +55,7 @@ module Banzai
path_parts = [Addressable::URI.unescape(html_attr.value)]
if group
- path_parts.unshift(relative_url_root, 'groups', group.full_path, '-')
+ path_parts.unshift(relative_url_root, "groups", group.full_path, "-")
elsif project
path_parts.unshift(relative_url_root, project.full_path)
else
@@ -92,9 +92,9 @@ module Banzai
relative_url_root,
project.full_path,
uri_type(file_path),
- Addressable::URI.escape(ref).gsub('#', '%23'),
- Addressable::URI.escape(file_path)
- ].compact.join('/').squeeze('/').chomp('/')
+ Addressable::URI.escape(ref).gsub("#", "%23"),
+ Addressable::URI.escape(file_path),
+ ].compact.join("/").squeeze("/").chomp("/")
uri
end
@@ -130,19 +130,19 @@ module Banzai
def build_relative_path(path, request_path)
return request_path if path.empty?
return path unless request_path
- return path[1..-1] if path.start_with?('/')
+ return path[1..-1] if path.start_with?("/")
- parts = request_path.split('/')
+ parts = request_path.split("/")
parts.pop if uri_type(request_path) != :tree
- path.sub!(%r{\A\./}, '')
+ path.sub!(%r{\A\./}, "")
- while path.start_with?('../')
+ while path.start_with?("../")
parts.pop
- path.sub!('../', '')
+ path.sub!("../", "")
end
- parts.push(path).join('/')
+ parts.push(path).join("/")
end
def file_exists?(path)
@@ -161,7 +161,7 @@ module Banzai
end
def relative_url_root
- Gitlab.config.gitlab.relative_url_root.presence || '/'
+ Gitlab.config.gitlab.relative_url_root.presence || "/"
end
def ref
diff --git a/lib/banzai/filter/sanitization_filter.rb b/lib/banzai/filter/sanitization_filter.rb
index a4a06eae7b7..652290c9f68 100644
--- a/lib/banzai/filter/sanitization_filter.rb
+++ b/lib/banzai/filter/sanitization_filter.rb
@@ -8,7 +8,7 @@ module Banzai
class SanitizationFilter < HTML::Pipeline::SanitizationFilter
include Gitlab::Utils::StrongMemoize
- UNSAFE_PROTOCOLS = %w(data javascript vbscript).freeze
+ UNSAFE_PROTOCOLS = %w[data javascript vbscript].freeze
TABLE_ALIGNMENT_PATTERN = /text-align: (?<alignment>center|left|right)/.freeze
def whitelist
@@ -22,35 +22,35 @@ module Banzai
def customize_whitelist(whitelist)
# Allow table alignment; we whitelist specific text-align values in a
# transformer below
- whitelist[:attributes]['th'] = %w(style)
- whitelist[:attributes]['td'] = %w(style)
- whitelist[:css] = { properties: ['text-align'] }
+ whitelist[:attributes]["th"] = %w[style]
+ whitelist[:attributes]["td"] = %w[style]
+ whitelist[:css] = {properties: ["text-align"]}
# Allow span elements
- whitelist[:elements].push('span')
+ whitelist[:elements].push("span")
# Allow data-math-style attribute in order to support LaTeX formatting
- whitelist[:attributes]['code'] = %w(data-math-style)
- whitelist[:attributes]['pre'] = %w(data-math-style)
+ whitelist[:attributes]["code"] = %w[data-math-style]
+ whitelist[:attributes]["pre"] = %w[data-math-style]
# Allow html5 details/summary elements
- whitelist[:elements].push('details')
- whitelist[:elements].push('summary')
+ whitelist[:elements].push("details")
+ whitelist[:elements].push("summary")
# Allow abbr elements with title attribute
- whitelist[:elements].push('abbr')
- whitelist[:attributes]['abbr'] = %w(title)
+ whitelist[:elements].push("abbr")
+ whitelist[:attributes]["abbr"] = %w[title]
# Allow the 'data-sourcepos' from CommonMark on all elements
- whitelist[:attributes][:all].push('data-sourcepos')
+ whitelist[:attributes][:all].push("data-sourcepos")
# Disallow `name` attribute globally, allow on `a`
- whitelist[:attributes][:all].delete('name')
- whitelist[:attributes]['a'].push('name')
+ whitelist[:attributes][:all].delete("name")
+ whitelist[:attributes]["a"].push("name")
# Allow any protocol in `a` elements
# and then remove links with unsafe protocols
- whitelist[:protocols].delete('a')
+ whitelist[:protocols].delete("a")
whitelist[:transformers].push(self.class.remove_unsafe_links)
# Remove `rel` attribute from `a` elements
@@ -61,8 +61,8 @@ module Banzai
# Allow `id` in a and li elements for footnotes
# and remove any `id` properties not matching for footnotes
- whitelist[:attributes]['a'].push('id')
- whitelist[:attributes]['li'] = %w(id)
+ whitelist[:attributes]["a"].push("id")
+ whitelist[:attributes]["li"] = %w[id]
whitelist[:transformers].push(self.class.remove_non_footnote_ids)
whitelist
@@ -73,12 +73,12 @@ module Banzai
lambda do |env|
node = env[:node]
- return unless node.name == 'a'
- return unless node.has_attribute?('href')
+ return unless node.name == "a"
+ return unless node.has_attribute?("href")
begin
- node['href'] = node['href'].strip
- uri = Addressable::URI.parse(node['href'])
+ node["href"] = node["href"].strip
+ uri = Addressable::URI.parse(node["href"])
return unless uri.scheme
@@ -89,19 +89,19 @@ module Banzai
scheme = uri.scheme
.strip
.downcase
- .gsub(/[^A-Za-z0-9\+\.\-]+/, '')
+ .gsub(/[^A-Za-z0-9\+\.\-]+/, "")
- node.remove_attribute('href') if UNSAFE_PROTOCOLS.include?(scheme)
+ node.remove_attribute("href") if UNSAFE_PROTOCOLS.include?(scheme)
rescue Addressable::URI::InvalidURIError
- node.remove_attribute('href')
+ node.remove_attribute("href")
end
end
end
def remove_rel
lambda do |env|
- if env[:node_name] == 'a'
- env[:node].remove_attribute('rel')
+ if env[:node_name] == "a"
+ env[:node].remove_attribute("rel")
end
end
end
@@ -110,13 +110,13 @@ module Banzai
lambda do |env|
node = env[:node]
- return unless node.name == 'th' || node.name == 'td'
- return unless node.has_attribute?('style')
+ return unless node.name == "th" || node.name == "td"
+ return unless node.has_attribute?("style")
- if node['style'] =~ TABLE_ALIGNMENT_PATTERN
- node['style'] = "text-align: #{$~[:alignment]}"
+ if node["style"] =~ TABLE_ALIGNMENT_PATTERN
+ node["style"] = "text-align: #{$~[:alignment]}"
else
- node.remove_attribute('style')
+ node.remove_attribute("style")
end
end
end
@@ -125,13 +125,13 @@ module Banzai
lambda do |env|
node = env[:node]
- return unless node.name == 'a' || node.name == 'li'
- return unless node.has_attribute?('id')
+ return unless node.name == "a" || node.name == "li"
+ return unless node.has_attribute?("id")
- return if node.name == 'a' && node['id'] =~ Banzai::Filter::FootnoteFilter::FOOTNOTE_LINK_REFERENCE_PATTERN
- return if node.name == 'li' && node['id'] =~ Banzai::Filter::FootnoteFilter::FOOTNOTE_LI_REFERENCE_PATTERN
+ return if node.name == "a" && node["id"] =~ Banzai::Filter::FootnoteFilter::FOOTNOTE_LINK_REFERENCE_PATTERN
+ return if node.name == "li" && node["id"] =~ Banzai::Filter::FootnoteFilter::FOOTNOTE_LI_REFERENCE_PATTERN
- node.remove_attribute('id')
+ node.remove_attribute("id")
end
end
end
diff --git a/lib/banzai/filter/set_direction_filter.rb b/lib/banzai/filter/set_direction_filter.rb
index 45b259a2faf..79c15a0ebef 100644
--- a/lib/banzai/filter/set_direction_filter.rb
+++ b/lib/banzai/filter/set_direction_filter.rb
@@ -7,7 +7,7 @@ module Banzai
def call
# select these elements just on top level of the document
doc.xpath('p|h1|h2|h3|h4|h5|h6|ol|ul[not(@class="section-nav")]|blockquote|table').each do |el|
- el['dir'] = 'auto'
+ el["dir"] = "auto"
end
doc
diff --git a/lib/banzai/filter/snippet_reference_filter.rb b/lib/banzai/filter/snippet_reference_filter.rb
index f4b6edb6174..7465c447c8d 100644
--- a/lib/banzai/filter/snippet_reference_filter.rb
+++ b/lib/banzai/filter/snippet_reference_filter.rb
@@ -22,7 +22,7 @@ module Banzai
def url_for_object(snippet, project)
h = Gitlab::Routing.url_helpers
h.project_snippet_url(project, snippet,
- only_path: context[:only_path])
+ only_path: context[:only_path])
end
end
end
diff --git a/lib/banzai/filter/spaced_link_filter.rb b/lib/banzai/filter/spaced_link_filter.rb
index 50bf823929c..dcf83f77641 100644
--- a/lib/banzai/filter/spaced_link_filter.rb
+++ b/lib/banzai/filter/spaced_link_filter.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'uri'
+require "uri"
module Banzai
module Filter
@@ -36,13 +36,13 @@ module Banzai
}x
# Text matching LINK_OR_IMAGE_PATTERN inside these elements will not be linked
- IGNORE_PARENTS = %w(a code kbd pre script style).to_set
+ IGNORE_PARENTS = %w[a code kbd pre script style].to_set
# The XPath query to use for finding text nodes to parse.
- TEXT_QUERY = %Q(descendant-or-self::text()[
- not(#{IGNORE_PARENTS.map { |p| "ancestor::#{p}" }.join(' or ')})
+ TEXT_QUERY = %(descendant-or-self::text()[
+ not(#{IGNORE_PARENTS.map { |p| "ancestor::#{p}" }.join(" or ")})
and contains(., ']\(')
- ]).freeze
+ ])
def call
doc.xpath(TEXT_QUERY).each do |node|
@@ -71,7 +71,7 @@ module Banzai
html = Banzai::Filter::MarkdownFilter.call(transform_markdown(match), context)
# link is wrapped in a <p>, so strip that off
- p_node = Nokogiri::HTML.fragment(html).at_css('p')
+ p_node = Nokogiri::HTML.fragment(html).at_css("p")
p_node ? p_node.children.to_html : html
end
@@ -91,8 +91,8 @@ module Banzai
[
match[:preview_operator],
match[:text],
- match[:new_link].gsub(' ', '%20'),
- match[:title]
+ match[:new_link].gsub(" ", "%20"),
+ match[:title],
]
end
end
diff --git a/lib/banzai/filter/suggestion_filter.rb b/lib/banzai/filter/suggestion_filter.rb
index 9950db373d8..4c9b0ab4f56 100644
--- a/lib/banzai/filter/suggestion_filter.rb
+++ b/lib/banzai/filter/suggestion_filter.rb
@@ -5,12 +5,12 @@ module Banzai
module Filter
class SuggestionFilter < HTML::Pipeline::Filter
# Class used for tagging elements that should be rendered
- TAG_CLASS = 'js-render-suggestion'.freeze
+ TAG_CLASS = "js-render-suggestion"
def call
return doc unless suggestions_filter_enabled?
- doc.search('pre.suggestion > code').each do |node|
+ doc.search("pre.suggestion > code").each do |node|
node.add_class(TAG_CLASS)
end
diff --git a/lib/banzai/filter/syntax_highlight_filter.rb b/lib/banzai/filter/syntax_highlight_filter.rb
index 9ffde52b5f2..9faea6fa59c 100644
--- a/lib/banzai/filter/syntax_highlight_filter.rb
+++ b/lib/banzai/filter/syntax_highlight_filter.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'rouge/plugins/common_mark'
+require "rouge/plugins/common_mark"
# Generated HTML is transformed back to GFM by app/assets/javascripts/behaviors/markdown/nodes/code_block.js
module Banzai
@@ -9,7 +9,7 @@ module Banzai
#
class SyntaxHighlightFilter < HTML::Pipeline::Filter
def call
- doc.search('pre > code').each do |node|
+ doc.search("pre > code").each do |node|
highlight_node(node)
end
@@ -17,8 +17,8 @@ module Banzai
end
def highlight_node(node)
- css_classes = +'code highlight js-syntax-highlight'
- lang = node.attr('lang')
+ css_classes = +"code highlight js-syntax-highlight"
+ lang = node.attr("lang")
retried = false
if use_rouge?(lang)
@@ -69,7 +69,7 @@ module Banzai
end
def use_rouge?(language)
- %w(math mermaid plantuml suggestion).exclude?(language)
+ %w[math mermaid plantuml suggestion].exclude?(language)
end
end
end
diff --git a/lib/banzai/filter/table_of_contents_filter.rb b/lib/banzai/filter/table_of_contents_filter.rb
index f2ae17b44fa..9fca8afd0b4 100644
--- a/lib/banzai/filter/table_of_contents_filter.rb
+++ b/lib/banzai/filter/table_of_contents_filter.rb
@@ -27,17 +27,17 @@ module Banzai
headers = Hash.new(0)
header_root = current_header = HeaderNode.new
- doc.css('h1, h2, h3, h4, h5, h6').each do |node|
+ doc.css("h1, h2, h3, h4, h5, h6").each do |node|
if header_content = node.children.first
id = node
.text
.downcase
- .gsub(PUNCTUATION_REGEXP, '') # remove punctuation
- .tr(' ', '-') # replace spaces with dash
- .squeeze('-') # replace multiple dashes with one
+ .gsub(PUNCTUATION_REGEXP, "") # remove punctuation
+ .tr(" ", "-") # replace spaces with dash
+ .squeeze("-") # replace multiple dashes with one
.gsub(/\A(\d+)\z/, 'anchor-\1') # digits-only hrefs conflict with issue refs
- uniq = headers[id] > 0 ? "-#{headers[id]}" : ''
+ uniq = headers[id] > 0 ? "-#{headers[id]}" : ""
headers[id] += 1
href = "#{id}#{uniq}"
@@ -55,7 +55,7 @@ module Banzai
private
def anchor_tag(href)
- %Q{<a id="user-content-#{href}" class="anchor" href="##{href}" aria-hidden="true"></a>}
+ %(<a id="user-content-#{href}" class="anchor" href="##{href}" aria-hidden="true"></a>)
end
def push_toc(children, root: false)
@@ -65,13 +65,13 @@ module Banzai
result[:toc] << "<ul#{klass}>"
children.each { |child| push_anchor(child) }
- result[:toc] << '</ul>'
+ result[:toc] << "</ul>"
end
def push_anchor(header_node)
- result[:toc] << %Q{<li><a href="##{header_node.href}">#{header_node.text}</a>}
+ result[:toc] << %(<li><a href="##{header_node.href}">#{header_node.text}</a>)
push_toc(header_node.children)
- result[:toc] << '</li>'
+ result[:toc] << "</li>"
end
class HeaderNode
@@ -83,7 +83,7 @@ module Banzai
@children = []
@parent = find_parent(previous_header)
- @parent.children.push(self) if @parent
+ @parent&.children&.push(self)
end
def level
@@ -93,7 +93,7 @@ module Banzai
end
def text
- return '' unless node
+ return "" unless node
@text ||= EscapeUtils.escape_html(node.text)
end
diff --git a/lib/banzai/filter/task_list_filter.rb b/lib/banzai/filter/task_list_filter.rb
index c6b402575cb..ce1561de1f4 100644
--- a/lib/banzai/filter/task_list_filter.rb
+++ b/lib/banzai/filter/task_list_filter.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'task_list/filter'
+require "task_list/filter"
# Generated HTML is transformed back to GFM by:
# - app/assets/javascripts/behaviors/markdown/nodes/ordered_task_list.js
diff --git a/lib/banzai/filter/user_reference_filter.rb b/lib/banzai/filter/user_reference_filter.rb
index 8cda67867a8..576bbdbd2cc 100644
--- a/lib/banzai/filter/user_reference_filter.rb
+++ b/lib/banzai/filter/user_reference_filter.rb
@@ -38,7 +38,7 @@ module Banzai
end
elsif element_node?(node)
yield_valid_link(node) do |link, inner_html|
- if link =~ ref_pattern_start
+ if link&.match?(ref_pattern_start)
replace_link_node_with_href(node, link) do
user_link_filter(link, link_content: inner_html)
end
@@ -60,7 +60,7 @@ module Banzai
# have `gfm` and `gfm-project_member` class names attached for styling.
def user_link_filter(text, link_content: nil)
self.class.references_in(text) do |match, username|
- if username == 'all' && !skip_project_check?
+ if username == "all" && !skip_project_check?
link_to_all(link_content: link_content)
else
cached_call(:banzai_url_for_object, match, path: [User, username.downcase]) do
@@ -81,9 +81,9 @@ module Banzai
# corresponding Namespace objects.
def namespaces
@namespaces ||= Namespace.eager_load(:owner, :route)
- .where_full_path_in(usernames)
- .index_by(&:full_path)
- .transform_keys(&:downcase)
+ .where_full_path_in(usernames)
+ .index_by(&:full_path)
+ .transform_keys(&:downcase)
end
# Returns all usernames referenced in the current document.
@@ -172,8 +172,8 @@ module Banzai
data = data_attribute(project: project.id, author: author.try(:id))
end
- content = link_content || User.reference_prefix + 'all'
- link_tag(url, data, content, 'All Project and Group Members')
+ content = link_content || User.reference_prefix + "all"
+ link_tag(url, data, content, "All Project and Group Members")
end
end
end
diff --git a/lib/banzai/filter/video_link_filter.rb b/lib/banzai/filter/video_link_filter.rb
index 0fff104cf91..b7c32ea741e 100644
--- a/lib/banzai/filter/video_link_filter.rb
+++ b/lib/banzai/filter/video_link_filter.rb
@@ -19,36 +19,38 @@ module Banzai
def query
@query ||= begin
- src_query = UploaderHelper::VIDEO_EXT.map do |ext|
+ src_query = UploaderHelper::VIDEO_EXT.map { |ext|
"'.#{ext}' = substring(@src, string-length(@src) - #{ext.size})"
- end
+ }
- "descendant-or-self::img[not(ancestor::a) and (#{src_query.join(' or ')})]"
+ "descendant-or-self::img[not(ancestor::a) and (#{src_query.join(" or ")})]"
end
end
def video_node(doc, element)
container = doc.document.create_element(
- 'div',
- class: 'video-container'
+ "div",
+ class: "video-container"
)
video = doc.document.create_element(
- 'video',
- src: element['src'],
- width: '400',
- controls: true,
- 'data-setup' => '{}',
- 'data-title' => element['title'] || element['alt'])
+ "video",
+ :src => element["src"],
+ :width => "400",
+ :controls => true,
+ "data-setup" => "{}",
+ "data-title" => element["title"] || element["alt"]
+ )
link = doc.document.create_element(
- 'a',
- element['title'] || element['alt'],
- href: element['src'],
- target: '_blank',
- rel: 'noopener noreferrer',
- title: "Download '#{element['title'] || element['alt']}'")
- download_paragraph = doc.document.create_element('p')
+ "a",
+ element["title"] || element["alt"],
+ href: element["src"],
+ target: "_blank",
+ rel: "noopener noreferrer",
+ title: "Download '#{element["title"] || element["alt"]}'"
+ )
+ download_paragraph = doc.document.create_element("p")
download_paragraph.children = link
container.add_child(video)
diff --git a/lib/banzai/filter/wiki_link_filter.rb b/lib/banzai/filter/wiki_link_filter.rb
index 1728a442533..b3004476a8f 100644
--- a/lib/banzai/filter/wiki_link_filter.rb
+++ b/lib/banzai/filter/wiki_link_filter.rb
@@ -11,10 +11,10 @@ module Banzai
def call
return doc unless project_wiki?
- doc.search('a:not(.gfm)').each { |el| process_link_attr(el.attribute('href')) }
- doc.search('video').each { |el| process_link_attr(el.attribute('src')) }
- doc.search('img').each do |el|
- attr = el.attribute('data-src') || el.attribute('src')
+ doc.search("a:not(.gfm)").each { |el| process_link_attr(el.attribute("href")) }
+ doc.search("video").each { |el| process_link_attr(el.attribute("src")) }
+ doc.search("img").each do |el|
+ attr = el.attribute("data-src") || el.attribute("src")
process_link_attr(attr)
end
diff --git a/lib/banzai/filter/wiki_link_filter/rewriter.rb b/lib/banzai/filter/wiki_link_filter/rewriter.rb
index f4cc8beeb52..cd6376f14a9 100644
--- a/lib/banzai/filter/wiki_link_filter/rewriter.rb
+++ b/lib/banzai/filter/wiki_link_filter/rewriter.rb
@@ -6,7 +6,7 @@ module Banzai
class Rewriter
def initialize(link_string, wiki:, slug:)
@uri = Addressable::URI.parse(link_string)
- @wiki_base_path = wiki && wiki.wiki_base_path
+ @wiki_base_path = wiki&.wiki_base_path
@slug = slug
end
@@ -35,7 +35,7 @@ module Banzai
# Of the form `./link`, `../link`, or similar
def apply_hierarchical_link_rules!
- @uri = Addressable::URI.join(@slug, @uri) if @uri.to_s[0] == '.'
+ @uri = Addressable::URI.join(@slug, @uri) if @uri.to_s[0] == "."
end
# Any link _not_ of the form `http://example.com/`
@@ -48,7 +48,7 @@ module Banzai
end
def public_upload?
- @uri.relative? && @uri.path.starts_with?('/uploads/')
+ @uri.relative? && @uri.path.starts_with?("/uploads/")
end
def repository_upload?
diff --git a/lib/banzai/issuable_extractor.rb b/lib/banzai/issuable_extractor.rb
index 341dbb74fe0..c0c9d51668b 100644
--- a/lib/banzai/issuable_extractor.rb
+++ b/lib/banzai/issuable_extractor.rb
@@ -11,8 +11,8 @@ module Banzai
class IssuableExtractor
attr_reader :context
- ISSUE_REFERENCE_TYPE = '@data-reference-type="issue"'.freeze
- MERGE_REQUEST_REFERENCE_TYPE = '@data-reference-type="merge_request"'.freeze
+ ISSUE_REFERENCE_TYPE = '@data-reference-type="issue"'
+ MERGE_REQUEST_REFERENCE_TYPE = '@data-reference-type="merge_request"'
# context - An instance of Banzai::RenderContext.
def initialize(context)
@@ -21,9 +21,9 @@ module Banzai
# Returns Hash in the form { node => issuable_instance }
def extract(documents)
- nodes = documents.flat_map do |document|
+ nodes = documents.flat_map { |document|
document.xpath(query)
- end
+ }
# The project or group for the issuable might be pending for deletion!
# Filter them out because we don't care about them.
@@ -41,14 +41,14 @@ module Banzai
def parsers
[
Banzai::ReferenceParser::IssueParser.new(context),
- Banzai::ReferenceParser::MergeRequestParser.new(context)
+ Banzai::ReferenceParser::MergeRequestParser.new(context),
]
end
def query
- %Q(
+ %(
descendant-or-self::a[contains(concat(" ", @class, " "), " gfm ")]
- [#{reference_types.join(' or ')}]
+ [#{reference_types.join(" or ")}]
)
end
diff --git a/lib/banzai/object_renderer.rb b/lib/banzai/object_renderer.rb
index 75661ffa233..4a520567ac5 100644
--- a/lib/banzai/object_renderer.rb
+++ b/lib/banzai/object_renderer.rb
@@ -87,14 +87,14 @@ module Banzai
def base_context
{
current_user: context.current_user,
- skip_redaction: true
+ skip_redaction: true,
}
end
def save_options
return {} unless @redaction_context[:xhtml]
- { save_with: Nokogiri::XML::Node::SaveOptions::AS_XHTML }
+ {save_with: Nokogiri::XML::Node::SaveOptions::AS_XHTML}
end
end
end
diff --git a/lib/banzai/pipeline/base_pipeline.rb b/lib/banzai/pipeline/base_pipeline.rb
index 87d1cf9912f..249b332be78 100644
--- a/lib/banzai/pipeline/base_pipeline.rb
+++ b/lib/banzai/pipeline/base_pipeline.rb
@@ -16,7 +16,7 @@ module Banzai
end
class << self
- %i(call to_document to_html).each do |meth|
+ %i[call to_document to_html].each do |meth|
define_method(meth) do |text, context|
context = transform_context(context)
diff --git a/lib/banzai/pipeline/broadcast_message_pipeline.rb b/lib/banzai/pipeline/broadcast_message_pipeline.rb
index 580b5b72474..b293ad8c4c6 100644
--- a/lib/banzai/pipeline/broadcast_message_pipeline.rb
+++ b/lib/banzai/pipeline/broadcast_message_pipeline.rb
@@ -7,7 +7,6 @@ module Banzai
@filters ||= FilterArray[
Filter::MarkdownFilter,
Filter::SanitizationFilter,
-
Filter::EmojiFilter,
Filter::ColorFilter,
Filter::AutolinkFilter,
diff --git a/lib/banzai/pipeline/description_pipeline.rb b/lib/banzai/pipeline/description_pipeline.rb
index d5ff9b025cc..8d5fe7fd6c2 100644
--- a/lib/banzai/pipeline/description_pipeline.rb
+++ b/lib/banzai/pipeline/description_pipeline.rb
@@ -4,7 +4,7 @@ module Banzai
module Pipeline
class DescriptionPipeline < FullPipeline
WHITELIST = Banzai::Filter::SanitizationFilter::LIMITED.deep_dup.merge(
- elements: Banzai::Filter::SanitizationFilter::LIMITED[:elements] - %w(pre code img ol ul li)
+ elements: Banzai::Filter::SanitizationFilter::LIMITED[:elements] - %w[pre code img ol ul li]
)
def self.transform_context(context)
diff --git a/lib/banzai/pipeline/gfm_pipeline.rb b/lib/banzai/pipeline/gfm_pipeline.rb
index 30cafd11834..8ba0011eea4 100644
--- a/lib/banzai/pipeline/gfm_pipeline.rb
+++ b/lib/banzai/pipeline/gfm_pipeline.rb
@@ -12,13 +12,10 @@ module Banzai
def self.filters
@filters ||= FilterArray[
Filter::PlantumlFilter,
-
# Must always be before the SanitizationFilter to prevent XSS attacks
Filter::SpacedLinkFilter,
-
Filter::SanitizationFilter,
Filter::SyntaxHighlightFilter,
-
Filter::MathFilter,
Filter::ColorFilter,
Filter::MermaidFilter,
@@ -31,12 +28,9 @@ module Banzai
Filter::ExternalLinkFilter,
Filter::SuggestionFilter,
Filter::FootnoteFilter,
-
*reference_filters,
-
Filter::TaskListFilter,
Filter::InlineDiffFilter,
-
Filter::SetDirectionFilter
]
end
@@ -52,7 +46,7 @@ module Banzai
Filter::CommitRangeReferenceFilter,
Filter::CommitReferenceFilter,
Filter::LabelReferenceFilter,
- Filter::MilestoneReferenceFilter
+ Filter::MilestoneReferenceFilter,
]
end
diff --git a/lib/banzai/pipeline/post_process_pipeline.rb b/lib/banzai/pipeline/post_process_pipeline.rb
index 7eaad6d7560..471c4dac270 100644
--- a/lib/banzai/pipeline/post_process_pipeline.rb
+++ b/lib/banzai/pipeline/post_process_pipeline.rb
@@ -15,7 +15,7 @@ module Banzai
Filter::RedactorFilter,
Filter::RelativeLinkFilter,
Filter::IssuableStateFilter,
- Filter::SuggestionFilter
+ Filter::SuggestionFilter,
]
end
diff --git a/lib/banzai/pipeline/single_line_pipeline.rb b/lib/banzai/pipeline/single_line_pipeline.rb
index 72374207a8f..104a3b1b7ed 100644
--- a/lib/banzai/pipeline/single_line_pipeline.rb
+++ b/lib/banzai/pipeline/single_line_pipeline.rb
@@ -7,11 +7,9 @@ module Banzai
@filters ||= FilterArray[
Filter::HtmlEntityFilter,
Filter::SanitizationFilter,
-
Filter::EmojiFilter,
Filter::AutolinkFilter,
Filter::ExternalLinkFilter,
-
*reference_filters
]
end
@@ -24,7 +22,7 @@ module Banzai
Filter::MergeRequestReferenceFilter,
Filter::SnippetReferenceFilter,
Filter::CommitRangeReferenceFilter,
- Filter::CommitReferenceFilter
+ Filter::CommitReferenceFilter,
]
end
diff --git a/lib/banzai/pipeline/wiki_pipeline.rb b/lib/banzai/pipeline/wiki_pipeline.rb
index 97a03895ff3..22eaf854cf7 100644
--- a/lib/banzai/pipeline/wiki_pipeline.rb
+++ b/lib/banzai/pipeline/wiki_pipeline.rb
@@ -6,7 +6,7 @@ module Banzai
def self.filters
@filters ||= begin
super.insert_after(Filter::TableOfContentsFilter, Filter::GollumTagsFilter)
- .insert_before(Filter::TaskListFilter, Filter::WikiLinkFilter)
+ .insert_before(Filter::TaskListFilter, Filter::WikiLinkFilter)
end
end
end
diff --git a/lib/banzai/querying.rb b/lib/banzai/querying.rb
index 55aa5fa66c3..20136b86884 100644
--- a/lib/banzai/querying.rb
+++ b/lib/banzai/querying.rb
@@ -16,7 +16,7 @@ module Banzai
def css(document, query, reference_options = {})
# When using "a.foo" Nokogiri compiles this to "//a[...]" but
# "descendant::a[...]" is quite a bit faster and achieves the same result.
- xpath = Nokogiri::CSS.xpath_for(query)[0].gsub(%r{^//}, 'descendant::')
+ xpath = Nokogiri::CSS.xpath_for(query)[0].gsub(%r{^//}, "descendant::")
xpath = restrict_to_p_nodes_at_root(xpath) if filter_nodes_at_beginning?(reference_options)
nodes = document.xpath(xpath)
@@ -24,7 +24,7 @@ module Banzai
end
def restrict_to_p_nodes_at_root(xpath)
- xpath.gsub('descendant::', './p/')
+ xpath.gsub("descendant::", "./p/")
end
def filter_nodes(nodes, reference_options)
diff --git a/lib/banzai/redactor.rb b/lib/banzai/redactor.rb
index 7db5f5e1f7d..223d2c52596 100644
--- a/lib/banzai/redactor.rb
+++ b/lib/banzai/redactor.rb
@@ -41,9 +41,9 @@ module Banzai
nodes_for_document = entry[:nodes]
doc_data = {
- document: entry[:document],
- total_reference_count: nodes_for_document.count,
- visible_reference_count: nodes_for_document.count
+ document: entry[:document],
+ total_reference_count: nodes_for_document.count,
+ visible_reference_count: nodes_for_document.count,
}
metadata << doc_data
@@ -64,13 +64,13 @@ module Banzai
# the original content (text), or the inner HTML of the node.
#
def redacted_node_content(node)
- original_content = node.attr('data-original')
- link_reference = node.attr('data-link-reference')
+ original_content = node.attr("data-original")
+ link_reference = node.attr("data-link-reference")
# Build the raw <a> tag just with a link as href and content if
# it's originally a link pattern. We shouldn't return a plain text href.
original_link =
- if link_reference == 'true' && href = original_content
+ if link_reference == "true" && href = original_content
%(<a href="#{href}">#{href}</a>)
end
@@ -86,8 +86,8 @@ module Banzai
issuables.each do |node, issuable|
next if issuable.project == context.project_for_node(node)
- node['class'] = node['class'].gsub('has-tooltip', '')
- node['title'] = nil
+ node["class"] = node["class"].gsub("has-tooltip", "")
+ node["title"] = nil
end
end
@@ -101,7 +101,7 @@ module Banzai
visible = Set.new
nodes.each do |node|
- per_type[node.attr('data-reference-type')] << node
+ per_type[node.attr("data-reference-type")] << node
end
per_type.each do |type, nodes|
@@ -115,7 +115,7 @@ module Banzai
def document_nodes(documents)
documents.map do |document|
- { document: document, nodes: Querying.css(document, 'a.gfm[data-reference-type]') }
+ {document: document, nodes: Querying.css(document, "a.gfm[data-reference-type]")}
end
end
diff --git a/lib/banzai/reference_extractor.rb b/lib/banzai/reference_extractor.rb
index 3fc3ae02088..66a4375746d 100644
--- a/lib/banzai/reference_extractor.rb
+++ b/lib/banzai/reference_extractor.rb
@@ -8,7 +8,7 @@ module Banzai
end
def analyze(text, context = {})
- @texts_and_contexts << { text: text, context: context }
+ @texts_and_contexts << {text: text, context: context}
end
def references(type, project, current_user = nil)
diff --git a/lib/banzai/reference_parser/base_parser.rb b/lib/banzai/reference_parser/base_parser.rb
index 8419769085a..8523d08f434 100644
--- a/lib/banzai/reference_parser/base_parser.rb
+++ b/lib/banzai/reference_parser/base_parser.rb
@@ -64,7 +64,7 @@ module Banzai
# Returns all the nodes that are visible to the given user.
def nodes_visible_to_user(user, nodes)
projects = lazy { projects_for_nodes(nodes) }
- project_attr = 'data-project'
+ project_attr = "data-project"
nodes.select do |node|
if node.has_attribute?(project_attr)
@@ -108,7 +108,7 @@ module Banzai
per_project = Hash.new { |hash, key| hash[key] = Set.new }
nodes.each do |node|
- project_id = node.attr('data-project').to_i
+ project_id = node.attr("data-project").to_i
id = node.attr(attribute)
per_project[project_id] << id if id
@@ -194,9 +194,9 @@ module Banzai
type = self.class.reference_type
reference_options = self.class.reference_options
- nodes = documents.flat_map do |document|
+ nodes = documents.flat_map { |document|
Querying.css(document, "a[data-reference-type='#{type}'].gfm", reference_options).to_a
- end
+ }
gather_references(nodes)
end
@@ -217,7 +217,7 @@ module Banzai
#
def projects_for_nodes(nodes)
@projects_for_nodes ||=
- grouped_objects_for_nodes(nodes, Project.includes(:project_feature), 'data-project')
+ grouped_objects_for_nodes(nodes, Project.includes(:project_feature), "data-project")
end
def can?(user, permission, subject = :global)
@@ -250,9 +250,9 @@ module Banzai
end
def collection_cache
- Gitlab::SafeRequestStore[:banzai_collection_cache] ||= Hash.new do |hash, key|
+ Gitlab::SafeRequestStore[:banzai_collection_cache] ||= Hash.new { |hash, key|
hash[key] = {}
- end
+ }
end
end
end
diff --git a/lib/banzai/reference_parser/directly_addressed_user_parser.rb b/lib/banzai/reference_parser/directly_addressed_user_parser.rb
index 1f18f82b916..08faa0ac526 100644
--- a/lib/banzai/reference_parser/directly_addressed_user_parser.rb
+++ b/lib/banzai/reference_parser/directly_addressed_user_parser.rb
@@ -4,7 +4,7 @@ module Banzai
module ReferenceParser
class DirectlyAddressedUserParser < UserParser
self.reference_type = :user
- self.reference_options = { location: :beginning }
+ self.reference_options = {location: :beginning}
end
end
end
diff --git a/lib/banzai/reference_parser/issue_parser.rb b/lib/banzai/reference_parser/issue_parser.rb
index 97c7173ac0f..de6d319160f 100644
--- a/lib/banzai/reference_parser/issue_parser.rb
+++ b/lib/banzai/reference_parser/issue_parser.rb
@@ -67,13 +67,13 @@ module Banzai
# Eager loading these ensures we don't end up running dozens of
# queries in this process.
project: [
- { namespace: :owner },
- { group: [:owners, :group_members] },
+ {namespace: :owner},
+ {group: [:owners, :group_members]},
:invited_groups,
:project_members,
:project_feature,
- :route
- ]
+ :route,
+ ],
}
),
self.class.data_attribute
diff --git a/lib/banzai/reference_parser/merge_request_parser.rb b/lib/banzai/reference_parser/merge_request_parser.rb
index e8147ac591a..fea56520866 100644
--- a/lib/banzai/reference_parser/merge_request_parser.rb
+++ b/lib/banzai/reference_parser/merge_request_parser.rb
@@ -16,14 +16,15 @@ module Banzai
# Eager loading these ensures we don't end up running dozens of
# queries in this process.
target_project: [
- { namespace: [:owner, :route] },
- { group: [:owners, :group_members] },
+ {namespace: [:owner, :route]},
+ {group: [:owners, :group_members]},
:invited_groups,
:project_members,
:project_feature,
- :route
- ]
- }),
+ :route,
+ ],
+ }
+ ),
self.class.data_attribute
)
end
diff --git a/lib/banzai/reference_parser/user_parser.rb b/lib/banzai/reference_parser/user_parser.rb
index 067b06b7590..dcb9d95c029 100644
--- a/lib/banzai/reference_parser/user_parser.rb
+++ b/lib/banzai/reference_parser/user_parser.rb
@@ -11,12 +11,12 @@ module Banzai
project_ids = []
nodes.each do |node|
- if node.has_attribute?('data-group')
- group_ids << node.attr('data-group').to_i
+ if node.has_attribute?("data-group")
+ group_ids << node.attr("data-group").to_i
elsif node.has_attribute?(self.class.data_attribute)
user_ids << node.attr(self.class.data_attribute).to_i
- elsif node.has_attribute?('data-project')
- project_ids << node.attr('data-project').to_i
+ elsif node.has_attribute?("data-project")
+ project_ids << node.attr("data-project").to_i
end
end
@@ -25,7 +25,7 @@ module Banzai
end
def nodes_visible_to_user(user, nodes)
- group_attr = 'data-group'
+ group_attr = "data-group"
groups = lazy { grouped_objects_for_nodes(nodes, Group, group_attr) }
visible = []
remaining = []
@@ -58,14 +58,14 @@ module Banzai
end
def can_read_project_reference?(node)
- node_id = node.attr('data-project').to_i
+ node_id = node.attr("data-project").to_i
project_for_node(node)&.id == node_id
end
def nodes_user_can_reference(current_user, nodes)
- project_attr = 'data-project'
- author_attr = 'data-author'
+ project_attr = "data-project"
+ author_attr = "data-author"
projects = lazy { projects_for_nodes(nodes) }
users = lazy { grouped_objects_for_nodes(nodes, User, author_attr) }
@@ -97,7 +97,7 @@ module Banzai
def find_users_for_groups(ids)
return [] if ids.empty?
- User.joins(:group_members).where(members: { source_id: ids }).to_a
+ User.joins(:group_members).where(members: {source_id: ids}).to_a
end
def find_users_for_projects(ids)
diff --git a/lib/banzai/renderer.rb b/lib/banzai/renderer.rb
index c7239a5eaa6..7179d273e76 100644
--- a/lib/banzai/renderer.rb
+++ b/lib/banzai/renderer.rb
@@ -90,10 +90,10 @@ module Banzai
unless cacheable_items.empty?
items_in_cache = Rails.cache.read_multi(*cacheable_items.map { |item| item[:cache_key] })
- items_not_in_cache = cacheable_items.reject do |item|
+ items_not_in_cache = cacheable_items.reject { |item|
item[:rendered] = items_in_cache[item[:cache_key]]
items_in_cache.key?(item[:cache_key])
- end
+ }
end
(items_not_in_cache + non_cacheable_items).each do |item|
diff --git a/lib/banzai/renderer/common_mark/html.rb b/lib/banzai/renderer/common_mark/html.rb
index 837665451a1..b0352d9b0e5 100644
--- a/lib/banzai/renderer/common_mark/html.rb
+++ b/lib/banzai/renderer/common_mark/html.rb
@@ -8,9 +8,9 @@ module Banzai
block do
out("<pre#{sourcepos(node)}><code")
out(' lang="', node.fence_info, '"') if node.fence_info.present?
- out('>')
+ out(">")
out(escape_html(node.string_content))
- out('</code></pre>')
+ out("</code></pre>")
end
end
end
diff --git a/lib/banzai/request_store_reference_cache.rb b/lib/banzai/request_store_reference_cache.rb
index 91fb489b72d..e0d90a731fe 100644
--- a/lib/banzai/request_store_reference_cache.rb
+++ b/lib/banzai/request_store_reference_cache.rb
@@ -4,9 +4,9 @@ module Banzai
module RequestStoreReferenceCache
def cached_call(request_store_key, cache_key, path: [])
if Gitlab::SafeRequestStore.active?
- cache = Gitlab::SafeRequestStore[request_store_key] ||= Hash.new do |hash, key|
+ cache = Gitlab::SafeRequestStore[request_store_key] ||= Hash.new { |hash, key|
hash[key] = Hash.new { |h, k| h[k] = {} }
- end
+ }
cache = cache.dig(*path) if path.any?
diff --git a/lib/banzai/suggestions_parser.rb b/lib/banzai/suggestions_parser.rb
index 09f36635020..82afc1c9c64 100644
--- a/lib/banzai/suggestions_parser.rb
+++ b/lib/banzai/suggestions_parser.rb
@@ -8,7 +8,7 @@ module Banzai
html = Banzai.render(text, project: nil, no_original_data: true)
doc = Nokogiri::HTML(html)
- doc.search('pre.suggestion').map { |node| node.text }
+ doc.search("pre.suggestion").map { |node| node.text }
end
end
end
diff --git a/lib/bitbucket/client.rb b/lib/bitbucket/client.rb
index 1343f424c51..4b928a7d32d 100644
--- a/lib/bitbucket/client.rb
+++ b/lib/bitbucket/client.rb
@@ -45,7 +45,7 @@ module Bitbucket
def user
@user ||= begin
- parsed_response = connection.get('/user')
+ parsed_response = connection.get("/user")
Representation::User.new(parsed_response)
end
end
diff --git a/lib/bitbucket/collection.rb b/lib/bitbucket/collection.rb
index 9c496daccaa..4e64a3f4616 100644
--- a/lib/bitbucket/collection.rb
+++ b/lib/bitbucket/collection.rb
@@ -13,9 +13,9 @@ module Bitbucket
end
def method_missing(method, *args)
- return super unless self.respond_to?(method)
+ return super unless respond_to?(method)
- self.__send__(method, *args) do |item| # rubocop:disable GitlabSecurity/PublicSend
+ __send__(method, *args) do |item| # rubocop:disable GitlabSecurity/PublicSend
block_given? ? yield(item) : item
end
end
diff --git a/lib/bitbucket/connection.rb b/lib/bitbucket/connection.rb
index 0041634f9e3..dd7f4e579f6 100644
--- a/lib/bitbucket/connection.rb
+++ b/lib/bitbucket/connection.rb
@@ -2,8 +2,8 @@
module Bitbucket
class Connection
- DEFAULT_API_VERSION = '2.0'.freeze
- DEFAULT_BASE_URI = 'https://api.bitbucket.org/'.freeze
+ DEFAULT_API_VERSION = "2.0"
+ DEFAULT_BASE_URI = "https://api.bitbucket.org/"
DEFAULT_QUERY = {}.freeze
attr_reader :expires_at, :expires_in, :refresh_token, :token
@@ -59,7 +59,7 @@ module Bitbucket
end
def provider
- Gitlab::Auth::OAuth::Provider.config_for('bitbucket')
+ Gitlab::Auth::OAuth::Provider.config_for("bitbucket")
end
def options
diff --git a/lib/bitbucket/page.rb b/lib/bitbucket/page.rb
index 7cc1342ad65..42bc81fc8d2 100644
--- a/lib/bitbucket/page.rb
+++ b/lib/bitbucket/page.rb
@@ -20,13 +20,13 @@ module Bitbucket
private
def parse_attrs(raw)
- raw.slice(*%w(size page pagelen next previous)).symbolize_keys
+ raw.slice("size", "page", "pagelen", "next", "previous").symbolize_keys
end
def parse_values(raw, bitbucket_rep_class)
- return [] unless raw['values'] && raw['values'].is_a?(Array)
+ return [] unless raw["values"]&.is_a?(Array)
- bitbucket_rep_class.decorate(raw['values'])
+ bitbucket_rep_class.decorate(raw["values"])
end
def representation_class(type)
diff --git a/lib/bitbucket/representation/comment.rb b/lib/bitbucket/representation/comment.rb
index 1b8dc27793a..9c1848738ba 100644
--- a/lib/bitbucket/representation/comment.rb
+++ b/lib/bitbucket/representation/comment.rb
@@ -4,25 +4,25 @@ module Bitbucket
module Representation
class Comment < Representation::Base
def author
- user['username']
+ user["username"]
end
def note
- raw.fetch('content', {}).fetch('raw', nil)
+ raw.fetch("content", {}).fetch("raw", nil)
end
def created_at
- raw['created_on']
+ raw["created_on"]
end
def updated_at
- raw['updated_on'] || raw['created_on']
+ raw["updated_on"] || raw["created_on"]
end
private
def user
- raw.fetch('user', {})
+ raw.fetch("user", {})
end
end
end
diff --git a/lib/bitbucket/representation/issue.rb b/lib/bitbucket/representation/issue.rb
index a88797cdab9..7c7a586f3bf 100644
--- a/lib/bitbucket/representation/issue.rb
+++ b/lib/bitbucket/representation/issue.rb
@@ -3,42 +3,42 @@
module Bitbucket
module Representation
class Issue < Representation::Base
- CLOSED_STATUS = %w(resolved invalid duplicate wontfix closed).freeze
+ CLOSED_STATUS = %w[resolved invalid duplicate wontfix closed].freeze
def iid
- raw['id']
+ raw["id"]
end
def kind
- raw['kind']
+ raw["kind"]
end
def author
- raw.dig('reporter', 'username')
+ raw.dig("reporter", "username")
end
def description
- raw.fetch('content', {}).fetch('raw', nil)
+ raw.fetch("content", {}).fetch("raw", nil)
end
def state
- closed? ? 'closed' : 'opened'
+ closed? ? "closed" : "opened"
end
def title
- raw['title']
+ raw["title"]
end
def milestone
- raw['milestone']['name'] if raw['milestone'].present?
+ raw["milestone"]["name"] if raw["milestone"].present?
end
def created_at
- raw['created_on']
+ raw["created_on"]
end
def updated_at
- raw['edited_on']
+ raw["edited_on"]
end
def to_s
@@ -48,7 +48,7 @@ module Bitbucket
private
def closed?
- CLOSED_STATUS.include?(raw['state'])
+ CLOSED_STATUS.include?(raw["state"])
end
end
end
diff --git a/lib/bitbucket/representation/pull_request.rb b/lib/bitbucket/representation/pull_request.rb
index 6a0e8b354bf..ecb8746da8d 100644
--- a/lib/bitbucket/representation/pull_request.rb
+++ b/lib/bitbucket/representation/pull_request.rb
@@ -4,63 +4,63 @@ module Bitbucket
module Representation
class PullRequest < Representation::Base
def author
- raw.fetch('author', {}).fetch('username', nil)
+ raw.fetch("author", {}).fetch("username", nil)
end
def description
- raw['description']
+ raw["description"]
end
def iid
- raw['id']
+ raw["id"]
end
def state
- if raw['state'] == 'MERGED'
- 'merged'
- elsif raw['state'] == 'DECLINED'
- 'closed'
+ if raw["state"] == "MERGED"
+ "merged"
+ elsif raw["state"] == "DECLINED"
+ "closed"
else
- 'opened'
+ "opened"
end
end
def created_at
- raw['created_on']
+ raw["created_on"]
end
def updated_at
- raw['updated_on']
+ raw["updated_on"]
end
def title
- raw['title']
+ raw["title"]
end
def source_branch_name
- source_branch.fetch('branch', {}).fetch('name', nil)
+ source_branch.fetch("branch", {}).fetch("name", nil)
end
def source_branch_sha
- source_branch.fetch('commit', {}).fetch('hash', nil)
+ source_branch.fetch("commit", {}).fetch("hash", nil)
end
def target_branch_name
- target_branch.fetch('branch', {}).fetch('name', nil)
+ target_branch.fetch("branch", {}).fetch("name", nil)
end
def target_branch_sha
- target_branch.fetch('commit', {}).fetch('hash', nil)
+ target_branch.fetch("commit", {}).fetch("hash", nil)
end
private
def source_branch
- raw['source']
+ raw["source"]
end
def target_branch
- raw['destination']
+ raw["destination"]
end
end
end
diff --git a/lib/bitbucket/representation/pull_request_comment.rb b/lib/bitbucket/representation/pull_request_comment.rb
index 34dbf9ad22d..7eb8ef6803f 100644
--- a/lib/bitbucket/representation/pull_request_comment.rb
+++ b/lib/bitbucket/representation/pull_request_comment.rb
@@ -4,37 +4,37 @@ module Bitbucket
module Representation
class PullRequestComment < Comment
def iid
- raw['id']
+ raw["id"]
end
def file_path
- inline.fetch('path')
+ inline.fetch("path")
end
def old_pos
- inline.fetch('from')
+ inline.fetch("from")
end
def new_pos
- inline.fetch('to')
+ inline.fetch("to")
end
def parent_id
- raw.fetch('parent', {}).fetch('id', nil)
+ raw.fetch("parent", {}).fetch("id", nil)
end
def inline?
- raw.key?('inline')
+ raw.key?("inline")
end
def has_parent?
- raw.key?('parent')
+ raw.key?("parent")
end
private
def inline
- raw.fetch('inline', {})
+ raw.fetch("inline", {})
end
end
end
diff --git a/lib/bitbucket/representation/repo.rb b/lib/bitbucket/representation/repo.rb
index c5bfc91e43d..78dcca4883d 100644
--- a/lib/bitbucket/representation/repo.rb
+++ b/lib/bitbucket/representation/repo.rb
@@ -10,7 +10,7 @@ module Bitbucket
end
def owner_and_slug
- @owner_and_slug ||= full_name.split('/', 2)
+ @owner_and_slug ||= full_name.split("/", 2)
end
def owner
@@ -22,7 +22,7 @@ module Bitbucket
end
def clone_url(token = nil)
- url = raw['links']['clone'].find { |link| link['name'] == 'https' }.fetch('href')
+ url = raw["links"]["clone"].find { |link| link["name"] == "https" }.fetch("href")
if token.present?
clone_url = URI.parse(url)
@@ -34,31 +34,31 @@ module Bitbucket
end
def description
- raw['description']
+ raw["description"]
end
def full_name
- raw['full_name']
+ raw["full_name"]
end
def issues_enabled?
- raw['has_issues']
+ raw["has_issues"]
end
def name
- raw['name']
+ raw["name"]
end
def valid?
- raw['scm'] == 'git'
+ raw["scm"] == "git"
end
def has_wiki?
- raw['has_wiki']
+ raw["has_wiki"]
end
def visibility_level
- if raw['is_private']
+ if raw["is_private"]
Gitlab::VisibilityLevel::PRIVATE
else
Gitlab::VisibilityLevel::PUBLIC
diff --git a/lib/bitbucket/representation/user.rb b/lib/bitbucket/representation/user.rb
index 2b45d751e70..23d7008de92 100644
--- a/lib/bitbucket/representation/user.rb
+++ b/lib/bitbucket/representation/user.rb
@@ -4,7 +4,7 @@ module Bitbucket
module Representation
class User < Representation::Base
def username
- raw['username']
+ raw["username"]
end
end
end
diff --git a/lib/bitbucket_server/client.rb b/lib/bitbucket_server/client.rb
index 6a608058813..dfe70fe4910 100644
--- a/lib/bitbucket_server/client.rb
+++ b/lib/bitbucket_server/client.rb
@@ -32,7 +32,7 @@ module BitbucketServer
payload = {
name: branch_name,
startPoint: sha,
- message: 'GitLab temporary branch for import'
+ message: "GitLab temporary branch for import",
}
connection.post("/projects/#{project_key}/repos/#{repo}/branches", payload.to_json)
@@ -41,7 +41,7 @@ module BitbucketServer
def delete_branch(project_key, repo, branch_name, sha)
payload = {
name: Gitlab::Git::BRANCH_REF_PREFIX + branch_name,
- dryRun: false
+ dryRun: false,
}
connection.delete(:branches, "/projects/#{project_key}/repos/#{repo}/branches", payload.to_json)
diff --git a/lib/bitbucket_server/collection.rb b/lib/bitbucket_server/collection.rb
index 7e4b2277bbe..2ef5d71ddaf 100644
--- a/lib/bitbucket_server/collection.rb
+++ b/lib/bitbucket_server/collection.rb
@@ -37,9 +37,9 @@ module BitbucketServer
end
def method_missing(method, *args)
- return super unless self.respond_to?(method)
+ return super unless respond_to?(method)
- self.__send__(method, *args) do |item| # rubocop:disable GitlabSecurity/PublicSend
+ __send__(method, *args) do |item| # rubocop:disable GitlabSecurity/PublicSend
block_given? ? yield(item) : item
end
end
diff --git a/lib/bitbucket_server/connection.rb b/lib/bitbucket_server/connection.rb
index fbd451efb23..272c8f9968d 100644
--- a/lib/bitbucket_server/connection.rb
+++ b/lib/bitbucket_server/connection.rb
@@ -4,8 +4,8 @@ module BitbucketServer
class Connection
include ActionView::Helpers::SanitizeHelper
- DEFAULT_API_VERSION = '1.0'
- SEPARATOR = '/'
+ DEFAULT_API_VERSION = "1.0"
+ SEPARATOR = "/"
NETWORK_ERRORS = [
SocketError,
@@ -15,7 +15,7 @@ module BitbucketServer
Errno::EHOSTUNREACH,
Net::OpenTimeout,
Net::ReadTimeout,
- Gitlab::HTTP::BlockedUrlError
+ Gitlab::HTTP::BlockedUrlError,
].freeze
attr_reader :api_version, :base_uri, :username, :token
@@ -31,9 +31,9 @@ module BitbucketServer
def get(path, extra_query = {})
response = Gitlab::HTTP.get(build_url(path),
- basic_auth: auth,
- headers: accept_headers,
- query: extra_query)
+ basic_auth: auth,
+ headers: accept_headers,
+ query: extra_query)
check_errors!(response)
@@ -44,9 +44,9 @@ module BitbucketServer
def post(path, body)
response = Gitlab::HTTP.post(build_url(path),
- basic_auth: auth,
- headers: post_headers,
- body: body)
+ basic_auth: auth,
+ headers: post_headers,
+ body: body)
check_errors!(response)
@@ -63,9 +63,9 @@ module BitbucketServer
url = delete_url(resource, path)
response = Gitlab::HTTP.delete(url,
- basic_auth: auth,
- headers: post_headers,
- body: body)
+ basic_auth: auth,
+ headers: post_headers,
+ body: body)
check_errors!(response)
@@ -82,7 +82,7 @@ module BitbucketServer
return if response.code >= 200 && response.code < 300
- details = sanitize(response.parsed_response.dig('errors', 0, 'message'))
+ details = sanitize(response.parsed_response.dig("errors", 0, "message"))
message = "Error #{response.code}"
message += ": #{details}" if details
@@ -92,15 +92,15 @@ module BitbucketServer
end
def auth
- @auth ||= { username: username, password: token }
+ @auth ||= {username: username, password: token}
end
def accept_headers
- @accept_headers ||= { 'Accept' => 'application/json' }
+ @accept_headers ||= {"Accept" => "application/json"}
end
def post_headers
- @post_headers ||= accept_headers.merge({ 'Content-Type' => 'application/json' })
+ @post_headers ||= accept_headers.merge({"Content-Type" => "application/json"})
end
def build_url(path)
diff --git a/lib/bitbucket_server/page.rb b/lib/bitbucket_server/page.rb
index 5d9a3168876..a15fe9d88ee 100644
--- a/lib/bitbucket_server/page.rb
+++ b/lib/bitbucket_server/page.rb
@@ -20,13 +20,13 @@ module BitbucketServer
private
def parse_attrs(raw)
- raw.slice('size', 'nextPageStart', 'isLastPage').symbolize_keys
+ raw.slice("size", "nextPageStart", "isLastPage").symbolize_keys
end
def parse_values(raw, bitbucket_rep_class)
- return [] unless raw['values'] && raw['values'].is_a?(Array)
+ return [] unless raw["values"]&.is_a?(Array)
- bitbucket_rep_class.decorate(raw['values'])
+ bitbucket_rep_class.decorate(raw["values"])
end
def representation_class(type)
diff --git a/lib/bitbucket_server/representation/activity.rb b/lib/bitbucket_server/representation/activity.rb
index 08bf30a5d1e..ec1e3d148f3 100644
--- a/lib/bitbucket_server/representation/activity.rb
+++ b/lib/bitbucket_server/representation/activity.rb
@@ -4,7 +4,7 @@ module BitbucketServer
module Representation
class Activity < Representation::Base
def comment?
- action == 'COMMENTED'
+ action == "COMMENTED"
end
def inline_comment?
@@ -24,25 +24,25 @@ module BitbucketServer
# TODO Move this into MergeEvent
def merge_event?
- action == 'MERGED'
+ action == "MERGED"
end
def committer_user
- commit.dig('committer', 'displayName')
+ commit.dig("committer", "displayName")
end
def committer_email
- commit.dig('committer', 'emailAddress')
+ commit.dig("committer", "emailAddress")
end
def merge_timestamp
- timestamp = commit['committerTimestamp']
+ timestamp = commit["committerTimestamp"]
self.class.convert_timestamp(timestamp)
end
def merge_commit
- commit['id']
+ commit["id"]
end
def created_at
@@ -52,19 +52,19 @@ module BitbucketServer
private
def commit
- raw.fetch('commit', {})
+ raw.fetch("commit", {})
end
def action
- raw['action']
+ raw["action"]
end
def comment_anchor
- raw['commentAnchor']
+ raw["commentAnchor"]
end
def created_date
- raw['createdDate']
+ raw["createdDate"]
end
end
end
diff --git a/lib/bitbucket_server/representation/comment.rb b/lib/bitbucket_server/representation/comment.rb
index 99b97a3b181..fdd8316cc6b 100644
--- a/lib/bitbucket_server/representation/comment.rb
+++ b/lib/bitbucket_server/representation/comment.rb
@@ -34,19 +34,19 @@ module BitbucketServer
end
def id
- raw_comment['id']
+ raw_comment["id"]
end
def author_username
- author['displayName']
+ author["displayName"]
end
def author_email
- author['emailAddress']
+ author["emailAddress"]
end
def note
- raw_comment['text']
+ raw_comment["text"]
end
def created_at
@@ -85,7 +85,7 @@ module BitbucketServer
# insert that node into the workset.
# b. Parse that note into a Comment structure and add it to a flat list.
def flatten_comments
- comments = raw_comment['comments']
+ comments = raw_comment["comments"]
workset =
if comments
[CommentNode.new(comments, self)]
@@ -100,8 +100,8 @@ module BitbucketServer
parent = node.parent
node.raw_comments.each do |comment|
- new_comments = comment.delete('comments')
- current_comment = Comment.new({ 'comment' => comment }, parent_comment: parent)
+ new_comments = comment.delete("comments")
+ current_comment = Comment.new({"comment" => comment}, parent_comment: parent)
all_comments << current_comment
workset << CommentNode.new(new_comments, current_comment) if new_comments
end
@@ -111,19 +111,19 @@ module BitbucketServer
end
def raw_comment
- raw.fetch('comment', {})
+ raw.fetch("comment", {})
end
def author
- raw_comment['author']
+ raw_comment["author"]
end
def created_date
- raw_comment['createdDate']
+ raw_comment["createdDate"]
end
def updated_date
- raw_comment['updatedDate']
+ raw_comment["updatedDate"]
end
end
end
diff --git a/lib/bitbucket_server/representation/pull_request.rb b/lib/bitbucket_server/representation/pull_request.rb
index c3e927d8de7..9475b2dff7e 100644
--- a/lib/bitbucket_server/representation/pull_request.rb
+++ b/lib/bitbucket_server/representation/pull_request.rb
@@ -4,34 +4,34 @@ module BitbucketServer
module Representation
class PullRequest < Representation::Base
def author
- raw.dig('author', 'user', 'name')
+ raw.dig("author", "user", "name")
end
def author_email
- raw.dig('author', 'user', 'emailAddress')
+ raw.dig("author", "user", "emailAddress")
end
def description
- raw['description']
+ raw["description"]
end
def iid
- raw['id']
+ raw["id"]
end
def state
- case raw['state']
- when 'MERGED'
- 'merged'
- when 'DECLINED'
- 'closed'
+ case raw["state"]
+ when "MERGED"
+ "merged"
+ when "DECLINED"
+ "closed"
else
- 'opened'
+ "opened"
end
end
def merged?
- state == 'merged'
+ state == "merged"
end
def created_at
@@ -43,33 +43,33 @@ module BitbucketServer
end
def title
- raw['title']
+ raw["title"]
end
def source_branch_name
- raw.dig('fromRef', 'id')
+ raw.dig("fromRef", "id")
end
def source_branch_sha
- raw.dig('fromRef', 'latestCommit')
+ raw.dig("fromRef", "latestCommit")
end
def target_branch_name
- raw.dig('toRef', 'id')
+ raw.dig("toRef", "id")
end
def target_branch_sha
- raw.dig('toRef', 'latestCommit')
+ raw.dig("toRef", "latestCommit")
end
private
def created_date
- raw['createdDate']
+ raw["createdDate"]
end
def updated_date
- raw['updatedDate']
+ raw["updatedDate"]
end
end
end
diff --git a/lib/bitbucket_server/representation/pull_request_comment.rb b/lib/bitbucket_server/representation/pull_request_comment.rb
index a2b3873a397..66dca57a0f8 100644
--- a/lib/bitbucket_server/representation/pull_request_comment.rb
+++ b/lib/bitbucket_server/representation/pull_request_comment.rb
@@ -19,27 +19,27 @@ module BitbucketServer
# More details in https://docs.atlassian.com/bitbucket-server/rest/5.12.0/bitbucket-rest.html.
class PullRequestComment < Comment
def from_sha
- comment_anchor['fromHash']
+ comment_anchor["fromHash"]
end
def to_sha
- comment_anchor['toHash']
+ comment_anchor["toHash"]
end
def to?
- file_type == 'TO'
+ file_type == "TO"
end
def from?
- file_type == 'FROM'
+ file_type == "FROM"
end
def added?
- line_type == 'ADDED'
+ line_type == "ADDED"
end
def removed?
- line_type == 'REMOVED'
+ line_type == "REMOVED"
end
# There are three line comment types: added, removed, or context.
@@ -63,17 +63,17 @@ module BitbucketServer
end
def file_path
- comment_anchor.fetch('path')
+ comment_anchor.fetch("path")
end
private
def file_type
- comment_anchor['fileType']
+ comment_anchor["fileType"]
end
def line_type
- comment_anchor['lineType']
+ comment_anchor["lineType"]
end
# Each comment contains the following information about the diff:
@@ -94,12 +94,12 @@ module BitbucketServer
# entries until we find this comment ID.
def line_position
@line_position ||= diff_hunks.each do |hunk|
- segments = hunk.fetch('segments', [])
+ segments = hunk.fetch("segments", [])
segments.each do |segment|
- lines = segment.fetch('lines', [])
+ lines = segment.fetch("lines", [])
lines.each do |line|
- if line['commentIds']&.include?(id)
- return [line['source'], line['destination']]
+ if line["commentIds"]&.include?(id)
+ return [line["source"], line["destination"]]
end
end
end
@@ -107,15 +107,15 @@ module BitbucketServer
end
def comment_anchor
- raw.fetch('commentAnchor', {})
+ raw.fetch("commentAnchor", {})
end
def diff
- raw.fetch('diff', {})
+ raw.fetch("diff", {})
end
def diff_hunks
- diff.fetch('hunks', [])
+ diff.fetch("hunks", [])
end
end
end
diff --git a/lib/bitbucket_server/representation/repo.rb b/lib/bitbucket_server/representation/repo.rb
index 6c494b79166..d67b11fd50b 100644
--- a/lib/bitbucket_server/representation/repo.rb
+++ b/lib/bitbucket_server/representation/repo.rb
@@ -8,29 +8,29 @@ module BitbucketServer
end
def project_key
- raw.dig('project', 'key')
+ raw.dig("project", "key")
end
def project_name
- raw.dig('project', 'name')
+ raw.dig("project", "name")
end
def slug
- raw['slug']
+ raw["slug"]
end
def browse_url
# The JSON reponse contains an array of 1 element. Not sure if there
# are cases where multiple links would be provided.
- raw.dig('links', 'self').first.fetch('href')
+ raw.dig("links", "self").first.fetch("href")
end
def clone_url
- raw['links']['clone'].find { |link| link['name'].starts_with?('http') }.fetch('href')
+ raw["links"]["clone"].find { |link| link["name"].starts_with?("http") }.fetch("href")
end
def description
- project['description']
+ project["description"]
end
def full_name
@@ -42,15 +42,15 @@ module BitbucketServer
end
def name
- raw['name']
+ raw["name"]
end
def valid?
- raw['scmId'] == 'git'
+ raw["scmId"] == "git"
end
def visibility_level
- if project['public']
+ if project["public"]
Gitlab::VisibilityLevel::PUBLIC
else
Gitlab::VisibilityLevel::PRIVATE
@@ -58,7 +58,7 @@ module BitbucketServer
end
def project
- raw['project']
+ raw["project"]
end
def to_s
diff --git a/lib/constraints/project_url_constrainer.rb b/lib/constraints/project_url_constrainer.rb
index eadfbf7bc01..a9a96ef3a00 100644
--- a/lib/constraints/project_url_constrainer.rb
+++ b/lib/constraints/project_url_constrainer.rb
@@ -5,7 +5,7 @@ module Constraints
def matches?(request)
namespace_path = request.params[:namespace_id]
project_path = request.params[:project_id] || request.params[:id]
- full_path = [namespace_path, project_path].join('/')
+ full_path = [namespace_path, project_path].join("/")
return false unless ProjectPathValidator.valid_path?(full_path)
diff --git a/lib/container_registry/blob.rb b/lib/container_registry/blob.rb
index 837b22c3082..54134fe0e68 100644
--- a/lib/container_registry/blob.rb
+++ b/lib/container_registry/blob.rb
@@ -20,19 +20,19 @@ module ContainerRegistry
end
def digest
- config['digest'] || config['blobSum']
+ config["digest"] || config["blobSum"]
end
def type
- config['mediaType']
+ config["mediaType"]
end
def size
- config['size']
+ config["size"]
end
def revision
- digest.split(':')[1]
+ digest.split(":")[1]
end
def short_revision
diff --git a/lib/container_registry/client.rb b/lib/container_registry/client.rb
index c80f49f5ae0..52c92bc694b 100644
--- a/lib/container_registry/client.rb
+++ b/lib/container_registry/client.rb
@@ -1,13 +1,13 @@
# frozen_string_literal: true
-require 'faraday'
-require 'faraday_middleware'
+require "faraday"
+require "faraday_middleware"
module ContainerRegistry
class Client
attr_accessor :uri
- MANIFEST_VERSION = 'application/vnd.docker.distribution.manifest.v2+json'.freeze
+ MANIFEST_VERSION = "application/vnd.docker.distribution.manifest.v2+json"
# Taken from: FaradayMiddleware::FollowRedirects
REDIRECT_CODES = Set.new [301, 302, 303, 307]
@@ -27,7 +27,7 @@ module ContainerRegistry
def repository_tag_digest(name, reference)
response = faraday.head("/v2/#{name}/manifests/#{reference}")
- response.headers['docker-content-digest'] if response.success?
+ response.headers["docker-content-digest"] if response.success?
end
def delete_repository_tag(name, reference)
@@ -35,8 +35,8 @@ module ContainerRegistry
end
def blob(name, digest, type = nil)
- type ||= 'application/octet-stream'
- response_body faraday_blob.get("/v2/#{name}/blobs/#{digest}", nil, 'Accept' => type), allow_redirect: true
+ type ||= "application/octet-stream"
+ response_body faraday_blob.get("/v2/#{name}/blobs/#{digest}", nil, "Accept" => type), allow_redirect: true
end
def delete_blob(name, digest)
@@ -60,20 +60,20 @@ module ContainerRegistry
end
def accept_manifest(conn)
- conn.headers['Accept'] = MANIFEST_VERSION
+ conn.headers["Accept"] = MANIFEST_VERSION
- conn.response :json, content_type: 'application/json'
- conn.response :json, content_type: 'application/vnd.docker.distribution.manifest.v1+prettyjws'
- conn.response :json, content_type: 'application/vnd.docker.distribution.manifest.v1+json'
- conn.response :json, content_type: 'application/vnd.docker.distribution.manifest.v2+json'
+ conn.response :json, content_type: "application/json"
+ conn.response :json, content_type: "application/vnd.docker.distribution.manifest.v1+prettyjws"
+ conn.response :json, content_type: "application/vnd.docker.distribution.manifest.v1+json"
+ conn.response :json, content_type: "application/vnd.docker.distribution.manifest.v2+json"
end
def response_body(response, allow_redirect: false)
if allow_redirect && REDIRECT_CODES.include?(response.status)
- response = redirect_response(response.headers['location'])
+ response = redirect_response(response.headers["location"])
end
- response.body if response && response.success?
+ response.body if response&.success?
end
def redirect_response(location)
@@ -83,24 +83,24 @@ module ContainerRegistry
end
def faraday
- @faraday ||= Faraday.new(@base_uri) do |conn|
+ @faraday ||= Faraday.new(@base_uri) { |conn|
initialize_connection(conn, @options, &method(:accept_manifest))
- end
+ }
end
def faraday_blob
- @faraday_blob ||= Faraday.new(@base_uri) do |conn|
+ @faraday_blob ||= Faraday.new(@base_uri) { |conn|
initialize_connection(conn, @options)
- end
+ }
end
# Create a new request to make sure the Authorization header is not inserted
# via the Faraday middleware
def faraday_redirect
- @faraday_redirect ||= Faraday.new(@base_uri) do |conn|
+ @faraday_redirect ||= Faraday.new(@base_uri) { |conn|
conn.request :json
conn.adapter :net_http
- end
+ }
end
end
end
diff --git a/lib/container_registry/path.rb b/lib/container_registry/path.rb
index 9b2a61cdedc..b9cc49cb379 100644
--- a/lib/container_registry/path.rb
+++ b/lib/container_registry/path.rb
@@ -27,16 +27,16 @@ module ContainerRegistry
end
def components
- @components ||= @path.split('/')
+ @components ||= @path.split("/")
end
# rubocop: disable CodeReuse/ActiveRecord
def nodes
raise InvalidRegistryPathError unless valid?
- @nodes ||= components.size.downto(2).map do |length|
- components.take(length).join('/')
- end
+ @nodes ||= components.size.downto(2).map { |length|
+ components.take(length).join("/")
+ }
end
# rubocop: enable CodeReuse/ActiveRecord
@@ -66,7 +66,7 @@ module ContainerRegistry
def repository_name
return unless has_project?
- @path.remove(%r(^#{Regexp.escape(project_path)}/?))
+ @path.remove(%r{^#{Regexp.escape(project_path)}/?})
end
def project_path
diff --git a/lib/container_registry/registry.rb b/lib/container_registry/registry.rb
index 523364ac7c7..c69dc0c5842 100644
--- a/lib/container_registry/registry.rb
+++ b/lib/container_registry/registry.rb
@@ -13,7 +13,7 @@ module ContainerRegistry
private
def default_path
- @uri.sub(%r{^https?://}, '')
+ @uri.sub(%r{^https?://}, "")
end
end
end
diff --git a/lib/container_registry/tag.rb b/lib/container_registry/tag.rb
index ef41dc560c9..0da4072367b 100644
--- a/lib/container_registry/tag.rb
+++ b/lib/container_registry/tag.rb
@@ -22,11 +22,11 @@ module ContainerRegistry
end
def v1?
- manifest && manifest['schemaVersion'] == 1
+ manifest && manifest["schemaVersion"] == 1
end
def v2?
- manifest && manifest['schemaVersion'] == 2
+ manifest && manifest["schemaVersion"] == 2
end
def manifest
@@ -56,10 +56,10 @@ module ContainerRegistry
end
def config_blob
- return unless manifest && manifest['config']
+ return unless manifest && manifest["config"]
strong_memoize(:config_blob) do
- repository.blob(manifest['config'])
+ repository.blob(manifest["config"])
end
end
@@ -75,7 +75,7 @@ module ContainerRegistry
return unless config
strong_memoize(:created_at) do
- DateTime.rfc3339(config['created'])
+ DateTime.rfc3339(config["created"])
end
end
@@ -83,7 +83,7 @@ module ContainerRegistry
return unless manifest
strong_memoize(:layers) do
- layers = manifest['layers'] || manifest['fsLayers']
+ layers = manifest["layers"] || manifest["fsLayers"]
layers.map do |layer|
repository.blob(layer)
diff --git a/lib/declarative_policy.rb b/lib/declarative_policy.rb
index 7ba48ae9c79..354db90ba3d 100644
--- a/lib/declarative_policy.rb
+++ b/lib/declarative_policy.rb
@@ -1,16 +1,16 @@
# frozen_string_literal: true
-require_dependency 'declarative_policy/cache'
-require_dependency 'declarative_policy/condition'
-require_dependency 'declarative_policy/delegate_dsl'
-require_dependency 'declarative_policy/policy_dsl'
-require_dependency 'declarative_policy/rule_dsl'
-require_dependency 'declarative_policy/preferred_scope'
-require_dependency 'declarative_policy/rule'
-require_dependency 'declarative_policy/runner'
-require_dependency 'declarative_policy/step'
-
-require_dependency 'declarative_policy/base'
+require_dependency "declarative_policy/cache"
+require_dependency "declarative_policy/condition"
+require_dependency "declarative_policy/delegate_dsl"
+require_dependency "declarative_policy/policy_dsl"
+require_dependency "declarative_policy/rule_dsl"
+require_dependency "declarative_policy/preferred_scope"
+require_dependency "declarative_policy/rule"
+require_dependency "declarative_policy/runner"
+require_dependency "declarative_policy/step"
+
+require_dependency "declarative_policy/base"
module DeclarativePolicy
CLASS_CACHE_MUTEX = Mutex.new
@@ -25,9 +25,9 @@ module DeclarativePolicy
# to avoid deadlocks in multi-threaded environment when
# autoloading is enabled, we allow concurrent loads,
# https://gitlab.com/gitlab-org/gitlab-ce/issues/48263
- ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
+ ActiveSupport::Dependencies.interlock.permit_concurrent_loads {
class_for(subject).new(user, subject, opts)
- end
+ }
end
def class_for(subject)
diff --git a/lib/declarative_policy/base.rb b/lib/declarative_policy/base.rb
index cd6e1606f22..3386f2935c2 100644
--- a/lib/declarative_policy/base.rb
+++ b/lib/declarative_policy/base.rb
@@ -165,7 +165,7 @@ module DeclarativePolicy
condition = Condition.new(name, opts, &value)
- self.own_conditions[name] = condition
+ own_conditions[name] = condition
define_method(:"#{name}?") { condition(name).pass? }
end
@@ -308,14 +308,14 @@ module DeclarativePolicy
# A list of other policies that we've delegated to (see `Base.delegate`)
def delegated_policies
- @delegated_policies ||= self.class.delegations.transform_values do |block|
+ @delegated_policies ||= self.class.delegations.transform_values { |block|
new_subject = instance_eval(&block)
# never delegate to nil, as that would immediately prevent_all
next if new_subject.nil?
policy_for(new_subject)
- end
+ }
end
def policy_for(other_subject)
diff --git a/lib/declarative_policy/cache.rb b/lib/declarative_policy/cache.rb
index 13006e56454..e51d6aa8851 100644
--- a/lib/declarative_policy/cache.rb
+++ b/lib/declarative_policy/cache.rb
@@ -4,7 +4,7 @@ module DeclarativePolicy
module Cache
class << self
def user_key(user)
- return '<anonymous>' if user.nil?
+ return "<anonymous>" if user.nil?
id_for(user)
end
@@ -16,7 +16,7 @@ module DeclarativePolicy
end
def subject_key(subject)
- return '<nil>' if subject.nil?
+ return "<nil>" if subject.nil?
return subject.inspect if subject.is_a?(Symbol)
"#{subject.class.name}:#{id_for(subject)}"
diff --git a/lib/declarative_policy/condition.rb b/lib/declarative_policy/condition.rb
index b77f40b1093..a0e4aa6facf 100644
--- a/lib/declarative_policy/condition.rb
+++ b/lib/declarative_policy/condition.rb
@@ -90,7 +90,7 @@ module DeclarativePolicy
when :user then "/dp/condition/#{@condition.key}/#{user_key}"
when :subject then "/dp/condition/#{@condition.key}/#{subject_key}"
when :global then "/dp/condition/#{@condition.key}"
- else raise 'invalid scope'
+ else raise "invalid scope"
end
end
diff --git a/lib/declarative_policy/rule.rb b/lib/declarative_policy/rule.rb
index f38f4f0a50f..dd3d13bc5a0 100644
--- a/lib/declarative_policy/rule.rb
+++ b/lib/declarative_policy/rule.rb
@@ -18,20 +18,20 @@ module DeclarativePolicy
# `context` is a policy - an instance of
# DeclarativePolicy::Base.
def pass?(context)
- raise 'abstract'
+ raise "abstract"
end
# same as #pass? except refuses to do any I/O,
# returning nil if the result is not yet cached.
# used for accurately scoring And/Or
def cached_pass?(context)
- raise 'abstract'
+ raise "abstract"
end
# abstractly, how long would it take to compute
# this rule? lower-scored rules are tried first.
def score(context)
- raise 'abstract'
+ raise "abstract"
end
# unwrap double negatives and nested and/or
@@ -52,9 +52,9 @@ module DeclarativePolicy
Not.make(self)
end
- alias_method :|, :or
- alias_method :&, :and
- alias_method :~@, :negate
+ alias | or
+ alias & and
+ alias ~ negate
def inspect
"#<Rule #{repr}>"
@@ -184,13 +184,13 @@ module DeclarativePolicy
end
def simplify
- simplified_rules = @rules.flat_map do |rule|
+ simplified_rules = @rules.flat_map { |rule|
simplified = rule.simplify
case simplified
when And then simplified.rules
else [simplified]
end
- end
+ }
And.new(simplified_rules)
end
@@ -222,7 +222,7 @@ module DeclarativePolicy
end
def repr
- "all?(#{rules.map(&:repr).join(', ')})"
+ "all?(#{rules.map(&:repr).join(", ")})"
end
end
@@ -241,13 +241,13 @@ module DeclarativePolicy
end
def simplify
- simplified_rules = @rules.flat_map do |rule|
+ simplified_rules = @rules.flat_map { |rule|
simplified = rule.simplify
case simplified
when Or then simplified.rules
else [simplified]
end
- end
+ }
Or.new(simplified_rules)
end
@@ -269,7 +269,7 @@ module DeclarativePolicy
end
def repr
- "any?(#{@rules.map(&:repr).join(', ')})"
+ "any?(#{@rules.map(&:repr).join(", ")})"
end
end
diff --git a/lib/declarative_policy/runner.rb b/lib/declarative_policy/runner.rb
index f739fe5e16e..fd17b1a2b5f 100644
--- a/lib/declarative_policy/runner.rb
+++ b/lib/declarative_policy/runner.rb
@@ -184,9 +184,9 @@ module DeclarativePolicy
def inspect_step(step, original_score, passed)
symbol =
case passed
- when true then '+'
- when false then '-'
- when nil then ' '
+ when true then "+"
+ when false then "-"
+ when nil then " "
end
"#{symbol} [#{original_score.to_i}] #{step.repr}\n"
diff --git a/lib/event_filter.rb b/lib/event_filter.rb
index 24fdcd6fbb1..015b27a5a4c 100644
--- a/lib/event_filter.rb
+++ b/lib/event_filter.rb
@@ -3,17 +3,17 @@
class EventFilter
attr_accessor :filter
- ALL = 'all'
- PUSH = 'push'
- MERGED = 'merged'
- ISSUE = 'issue'
- COMMENTS = 'comments'
- TEAM = 'team'
+ ALL = "all"
+ PUSH = "push"
+ MERGED = "merged"
+ ISSUE = "issue"
+ COMMENTS = "comments"
+ TEAM = "team"
FILTERS = [ALL, PUSH, MERGED, ISSUE, COMMENTS, TEAM].freeze
def initialize(filter)
# Split using comma to maintain backward compatibility Ex/ "filter1,filter2"
- filter = filter.to_s.split(',')[0].to_s
+ filter = filter.to_s.split(",")[0].to_s
@filter = FILTERS.include?(filter) ? filter : ALL
end
diff --git a/lib/expand_variables.rb b/lib/expand_variables.rb
index c83cec9dc4a..ff97a02ebde 100644
--- a/lib/expand_variables.rb
+++ b/lib/expand_variables.rb
@@ -5,10 +5,9 @@ module ExpandVariables
def expand(value, variables)
# Convert hash array to variables
if variables.is_a?(Array)
- variables = variables.reduce({}) do |hash, variable|
+ variables = variables.each_with_object({}) { |variable, hash|
hash[variable[:key]] = variable[:value]
- hash
- end
+ }
end
value.gsub(/\$([a-zA-Z_][a-zA-Z0-9_]*)|\${\g<1>}|%\g<1>%/) do
diff --git a/lib/extracts_path.rb b/lib/extracts_path.rb
index b2c8d46ede1..3432c0a7850 100644
--- a/lib/extracts_path.rb
+++ b/lib/extracts_path.rb
@@ -40,7 +40,7 @@ module ExtractsPath
# Returns an Array where the first value is the tree-ish and the second is the
# path
def extract_ref(id)
- pair = ['', '']
+ pair = ["", ""]
return pair unless @project # rubocop:disable Gitlab/ModuleWithInstanceVariables
@@ -52,8 +52,8 @@ module ExtractsPath
# branches and tags
# Append a trailing slash if we only get a ref and no file path
- unless id.ends_with?('/')
- id = [id, '/'].join
+ unless id.ends_with?("/")
+ id = [id, "/"].join
end
valid_refs = ref_names.select { |v| id.start_with?("#{v}/") }
@@ -72,7 +72,7 @@ module ExtractsPath
end
# Remove ending slashes from path
- pair[1].gsub!(%r{^/|/$}, '')
+ pair[1].gsub!(%r{^/|/$}, "")
pair
end
@@ -84,7 +84,7 @@ module ExtractsPath
# match, so it is possible to create a branch which has an unroutable Atom
# feed.
def extract_ref_without_atom(id)
- id_without_atom = id.sub(/\.atom$/, '')
+ id_without_atom = id.sub(/\.atom$/, "")
valid_refs = ref_names.select { |v| "#{id_without_atom}/".start_with?("#{v}/") }
valid_refs.max_by(&:length)
@@ -116,7 +116,7 @@ module ExtractsPath
@commit = @repo.commit(@ref)
- if @path.empty? && !@commit && @id.ends_with?('.atom')
+ if @path.empty? && !@commit && @id.ends_with?(".atom")
@id = @ref = extract_ref_without_atom(@id)
@commit = @repo.commit(@ref)
diff --git a/lib/feature.rb b/lib/feature.rb
index 749c861d740..8623bf35f31 100644
--- a/lib/feature.rb
+++ b/lib/feature.rb
@@ -1,13 +1,13 @@
# frozen_string_literal: true
-require 'flipper/adapters/active_record'
-require 'flipper/adapters/active_support_cache_store'
+require "flipper/adapters/active_record"
+require "flipper/adapters/active_support_cache_store"
class Feature
# Classes to override flipper table names
class FlipperFeature < Flipper::Adapters::ActiveRecord::Feature
# Using `self.table_name` won't work. ActiveRecord bug?
- superclass.table_name = 'features'
+ superclass.table_name = "features"
def self.feature_names
pluck(:key)
@@ -15,7 +15,7 @@ class Feature
end
class FlipperGate < Flipper::Adapters::ActiveRecord::Gate
- superclass.table_name = 'feature_gates'
+ superclass.table_name = "feature_gates"
end
class << self
@@ -94,12 +94,14 @@ class Feature
def flipper_adapter
active_record_adapter = Flipper::Adapters::ActiveRecord.new(
feature_class: FlipperFeature,
- gate_class: FlipperGate)
+ gate_class: FlipperGate
+ )
Flipper::Adapters::ActiveSupportCacheStore.new(
active_record_adapter,
Rails.cache,
- expires_in: 1.hour)
+ expires_in: 1.hour
+ )
end
end
@@ -111,7 +113,7 @@ class Feature
end
def gate_specified?
- %i(user project group feature_group).any? { |key| params.key?(key) }
+ %i[user project group feature_group].any? { |key| params.key?(key) }
end
def targets
diff --git a/lib/file_size_validator.rb b/lib/file_size_validator.rb
index 70a145cd5bd..fcf648796e9 100644
--- a/lib/file_size_validator.rb
+++ b/lib/file_size_validator.rb
@@ -1,10 +1,10 @@
# frozen_string_literal: true
class FileSizeValidator < ActiveModel::EachValidator
- MESSAGES = { is: :wrong_size, minimum: :size_too_small, maximum: :size_too_big }.freeze
- CHECKS = { is: :==, minimum: :>=, maximum: :<= }.freeze
+ MESSAGES = {is: :wrong_size, minimum: :size_too_small, maximum: :size_too_big}.freeze
+ CHECKS = {is: :==, minimum: :>=, maximum: :<=}.freeze
- DEFAULT_TOKENIZER = -> (value) { value.split(//) }.freeze
+ DEFAULT_TOKENIZER = ->(value) { value.split(//) }.freeze
RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long].freeze
def initialize(options)
@@ -22,7 +22,7 @@ class FileSizeValidator < ActiveModel::EachValidator
keys = CHECKS.keys & options.keys
if keys.empty?
- raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
+ raise ArgumentError, "Range unspecified. Specify the :within, :maximum, :minimum, or :is option."
end
keys.each do |key|
diff --git a/lib/flowdock/git.rb b/lib/flowdock/git.rb
index f165ecfc1fa..be36f4c662f 100644
--- a/lib/flowdock/git.rb
+++ b/lib/flowdock/git.rb
@@ -1,13 +1,14 @@
# frozen_string_literal: true
-require 'flowdock'
-require 'flowdock/git/builder'
+
+require "flowdock"
+require "flowdock/git/builder"
module Flowdock
class Git
TokenError = Class.new(StandardError)
DEFAULT_PERMANENT_REFS = [
- Regexp.new('refs/heads/master')
+ Regexp.new("refs/heads/master"),
].freeze
class << self
@@ -55,8 +56,7 @@ module Flowdock
repo_url: @repo_url,
repo_name: @repo_name,
permanent_refs: @permanent_refs,
- tags: tags
- ).to_hashes
+ tags: tags).to_hashes
end
# Flowdock tags attached to the push notification
diff --git a/lib/flowdock/git/builder.rb b/lib/flowdock/git/builder.rb
index 6f4428d1f42..46513e19fd4 100644
--- a/lib/flowdock/git/builder.rb
+++ b/lib/flowdock/git/builder.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
module Flowdock
class Git
class Commit
@@ -15,11 +16,11 @@ module Flowdock
event: "activity",
author: {
name: @commit[:author][:name],
- email: @commit[:author][:email]
+ email: @commit[:author][:email],
},
title: title,
thread: @thread,
- body: body
+ body: body,
}
hash[:tags] = @tags if @tags
encode(hash)
@@ -52,7 +53,7 @@ module Flowdock
def body
content = @commit[:message][first_line.size..-1]
- content.strip! if content
+ content&.strip!
"<pre>#{content}</pre>" unless content.empty?
end
@@ -94,14 +95,14 @@ module Flowdock
message: commit.message,
author: {
name: commit.author_name,
- email: commit.author_email
- }
+ email: commit.author_email,
+ },
}
end
end
def ref_name
- @ref.to_s.sub(%r{\Arefs/(heads|tags)/}, '')
+ @ref.to_s.sub(%r{\Arefs/(heads|tags)/}, "")
end
def to_hashes
@@ -115,7 +116,7 @@ module Flowdock
def thread
@thread ||= {
title: thread_title,
- external_url: @opts[:repo_url]
+ external_url: @opts[:repo_url],
}
end
@@ -127,7 +128,7 @@ module Flowdock
def thread_title
action = "updated" if permanent?
- type = @ref =~ %r(^refs/heads/) ? "branch" : "tag"
+ type = %r{^refs/heads/}.match?(@ref) ? "branch" : "tag"
[@opts[:repo_name], type, ref_name, action].compact.join(" ")
end
diff --git a/lib/forever.rb b/lib/forever.rb
index 0a37118fe68..5a4ff22fb62 100644
--- a/lib/forever.rb
+++ b/lib/forever.rb
@@ -2,7 +2,7 @@
class Forever
POSTGRESQL_DATE = DateTime.new(3000, 1, 1)
- MYSQL_DATE = DateTime.new(2038, 01, 19)
+ MYSQL_DATE = DateTime.new(2038, 0o1, 19)
# MySQL timestamp has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC
def self.date
diff --git a/lib/generators/rails/post_deployment_migration/post_deployment_migration_generator.rb b/lib/generators/rails/post_deployment_migration/post_deployment_migration_generator.rb
index 15cdd25e711..a68bde5f50c 100644
--- a/lib/generators/rails/post_deployment_migration/post_deployment_migration_generator.rb
+++ b/lib/generators/rails/post_deployment_migration/post_deployment_migration_generator.rb
@@ -1,11 +1,11 @@
# frozen_string_literal: true
-require 'rails/generators'
+require "rails/generators"
module Rails
class PostDeploymentMigrationGenerator < Rails::Generators::NamedBase
def create_migration_file
- timestamp = Time.now.strftime('%Y%m%d%H%M%S')
+ timestamp = Time.now.strftime("%Y%m%d%H%M%S")
template "migration.rb", "db/post_migrate/#{timestamp}_#{file_name}.rb"
end
diff --git a/lib/gitaly/server.rb b/lib/gitaly/server.rb
index 7b238623418..6ebe36c8189 100644
--- a/lib/gitaly/server.rb
+++ b/lib/gitaly/server.rb
@@ -54,7 +54,7 @@ module Gitaly
Gitlab::GitalyClient::ServerService.new(@storage).info
rescue GRPC::Unavailable, GRPC::DeadlineExceeded
# This will show the server as being out of date
- Gitaly::ServerInfoResponse.new(git_version: '', server_version: '', storage_statuses: [])
+ Gitaly::ServerInfoResponse.new(git_version: "", server_version: "", storage_statuses: [])
end
end
end
diff --git a/lib/gitlab.rb b/lib/gitlab.rb
index e073450283b..b90121c0254 100644
--- a/lib/gitlab.rb
+++ b/lib/gitlab.rb
@@ -1,10 +1,10 @@
# frozen_string_literal: true
-require_dependency 'gitlab/popen'
+require_dependency "gitlab/popen"
module Gitlab
def self.root
- Pathname.new(File.expand_path('..', __dir__))
+ Pathname.new(File.expand_path("..", __dir__))
end
def self.version_info
@@ -12,7 +12,7 @@ module Gitlab
end
def self.pre_release?
- VERSION.include?('pre')
+ VERSION.include?("pre")
end
def self.config
@@ -29,13 +29,13 @@ module Gitlab
if result.status.success?
result.stdout.chomp.freeze
else
- "Unknown".freeze
+ "Unknown"
end
end
end
end
- COM_URL = 'https://gitlab.com'.freeze
+ COM_URL = "https://gitlab.com"
APP_DIRS_PATTERN = %r{^/?(app|config|ee|lib|spec|\(\w*\))}
SUBDOMAIN_REGEX = %r{\Ahttps://[a-z0-9]+\.gitlab\.com\z}
VERSION = File.read(root.join("VERSION")).strip.freeze
@@ -47,7 +47,7 @@ module Gitlab
end
def self.org?
- Gitlab.config.gitlab.url == 'https://dev.gitlab.org'
+ Gitlab.config.gitlab.url == "https://dev.gitlab.org"
end
def self.gl_subdomain?
@@ -59,10 +59,10 @@ module Gitlab
end
def self.process_name
- return 'sidekiq' if Sidekiq.server?
- return 'console' if defined?(Rails::Console)
- return 'test' if Rails.env.test?
+ return "sidekiq" if Sidekiq.server?
+ return "console" if defined?(Rails::Console)
+ return "test" if Rails.env.test?
- 'web'
+ "web"
end
end
diff --git a/lib/gitlab/access.rb b/lib/gitlab/access.rb
index ec090aea784..391ac9ab2cf 100644
--- a/lib/gitlab/access.rb
+++ b/lib/gitlab/access.rb
@@ -33,10 +33,10 @@ module Gitlab
def options
{
- "Guest" => GUEST,
- "Reporter" => REPORTER,
- "Developer" => DEVELOPER,
- "Maintainer" => MAINTAINER
+ "Guest" => GUEST,
+ "Reporter" => REPORTER,
+ "Developer" => DEVELOPER,
+ "Maintainer" => MAINTAINER,
}
end
@@ -48,10 +48,10 @@ module Gitlab
def sym_options
{
- guest: GUEST,
- reporter: REPORTER,
- developer: DEVELOPER,
- maintainer: MAINTAINER
+ guest: GUEST,
+ reporter: REPORTER,
+ developer: DEVELOPER,
+ maintainer: MAINTAINER,
}
end
@@ -64,7 +64,7 @@ module Gitlab
"Not protected: Both developers and maintainers can push new commits, force push, or delete the branch." => PROTECTION_NONE,
"Protected against pushes: Developers cannot push new commits, but are allowed to accept merge requests to the branch. Maintainers can push to the branch." => PROTECTION_DEV_CAN_MERGE,
"Partially protected: Both developers and maintainers can push new commits, but cannot force push or delete the branch." => PROTECTION_DEV_CAN_PUSH,
- "Fully protected: Developers cannot push new commits, but maintainers can. No-one can force push or delete the branch." => PROTECTION_FULL
+ "Fully protected: Developers cannot push new commits, but maintainers can. No-one can force push or delete the branch." => PROTECTION_FULL,
}
end
diff --git a/lib/gitlab/action_rate_limiter.rb b/lib/gitlab/action_rate_limiter.rb
index c442211e073..f16d14b96c9 100644
--- a/lib/gitlab/action_rate_limiter.rb
+++ b/lib/gitlab/action_rate_limiter.rb
@@ -36,7 +36,7 @@ module Gitlab
# key - An array of ActiveRecord instances
# threshold_value - The maximum number of times this action should occur in the given time interval
def throttled?(key, threshold_value)
- self.increment(key) > threshold_value
+ increment(key) > threshold_value
end
private
diff --git a/lib/gitlab/app_logger.rb b/lib/gitlab/app_logger.rb
index 5edec8b3efe..62296f075be 100644
--- a/lib/gitlab/app_logger.rb
+++ b/lib/gitlab/app_logger.rb
@@ -3,7 +3,7 @@
module Gitlab
class AppLogger < Gitlab::Logger
def self.file_name_noext
- 'application'
+ "application"
end
def format_message(severity, timestamp, progname, msg)
diff --git a/lib/gitlab/asciidoc.rb b/lib/gitlab/asciidoc.rb
index df8f0470063..cfa3053886d 100644
--- a/lib/gitlab/asciidoc.rb
+++ b/lib/gitlab/asciidoc.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'asciidoctor'
-require 'asciidoctor/converter/html5'
+require "asciidoctor"
+require "asciidoctor/converter/html5"
require "asciidoctor-plantuml"
module Gitlab
@@ -9,9 +9,9 @@ module Gitlab
# the resulting HTML through HTML pipeline filters.
module Asciidoc
DEFAULT_ADOC_ATTRS = [
- 'showtitle', 'idprefix=user-content-', 'idseparator=-', 'env=gitlab',
- 'env-gitlab', 'source-highlighter=html-pipeline', 'icons=font',
- 'outfilesuffix=.adoc'
+ "showtitle", "idprefix=user-content-", "idseparator=-", "env=gitlab",
+ "env-gitlab", "source-highlighter=html-pipeline", "icons=font",
+ "outfilesuffix=.adoc",
].freeze
# Public: Converts the provided Asciidoc markup into HTML.
@@ -19,9 +19,9 @@ module Gitlab
# input - the source text in Asciidoc format
#
def self.render(input, context)
- asciidoc_opts = { safe: :secure,
- backend: :gitlab_html5,
- attributes: DEFAULT_ADOC_ATTRS }
+ asciidoc_opts = {safe: :secure,
+ backend: :gitlab_html5,
+ attributes: DEFAULT_ADOC_ATTRS,}
context[:pipeline] = :ascii_doc
@@ -44,7 +44,7 @@ module Gitlab
class Html5Converter < Asciidoctor::Converter::Html5Converter
extend Asciidoctor::Converter::Config
- register_for 'gitlab_html5'
+ register_for "gitlab_html5"
def stem(node)
return super unless node.style.to_sym == :latexmath
diff --git a/lib/gitlab/audit_json_logger.rb b/lib/gitlab/audit_json_logger.rb
index 12e0645f3e4..e9a41c0c746 100644
--- a/lib/gitlab/audit_json_logger.rb
+++ b/lib/gitlab/audit_json_logger.rb
@@ -3,7 +3,7 @@
module Gitlab
class AuditJsonLogger < Gitlab::JsonLogger
def self.file_name_noext
- 'audit_json'
+ "audit_json"
end
end
end
diff --git a/lib/gitlab/auth.rb b/lib/gitlab/auth.rb
index b2ef04d23d7..fedbbaf6bb1 100644
--- a/lib/gitlab/auth.rb
+++ b/lib/gitlab/auth.rb
@@ -65,7 +65,7 @@ module Gitlab
authenticators = []
if user
- authenticators << Gitlab::Auth::OAuth::Provider.authentication(user, 'database')
+ authenticators << Gitlab::Auth::OAuth::Provider.authentication(user, "database")
# Add authenticators for all identities if user is not nil
user&.identities&.each do |identity|
@@ -119,14 +119,14 @@ module Gitlab
return unless project && matched_login.present?
- underscored_service = matched_login['service'].underscore
+ underscored_service = matched_login["service"].underscore
if Service.available_services_names.include?(underscored_service)
# We treat underscored_service as a trusted input because it is included
# in the Service.available_services_names whitelist.
service = project.public_send("#{underscored_service}_service") # rubocop:disable GitlabSecurity/PublicSend
- if service && service.activated? && service.valid_token?(password)
+ if service&.activated? && service&.valid_token?(password)
Gitlab::Auth::Result.new(nil, project, :ci, build_authentication_abilities)
end
end
@@ -157,7 +157,7 @@ module Gitlab
def personal_access_token_check(password)
return unless password.present?
- token = PersonalAccessTokensFinder.new(state: 'active').find_by_token(password)
+ token = PersonalAccessTokensFinder.new(state: "active").find_by_token(password)
if token && valid_scoped_token?(token, available_scopes)
Gitlab::Auth::Result.new(token.user, nil, :personal_access_token, abilities_for_scopes(token.scopes))
@@ -165,7 +165,7 @@ module Gitlab
end
def valid_oauth_token?(token)
- token && token.accessible? && valid_scoped_token?(token, [:api])
+ token&.accessible? && valid_scoped_token?(token, [:api])
end
def valid_scoped_token?(token, scopes)
@@ -176,12 +176,12 @@ module Gitlab
abilities_by_scope = {
api: full_authentication_abilities,
read_registry: [:read_container_image],
- read_repository: [:download_code]
+ read_repository: [:download_code],
}
- scopes.flat_map do |scope|
+ scopes.flat_map { |scope|
abilities_by_scope.fetch(scope.to_sym, [])
- end.uniq
+ }.uniq
end
# rubocop: disable CodeReuse/ActiveRecord
@@ -231,7 +231,7 @@ module Gitlab
end
def build_access_token_check(login, password)
- return unless login == 'gitlab-ci-token'
+ return unless login == "gitlab-ci-token"
return unless password
build = find_build_by_token(password)
@@ -254,7 +254,7 @@ module Gitlab
:read_project,
:build_download_code,
:build_read_container_image,
- :build_create_container_image
+ :build_create_container_image,
]
end
@@ -262,20 +262,20 @@ module Gitlab
[
:read_project,
:download_code,
- :read_container_image
+ :read_container_image,
]
end
def read_write_authentication_abilities
read_authentication_abilities + [
:push_code,
- :create_container_image
+ :create_container_image,
]
end
def full_authentication_abilities
read_write_authentication_abilities + [
- :admin_container_image
+ :admin_container_image,
]
end
diff --git a/lib/gitlab/auth/activity.rb b/lib/gitlab/auth/activity.rb
index 558628b5422..d48b3d61501 100644
--- a/lib/gitlab/auth/activity.rb
+++ b/lib/gitlab/auth/activity.rb
@@ -9,15 +9,15 @@ module Gitlab
extend Gitlab::Utils::StrongMemoize
COUNTERS = {
- user_authenticated: 'Counter of successful authentication events',
- user_unauthenticated: 'Counter of authentication failures',
- user_not_found: 'Counter of failed log-ins when user is unknown',
- user_password_invalid: 'Counter of failed log-ins with invalid password',
- user_session_override: 'Counter of manual log-ins and sessions overrides',
- user_session_destroyed: 'Counter of user sessions being destroyed',
- user_two_factor_authenticated: 'Counter of two factor authentications',
- user_sessionless_authentication: 'Counter of sessionless authentications',
- user_blocked: 'Counter of sign in attempts when user is blocked'
+ user_authenticated: "Counter of successful authentication events",
+ user_unauthenticated: "Counter of authentication failures",
+ user_not_found: "Counter of failed log-ins when user is unknown",
+ user_password_invalid: "Counter of failed log-ins with invalid password",
+ user_session_override: "Counter of manual log-ins and sessions overrides",
+ user_session_destroyed: "Counter of user sessions being destroyed",
+ user_two_factor_authenticated: "Counter of two factor authentications",
+ user_sessionless_authentication: "Counter of sessionless authentications",
+ user_blocked: "Counter of sign in attempts when user is blocked",
}.freeze
def initialize(opts)
diff --git a/lib/gitlab/auth/blocked_user_tracker.rb b/lib/gitlab/auth/blocked_user_tracker.rb
index 50712d7eac2..fbed4af0525 100644
--- a/lib/gitlab/auth/blocked_user_tracker.rb
+++ b/lib/gitlab/auth/blocked_user_tracker.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
module Gitlab
module Auth
class BlockedUserTracker
diff --git a/lib/gitlab/auth/ip_rate_limiter.rb b/lib/gitlab/auth/ip_rate_limiter.rb
index 81e616fa20a..8bc2141e804 100644
--- a/lib/gitlab/auth/ip_rate_limiter.rb
+++ b/lib/gitlab/auth/ip_rate_limiter.rb
@@ -20,10 +20,10 @@ module Gitlab
def register_fail!
# Allow2Ban.filter will return false if this IP has not failed too often yet
- @banned = Rack::Attack::Allow2Ban.filter(ip, config) do
+ @banned = Rack::Attack::Allow2Ban.filter(ip, config) {
# If we return false here, the failure for this IP is ignored by Allow2Ban
ip_can_be_banned?
- end
+ }
end
def banned?
diff --git a/lib/gitlab/auth/ldap/access.rb b/lib/gitlab/auth/ldap/access.rb
index c875bba4bcb..bb3be78d527 100644
--- a/lib/gitlab/auth/ldap/access.rb
+++ b/lib/gitlab/auth/ldap/access.rb
@@ -12,12 +12,12 @@ module Gitlab
def self.open(user, &block)
Gitlab::Auth::LDAP::Adapter.open(user.ldap_identity.provider) do |adapter|
- block.call(self.new(user, adapter))
+ block.call(new(user, adapter))
end
end
def self.allowed?(user, options = {})
- self.open(user) do |access|
+ open(user) do |access|
# Whether user is allowed, or not, we should update
# permissions to keep things clean
if access.allowed?
@@ -43,21 +43,21 @@ module Gitlab
def allowed?
if ldap_user
unless ldap_config.active_directory
- unblock_user(user, 'is available again') if user.ldap_blocked?
+ unblock_user(user, "is available again") if user.ldap_blocked?
return true
end
# Block user in GitLab if he/she was blocked in AD
if Gitlab::Auth::LDAP::Person.disabled_via_active_directory?(ldap_identity.extern_uid, adapter)
- block_user(user, 'is disabled in Active Directory')
+ block_user(user, "is disabled in Active Directory")
false
else
- unblock_user(user, 'is not disabled anymore') if user.ldap_blocked?
+ unblock_user(user, "is not disabled anymore") if user.ldap_blocked?
true
end
else
# Block the user if they no longer exist in LDAP/AD
- block_user(user, 'does not exist anymore')
+ block_user(user, "does not exist anymore")
false
end
rescue LDAPConnectionError
diff --git a/lib/gitlab/auth/ldap/adapter.rb b/lib/gitlab/auth/ldap/adapter.rb
index 15b9d5ad6e9..23b880b6a0b 100644
--- a/lib/gitlab/auth/ldap/adapter.rb
+++ b/lib/gitlab/auth/ldap/adapter.rb
@@ -11,7 +11,7 @@ module Gitlab
def self.open(provider, &block)
Net::LDAP.open(config(provider).adapter_options) do |ldap|
- block.call(self.new(provider, ldap))
+ block.call(new(provider, ldap))
end
end
@@ -41,7 +41,7 @@ module Gitlab
ldap_search(base: dn,
filter: filter,
scope: Net::LDAP::SearchScope_BaseObject,
- attributes: %w{dn}).any?
+ attributes: %w[dn]).any?
end
def ldap_search(*args)
@@ -84,9 +84,9 @@ module Gitlab
end
def users_search(options)
- entries = ldap_search(options).select do |entry|
+ entries = ldap_search(options).select { |entry|
entry.respond_to? config.uid
- end
+ }
entries.map do |entry|
Gitlab::Auth::LDAP::Person.new(entry, provider)
@@ -96,13 +96,13 @@ module Gitlab
def user_options(fields, value, limit)
options = {
attributes: Gitlab::Auth::LDAP::Person.ldap_attributes(config),
- base: config.base
+ base: config.base,
}
options[:size] = limit if limit
- if fields.include?('dn')
- raise ArgumentError, 'It is not currently possible to search the DN and other fields at the same time.' if fields.size > 1
+ if fields.include?("dn")
+ raise ArgumentError, "It is not currently possible to search the DN and other fields at the same time." if fields.size > 1
options[:base] = value
options[:scope] = Net::LDAP::SearchScope_BaseObject
diff --git a/lib/gitlab/auth/ldap/auth_hash.rb b/lib/gitlab/auth/ldap/auth_hash.rb
index 83fdc8a8c76..8b592a7fd0e 100644
--- a/lib/gitlab/auth/ldap/auth_hash.rb
+++ b/lib/gitlab/auth/ldap/auth_hash.rb
@@ -42,7 +42,7 @@ module Gitlab
end
def ldap_config
- @ldap_config ||= Gitlab::Auth::LDAP::Config.new(self.provider)
+ @ldap_config ||= Gitlab::Auth::LDAP::Config.new(provider)
end
end
end
diff --git a/lib/gitlab/auth/ldap/config.rb b/lib/gitlab/auth/ldap/config.rb
index 7ceb96f502b..c7e464b139c 100644
--- a/lib/gitlab/auth/ldap/config.rb
+++ b/lib/gitlab/auth/ldap/config.rb
@@ -7,8 +7,8 @@ module Gitlab
class Config
NET_LDAP_ENCRYPTION_METHOD = {
simple_tls: :simple_tls,
- start_tls: :start_tls,
- plain: nil
+ start_tls: :start_tls,
+ plain: nil,
}.freeze
attr_accessor :provider, :options
@@ -20,7 +20,7 @@ module Gitlab
end
def self.servers
- Gitlab.config.ldap['servers']&.values || []
+ Gitlab.config.ldap["servers"]&.values || []
end
def self.available_servers
@@ -34,7 +34,7 @@ module Gitlab
end
def self.providers
- servers.map { |server| server['provider_name'] }
+ servers.map { |server| server["provider_name"] }
end
def self.valid_provider?(provider)
@@ -72,35 +72,33 @@ module Gitlab
def omniauth_options
opts = base_options.merge(
base: base,
- encryption: options['encryption'],
+ encryption: options["encryption"],
filter: omniauth_user_filter,
name_proc: name_proc,
- disable_verify_certificates: !options['verify_certificates']
+ disable_verify_certificates: !options["verify_certificates"]
)
if has_auth?
- opts.merge!(
- bind_dn: options['bind_dn'],
- password: options['password']
- )
+ opts[:bind_dn] = options["bind_dn"]
+ opts[:password] = options["password"]
end
- opts[:ca_file] = options['ca_file'] if options['ca_file'].present?
- opts[:ssl_version] = options['ssl_version'] if options['ssl_version'].present?
+ opts[:ca_file] = options["ca_file"] if options["ca_file"].present?
+ opts[:ssl_version] = options["ssl_version"] if options["ssl_version"].present?
opts
end
def base
- @base ||= Person.normalize_dn(options['base'])
+ @base ||= Person.normalize_dn(options["base"])
end
def uid
- options['uid']
+ options["uid"]
end
def label
- options['label']
+ options["label"]
end
def sync_ssh_keys?
@@ -109,11 +107,11 @@ module Gitlab
# The LDAP attribute in which the ssh keys are stored
def sync_ssh_keys
- options['sync_ssh_keys']
+ options["sync_ssh_keys"]
end
def user_filter
- options['user_filter']
+ options["user_filter"]
end
def constructed_user_filter
@@ -121,48 +119,48 @@ module Gitlab
end
def group_base
- options['group_base']
+ options["group_base"]
end
def admin_group
- options['admin_group']
+ options["admin_group"]
end
def active_directory
- options['active_directory']
+ options["active_directory"]
end
def block_auto_created_users
- options['block_auto_created_users']
+ options["block_auto_created_users"]
end
def attributes
- default_attributes.merge(options['attributes'])
+ default_attributes.merge(options["attributes"])
end
def timeout
- options['timeout'].to_i
+ options["timeout"].to_i
end
def external_groups
- options['external_groups'] || []
+ options["external_groups"] || []
end
def has_auth?
- options['password'] || options['bind_dn']
+ options["password"] || options["bind_dn"]
end
def allow_username_or_email_login
- options['allow_username_or_email_login']
+ options["allow_username_or_email_login"]
end
def lowercase_usernames
- options['lowercase_usernames']
+ options["lowercase_usernames"]
end
def name_proc
if allow_username_or_email_login
- proc { |name| name.gsub(/@.*\z/, '') }
+ proc { |name| name.gsub(/@.*\z/, "") }
else
proc { |name| name }
end
@@ -170,11 +168,11 @@ module Gitlab
def default_attributes
{
- 'username' => %w(uid sAMAccountName userid),
- 'email' => %w(mail email userPrincipalName),
- 'name' => 'cn',
- 'first_name' => 'givenName',
- 'last_name' => 'sn'
+ "username" => %w[uid sAMAccountName userid],
+ "email" => %w[mail email userPrincipalName],
+ "name" => "cn",
+ "first_name" => "givenName",
+ "last_name" => "sn",
}
end
@@ -182,8 +180,8 @@ module Gitlab
def base_options
{
- host: options['host'],
- port: options['port']
+ host: options["host"],
+ port: options["port"],
}
end
@@ -192,16 +190,16 @@ module Gitlab
end
def config_for(provider)
- base_config.servers.values.find { |server| server['provider_name'] == provider }
+ base_config.servers.values.find { |server| server["provider_name"] == provider }
end
def encryption_options
- method = translate_method(options['encryption'])
+ method = translate_method(options["encryption"])
return nil unless method
{
method: method,
- tls_options: tls_options(method)
+ tls_options: tls_options(method),
}
end
@@ -210,20 +208,20 @@ module Gitlab
end
def tls_options(method)
- return { verify_mode: OpenSSL::SSL::VERIFY_NONE } unless method
+ return {verify_mode: OpenSSL::SSL::VERIFY_NONE} unless method
- opts = if options['verify_certificates']
- OpenSSL::SSL::SSLContext::DEFAULT_PARAMS
- else
- # It is important to explicitly set verify_mode for two reasons:
- # 1. The behavior of OpenSSL is undefined when verify_mode is not set.
- # 2. The net-ldap gem implementation verifies the certificate hostname
- # unless verify_mode is set to VERIFY_NONE.
- { verify_mode: OpenSSL::SSL::VERIFY_NONE }
- end
+ opts = if options["verify_certificates"]
+ OpenSSL::SSL::SSLContext::DEFAULT_PARAMS
+ else
+ # It is important to explicitly set verify_mode for two reasons:
+ # 1. The behavior of OpenSSL is undefined when verify_mode is not set.
+ # 2. The net-ldap gem implementation verifies the certificate hostname
+ # unless verify_mode is set to VERIFY_NONE.
+ {verify_mode: OpenSSL::SSL::VERIFY_NONE}
+ end
- opts[:ca_file] = options['ca_file'] if options['ca_file'].present?
- opts[:ssl_version] = options['ssl_version'] if options['ssl_version'].present?
+ opts[:ca_file] = options["ca_file"] if options["ca_file"].present?
+ opts[:ssl_version] = options["ssl_version"] if options["ssl_version"].present?
opts
end
@@ -232,14 +230,14 @@ module Gitlab
{
auth: {
method: :simple,
- username: options['bind_dn'],
- password: options['password']
- }
+ username: options["bind_dn"],
+ password: options["password"],
+ },
}
end
def omniauth_user_filter
- uid_filter = Net::LDAP::Filter.eq(uid, '%{username}')
+ uid_filter = Net::LDAP::Filter.eq(uid, "%{username}")
if user_filter.present?
Net::LDAP::Filter.join(uid_filter, constructed_user_filter).to_s
diff --git a/lib/gitlab/auth/ldap/dn.rb b/lib/gitlab/auth/ldap/dn.rb
index 5df914aa367..669493e1f89 100644
--- a/lib/gitlab/auth/ldap/dn.rb
+++ b/lib/gitlab/auth/ldap/dn.rb
@@ -1,4 +1,3 @@
-# -*- ruby encoding: utf-8 -*-
# frozen_string_literal: true
# Based on the `ruby-net-ldap` gem's `Net::LDAP::DN`
@@ -31,7 +30,7 @@ module Gitlab
def self.normalize_value(given_value)
dummy_dn = "placeholder=#{given_value}"
normalized_dn = new(*dummy_dn).to_normalized_s
- normalized_dn.sub(/\Aplaceholder=/, '')
+ normalized_dn.sub(/\Aplaceholder=/, "")
end
##
@@ -66,36 +65,36 @@ module Gitlab
case state
when :key then
case char
- when 'a'..'z', 'A'..'Z' then
+ when "a".."z", "A".."Z" then
state = :key_normal
key << char
- when '0'..'9' then
+ when "0".."9" then
state = :key_oid
key << char
- when ' ' then state = :key
+ when " " then state = :key
else raise(MalformedError, "Unrecognized first character of an RDN attribute type name \"#{char}\"")
end
when :key_normal then
case char
- when '=' then state = :value
- when 'a'..'z', 'A'..'Z', '0'..'9', '-', ' ' then key << char
+ when "=" then state = :value
+ when "a".."z", "A".."Z", "0".."9", "-", " " then key << char
else raise(MalformedError, "Unrecognized RDN attribute type name character \"#{char}\"")
end
when :key_oid then
case char
- when '=' then state = :value
- when '0'..'9', '.', ' ' then key << char
+ when "=" then state = :value
+ when "0".."9", ".", " " then key << char
else raise(MalformedError, "Unrecognized RDN OID attribute type name character \"#{char}\"")
end
when :value then
case char
when '\\' then state = :value_normal_escape
when '"' then state = :value_quoted
- when ' ' then state = :value
- when '#' then
+ when " " then state = :value
+ when "#" then
state = :value_hexstring
value << char
- when ',' then
+ when "," then
state = :key
yield key.string.strip, rstrip_except_escaped(value.string, dn_index)
key = StringIO.new
@@ -107,17 +106,17 @@ module Gitlab
when :value_normal then
case char
when '\\' then state = :value_normal_escape
- when ',' then
+ when "," then
state = :key
yield key.string.strip, rstrip_except_escaped(value.string, dn_index)
key = StringIO.new
value = StringIO.new
- when '+' then raise(UnsupportedError, "Multivalued RDNs are not supported")
+ when "+" then raise(UnsupportedError, "Multivalued RDNs are not supported")
else value << char
end
when :value_normal_escape then
case char
- when '0'..'9', 'a'..'f', 'A'..'F' then
+ when "0".."9", "a".."f", "A".."F" then
state = :value_normal_escape_hex
hex_buffer = char
else
@@ -126,7 +125,7 @@ module Gitlab
end
when :value_normal_escape_hex then
case char
- when '0'..'9', 'a'..'f', 'A'..'F' then
+ when "0".."9", "a".."f", "A".."F" then
state = :value_normal
value << "#{hex_buffer}#{char}".to_i(16).chr
else raise(MalformedError, "Invalid escaped hex code \"\\#{hex_buffer}#{char}\"")
@@ -139,7 +138,7 @@ module Gitlab
end
when :value_quoted_escape then
case char
- when '0'..'9', 'a'..'f', 'A'..'F' then
+ when "0".."9", "a".."f", "A".."F" then
state = :value_quoted_escape_hex
hex_buffer = char
else
@@ -148,18 +147,18 @@ module Gitlab
end
when :value_quoted_escape_hex then
case char
- when '0'..'9', 'a'..'f', 'A'..'F' then
+ when "0".."9", "a".."f", "A".."F" then
state = :value_quoted
value << "#{hex_buffer}#{char}".to_i(16).chr
else raise(MalformedError, "Expected the second character of a hex pair inside a double quoted value, but got \"#{char}\"")
end
when :value_hexstring then
case char
- when '0'..'9', 'a'..'f', 'A'..'F' then
+ when "0".."9", "a".."f", "A".."F" then
state = :value_hexstring_hex
value << char
- when ' ' then state = :value_end
- when ',' then
+ when " " then state = :value_end
+ when "," then
state = :key
yield key.string.strip, rstrip_except_escaped(value.string, dn_index)
key = StringIO.new
@@ -168,15 +167,15 @@ module Gitlab
end
when :value_hexstring_hex then
case char
- when '0'..'9', 'a'..'f', 'A'..'F' then
+ when "0".."9", "a".."f", "A".."F" then
state = :value_hexstring
value << char
else raise(MalformedError, "Expected the second character of a hex pair, but got \"#{char}\"")
end
when :value_end then
case char
- when ' ' then state = :value_end
- when ',' then
+ when " " then state = :value_end
+ when "," then
state = :key
yield key.string.strip, rstrip_except_escaped(value.string, dn_index)
key = StringIO.new
@@ -188,7 +187,7 @@ module Gitlab
end
# Last pair
- raise(MalformedError, 'DN string ended unexpectedly') unless
+ raise(MalformedError, "DN string ended unexpectedly") unless
[:value, :value_normal, :value_hexstring, :value_end].include? state
yield key.string.strip, rstrip_except_escaped(value.string, @dn.length)
@@ -216,7 +215,7 @@ module Gitlab
# Returns the DN as an array in the form expected by the constructor.
def to_a
a = []
- self.each_pair { |key, value| a << key << value } unless @dn.empty?
+ each_pair { |key, value| a << key << value } unless @dn.empty?
a
end
@@ -237,12 +236,12 @@ module Gitlab
# using a single backslash ('\') as escape. The space character is left
# out here because in a "normalized" string, spaces should only be escaped
# if necessary (i.e. leading or trailing space).
- NORMAL_ESCAPES = [',', '+', '"', '\\', '<', '>', ';', '='].freeze
+ NORMAL_ESCAPES = [",", "+", '"', '\\', "<", ">", ";", "="].freeze
# The following must be represented as escaped hex
HEX_ESCAPES = {
"\n" => '\0a',
- "\r" => '\0d'
+ "\r" => '\0d',
}.freeze
# Compiled character class regexp using the keys from the above hash, and
diff --git a/lib/gitlab/auth/ldap/person.rb b/lib/gitlab/auth/ldap/person.rb
index 48d134f91b0..03357581869 100644
--- a/lib/gitlab/auth/ldap/person.rb
+++ b/lib/gitlab/auth/ldap/person.rb
@@ -19,11 +19,11 @@ module Gitlab
end
def self.find_by_dn(dn, adapter)
- adapter.user('dn', dn)
+ adapter.user("dn", dn)
end
def self.find_by_email(email, adapter)
- email_fields = adapter.config.attributes['email']
+ email_fields = adapter.config.attributes["email"]
adapter.user(email_fields, email)
end
@@ -34,11 +34,11 @@ module Gitlab
def self.ldap_attributes(config)
[
- 'dn',
+ "dn",
config.uid,
- *config.attributes['name'],
- *config.attributes['email'],
- *config.attributes['username']
+ *config.attributes["name"],
+ *config.attributes["email"],
+ *config.attributes["username"],
].compact.uniq
end
diff --git a/lib/gitlab/auth/ldap/user.rb b/lib/gitlab/auth/ldap/user.rb
index 9c71671f409..44d508f17dc 100644
--- a/lib/gitlab/auth/ldap/user.rb
+++ b/lib/gitlab/auth/ldap/user.rb
@@ -17,13 +17,13 @@ module Gitlab
def find_by_uid_and_provider(uid, provider)
identity = ::Identity.with_extern_uid(provider, uid).take
- identity && identity.user
+ identity&.user
end
# rubocop: enable CodeReuse/ActiveRecord
end
def save
- super('LDAP')
+ super("LDAP")
end
# instance methods
diff --git a/lib/gitlab/auth/o_auth/auth_hash.rb b/lib/gitlab/auth/o_auth/auth_hash.rb
index 36fc8061d92..2898c949438 100644
--- a/lib/gitlab/auth/o_auth/auth_hash.rb
+++ b/lib/gitlab/auth/o_auth/auth_hash.rb
@@ -38,7 +38,7 @@ module Gitlab
def location
location = get_info(:address)
if location.is_a?(Hash)
- [location.locality.presence, location.country.presence].compact.join(', ')
+ [location.locality.presence, location.country.presence].compact.join(", ")
else
location
end
@@ -74,7 +74,7 @@ module Gitlab
{
username: username,
- email: email
+ email: email,
}
end
end
@@ -82,7 +82,7 @@ module Gitlab
# Get the first part of the email address (before @)
# In addition in removes illegal characters
def generate_username(email)
- email.match(/^[^@]*/)[0].mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/, '').to_s
+ email.match(/^[^@]*/)[0].mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/, "").to_s
end
def generate_temporarily_email(username)
diff --git a/lib/gitlab/auth/o_auth/provider.rb b/lib/gitlab/auth/o_auth/provider.rb
index 9fdf3324db3..497746fbaa2 100644
--- a/lib/gitlab/auth/o_auth/provider.rb
+++ b/lib/gitlab/auth/o_auth/provider.rb
@@ -5,9 +5,9 @@ module Gitlab
module OAuth
class Provider
LABELS = {
- "github" => "GitHub",
- "gitlab" => "GitLab.com",
- "google_oauth2" => "Google"
+ "github" => "GitHub",
+ "gitlab" => "GitLab.com",
+ "google_oauth2" => "Google",
}.freeze
def self.authentication(user, provider)
@@ -18,7 +18,7 @@ module Gitlab
case provider
when /^ldap/
Gitlab::Auth::LDAP::Authentication
- when 'database'
+ when "database"
Gitlab::Auth::Database::Authentication
end
@@ -30,14 +30,14 @@ module Gitlab
end
def self.enabled?(name)
- return true if name == 'database'
- return true if self.ldap_provider?(name) && providers.include?(name.to_sym)
+ return true if name == "database"
+ return true if ldap_provider?(name) && providers.include?(name.to_sym)
Gitlab::Auth.omniauth_enabled? && providers.include?(name.to_sym)
end
def self.ldap_provider?(name)
- name.to_s.start_with?('ldap')
+ name.to_s.start_with?("ldap")
end
def self.sync_profile_from_provider?(provider)
@@ -57,8 +57,6 @@ module Gitlab
if ldap_provider?(name)
if Gitlab::Auth::LDAP::Config.valid_provider?(name)
Gitlab::Auth::LDAP::Config.new(name).options
- else
- nil
end
else
Gitlab.config.omniauth.providers.find { |provider| provider.name == name }
@@ -68,7 +66,7 @@ module Gitlab
def self.label_for(name)
name = name.to_s
config = config_for(name)
- (config && config['label']) || LABELS[name] || name.titleize
+ (config && config["label"]) || LABELS[name] || name.titleize
end
end
end
diff --git a/lib/gitlab/auth/o_auth/user.rb b/lib/gitlab/auth/o_auth/user.rb
index f38c5d57c44..222700d4615 100644
--- a/lib/gitlab/auth/o_auth/user.rb
+++ b/lib/gitlab/auth/o_auth/user.rb
@@ -36,7 +36,7 @@ module Gitlab
valid? && persisted?
end
- def save(provider = 'OAuth')
+ def save(provider = "OAuth")
raise SigninDisabledForProviderError if oauth_provider_disabled?
raise SignupDisabledError unless gl_user
@@ -146,7 +146,6 @@ module Gitlab
Gitlab::Auth::LDAP::Person.find_by_uid(auth_hash.uid, adapter) ||
Gitlab::Auth::LDAP::Person.find_by_email(auth_hash.uid, adapter) ||
Gitlab::Auth::LDAP::Person.find_by_dn(auth_hash.uid, adapter)
-
rescue Gitlab::Auth::LDAP::LDAPConnectionError
nil
end
@@ -215,12 +214,12 @@ module Gitlab
name = valid_username if name.strip.empty?
{
- name: name,
- username: valid_username,
- email: email,
- password: auth_hash.password,
- password_confirmation: auth_hash.password,
- password_automatically_set: true
+ name: name,
+ username: valid_username,
+ email: email,
+ password: auth_hash.password,
+ password_confirmation: auth_hash.password,
+ password_automatically_set: true,
}
end
@@ -264,8 +263,8 @@ module Gitlab
def oauth_provider_disabled?
Gitlab::CurrentSettings.current_application_settings
- .disabled_oauth_sign_in_sources
- .include?(auth_hash.provider)
+ .disabled_oauth_sign_in_sources
+ .include?(auth_hash.provider)
end
end
end
diff --git a/lib/gitlab/auth/omniauth_identity_linker_base.rb b/lib/gitlab/auth/omniauth_identity_linker_base.rb
index 253445570f2..c9c2d83716a 100644
--- a/lib/gitlab/auth/omniauth_identity_linker_base.rb
+++ b/lib/gitlab/auth/omniauth_identity_linker_base.rb
@@ -26,7 +26,7 @@ module Gitlab
def error_message
identity.validate
- identity.errors.full_messages.join(', ')
+ identity.errors.full_messages.join(", ")
end
private
@@ -38,17 +38,17 @@ module Gitlab
# rubocop: disable CodeReuse/ActiveRecord
def identity
@identity ||= current_user.identities
- .with_extern_uid(provider, uid)
- .first_or_initialize(extern_uid: uid)
+ .with_extern_uid(provider, uid)
+ .first_or_initialize(extern_uid: uid)
end
# rubocop: enable CodeReuse/ActiveRecord
def provider
- oauth['provider']
+ oauth["provider"]
end
def uid
- oauth['uid']
+ oauth["uid"]
end
end
end
diff --git a/lib/gitlab/auth/result.rb b/lib/gitlab/auth/result.rb
index 78fa25c5516..93bc3adc0ae 100644
--- a/lib/gitlab/auth/result.rb
+++ b/lib/gitlab/auth/result.rb
@@ -3,7 +3,7 @@
module Gitlab
module Auth
- Result = Struct.new(:actor, :project, :type, :authentication_abilities) do
+ Result = Struct.new(:actor, :project, :type, :authentication_abilities) {
def ci?(for_project)
type == :ci &&
project &&
@@ -22,6 +22,6 @@ module Gitlab
def failed?
!success?
end
- end
+ }
end
end
diff --git a/lib/gitlab/auth/saml/config.rb b/lib/gitlab/auth/saml/config.rb
index 8cb999f50d4..6717375775f 100644
--- a/lib/gitlab/auth/saml/config.rb
+++ b/lib/gitlab/auth/saml/config.rb
@@ -6,7 +6,7 @@ module Gitlab
class Config
class << self
def options
- Gitlab::Auth::OAuth::Provider.config_for('saml')
+ Gitlab::Auth::OAuth::Provider.config_for("saml")
end
def upstream_two_factor_authn_contexts
diff --git a/lib/gitlab/auth/saml/user.rb b/lib/gitlab/auth/saml/user.rb
index ec95bc46791..e664ee57153 100644
--- a/lib/gitlab/auth/saml/user.rb
+++ b/lib/gitlab/auth/saml/user.rb
@@ -12,7 +12,7 @@ module Gitlab
extend ::Gitlab::Utils::Override
def save
- super('SAML')
+ super("SAML")
end
def find_user
diff --git a/lib/gitlab/auth/unique_ips_limiter.rb b/lib/gitlab/auth/unique_ips_limiter.rb
index 31dd61ae6cf..717c3e0266f 100644
--- a/lib/gitlab/auth/unique_ips_limiter.rb
+++ b/lib/gitlab/auth/unique_ips_limiter.rb
@@ -3,7 +3,7 @@
module Gitlab
module Auth
class UniqueIpsLimiter
- USER_UNIQUE_IPS_PREFIX = 'user_unique_ips'.freeze
+ USER_UNIQUE_IPS_PREFIX = "user_unique_ips"
class << self
def limit_user_id!(user_id)
diff --git a/lib/gitlab/auth/user_auth_finders.rb b/lib/gitlab/auth/user_auth_finders.rb
index a5efe33bdc6..d0eb2854b78 100644
--- a/lib/gitlab/auth/user_auth_finders.rb
+++ b/lib/gitlab/auth/user_auth_finders.rb
@@ -20,12 +20,12 @@ module Gitlab
module UserAuthFinders
include Gitlab::Utils::StrongMemoize
- PRIVATE_TOKEN_HEADER = 'HTTP_PRIVATE_TOKEN'.freeze
+ PRIVATE_TOKEN_HEADER = "HTTP_PRIVATE_TOKEN"
PRIVATE_TOKEN_PARAM = :private_token
# Check the Rails session for valid authentication details
def find_user_from_warden
- current_request.env['warden']&.authenticate if verified_request?
+ current_request.env["warden"]&.authenticate if verified_request?
end
def find_user_from_feed_token(request_format)
@@ -144,11 +144,11 @@ module Gitlab
end
def rss_request?
- current_request.path.ends_with?('.atom') || current_request.format.atom?
+ current_request.path.ends_with?(".atom") || current_request.format.atom?
end
def ics_request?
- current_request.path.ends_with?('.ics') || current_request.format.ics?
+ current_request.path.ends_with?(".ics") || current_request.format.ics?
end
def api_request?
diff --git a/lib/gitlab/background_migration.rb b/lib/gitlab/background_migration.rb
index 5251e0fadf9..402d3e8f3f7 100644
--- a/lib/gitlab/background_migration.rb
+++ b/lib/gitlab/background_migration.rb
@@ -3,7 +3,7 @@
module Gitlab
module BackgroundMigration
def self.queue
- @queue ||= BackgroundMigrationWorker.sidekiq_options['queue']
+ @queue ||= BackgroundMigrationWorker.sidekiq_options["queue"]
end
# Begins stealing jobs from the background migrations queue, blocking the
@@ -19,7 +19,7 @@ module Gitlab
def self.steal(steal_class, retry_dead_jobs: false)
queues = [
Sidekiq::ScheduledSet.new,
- Sidekiq::Queue.new(self.queue)
+ Sidekiq::Queue.new(queue),
]
if retry_dead_jobs
@@ -59,7 +59,7 @@ module Gitlab
end
def self.exists?(migration_class)
- enqueued = Sidekiq::Queue.new(self.queue)
+ enqueued = Sidekiq::Queue.new(queue)
scheduled = Sidekiq::ScheduledSet.new
[enqueued, scheduled].each do |queue|
diff --git a/lib/gitlab/background_migration/add_merge_request_diff_commits_count.rb b/lib/gitlab/background_migration/add_merge_request_diff_commits_count.rb
index cb2bdea755c..460c48a8fba 100644
--- a/lib/gitlab/background_migration/add_merge_request_diff_commits_count.rb
+++ b/lib/gitlab/background_migration/add_merge_request_diff_commits_count.rb
@@ -1,11 +1,12 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
module BackgroundMigration
class AddMergeRequestDiffCommitsCount
class MergeRequestDiff < ActiveRecord::Base
- self.table_name = 'merge_request_diffs'
+ self.table_name = "merge_request_diffs"
end
def perform(start_id, stop_id)
diff --git a/lib/gitlab/background_migration/archive_legacy_traces.rb b/lib/gitlab/background_migration/archive_legacy_traces.rb
index 92096e29ef1..270631d8998 100644
--- a/lib/gitlab/background_migration/archive_legacy_traces.rb
+++ b/lib/gitlab/background_migration/archive_legacy_traces.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
@@ -11,11 +12,10 @@ module Gitlab
# So we chose a way to use ::Ci::Build directly and we don't change the `archive!` method until 11.1
::Ci::Build.finished.without_archived_trace
.where(id: start_id..stop_id).find_each do |build|
- begin
- build.trace.archive!
- rescue => e
- Rails.logger.error "Failed to archive live trace. id: #{build.id} message: #{e.message}"
- end
+
+ build.trace.archive!
+ rescue => e
+ Rails.logger.error "Failed to archive live trace. id: #{build.id} message: #{e.message}"
end
end
end
diff --git a/lib/gitlab/background_migration/backfill_project_fullpath_in_repo_config.rb b/lib/gitlab/background_migration/backfill_project_fullpath_in_repo_config.rb
index 29fa0f18448..f7ec7b62363 100644
--- a/lib/gitlab/background_migration/backfill_project_fullpath_in_repo_config.rb
+++ b/lib/gitlab/background_migration/backfill_project_fullpath_in_repo_config.rb
@@ -14,7 +14,7 @@ module Gitlab
class HashedProject
attr_accessor :project
- ROOT_PATH_PREFIX = '@hashed'
+ ROOT_PATH_PREFIX = "@hashed"
def initialize(project)
@project = project
@@ -57,7 +57,7 @@ module Gitlab
raise OrphanedNamespaceError if parent.nil?
- parent.full_path + '/' + path
+ parent.full_path + "/" + path
end
def has_parent?
@@ -82,30 +82,30 @@ module Gitlab
# Namespace can be a user or group. It can be the root or a
# child of another namespace.
class Namespace < ActiveRecord::Base
- self.table_name = 'namespaces'
+ self.table_name = "namespaces"
self.inheritance_column = nil
include Routable
- belongs_to :parent, class_name: 'Namespace', inverse_of: 'namespaces'
+ belongs_to :parent, class_name: "Namespace", inverse_of: "namespaces"
has_many :projects, inverse_of: :parent
has_many :namespaces, inverse_of: :parent
end
# Project is where the repository (etc.) is stored
class Project < ActiveRecord::Base
- self.table_name = 'projects'
+ self.table_name = "projects"
include Routable
include EachBatch
- FULLPATH_CONFIG_KEY = 'gitlab.fullpath'
+ FULLPATH_CONFIG_KEY = "gitlab.fullpath"
- belongs_to :parent, class_name: 'Namespace', foreign_key: :namespace_id, inverse_of: 'projects'
+ belongs_to :parent, class_name: "Namespace", foreign_key: :namespace_id, inverse_of: "projects"
delegate :disk_path, to: :storage
def add_fullpath_config
- entries = { FULLPATH_CONFIG_KEY => full_path }
+ entries = {FULLPATH_CONFIG_KEY => full_path}
repository_service.set_config(entries)
end
@@ -128,11 +128,11 @@ module Gitlab
end
def hashed_storage?
- self.storage_version && self.storage_version >= 1
+ storage_version && storage_version >= 1
end
def repository
- @repository ||= Repository.new(repository_storage, disk_path + '.git')
+ @repository ||= Repository.new(repository_storage, disk_path + ".git")
end
def repository_service
diff --git a/lib/gitlab/background_migration/backfill_project_repositories.rb b/lib/gitlab/background_migration/backfill_project_repositories.rb
index c8d83cc1803..6f2e71c8c7f 100644
--- a/lib/gitlab/background_migration/backfill_project_repositories.rb
+++ b/lib/gitlab/background_migration/backfill_project_repositories.rb
@@ -9,7 +9,7 @@ module Gitlab
# Shard model
class Shard < ActiveRecord::Base
- self.table_name = 'shards'
+ self.table_name = "shards"
end
# Class that will find or create the shard by name.
@@ -49,7 +49,7 @@ module Gitlab
class HashedProject
attr_accessor :project
- ROOT_PATH_PREFIX = '@hashed'
+ ROOT_PATH_PREFIX = "@hashed"
def initialize(project)
@project = project
@@ -91,7 +91,7 @@ module Gitlab
raise OrphanedNamespaceError if parent.nil?
- parent.full_path + '/' + path
+ parent.full_path + "/" + path
end
def has_parent?
@@ -106,14 +106,14 @@ module Gitlab
# Namespace model
class Namespace < ActiveRecord::Base
- self.table_name = 'namespaces'
+ self.table_name = "namespaces"
self.inheritance_column = nil
include Routable
- belongs_to :parent, class_name: 'Namespace', inverse_of: 'namespaces'
+ belongs_to :parent, class_name: "Namespace", inverse_of: "namespaces"
- has_one :route, -> { where(source_type: 'Namespace') }, inverse_of: :source, foreign_key: :source_id
+ has_one :route, -> { where(source_type: "Namespace") }, inverse_of: :source, foreign_key: :source_id
has_many :projects, inverse_of: :parent
has_many :namespaces, inverse_of: :parent
@@ -121,27 +121,27 @@ module Gitlab
# ProjectRegistry model
class ProjectRepository < ActiveRecord::Base
- self.table_name = 'project_repositories'
+ self.table_name = "project_repositories"
belongs_to :project, inverse_of: :project_repository
end
# Project model
class Project < ActiveRecord::Base
- self.table_name = 'projects'
+ self.table_name = "projects"
include Routable
HASHED_STORAGE_FEATURES = {
repository: 1,
- attachments: 2
+ attachments: 2,
}.freeze
scope :with_parent, -> { includes(:parent) }
- belongs_to :parent, class_name: 'Namespace', foreign_key: :namespace_id, inverse_of: 'projects'
+ belongs_to :parent, class_name: "Namespace", foreign_key: :namespace_id, inverse_of: "projects"
- has_one :route, -> { where(source_type: 'Project') }, inverse_of: :source, foreign_key: :source_id
+ has_one :route, -> { where(source_type: "Project") }, inverse_of: :source, foreign_key: :source_id
has_one :project_repository, inverse_of: :project
delegate :disk_path, to: :storage
@@ -183,8 +183,8 @@ module Gitlab
end
def hashed_storage?
- self.storage_version &&
- self.storage_version >= HASHED_STORAGE_FEATURES[:repository]
+ storage_version &&
+ storage_version >= HASHED_STORAGE_FEATURES[:repository]
end
end
@@ -212,8 +212,8 @@ module Gitlab
def build_attributes_for_project(project)
{
project_id: project.id,
- shard_id: find_shard_id(project.repository_storage),
- disk_path: project.disk_path
+ shard_id: find_shard_id(project.repository_storage),
+ disk_path: project.disk_path,
}
end
diff --git a/lib/gitlab/background_migration/create_fork_network_memberships_range.rb b/lib/gitlab/background_migration/create_fork_network_memberships_range.rb
index ccd1f9b4dba..4387307d416 100644
--- a/lib/gitlab/background_migration/create_fork_network_memberships_range.rb
+++ b/lib/gitlab/background_migration/create_fork_network_memberships_range.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
@@ -7,7 +8,7 @@ module Gitlab
RESCHEDULE_DELAY = 15
class ForkedProjectLink < ActiveRecord::Base
- self.table_name = 'forked_project_links'
+ self.table_name = "forked_project_links"
end
def perform(start_id, end_id)
diff --git a/lib/gitlab/background_migration/create_gpg_key_subkeys_from_gpg_keys.rb b/lib/gitlab/background_migration/create_gpg_key_subkeys_from_gpg_keys.rb
index da8265a3a5f..4602b12dfbd 100644
--- a/lib/gitlab/background_migration/create_gpg_key_subkeys_from_gpg_keys.rb
+++ b/lib/gitlab/background_migration/create_gpg_key_subkeys_from_gpg_keys.rb
@@ -1,9 +1,10 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
class Gitlab::BackgroundMigration::CreateGpgKeySubkeysFromGpgKeys
class GpgKey < ActiveRecord::Base
- self.table_name = 'gpg_keys'
+ self.table_name = "gpg_keys"
include EachBatch
include ShaAttribute
@@ -11,11 +12,11 @@ class Gitlab::BackgroundMigration::CreateGpgKeySubkeysFromGpgKeys
sha_attribute :primary_keyid
sha_attribute :fingerprint
- has_many :subkeys, class_name: 'GpgKeySubkey'
+ has_many :subkeys, class_name: "GpgKeySubkey"
end
class GpgKeySubkey < ActiveRecord::Base
- self.table_name = 'gpg_key_subkeys'
+ self.table_name = "gpg_key_subkeys"
include ShaAttribute
diff --git a/lib/gitlab/background_migration/delete_conflicting_redirect_routes_range.rb b/lib/gitlab/background_migration/delete_conflicting_redirect_routes_range.rb
index 21b626dde56..a1bc7fc3ec1 100644
--- a/lib/gitlab/background_migration/delete_conflicting_redirect_routes_range.rb
+++ b/lib/gitlab/background_migration/delete_conflicting_redirect_routes_range.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
diff --git a/lib/gitlab/background_migration/delete_diff_files.rb b/lib/gitlab/background_migration/delete_diff_files.rb
index 664ead1af44..879e77a5bcc 100644
--- a/lib/gitlab/background_migration/delete_diff_files.rb
+++ b/lib/gitlab/background_migration/delete_diff_files.rb
@@ -1,18 +1,19 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
module BackgroundMigration
class DeleteDiffFiles
class MergeRequestDiff < ActiveRecord::Base
- self.table_name = 'merge_request_diffs'
+ self.table_name = "merge_request_diffs"
belongs_to :merge_request
has_many :merge_request_diff_files
end
class MergeRequestDiffFile < ActiveRecord::Base
- self.table_name = 'merge_request_diff_files'
+ self.table_name = "merge_request_diff_files"
end
DEAD_TUPLES_THRESHOLD = 50_000
@@ -53,7 +54,7 @@ module Gitlab
execute_statement("SELECT n_dead_tup FROM pg_stat_all_tables "\
"WHERE relname = 'merge_request_diff_files'")[0]
- dead_tuple&.fetch('n_dead_tup', 0).to_i
+ dead_tuple&.fetch("n_dead_tup", 0).to_i
end
def prune_diff_files
@@ -61,7 +62,7 @@ module Gitlab
updated = 0
MergeRequestDiff.transaction do
- updated = diffs_collection.update_all(state: 'without_files')
+ updated = diffs_collection.update_all(state: "without_files")
removed = MergeRequestDiffFile.where(merge_request_diff_id: @ids).delete_all
end
diff --git a/lib/gitlab/background_migration/deserialize_merge_request_diffs_and_commits.rb b/lib/gitlab/background_migration/deserialize_merge_request_diffs_and_commits.rb
index 58df74cfa9b..9c50fa1fe37 100644
--- a/lib/gitlab/background_migration/deserialize_merge_request_diffs_and_commits.rb
+++ b/lib/gitlab/background_migration/deserialize_merge_request_diffs_and_commits.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/AbcSize
# rubocop:disable Style/Documentation
@@ -15,7 +16,7 @@ module Gitlab
end
class MergeRequestDiff < ActiveRecord::Base
- self.table_name = 'merge_request_diffs'
+ self.table_name = "merge_request_diffs"
end
BUFFER_ROWS = 1000
@@ -23,9 +24,9 @@ module Gitlab
def perform(start_id, stop_id)
merge_request_diffs = MergeRequestDiff
- .select(:id, :st_commits, :st_diffs)
- .where('st_commits IS NOT NULL OR st_diffs IS NOT NULL')
- .where(id: start_id..stop_id)
+ .select(:id, :st_commits, :st_diffs)
+ .where("st_commits IS NOT NULL OR st_diffs IS NOT NULL")
+ .where(id: start_id..stop_id)
reset_buffers!
@@ -62,11 +63,11 @@ module Gitlab
def flush_buffers!
if diff_ids.any?
commit_rows.each_slice(BUFFER_ROWS).each do |commit_rows_slice|
- bulk_insert('merge_request_diff_commits', commit_rows_slice)
+ bulk_insert("merge_request_diff_commits", commit_rows_slice)
end
file_rows.each_slice(DIFF_FILE_BUFFER_ROWS).each do |file_rows_slice|
- bulk_insert('merge_request_diff_files', file_rows_slice)
+ bulk_insert("merge_request_diff_files", file_rows_slice)
end
MergeRequestDiff.where(id: diff_ids).update_all(st_commits: nil, st_diffs: nil)
@@ -85,10 +86,14 @@ module Gitlab
def single_diff_rows(merge_request_diff)
sha_attribute = Gitlab::Database::ShaAttribute.new
- commits = YAML.load(merge_request_diff.st_commits) rescue []
+ commits = begin
+ YAML.load(merge_request_diff.st_commits)
+ rescue
+ []
+ end
commits ||= []
- commit_rows = commits.map.with_index do |commit, index|
+ commit_rows = commits.map.with_index { |commit, index|
commit_hash = commit.to_hash.with_indifferent_access.except(:parent_ids)
sha = commit_hash.delete(:id)
@@ -97,12 +102,16 @@ module Gitlab
relative_order: index,
sha: sha_attribute.serialize(sha)
)
- end
+ }
- diffs = YAML.load(merge_request_diff.st_diffs) rescue []
+ diffs = begin
+ YAML.load(merge_request_diff.st_diffs)
+ rescue
+ []
+ end
diffs = [] unless valid_raw_diffs?(diffs)
- file_rows = diffs.map.with_index do |diff, index|
+ file_rows = diffs.map.with_index { |diff, index|
diff_hash = diff.to_hash.with_indifferent_access.merge(
binary: false,
merge_request_diff_id: merge_request_diff.id,
@@ -120,10 +129,10 @@ module Gitlab
# Compatibility with old diffs created with Psych.
if diff_text.encoding == Encoding::BINARY && !diff_text.ascii_only?
hash[:binary] = true
- hash[:diff] = [diff_text].pack('m0')
+ hash[:diff] = [diff_text].pack("m0")
end
end
- end
+ }
[commit_rows, file_rows]
end
@@ -132,9 +141,9 @@ module Gitlab
# display - it won't change file modes in the repository. Submodules are
# created as 600, regular files as 644.
def guess_mode(file_missing, diff)
- return '0' if file_missing
+ return "0" if file_missing
- diff.include?('Subproject commit') ? '160000' : '100644'
+ diff.include?("Subproject commit") ? "160000" : "100644"
end
# Unlike MergeRequestDiff#valid_raw_diff?, don't count Rugged objects as
diff --git a/lib/gitlab/background_migration/digest_column.rb b/lib/gitlab/background_migration/digest_column.rb
index 22a3bb8f8f3..2ad64f63e98 100644
--- a/lib/gitlab/background_migration/digest_column.rb
+++ b/lib/gitlab/background_migration/digest_column.rb
@@ -5,7 +5,7 @@ module Gitlab
module BackgroundMigration
class DigestColumn
class PersonalAccessToken < ActiveRecord::Base
- self.table_name = 'personal_access_tokens'
+ self.table_name = "personal_access_tokens"
end
def perform(model, attribute_from, attribute_to, start_id, stop_id)
diff --git a/lib/gitlab/background_migration/encrypt_columns.rb b/lib/gitlab/background_migration/encrypt_columns.rb
index b9ad8267e37..0362e11705b 100644
--- a/lib/gitlab/background_migration/encrypt_columns.rb
+++ b/lib/gitlab/background_migration/encrypt_columns.rb
@@ -46,7 +46,7 @@ module Gitlab
# Build a hash of { attribute => encrypted column name }
def expand_attributes(klass, attributes)
- expanded = attributes.flat_map do |attribute|
+ expanded = attributes.flat_map { |attribute|
attr_config = klass.encrypted_attributes[attribute]
crypt_column_name = attr_config&.fetch(:attribute)
@@ -62,7 +62,7 @@ module Gitlab
klass.column_names.include?(crypt_column_name.to_s)
[attribute, crypt_column_name]
- end
+ }
Hash[*expanded]
end
diff --git a/lib/gitlab/background_migration/fill_file_store_job_artifact.rb b/lib/gitlab/background_migration/fill_file_store_job_artifact.rb
index 103bd98af14..4e98b4eb4a0 100644
--- a/lib/gitlab/background_migration/fill_file_store_job_artifact.rb
+++ b/lib/gitlab/background_migration/fill_file_store_job_artifact.rb
@@ -1,11 +1,12 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
module BackgroundMigration
class FillFileStoreJobArtifact
class JobArtifact < ActiveRecord::Base
- self.table_name = 'ci_job_artifacts'
+ self.table_name = "ci_job_artifacts"
end
def perform(start_id, stop_id)
diff --git a/lib/gitlab/background_migration/fill_file_store_lfs_object.rb b/lib/gitlab/background_migration/fill_file_store_lfs_object.rb
index 77c1f1ffaf0..9ccdf04bbe2 100644
--- a/lib/gitlab/background_migration/fill_file_store_lfs_object.rb
+++ b/lib/gitlab/background_migration/fill_file_store_lfs_object.rb
@@ -1,11 +1,12 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
module BackgroundMigration
class FillFileStoreLfsObject
class LfsObject < ActiveRecord::Base
- self.table_name = 'lfs_objects'
+ self.table_name = "lfs_objects"
end
def perform(start_id, stop_id)
diff --git a/lib/gitlab/background_migration/fill_store_upload.rb b/lib/gitlab/background_migration/fill_store_upload.rb
index cba3e21cea6..f3ee5eee60e 100644
--- a/lib/gitlab/background_migration/fill_store_upload.rb
+++ b/lib/gitlab/background_migration/fill_store_upload.rb
@@ -1,11 +1,12 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
module BackgroundMigration
class FillStoreUpload
class Upload < ActiveRecord::Base
- self.table_name = 'uploads'
+ self.table_name = "uploads"
self.inheritance_column = :_type_disabled
end
diff --git a/lib/gitlab/background_migration/fix_cross_project_label_links.rb b/lib/gitlab/background_migration/fix_cross_project_label_links.rb
index 0a12401c35f..5ac3d0fc647 100644
--- a/lib/gitlab/background_migration/fix_cross_project_label_links.rb
+++ b/lib/gitlab/background_migration/fix_cross_project_label_links.rb
@@ -1,45 +1,46 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
module BackgroundMigration
class FixCrossProjectLabelLinks
- GROUP_NESTED_LEVEL = 10.freeze
+ GROUP_NESTED_LEVEL = 10
class Project < ActiveRecord::Base
- self.table_name = 'projects'
+ self.table_name = "projects"
end
class Label < ActiveRecord::Base
self.inheritance_column = :_type_disabled
- self.table_name = 'labels'
+ self.table_name = "labels"
end
class LabelLink < ActiveRecord::Base
- self.table_name = 'label_links'
+ self.table_name = "label_links"
end
class Issue < ActiveRecord::Base
- self.table_name = 'issues'
+ self.table_name = "issues"
end
class MergeRequest < ActiveRecord::Base
- self.table_name = 'merge_requests'
+ self.table_name = "merge_requests"
end
class Namespace < ActiveRecord::Base
self.inheritance_column = :_type_disabled
- self.table_name = 'namespaces'
+ self.table_name = "namespaces"
def self.groups_with_descendants_ids(start_id, stop_id)
# To isolate migration code, we avoid usage of
# Gitlab::GroupHierarchy#base_and_descendants which already
# does this job better
- ids = Namespace.where(type: 'Group', id: Label.where(type: 'GroupLabel').select('distinct group_id')).where(id: start_id..stop_id).pluck(:id)
+ ids = Namespace.where(type: "Group", id: Label.where(type: "GroupLabel").select("distinct group_id")).where(id: start_id..stop_id).pluck(:id)
group_ids = ids
GROUP_NESTED_LEVEL.times do
- ids = Namespace.where(type: 'Group', parent_id: ids).pluck(:id)
+ ids = Namespace.where(type: "Group", parent_id: ids).pluck(:id)
break if ids.empty?
group_ids += ids
@@ -67,10 +68,10 @@ module Gitlab
.joins('INNER JOIN label_links ON label_links.label_id = labels.id AND label_links.target_type = \'Issue\'
INNER JOIN issues ON issues.id = label_links.target_id
INNER JOIN projects ON projects.id = issues.project_id')
- .where('issues.project_id in (?)', project_ids)
- .where('(labels.project_id is not null and labels.project_id != issues.project_id) '\
- 'or (labels.group_id is not null and labels.group_id != projects.namespace_id)')
- .select('distinct issues.id')
+ .where("issues.project_id in (?)", project_ids)
+ .where("(labels.project_id is not null and labels.project_id != issues.project_id) "\
+ "or (labels.group_id is not null and labels.group_id != projects.namespace_id)")
+ .select("distinct issues.id")
Issue.where(id: issue_ids).find_each { |issue| check_resource_labels(issue, issue.project_id) }
end
@@ -83,10 +84,10 @@ module Gitlab
.joins('INNER JOIN label_links ON label_links.label_id = labels.id AND label_links.target_type = \'MergeRequest\'
INNER JOIN merge_requests ON merge_requests.id = label_links.target_id
INNER JOIN projects ON projects.id = merge_requests.target_project_id')
- .where('merge_requests.target_project_id in (?)', project_ids)
- .where('(labels.project_id is not null and labels.project_id != merge_requests.target_project_id) '\
- 'or (labels.group_id is not null and labels.group_id != projects.namespace_id)')
- .select('distinct merge_requests.id')
+ .where("merge_requests.target_project_id in (?)", project_ids)
+ .where("(labels.project_id is not null and labels.project_id != merge_requests.target_project_id) "\
+ "or (labels.group_id is not null and labels.group_id != projects.namespace_id)")
+ .select("distinct merge_requests.id")
MergeRequest.where(id: mr_ids).find_each { |merge_request| check_resource_labels(merge_request, merge_request.target_project_id) }
end
@@ -98,10 +99,10 @@ module Gitlab
# which reference a label not included in avaiable_labels
# (other than its project labels and labels of ancestor groups)
cross_labels = LabelLink
- .select('label_id, labels.title as title, labels.color as color, label_links.id as label_link_id')
- .joins('INNER JOIN labels ON labels.id = label_links.label_id')
+ .select("label_id, labels.title as title, labels.color as color, label_links.id as label_link_id")
+ .joins("INNER JOIN labels ON labels.id = label_links.label_id")
.where(target_type: resource.class.name.demodulize, target_id: resource.id)
- .where('labels.id not in (?)', local_labels.select(:id))
+ .where("labels.id not in (?)", local_labels.select(:id))
cross_labels.each do |label|
matching_label = local_labels.find {|l| l.title == label.title && l.color == label.color}
@@ -119,8 +120,8 @@ module Gitlab
@labels ||= {}
@labels[project_id] ||= Label
.where("(type = 'GroupLabel' and group_id in (?)) or (type = 'ProjectLabel' and id = ?)",
- project_group_ids(project_id),
- project_id)
+ project_group_ids(project_id),
+ project_id)
end
def project_group_ids(project_id)
diff --git a/lib/gitlab/background_migration/migrate_build_stage.rb b/lib/gitlab/background_migration/migrate_build_stage.rb
index 268c6083d3c..b80cd9e2b4f 100644
--- a/lib/gitlab/background_migration/migrate_build_stage.rb
+++ b/lib/gitlab/background_migration/migrate_build_stage.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
@@ -6,11 +7,11 @@ module Gitlab
class MigrateBuildStage
module Migratable
class Stage < ActiveRecord::Base
- self.table_name = 'ci_stages'
+ self.table_name = "ci_stages"
end
class Build < ActiveRecord::Base
- self.table_name = 'ci_builds'
+ self.table_name = "ci_builds"
self.inheritance_column = :_type_disabled
def ensure_stage!(attempts: 2)
@@ -21,22 +22,22 @@ module Gitlab
end
def find_stage
- Stage.find_by(name: self.stage || 'test',
- pipeline_id: self.commit_id,
- project_id: self.project_id)
+ Stage.find_by(name: stage || "test",
+ pipeline_id: commit_id,
+ project_id: project_id)
end
def create_stage!
- Stage.create!(name: self.stage || 'test',
- pipeline_id: self.commit_id,
- project_id: self.project_id)
+ Stage.create!(name: stage || "test",
+ pipeline_id: commit_id,
+ project_id: project_id)
end
end
end
def perform(start_id, stop_id)
- stages = Migratable::Build.where('stage_id IS NULL')
- .where('id BETWEEN ? AND ?', start_id, stop_id)
+ stages = Migratable::Build.where("stage_id IS NULL")
+ .where("id BETWEEN ? AND ?", start_id, stop_id)
.map { |build| build.ensure_stage! }
.compact.map(&:id)
diff --git a/lib/gitlab/background_migration/migrate_build_stage_id_reference.rb b/lib/gitlab/background_migration/migrate_build_stage_id_reference.rb
index 0a8a4313cd5..14be937db7f 100644
--- a/lib/gitlab/background_migration/migrate_build_stage_id_reference.rb
+++ b/lib/gitlab/background_migration/migrate_build_stage_id_reference.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
diff --git a/lib/gitlab/background_migration/migrate_events_to_push_event_payloads.rb b/lib/gitlab/background_migration/migrate_events_to_push_event_payloads.rb
index 38fecac1bfe..79831238896 100644
--- a/lib/gitlab/background_migration/migrate_events_to_push_event_payloads.rb
+++ b/lib/gitlab/background_migration/migrate_events_to_push_event_payloads.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
@@ -8,12 +9,12 @@ module Gitlab
# created in the push_event_payloads table.
class MigrateEventsToPushEventPayloads
class Event < ActiveRecord::Base
- self.table_name = 'events'
+ self.table_name = "events"
serialize :data
- BLANK_REF = ('0' * 40).freeze
- TAG_REF_PREFIX = 'refs/tags/'.freeze
+ BLANK_REF = ("0" * 40).freeze
+ TAG_REF_PREFIX = "refs/tags/"
MAX_INDEX = 69
PUSHED = 5
@@ -100,21 +101,21 @@ module Gitlab
end
class EventForMigration < ActiveRecord::Base
- self.table_name = 'events_for_migration'
+ self.table_name = "events_for_migration"
end
class PushEventPayload < ActiveRecord::Base
- self.table_name = 'push_event_payloads'
+ self.table_name = "push_event_payloads"
enum action: {
created: 0,
removed: 1,
- pushed: 2
+ pushed: 2,
}
enum ref_type: {
branch: 0,
- tag: 1
+ tag: 1,
}
end
@@ -162,7 +163,7 @@ module Gitlab
def find_events(start_id, end_id)
Event
- .where('NOT EXISTS (SELECT true FROM events_for_migration WHERE events_for_migration.id = events.id)')
+ .where("NOT EXISTS (SELECT true FROM events_for_migration WHERE events_for_migration.id = events.id)")
.where(id: start_id..end_id)
end
@@ -172,7 +173,7 @@ module Gitlab
end
def pack(value)
- value ? [value].pack('H*') : nil
+ value ? [value].pack("H*") : nil
end
end
end
diff --git a/lib/gitlab/background_migration/migrate_legacy_artifacts.rb b/lib/gitlab/background_migration/migrate_legacy_artifacts.rb
index 5cd638083b0..07b18c759a5 100644
--- a/lib/gitlab/background_migration/migrate_legacy_artifacts.rb
+++ b/lib/gitlab/background_migration/migrate_legacy_artifacts.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Metrics/ClassLength
module Gitlab
diff --git a/lib/gitlab/background_migration/migrate_stage_index.rb b/lib/gitlab/background_migration/migrate_stage_index.rb
index f90f35a913d..238bdad0f66 100644
--- a/lib/gitlab/background_migration/migrate_stage_index.rb
+++ b/lib/gitlab/background_migration/migrate_stage_index.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
diff --git a/lib/gitlab/background_migration/migrate_stage_status.rb b/lib/gitlab/background_migration/migrate_stage_status.rb
index 6a29a632577..f9f3d54dbac 100644
--- a/lib/gitlab/background_migration/migrate_stage_status.rb
+++ b/lib/gitlab/background_migration/migrate_stage_status.rb
@@ -1,25 +1,26 @@
# frozen_string_literal: true
+
# rubocop:disable Metrics/AbcSize
# rubocop:disable Style/Documentation
module Gitlab
module BackgroundMigration
class MigrateStageStatus
- STATUSES = { created: 0, pending: 1, running: 2, success: 3,
- failed: 4, canceled: 5, skipped: 6, manual: 7 }.freeze
+ STATUSES = {created: 0, pending: 1, running: 2, success: 3,
+ failed: 4, canceled: 5, skipped: 6, manual: 7,}.freeze
class Build < ActiveRecord::Base
- self.table_name = 'ci_builds'
+ self.table_name = "ci_builds"
scope :latest, -> { where(retried: [false, nil]) }
- scope :created, -> { where(status: 'created') }
- scope :running, -> { where(status: 'running') }
- scope :pending, -> { where(status: 'pending') }
- scope :success, -> { where(status: 'success') }
- scope :failed, -> { where(status: 'failed') }
- scope :canceled, -> { where(status: 'canceled') }
- scope :skipped, -> { where(status: 'skipped') }
- scope :manual, -> { where(status: 'manual') }
+ scope :created, -> { where(status: "created") }
+ scope :running, -> { where(status: "running") }
+ scope :pending, -> { where(status: "pending") }
+ scope :success, -> { where(status: "success") }
+ scope :failed, -> { where(status: "failed") }
+ scope :canceled, -> { where(status: "canceled") }
+ scope :skipped, -> { where(status: "skipped") }
+ scope :manual, -> { where(status: "manual") }
scope :failed_but_allowed, -> do
where(allow_failure: true, status: [:failed, :canceled])
@@ -34,15 +35,15 @@ module Gitlab
scope_relevant = latest.exclude_ignored
scope_warnings = latest.failed_but_allowed
- builds = scope_relevant.select('count(*)').to_sql
- created = scope_relevant.created.select('count(*)').to_sql
- success = scope_relevant.success.select('count(*)').to_sql
- manual = scope_relevant.manual.select('count(*)').to_sql
- pending = scope_relevant.pending.select('count(*)').to_sql
- running = scope_relevant.running.select('count(*)').to_sql
- skipped = scope_relevant.skipped.select('count(*)').to_sql
- canceled = scope_relevant.canceled.select('count(*)').to_sql
- warnings = scope_warnings.select('count(*) > 0').to_sql
+ builds = scope_relevant.select("count(*)").to_sql
+ created = scope_relevant.created.select("count(*)").to_sql
+ success = scope_relevant.success.select("count(*)").to_sql
+ manual = scope_relevant.manual.select("count(*)").to_sql
+ pending = scope_relevant.pending.select("count(*)").to_sql
+ running = scope_relevant.running.select("count(*)").to_sql
+ skipped = scope_relevant.skipped.select("count(*)").to_sql
+ canceled = scope_relevant.canceled.select("count(*)").to_sql
+ warnings = scope_warnings.select("count(*) > 0").to_sql
<<-SQL.strip_heredoc
(CASE
@@ -64,8 +65,8 @@ module Gitlab
def perform(start_id, stop_id)
status_sql = Build
- .where('ci_builds.commit_id = ci_stages.pipeline_id')
- .where('ci_builds.stage = ci_stages.name')
+ .where("ci_builds.commit_id = ci_stages.pipeline_id")
+ .where("ci_builds.stage = ci_stages.name")
.status_sql
sql = <<-SQL
diff --git a/lib/gitlab/background_migration/migrate_system_uploads_to_new_folder.rb b/lib/gitlab/background_migration/migrate_system_uploads_to_new_folder.rb
index ef50fe4adb1..651fd496eb0 100644
--- a/lib/gitlab/background_migration/migrate_system_uploads_to_new_folder.rb
+++ b/lib/gitlab/background_migration/migrate_system_uploads_to_new_folder.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
@@ -8,7 +9,7 @@ module Gitlab
attr_reader :old_folder, :new_folder
class Upload < ActiveRecord::Base
- self.table_name = 'uploads'
+ self.table_name = "uploads"
include EachBatch
end
@@ -22,7 +23,7 @@ module Gitlab
end
def uploads
- Arel::Table.new('uploads')
+ Arel::Table.new("uploads")
end
end
end
diff --git a/lib/gitlab/background_migration/models/encrypt_columns/namespace.rb b/lib/gitlab/background_migration/models/encrypt_columns/namespace.rb
index 41f18979d76..45bbb19ceb7 100644
--- a/lib/gitlab/background_migration/models/encrypt_columns/namespace.rb
+++ b/lib/gitlab/background_migration/models/encrypt_columns/namespace.rb
@@ -10,7 +10,7 @@ module Gitlab
class Namespace < ActiveRecord::Base
include ::EachBatch
- self.table_name = 'namespaces'
+ self.table_name = "namespaces"
self.inheritance_column = :_type_disabled
def runners_token=(value)
@@ -19,7 +19,7 @@ module Gitlab
end
def self.encrypted_attributes
- { runners_token: { attribute: :runners_token_encrypted } }
+ {runners_token: {attribute: :runners_token_encrypted}}
end
end
end
diff --git a/lib/gitlab/background_migration/models/encrypt_columns/project.rb b/lib/gitlab/background_migration/models/encrypt_columns/project.rb
index bfeae14584d..90a8ed2512b 100644
--- a/lib/gitlab/background_migration/models/encrypt_columns/project.rb
+++ b/lib/gitlab/background_migration/models/encrypt_columns/project.rb
@@ -10,7 +10,7 @@ module Gitlab
class Project < ActiveRecord::Base
include ::EachBatch
- self.table_name = 'projects'
+ self.table_name = "projects"
self.inheritance_column = :_type_disabled
def runners_token=(value)
@@ -19,7 +19,7 @@ module Gitlab
end
def self.encrypted_attributes
- { runners_token: { attribute: :runners_token_encrypted } }
+ {runners_token: {attribute: :runners_token_encrypted}}
end
end
end
diff --git a/lib/gitlab/background_migration/models/encrypt_columns/runner.rb b/lib/gitlab/background_migration/models/encrypt_columns/runner.rb
index 14ddce4b147..70015ad0989 100644
--- a/lib/gitlab/background_migration/models/encrypt_columns/runner.rb
+++ b/lib/gitlab/background_migration/models/encrypt_columns/runner.rb
@@ -10,7 +10,7 @@ module Gitlab
class Runner < ActiveRecord::Base
include ::EachBatch
- self.table_name = 'ci_runners'
+ self.table_name = "ci_runners"
self.inheritance_column = :_type_disabled
def token=(value)
@@ -19,7 +19,7 @@ module Gitlab
end
def self.encrypted_attributes
- { token: { attribute: :token_encrypted } }
+ {token: {attribute: :token_encrypted}}
end
end
end
diff --git a/lib/gitlab/background_migration/models/encrypt_columns/settings.rb b/lib/gitlab/background_migration/models/encrypt_columns/settings.rb
index 08ae35c0671..5ddfbbbe6f3 100644
--- a/lib/gitlab/background_migration/models/encrypt_columns/settings.rb
+++ b/lib/gitlab/background_migration/models/encrypt_columns/settings.rb
@@ -11,7 +11,7 @@ module Gitlab
include ::EachBatch
include ::CacheableAttributes
- self.table_name = 'application_settings'
+ self.table_name = "application_settings"
self.inheritance_column = :_type_disabled
after_commit do
@@ -26,8 +26,8 @@ module Gitlab
def self.encrypted_attributes
{
runners_registration_token: {
- attribute: :runners_registration_token_encrypted
- }
+ attribute: :runners_registration_token_encrypted,
+ },
}
end
end
diff --git a/lib/gitlab/background_migration/models/encrypt_columns/web_hook.rb b/lib/gitlab/background_migration/models/encrypt_columns/web_hook.rb
index 34e72fd9f34..ae1367b4817 100644
--- a/lib/gitlab/background_migration/models/encrypt_columns/web_hook.rb
+++ b/lib/gitlab/background_migration/models/encrypt_columns/web_hook.rb
@@ -9,18 +9,18 @@ module Gitlab
class WebHook < ActiveRecord::Base
include ::EachBatch
- self.table_name = 'web_hooks'
+ self.table_name = "web_hooks"
self.inheritance_column = :_type_disabled
attr_encrypted :token,
- mode: :per_attribute_iv,
- algorithm: 'aes-256-gcm',
- key: ::Settings.attr_encrypted_db_key_base_32
+ mode: :per_attribute_iv,
+ algorithm: "aes-256-gcm",
+ key: ::Settings.attr_encrypted_db_key_base_32
attr_encrypted :url,
- mode: :per_attribute_iv,
- algorithm: 'aes-256-gcm',
- key: ::Settings.attr_encrypted_db_key_base_32
+ mode: :per_attribute_iv,
+ algorithm: "aes-256-gcm",
+ key: ::Settings.attr_encrypted_db_key_base_32
end
end
end
diff --git a/lib/gitlab/background_migration/move_personal_snippet_files.rb b/lib/gitlab/background_migration/move_personal_snippet_files.rb
index 5b2b2af718a..8a8103d2ace 100644
--- a/lib/gitlab/background_migration/move_personal_snippet_files.rb
+++ b/lib/gitlab/background_migration/move_personal_snippet_files.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
@@ -17,11 +18,11 @@ module Gitlab
query = "SELECT uploads.path, uploads.model_id FROM uploads "\
"INNER JOIN snippets ON snippets.id = uploads.model_id WHERE uploader = 'PersonalFileUploader'"
select_all(query).each do |upload|
- secret = upload['path'].split('/')[0]
- file_name = upload['path'].split('/')[1]
+ secret = upload["path"].split("/")[0]
+ file_name = upload["path"].split("/")[1]
- move_file(upload['model_id'], secret, file_name)
- update_markdown(upload['model_id'], secret, file_name)
+ move_file(upload["model_id"], secret, file_name)
+ update_markdown(upload["model_id"], secret, file_name)
end
end
@@ -59,15 +60,15 @@ module Gitlab
query = "SELECT id, note FROM notes WHERE noteable_id = #{snippet_id} "\
"AND noteable_type = 'Snippet' AND note IS NOT NULL"
select_all(query).each do |note|
- text = note['note'].gsub(source_markdown, destination_markdown)
+ text = note["note"].gsub(source_markdown, destination_markdown)
quoted_text = quote_string(text)
- execute("UPDATE notes SET note = '#{quoted_text}', note_html = NULL WHERE id = #{note['id']}")
+ execute("UPDATE notes SET note = '#{quoted_text}', note_html = NULL WHERE id = #{note["id"]}")
end
end
def base_directory
- File.join(Rails.root, 'public')
+ File.join(Rails.root, "public")
end
def connection
diff --git a/lib/gitlab/background_migration/normalize_ldap_extern_uids_range.rb b/lib/gitlab/background_migration/normalize_ldap_extern_uids_range.rb
index 698f5e46c0c..2a921c0e36e 100644
--- a/lib/gitlab/background_migration/normalize_ldap_extern_uids_range.rb
+++ b/lib/gitlab/background_migration/normalize_ldap_extern_uids_range.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/ClassLength
# rubocop:disable Metrics/BlockLength
@@ -8,7 +9,7 @@ module Gitlab
module BackgroundMigration
class NormalizeLdapExternUidsRange
class Identity < ActiveRecord::Base
- self.table_name = 'identities'
+ self.table_name = "identities"
end
# Copied this class to make this migration resilient to future code changes.
@@ -25,7 +26,7 @@ module Gitlab
def self.normalize_value(given_value)
dummy_dn = "placeholder=#{given_value}"
normalized_dn = new(*dummy_dn).to_normalized_s
- normalized_dn.sub(/\Aplaceholder=/, '')
+ normalized_dn.sub(/\Aplaceholder=/, "")
end
##
@@ -60,36 +61,36 @@ module Gitlab
case state
when :key then
case char
- when 'a'..'z', 'A'..'Z' then
+ when "a".."z", "A".."Z" then
state = :key_normal
key << char
- when '0'..'9' then
+ when "0".."9" then
state = :key_oid
key << char
- when ' ' then state = :key
+ when " " then state = :key
else raise(MalformedError, "Unrecognized first character of an RDN attribute type name \"#{char}\"")
end
when :key_normal then
case char
- when '=' then state = :value
- when 'a'..'z', 'A'..'Z', '0'..'9', '-', ' ' then key << char
+ when "=" then state = :value
+ when "a".."z", "A".."Z", "0".."9", "-", " " then key << char
else raise(MalformedError, "Unrecognized RDN attribute type name character \"#{char}\"")
end
when :key_oid then
case char
- when '=' then state = :value
- when '0'..'9', '.', ' ' then key << char
+ when "=" then state = :value
+ when "0".."9", ".", " " then key << char
else raise(MalformedError, "Unrecognized RDN OID attribute type name character \"#{char}\"")
end
when :value then
case char
when '\\' then state = :value_normal_escape
when '"' then state = :value_quoted
- when ' ' then state = :value
- when '#' then
+ when " " then state = :value
+ when "#" then
state = :value_hexstring
value << char
- when ',' then
+ when "," then
state = :key
yield key.string.strip, rstrip_except_escaped(value.string, dn_index)
key = StringIO.new
@@ -101,17 +102,17 @@ module Gitlab
when :value_normal then
case char
when '\\' then state = :value_normal_escape
- when ',' then
+ when "," then
state = :key
yield key.string.strip, rstrip_except_escaped(value.string, dn_index)
key = StringIO.new
value = StringIO.new
- when '+' then raise(UnsupportedError, "Multivalued RDNs are not supported")
+ when "+" then raise(UnsupportedError, "Multivalued RDNs are not supported")
else value << char
end
when :value_normal_escape then
case char
- when '0'..'9', 'a'..'f', 'A'..'F' then
+ when "0".."9", "a".."f", "A".."F" then
state = :value_normal_escape_hex
hex_buffer = char
else
@@ -120,7 +121,7 @@ module Gitlab
end
when :value_normal_escape_hex then
case char
- when '0'..'9', 'a'..'f', 'A'..'F' then
+ when "0".."9", "a".."f", "A".."F" then
state = :value_normal
value << "#{hex_buffer}#{char}".to_i(16).chr
else raise(MalformedError, "Invalid escaped hex code \"\\#{hex_buffer}#{char}\"")
@@ -133,7 +134,7 @@ module Gitlab
end
when :value_quoted_escape then
case char
- when '0'..'9', 'a'..'f', 'A'..'F' then
+ when "0".."9", "a".."f", "A".."F" then
state = :value_quoted_escape_hex
hex_buffer = char
else
@@ -142,18 +143,18 @@ module Gitlab
end
when :value_quoted_escape_hex then
case char
- when '0'..'9', 'a'..'f', 'A'..'F' then
+ when "0".."9", "a".."f", "A".."F" then
state = :value_quoted
value << "#{hex_buffer}#{char}".to_i(16).chr
else raise(MalformedError, "Expected the second character of a hex pair inside a double quoted value, but got \"#{char}\"")
end
when :value_hexstring then
case char
- when '0'..'9', 'a'..'f', 'A'..'F' then
+ when "0".."9", "a".."f", "A".."F" then
state = :value_hexstring_hex
value << char
- when ' ' then state = :value_end
- when ',' then
+ when " " then state = :value_end
+ when "," then
state = :key
yield key.string.strip, rstrip_except_escaped(value.string, dn_index)
key = StringIO.new
@@ -162,15 +163,15 @@ module Gitlab
end
when :value_hexstring_hex then
case char
- when '0'..'9', 'a'..'f', 'A'..'F' then
+ when "0".."9", "a".."f", "A".."F" then
state = :value_hexstring
value << char
else raise(MalformedError, "Expected the second character of a hex pair, but got \"#{char}\"")
end
when :value_end then
case char
- when ' ' then state = :value_end
- when ',' then
+ when " " then state = :value_end
+ when "," then
state = :key
yield key.string.strip, rstrip_except_escaped(value.string, dn_index)
key = StringIO.new
@@ -182,7 +183,7 @@ module Gitlab
end
# Last pair
- raise(MalformedError, 'DN string ended unexpectedly') unless
+ raise(MalformedError, "DN string ended unexpectedly") unless
[:value, :value_normal, :value_hexstring, :value_end].include? state
yield key.string.strip, rstrip_except_escaped(value.string, @dn.length)
@@ -210,7 +211,7 @@ module Gitlab
# Returns the DN as an array in the form expected by the constructor.
def to_a
a = []
- self.each_pair { |key, value| a << key << value } unless @dn.empty?
+ each_pair { |key, value| a << key << value } unless @dn.empty?
a
end
@@ -231,12 +232,12 @@ module Gitlab
# using a single backslash ('\') as escape. The space character is left
# out here because in a "normalized" string, spaces should only be escaped
# if necessary (i.e. leading or trailing space).
- NORMAL_ESCAPES = [',', '+', '"', '\\', '<', '>', ';', '='].freeze
+ NORMAL_ESCAPES = [",", "+", '"', '\\', "<", ">", ";", "="].freeze
# The following must be represented as escaped hex
HEX_ESCAPES = {
"\n" => '\0a',
- "\r" => '\0d'
+ "\r" => '\0d',
}.freeze
# Compiled character class regexp using the keys from the above hash, and
@@ -302,14 +303,12 @@ module Gitlab
ldap_identities = Identity.where("provider like 'ldap%'").where(id: start_id..end_id)
ldap_identities.each do |identity|
- begin
- identity.extern_uid = Gitlab::Auth::LDAP::DN.new(identity.extern_uid).to_normalized_s
- unless identity.save
- Rails.logger.info "Unable to normalize \"#{identity.extern_uid}\". Skipping."
- end
- rescue Gitlab::Auth::LDAP::DN::FormatError => e
- Rails.logger.info "Unable to normalize \"#{identity.extern_uid}\" due to \"#{e.message}\". Skipping."
+ identity.extern_uid = Gitlab::Auth::LDAP::DN.new(identity.extern_uid).to_normalized_s
+ unless identity.save
+ Rails.logger.info "Unable to normalize \"#{identity.extern_uid}\". Skipping."
end
+ rescue Gitlab::Auth::LDAP::DN::FormatError => e
+ Rails.logger.info "Unable to normalize \"#{identity.extern_uid}\" due to \"#{e.message}\". Skipping."
end
end
diff --git a/lib/gitlab/background_migration/populate_cluster_kubernetes_namespace_table.rb b/lib/gitlab/background_migration/populate_cluster_kubernetes_namespace_table.rb
index 35bfc381180..9eb3509be6d 100644
--- a/lib/gitlab/background_migration/populate_cluster_kubernetes_namespace_table.rb
+++ b/lib/gitlab/background_migration/populate_cluster_kubernetes_namespace_table.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
#
# rubocop:disable Style/Documentation
@@ -11,13 +12,13 @@ module Gitlab
module Migratable
class KubernetesNamespace < ActiveRecord::Base
- self.table_name = 'clusters_kubernetes_namespaces'
+ self.table_name = "clusters_kubernetes_namespaces"
end
class ClusterProject < ActiveRecord::Base
include EachBatch
- self.table_name = 'cluster_projects'
+ self.table_name = "cluster_projects"
belongs_to :project
@@ -27,7 +28,7 @@ module Gitlab
def namespace
slug = "#{project.path}-#{project.id}".downcase
- slug.gsub(/[^-a-z0-9]/, '-').gsub(/^-+/, '')
+ slug.gsub(/[^-a-z0-9]/, "-").gsub(/^-+/, "")
end
def service_account
@@ -36,7 +37,7 @@ module Gitlab
end
class Project < ActiveRecord::Base
- self.table_name = 'projects'
+ self.table_name = "projects"
end
end
@@ -67,15 +68,15 @@ module Gitlab
project_id: cluster_project.project_id,
namespace: cluster_project.namespace,
service_account_name: cluster_project.service_account,
- created_at: 'NOW()',
- updated_at: 'NOW()'
+ created_at: "NOW()",
+ updated_at: "NOW()",
}
end
def insert_into_cluster_kubernetes_namespace(rows)
Gitlab::Database.bulk_insert(Migratable::KubernetesNamespace.table_name,
- rows,
- disable_quote: [:created_at, :updated_at])
+ rows,
+ disable_quote: [:created_at, :updated_at])
end
end
end
diff --git a/lib/gitlab/background_migration/populate_external_pipeline_source.rb b/lib/gitlab/background_migration/populate_external_pipeline_source.rb
index 036fe641757..9f0795ff2b3 100644
--- a/lib/gitlab/background_migration/populate_external_pipeline_source.rb
+++ b/lib/gitlab/background_migration/populate_external_pipeline_source.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
@@ -6,7 +7,7 @@ module Gitlab
class PopulateExternalPipelineSource
module Migratable
class Pipeline < ActiveRecord::Base
- self.table_name = 'ci_pipelines'
+ self.table_name = "ci_pipelines"
def self.sources
{
@@ -16,17 +17,17 @@ module Gitlab
trigger: 3,
schedule: 4,
api: 5,
- external: 6
+ external: 6,
}
end
end
class CommitStatus < ActiveRecord::Base
- self.table_name = 'ci_builds'
+ self.table_name = "ci_builds"
self.inheritance_column = :_type_disabled
- scope :has_pipeline, -> { where('ci_builds.commit_id=ci_pipelines.id') }
- scope :of_type, -> (type) { where('type=?', type) }
+ scope :has_pipeline, -> { where("ci_builds.commit_id=ci_pipelines.id") }
+ scope :of_type, ->(type) { where("type=?", type) }
end
end
@@ -40,9 +41,9 @@ module Gitlab
def external_pipelines(start_id, stop_id)
Migratable::Pipeline.where(id: (start_id..stop_id))
.where(
- 'EXISTS (?) AND NOT EXISTS (?)',
- Migratable::CommitStatus.of_type('GenericCommitStatus').has_pipeline.select(1),
- Migratable::CommitStatus.of_type('Ci::Build').has_pipeline.select(1)
+ "EXISTS (?) AND NOT EXISTS (?)",
+ Migratable::CommitStatus.of_type("GenericCommitStatus").has_pipeline.select(1),
+ Migratable::CommitStatus.of_type("Ci::Build").has_pipeline.select(1)
)
end
end
diff --git a/lib/gitlab/background_migration/populate_fork_networks_range.rb b/lib/gitlab/background_migration/populate_fork_networks_range.rb
index aa4f130538c..f607186974e 100644
--- a/lib/gitlab/background_migration/populate_fork_networks_range.rb
+++ b/lib/gitlab/background_migration/populate_fork_networks_range.rb
@@ -28,70 +28,62 @@ module Gitlab
def create_fork_networks_for_existing_projects(start_id, end_id)
log("Creating fork networks: #{start_id} - #{end_id}")
ActiveRecord::Base.connection.execute <<~INSERT_NETWORKS
- INSERT INTO fork_networks (root_project_id)
- SELECT DISTINCT forked_project_links.forked_from_project_id
-
- FROM forked_project_links
-
- -- Exclude the forks that are not the first level fork of a project
- WHERE NOT EXISTS (
- SELECT true
- FROM forked_project_links inner_links
- WHERE inner_links.forked_to_project_id = forked_project_links.forked_from_project_id
- )
-
- /* Exclude the ones that are already created, in case the fork network
- was already created for another fork of the project.
- */
- AND NOT EXISTS (
- SELECT true
- FROM fork_networks
- WHERE forked_project_links.forked_from_project_id = fork_networks.root_project_id
- )
-
- -- Only create a fork network for a root project that still exists
- AND EXISTS (
- SELECT true
- FROM projects
- WHERE projects.id = forked_project_links.forked_from_project_id
- )
- AND forked_project_links.id BETWEEN #{start_id} AND #{end_id}
+ INSERT INTO fork_networks (root_project_id)
+ SELECT DISTINCT forked_project_links.forked_from_project_id
+ FROM forked_project_links
+ -- Exclude the forks that are not the first level fork of a project
+ WHERE NOT EXISTS (
+ SELECT true
+ FROM forked_project_links inner_links
+ WHERE inner_links.forked_to_project_id = forked_project_links.forked_from_project_id
+ )
+ /* Exclude the ones that are already created, in case the fork network
+ was already created for another fork of the project.
+ */
+ AND NOT EXISTS (
+ SELECT true
+ FROM fork_networks
+ WHERE forked_project_links.forked_from_project_id = fork_networks.root_project_id
+ )
+ -- Only create a fork network for a root project that still exists
+ AND EXISTS (
+ SELECT true
+ FROM projects
+ WHERE projects.id = forked_project_links.forked_from_project_id
+ )
+ AND forked_project_links.id BETWEEN #{start_id} AND #{end_id}
INSERT_NETWORKS
end
def create_fork_networks_for_missing_projects(start_id, end_id)
log("Creating fork networks with missing root: #{start_id} - #{end_id}")
ActiveRecord::Base.connection.execute <<~INSERT_NETWORKS
- INSERT INTO fork_networks (root_project_id)
- SELECT DISTINCT forked_project_links.forked_to_project_id
-
- FROM forked_project_links
-
- -- Exclude forks that are not the root forks
- WHERE NOT EXISTS (
- SELECT true
- FROM forked_project_links inner_links
- WHERE inner_links.forked_to_project_id = forked_project_links.forked_from_project_id
- )
-
- /* Exclude the ones that are already created, in case this migration is
- re-run
- */
- AND NOT EXISTS (
- SELECT true
- FROM fork_networks
- WHERE forked_project_links.forked_to_project_id = fork_networks.root_project_id
- )
-
- /* Exclude projects for which the project still exists, those are
- Processed in the previous step of this migration
- */
- AND NOT EXISTS (
- SELECT true
- FROM projects
- WHERE projects.id = forked_project_links.forked_from_project_id
- )
- AND forked_project_links.id BETWEEN #{start_id} AND #{end_id}
+ INSERT INTO fork_networks (root_project_id)
+ SELECT DISTINCT forked_project_links.forked_to_project_id
+ FROM forked_project_links
+ -- Exclude forks that are not the root forks
+ WHERE NOT EXISTS (
+ SELECT true
+ FROM forked_project_links inner_links
+ WHERE inner_links.forked_to_project_id = forked_project_links.forked_from_project_id
+ )
+ /* Exclude the ones that are already created, in case this migration is
+ re-run
+ */
+ AND NOT EXISTS (
+ SELECT true
+ FROM fork_networks
+ WHERE forked_project_links.forked_to_project_id = fork_networks.root_project_id
+ )
+ /* Exclude projects for which the project still exists, those are
+ Processed in the previous step of this migration
+ */
+ AND NOT EXISTS (
+ SELECT true
+ FROM projects
+ WHERE projects.id = forked_project_links.forked_from_project_id
+ )
+ AND forked_project_links.id BETWEEN #{start_id} AND #{end_id}
INSERT_NETWORKS
end
diff --git a/lib/gitlab/background_migration/populate_merge_request_metrics_with_events_data.rb b/lib/gitlab/background_migration/populate_merge_request_metrics_with_events_data.rb
index d89ce358bb9..302157798aa 100644
--- a/lib/gitlab/background_migration/populate_merge_request_metrics_with_events_data.rb
+++ b/lib/gitlab/background_migration/populate_merge_request_metrics_with_events_data.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
diff --git a/lib/gitlab/background_migration/populate_merge_request_metrics_with_events_data_improved.rb b/lib/gitlab/background_migration/populate_merge_request_metrics_with_events_data_improved.rb
index 37592d67dd9..5de0c3894f1 100644
--- a/lib/gitlab/background_migration/populate_merge_request_metrics_with_events_data_improved.rb
+++ b/lib/gitlab/background_migration/populate_merge_request_metrics_with_events_data_improved.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
diff --git a/lib/gitlab/background_migration/populate_merge_requests_latest_merge_request_diff_id.rb b/lib/gitlab/background_migration/populate_merge_requests_latest_merge_request_diff_id.rb
index dcac355e1b0..0116b07ea79 100644
--- a/lib/gitlab/background_migration/populate_merge_requests_latest_merge_request_diff_id.rb
+++ b/lib/gitlab/background_migration/populate_merge_requests_latest_merge_request_diff_id.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
@@ -7,7 +8,7 @@ module Gitlab
BATCH_SIZE = 1_000
class MergeRequest < ActiveRecord::Base
- self.table_name = 'merge_requests'
+ self.table_name = "merge_requests"
include ::EachBatch
end
diff --git a/lib/gitlab/background_migration/populate_untracked_uploads.rb b/lib/gitlab/background_migration/populate_untracked_uploads.rb
index a19dc9747fb..21b13a1bab7 100644
--- a/lib/gitlab/background_migration/populate_untracked_uploads.rb
+++ b/lib/gitlab/background_migration/populate_untracked_uploads.rb
@@ -34,18 +34,16 @@ module Gitlab
def filter_error_files(files)
files.partition do |file|
- begin
- file.to_h
- true
- rescue => e
- msg = <<~MSG
- Error parsing path "#{file.path}":
- #{e.message}
- #{e.backtrace.join("\n ")}
- MSG
- Rails.logger.error(msg)
- false
- end
+ file.to_h
+ true
+ rescue => e
+ msg = <<~MSG
+ Error parsing path "#{file.path}":
+ #{e.message}
+ #{e.backtrace.join("\n ")}
+ MSG
+ Rails.logger.error(msg)
+ false
end
end
@@ -70,11 +68,11 @@ module Gitlab
def deleted_model_ids(files)
ids = {
- 'Appearance' => [],
- 'Namespace' => [],
- 'Note' => [],
- 'Project' => [],
- 'User' => []
+ "Appearance" => [],
+ "Namespace" => [],
+ "Note" => [],
+ "Project" => [],
+ "User" => [],
}
# group model IDs by model type
@@ -93,19 +91,19 @@ module Gitlab
end
def insert(files)
- rows = files.map do |file|
- file.to_h.merge(created_at: 'NOW()')
- end
+ rows = files.map { |file|
+ file.to_h.merge(created_at: "NOW()")
+ }
- Gitlab::Database.bulk_insert('uploads',
- rows,
- disable_quote: :created_at)
+ Gitlab::Database.bulk_insert("uploads",
+ rows,
+ disable_quote: :created_at)
end
def drop_temp_table_if_finished
if Gitlab::BackgroundMigration::PopulateUntrackedUploadsDependencies::UntrackedFile.all.empty? && !Rails.env.test? # Dropping a table intermittently breaks test cleanup
Gitlab::BackgroundMigration::PopulateUntrackedUploadsDependencies::UntrackedFile.connection.drop_table(:untracked_files_for_uploads,
- if_exists: true)
+ if_exists: true)
end
end
end
diff --git a/lib/gitlab/background_migration/populate_untracked_uploads_dependencies.rb b/lib/gitlab/background_migration/populate_untracked_uploads_dependencies.rb
index 4a9a62aaeb5..bf7d3d6a9ca 100644
--- a/lib/gitlab/background_migration/populate_untracked_uploads_dependencies.rb
+++ b/lib/gitlab/background_migration/populate_untracked_uploads_dependencies.rb
@@ -1,11 +1,12 @@
# frozen_string_literal: true
+
module Gitlab
module BackgroundMigration
module PopulateUntrackedUploadsDependencies
# This class is responsible for producing the attributes necessary to
# track an uploaded file in the `uploads` table.
class UntrackedFile < ActiveRecord::Base # rubocop:disable Metrics/ClassLength
- self.table_name = 'untracked_files_for_uploads'
+ self.table_name = "untracked_files_for_uploads"
# Ends with /:random_hex/:filename
FILE_UPLOADER_PATH = %r{/\h+/[^/]+\z}
@@ -18,39 +19,39 @@ module Gitlab
PATH_PATTERNS = [
{
pattern: %r{\A-/system/appearance/logo/(\d+)/},
- uploader: 'AttachmentUploader',
- model_type: 'Appearance'
+ uploader: "AttachmentUploader",
+ model_type: "Appearance",
},
{
pattern: %r{\A-/system/appearance/header_logo/(\d+)/},
- uploader: 'AttachmentUploader',
- model_type: 'Appearance'
+ uploader: "AttachmentUploader",
+ model_type: "Appearance",
},
{
pattern: %r{\A-/system/note/attachment/(\d+)/},
- uploader: 'AttachmentUploader',
- model_type: 'Note'
+ uploader: "AttachmentUploader",
+ model_type: "Note",
},
{
pattern: %r{\A-/system/user/avatar/(\d+)/},
- uploader: 'AvatarUploader',
- model_type: 'User'
+ uploader: "AvatarUploader",
+ model_type: "User",
},
{
pattern: %r{\A-/system/group/avatar/(\d+)/},
- uploader: 'AvatarUploader',
- model_type: 'Namespace'
+ uploader: "AvatarUploader",
+ model_type: "Namespace",
},
{
pattern: %r{\A-/system/project/avatar/(\d+)/},
- uploader: 'AvatarUploader',
- model_type: 'Project'
+ uploader: "AvatarUploader",
+ model_type: "Project",
},
{
pattern: FILE_UPLOADER_PATH,
- uploader: 'FileUploader',
- model_type: 'Project'
- }
+ uploader: "FileUploader",
+ model_type: "Project",
+ },
].freeze
def to_h
@@ -60,17 +61,17 @@ module Gitlab
model_type: model_type,
model_id: model_id,
size: file_size,
- checksum: checksum
+ checksum: checksum,
}
end
def upload_path
# UntrackedFile#path is absolute, but Upload#path depends on uploader
@upload_path ||=
- if uploader == 'FileUploader'
+ if uploader == "FileUploader"
# Path relative to project directory in uploads
matchd = path_relative_to_upload_dir.match(FILE_UPLOADER_PATH)
- matchd[0].sub(%r{\A/}, '') # remove leading slash
+ matchd[0].sub(%r{\A/}, "") # remove leading slash
else
path
end
@@ -106,9 +107,9 @@ module Gitlab
private
def matching_pattern_map
- @matching_pattern_map ||= PATH_PATTERNS.find do |path_pattern_map|
+ @matching_pattern_map ||= PATH_PATTERNS.find { |path_pattern_map|
path_relative_to_upload_dir.match(path_pattern_map[:pattern])
- end
+ }
unless @matching_pattern_map
raise "Unknown upload path pattern \"#{path}\""
@@ -136,7 +137,7 @@ module Gitlab
def path_relative_to_upload_dir
upload_dir = Gitlab::BackgroundMigration::PrepareUntrackedUploads::RELATIVE_UPLOAD_DIR
base = %r{\A#{Regexp.escape(upload_dir)}/}
- @path_relative_to_upload_dir ||= path.sub(base, '')
+ @path_relative_to_upload_dir ||= path.sub(base, "")
end
def absolute_path
@@ -146,37 +147,37 @@ module Gitlab
# Avoid using application code
class Upload < ActiveRecord::Base
- self.table_name = 'uploads'
+ self.table_name = "uploads"
end
# Avoid using application code
class Appearance < ActiveRecord::Base
- self.table_name = 'appearances'
+ self.table_name = "appearances"
end
# Avoid using application code
class Namespace < ActiveRecord::Base
- self.table_name = 'namespaces'
+ self.table_name = "namespaces"
end
# Avoid using application code
class Note < ActiveRecord::Base
- self.table_name = 'notes'
+ self.table_name = "notes"
end
# Avoid using application code
class User < ActiveRecord::Base
- self.table_name = 'users'
+ self.table_name = "users"
end
# Since project Markdown upload paths don't contain the project ID, we have to find the
# project by its full_path. Due to MySQL/PostgreSQL differences, and historical reasons,
# the logic is somewhat complex, so I've mostly copied it in here.
class Project < ActiveRecord::Base
- self.table_name = 'projects'
+ self.table_name = "projects"
def self.find_by_full_path(path)
- binary = Gitlab::Database.mysql? ? 'BINARY' : ''
+ binary = Gitlab::Database.mysql? ? "BINARY" : ""
order_sql = "(CASE WHEN #{binary} routes.path = #{connection.quote(path)} THEN 0 ELSE 1 END)"
where_full_path_in(path).reorder(order_sql).take
end
diff --git a/lib/gitlab/background_migration/prepare_untracked_uploads.rb b/lib/gitlab/background_migration/prepare_untracked_uploads.rb
index 81ca2b0a9b7..3e54de86157 100644
--- a/lib/gitlab/background_migration/prepare_untracked_uploads.rb
+++ b/lib/gitlab/background_migration/prepare_untracked_uploads.rb
@@ -10,22 +10,22 @@ module Gitlab
include ::Gitlab::Utils::StrongMemoize
FIND_BATCH_SIZE = 500
- RELATIVE_UPLOAD_DIR = "uploads".freeze
+ RELATIVE_UPLOAD_DIR = "uploads"
ABSOLUTE_UPLOAD_DIR = File.join(
Gitlab.config.uploads.storage_path,
RELATIVE_UPLOAD_DIR
)
- FOLLOW_UP_MIGRATION = 'PopulateUntrackedUploads'.freeze
+ FOLLOW_UP_MIGRATION = "PopulateUntrackedUploads"
START_WITH_ROOT_REGEX = %r{\A#{Gitlab.config.uploads.storage_path}/}
- EXCLUDED_HASHED_UPLOADS_PATH = "#{ABSOLUTE_UPLOAD_DIR}/@hashed/*".freeze
- EXCLUDED_TMP_UPLOADS_PATH = "#{ABSOLUTE_UPLOAD_DIR}/tmp/*".freeze
+ EXCLUDED_HASHED_UPLOADS_PATH = "#{ABSOLUTE_UPLOAD_DIR}/@hashed/*"
+ EXCLUDED_TMP_UPLOADS_PATH = "#{ABSOLUTE_UPLOAD_DIR}/tmp/*"
# This class is used to iterate over batches of
# `untracked_files_for_uploads` rows.
class UntrackedFile < ActiveRecord::Base
include EachBatch
- self.table_name = 'untracked_files_for_uploads'
+ self.table_name = "untracked_files_for_uploads"
end
def perform
@@ -89,7 +89,7 @@ module Gitlab
paths = []
stdout.each_line("\0") do |line|
- paths << line.chomp("\0").sub(START_WITH_ROOT_REGEX, '')
+ paths << line.chomp("\0").sub(START_WITH_ROOT_REGEX, "")
if paths.size >= batch_size
yield(paths)
@@ -110,15 +110,15 @@ module Gitlab
ionice = which_ionice
cmd = %W[#{ionice} -c Idle] + cmd if ionice
- log_msg = "PrepareUntrackedUploads find command: \"#{cmd.join(' ')}\""
+ log_msg = "PrepareUntrackedUploads find command: \"#{cmd.join(" ")}\""
Rails.logger.info log_msg
cmd
end
def which_ionice
- Gitlab::Utils.which('ionice')
- rescue StandardError
+ Gitlab::Utils.which("ionice")
+ rescue
# In this case, returning false is relatively safe,
# even though it isn't very nice
false
@@ -143,9 +143,9 @@ module Gitlab
end
def table_columns_and_values_for_insert(file_paths)
- values = file_paths.map do |file_path|
- ActiveRecord::Base.send(:sanitize_sql_array, ['(?)', file_path]) # rubocop:disable GitlabSecurity/PublicSend
- end.join(', ')
+ values = file_paths.map { |file_path|
+ ActiveRecord::Base.send(:sanitize_sql_array, ["(?)", file_path]) # rubocop:disable GitlabSecurity/PublicSend
+ }.join(", ")
"#{UntrackedFile.table_name} (path) VALUES #{values}"
end
@@ -168,13 +168,14 @@ module Gitlab
def schedule_populate_untracked_uploads_jobs
bulk_queue_background_migration_jobs_by_range(
- UntrackedFile, FOLLOW_UP_MIGRATION)
+ UntrackedFile, FOLLOW_UP_MIGRATION
+ )
end
def drop_temp_table
unless Rails.env.test? # Dropping a table intermittently breaks test cleanup
UntrackedFile.connection.drop_table(:untracked_files_for_uploads,
- if_exists: true)
+ if_exists: true)
end
end
end
diff --git a/lib/gitlab/background_migration/redact_links.rb b/lib/gitlab/background_migration/redact_links.rb
index 92256e59a6c..587c0ad76fc 100644
--- a/lib/gitlab/background_migration/redact_links.rb
+++ b/lib/gitlab/background_migration/redact_links.rb
@@ -1,7 +1,8 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
-require_relative 'redact_links/redactable'
+require_relative "redact_links/redactable"
module Gitlab
module BackgroundMigration
@@ -10,7 +11,7 @@ module Gitlab
include EachBatch
include ::Gitlab::BackgroundMigration::RedactLinks::Redactable
- self.table_name = 'notes'
+ self.table_name = "notes"
self.inheritance_column = :_type_disabled
end
@@ -18,7 +19,7 @@ module Gitlab
include EachBatch
include ::Gitlab::BackgroundMigration::RedactLinks::Redactable
- self.table_name = 'issues'
+ self.table_name = "issues"
self.inheritance_column = :_type_disabled
end
@@ -26,7 +27,7 @@ module Gitlab
include EachBatch
include ::Gitlab::BackgroundMigration::RedactLinks::Redactable
- self.table_name = 'merge_requests'
+ self.table_name = "merge_requests"
self.inheritance_column = :_type_disabled
end
@@ -34,7 +35,7 @@ module Gitlab
include EachBatch
include ::Gitlab::BackgroundMigration::RedactLinks::Redactable
- self.table_name = 'snippets'
+ self.table_name = "snippets"
self.inheritance_column = :_type_disabled
end
diff --git a/lib/gitlab/background_migration/redact_links/redactable.rb b/lib/gitlab/background_migration/redact_links/redactable.rb
index baab34221f1..e582dced24d 100644
--- a/lib/gitlab/background_migration/redact_links/redactable.rb
+++ b/lib/gitlab/background_migration/redact_links/redactable.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
@@ -8,11 +9,11 @@ module Gitlab
extend ActiveSupport::Concern
def redact_field!(field)
- self[field].gsub!(%r{/sent_notifications/\h{32}/unsubscribe}, '/sent_notifications/REDACTED/unsubscribe')
+ self[field].gsub!(%r{/sent_notifications/\h{32}/unsubscribe}, "/sent_notifications/REDACTED/unsubscribe")
- if self.changed?
- self.update_columns(field => self[field],
- "#{field}_html" => nil)
+ if changed?
+ update_columns(field => self[field],
+ "#{field}_html" => nil)
end
end
end
diff --git a/lib/gitlab/background_migration/remove_restricted_todos.rb b/lib/gitlab/background_migration/remove_restricted_todos.rb
index 47579d46c1b..fc0d4abdf10 100644
--- a/lib/gitlab/background_migration/remove_restricted_todos.rb
+++ b/lib/gitlab/background_migration/remove_restricted_todos.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
# rubocop:disable Metrics/ClassLength
@@ -9,31 +10,31 @@ module Gitlab
PRIVATE_PROJECT = 0
class Project < ActiveRecord::Base
- self.table_name = 'projects'
+ self.table_name = "projects"
end
class ProjectAuthorization < ActiveRecord::Base
- self.table_name = 'project_authorizations'
+ self.table_name = "project_authorizations"
end
class ProjectFeature < ActiveRecord::Base
- self.table_name = 'project_features'
+ self.table_name = "project_features"
end
class Todo < ActiveRecord::Base
include EachBatch
- self.table_name = 'todos'
+ self.table_name = "todos"
end
class Issue < ActiveRecord::Base
include EachBatch
- self.table_name = 'issues'
+ self.table_name = "issues"
end
def perform(start_id, stop_id)
- projects = Project.where('EXISTS (SELECT 1 FROM todos WHERE todos.project_id = projects.id)')
+ projects = Project.where("EXISTS (SELECT 1 FROM todos WHERE todos.project_id = projects.id)")
.where(id: start_id..stop_id)
projects.each do |project|
@@ -64,17 +65,17 @@ module Gitlab
# min access level to access a confidential issue is reporter
min_reporters = authorized_users(project_id)
.select(:user_id)
- .where('access_level >= ?', 20)
+ .where("access_level >= ?", 20)
confidential_issues = Issue.select(:id, :author_id).where(confidential: true, project_id: project_id)
confidential_issues.each_batch(of: 100, order_hint: :confidential) do |batch|
batch.each do |issue|
assigned_users = IssueAssignee.select(:user_id).where(issue_id: issue.id)
- todos = Todo.where(target_type: 'Issue', target_id: issue.id)
- .where('user_id NOT IN (?)', min_reporters)
- .where('user_id NOT IN (?)', assigned_users)
- todos = todos.where('user_id != ?', issue.author_id) if issue.author_id
+ todos = Todo.where(target_type: "Issue", target_id: issue.id)
+ .where("user_id NOT IN (?)", min_reporters)
+ .where("user_id NOT IN (?)", assigned_users)
+ todos = todos.where("user_id != ?", issue.author_id) if issue.author_id
todos.delete_all
end
@@ -84,9 +85,9 @@ module Gitlab
def remove_restricted_features_todos(project_id)
ProjectFeature.where(project_id: project_id).each do |project_features|
target_types = []
- target_types << 'Issue' if private?(project_features.issues_access_level)
- target_types << 'MergeRequest' if private?(project_features.merge_requests_access_level)
- target_types << 'Commit' if private?(project_features.repository_access_level)
+ target_types << "Issue" if private?(project_features.issues_access_level)
+ target_types << "MergeRequest" if private?(project_features.merge_requests_access_level)
+ target_types << "Commit" if private?(project_features.repository_access_level)
next if target_types.empty?
@@ -110,7 +111,7 @@ module Gitlab
def unauthorized_project_todos(project_id)
Todo.where(project_id: project_id)
- .where('user_id NOT IN (?)', authorized_users(project_id))
+ .where("user_id NOT IN (?)", authorized_users(project_id))
end
def batch_remove_todos_cte(project_id, target_types = nil)
@@ -127,7 +128,7 @@ module Gitlab
sql << as_deleted_sql
sql << "SELECT count(*) FROM deleted"
- result = Todo.connection.exec_query(sql.join(' '))
+ result = Todo.connection.exec_query(sql.join(" "))
result.rows[0][0].to_i
end
diff --git a/lib/gitlab/background_migration/schedule_diff_files_deletion.rb b/lib/gitlab/background_migration/schedule_diff_files_deletion.rb
index 609cf19187c..4edf5109ad4 100644
--- a/lib/gitlab/background_migration/schedule_diff_files_deletion.rb
+++ b/lib/gitlab/background_migration/schedule_diff_files_deletion.rb
@@ -1,11 +1,12 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
module BackgroundMigration
class ScheduleDiffFilesDeletion
class MergeRequestDiff < ActiveRecord::Base
- self.table_name = 'merge_request_diffs'
+ self.table_name = "merge_request_diffs"
belongs_to :merge_request
@@ -14,12 +15,12 @@ module Gitlab
DIFF_BATCH_SIZE = 5_000
INTERVAL = 5.minutes
- MIGRATION = 'DeleteDiffFiles'
+ MIGRATION = "DeleteDiffFiles"
def perform
diffs = MergeRequestDiff
.from("(#{diffs_collection.to_sql}) merge_request_diffs")
- .where('merge_request_diffs.id != merge_request_diffs.latest_merge_request_diff_id')
+ .where("merge_request_diffs.id != merge_request_diffs.latest_merge_request_diff_id")
.select(:id)
diffs.each_batch(of: DIFF_BATCH_SIZE) do |relation, index|
@@ -35,9 +36,9 @@ module Gitlab
MergeRequestDiff
.joins(:merge_request)
.where("merge_requests.state = 'merged'")
- .where('merge_requests.latest_merge_request_diff_id IS NOT NULL')
+ .where("merge_requests.latest_merge_request_diff_id IS NOT NULL")
.where("merge_request_diffs.state NOT IN ('without_files', 'empty')")
- .select('merge_requests.latest_merge_request_diff_id, merge_request_diffs.id')
+ .select("merge_requests.latest_merge_request_diff_id, merge_request_diffs.id")
end
end
end
diff --git a/lib/gitlab/background_migration/set_confidential_note_events_on_services.rb b/lib/gitlab/background_migration/set_confidential_note_events_on_services.rb
index bc434b0cb64..31f8cf27719 100644
--- a/lib/gitlab/background_migration/set_confidential_note_events_on_services.rb
+++ b/lib/gitlab/background_migration/set_confidential_note_events_on_services.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
@@ -7,7 +8,7 @@ module Gitlab
# to receive confidential ones.
class SetConfidentialNoteEventsOnServices
class Service < ActiveRecord::Base
- self.table_name = 'services'
+ self.table_name = "services"
include ::EachBatch
@@ -18,8 +19,8 @@ module Gitlab
def perform(start_id, stop_id)
Service.services_to_update
- .where(id: start_id..stop_id)
- .update_all(confidential_note_events: true)
+ .where(id: start_id..stop_id)
+ .update_all(confidential_note_events: true)
end
end
end
diff --git a/lib/gitlab/background_migration/set_confidential_note_events_on_webhooks.rb b/lib/gitlab/background_migration/set_confidential_note_events_on_webhooks.rb
index 28d8d2c640b..4514ba94ec8 100644
--- a/lib/gitlab/background_migration/set_confidential_note_events_on_webhooks.rb
+++ b/lib/gitlab/background_migration/set_confidential_note_events_on_webhooks.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
# rubocop:disable Style/Documentation
module Gitlab
@@ -7,7 +8,7 @@ module Gitlab
# to receive confidential ones.
class SetConfidentialNoteEventsOnWebhooks
class WebHook < ActiveRecord::Base
- self.table_name = 'web_hooks'
+ self.table_name = "web_hooks"
include ::EachBatch
@@ -18,8 +19,8 @@ module Gitlab
def perform(start_id, stop_id)
WebHook.hooks_to_update
- .where(id: start_id..stop_id)
- .update_all(confidential_note_events: true)
+ .where(id: start_id..stop_id)
+ .update_all(confidential_note_events: true)
end
end
end
diff --git a/lib/gitlab/badge/coverage/metadata.rb b/lib/gitlab/badge/coverage/metadata.rb
index 9181ba2d4b0..3387ead969c 100644
--- a/lib/gitlab/badge/coverage/metadata.rb
+++ b/lib/gitlab/badge/coverage/metadata.rb
@@ -14,7 +14,7 @@ module Gitlab
end
def title
- 'coverage report'
+ "coverage report"
end
def image_url
diff --git a/lib/gitlab/badge/coverage/report.rb b/lib/gitlab/badge/coverage/report.rb
index 7f7cc62c8ef..18593e9e1ac 100644
--- a/lib/gitlab/badge/coverage/report.rb
+++ b/lib/gitlab/badge/coverage/report.rb
@@ -18,7 +18,7 @@ module Gitlab
end
def entity
- 'coverage'
+ "coverage"
end
def status
diff --git a/lib/gitlab/badge/coverage/template.rb b/lib/gitlab/badge/coverage/template.rb
index 817dc28f84a..a172c0d155a 100644
--- a/lib/gitlab/badge/coverage/template.rb
+++ b/lib/gitlab/badge/coverage/template.rb
@@ -10,11 +10,11 @@ module Gitlab
#
class Template < Badge::Template
STATUS_COLOR = {
- good: '#4c1',
- acceptable: '#a3c51c',
- medium: '#dfb317',
- low: '#e05d44',
- unknown: '#9f9f9f'
+ good: "#4c1",
+ acceptable: "#a3c51c",
+ medium: "#dfb317",
+ low: "#e05d44",
+ unknown: "#9f9f9f",
}.freeze
def initialize(badge)
@@ -27,7 +27,7 @@ module Gitlab
end
def value_text
- @status ? ("%.2f%%" % @status) : 'unknown'
+ @status ? ("%.2f%%" % @status) : "unknown"
end
def key_width
diff --git a/lib/gitlab/badge/pipeline/metadata.rb b/lib/gitlab/badge/pipeline/metadata.rb
index d4d789558c9..0557ad8707c 100644
--- a/lib/gitlab/badge/pipeline/metadata.rb
+++ b/lib/gitlab/badge/pipeline/metadata.rb
@@ -13,7 +13,7 @@ module Gitlab
end
def title
- 'pipeline status'
+ "pipeline status"
end
def image_url
diff --git a/lib/gitlab/badge/pipeline/status.rb b/lib/gitlab/badge/pipeline/status.rb
index a403d839517..4f90e745516 100644
--- a/lib/gitlab/badge/pipeline/status.rb
+++ b/lib/gitlab/badge/pipeline/status.rb
@@ -17,14 +17,14 @@ module Gitlab
end
def entity
- 'pipeline'
+ "pipeline"
end
# rubocop: disable CodeReuse/ActiveRecord
def status
@project.ci_pipelines
.where(sha: @sha)
- .latest_status(@ref) || 'unknown'
+ .latest_status(@ref) || "unknown"
end
# rubocop: enable CodeReuse/ActiveRecord
diff --git a/lib/gitlab/badge/pipeline/template.rb b/lib/gitlab/badge/pipeline/template.rb
index 64c3dfcd10b..4e10b735f27 100644
--- a/lib/gitlab/badge/pipeline/template.rb
+++ b/lib/gitlab/badge/pipeline/template.rb
@@ -9,15 +9,15 @@ module Gitlab
# Template object will be passed to badge.svg.erb template.
#
class Template < Badge::Template
- STATUS_RENAME = { 'success' => 'passed' }.freeze
+ STATUS_RENAME = {"success" => "passed"}.freeze
STATUS_COLOR = {
- success: '#4c1',
- failed: '#e05d44',
- running: '#dfb317',
- pending: '#dfb317',
- canceled: '#9f9f9f',
- skipped: '#9f9f9f',
- unknown: '#9f9f9f'
+ success: "#4c1",
+ failed: "#e05d44",
+ running: "#dfb317",
+ pending: "#dfb317",
+ canceled: "#9f9f9f",
+ skipped: "#9f9f9f",
+ unknown: "#9f9f9f",
}.freeze
def initialize(badge)
diff --git a/lib/gitlab/badge/template.rb b/lib/gitlab/badge/template.rb
index ed2ec50b197..a15ffdfad05 100644
--- a/lib/gitlab/badge/template.rb
+++ b/lib/gitlab/badge/template.rb
@@ -32,7 +32,7 @@ module Gitlab
end
def key_color
- '#555'
+ "#555"
end
def key_text_anchor
diff --git a/lib/gitlab/bare_repository_import/importer.rb b/lib/gitlab/bare_repository_import/importer.rb
index 3cd327f5109..c9bd0c5c018 100644
--- a/lib/gitlab/bare_repository_import/importer.rb
+++ b/lib/gitlab/bare_repository_import/importer.rb
@@ -6,14 +6,14 @@ module Gitlab
NoAdminError = Class.new(StandardError)
def self.execute(import_path)
- unless import_path.ends_with?('/')
+ unless import_path.ends_with?("/")
import_path = "#{import_path}/"
end
- repos_to_import = Dir.glob(import_path + '**/*.git')
+ repos_to_import = Dir.glob(import_path + "**/*.git")
unless user = User.admins.order_id_asc.first
- raise NoAdminError.new('No admin user found to import repositories')
+ raise NoAdminError.new("No admin user found to import repositories")
end
repos_to_import.each do |repo_path|
@@ -63,12 +63,12 @@ module Gitlab
group = find_or_create_groups
project = Projects::CreateService.new(user,
- name: project_name,
- path: project_name,
- skip_disk_validation: true,
- skip_wiki: bare_repo.wiki_exists?,
- import_type: 'bare_repository',
- namespace_id: group&.id).execute
+ name: project_name,
+ path: project_name,
+ skip_disk_validation: true,
+ skip_wiki: bare_repo.wiki_exists?,
+ import_type: "bare_repository",
+ namespace_id: group&.id).execute
if project.persisted? && mv_repositories(project)
log " * Created #{project.name} (#{project_full_path})".color(:green)
@@ -120,7 +120,7 @@ module Gitlab
# `git bundle create - --all` and streaming the bundle directly to
# Gitaly, rather than writing it on disk first
bundle_path = "#{repo_path}.bundle"
- cmd = %W(#{Gitlab.config.git.bin_path} --git-dir=#{repo_path} bundle create #{bundle_path} --all)
+ cmd = %W[#{Gitlab.config.git.bin_path} --git-dir=#{repo_path} bundle create #{bundle_path} --all]
output, status = Gitlab::Popen.popen(cmd)
raise output unless status.zero?
diff --git a/lib/gitlab/bare_repository_import/repository.rb b/lib/gitlab/bare_repository_import/repository.rb
index b903c581aac..10317fd890b 100644
--- a/lib/gitlab/bare_repository_import/repository.rb
+++ b/lib/gitlab/bare_repository_import/repository.rb
@@ -8,7 +8,7 @@ module Gitlab
attr_reader :group_path, :project_name, :repo_path
def initialize(root_path, repo_path)
- unless root_path.ends_with?('/')
+ unless root_path.ends_with?("/")
root_path = "#{root_path}/"
end
@@ -17,13 +17,13 @@ module Gitlab
full_path =
if hashed? && !wiki?
- repository.config.get('gitlab.fullpath')
+ repository.config.get("gitlab.fullpath")
else
repo_relative_path
end
# Split path into 'all/the/namespaces' and 'project_name'
- @group_path, _, @project_name = full_path.to_s.rpartition('/')
+ @group_path, _, @project_name = full_path.to_s.rpartition("/")
end
def wiki_exists?
@@ -31,7 +31,7 @@ module Gitlab
end
def wiki_path
- @wiki_path ||= repo_path.sub(/\.git$/, '.wiki.git')
+ @wiki_path ||= repo_path.sub(/\.git$/, ".wiki.git")
end
def project_full_path
@@ -49,13 +49,13 @@ module Gitlab
def wiki?
strong_memoize(:wiki) do
- repo_path.end_with?('.wiki.git')
+ repo_path.end_with?(".wiki.git")
end
end
def hashed?
strong_memoize(:hashed) do
- repo_relative_path.include?('@hashed')
+ repo_relative_path.include?("@hashed")
end
end
diff --git a/lib/gitlab/bitbucket_import/importer.rb b/lib/gitlab/bitbucket_import/importer.rb
index 75a3f17f549..cce4cdbb2fc 100644
--- a/lib/gitlab/bitbucket_import/importer.rb
+++ b/lib/gitlab/bitbucket_import/importer.rb
@@ -5,10 +5,10 @@ module Gitlab
class Importer
include Gitlab::ShellAdapter
- LABELS = [{ title: 'bug', color: '#FF0000' },
- { title: 'enhancement', color: '#428BCA' },
- { title: 'proposal', color: '#69D100' },
- { title: 'task', color: '#7F8C8D' }].freeze
+ LABELS = [{title: "bug", color: "#FF0000"},
+ {title: "enhancement", color: "#428BCA"},
+ {title: "proposal", color: "#69D100"},
+ {title: "task", color: "#7F8C8D"},].freeze
attr_reader :project, :client, :errors, :users
@@ -36,8 +36,8 @@ module Gitlab
return unless errors.any?
project.import_state.update_column(:last_error, {
- message: 'The remote data could not be fully imported.',
- errors: errors
+ message: "The remote data could not be fully imported.",
+ errors: errors,
}.to_json)
end
@@ -52,9 +52,9 @@ module Gitlab
return users[username] if users.key?(username)
users[username] = User.select(:id)
- .joins(:identities)
- .find_by("identities.extern_uid = ? AND identities.provider = 'bitbucket'", username)
- .try(:id)
+ .joins(:identities)
+ .find_by("identities.extern_uid = ? AND identities.provider = 'bitbucket'", username)
+ .try(:id)
end
# rubocop: enable CodeReuse/ActiveRecord
@@ -68,8 +68,8 @@ module Gitlab
wiki = WikiFormatter.new(project)
gitlab_shell.import_wiki_repository(project, wiki)
- rescue StandardError => e
- errors << { type: :wiki, errors: e.message }
+ rescue => e
+ errors << {type: :wiki, errors: e.message}
end
# rubocop: disable CodeReuse/ActiveRecord
@@ -79,31 +79,29 @@ module Gitlab
create_labels
client.issues(repo).each do |issue|
- begin
- description = ''
- description += @formatter.author_line(issue.author) unless find_user_id(issue.author)
- description += issue.description
-
- label_name = issue.kind
- milestone = issue.milestone ? project.milestones.find_or_create_by(title: issue.milestone) : nil
-
- gitlab_issue = project.issues.create!(
- iid: issue.iid,
- title: issue.title,
- description: description,
- state: issue.state,
- author_id: gitlab_user_id(project, issue.author),
- milestone: milestone,
- created_at: issue.created_at,
- updated_at: issue.updated_at
- )
-
- gitlab_issue.labels << @labels[label_name]
-
- import_issue_comments(issue, gitlab_issue) if gitlab_issue.persisted?
- rescue StandardError => e
- errors << { type: :issue, iid: issue.iid, errors: e.message }
- end
+ description = ""
+ description += @formatter.author_line(issue.author) unless find_user_id(issue.author)
+ description += issue.description
+
+ label_name = issue.kind
+ milestone = issue.milestone ? project.milestones.find_or_create_by(title: issue.milestone) : nil
+
+ gitlab_issue = project.issues.create!(
+ iid: issue.iid,
+ title: issue.title,
+ description: description,
+ state: issue.state,
+ author_id: gitlab_user_id(project, issue.author),
+ milestone: milestone,
+ created_at: issue.created_at,
+ updated_at: issue.updated_at
+ )
+
+ gitlab_issue.labels << @labels[label_name]
+
+ import_issue_comments(issue, gitlab_issue) if gitlab_issue.persisted?
+ rescue => e
+ errors << {type: :issue, iid: issue.iid, errors: e.message}
end
end
# rubocop: enable CodeReuse/ActiveRecord
@@ -117,7 +115,7 @@ module Gitlab
# we do this check.
next unless comment.note.present?
- note = ''
+ note = ""
note += @formatter.author_line(comment.author) unless find_user_id(comment.author)
note += comment.note
@@ -129,8 +127,8 @@ module Gitlab
created_at: comment.created_at,
updated_at: comment.updated_at
)
- rescue StandardError => e
- errors << { type: :issue_comment, iid: issue.iid, errors: e.message }
+ rescue => e
+ errors << {type: :issue_comment, iid: issue.iid, errors: e.message}
end
end
end
@@ -150,37 +148,35 @@ module Gitlab
pull_requests = client.pull_requests(repo)
pull_requests.each do |pull_request|
- begin
- description = ''
- description += @formatter.author_line(pull_request.author) unless find_user_id(pull_request.author)
- description += pull_request.description
-
- source_branch_sha = pull_request.source_branch_sha
- target_branch_sha = pull_request.target_branch_sha
- source_branch_sha = project.repository.commit(source_branch_sha)&.sha || source_branch_sha
- target_branch_sha = project.repository.commit(target_branch_sha)&.sha || target_branch_sha
-
- merge_request = project.merge_requests.create!(
- iid: pull_request.iid,
- title: pull_request.title,
- description: description,
- source_project: project,
- source_branch: pull_request.source_branch_name,
- source_branch_sha: source_branch_sha,
- target_project: project,
- target_branch: pull_request.target_branch_name,
- target_branch_sha: target_branch_sha,
- state: pull_request.state,
- author_id: gitlab_user_id(project, pull_request.author),
- assignee_id: nil,
- created_at: pull_request.created_at,
- updated_at: pull_request.updated_at
- )
-
- import_pull_request_comments(pull_request, merge_request) if merge_request.persisted?
- rescue StandardError => e
- errors << { type: :pull_request, iid: pull_request.iid, errors: e.message, trace: e.backtrace.join("\n"), raw_response: pull_request.raw }
- end
+ description = ""
+ description += @formatter.author_line(pull_request.author) unless find_user_id(pull_request.author)
+ description += pull_request.description
+
+ source_branch_sha = pull_request.source_branch_sha
+ target_branch_sha = pull_request.target_branch_sha
+ source_branch_sha = project.repository.commit(source_branch_sha)&.sha || source_branch_sha
+ target_branch_sha = project.repository.commit(target_branch_sha)&.sha || target_branch_sha
+
+ merge_request = project.merge_requests.create!(
+ iid: pull_request.iid,
+ title: pull_request.title,
+ description: description,
+ source_project: project,
+ source_branch: pull_request.source_branch_name,
+ source_branch_sha: source_branch_sha,
+ target_project: project,
+ target_branch: pull_request.target_branch_name,
+ target_branch_sha: target_branch_sha,
+ state: pull_request.state,
+ author_id: gitlab_user_id(project, pull_request.author),
+ assignee_id: nil,
+ created_at: pull_request.created_at,
+ updated_at: pull_request.updated_at
+ )
+
+ import_pull_request_comments(pull_request, merge_request) if merge_request.persisted?
+ rescue => e
+ errors << {type: :pull_request, iid: pull_request.iid, errors: e.message, trace: e.backtrace.join("\n"), raw_response: pull_request.raw}
end
end
@@ -211,23 +207,20 @@ module Gitlab
end
inline_comments.each do |comment|
- begin
- attributes = pull_request_comment_attributes(comment)
- attributes[:discussion_id] = discussion_map[comment.parent_id] if comment.has_parent?
+ attributes = pull_request_comment_attributes(comment)
+ attributes[:discussion_id] = discussion_map[comment.parent_id] if comment.has_parent?
- attributes.merge!(
- position: position_map[comment.iid],
- type: 'DiffNote')
+ attributes[:position] = position_map[comment.iid]
+ attributes[:type] = "DiffNote"
- note = merge_request.notes.create!(attributes)
+ note = merge_request.notes.create!(attributes)
- # We can't store a discussion ID until a note is created, so if
- # replies are created before the parent the discussion ID won't be
- # linked properly.
- discussion_map[comment.iid] = note.discussion_id
- rescue StandardError => e
- errors << { type: :pull_request, iid: comment.iid, errors: e.message }
- end
+ # We can't store a discussion ID until a note is created, so if
+ # replies are created before the parent the discussion ID won't be
+ # linked properly.
+ discussion_map[comment.iid] = note.discussion_id
+ rescue => e
+ errors << {type: :pull_request, iid: comment.iid, errors: e.message}
end
end
@@ -237,7 +230,7 @@ module Gitlab
old_path: pr_comment.file_path,
new_path: pr_comment.file_path,
old_line: pr_comment.old_pos,
- new_line: pr_comment.new_pos
+ new_line: pr_comment.new_pos,
}
Gitlab::Diff::Position.new(params)
@@ -245,11 +238,9 @@ module Gitlab
def import_standalone_pr_comments(pr_comments, merge_request)
pr_comments.each do |comment|
- begin
- merge_request.notes.create!(pull_request_comment_attributes(comment))
- rescue StandardError => e
- errors << { type: :pull_request, iid: comment.iid, errors: e.message }
- end
+ merge_request.notes.create!(pull_request_comment_attributes(comment))
+ rescue => e
+ errors << {type: :pull_request, iid: comment.iid, errors: e.message}
end
end
@@ -259,7 +250,7 @@ module Gitlab
note: comment.note,
author_id: gitlab_user_id(project, comment.author),
created_at: comment.created_at,
- updated_at: comment.updated_at
+ updated_at: comment.updated_at,
}
end
end
diff --git a/lib/gitlab/bitbucket_import/project_creator.rb b/lib/gitlab/bitbucket_import/project_creator.rb
index 11070a68e02..ebad4f27c0f 100644
--- a/lib/gitlab/bitbucket_import/project_creator.rb
+++ b/lib/gitlab/bitbucket_import/project_creator.rb
@@ -21,10 +21,10 @@ module Gitlab
description: repo.description,
namespace_id: namespace.id,
visibility_level: repo.visibility_level,
- import_type: 'bitbucket',
+ import_type: "bitbucket",
import_source: repo.full_name,
import_url: repo.clone_url(session_data[:token]),
- import_data: { credentials: session_data },
+ import_data: {credentials: session_data},
skip_wiki: skip_wiki
).execute
end
diff --git a/lib/gitlab/bitbucket_server_import/importer.rb b/lib/gitlab/bitbucket_server_import/importer.rb
index dbbedd5dcbe..65b588cbdab 100644
--- a/lib/gitlab/bitbucket_server_import/importer.rb
+++ b/lib/gitlab/bitbucket_server_import/importer.rb
@@ -7,7 +7,7 @@ module Gitlab
attr_reader :project, :project_key, :repository_slug, :client, :errors, :users
attr_accessor :logger
- REMOTE_NAME = 'bitbucket_server'.freeze
+ REMOTE_NAME = "bitbucket_server"
BATCH_SIZE = 100
TempBranch = Struct.new(:name, :sha)
@@ -17,7 +17,7 @@ module Gitlab
end
def self.refmap
- [:heads, :tags, '+refs/pull-requests/*/to:refs/merge-requests/*/head']
+ [:heads, :tags, "+refs/pull-requests/*/to:refs/merge-requests/*/head"]
end
# Unlike GitHub, you can't grab the commit SHAs for pull requests that
@@ -28,8 +28,8 @@ module Gitlab
def initialize(project, recover_missing_commits: false)
@project = project
@recover_missing_commits = recover_missing_commits
- @project_key = project.import_data.data['project_key']
- @repository_slug = project.import_data.data['repo_slug']
+ @project_key = project.import_data.data["project_key"]
+ @repository_slug = project.import_data.data["repo_slug"]
@client = BitbucketServer::Client.new(project.import_data.credentials)
@formatter = Gitlab::ImportFormatter.new
@errors = []
@@ -55,8 +55,8 @@ module Gitlab
return unless errors.any?
project.import_state.update_column(:last_error, {
- message: 'The remote data could not be fully imported.',
- errors: errors
+ message: "The remote data could not be fully imported.",
+ errors: errors,
}.to_json)
end
@@ -96,9 +96,9 @@ module Gitlab
pull_requests.each do |pull_request|
shas_to_restore << TempBranch.new(temp_branch_name(pull_request, :from),
- pull_request.source_branch_sha)
+ pull_request.source_branch_sha)
shas_to_restore << TempBranch.new(temp_branch_name(pull_request, :to),
- pull_request.target_branch_sha)
+ pull_request.target_branch_sha)
end
# Create the branches on the Bitbucket Server first
@@ -126,14 +126,14 @@ module Gitlab
end
def import_repository
- log_info(stage: 'import_repository', message: 'starting import')
+ log_info(stage: "import_repository", message: "starting import")
project.ensure_repository
project.repository.fetch_as_mirror(project.import_url, refmap: self.class.refmap, remote_name: REMOTE_NAME)
- log_info(stage: 'import_repository', message: 'finished import')
+ log_info(stage: "import_repository", message: "finished import")
rescue Gitlab::Shell::Error => e
- log_error(stage: 'import_repository', message: 'failed import', error: e.message)
+ log_error(stage: "import_repository", message: "failed import", error: e.message)
# Expire cache to prevent scenarios such as:
# 1. First import failed, but the repo was imported successfully, so +exists?+ returns true
@@ -162,34 +162,30 @@ module Gitlab
restore_branches(batch) if recover_missing_commits
batch.each do |pull_request|
- begin
- import_bitbucket_pull_request(pull_request)
- rescue StandardError => e
- backtrace = Gitlab::Profiler.clean_backtrace(e.backtrace)
- log_error(stage: 'import_pull_requests', iid: pull_request.iid, error: e.message, backtrace: backtrace)
-
- errors << { type: :pull_request, iid: pull_request.iid, errors: e.message, backtrace: backtrace.join("\n"), raw_response: pull_request.raw }
- end
+ import_bitbucket_pull_request(pull_request)
+ rescue => e
+ backtrace = Gitlab::Profiler.clean_backtrace(e.backtrace)
+ log_error(stage: "import_pull_requests", iid: pull_request.iid, error: e.message, backtrace: backtrace)
+
+ errors << {type: :pull_request, iid: pull_request.iid, errors: e.message, backtrace: backtrace.join("\n"), raw_response: pull_request.raw}
end
end
end
def delete_temp_branches
@temp_branches.each do |branch|
- begin
- client.delete_branch(project_key, repository_slug, branch.name, branch.sha)
- project.repository.delete_branch(branch.name)
- rescue BitbucketServer::Connection::ConnectionError => e
- log_error(stage: 'delete_temp_branches', branch: branch.name, error: e.message)
- @errors << { type: :delete_temp_branches, branch_name: branch.name, errors: e.message }
- end
+ client.delete_branch(project_key, repository_slug, branch.name, branch.sha)
+ project.repository.delete_branch(branch.name)
+ rescue BitbucketServer::Connection::ConnectionError => e
+ log_error(stage: "delete_temp_branches", branch: branch.name, error: e.message)
+ @errors << {type: :delete_temp_branches, branch_name: branch.name, errors: e.message}
end
end
def import_bitbucket_pull_request(pull_request)
- log_info(stage: 'import_bitbucket_pull_requests', message: 'starting', iid: pull_request.iid)
+ log_info(stage: "import_bitbucket_pull_requests", message: "starting", iid: pull_request.iid)
- description = ''
+ description = ""
description += @formatter.author_line(pull_request.author) unless find_user_id(pull_request.author_email)
description += pull_request.description if pull_request.description
author_id = gitlab_user_id(pull_request.author_email)
@@ -208,7 +204,7 @@ module Gitlab
author_id: author_id,
assignee_id: nil,
created_at: pull_request.created_at,
- updated_at: pull_request.updated_at
+ updated_at: pull_request.updated_at,
}
creator = Gitlab::Import::MergeRequestCreator.new(project)
@@ -216,11 +212,11 @@ module Gitlab
import_pull_request_comments(pull_request, merge_request) if merge_request.persisted?
- log_info(stage: 'import_bitbucket_pull_requests', message: 'finished', iid: pull_request.iid)
+ log_info(stage: "import_bitbucket_pull_requests", message: "finished", iid: pull_request.iid)
end
def import_pull_request_comments(pull_request, merge_request)
- log_info(stage: 'import_pull_request_comments', message: 'starting', iid: merge_request.iid)
+ log_info(stage: "import_pull_request_comments", message: "starting", iid: merge_request.iid)
comments, other_activities = client.activities(project_key, repository_slug, pull_request.iid).partition(&:comment?)
@@ -232,7 +228,7 @@ module Gitlab
import_inline_comments(inline_comments.map(&:comment), merge_request)
import_standalone_pr_comments(pr_comments.map(&:comment), merge_request)
- log_info(stage: 'import_pull_request_comments', message: 'finished', iid: merge_request.iid,
+ log_info(stage: "import_pull_request_comments", message: "finished", iid: merge_request.iid,
merge_event_found: merge_event.present?,
inline_comments_count: inline_comments.count,
standalone_pr_comments: pr_comments.count)
@@ -240,22 +236,22 @@ module Gitlab
# rubocop: disable CodeReuse/ActiveRecord
def import_merge_event(merge_request, merge_event)
- log_info(stage: 'import_merge_event', message: 'starting', iid: merge_request.iid)
+ log_info(stage: "import_merge_event", message: "starting", iid: merge_request.iid)
committer = merge_event.committer_email
user_id = gitlab_user_id(committer)
timestamp = merge_event.merge_timestamp
- merge_request.update({ merge_commit_sha: merge_event.merge_commit })
+ merge_request.update({merge_commit_sha: merge_event.merge_commit})
metric = MergeRequest::Metrics.find_or_initialize_by(merge_request: merge_request)
metric.update(merged_by_id: user_id, merged_at: timestamp)
- log_info(stage: 'import_merge_event', message: 'finished', iid: merge_request.iid)
+ log_info(stage: "import_merge_event", message: "finished", iid: merge_request.iid)
end
# rubocop: enable CodeReuse/ActiveRecord
def import_inline_comments(inline_comments, merge_request)
- log_info(stage: 'import_inline_comments', message: 'starting', iid: merge_request.iid)
+ log_info(stage: "import_inline_comments", message: "starting", iid: merge_request.iid)
inline_comments.each do |comment|
position = build_position(merge_request, comment)
@@ -270,12 +266,13 @@ module Gitlab
end
end
- log_info(stage: 'import_inline_comments', message: 'finished', iid: merge_request.iid)
+ log_info(stage: "import_inline_comments", message: "finished", iid: merge_request.iid)
end
def create_diff_note(merge_request, comment, position, discussion_id = nil)
attributes = pull_request_comment_attributes(comment)
- attributes.merge!(position: position, type: 'DiffNote')
+ attributes[:position] = position
+ attributes[:type] = "DiffNote"
attributes[:discussion_id] = discussion_id if discussion_id
note = merge_request.notes.build(attributes)
@@ -285,15 +282,15 @@ module Gitlab
return note
end
- log_info(stage: 'create_diff_note', message: 'creating fallback DiffNote', iid: merge_request.iid)
+ log_info(stage: "create_diff_note", message: "creating fallback DiffNote", iid: merge_request.iid)
# Bitbucket Server supports the ability to comment on any line, not just the
# line in the diff. If we can't add the note as a DiffNote, fallback to creating
# a regular note.
create_fallback_diff_note(merge_request, comment, position)
- rescue StandardError => e
- log_error(stage: 'create_diff_note', comment_id: comment.id, error: e.message)
- errors << { type: :pull_request, id: comment.id, errors: e.message }
+ rescue => e
+ log_error(stage: "create_diff_note", comment_id: comment.id, error: e.message)
+ errors << {type: :pull_request, id: comment.id, errors: e.message}
nil
end
@@ -315,7 +312,7 @@ module Gitlab
old_path: pr_comment.file_path,
new_path: pr_comment.file_path,
old_line: pr_comment.old_pos,
- new_line: pr_comment.new_pos
+ new_line: pr_comment.new_pos,
}
Gitlab::Diff::Position.new(params)
@@ -323,22 +320,20 @@ module Gitlab
def import_standalone_pr_comments(pr_comments, merge_request)
pr_comments.each do |comment|
- begin
- merge_request.notes.create!(pull_request_comment_attributes(comment))
-
- comment.comments.each do |replies|
- merge_request.notes.create!(pull_request_comment_attributes(replies))
- end
- rescue StandardError => e
- log_error(stage: 'import_standalone_pr_comments', merge_request_id: merge_request.id, comment_id: comment.id, error: e.message)
- errors << { type: :pull_request, comment_id: comment.id, errors: e.message }
+ merge_request.notes.create!(pull_request_comment_attributes(comment))
+
+ comment.comments.each do |replies|
+ merge_request.notes.create!(pull_request_comment_attributes(replies))
end
+ rescue => e
+ log_error(stage: "import_standalone_pr_comments", merge_request_id: merge_request.id, comment_id: comment.id, error: e.message)
+ errors << {type: :pull_request, comment_id: comment.id, errors: e.message}
end
end
def pull_request_comment_attributes(comment)
author = find_user_id(comment.author_email)
- note = ''
+ note = ""
unless author
author = project.creator_id
@@ -358,7 +353,7 @@ module Gitlab
note: note,
author_id: author,
created_at: comment.created_at,
- updated_at: comment.updated_at
+ updated_at: comment.updated_at,
}
end
@@ -378,7 +373,7 @@ module Gitlab
{
class: self.class.name,
project_id: project.id,
- project_path: project.full_path
+ project_path: project.full_path,
}
end
end
diff --git a/lib/gitlab/bitbucket_server_import/project_creator.rb b/lib/gitlab/bitbucket_server_import/project_creator.rb
index 48ca4951957..fc872e1f051 100644
--- a/lib/gitlab/bitbucket_server_import/project_creator.rb
+++ b/lib/gitlab/bitbucket_server_import/project_creator.rb
@@ -23,12 +23,12 @@ module Gitlab
description: repo.description,
namespace_id: namespace.id,
visibility_level: repo.visibility_level,
- import_type: 'bitbucket_server',
+ import_type: "bitbucket_server",
import_source: repo.browse_url,
import_url: repo.clone_url,
import_data: {
credentials: session_data,
- data: { project_key: project_key, repo_slug: repo_slug }
+ data: {project_key: project_key, repo_slug: repo_slug},
},
skip_wiki: true
).execute
diff --git a/lib/gitlab/blame.rb b/lib/gitlab/blame.rb
index f1a653a9d95..551484c0722 100644
--- a/lib/gitlab/blame.rb
+++ b/lib/gitlab/blame.rb
@@ -21,7 +21,7 @@ module Gitlab
sha = commit.sha
if prev_sha != sha
groups << current_group if current_group
- current_group = { commit: commit, lines: [] }
+ current_group = {commit: commit, lines: []}
end
line = highlighted_lines[i].html_safe if highlight
diff --git a/lib/gitlab/blob_helper.rb b/lib/gitlab/blob_helper.rb
index d3e15a79a8b..5a32d01c8a2 100644
--- a/lib/gitlab/blob_helper.rb
+++ b/lib/gitlab/blob_helper.rb
@@ -45,7 +45,7 @@ module Gitlab
end
def image?
- ['.png', '.jpg', '.jpeg', '.gif'].include?(extname.downcase)
+ [".png", ".jpg", ".jpeg", ".gif"].include?(extname.downcase)
end
# Internal: Lookup mime type for extension.
@@ -73,7 +73,7 @@ module Gitlab
#
# Returns a mime type String.
def mime_type
- _mime_type ? _mime_type.to_s : 'text/plain'
+ _mime_type ? _mime_type.to_s : "text/plain"
end
def binary_mime_type?
diff --git a/lib/gitlab/cache/ci/project_pipeline_status.rb b/lib/gitlab/cache/ci/project_pipeline_status.rb
index ea7013db2ce..08b7009e541 100644
--- a/lib/gitlab/cache/ci/project_pipeline_status.rb
+++ b/lib/gitlab/cache/ci/project_pipeline_status.rb
@@ -28,7 +28,7 @@ module Gitlab
pipeline_info = {
sha: pipeline.sha,
status: pipeline.status,
- ref: pipeline.ref
+ ref: pipeline.ref,
}
new(pipeline.project, pipeline_info: pipeline_info)
@@ -81,13 +81,13 @@ module Gitlab
Gitlab::Redis::Cache.with do |redis|
self.sha, self.status, self.ref = redis.hmget(cache_key, :sha, :status, :ref)
- self.status = nil if self.status.empty?
+ self.status = nil if status.empty?
end
end
def store_in_cache
Gitlab::Redis::Cache.with do |redis|
- redis.mapped_hmset(cache_key, { sha: sha, status: status, ref: ref })
+ redis.mapped_hmset(cache_key, {sha: sha, status: status, ref: ref})
end
end
@@ -98,7 +98,7 @@ module Gitlab
end
def has_cache?
- return self.loaded unless self.loaded.nil?
+ return loaded unless loaded.nil?
Gitlab::Redis::Cache.with do |redis|
redis.exists(cache_key)
@@ -106,7 +106,7 @@ module Gitlab
end
def loaded?
- self.loaded
+ loaded
end
def cache_key
diff --git a/lib/gitlab/cache/request_cache.rb b/lib/gitlab/cache/request_cache.rb
index 4c658dc0b8d..4f6fab795ac 100644
--- a/lib/gitlab/cache/request_cache.rb
+++ b/lib/gitlab/cache/request_cache.rb
@@ -32,7 +32,7 @@ module Gitlab
Gitlab::SafeRequestStore.store
else
ivar_name = # ! and ? cannot be used as ivar name
- "@cache_#{method_name.to_s.tr('!?', "\u2605\u2606")}"
+ "@cache_#{method_name.to_s.tr("!?", "\u2605\u2606")}"
instance_variable_get(ivar_name) ||
instance_variable_set(ivar_name, {})
@@ -52,7 +52,7 @@ module Gitlab
method_key = instance_exec(&method_key_block) if method_key_block
[klass.name, method_name, *instance_key, *method_key, *args]
- .join(':')
+ .join(":")
end
private cache_key_method_name
diff --git a/lib/gitlab/changes_list.rb b/lib/gitlab/changes_list.rb
index fb75a78a978..32b9f3465a5 100644
--- a/lib/gitlab/changes_list.rb
+++ b/lib/gitlab/changes_list.rb
@@ -16,12 +16,12 @@ module Gitlab
def changes
@changes ||= begin
- @raw_changes.map do |change|
+ @raw_changes.map { |change|
next if change.blank?
- oldrev, newrev, ref = change.strip.split(' ')
- { oldrev: oldrev, newrev: newrev, ref: ref }
- end.compact
+ oldrev, newrev, ref = change.strip.split(" ")
+ {oldrev: oldrev, newrev: newrev, ref: ref}
+ }.compact
end
end
end
diff --git a/lib/gitlab/chat/command.rb b/lib/gitlab/chat/command.rb
index 49b7dcf4bbe..34a095a3cce 100644
--- a/lib/gitlab/chat/command.rb
+++ b/lib/gitlab/chat/command.rb
@@ -12,7 +12,7 @@ module Gitlab
include Utils::StrongMemoize
attr_reader :project, :chat_name, :name, :arguments, :response_url,
- :channel
+ :channel
# project - The Project to schedule the command for.
# chat_name - The ChatName belonging to the user that scheduled the
@@ -50,7 +50,7 @@ module Gitlab
chat_name_id: chat_name.id,
command: name,
arguments: arguments,
- response_url: response_url
+ response_url: response_url,
}
)
@@ -63,8 +63,8 @@ module Gitlab
# pipeline - The `Ci::Pipeline` to create the environment variables for.
def build_environment_variables(pipeline)
pipeline.variables.build(
- [{ key: 'CHAT_INPUT', value: arguments },
- { key: 'CHAT_CHANNEL', value: channel }]
+ [{key: "CHAT_INPUT", value: arguments},
+ {key: "CHAT_CHANNEL", value: channel},]
)
end
diff --git a/lib/gitlab/chat/output.rb b/lib/gitlab/chat/output.rb
index 411b1555a7d..08724c9b285 100644
--- a/lib/gitlab/chat/output.rb
+++ b/lib/gitlab/chat/output.rb
@@ -9,10 +9,10 @@ module Gitlab
MissingBuildSectionError = Class.new(StandardError)
# The primary trace section to look for.
- PRIMARY_SECTION = 'chat_reply'
+ PRIMARY_SECTION = "chat_reply"
# The backup trace section in case the primary one could not be found.
- FALLBACK_SECTION = 'build_script'
+ FALLBACK_SECTION = "build_script"
# build - The `Ci::Build` to obtain the output from.
def initialize(build)
@@ -69,7 +69,7 @@ module Gitlab
if (converted = output.split("\n")[1..-1])
converted.join("\n")
else
- ''
+ ""
end
end
diff --git a/lib/gitlab/chat/responder/base.rb b/lib/gitlab/chat/responder/base.rb
index f1ad0e36793..c0f71eee172 100644
--- a/lib/gitlab/chat/responder/base.rb
+++ b/lib/gitlab/chat/responder/base.rb
@@ -20,19 +20,19 @@ module Gitlab
end
def success(*)
- raise NotImplementedError, 'You must implement #success(output)'
+ raise NotImplementedError, "You must implement #success(output)"
end
def failure
- raise NotImplementedError, 'You must implement #failure'
+ raise NotImplementedError, "You must implement #failure"
end
def send_response(output)
- raise NotImplementedError, 'You must implement #send_response(output)'
+ raise NotImplementedError, "You must implement #send_response(output)"
end
def scheduled_output
- raise NotImplementedError, 'You must implement #scheduled_output'
+ raise NotImplementedError, "You must implement #scheduled_output"
end
end
end
diff --git a/lib/gitlab/chat/responder/slack.rb b/lib/gitlab/chat/responder/slack.rb
index 0cf02c92a67..90457a214b8 100644
--- a/lib/gitlab/chat/responder/slack.rb
+++ b/lib/gitlab/chat/responder/slack.rb
@@ -4,8 +4,8 @@ module Gitlab
module Chat
module Responder
class Slack < Responder::Base
- SUCCESS_COLOR = '#B3ED8E'
- FAILURE_COLOR = '#FF5640'
+ SUCCESS_COLOR = "#B3ED8E"
+ FAILURE_COLOR = "#FF5640"
RESPONSE_TYPE = :in_channel
# Slack breaks messages apart if they're around 4 KB in size. We use a
@@ -19,8 +19,8 @@ module Gitlab
Gitlab::HTTP.post(
pipeline.chat_data.response_url,
{
- headers: { Accept: 'application/json' },
- body: output.to_json
+ headers: {Accept: "application/json"},
+ body: output.to_json,
}
)
end
@@ -50,7 +50,7 @@ module Gitlab
# We return an empty message so that Slack still shows the input
# command, without polluting the channel with standard "The job has
# been scheduled" (or similar) responses.
- { text: '' }
+ {text: ""}
end
private
diff --git a/lib/gitlab/chat_name_token.rb b/lib/gitlab/chat_name_token.rb
index 8b3c5dc9e8b..4b7ee694e86 100644
--- a/lib/gitlab/chat_name_token.rb
+++ b/lib/gitlab/chat_name_token.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'json'
+require "json"
module Gitlab
class ChatNameToken
diff --git a/lib/gitlab/checks/base_checker.rb b/lib/gitlab/checks/base_checker.rb
index 09b17b5b76b..e499ed4a209 100644
--- a/lib/gitlab/checks/base_checker.rb
+++ b/lib/gitlab/checks/base_checker.rb
@@ -31,7 +31,7 @@ module Gitlab
end
def updated_from_web?
- protocol == 'web'
+ protocol == "web"
end
def tag_exists?
diff --git a/lib/gitlab/checks/branch_check.rb b/lib/gitlab/checks/branch_check.rb
index d06b2df36f2..cdc8fe43bf2 100644
--- a/lib/gitlab/checks/branch_check.rb
+++ b/lib/gitlab/checks/branch_check.rb
@@ -4,19 +4,19 @@ module Gitlab
module Checks
class BranchCheck < BaseChecker
ERROR_MESSAGES = {
- delete_default_branch: 'The default branch of a project cannot be deleted.',
- force_push_protected_branch: 'You are not allowed to force push code to a protected branch on this project.',
- non_master_delete_protected_branch: 'You are not allowed to delete protected branches from this project. Only a project maintainer or owner can delete a protected branch.',
- non_web_delete_protected_branch: 'You can only delete protected branches using the web interface.',
- merge_protected_branch: 'You are not allowed to merge code into protected branches on this project.',
- push_protected_branch: 'You are not allowed to push code to protected branches on this project.'
+ delete_default_branch: "The default branch of a project cannot be deleted.",
+ force_push_protected_branch: "You are not allowed to force push code to a protected branch on this project.",
+ non_master_delete_protected_branch: "You are not allowed to delete protected branches from this project. Only a project maintainer or owner can delete a protected branch.",
+ non_web_delete_protected_branch: "You can only delete protected branches using the web interface.",
+ merge_protected_branch: "You are not allowed to merge code into protected branches on this project.",
+ push_protected_branch: "You are not allowed to push code to protected branches on this project.",
}.freeze
LOG_MESSAGES = {
delete_default_branch_check: "Checking if default branch is being deleted...",
protected_branch_checks: "Checking if you are force pushing to a protected branch...",
protected_branch_push_checks: "Checking if you are allowed to push to the protected branch...",
- protected_branch_deletion_checks: "Checking if you are allowed to delete the protected branch..."
+ protected_branch_deletion_checks: "Checking if you are allowed to delete the protected branch...",
}.freeze
def validate!
@@ -85,11 +85,9 @@ module Gitlab
def empty_project_push_message
<<~MESSAGE
-
- A default branch (e.g. master) does not yet exist for #{project.full_path}
- Ask a project Owner or Maintainer to create a default branch:
-
- #{project_members_url}
+ A default branch (e.g. master) does not yet exist for #{project.full_path}
+ Ask a project Owner or Maintainer to create a default branch:
+ #{project_members_url}
MESSAGE
end
diff --git a/lib/gitlab/checks/diff_check.rb b/lib/gitlab/checks/diff_check.rb
index ea0d8c85a66..6eb3647bc01 100644
--- a/lib/gitlab/checks/diff_check.rb
+++ b/lib/gitlab/checks/diff_check.rb
@@ -7,7 +7,7 @@ module Gitlab
LOG_MESSAGES = {
validate_file_paths: "Validating diffs' file paths...",
- diff_content_check: "Validating diff contents..."
+ diff_content_check: "Validating diff contents...",
}.freeze
def validate!
diff --git a/lib/gitlab/checks/lfs_check.rb b/lib/gitlab/checks/lfs_check.rb
index cc6a14d2d9a..333284424e0 100644
--- a/lib/gitlab/checks/lfs_check.rb
+++ b/lib/gitlab/checks/lfs_check.rb
@@ -3,8 +3,8 @@
module Gitlab
module Checks
class LfsCheck < BaseChecker
- LOG_MESSAGE = "Scanning repository for blobs stored in LFS and verifying their files have been uploaded to GitLab...".freeze
- ERROR_MESSAGE = 'LFS objects are missing. Ensure LFS is properly set up or try a manual "git lfs push --all".'.freeze
+ LOG_MESSAGE = "Scanning repository for blobs stored in LFS and verifying their files have been uploaded to GitLab..."
+ ERROR_MESSAGE = 'LFS objects are missing. Ensure LFS is properly set up or try a manual "git lfs push --all".'
def validate!
return unless project.lfs_enabled?
diff --git a/lib/gitlab/checks/lfs_integrity.rb b/lib/gitlab/checks/lfs_integrity.rb
index 1652d5a30a4..d36bcc56099 100644
--- a/lib/gitlab/checks/lfs_integrity.rb
+++ b/lib/gitlab/checks/lfs_integrity.rb
@@ -14,13 +14,13 @@ module Gitlab
return false unless @newrev && @project.lfs_enabled?
new_lfs_pointers = Gitlab::Git::LfsChanges.new(@project.repository, @newrev)
- .new_pointers(object_limit: ::Gitlab::Git::Repository::REV_LIST_COMMIT_LIMIT, dynamic_timeout: @time_left)
+ .new_pointers(object_limit: ::Gitlab::Git::Repository::REV_LIST_COMMIT_LIMIT, dynamic_timeout: @time_left)
return false unless new_lfs_pointers.present?
existing_count = @project.all_lfs_objects
- .where(oid: new_lfs_pointers.map(&:lfs_oid))
- .count
+ .where(oid: new_lfs_pointers.map(&:lfs_oid))
+ .count
existing_count != new_lfs_pointers.count
end
diff --git a/lib/gitlab/checks/post_push_message.rb b/lib/gitlab/checks/post_push_message.rb
index 492dbb5a596..5ef077b517c 100644
--- a/lib/gitlab/checks/post_push_message.rb
+++ b/lib/gitlab/checks/post_push_message.rb
@@ -41,7 +41,7 @@ module Gitlab
end
def url_to_repo
- protocol == 'ssh' ? project.ssh_url_to_repo : project.http_url_to_repo
+ protocol == "ssh" ? project.ssh_url_to_repo : project.http_url_to_repo
end
end
end
diff --git a/lib/gitlab/checks/project_created.rb b/lib/gitlab/checks/project_created.rb
index 0058a402a62..9c40efd2699 100644
--- a/lib/gitlab/checks/project_created.rb
+++ b/lib/gitlab/checks/project_created.rb
@@ -3,18 +3,15 @@
module Gitlab
module Checks
class ProjectCreated < PostPushMessage
- PROJECT_CREATED = "project_created".freeze
+ PROJECT_CREATED = "project_created"
def message
<<~MESSAGE
-
- The private project #{project.full_path} was successfully created.
-
- To configure the remote, run:
- git remote add origin #{url_to_repo}
-
- To view the project, visit:
- #{project_url}
+ The private project #{project.full_path} was successfully created.
+ To configure the remote, run:
+ git remote add origin #{url_to_repo}
+ To view the project, visit:
+ #{project_url}
MESSAGE
end
diff --git a/lib/gitlab/checks/project_moved.rb b/lib/gitlab/checks/project_moved.rb
index cb3b7acaaad..5c78d1c278f 100644
--- a/lib/gitlab/checks/project_moved.rb
+++ b/lib/gitlab/checks/project_moved.rb
@@ -3,7 +3,7 @@
module Gitlab
module Checks
class ProjectMoved < PostPushMessage
- REDIRECT_NAMESPACE = "redirect_namespace".freeze
+ REDIRECT_NAMESPACE = "redirect_namespace"
def initialize(project, user, protocol, redirected_path)
@redirected_path = redirected_path
@@ -13,11 +13,9 @@ module Gitlab
def message
<<~MESSAGE
- Project '#{redirected_path}' was moved to '#{project.full_path}'.
-
- Please update your Git remote:
-
- git remote set-url origin #{url_to_repo}
+ Project '#{redirected_path}' was moved to '#{project.full_path}'.
+ Please update your Git remote:
+ git remote set-url origin #{url_to_repo}
MESSAGE
end
diff --git a/lib/gitlab/checks/tag_check.rb b/lib/gitlab/checks/tag_check.rb
index 2a75c8059bd..55613155077 100644
--- a/lib/gitlab/checks/tag_check.rb
+++ b/lib/gitlab/checks/tag_check.rb
@@ -4,15 +4,15 @@ module Gitlab
module Checks
class TagCheck < BaseChecker
ERROR_MESSAGES = {
- change_existing_tags: 'You are not allowed to change existing tags on this project.',
- update_protected_tag: 'Protected tags cannot be updated.',
- delete_protected_tag: 'Protected tags cannot be deleted.',
- create_protected_tag: 'You are not allowed to create this tag as it is protected.'
+ change_existing_tags: "You are not allowed to change existing tags on this project.",
+ update_protected_tag: "Protected tags cannot be updated.",
+ delete_protected_tag: "Protected tags cannot be deleted.",
+ create_protected_tag: "You are not allowed to create this tag as it is protected.",
}.freeze
LOG_MESSAGES = {
tag_checks: "Checking if you are allowed to change existing tags...",
- protected_tag_checks: "Checking if you are creating, updating or deleting a protected tag..."
+ protected_tag_checks: "Checking if you are creating, updating or deleting a protected tag...",
}.freeze
def validate!
diff --git a/lib/gitlab/checks/timed_logger.rb b/lib/gitlab/checks/timed_logger.rb
index f365e0a43f6..6b7d5c6dde2 100644
--- a/lib/gitlab/checks/timed_logger.rb
+++ b/lib/gitlab/checks/timed_logger.rb
@@ -28,7 +28,7 @@ module Gitlab
append_message(log_message + time_suffix_message(start: start))
rescue GRPC::DeadlineExceeded, TimeoutError
- args = { cancelled: true }
+ args = {cancelled: true}
args[:start] = start if timed
append_message(log_message + time_suffix_message(args))
diff --git a/lib/gitlab/ci/ansi2html.rb b/lib/gitlab/ci/ansi2html.rb
index 4dcb3869d4f..bcee5d9043d 100644
--- a/lib/gitlab/ci/ansi2html.rb
+++ b/lib/gitlab/ci/ansi2html.rb
@@ -8,22 +8,22 @@ module Gitlab
module Ansi2html
# keys represent the trailing digit in color changing command (30-37, 40-47, 90-97. 100-107)
COLOR = {
- 0 => 'black', # not that this is gray in the intense color table
- 1 => 'red',
- 2 => 'green',
- 3 => 'yellow',
- 4 => 'blue',
- 5 => 'magenta',
- 6 => 'cyan',
- 7 => 'white', # not that this is gray in the dark (aka default) color table
+ 0 => "black", # not that this is gray in the intense color table
+ 1 => "red",
+ 2 => "green",
+ 3 => "yellow",
+ 4 => "blue",
+ 5 => "magenta",
+ 6 => "cyan",
+ 7 => "white", # not that this is gray in the dark (aka default) color table
}.freeze
STYLE_SWITCHES = {
- bold: 0x01,
- italic: 0x02,
- underline: 0x04,
- conceal: 0x08,
- cross: 0x10
+ bold: 0x01,
+ italic: 0x02,
+ underline: 0x04,
+ conceal: 0x08,
+ cross: 0x10,
}.freeze
def self.convert(ansi, state = nil)
@@ -31,105 +31,205 @@ module Gitlab
end
class Converter
- def on_0(_) reset end
+ def on_0(_)
+ reset
+ end
- def on_1(_) enable(STYLE_SWITCHES[:bold]) end
+ def on_1(_)
+ enable(STYLE_SWITCHES[:bold])
+ end
- def on_3(_) enable(STYLE_SWITCHES[:italic]) end
+ def on_3(_)
+ enable(STYLE_SWITCHES[:italic])
+ end
- def on_4(_) enable(STYLE_SWITCHES[:underline]) end
+ def on_4(_)
+ enable(STYLE_SWITCHES[:underline])
+ end
- def on_8(_) enable(STYLE_SWITCHES[:conceal]) end
+ def on_8(_)
+ enable(STYLE_SWITCHES[:conceal])
+ end
- def on_9(_) enable(STYLE_SWITCHES[:cross]) end
+ def on_9(_)
+ enable(STYLE_SWITCHES[:cross])
+ end
- def on_21(_) disable(STYLE_SWITCHES[:bold]) end
+ def on_21(_)
+ disable(STYLE_SWITCHES[:bold])
+ end
- def on_22(_) disable(STYLE_SWITCHES[:bold]) end
+ def on_22(_)
+ disable(STYLE_SWITCHES[:bold])
+ end
- def on_23(_) disable(STYLE_SWITCHES[:italic]) end
+ def on_23(_)
+ disable(STYLE_SWITCHES[:italic])
+ end
- def on_24(_) disable(STYLE_SWITCHES[:underline]) end
+ def on_24(_)
+ disable(STYLE_SWITCHES[:underline])
+ end
- def on_28(_) disable(STYLE_SWITCHES[:conceal]) end
+ def on_28(_)
+ disable(STYLE_SWITCHES[:conceal])
+ end
- def on_29(_) disable(STYLE_SWITCHES[:cross]) end
+ def on_29(_)
+ disable(STYLE_SWITCHES[:cross])
+ end
- def on_30(_) set_fg_color(0) end
+ def on_30(_)
+ set_fg_color(0)
+ end
- def on_31(_) set_fg_color(1) end
+ def on_31(_)
+ set_fg_color(1)
+ end
- def on_32(_) set_fg_color(2) end
+ def on_32(_)
+ set_fg_color(2)
+ end
- def on_33(_) set_fg_color(3) end
+ def on_33(_)
+ set_fg_color(3)
+ end
- def on_34(_) set_fg_color(4) end
+ def on_34(_)
+ set_fg_color(4)
+ end
- def on_35(_) set_fg_color(5) end
+ def on_35(_)
+ set_fg_color(5)
+ end
- def on_36(_) set_fg_color(6) end
+ def on_36(_)
+ set_fg_color(6)
+ end
- def on_37(_) set_fg_color(7) end
+ def on_37(_)
+ set_fg_color(7)
+ end
- def on_38(stack) set_fg_color_256(stack) end
+ def on_38(stack)
+ set_fg_color_256(stack)
+ end
- def on_39(_) set_fg_color(9) end
+ def on_39(_)
+ set_fg_color(9)
+ end
- def on_40(_) set_bg_color(0) end
+ def on_40(_)
+ set_bg_color(0)
+ end
- def on_41(_) set_bg_color(1) end
+ def on_41(_)
+ set_bg_color(1)
+ end
- def on_42(_) set_bg_color(2) end
+ def on_42(_)
+ set_bg_color(2)
+ end
- def on_43(_) set_bg_color(3) end
+ def on_43(_)
+ set_bg_color(3)
+ end
- def on_44(_) set_bg_color(4) end
+ def on_44(_)
+ set_bg_color(4)
+ end
- def on_45(_) set_bg_color(5) end
+ def on_45(_)
+ set_bg_color(5)
+ end
- def on_46(_) set_bg_color(6) end
+ def on_46(_)
+ set_bg_color(6)
+ end
- def on_47(_) set_bg_color(7) end
+ def on_47(_)
+ set_bg_color(7)
+ end
- def on_48(stack) set_bg_color_256(stack) end
+ def on_48(stack)
+ set_bg_color_256(stack)
+ end
- def on_49(_) set_bg_color(9) end
+ def on_49(_)
+ set_bg_color(9)
+ end
- def on_90(_) set_fg_color(0, 'l') end
+ def on_90(_)
+ set_fg_color(0, "l")
+ end
- def on_91(_) set_fg_color(1, 'l') end
+ def on_91(_)
+ set_fg_color(1, "l")
+ end
- def on_92(_) set_fg_color(2, 'l') end
+ def on_92(_)
+ set_fg_color(2, "l")
+ end
- def on_93(_) set_fg_color(3, 'l') end
+ def on_93(_)
+ set_fg_color(3, "l")
+ end
- def on_94(_) set_fg_color(4, 'l') end
+ def on_94(_)
+ set_fg_color(4, "l")
+ end
- def on_95(_) set_fg_color(5, 'l') end
+ def on_95(_)
+ set_fg_color(5, "l")
+ end
- def on_96(_) set_fg_color(6, 'l') end
+ def on_96(_)
+ set_fg_color(6, "l")
+ end
- def on_97(_) set_fg_color(7, 'l') end
+ def on_97(_)
+ set_fg_color(7, "l")
+ end
- def on_99(_) set_fg_color(9, 'l') end
+ def on_99(_)
+ set_fg_color(9, "l")
+ end
- def on_100(_) set_bg_color(0, 'l') end
+ def on_100(_)
+ set_bg_color(0, "l")
+ end
- def on_101(_) set_bg_color(1, 'l') end
+ def on_101(_)
+ set_bg_color(1, "l")
+ end
- def on_102(_) set_bg_color(2, 'l') end
+ def on_102(_)
+ set_bg_color(2, "l")
+ end
- def on_103(_) set_bg_color(3, 'l') end
+ def on_103(_)
+ set_bg_color(3, "l")
+ end
- def on_104(_) set_bg_color(4, 'l') end
+ def on_104(_)
+ set_bg_color(4, "l")
+ end
- def on_105(_) set_bg_color(5, 'l') end
+ def on_105(_)
+ set_bg_color(5, "l")
+ end
- def on_106(_) set_bg_color(6, 'l') end
+ def on_106(_)
+ set_bg_color(6, "l")
+ end
- def on_107(_) set_bg_color(7, 'l') end
+ def on_107(_)
+ set_bg_color(7, "l")
+ end
- def on_109(_) set_bg_color(9, 'l') end
+ def on_109(_)
+ set_bg_color(9, "l")
+ end
attr_accessor :offset, :n_open_tags, :fg_color, :bg_color, :style_mask
@@ -166,9 +266,9 @@ module Gitlab
elsif s.scan(/\e(([@-_])(.*?)?)?$/)
break
elsif s.scan(/</)
- @out << '&lt;'
+ @out << "&lt;"
elsif s.scan(/\r?\n/)
- @out << '<br>'
+ @out << "<br>"
else
@out << s.scan(/./m)
end
@@ -196,18 +296,18 @@ module Gitlab
section = scanner[3]
line = scanner.matched[0...-5] # strips \r\033[0K
- @out << %{<div class="hidden" data-action="#{action}" data-timestamp="#{timestamp}" data-section="#{section}">#{line}</div>}
+ @out << %(<div class="hidden" data-action="#{action}" data-timestamp="#{timestamp}" data-section="#{section}">#{line}</div>)
end
def handle_sequence(scanner)
indicator = scanner[1]
- commands = scanner[2].split ';'
+ commands = scanner[2].split ";"
terminator = scanner[3]
# We are only interested in color and text style changes - triggered by
# sequences starting with '\e[' and ending with 'm'. Any other control
# sequence gets stripped (including stuff like "delete last line")
- return unless indicator == '[' && terminator == 'm'
+ return unless indicator == "[" && terminator == "m"
close_open_tags
@@ -224,8 +324,8 @@ module Gitlab
def evaluate_command_stack(stack)
return unless command = stack.shift
- if self.respond_to?("on_#{command}", true)
- self.__send__("on_#{command}", stack) # rubocop:disable GitlabSecurity/PublicSend
+ if respond_to?("on_#{command}", true)
+ __send__("on_#{command}", stack) # rubocop:disable GitlabSecurity/PublicSend
end
evaluate_command_stack(stack)
@@ -253,13 +353,13 @@ module Gitlab
return if css_classes.empty?
- @out << %{<span class="#{css_classes.join(' ')}">}
+ @out << %(<span class="#{css_classes.join(" ")}">)
@n_open_tags += 1
end
def close_open_tags
while @n_open_tags > 0
- @out << %{</span>}
+ @out << %(</span>)
@n_open_tags -= 1
end
end
@@ -267,15 +367,14 @@ module Gitlab
def reset_state
@offset = 0
@n_open_tags = 0
- @out = +''
+ @out = +""
reset
end
def state
- state = STATE_PARAMS.inject({}) do |h, param|
+ state = STATE_PARAMS.each_with_object({}) { |param, h|
h[param] = send(param) # rubocop:disable GitlabSecurity/PublicSend
- h
- end
+ }
Base64.urlsafe_encode64(state.to_json)
end
@@ -343,7 +442,7 @@ module Gitlab
end
def get_color_class(segments)
- [segments].flatten.compact.join('-')
+ [segments].flatten.compact.join("-")
end
end
end
diff --git a/lib/gitlab/ci/build/artifacts/adapters/raw_stream.rb b/lib/gitlab/ci/build/artifacts/adapters/raw_stream.rb
index cf37d700991..c2448107a3b 100644
--- a/lib/gitlab/ci/build/artifacts/adapters/raw_stream.rb
+++ b/lib/gitlab/ci/build/artifacts/adapters/raw_stream.rb
@@ -19,7 +19,7 @@ module Gitlab
def each_blob
stream.seek(0)
- yield(stream.read, 'raw') unless stream.eof?
+ yield(stream.read, "raw") unless stream.eof?
end
end
end
diff --git a/lib/gitlab/ci/build/artifacts/metadata.rb b/lib/gitlab/ci/build/artifacts/metadata.rb
index 08dac756cc1..03243d741fb 100644
--- a/lib/gitlab/ci/build/artifacts/metadata.rb
+++ b/lib/gitlab/ci/build/artifacts/metadata.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'zlib'
-require 'json'
+require "zlib"
+require "json"
module Gitlab
module Ci
@@ -29,12 +29,12 @@ module Gitlab
gzip do |gz|
read_string(gz) # version
errors = read_string(gz)
- raise ParserError, 'Errors field not found!' unless errors
+ raise ParserError, "Errors field not found!" unless errors
begin
JSON.parse(errors)
rescue JSON::ParserError
- raise ParserError, 'Invalid errors field!'
+ raise ParserError, "Invalid errors field!"
end
end
end
@@ -56,13 +56,13 @@ module Gitlab
def match_entries(gz)
entries = {}
- child_pattern = '[^/]*/?$' unless @opts[:recursive]
+ child_pattern = "[^/]*/?$" unless @opts[:recursive]
match_pattern = /^#{Regexp.escape(@path)}#{child_pattern}/
until gz.eof?
begin
- path = read_string(gz)&.force_encoding('UTF-8')
- meta = read_string(gz)&.force_encoding('UTF-8')
+ path = read_string(gz)&.force_encoding("UTF-8")
+ meta = read_string(gz)&.force_encoding("UTF-8")
# We might hit an EOF while reading either value, so we should
# abort if we don't get any data.
@@ -85,11 +85,11 @@ module Gitlab
version_string = read_string(gz)
unless version_string
- raise ParserError, 'Artifacts metadata file empty!'
+ raise ParserError, "Artifacts metadata file empty!"
end
- unless version_string =~ VERSION_PATTERN
- raise ParserError, 'Invalid version!'
+ unless VERSION_PATTERN.match?(version_string)
+ raise ParserError, "Invalid version!"
end
version_string.chomp
@@ -98,7 +98,7 @@ module Gitlab
def read_uint32(gz)
binary = gz.read(4)
- binary.unpack('L>')[0] if binary
+ binary&.unpack1("L>")
end
def read_string(gz)
diff --git a/lib/gitlab/ci/build/artifacts/metadata/entry.rb b/lib/gitlab/ci/build/artifacts/metadata/entry.rb
index d0a80518ae8..01b2200761d 100644
--- a/lib/gitlab/ci/build/artifacts/metadata/entry.rb
+++ b/lib/gitlab/ci/build/artifacts/metadata/entry.rb
@@ -50,7 +50,7 @@ module Gitlab
end
def basename
- (directory? && !blank_node?) ? name + '/' : name
+ directory? && !blank_node? ? name + "/" : name
end
def name
@@ -72,7 +72,7 @@ module Gitlab
return dirs unless has_parent? && opts[:parent]
dotted_parent = parent
- dotted_parent.name = '..'
+ dotted_parent.name = ".."
dirs.prepend(dotted_parent)
end
diff --git a/lib/gitlab/ci/build/artifacts/path.rb b/lib/gitlab/ci/build/artifacts/path.rb
index 65cd935afaa..f704e91d1e9 100644
--- a/lib/gitlab/ci/build/artifacts/path.rb
+++ b/lib/gitlab/ci/build/artifacts/path.rb
@@ -6,7 +6,7 @@ module Gitlab
module Artifacts
class Path
def initialize(path)
- @path = path.dup.force_encoding('UTF-8')
+ @path = path.dup.force_encoding("UTF-8")
end
def valid?
@@ -14,25 +14,25 @@ module Gitlab
end
def directory?
- @path.end_with?('/')
+ @path.end_with?("/")
end
def name
- @path.split('/').last.to_s
+ @path.split("/").last.to_s
end
def nodes
- @path.count('/')
+ @path.count("/")
end
def to_s
@path.tap do |path|
unless nonzero?
- raise ArgumentError, 'Path contains zero byte character!'
+ raise ArgumentError, "Path contains zero byte character!"
end
unless utf8?
- raise ArgumentError, 'Path contains non-UTF-8 byte sequence!'
+ raise ArgumentError, "Path contains non-UTF-8 byte sequence!"
end
end
end
diff --git a/lib/gitlab/ci/build/credentials/registry.rb b/lib/gitlab/ci/build/credentials/registry.rb
index 1c8588d9913..be3b7ea53b9 100644
--- a/lib/gitlab/ci/build/credentials/registry.rb
+++ b/lib/gitlab/ci/build/credentials/registry.rb
@@ -8,7 +8,7 @@ module Gitlab
attr_reader :username, :password
def initialize(build)
- @username = 'gitlab-ci-token'
+ @username = "gitlab-ci-token"
@password = build.token
end
diff --git a/lib/gitlab/ci/build/image.rb b/lib/gitlab/ci/build/image.rb
index 4dd932f61d4..7f6118be3ec 100644
--- a/lib/gitlab/ci/build/image.rb
+++ b/lib/gitlab/ci/build/image.rb
@@ -15,9 +15,9 @@ module Gitlab
end
def from_services(job)
- services = job.options[:services].to_a.map do |service|
+ services = job.options[:services].to_a.map { |service|
Gitlab::Ci::Build::Image.new(service)
- end
+ }
services.select(&:valid?).compact
end
diff --git a/lib/gitlab/ci/build/policy.rb b/lib/gitlab/ci/build/policy.rb
index 43c46ad74af..27f27729dd1 100644
--- a/lib/gitlab/ci/build/policy.rb
+++ b/lib/gitlab/ci/build/policy.rb
@@ -5,9 +5,9 @@ module Gitlab
module Build
module Policy
def self.fabricate(specs)
- specifications = specs.to_h.map do |spec, value|
- self.const_get(spec.to_s.camelize).new(value)
- end
+ specifications = specs.to_h.map { |spec, value|
+ const_get(spec.to_s.camelize).new(value)
+ }
specifications.compact
end
diff --git a/lib/gitlab/ci/build/policy/refs.rb b/lib/gitlab/ci/build/policy/refs.rb
index 0e9bb5c94bb..708daaff5a6 100644
--- a/lib/gitlab/ci/build/policy/refs.rb
+++ b/lib/gitlab/ci/build/policy/refs.rb
@@ -11,7 +11,7 @@ module Gitlab
def satisfied_by?(pipeline, seed = nil)
@patterns.any? do |pattern|
- pattern, path = pattern.split('@', 2)
+ pattern, path = pattern.split("@", 2)
matches_path?(path, pipeline) &&
matches_pattern?(pattern, pipeline)
@@ -27,8 +27,8 @@ module Gitlab
end
def matches_pattern?(pattern, pipeline)
- return true if pipeline.tag? && pattern == 'tags'
- return true if pipeline.branch? && pattern == 'branches'
+ return true if pipeline.tag? && pattern == "tags"
+ return true if pipeline.branch? && pattern == "branches"
return true if pipeline.source == pattern
return true if pipeline.source&.pluralize == pattern
diff --git a/lib/gitlab/ci/build/policy/variables.rb b/lib/gitlab/ci/build/policy/variables.rb
index 0698136166a..5f69e96f56d 100644
--- a/lib/gitlab/ci/build/policy/variables.rb
+++ b/lib/gitlab/ci/build/policy/variables.rb
@@ -12,10 +12,10 @@ module Gitlab
def satisfied_by?(pipeline, seed)
variables = seed.to_resource.scoped_variables_hash
- statements = @expressions.map do |statement|
+ statements = @expressions.map { |statement|
::Gitlab::Ci::Pipeline::Expression::Statement
.new(statement, variables)
- end
+ }
statements.any?(&:truthful?)
end
diff --git a/lib/gitlab/ci/build/step.rb b/lib/gitlab/ci/build/step.rb
index 7fcabc035ac..881fa5cb00a 100644
--- a/lib/gitlab/ci/build/step.rb
+++ b/lib/gitlab/ci/build/step.rb
@@ -4,16 +4,16 @@ module Gitlab
module Ci
module Build
class Step
- WHEN_ON_FAILURE = 'on_failure'.freeze
- WHEN_ON_SUCCESS = 'on_success'.freeze
- WHEN_ALWAYS = 'always'.freeze
+ WHEN_ON_FAILURE = "on_failure"
+ WHEN_ON_SUCCESS = "on_success"
+ WHEN_ALWAYS = "always"
attr_reader :name
attr_accessor :script, :timeout, :when, :allow_failure
class << self
def from_commands(job)
- self.new(:script).tap do |step|
+ new(:script).tap do |step|
step.script = job.options[:before_script].to_a + job.options[:script].to_a
step.timeout = job.metadata_timeout
step.when = WHEN_ON_SUCCESS
@@ -24,7 +24,7 @@ module Gitlab
after_script = job.options[:after_script]
return unless after_script
- self.new(:after_script).tap do |step|
+ new(:after_script).tap do |step|
step.script = after_script
step.timeout = job.metadata_timeout
step.when = WHEN_ALWAYS
diff --git a/lib/gitlab/ci/charts.rb b/lib/gitlab/ci/charts.rb
index 7cabaadb122..ec500d4c2bb 100644
--- a/lib/gitlab/ci/charts.rb
+++ b/lib/gitlab/ci/charts.rb
@@ -81,7 +81,7 @@ module Gitlab
def initialize(*)
@to = Date.today.end_of_month.end_of_day
@from = @to.years_ago(1).beginning_of_month.beginning_of_day
- @format = '%d %B %Y'
+ @format = "%d %B %Y"
super
end
@@ -94,7 +94,7 @@ module Gitlab
def initialize(*)
@to = Date.today.end_of_day
@from = 1.month.ago.beginning_of_day
- @format = '%d %B'
+ @format = "%d %B"
super
end
@@ -107,7 +107,7 @@ module Gitlab
def initialize(*)
@to = Date.today.end_of_day
@from = 1.week.ago.beginning_of_day
- @format = '%d %B'
+ @format = "%d %B"
super
end
diff --git a/lib/gitlab/ci/config/entry/artifacts.rb b/lib/gitlab/ci/config/entry/artifacts.rb
index 41613369ca2..99965c8ecf2 100644
--- a/lib/gitlab/ci/config/entry/artifacts.rb
+++ b/lib/gitlab/ci/config/entry/artifacts.rb
@@ -16,7 +16,7 @@ module Gitlab
attributes ALLOWED_KEYS
- entry :reports, Entry::Reports, description: 'Report-type artifacts.'
+ entry :reports, Entry::Reports, description: "Report-type artifacts."
validations do
validates :config, type: Hash
@@ -28,9 +28,9 @@ module Gitlab
validates :paths, array_of_strings: true
validates :reports, type: Hash
validates :when,
- inclusion: { in: %w[on_success on_failure always],
- message: 'should be on_success, on_failure ' \
- 'or always' }
+ inclusion: {in: %w[on_success on_failure always],
+ message: "should be on_success, on_failure " \
+ "or always",}
validates :expire_in, duration: true
end
end
diff --git a/lib/gitlab/ci/config/entry/cache.rb b/lib/gitlab/ci/config/entry/cache.rb
index 7b94af24c09..266f41db139 100644
--- a/lib/gitlab/ci/config/entry/cache.rb
+++ b/lib/gitlab/ci/config/entry/cache.rb
@@ -12,21 +12,21 @@ module Gitlab
include ::Gitlab::Config::Entry::Attributable
ALLOWED_KEYS = %i[key untracked paths policy].freeze
- DEFAULT_POLICY = 'pull-push'.freeze
+ DEFAULT_POLICY = "pull-push"
validations do
validates :config, allowed_keys: ALLOWED_KEYS
- validates :policy, inclusion: { in: %w[pull-push push pull], message: 'should be pull-push, push, or pull' }, allow_blank: true
+ validates :policy, inclusion: {in: %w[pull-push push pull], message: "should be pull-push, push, or pull"}, allow_blank: true
end
entry :key, Entry::Key,
- description: 'Cache key used to define a cache affinity.'
+ description: "Cache key used to define a cache affinity."
entry :untracked, ::Gitlab::Config::Entry::Boolean,
- description: 'Cache all untracked files.'
+ description: "Cache all untracked files."
entry :paths, Entry::Paths,
- description: 'Specify which paths should be cached across builds.'
+ description: "Specify which paths should be cached across builds."
helpers :key
diff --git a/lib/gitlab/ci/config/entry/environment.rb b/lib/gitlab/ci/config/entry/environment.rb
index 69a3a1aedef..3b05f92b9c9 100644
--- a/lib/gitlab/ci/config/entry/environment.rb
+++ b/lib/gitlab/ci/config/entry/environment.rb
@@ -15,7 +15,7 @@ module Gitlab
validations do
validate do
unless hash? || string?
- errors.add(:config, 'should be a hash or a string')
+ errors.add(:config, "should be a hash or a string")
end
end
@@ -23,25 +23,25 @@ module Gitlab
validates :name,
type: {
with: String,
- message: Gitlab::Regex.environment_name_regex_message
+ message: Gitlab::Regex.environment_name_regex_message,
}
validates :name,
format: {
with: Gitlab::Regex.environment_name_regex,
- message: Gitlab::Regex.environment_name_regex_message
+ message: Gitlab::Regex.environment_name_regex_message,
}
with_options if: :hash? do
validates :config, allowed_keys: ALLOWED_KEYS
validates :url,
- length: { maximum: 255 },
- allow_nil: true
+ length: {maximum: 255},
+ allow_nil: true
validates :action,
- inclusion: { in: %w[start stop], message: 'should be start or stop' },
- allow_nil: true
+ inclusion: {in: %w[start stop], message: "should be start or stop"},
+ allow_nil: true
validates :on_stop, type: String, allow_nil: true
end
@@ -64,7 +64,7 @@ module Gitlab
end
def action
- value[:action] || 'start'
+ value[:action] || "start"
end
def on_stop
@@ -73,7 +73,7 @@ module Gitlab
def value
case @config
- when String then { name: @config, action: 'start' }
+ when String then {name: @config, action: "start"}
when Hash then @config
else {}
end
diff --git a/lib/gitlab/ci/config/entry/global.rb b/lib/gitlab/ci/config/entry/global.rb
index 2b5a59c078e..05e000ba0fa 100644
--- a/lib/gitlab/ci/config/entry/global.rb
+++ b/lib/gitlab/ci/config/entry/global.rb
@@ -12,34 +12,34 @@ module Gitlab
include ::Gitlab::Config::Entry::Configurable
entry :before_script, Entry::Script,
- description: 'Script that will be executed before each job.'
+ description: "Script that will be executed before each job."
entry :image, Entry::Image,
- description: 'Docker image that will be used to execute jobs.'
+ description: "Docker image that will be used to execute jobs."
entry :include, Entry::Includes,
- description: 'List of external YAML files to include.'
+ description: "List of external YAML files to include."
entry :services, Entry::Services,
- description: 'Docker images that will be linked to the container.'
+ description: "Docker images that will be linked to the container."
entry :after_script, Entry::Script,
- description: 'Script that will be executed after each job.'
+ description: "Script that will be executed after each job."
entry :variables, Entry::Variables,
- description: 'Environment variables that will be used.'
+ description: "Environment variables that will be used."
entry :stages, Entry::Stages,
- description: 'Configuration of stages for this pipeline.'
+ description: "Configuration of stages for this pipeline."
entry :types, Entry::Stages,
- description: 'Deprecated: stages for this pipeline.'
+ description: "Deprecated: stages for this pipeline."
entry :cache, Entry::Cache,
- description: 'Configure caching between build jobs.'
+ description: "Configure caching between build jobs."
helpers :before_script, :image, :services, :after_script,
- :variables, :stages, :types, :cache, :jobs
+ :variables, :stages, :types, :cache, :jobs
def compose!(_deps = nil)
super(self) do
@@ -55,7 +55,7 @@ module Gitlab
factory = ::Gitlab::Config::Entry::Factory.new(Entry::Jobs)
.value(@config.except(*self.class.nodes.keys))
.with(key: :jobs, parent: self,
- description: 'Jobs definition for this pipeline')
+ description: "Jobs definition for this pipeline")
@entries[:jobs] = factory.create!
end
diff --git a/lib/gitlab/ci/config/entry/image.rb b/lib/gitlab/ci/config/entry/image.rb
index a13a0625e90..9ac5e682c3d 100644
--- a/lib/gitlab/ci/config/entry/image.rb
+++ b/lib/gitlab/ci/config/entry/image.rb
@@ -37,7 +37,7 @@ module Gitlab
end
def value
- return { name: @config } if string?
+ return {name: @config} if string?
return @config if hash?
{}
diff --git a/lib/gitlab/ci/config/entry/includes.rb b/lib/gitlab/ci/config/entry/includes.rb
index 82b2b1ccf4b..d24876ac0ad 100644
--- a/lib/gitlab/ci/config/entry/includes.rb
+++ b/lib/gitlab/ci/config/entry/includes.rb
@@ -20,8 +20,8 @@ module Gitlab
@config.each_with_index do |config, i|
@entries[i] = ::Gitlab::Config::Entry::Factory.new(Entry::Include)
- .value(config || {})
- .create!
+ .value(config || {})
+ .create!
end
end
end
diff --git a/lib/gitlab/ci/config/entry/job.rb b/lib/gitlab/ci/config/entry/job.rb
index 290c9591b98..cef269d8681 100644
--- a/lib/gitlab/ci/config/entry/job.rb
+++ b/lib/gitlab/ci/config/entry/job.rb
@@ -26,74 +26,74 @@ module Gitlab
with_options allow_nil: true do
validates :tags, array_of_strings: true
validates :allow_failure, boolean: true
- validates :parallel, numericality: { only_integer: true,
- greater_than_or_equal_to: 2,
- less_than_or_equal_to: 50 }
+ validates :parallel, numericality: {only_integer: true,
+ greater_than_or_equal_to: 2,
+ less_than_or_equal_to: 50,}
validates :when,
- inclusion: { in: %w[on_success on_failure always manual delayed],
- message: 'should be on_success, on_failure, ' \
- 'always, manual or delayed' }
+ inclusion: {in: %w[on_success on_failure always manual delayed],
+ message: "should be on_success, on_failure, " \
+ "always, manual or delayed",}
validates :dependencies, array_of_strings: true
validates :extends, type: String
end
- validates :start_in, duration: { limit: '1 day' }, if: :delayed?
+ validates :start_in, duration: {limit: "1 day"}, if: :delayed?
validates :start_in, absence: true, unless: :delayed?
end
entry :before_script, Entry::Script,
- description: 'Global before script overridden in this job.'
+ description: "Global before script overridden in this job."
entry :script, Entry::Commands,
- description: 'Commands that will be executed in this job.'
+ description: "Commands that will be executed in this job."
entry :stage, Entry::Stage,
- description: 'Pipeline stage this job will be executed into.'
+ description: "Pipeline stage this job will be executed into."
entry :type, Entry::Stage,
- description: 'Deprecated: stage this job will be executed into.'
+ description: "Deprecated: stage this job will be executed into."
entry :after_script, Entry::Script,
- description: 'Commands that will be executed when finishing job.'
+ description: "Commands that will be executed when finishing job."
entry :cache, Entry::Cache,
- description: 'Cache definition for this job.'
+ description: "Cache definition for this job."
entry :image, Entry::Image,
- description: 'Image that will be used to execute this job.'
+ description: "Image that will be used to execute this job."
entry :services, Entry::Services,
- description: 'Services that will be used to execute this job.'
+ description: "Services that will be used to execute this job."
entry :only, Entry::Policy,
- description: 'Refs policy this job will be executed for.',
+ description: "Refs policy this job will be executed for.",
default: Entry::Policy::DEFAULT_ONLY
entry :except, Entry::Policy,
- description: 'Refs policy this job will be executed for.'
+ description: "Refs policy this job will be executed for."
entry :variables, Entry::Variables,
- description: 'Environment variables available for this job.'
+ description: "Environment variables available for this job."
entry :artifacts, Entry::Artifacts,
- description: 'Artifacts configuration for this job.'
+ description: "Artifacts configuration for this job."
entry :environment, Entry::Environment,
- description: 'Environment configuration for this job.'
+ description: "Environment configuration for this job."
entry :coverage, Entry::Coverage,
- description: 'Coverage configuration for this job.'
+ description: "Coverage configuration for this job."
entry :retry, Entry::Retry,
- description: 'Retry configuration for this job.'
+ description: "Retry configuration for this job."
helpers :before_script, :script, :stage, :type, :after_script,
- :cache, :image, :services, :only, :except, :variables,
- :artifacts, :environment, :coverage, :retry,
- :parallel
+ :cache, :image, :services, :only, :except, :variables,
+ :artifacts, :environment, :coverage, :retry,
+ :parallel
attributes :script, :tags, :allow_failure, :when, :dependencies,
- :retry, :parallel, :extends, :start_in
+ :retry, :parallel, :extends, :start_in
def compose!(deps = nil)
super do
@@ -116,11 +116,11 @@ module Gitlab
end
def manual_action?
- self.when == 'manual'
+ self.when == "manual"
end
def delayed?
- self.when == 'delayed'
+ self.when == "delayed"
end
def ignored?
@@ -143,24 +143,24 @@ module Gitlab
end
def to_hash
- { name: name,
- before_script: before_script_value,
- script: script_value,
- image: image_value,
- services: services_value,
- stage: stage_value,
- cache: cache_value,
- only: only_value,
- except: except_value,
- variables: variables_defined? ? variables_value : nil,
- environment: environment_defined? ? environment_value : nil,
- environment_name: environment_defined? ? environment_value[:name] : nil,
- coverage: coverage_defined? ? coverage_value : nil,
- retry: retry_defined? ? retry_value : nil,
- parallel: parallel_defined? ? parallel_value.to_i : nil,
- artifacts: artifacts_value,
- after_script: after_script_value,
- ignore: ignored? }
+ {name: name,
+ before_script: before_script_value,
+ script: script_value,
+ image: image_value,
+ services: services_value,
+ stage: stage_value,
+ cache: cache_value,
+ only: only_value,
+ except: except_value,
+ variables: variables_defined? ? variables_value : nil,
+ environment: environment_defined? ? environment_value : nil,
+ environment_name: environment_defined? ? environment_value[:name] : nil,
+ coverage: coverage_defined? ? coverage_value : nil,
+ retry: retry_defined? ? retry_value : nil,
+ parallel: parallel_defined? ? parallel_value.to_i : nil,
+ artifacts: artifacts_value,
+ after_script: after_script_value,
+ ignore: ignored?,}
end
end
end
diff --git a/lib/gitlab/ci/config/entry/jobs.rb b/lib/gitlab/ci/config/entry/jobs.rb
index 9845c4af655..87419bcb5d7 100644
--- a/lib/gitlab/ci/config/entry/jobs.rb
+++ b/lib/gitlab/ci/config/entry/jobs.rb
@@ -15,7 +15,7 @@ module Gitlab
validate do
unless has_visible_job?
- errors.add(:config, 'should contain at least one visible job')
+ errors.add(:config, "should contain at least one visible job")
end
end
@@ -25,7 +25,7 @@ module Gitlab
end
def hidden?(name)
- name.to_s.start_with?('.')
+ name.to_s.start_with?(".")
end
def node_type(name)
diff --git a/lib/gitlab/ci/config/entry/key.rb b/lib/gitlab/ci/config/entry/key.rb
index 0c10967e629..4f8bd35f0b9 100644
--- a/lib/gitlab/ci/config/entry/key.rb
+++ b/lib/gitlab/ci/config/entry/key.rb
@@ -15,7 +15,7 @@ module Gitlab
end
def self.default
- 'default'
+ "default"
end
end
end
diff --git a/lib/gitlab/ci/config/entry/policy.rb b/lib/gitlab/ci/config/entry/policy.rb
index adc3660d950..7a16ae52ef4 100644
--- a/lib/gitlab/ci/config/entry/policy.rb
+++ b/lib/gitlab/ci/config/entry/policy.rb
@@ -8,10 +8,10 @@ module Gitlab
# Entry that represents an only/except trigger policy for the job.
#
class Policy < ::Gitlab::Config::Entry::Simplifiable
- strategy :RefsPolicy, if: -> (config) { config.is_a?(Array) }
- strategy :ComplexPolicy, if: -> (config) { config.is_a?(Hash) }
+ strategy :RefsPolicy, if: ->(config) { config.is_a?(Array) }
+ strategy :ComplexPolicy, if: ->(config) { config.is_a?(Hash) }
- DEFAULT_ONLY = { refs: %w[branches tags] }.freeze
+ DEFAULT_ONLY = {refs: %w[branches tags]}.freeze
class RefsPolicy < ::Gitlab::Config::Entry::Node
include ::Gitlab::Config::Entry::Validatable
@@ -21,7 +21,7 @@ module Gitlab
end
def value
- { refs: @config }
+ {refs: @config}
end
end
@@ -47,9 +47,9 @@ module Gitlab
def variables_expressions_syntax
return unless variables.is_a?(Array)
- statements = variables.map do |statement|
+ statements = variables.map { |statement|
::Gitlab::Ci::Pipeline::Expression::Statement.new(statement)
- end
+ }
statements.each do |statement|
unless statement.valid?
diff --git a/lib/gitlab/ci/config/entry/retry.rb b/lib/gitlab/ci/config/entry/retry.rb
index e9cbcb31e21..737ad96db15 100644
--- a/lib/gitlab/ci/config/entry/retry.rb
+++ b/lib/gitlab/ci/config/entry/retry.rb
@@ -8,26 +8,26 @@ module Gitlab
# Entry that represents a retry config for a job.
#
class Retry < ::Gitlab::Config::Entry::Simplifiable
- strategy :SimpleRetry, if: -> (config) { config.is_a?(Integer) }
- strategy :FullRetry, if: -> (config) { config.is_a?(Hash) }
+ strategy :SimpleRetry, if: ->(config) { config.is_a?(Integer) }
+ strategy :FullRetry, if: ->(config) { config.is_a?(Hash) }
class SimpleRetry < ::Gitlab::Config::Entry::Node
include ::Gitlab::Config::Entry::Validatable
validations do
- validates :config, numericality: { only_integer: true,
- greater_than_or_equal_to: 0,
- less_than_or_equal_to: 2 }
+ validates :config, numericality: {only_integer: true,
+ greater_than_or_equal_to: 0,
+ less_than_or_equal_to: 2,}
end
def value
{
- max: config
+ max: config,
}
end
def location
- 'retry'
+ "retry"
end
end
@@ -42,22 +42,22 @@ module Gitlab
validates :config, allowed_keys: ALLOWED_KEYS
with_options allow_nil: true do
- validates :max, numericality: { only_integer: true,
- greater_than_or_equal_to: 0,
- less_than_or_equal_to: 2 }
+ validates :max, numericality: {only_integer: true,
+ greater_than_or_equal_to: 0,
+ less_than_or_equal_to: 2,}
validates :when, array_of_strings_or_string: true
validates :when,
- allowed_array_values: { in: FullRetry.possible_retry_when_values },
- if: -> (config) { config.when.is_a?(Array) }
+ allowed_array_values: {in: FullRetry.possible_retry_when_values},
+ if: ->(config) { config.when.is_a?(Array) }
validates :when,
- inclusion: { in: FullRetry.possible_retry_when_values },
- if: -> (config) { config.when.is_a?(String) }
+ inclusion: {in: FullRetry.possible_retry_when_values},
+ if: ->(config) { config.when.is_a?(String) }
end
end
def self.possible_retry_when_values
- @possible_retry_when_values ||= ::Ci::Build.failure_reasons.keys.map(&:to_s) + ['always']
+ @possible_retry_when_values ||= ::Ci::Build.failure_reasons.keys.map(&:to_s) + ["always"]
end
def value
@@ -69,7 +69,7 @@ module Gitlab
end
def location
- 'retry'
+ "retry"
end
end
@@ -79,7 +79,7 @@ module Gitlab
end
def location
- 'retry config'
+ "retry config"
end
end
end
diff --git a/lib/gitlab/ci/config/entry/stage.rb b/lib/gitlab/ci/config/entry/stage.rb
index d6d576a3139..f18b1740866 100644
--- a/lib/gitlab/ci/config/entry/stage.rb
+++ b/lib/gitlab/ci/config/entry/stage.rb
@@ -15,7 +15,7 @@ module Gitlab
end
def self.default
- 'test'
+ "test"
end
end
end
diff --git a/lib/gitlab/ci/config/extendable/entry.rb b/lib/gitlab/ci/config/extendable/entry.rb
index 7793db09d33..3d660c73114 100644
--- a/lib/gitlab/ci/config/extendable/entry.rb
+++ b/lib/gitlab/ci/config/extendable/entry.rb
@@ -19,7 +19,7 @@ module Gitlab
@parent = parent
unless @context.key?(@key)
- raise StandardError, 'Invalid entry key!'
+ raise StandardError, "Invalid entry key!"
end
end
@@ -50,22 +50,22 @@ module Gitlab
if unknown_extension?
raise Entry::InvalidExtensionError,
- "#{key}: unknown key in `extends`"
+ "#{key}: unknown key in `extends`"
end
if invalid_base?
raise Entry::InvalidExtensionError,
- "#{key}: invalid base hash in `extends`"
+ "#{key}: invalid base hash in `extends`"
end
if nesting_too_deep?
raise Entry::NestingTooDeepError,
- "#{key}: nesting too deep in `extends`"
+ "#{key}: nesting too deep in `extends`"
end
if circular_dependency?
raise Entry::CircularDependencyError,
- "#{key}: circular dependency detected in `extends`"
+ "#{key}: circular dependency detected in `extends`"
end
@context[key] = base_hash!.deep_merge(value)
diff --git a/lib/gitlab/ci/config/external/file/base.rb b/lib/gitlab/ci/config/external/file/base.rb
index a747886093c..797d5b805ca 100644
--- a/lib/gitlab/ci/config/external/file/base.rb
+++ b/lib/gitlab/ci/config/external/file/base.rb
@@ -39,7 +39,7 @@ module Gitlab
end
def content
- raise NotImplementedError, 'subclass must implement fetching raw content'
+ raise NotImplementedError, "subclass must implement fetching raw content"
end
def to_hash
diff --git a/lib/gitlab/ci/config/external/file/project.rb b/lib/gitlab/ci/config/external/file/project.rb
index e75540dbe5a..089e6cc3628 100644
--- a/lib/gitlab/ci/config/external/file/project.rb
+++ b/lib/gitlab/ci/config/external/file/project.rb
@@ -13,7 +13,7 @@ module Gitlab
def initialize(params, context = {})
@location = params[:file]
@project_name = params[:project]
- @ref_name = params[:ref] || 'HEAD'
+ @ref_name = params[:ref] || "HEAD"
super
end
diff --git a/lib/gitlab/ci/config/external/file/template.rb b/lib/gitlab/ci/config/external/file/template.rb
index 54f4cf74c4d..af3f7fd88bd 100644
--- a/lib/gitlab/ci/config/external/file/template.rb
+++ b/lib/gitlab/ci/config/external/file/template.rb
@@ -8,7 +8,7 @@ module Gitlab
class Template < Base
attr_reader :location, :project
- SUFFIX = '.gitlab-ci.yml'.freeze
+ SUFFIX = ".gitlab-ci.yml"
def initialize(params, context)
@location = params[:template]
diff --git a/lib/gitlab/ci/config/external/mapper.rb b/lib/gitlab/ci/config/external/mapper.rb
index 108bfd5eb43..2008008def5 100644
--- a/lib/gitlab/ci/config/external/mapper.rb
+++ b/lib/gitlab/ci/config/external/mapper.rb
@@ -11,7 +11,7 @@ module Gitlab
External::File::Remote,
External::File::Template,
External::File::Local,
- External::File::Project
+ External::File::Project,
].freeze
AmbigiousSpecificationError = Class.new(StandardError)
@@ -45,16 +45,16 @@ module Gitlab
def normalize_location_string(location)
if ::Gitlab::UrlSanitizer.valid?(location)
- { remote: location }
+ {remote: location}
else
- { local: location }
+ {local: location}
end
end
def select_first_matching(location)
- matching = FILE_CLASSES.map do |file_class|
+ matching = FILE_CLASSES.map { |file_class|
file_class.new(location, context)
- end.select(&:matching?)
+ }.select(&:matching?)
raise AmbigiousSpecificationError, "Include `#{location.to_json}` needs to match exactly one accessor!" unless matching.one?
diff --git a/lib/gitlab/ci/cron_parser.rb b/lib/gitlab/ci/cron_parser.rb
index 94f4a4e36c9..e46f0ae4d4a 100644
--- a/lib/gitlab/ci/cron_parser.rb
+++ b/lib/gitlab/ci/cron_parser.rb
@@ -3,10 +3,10 @@
module Gitlab
module Ci
class CronParser
- VALID_SYNTAX_SAMPLE_TIME_ZONE = 'UTC'.freeze
- VALID_SYNTAX_SAMPLE_CRON = '* * * * *'.freeze
+ VALID_SYNTAX_SAMPLE_TIME_ZONE = "UTC"
+ VALID_SYNTAX_SAMPLE_CRON = "* * * * *"
- def initialize(cron, cron_timezone = 'UTC')
+ def initialize(cron, cron_timezone = "UTC")
@cron = cron
@cron_timezone = timezone_name(cron_timezone)
end
diff --git a/lib/gitlab/ci/mask_secret.rb b/lib/gitlab/ci/mask_secret.rb
index 58d55b1bd6f..5ddbf9a2460 100644
--- a/lib/gitlab/ci/mask_secret.rb
+++ b/lib/gitlab/ci/mask_secret.rb
@@ -8,7 +8,7 @@ module Gitlab
# We assume 'value' must be mutable, given
# that frozen string is enabled.
- value.gsub!(token, 'x' * token.length)
+ value.gsub!(token, "x" * token.length)
value
end
end
diff --git a/lib/gitlab/ci/model.rb b/lib/gitlab/ci/model.rb
index fbdb84c0522..89a50bf4a97 100644
--- a/lib/gitlab/ci/model.rb
+++ b/lib/gitlab/ci/model.rb
@@ -8,7 +8,7 @@ module Gitlab
end
def model_name
- @model_name ||= ActiveModel::Name.new(self, nil, self.name.split("::").last)
+ @model_name ||= ActiveModel::Name.new(self, nil, name.split("::").last)
end
end
end
diff --git a/lib/gitlab/ci/parsers.rb b/lib/gitlab/ci/parsers.rb
index eb63e6c8363..c5666e83201 100644
--- a/lib/gitlab/ci/parsers.rb
+++ b/lib/gitlab/ci/parsers.rb
@@ -7,7 +7,7 @@ module Gitlab
def self.parsers
{
- junit: ::Gitlab::Ci::Parsers::Test::Junit
+ junit: ::Gitlab::Ci::Parsers::Test::Junit,
}
end
diff --git a/lib/gitlab/ci/parsers/test/junit.rb b/lib/gitlab/ci/parsers/test/junit.rb
index dca60eabc1c..e5a59b85dad 100644
--- a/lib/gitlab/ci/parsers/test/junit.rb
+++ b/lib/gitlab/ci/parsers/test/junit.rb
@@ -29,13 +29,13 @@ module Gitlab
next unless node.is_a?(Hash)
# we allow only one top-level 'testsuites'
- all_cases(node['testsuites'], root, &blk) unless parent
+ all_cases(node["testsuites"], root, &blk) unless parent
# we require at least one level of testsuites or testsuite
- each_case(node['testcase'], &blk) if parent
+ each_case(node["testcase"], &blk) if parent
# we allow multiple nested 'testsuite' (eg. PHPUnit)
- all_cases(node['testsuite'], root, &blk)
+ all_cases(node["testsuite"], root, &blk)
end
end
@@ -46,19 +46,19 @@ module Gitlab
end
def create_test_case(data)
- if data['failure']
+ if data["failure"]
status = ::Gitlab::Ci::Reports::TestCase::STATUS_FAILED
- system_output = data['failure']
+ system_output = data["failure"]
else
status = ::Gitlab::Ci::Reports::TestCase::STATUS_SUCCESS
system_output = nil
end
::Gitlab::Ci::Reports::TestCase.new(
- classname: data['classname'],
- name: data['name'],
- file: data['file'],
- execution_time: data['time'],
+ classname: data["classname"],
+ name: data["name"],
+ file: data["file"],
+ execution_time: data["time"],
status: status,
system_output: system_output
)
diff --git a/lib/gitlab/ci/pipeline/chain/command.rb b/lib/gitlab/ci/pipeline/chain/command.rb
index 7b77e86feae..c36986a5d72 100644
--- a/lib/gitlab/ci/pipeline/chain/command.rb
+++ b/lib/gitlab/ci/pipeline/chain/command.rb
@@ -12,7 +12,7 @@ module Gitlab
:ignore_skip_ci, :save_incompleted,
:seeds_block, :variables_attributes, :push_options,
:chat_data
- ) do
+ ) {
include Gitlab::Utils::StrongMemoize
def initialize(**params)
@@ -64,7 +64,7 @@ module Gitlab
project.repository.ambiguous_ref?(origin_ref)
end
end
- end
+ }
end
end
end
diff --git a/lib/gitlab/ci/pipeline/chain/populate.rb b/lib/gitlab/ci/pipeline/chain/populate.rb
index 0405292a25b..330a6567430 100644
--- a/lib/gitlab/ci/pipeline/chain/populate.rb
+++ b/lib/gitlab/ci/pipeline/chain/populate.rb
@@ -30,11 +30,11 @@ module Gitlab
end
if pipeline.stages.none?
- return error('No stages / jobs for this pipeline.')
+ return error("No stages / jobs for this pipeline.")
end
if pipeline.invalid?
- return error('Failed to build the pipeline!')
+ return error("Failed to build the pipeline!")
end
raise Populate::PopulateError if pipeline.persisted?
diff --git a/lib/gitlab/ci/pipeline/chain/skip.rb b/lib/gitlab/ci/pipeline/chain/skip.rb
index 79bbcc1ed1e..328336097c2 100644
--- a/lib/gitlab/ci/pipeline/chain/skip.rb
+++ b/lib/gitlab/ci/pipeline/chain/skip.rb
@@ -8,7 +8,7 @@ module Gitlab
include ::Gitlab::Utils::StrongMemoize
SKIP_PATTERN = /\[(ci[ _-]skip|skip[ _-]ci)\]/i
- SKIP_PUSH_OPTION = 'ci.skip'
+ SKIP_PUSH_OPTION = "ci.skip"
def perform!
if skipped?
diff --git a/lib/gitlab/ci/pipeline/chain/validate/abilities.rb b/lib/gitlab/ci/pipeline/chain/validate/abilities.rb
index ebd7e6e8289..61ed7959783 100644
--- a/lib/gitlab/ci/pipeline/chain/validate/abilities.rb
+++ b/lib/gitlab/ci/pipeline/chain/validate/abilities.rb
@@ -11,14 +11,14 @@ module Gitlab
def perform!
unless project.builds_enabled?
- return error('Pipelines are disabled!')
+ return error("Pipelines are disabled!")
end
unless allowed_to_trigger_pipeline?
if can?(current_user, :create_pipeline, project)
return error("Insufficient permissions for protected ref '#{command.ref}'")
else
- return error('Insufficient permissions to create a new pipeline')
+ return error("Insufficient permissions to create a new pipeline")
end
end
end
diff --git a/lib/gitlab/ci/pipeline/chain/validate/repository.rb b/lib/gitlab/ci/pipeline/chain/validate/repository.rb
index 9c6c2bc8e25..b8cfc81e531 100644
--- a/lib/gitlab/ci/pipeline/chain/validate/repository.rb
+++ b/lib/gitlab/ci/pipeline/chain/validate/repository.rb
@@ -10,15 +10,15 @@ module Gitlab
def perform!
unless @command.branch_exists? || @command.tag_exists?
- return error('Reference not found')
+ return error("Reference not found")
end
unless @command.sha
- return error('Commit not found')
+ return error("Commit not found")
end
if @command.ambiguous_ref?
- return error('Ref is ambiguous')
+ return error("Ref is ambiguous")
end
end
diff --git a/lib/gitlab/ci/pipeline/duration.rb b/lib/gitlab/ci/pipeline/duration.rb
index de24bbf688b..a952f6bdc55 100644
--- a/lib/gitlab/ci/pipeline/duration.rb
+++ b/lib/gitlab/ci/pipeline/duration.rb
@@ -82,11 +82,11 @@ module Gitlab
module Duration
extend self
- Period = Struct.new(:first, :last) do
+ Period = Struct.new(:first, :last) {
def duration
last - first
end
- end
+ }
# rubocop: disable CodeReuse/ActiveRecord
def from_pipeline(pipeline)
@@ -101,9 +101,9 @@ module Gitlab
def from_builds(builds)
now = Time.now
- periods = builds.map do |b|
+ periods = builds.map { |b|
Period.new(b.started_at, b.finished_at || now)
- end
+ }
from_periods(periods)
end
diff --git a/lib/gitlab/ci/pipeline/expression/lexeme/null.rb b/lib/gitlab/ci/pipeline/expression/lexeme/null.rb
index be7258c201a..99b70e17b9b 100644
--- a/lib/gitlab/ci/pipeline/expression/lexeme/null.rb
+++ b/lib/gitlab/ci/pipeline/expression/lexeme/null.rb
@@ -17,7 +17,7 @@ module Gitlab
end
def self.build(_value)
- self.new
+ new
end
end
end
diff --git a/lib/gitlab/ci/pipeline/expression/lexeme/pattern.rb b/lib/gitlab/ci/pipeline/expression/lexeme/pattern.rb
index d7e6dacf068..27c4aecb3f1 100644
--- a/lib/gitlab/ci/pipeline/expression/lexeme/pattern.rb
+++ b/lib/gitlab/ci/pipeline/expression/lexeme/pattern.rb
@@ -5,7 +5,7 @@ module Gitlab
module Pipeline
module Expression
module Lexeme
- require_dependency 're2'
+ require_dependency "re2"
class Pattern < Lexeme::Value
PATTERN = %r{^/.+/[ismU]*$}.freeze
@@ -14,14 +14,14 @@ module Gitlab
@value = regexp
unless Gitlab::UntrustedRegexp.valid?(@value)
- raise Lexer::SyntaxError, 'Invalid regular expression!'
+ raise Lexer::SyntaxError, "Invalid regular expression!"
end
end
def evaluate(variables = {})
Gitlab::UntrustedRegexp.fabricate(@value)
rescue RegexpError
- raise Expression::RuntimeError, 'Invalid regular expression!'
+ raise Expression::RuntimeError, "Invalid regular expression!"
end
def self.build(string)
diff --git a/lib/gitlab/ci/pipeline/expression/lexer.rb b/lib/gitlab/ci/pipeline/expression/lexer.rb
index f26542361a2..dc1b020b311 100644
--- a/lib/gitlab/ci/pipeline/expression/lexer.rb
+++ b/lib/gitlab/ci/pipeline/expression/lexer.rb
@@ -15,7 +15,7 @@ module Gitlab
Expression::Lexeme::Pattern,
Expression::Lexeme::Null,
Expression::Lexeme::Equals,
- Expression::Lexeme::Matches
+ Expression::Lexeme::Matches,
].freeze
MAX_TOKENS = 100
@@ -43,18 +43,18 @@ module Gitlab
return tokens if @scanner.eos?
- lexeme = LEXEMES.find do |type|
+ lexeme = LEXEMES.find { |type|
type.scan(@scanner).tap do |token|
tokens.push(token) if token.present?
end
- end
+ }
unless lexeme.present?
- raise Lexer::SyntaxError, 'Unknown lexeme found!'
+ raise Lexer::SyntaxError, "Unknown lexeme found!"
end
end
- raise Lexer::SyntaxError, 'Too many tokens!'
+ raise Lexer::SyntaxError, "Too many tokens!"
end
end
end
diff --git a/lib/gitlab/ci/pipeline/expression/statement.rb b/lib/gitlab/ci/pipeline/expression/statement.rb
index b03611f756e..d95cce4dc00 100644
--- a/lib/gitlab/ci/pipeline/expression/statement.rb
+++ b/lib/gitlab/ci/pipeline/expression/statement.rb
@@ -14,7 +14,7 @@ module Gitlab
%w[variable equals null],
%w[string equals variable],
%w[null equals variable],
- %w[variable matches pattern]
+ %w[variable matches pattern],
].freeze
def initialize(statement, variables = {})
@@ -26,7 +26,7 @@ module Gitlab
raise StatementError if @lexer.lexemes.empty?
unless GRAMMAR.find { |syntax| syntax == @lexer.lexemes }
- raise StatementError, 'Unknown pipeline expression!'
+ raise StatementError, "Unknown pipeline expression!"
end
Expression::Parser.new(@lexer.tokens).tree
diff --git a/lib/gitlab/ci/pipeline/preloader.rb b/lib/gitlab/ci/pipeline/preloader.rb
index db0a1ea4dab..d5f1e434d12 100644
--- a/lib/gitlab/ci/pipeline/preloader.rb
+++ b/lib/gitlab/ci/pipeline/preloader.rb
@@ -15,7 +15,7 @@ module Gitlab
pipelines.each(&:commit)
pipelines.each do |pipeline|
- self.new(pipeline).tap do |preloader|
+ new(pipeline).tap do |preloader|
preloader.preload_commit_authors
preloader.preload_pipeline_warnings
preloader.preload_stages_warnings
diff --git a/lib/gitlab/ci/pipeline/seed/stage.rb b/lib/gitlab/ci/pipeline/seed/stage.rb
index 9c15064756a..fe1f441f69f 100644
--- a/lib/gitlab/ci/pipeline/seed/stage.rb
+++ b/lib/gitlab/ci/pipeline/seed/stage.rb
@@ -14,16 +14,16 @@ module Gitlab
@pipeline = pipeline
@attributes = attributes
- @builds = attributes.fetch(:builds).map do |attributes|
+ @builds = attributes.fetch(:builds).map { |attributes|
Seed::Build.new(@pipeline, attributes)
- end
+ }
end
def attributes
- { name: @attributes.fetch(:name),
- position: @attributes.fetch(:index),
- pipeline: @pipeline,
- project: @pipeline.project }
+ {name: @attributes.fetch(:name),
+ position: @attributes.fetch(:index),
+ pipeline: @pipeline,
+ project: @pipeline.project,}
end
def seeds
diff --git a/lib/gitlab/ci/reports/test_case.rb b/lib/gitlab/ci/reports/test_case.rb
index 292e273a03a..dccd716f6df 100644
--- a/lib/gitlab/ci/reports/test_case.rb
+++ b/lib/gitlab/ci/reports/test_case.rb
@@ -4,10 +4,10 @@ module Gitlab
module Ci
module Reports
class TestCase
- STATUS_SUCCESS = 'success'.freeze
- STATUS_FAILED = 'failed'.freeze
- STATUS_SKIPPED = 'skipped'.freeze
- STATUS_ERROR = 'error'.freeze
+ STATUS_SUCCESS = "success"
+ STATUS_FAILED = "failed"
+ STATUS_SKIPPED = "skipped"
+ STATUS_ERROR = "error"
STATUS_TYPES = [STATUS_SUCCESS, STATUS_FAILED, STATUS_SKIPPED, STATUS_ERROR].freeze
attr_reader :name, :classname, :execution_time, :status, :file, :system_output, :stack_trace, :key
@@ -26,7 +26,7 @@ module Gitlab
private
def sanitize_key_name(key)
- key.gsub(/[^0-9A-Za-z]/, '-')
+ key.gsub(/[^0-9A-Za-z]/, "-")
end
end
end
diff --git a/lib/gitlab/ci/reports/test_reports_comparer.rb b/lib/gitlab/ci/reports/test_reports_comparer.rb
index 11810bdc0a8..c644dff5569 100644
--- a/lib/gitlab/ci/reports/test_reports_comparer.rb
+++ b/lib/gitlab/ci/reports/test_reports_comparer.rb
@@ -29,7 +29,7 @@ module Gitlab
end
end
- %w(total_count resolved_count failed_count).each do |method|
+ %w[total_count resolved_count failed_count].each do |method|
define_method(method) do
# rubocop: disable CodeReuse/ActiveRecord
suite_comparers.sum { |suite| suite.public_send(method) } # rubocop:disable GitlabSecurity/PublicSend
diff --git a/lib/gitlab/ci/reports/test_suite.rb b/lib/gitlab/ci/reports/test_suite.rb
index b0391160c15..df3c98bb54e 100644
--- a/lib/gitlab/ci/reports/test_suite.rb
+++ b/lib/gitlab/ci/reports/test_suite.rb
@@ -38,7 +38,7 @@ module Gitlab
end
TestCase::STATUS_TYPES.each do |status_type|
- define_method("#{status_type}") do
+ define_method(status_type.to_s) do
test_cases[status_type] || {}
end
diff --git a/lib/gitlab/ci/reports/test_suite_comparer.rb b/lib/gitlab/ci/reports/test_suite_comparer.rb
index 9cb7db5934c..fb470d000b7 100644
--- a/lib/gitlab/ci/reports/test_suite_comparer.rb
+++ b/lib/gitlab/ci/reports/test_suite_comparer.rb
@@ -16,25 +16,25 @@ module Gitlab
def new_failures
strong_memoize(:new_failures) do
- head_suite.failed.reject do |key, _|
+ head_suite.failed.reject { |key, _|
base_suite.failed.include?(key)
- end.values
+ }.values
end
end
def existing_failures
strong_memoize(:existing_failures) do
- head_suite.failed.select do |key, _|
+ head_suite.failed.select { |key, _|
base_suite.failed.include?(key)
- end.values
+ }.values
end
end
def resolved_failures
strong_memoize(:resolved_failures) do
- head_suite.success.select do |key, _|
+ head_suite.success.select { |key, _|
base_suite.failed.include?(key)
- end.values
+ }.values
end
end
diff --git a/lib/gitlab/ci/status/build/cancelable.rb b/lib/gitlab/ci/status/build/cancelable.rb
index 43fb5cdbbe6..ca6b59bbe23 100644
--- a/lib/gitlab/ci/status/build/cancelable.rb
+++ b/lib/gitlab/ci/status/build/cancelable.rb
@@ -10,7 +10,7 @@ module Gitlab
end
def action_icon
- 'cancel'
+ "cancel"
end
def action_path
@@ -22,11 +22,11 @@ module Gitlab
end
def action_title
- 'Cancel'
+ "Cancel"
end
def action_button_title
- _('Cancel this job')
+ _("Cancel this job")
end
def self.matches?(build, user)
diff --git a/lib/gitlab/ci/status/build/canceled.rb b/lib/gitlab/ci/status/build/canceled.rb
index 0518b9e673d..1bd40119e2c 100644
--- a/lib/gitlab/ci/status/build/canceled.rb
+++ b/lib/gitlab/ci/status/build/canceled.rb
@@ -7,9 +7,9 @@ module Gitlab
class Canceled < Status::Extended
def illustration
{
- image: 'illustrations/canceled-job_empty.svg',
- size: 'svg-430',
- title: _('This job has been canceled')
+ image: "illustrations/canceled-job_empty.svg",
+ size: "svg-430",
+ title: _("This job has been canceled"),
}
end
diff --git a/lib/gitlab/ci/status/build/common.rb b/lib/gitlab/ci/status/build/common.rb
index 6a75ec5c37f..24d0d8d4aab 100644
--- a/lib/gitlab/ci/status/build/common.rb
+++ b/lib/gitlab/ci/status/build/common.rb
@@ -7,9 +7,9 @@ module Gitlab
module Common
def illustration
{
- image: 'illustrations/skipped-job_empty.svg',
- size: 'svg-430',
- title: _('This job does not have a trace.')
+ image: "illustrations/skipped-job_empty.svg",
+ size: "svg-430",
+ title: _("This job does not have a trace."),
}
end
diff --git a/lib/gitlab/ci/status/build/created.rb b/lib/gitlab/ci/status/build/created.rb
index 780fea23123..dd4d2793b1e 100644
--- a/lib/gitlab/ci/status/build/created.rb
+++ b/lib/gitlab/ci/status/build/created.rb
@@ -7,10 +7,10 @@ module Gitlab
class Created < Status::Extended
def illustration
{
- image: 'illustrations/job_not_triggered.svg',
- size: 'svg-306',
- title: _('This job has not been triggered yet'),
- content: _('This job depends on upstream jobs that need to succeed in order for this job to be triggered')
+ image: "illustrations/job_not_triggered.svg",
+ size: "svg-306",
+ title: _("This job has not been triggered yet"),
+ content: _("This job depends on upstream jobs that need to succeed in order for this job to be triggered"),
}
end
diff --git a/lib/gitlab/ci/status/build/erased.rb b/lib/gitlab/ci/status/build/erased.rb
index d74cfc1ee77..82c107f8cf0 100644
--- a/lib/gitlab/ci/status/build/erased.rb
+++ b/lib/gitlab/ci/status/build/erased.rb
@@ -7,9 +7,9 @@ module Gitlab
class Erased < Status::Extended
def illustration
{
- image: 'illustrations/erased-log_empty.svg',
- size: 'svg-430',
- title: _('Job has been erased')
+ image: "illustrations/erased-log_empty.svg",
+ size: "svg-430",
+ title: _("Job has been erased"),
}
end
diff --git a/lib/gitlab/ci/status/build/factory.rb b/lib/gitlab/ci/status/build/factory.rb
index 6e4bfe23f2b..806caf4d091 100644
--- a/lib/gitlab/ci/status/build/factory.rb
+++ b/lib/gitlab/ci/status/build/factory.rb
@@ -12,16 +12,16 @@ module Gitlab
Status::Build::Canceled,
Status::Build::Created,
Status::Build::Pending,
- Status::Build::Skipped],
+ Status::Build::Skipped,],
[Status::Build::Cancelable,
- Status::Build::Retryable],
+ Status::Build::Retryable,],
[Status::Build::Failed],
[Status::Build::FailedAllowed,
Status::Build::Unschedule,
Status::Build::Play,
- Status::Build::Stop],
+ Status::Build::Stop,],
[Status::Build::Action],
- [Status::Build::Retried]]
+ [Status::Build::Retried],]
end
def self.common_helpers
diff --git a/lib/gitlab/ci/status/build/failed.rb b/lib/gitlab/ci/status/build/failed.rb
index d40454df737..3c0ff7ae739 100644
--- a/lib/gitlab/ci/status/build/failed.rb
+++ b/lib/gitlab/ci/status/build/failed.rb
@@ -6,16 +6,16 @@ module Gitlab
module Build
class Failed < Status::Extended
REASONS = {
- unknown_failure: 'unknown failure',
- script_failure: 'script failure',
- api_failure: 'API failure',
- stuck_or_timeout_failure: 'stuck or timeout failure',
- runner_system_failure: 'runner system failure',
- missing_dependency_failure: 'missing dependency failure',
- runner_unsupported: 'unsupported runner',
- stale_schedule: 'stale schedule',
- job_execution_timeout: 'job execution timeout',
- archived_failure: 'archived failure'
+ unknown_failure: "unknown failure",
+ script_failure: "script failure",
+ api_failure: "API failure",
+ stuck_or_timeout_failure: "stuck or timeout failure",
+ runner_system_failure: "runner system failure",
+ missing_dependency_failure: "missing dependency failure",
+ runner_unsupported: "unsupported runner",
+ stale_schedule: "stale schedule",
+ job_execution_timeout: "job execution timeout",
+ archived_failure: "archived failure",
}.freeze
private_constant :REASONS
@@ -39,7 +39,7 @@ module Gitlab
private
def base_message
- "#{s_('CiStatusLabel|failed')} #{description}"
+ "#{s_("CiStatusLabel|failed")} #{description}"
end
def description
diff --git a/lib/gitlab/ci/status/build/failed_allowed.rb b/lib/gitlab/ci/status/build/failed_allowed.rb
index d7570fdd3e2..ab8e0e1b31d 100644
--- a/lib/gitlab/ci/status/build/failed_allowed.rb
+++ b/lib/gitlab/ci/status/build/failed_allowed.rb
@@ -10,11 +10,11 @@ module Gitlab
end
def icon
- 'status_warning'
+ "status_warning"
end
def group
- 'failed_with_warnings'
+ "failed_with_warnings"
end
def status_tooltip
diff --git a/lib/gitlab/ci/status/build/manual.rb b/lib/gitlab/ci/status/build/manual.rb
index d01b09f1398..f872cb406f1 100644
--- a/lib/gitlab/ci/status/build/manual.rb
+++ b/lib/gitlab/ci/status/build/manual.rb
@@ -7,10 +7,10 @@ module Gitlab
class Manual < Status::Extended
def illustration
{
- image: 'illustrations/manual_action.svg',
- size: 'svg-394',
- title: _('This job requires a manual action'),
- content: _('This job depends on a user to trigger its process. Often they are used to deploy code to production environments')
+ image: "illustrations/manual_action.svg",
+ size: "svg-394",
+ title: _("This job requires a manual action"),
+ content: _("This job depends on a user to trigger its process. Often they are used to deploy code to production environments"),
}
end
diff --git a/lib/gitlab/ci/status/build/pending.rb b/lib/gitlab/ci/status/build/pending.rb
index 95f668295dd..50ad4854a66 100644
--- a/lib/gitlab/ci/status/build/pending.rb
+++ b/lib/gitlab/ci/status/build/pending.rb
@@ -7,10 +7,10 @@ module Gitlab
class Pending < Status::Extended
def illustration
{
- image: 'illustrations/pending_job_empty.svg',
- size: 'svg-430',
- title: _('This job has not started yet'),
- content: _('This job is in pending state and is waiting to be picked by a runner')
+ image: "illustrations/pending_job_empty.svg",
+ size: "svg-430",
+ title: _("This job has not started yet"),
+ content: _("This job is in pending state and is waiting to be picked by a runner"),
}
end
diff --git a/lib/gitlab/ci/status/build/play.rb b/lib/gitlab/ci/status/build/play.rb
index c66b8ca5654..780808af129 100644
--- a/lib/gitlab/ci/status/build/play.rb
+++ b/lib/gitlab/ci/status/build/play.rb
@@ -6,7 +6,7 @@ module Gitlab
module Build
class Play < Status::Extended
def label
- 'manual play action'
+ "manual play action"
end
def has_action?
@@ -14,15 +14,15 @@ module Gitlab
end
def action_icon
- 'play'
+ "play"
end
def action_title
- 'Play'
+ "Play"
end
def action_button_title
- _('Trigger this manual action')
+ _("Trigger this manual action")
end
def action_path
diff --git a/lib/gitlab/ci/status/build/retryable.rb b/lib/gitlab/ci/status/build/retryable.rb
index eb6b3f21604..c2ee793cfbe 100644
--- a/lib/gitlab/ci/status/build/retryable.rb
+++ b/lib/gitlab/ci/status/build/retryable.rb
@@ -10,15 +10,15 @@ module Gitlab
end
def action_icon
- 'retry'
+ "retry"
end
def action_title
- 'Retry'
+ "Retry"
end
def action_button_title
- _('Retry this job')
+ _("Retry this job")
end
def action_path
diff --git a/lib/gitlab/ci/status/build/scheduled.rb b/lib/gitlab/ci/status/build/scheduled.rb
index 0a09dbe5f42..386a34d6343 100644
--- a/lib/gitlab/ci/status/build/scheduled.rb
+++ b/lib/gitlab/ci/status/build/scheduled.rb
@@ -7,13 +7,13 @@ module Gitlab
class Scheduled < Status::Extended
def illustration
{
- image: 'illustrations/illustrations_scheduled-job_countdown.svg',
- size: 'svg-394',
+ image: "illustrations/illustrations_scheduled-job_countdown.svg",
+ size: "svg-394",
title: _("This is a delayed job to run in %{remainingTime}"),
content: _("This job will automatically run after its timer finishes. " \
"Often they are used for incremental roll-out deploys " \
"to production environments. When unscheduled it converts " \
- "into a manual action.")
+ "into a manual action."),
}
end
diff --git a/lib/gitlab/ci/status/build/skipped.rb b/lib/gitlab/ci/status/build/skipped.rb
index 4fe2f7b3114..451b30f6391 100644
--- a/lib/gitlab/ci/status/build/skipped.rb
+++ b/lib/gitlab/ci/status/build/skipped.rb
@@ -7,9 +7,9 @@ module Gitlab
class Skipped < Status::Extended
def illustration
{
- image: 'illustrations/skipped-job_empty.svg',
- size: 'svg-430',
- title: _('This job has been skipped')
+ image: "illustrations/skipped-job_empty.svg",
+ size: "svg-430",
+ title: _("This job has been skipped"),
}
end
diff --git a/lib/gitlab/ci/status/build/stop.rb b/lib/gitlab/ci/status/build/stop.rb
index a620e7ad126..823649b785d 100644
--- a/lib/gitlab/ci/status/build/stop.rb
+++ b/lib/gitlab/ci/status/build/stop.rb
@@ -6,7 +6,7 @@ module Gitlab
module Build
class Stop < Status::Extended
def label
- 'manual stop action'
+ "manual stop action"
end
def has_action?
@@ -14,15 +14,15 @@ module Gitlab
end
def action_icon
- 'stop'
+ "stop"
end
def action_title
- 'Stop'
+ "Stop"
end
def action_button_title
- _('Stop this environment')
+ _("Stop this environment")
end
def action_path
diff --git a/lib/gitlab/ci/status/build/unschedule.rb b/lib/gitlab/ci/status/build/unschedule.rb
index 9110839cb55..e603c9ee0a5 100644
--- a/lib/gitlab/ci/status/build/unschedule.rb
+++ b/lib/gitlab/ci/status/build/unschedule.rb
@@ -6,7 +6,7 @@ module Gitlab
module Build
class Unschedule < Status::Extended
def label
- 'unschedule action'
+ "unschedule action"
end
def has_action?
@@ -14,15 +14,15 @@ module Gitlab
end
def action_icon
- 'time-out'
+ "time-out"
end
def action_title
- 'Unschedule'
+ "Unschedule"
end
def action_button_title
- _('Unschedule job')
+ _("Unschedule job")
end
def action_path
diff --git a/lib/gitlab/ci/status/canceled.rb b/lib/gitlab/ci/status/canceled.rb
index 07f37732023..0abf5acdd52 100644
--- a/lib/gitlab/ci/status/canceled.rb
+++ b/lib/gitlab/ci/status/canceled.rb
@@ -5,19 +5,19 @@ module Gitlab
module Status
class Canceled < Status::Core
def text
- s_('CiStatusText|canceled')
+ s_("CiStatusText|canceled")
end
def label
- s_('CiStatusLabel|canceled')
+ s_("CiStatusLabel|canceled")
end
def icon
- 'status_canceled'
+ "status_canceled"
end
def favicon
- 'favicon_status_canceled'
+ "favicon_status_canceled"
end
end
end
diff --git a/lib/gitlab/ci/status/created.rb b/lib/gitlab/ci/status/created.rb
index fface4bb97b..4fb6ad6ed97 100644
--- a/lib/gitlab/ci/status/created.rb
+++ b/lib/gitlab/ci/status/created.rb
@@ -5,19 +5,19 @@ module Gitlab
module Status
class Created < Status::Core
def text
- s_('CiStatusText|created')
+ s_("CiStatusText|created")
end
def label
- s_('CiStatusLabel|created')
+ s_("CiStatusLabel|created")
end
def icon
- 'status_created'
+ "status_created"
end
def favicon
- 'favicon_status_created'
+ "favicon_status_created"
end
end
end
diff --git a/lib/gitlab/ci/status/factory.rb b/lib/gitlab/ci/status/factory.rb
index 3446644eff8..654515bd509 100644
--- a/lib/gitlab/ci/status/factory.rb
+++ b/lib/gitlab/ci/status/factory.rb
@@ -34,9 +34,9 @@ module Gitlab
def extended_statuses
return @extended_statuses if defined?(@extended_statuses)
- groups = self.class.extended_statuses.map do |group|
+ groups = self.class.extended_statuses.map { |group|
Array(group).find { |status| status.matches?(@subject, @user) }
- end
+ }
@extended_statuses = groups.flatten.compact
end
diff --git a/lib/gitlab/ci/status/failed.rb b/lib/gitlab/ci/status/failed.rb
index 770ed7d4d5a..f5a67778a0c 100644
--- a/lib/gitlab/ci/status/failed.rb
+++ b/lib/gitlab/ci/status/failed.rb
@@ -5,19 +5,19 @@ module Gitlab
module Status
class Failed < Status::Core
def text
- s_('CiStatusText|failed')
+ s_("CiStatusText|failed")
end
def label
- s_('CiStatusLabel|failed')
+ s_("CiStatusLabel|failed")
end
def icon
- 'status_failed'
+ "status_failed"
end
def favicon
- 'favicon_status_failed'
+ "favicon_status_failed"
end
end
end
diff --git a/lib/gitlab/ci/status/manual.rb b/lib/gitlab/ci/status/manual.rb
index 50c92add400..2d8e7033e44 100644
--- a/lib/gitlab/ci/status/manual.rb
+++ b/lib/gitlab/ci/status/manual.rb
@@ -5,19 +5,19 @@ module Gitlab
module Status
class Manual < Status::Core
def text
- s_('CiStatusText|manual')
+ s_("CiStatusText|manual")
end
def label
- s_('CiStatusLabel|manual action')
+ s_("CiStatusLabel|manual action")
end
def icon
- 'status_manual'
+ "status_manual"
end
def favicon
- 'favicon_status_manual'
+ "favicon_status_manual"
end
end
end
diff --git a/lib/gitlab/ci/status/pending.rb b/lib/gitlab/ci/status/pending.rb
index cea7e6ed938..4aebe115c2d 100644
--- a/lib/gitlab/ci/status/pending.rb
+++ b/lib/gitlab/ci/status/pending.rb
@@ -5,19 +5,19 @@ module Gitlab
module Status
class Pending < Status::Core
def text
- s_('CiStatusText|pending')
+ s_("CiStatusText|pending")
end
def label
- s_('CiStatusLabel|pending')
+ s_("CiStatusLabel|pending")
end
def icon
- 'status_pending'
+ "status_pending"
end
def favicon
- 'favicon_status_pending'
+ "favicon_status_pending"
end
end
end
diff --git a/lib/gitlab/ci/status/pipeline/blocked.rb b/lib/gitlab/ci/status/pipeline/blocked.rb
index ed13a439be0..a1dbf0a63f2 100644
--- a/lib/gitlab/ci/status/pipeline/blocked.rb
+++ b/lib/gitlab/ci/status/pipeline/blocked.rb
@@ -6,11 +6,11 @@ module Gitlab
module Pipeline
class Blocked < Status::Extended
def text
- s_('CiStatusText|blocked')
+ s_("CiStatusText|blocked")
end
def label
- s_('CiStatusLabel|waiting for manual action')
+ s_("CiStatusLabel|waiting for manual action")
end
def self.matches?(pipeline, user)
diff --git a/lib/gitlab/ci/status/pipeline/delayed.rb b/lib/gitlab/ci/status/pipeline/delayed.rb
index e61acdcd167..9b87aaaacef 100644
--- a/lib/gitlab/ci/status/pipeline/delayed.rb
+++ b/lib/gitlab/ci/status/pipeline/delayed.rb
@@ -6,11 +6,11 @@ module Gitlab
module Pipeline
class Delayed < Status::Extended
def text
- s_('CiStatusText|delayed')
+ s_("CiStatusText|delayed")
end
def label
- s_('CiStatusLabel|waiting for delayed job')
+ s_("CiStatusLabel|waiting for delayed job")
end
def self.matches?(pipeline, user)
diff --git a/lib/gitlab/ci/status/pipeline/factory.rb b/lib/gitlab/ci/status/pipeline/factory.rb
index 5d1a8bbd924..606fa7bba7b 100644
--- a/lib/gitlab/ci/status/pipeline/factory.rb
+++ b/lib/gitlab/ci/status/pipeline/factory.rb
@@ -8,7 +8,7 @@ module Gitlab
def self.extended_statuses
[[Status::SuccessWarning,
Status::Pipeline::Delayed,
- Status::Pipeline::Blocked]]
+ Status::Pipeline::Blocked,]]
end
def self.common_helpers
diff --git a/lib/gitlab/ci/status/running.rb b/lib/gitlab/ci/status/running.rb
index ac7dd74cdce..65563b33fd5 100644
--- a/lib/gitlab/ci/status/running.rb
+++ b/lib/gitlab/ci/status/running.rb
@@ -5,19 +5,19 @@ module Gitlab
module Status
class Running < Status::Core
def text
- s_('CiStatus|running')
+ s_("CiStatus|running")
end
def label
- s_('CiStatus|running')
+ s_("CiStatus|running")
end
def icon
- 'status_running'
+ "status_running"
end
def favicon
- 'favicon_status_running'
+ "favicon_status_running"
end
end
end
diff --git a/lib/gitlab/ci/status/scheduled.rb b/lib/gitlab/ci/status/scheduled.rb
index 16ad1da89e3..2fb4c766f08 100644
--- a/lib/gitlab/ci/status/scheduled.rb
+++ b/lib/gitlab/ci/status/scheduled.rb
@@ -5,19 +5,19 @@ module Gitlab
module Status
class Scheduled < Status::Core
def text
- s_('CiStatusText|delayed')
+ s_("CiStatusText|delayed")
end
def label
- s_('CiStatusLabel|delayed')
+ s_("CiStatusLabel|delayed")
end
def icon
- 'status_scheduled'
+ "status_scheduled"
end
def favicon
- 'favicon_status_scheduled'
+ "favicon_status_scheduled"
end
end
end
diff --git a/lib/gitlab/ci/status/skipped.rb b/lib/gitlab/ci/status/skipped.rb
index aaec1e1d201..e5d7bd01fe2 100644
--- a/lib/gitlab/ci/status/skipped.rb
+++ b/lib/gitlab/ci/status/skipped.rb
@@ -5,19 +5,19 @@ module Gitlab
module Status
class Skipped < Status::Core
def text
- s_('CiStatusText|skipped')
+ s_("CiStatusText|skipped")
end
def label
- s_('CiStatusLabel|skipped')
+ s_("CiStatusLabel|skipped")
end
def icon
- 'status_skipped'
+ "status_skipped"
end
def favicon
- 'favicon_status_skipped'
+ "favicon_status_skipped"
end
end
end
diff --git a/lib/gitlab/ci/status/stage/common.rb b/lib/gitlab/ci/status/stage/common.rb
index f12daaa9676..a0dc5c4ce84 100644
--- a/lib/gitlab/ci/status/stage/common.rb
+++ b/lib/gitlab/ci/status/stage/common.rb
@@ -11,8 +11,8 @@ module Gitlab
def details_path
project_pipeline_path(subject.pipeline.project,
- subject.pipeline,
- anchor: subject.name)
+ subject.pipeline,
+ anchor: subject.name)
end
def has_action?
diff --git a/lib/gitlab/ci/status/success.rb b/lib/gitlab/ci/status/success.rb
index 020f2c5b89f..507e3c8d7b2 100644
--- a/lib/gitlab/ci/status/success.rb
+++ b/lib/gitlab/ci/status/success.rb
@@ -5,19 +5,19 @@ module Gitlab
module Status
class Success < Status::Core
def text
- s_('CiStatusText|passed')
+ s_("CiStatusText|passed")
end
def label
- s_('CiStatusLabel|passed')
+ s_("CiStatusLabel|passed")
end
def icon
- 'status_success'
+ "status_success"
end
def favicon
- 'favicon_status_success'
+ "favicon_status_success"
end
end
end
diff --git a/lib/gitlab/ci/status/success_warning.rb b/lib/gitlab/ci/status/success_warning.rb
index 6632cd9b143..9cc58742a4c 100644
--- a/lib/gitlab/ci/status/success_warning.rb
+++ b/lib/gitlab/ci/status/success_warning.rb
@@ -9,19 +9,19 @@ module Gitlab
#
class SuccessWarning < Status::Extended
def text
- s_('CiStatusText|passed')
+ s_("CiStatusText|passed")
end
def label
- s_('CiStatusLabel|passed with warnings')
+ s_("CiStatusLabel|passed with warnings")
end
def icon
- 'status_warning'
+ "status_warning"
end
def group
- 'success_with_warnings'
+ "success_with_warnings"
end
def self.matches?(subject, user)
diff --git a/lib/gitlab/ci/trace.rb b/lib/gitlab/ci/trace.rb
index bf5f2a31f0e..a2ed99402a5 100644
--- a/lib/gitlab/ci/trace.rb
+++ b/lib/gitlab/ci/trace.rb
@@ -45,14 +45,14 @@ module Gitlab
end
def set(data)
- write('w+b') do |stream|
+ write("w+b") do |stream|
data = job.hide_secrets(data)
stream.set(data)
end
end
def append(data, offset)
- write('a+b') do |stream|
+ write("a+b") do |stream|
current_length = stream.size
break current_length unless current_length == offset
@@ -67,7 +67,7 @@ module Gitlab
end
def read
- stream = Gitlab::Ci::Trace::Stream.new do
+ stream = Gitlab::Ci::Trace::Stream.new {
if trace_artifact
trace_artifact.open
elsif job.trace_chunks.any?
@@ -77,7 +77,7 @@ module Gitlab
elsif old_trace
StringIO.new(old_trace)
end
- end
+ }
yield stream
ensure
@@ -113,17 +113,17 @@ module Gitlab
private
def unsafe_write!(mode, &blk)
- stream = Gitlab::Ci::Trace::Stream.new do
+ stream = Gitlab::Ci::Trace::Stream.new {
if trace_artifact
- raise AlreadyArchivedError, 'Could not write to the archived trace'
+ raise AlreadyArchivedError, "Could not write to the archived trace"
elsif current_path
File.open(current_path, mode)
- elsif Feature.enabled?('ci_enable_live_trace')
+ elsif Feature.enabled?("ci_enable_live_trace")
Gitlab::Ci::Trace::ChunkedIO.new(job)
else
File.open(ensure_path, mode)
end
- end
+ }
yield(stream).tap do
job.touch if job.needs_touch?
@@ -133,8 +133,8 @@ module Gitlab
end
def unsafe_archive!
- raise AlreadyArchivedError, 'Could not archive again' if trace_artifact
- raise ArchiveError, 'Job is not finished yet' unless job.complete?
+ raise AlreadyArchivedError, "Could not archive again" if trace_artifact
+ raise ArchiveError, "Job is not finished yet" unless job.complete?
if job.trace_chunks.any?
Gitlab::Ci::Trace::ChunkedIO.new(job) do |stream|
@@ -147,7 +147,7 @@ module Gitlab
FileUtils.rm(current_path)
end
elsif old_trace
- StringIO.new(old_trace, 'rb').tap do |stream|
+ StringIO.new(old_trace, "rb").tap do |stream|
archive_stream!(stream)
job.erase_old_trace!
end
@@ -167,11 +167,11 @@ module Gitlab
def clone_file!(src_stream, temp_dir)
FileUtils.mkdir_p(temp_dir)
- Dir.mktmpdir('tmp-trace', temp_dir) do |dir_path|
+ Dir.mktmpdir("tmp-trace", temp_dir) do |dir_path|
temp_path = File.join(dir_path, "job.log")
FileUtils.touch(temp_path)
size = IO.copy_stream(src_stream, temp_path)
- raise ArchiveError, 'Failed to copy stream' unless size == src_stream.size
+ raise ArchiveError, "Failed to copy stream" unless size == src_stream.size
yield(temp_path)
end
@@ -185,7 +185,8 @@ module Gitlab
project: job.project,
file_type: :trace,
file: stream,
- file_sha256: Digest::SHA256.file(path).hexdigest)
+ file_sha256: Digest::SHA256.file(path).hexdigest
+ )
end
end
@@ -203,15 +204,15 @@ module Gitlab
end
def current_path
- @current_path ||= paths.find do |trace_path|
+ @current_path ||= paths.find { |trace_path|
File.exist?(trace_path)
- end
+ }
end
def paths
[
default_path,
- deprecated_path
+ deprecated_path,
].compact
end
@@ -228,12 +229,14 @@ module Gitlab
end
def deprecated_path
- File.join(
- Settings.gitlab_ci.builds_path,
- job.created_at.utc.strftime("%Y_%m"),
- job.project.ci_id.to_s,
- "#{job.id}.log"
- ) if job.project&.ci_id
+ if job.project&.ci_id
+ File.join(
+ Settings.gitlab_ci.builds_path,
+ job.created_at.utc.strftime("%Y_%m"),
+ job.project.ci_id.to_s,
+ "#{job.id}.log"
+ )
+ end
end
def trace_artifact
diff --git a/lib/gitlab/ci/trace/chunked_io.rb b/lib/gitlab/ci/trace/chunked_io.rb
index 8c6fd56493f..8c0113f6274 100644
--- a/lib/gitlab/ci/trace/chunked_io.rb
+++ b/lib/gitlab/ci/trace/chunked_io.rb
@@ -15,7 +15,7 @@ module Gitlab
attr_reader :tell, :size
attr_reader :chunk_data, :chunk_range
- alias_method :pos, :tell
+ alias pos tell
def initialize(build, &block)
@build = build
@@ -50,7 +50,7 @@ module Gitlab
-1
end
- raise ArgumentError, 'new position is outside of file' if new_pos < 0 || new_pos > size
+ raise ArgumentError, "new position is outside of file" if new_pos < 0 || new_pos > size
@tell = new_pos
end
@@ -88,9 +88,7 @@ module Gitlab
out = out.join
# If outbuf is passed, we put the output into the buffer. This supports IO.copy_stream functionality
- if outbuf
- outbuf.replace(out)
- end
+ outbuf&.replace(out)
out
end
@@ -141,14 +139,14 @@ module Gitlab
# rubocop: disable CodeReuse/ActiveRecord
def truncate(offset)
- raise ArgumentError, 'Outside of file' if offset > size || offset < 0
+ raise ArgumentError, "Outside of file" if offset > size || offset < 0
return if offset == size # Skip the following process as it doesn't affect anything
@tell = offset
@size = offset
# remove all next chunks
- trace_chunks.where('chunk_index > ?', chunk_index).fast_destroy_all
+ trace_chunks.where("chunk_index > ?", chunk_index).fast_destroy_all
# truncate current chunk
current_chunk.truncate(chunk_offset)
diff --git a/lib/gitlab/ci/trace/section_parser.rb b/lib/gitlab/ci/trace/section_parser.rb
index f33f8cc56c1..36ff14fb67f 100644
--- a/lib/gitlab/ci/trace/section_parser.rb
+++ b/lib/gitlab/ci/trace/section_parser.rb
@@ -25,7 +25,7 @@ module Gitlab
byte_start: start_[:marker],
byte_end: end_[:marker],
date_start: start_[:timestamp],
- date_end: end_[:timestamp]
+ date_end: end_[:timestamp],
}
end
end
@@ -59,17 +59,17 @@ module Gitlab
action = action.to_sym
timestamp = Time.at(time).utc
marker = if action == :start
- marker_end
- else
- marker_start
- end
+ marker_end
+ else
+ marker_start
+ end
@markers[name] ||= []
@markers[name] << {
name: name,
action: action,
timestamp: timestamp,
- marker: marker
+ marker: marker,
}
end
diff --git a/lib/gitlab/ci/trace/stream.rb b/lib/gitlab/ci/trace/stream.rb
index e61fb50a303..23ef5f93926 100644
--- a/lib/gitlab/ci/trace/stream.rb
+++ b/lib/gitlab/ci/trace/stream.rb
@@ -14,7 +14,7 @@ module Gitlab
delegate :valid?, to: :stream, allow_nil: true
- alias_method :present?, :valid?
+ alias present? valid?
def initialize
@stream = yield
@@ -22,15 +22,15 @@ module Gitlab
end
def valid?
- self.stream.present?
+ stream.present?
end
def file?
- self.path.present?
+ path.present?
end
def path
- self.stream.path if self.stream.respond_to?(:path)
+ stream.path if stream.respond_to?(:path)
end
def limit(last_bytes = LIMIT_SIZE)
@@ -123,7 +123,7 @@ module Gitlab
def reverse_line
stream.seek(0, IO::SEEK_END)
- debris = ''
+ debris = ""
until (buf = read_backward(BUFFER_SIZE)).empty?
debris, *lines = (buf + debris).each_line.to_a
diff --git a/lib/gitlab/ci/variables/collection.rb b/lib/gitlab/ci/variables/collection.rb
index a7b4e0348c2..8a513e8fa58 100644
--- a/lib/gitlab/ci/variables/collection.rb
+++ b/lib/gitlab/ci/variables/collection.rb
@@ -9,7 +9,7 @@ module Gitlab
def initialize(variables = [])
@variables = []
- variables.each { |variable| self.append(variable) }
+ variables.each { |variable| append(variable) }
end
def append(resource)
@@ -17,7 +17,7 @@ module Gitlab
end
def concat(resources)
- tap { resources.each { |variable| self.append(variable) } }
+ tap { resources.each { |variable| append(variable) } }
end
def each
@@ -26,17 +26,17 @@ module Gitlab
def +(other)
self.class.new.tap do |collection|
- self.each { |variable| collection.append(variable) }
+ each { |variable| collection.append(variable) }
other.each { |variable| collection.append(variable) }
end
end
def to_runner_variables
- self.map(&:to_runner_variable)
+ map(&:to_runner_variable)
end
def to_hash
- self.to_runner_variables
+ to_runner_variables
.map { |env| [env.fetch(:key), env.fetch(:value)] }
.to_h.with_indifferent_access
end
diff --git a/lib/gitlab/ci/variables/collection/item.rb b/lib/gitlab/ci/variables/collection/item.rb
index 833aa75adb5..9d344261d8b 100644
--- a/lib/gitlab/ci/variables/collection/item.rb
+++ b/lib/gitlab/ci/variables/collection/item.rb
@@ -10,7 +10,7 @@ module Gitlab
value.is_a?(String) || value.nil?
@variable = {
- key: key, value: value, public: public, file: file, masked: masked
+ key: key, value: value, public: public, file: file, masked: masked,
}
end
@@ -40,9 +40,9 @@ module Gitlab
def self.fabricate(resource)
case resource
when Hash
- self.new(resource.symbolize_keys)
+ new(resource.symbolize_keys)
when ::HasVariable
- self.new(resource.to_runner_variable)
+ new(resource.to_runner_variable)
when self
resource.dup
else
diff --git a/lib/gitlab/ci/yaml_processor.rb b/lib/gitlab/ci/yaml_processor.rb
index 07ba6f83d47..9600b9dae8c 100644
--- a/lib/gitlab/ci/yaml_processor.rb
+++ b/lib/gitlab/ci/yaml_processor.rb
@@ -31,31 +31,31 @@ module Gitlab
def build_attributes(name)
job = @jobs.fetch(name.to_sym, {})
- { stage_idx: @stages.index(job[:stage]),
- stage: job[:stage],
- tag_list: job[:tags],
- name: job[:name].to_s,
- allow_failure: job[:ignore],
- when: job[:when] || 'on_success',
- environment: job[:environment_name],
- coverage_regex: job[:coverage],
- yaml_variables: yaml_variables(name),
- options: {
- image: job[:image],
- services: job[:services],
- artifacts: job[:artifacts],
- cache: job[:cache],
- dependencies: job[:dependencies],
- before_script: job[:before_script],
- script: job[:script],
- after_script: job[:after_script],
- environment: job[:environment],
- retry: job[:retry],
- parallel: job[:parallel],
- instance: job[:instance],
- start_in: job[:start_in],
- trigger: job[:trigger]
- }.compact }.compact
+ {stage_idx: @stages.index(job[:stage]),
+ stage: job[:stage],
+ tag_list: job[:tags],
+ name: job[:name].to_s,
+ allow_failure: job[:ignore],
+ when: job[:when] || "on_success",
+ environment: job[:environment_name],
+ coverage_regex: job[:coverage],
+ yaml_variables: yaml_variables(name),
+ options: {
+ image: job[:image],
+ services: job[:services],
+ artifacts: job[:artifacts],
+ cache: job[:cache],
+ dependencies: job[:dependencies],
+ before_script: job[:before_script],
+ script: job[:script],
+ after_script: job[:after_script],
+ environment: job[:environment],
+ retry: job[:retry],
+ parallel: job[:parallel],
+ instance: job[:instance],
+ start_in: job[:start_in],
+ trigger: job[:trigger],
+ }.compact,}.compact
end
def stage_builds_attributes(stage)
@@ -66,20 +66,20 @@ module Gitlab
def stages_attributes
@stages.uniq.map do |stage|
- seeds = stage_builds_attributes(stage).map do |attributes|
+ seeds = stage_builds_attributes(stage).map { |attributes|
job = @jobs.fetch(attributes[:name].to_sym)
attributes
.merge(only: job.fetch(:only, {}))
.merge(except: job.fetch(:except, {}))
- end
+ }
- { name: stage, index: @stages.index(stage), builds: seeds }
+ {name: stage, index: @stages.index(stage), builds: seeds}
end
end
def self.validation_message(content, opts = {})
- return 'Please provide content of .gitlab-ci.yml' if content.blank?
+ return "Please provide content of .gitlab-ci.yml" if content.blank?
begin
Gitlab::Ci::YamlProcessor.new(content, opts)
@@ -122,7 +122,7 @@ module Gitlab
.merge(job_variables(name))
variables.map do |key, value|
- { key: key.to_s, value: value, public: true }
+ {key: key.to_s, value: value, public: true}
end
end
@@ -179,7 +179,7 @@ module Gitlab
raise ValidationError, "#{name} job: on_stop job #{on_stop} have different environment name"
end
- unless on_stop_job[:environment][:action] == 'stop'
+ unless on_stop_job[:environment][:action] == "stop"
raise ValidationError, "#{name} job: on_stop job #{on_stop} needs to have action stop defined"
end
end
diff --git a/lib/gitlab/cleanup/project_upload_file_finder.rb b/lib/gitlab/cleanup/project_upload_file_finder.rb
index 2ee8b60e76a..73877e5b642 100644
--- a/lib/gitlab/cleanup/project_upload_file_finder.rb
+++ b/lib/gitlab/cleanup/project_upload_file_finder.rb
@@ -5,9 +5,9 @@ module Gitlab
class ProjectUploadFileFinder
FIND_BATCH_SIZE = 500
ABSOLUTE_UPLOAD_DIR = FileUploader.root.freeze
- EXCLUDED_SYSTEM_UPLOADS_PATH = "#{ABSOLUTE_UPLOAD_DIR}/-/*".freeze
- EXCLUDED_HASHED_UPLOADS_PATH = "#{ABSOLUTE_UPLOAD_DIR}/@hashed/*".freeze
- EXCLUDED_TMP_UPLOADS_PATH = "#{ABSOLUTE_UPLOAD_DIR}/tmp/*".freeze
+ EXCLUDED_SYSTEM_UPLOADS_PATH = "#{ABSOLUTE_UPLOAD_DIR}/-/*"
+ EXCLUDED_HASHED_UPLOADS_PATH = "#{ABSOLUTE_UPLOAD_DIR}/@hashed/*"
+ EXCLUDED_TMP_UPLOADS_PATH = "#{ABSOLUTE_UPLOAD_DIR}/tmp/*"
# Paths are relative to the upload directory
def each_file_batch(batch_size: FIND_BATCH_SIZE, &block)
@@ -48,15 +48,15 @@ module Gitlab
ionice = which_ionice
cmd = %W[#{ionice} -c Idle] + cmd if ionice
- log_msg = "find command: \"#{cmd.join(' ')}\""
+ log_msg = "find command: \"#{cmd.join(" ")}\""
Rails.logger.info log_msg
cmd
end
def which_ionice
- Gitlab::Utils.which('ionice')
- rescue StandardError
+ Gitlab::Utils.which("ionice")
+ rescue
# In this case, returning false is relatively safe,
# even though it isn't very nice
false
diff --git a/lib/gitlab/cleanup/project_uploads.rb b/lib/gitlab/cleanup/project_uploads.rb
index 82a405362c2..8c3e6fac399 100644
--- a/lib/gitlab/cleanup/project_uploads.rb
+++ b/lib/gitlab/cleanup/project_uploads.rb
@@ -3,7 +3,7 @@
module Gitlab
module Cleanup
class ProjectUploads
- LOST_AND_FOUND = File.join(ProjectUploadFileFinder::ABSOLUTE_UPLOAD_DIR, '-', 'project-lost-found')
+ LOST_AND_FOUND = File.join(ProjectUploadFileFinder::ABSOLUTE_UPLOAD_DIR, "-", "project-lost-found")
attr_reader :logger
@@ -12,7 +12,7 @@ module Gitlab
end
def run!(dry_run: true)
- logger.info "Looking for orphaned project uploads to clean up#{'. Dry run' if dry_run}..."
+ logger.info "Looking for orphaned project uploads to clean up#{". Dry run" if dry_run}..."
each_orphan_file do |path, upload_path|
result = cleanup(path, upload_path, dry_run)
@@ -31,7 +31,7 @@ module Gitlab
correct_path = upload_path && find_correct_path(upload_path)
if correct_path
- move(path, correct_path, 'fix', dry_run)
+ move(path, correct_path, "fix", dry_run)
else
move_to_lost_and_found(path, dry_run)
end
@@ -40,8 +40,8 @@ module Gitlab
# Accepts a path in the form of "#{hex_secret}/#{filename}"
# rubocop: disable CodeReuse/ActiveRecord
def find_correct_path(upload_path)
- upload = Upload.find_by(uploader: 'FileUploader', path: upload_path)
- return unless upload && upload.local? && upload.model
+ upload = Upload.find_by(uploader: "FileUploader", path: upload_path)
+ return unless upload&.local? && upload&.model
upload.absolute_path
rescue => e
@@ -58,7 +58,7 @@ module Gitlab
def move_to_lost_and_found(path, dry_run)
new_path = path.sub(/\A#{ProjectUploadFileFinder::ABSOLUTE_UPLOAD_DIR}/, LOST_AND_FOUND)
- move(path, new_path, 'move to lost and found', dry_run)
+ move(path, new_path, "move to lost and found", dry_run)
end
def move(path, new_path, prefix, dry_run)
@@ -114,7 +114,7 @@ module Gitlab
return true if full_path.nil? || upload_path.nil?
# It's possible to reduce to one query, but `where_full_path_in` is complex
- !Upload.exists?(path: upload_path, model_id: project_id, model_type: 'Project', uploader: 'FileUploader')
+ !Upload.exists?(path: upload_path, model_id: project_id, model_type: "Project", uploader: "FileUploader")
end
# rubocop: enable CodeReuse/ActiveRecord
diff --git a/lib/gitlab/cleanup/remote_uploads.rb b/lib/gitlab/cleanup/remote_uploads.rb
index 03298d960a4..2c552c2664b 100644
--- a/lib/gitlab/cleanup/remote_uploads.rb
+++ b/lib/gitlab/cleanup/remote_uploads.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
module Gitlab
module Cleanup
class RemoteUploads
@@ -17,15 +18,15 @@ module Gitlab
return
end
- logger.info "Looking for orphaned remote uploads to remove#{'. Dry run' if dry_run}..."
+ logger.info "Looking for orphaned remote uploads to remove#{". Dry run" if dry_run}..."
each_orphan_file do |file|
info = if dry_run
- "Can be moved to lost and found: #{file.key}"
- else
- new_path = move_to_lost_and_found(file)
- "Moved to lost and found: #{file.key} -> #{new_path}"
- end
+ "Can be moved to lost and found: #{file.key}"
+ else
+ new_path = move_to_lost_and_found(file)
+ "Moved to lost and found: #{file.key} -> #{new_path}"
+ end
logger.info(info)
end
@@ -56,22 +57,22 @@ module Gitlab
def move_to_lost_and_found(file)
new_path = "#{lost_and_found_dir}/#{file.key}"
- file.copy(configuration['remote_directory'], new_path)
+ file.copy(configuration["remote_directory"], new_path)
file.destroy
new_path
end
def lost_and_found_dir
- 'lost_and_found'
+ "lost_and_found"
end
def remote_directory
- connection.directories.new(key: configuration['remote_directory'])
+ connection.directories.new(key: configuration["remote_directory"])
end
def connection
- ::Fog::Storage.new(configuration['connection'].symbolize_keys)
+ ::Fog::Storage.new(configuration["connection"].symbolize_keys)
end
def configuration
diff --git a/lib/gitlab/closing_issue_extractor.rb b/lib/gitlab/closing_issue_extractor.rb
index 4ba921569ad..9c5709f2854 100644
--- a/lib/gitlab/closing_issue_extractor.rb
+++ b/lib/gitlab/closing_issue_extractor.rb
@@ -6,7 +6,7 @@ module Gitlab
link_pattern = Banzai::Filter::AutolinkFilter::LINK_PATTERN
pattern = Gitlab.config.gitlab.issue_closing_pattern
- pattern = pattern.sub('%{issue_ref}', "(?:(?:#{link_pattern})|(?:#{Issue.reference_pattern}))")
+ pattern = pattern.sub("%{issue_ref}", "(?:(?:#{link_pattern})|(?:#{Issue.reference_pattern}))")
Regexp.new(pattern).freeze
end
diff --git a/lib/gitlab/cluster/lifecycle_events.rb b/lib/gitlab/cluster/lifecycle_events.rb
index b05dca409d1..ba55105e8b3 100644
--- a/lib/gitlab/cluster/lifecycle_events.rb
+++ b/lib/gitlab/cluster/lifecycle_events.rb
@@ -60,7 +60,7 @@ module Gitlab
end
def do_master_restart
- @master_restart_hooks && @master_restart_hooks.each do |block|
+ @master_restart_hooks&.each do |block|
block.call
end
end
diff --git a/lib/gitlab/cluster/puma_worker_killer_initializer.rb b/lib/gitlab/cluster/puma_worker_killer_initializer.rb
index 4ed9a9a02ab..d4fe2995c99 100644
--- a/lib/gitlab/cluster/puma_worker_killer_initializer.rb
+++ b/lib/gitlab/cluster/puma_worker_killer_initializer.rb
@@ -4,7 +4,7 @@ module Gitlab
module Cluster
class PumaWorkerKillerInitializer
def self.start(puma_options, puma_per_worker_max_memory_mb: 650)
- require 'puma_worker_killer'
+ require "puma_worker_killer"
PumaWorkerKiller.config do |config|
# Note! ram is expressed in megabytes (whereas GITLAB_UNICORN_MEMORY_MAX is in bytes)
diff --git a/lib/gitlab/color_schemes.rb b/lib/gitlab/color_schemes.rb
index 881e5dbc923..0ae829c0e83 100644
--- a/lib/gitlab/color_schemes.rb
+++ b/lib/gitlab/color_schemes.rb
@@ -8,12 +8,12 @@ module Gitlab
Scheme = Struct.new(:id, :name, :css_class)
SCHEMES = [
- Scheme.new(1, 'White', 'white'),
- Scheme.new(2, 'Dark', 'dark'),
- Scheme.new(3, 'Solarized Light', 'solarized-light'),
- Scheme.new(4, 'Solarized Dark', 'solarized-dark'),
- Scheme.new(5, 'Monokai', 'monokai'),
- Scheme.new(6, 'None', 'none')
+ Scheme.new(1, "White", "white"),
+ Scheme.new(2, "Dark", "dark"),
+ Scheme.new(3, "Solarized Light", "solarized-light"),
+ Scheme.new(4, "Solarized Dark", "solarized-dark"),
+ Scheme.new(5, "Monokai", "monokai"),
+ Scheme.new(6, "None", "none"),
].freeze
# Convenience method to get a space-separated String of all the color scheme
@@ -21,7 +21,7 @@ module Gitlab
#
# Returns a String
def self.body_classes
- SCHEMES.collect(&:css_class).uniq.join(' ')
+ SCHEMES.collect(&:css_class).uniq.join(" ")
end
# Get a Scheme by its ID
diff --git a/lib/gitlab/config/entry/attributable.rb b/lib/gitlab/config/entry/attributable.rb
index 560fe63df0e..b84e9160e25 100644
--- a/lib/gitlab/config/entry/attributable.rb
+++ b/lib/gitlab/config/entry/attributable.rb
@@ -10,7 +10,7 @@ module Gitlab
def attributes(*attributes)
attributes.flatten.each do |attribute|
if method_defined?(attribute)
- raise ArgumentError, 'Method already defined!'
+ raise ArgumentError, "Method already defined!"
end
define_method(attribute) do
diff --git a/lib/gitlab/config/entry/configurable.rb b/lib/gitlab/config/entry/configurable.rb
index 37ba16dba25..9c40014133f 100644
--- a/lib/gitlab/config/entry/configurable.rb
+++ b/lib/gitlab/config/entry/configurable.rb
@@ -69,7 +69,7 @@ module Gitlab
end
define_method("#{symbol}_value") do
- return unless entries[symbol] && entries[symbol].valid?
+ return unless entries[symbol]&.valid?
entries[symbol].value
end
diff --git a/lib/gitlab/config/entry/factory.rb b/lib/gitlab/config/entry/factory.rb
index 79f9ff32514..dda55019bb9 100644
--- a/lib/gitlab/config/entry/factory.rb
+++ b/lib/gitlab/config/entry/factory.rb
@@ -12,7 +12,7 @@ module Gitlab
def initialize(entry)
@entry = entry
@metadata = {}
- @attributes = { default: entry.default }
+ @attributes = {default: entry.default}
end
def value(value)
diff --git a/lib/gitlab/config/entry/legacy_validation_helpers.rb b/lib/gitlab/config/entry/legacy_validation_helpers.rb
index d3ab5625743..5cbbb1b3013 100644
--- a/lib/gitlab/config/entry/legacy_validation_helpers.rb
+++ b/lib/gitlab/config/entry/legacy_validation_helpers.rb
@@ -54,7 +54,7 @@ module Gitlab
return true if value.is_a?(Symbol)
return false unless value.is_a?(String)
- if value.first == '/' && value.last == '/'
+ if value.first == "/" && value.last == "/"
validate_regexp(value[1...-1])
else
true
diff --git a/lib/gitlab/config/entry/node.rb b/lib/gitlab/config/entry/node.rb
index 9999ab4ff95..bcddb7ebcd1 100644
--- a/lib/gitlab/config/entry/node.rb
+++ b/lib/gitlab/config/entry/node.rb
@@ -56,9 +56,9 @@ module Gitlab
if leaf?
@config
else
- meaningful = @entries.select do |_key, value|
+ meaningful = @entries.select { |_key, value|
value.specified? && value.relevant?
- end
+ }
Hash[meaningful.map { |key, entry| [key, entry.value] }]
end
@@ -74,14 +74,14 @@ module Gitlab
def location
name = @key.presence || self.class.name.to_s.demodulize
- .underscore.humanize.downcase
+ .underscore.humanize.downcase
- ancestors.map(&:key).append(name).compact.join(':')
+ ancestors.map(&:key).append(name).compact.join(":")
end
def inspect
val = leaf? ? config : descendants
- unspecified = specified? ? '' : '(unspecified) '
+ unspecified = specified? ? "" : "(unspecified) "
"#<#{self.class.name} #{unspecified}{#{key}: #{val.inspect}}>"
end
diff --git a/lib/gitlab/config/entry/simplifiable.rb b/lib/gitlab/config/entry/simplifiable.rb
index 5fbf7565e2a..6a7789ed2be 100644
--- a/lib/gitlab/config/entry/simplifiable.rb
+++ b/lib/gitlab/config/entry/simplifiable.rb
@@ -10,12 +10,12 @@ module Gitlab
def initialize(config, **metadata)
unless self.class.const_defined?(:UnknownStrategy)
- raise ArgumentError, 'UndefinedStrategy not available!'
+ raise ArgumentError, "UndefinedStrategy not available!"
end
- strategy = self.class.strategies.find do |variant|
+ strategy = self.class.strategies.find { |variant|
variant.condition.call(config)
- end
+ }
entry = self.class.entry_class(strategy)
@@ -34,7 +34,7 @@ module Gitlab
def self.entry_class(strategy)
if strategy.present?
- self.const_get(strategy.name)
+ const_get(strategy.name)
else
self::UnknownStrategy
end
diff --git a/lib/gitlab/config/entry/validator.rb b/lib/gitlab/config/entry/validator.rb
index e5efd4a7b0a..32f3b508696 100644
--- a/lib/gitlab/config/entry/validator.rb
+++ b/lib/gitlab/config/entry/validator.rb
@@ -18,7 +18,7 @@ module Gitlab
end
def self.name
- 'Validator'
+ "Validator"
end
end
end
diff --git a/lib/gitlab/config/entry/validators.rb b/lib/gitlab/config/entry/validators.rb
index 25bfa50f829..8dd1bc3fdf3 100644
--- a/lib/gitlab/config/entry/validators.rb
+++ b/lib/gitlab/config/entry/validators.rb
@@ -10,7 +10,7 @@ module Gitlab
if unknown_keys.any?
record.errors.add(attribute, "contains unknown keys: " +
- unknown_keys.join(', '))
+ unknown_keys.join(", "))
end
end
end
@@ -28,7 +28,7 @@ module Gitlab
unkown_values = value - options[:in]
unless unkown_values.empty?
record.errors.add(attribute, "contains unknown values: " +
- unkown_values.join(', '))
+ unkown_values.join(", "))
end
end
end
@@ -38,7 +38,7 @@ module Gitlab
def validate_each(record, attribute, value)
unless validate_array_of_strings(value)
- record.errors.add(attribute, 'should be an array of strings')
+ record.errors.add(attribute, "should be an array of strings")
end
end
end
@@ -48,7 +48,7 @@ module Gitlab
def validate_each(record, attribute, value)
unless validate_boolean(value)
- record.errors.add(attribute, 'should be a boolean value')
+ record.errors.add(attribute, "should be a boolean value")
end
end
end
@@ -58,12 +58,12 @@ module Gitlab
def validate_each(record, attribute, value)
unless validate_duration(value)
- record.errors.add(attribute, 'should be a duration')
+ record.errors.add(attribute, "should be a duration")
end
if options[:limit]
unless validate_duration_limit(value, options[:limit])
- record.errors.add(attribute, 'should not exceed the limit')
+ record.errors.add(attribute, "should not exceed the limit")
end
end
end
@@ -72,7 +72,7 @@ module Gitlab
class HashOrStringValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value.is_a?(Hash) || value.is_a?(String)
- record.errors.add(attribute, 'should be a hash or a string')
+ record.errors.add(attribute, "should be a hash or a string")
end
end
end
@@ -80,7 +80,7 @@ module Gitlab
class HashOrIntegerValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value.is_a?(Hash) || value.is_a?(Integer)
- record.errors.add(attribute, 'should be a hash or an integer')
+ record.errors.add(attribute, "should be a hash or an integer")
end
end
end
@@ -92,7 +92,7 @@ module Gitlab
if validate_string(value)
validate_path(record, attribute, value)
else
- record.errors.add(attribute, 'should be a string or symbol')
+ record.errors.add(attribute, "should be a string or symbol")
end
end
@@ -101,9 +101,9 @@ module Gitlab
def validate_path(record, attribute, value)
path = CGI.unescape(value.to_s)
- if path.include?('/')
+ if path.include?("/")
record.errors.add(attribute, 'cannot contain the "/" character')
- elsif path == '.' || path == '..'
+ elsif path == "." || path == ".."
record.errors.add(attribute, 'cannot be "." or ".."')
end
end
@@ -114,15 +114,15 @@ module Gitlab
def validate_each(record, attribute, value)
unless validate_regexp(value)
- record.errors.add(attribute, 'must be a regular expression')
+ record.errors.add(attribute, "must be a regular expression")
end
end
private
def look_like_regexp?(value)
- value.is_a?(String) && value.start_with?('/') &&
- value.end_with?('/')
+ value.is_a?(String) && value.start_with?("/") &&
+ value.end_with?("/")
end
def validate_regexp(value)
@@ -137,7 +137,7 @@ module Gitlab
class ArrayOfStringsOrRegexpsValidator < RegexpValidator
def validate_each(record, attribute, value)
unless validate_array_of_strings_or_regexps(value)
- record.errors.add(attribute, 'should be an array of strings or regexps')
+ record.errors.add(attribute, "should be an array of strings or regexps")
end
end
@@ -158,7 +158,7 @@ module Gitlab
class ArrayOfStringsOrStringValidator < RegexpValidator
def validate_each(record, attribute, value)
unless validate_array_of_strings_or_string(value)
- record.errors.add(attribute, 'should be an array of strings or a string')
+ record.errors.add(attribute, "should be an array of strings or a string")
end
end
@@ -186,7 +186,7 @@ module Gitlab
def validate_each(record, attribute, value)
unless validate_variables(value)
- record.errors.add(attribute, 'should be a hash of key value pairs')
+ record.errors.add(attribute, "should be a hash of key value pairs")
end
end
end
diff --git a/lib/gitlab/config/loader/yaml.rb b/lib/gitlab/config/loader/yaml.rb
index 8159f8b8026..adaa6083fc7 100644
--- a/lib/gitlab/config/loader/yaml.rb
+++ b/lib/gitlab/config/loader/yaml.rb
@@ -16,7 +16,7 @@ module Gitlab
def load!
unless valid?
- raise Loader::FormatError, 'Invalid configuration format'
+ raise Loader::FormatError, "Invalid configuration format"
end
@config.deep_symbolize_keys
diff --git a/lib/gitlab/conflict/file.rb b/lib/gitlab/conflict/file.rb
index 0ca99506311..7f46a74f424 100644
--- a/lib/gitlab/conflict/file.rb
+++ b/lib/gitlab/conflict/file.rb
@@ -38,7 +38,7 @@ module Gitlab
lines.each do |line|
line.rich_text =
- if line.type == 'old'
+ if line.type == "old"
their_highlight[line.old_line - 1].try(:html_safe)
else
our_highlight[line.new_line - 1].try(:html_safe)
@@ -54,7 +54,7 @@ module Gitlab
sections_count = chunked_lines.size
- @sections = chunked_lines.flat_map.with_index do |(no_conflict, lines), i|
+ @sections = chunked_lines.flat_map.with_index { |(no_conflict, lines), i|
section = nil
# We need to reduce context sections to CONTEXT_LINES. Conflict sections are
@@ -77,8 +77,8 @@ module Gitlab
match_line = create_match_line(tail_lines.first)
section = [
- { conflict: false, lines: head_lines },
- { conflict: false, lines: tail_lines.unshift(match_line) }
+ {conflict: false, lines: head_lines},
+ {conflict: false, lines: tail_lines.unshift(match_line)},
]
end
elsif conflict_after
@@ -103,10 +103,10 @@ module Gitlab
# created a gap and its corresponding match line.
update_match_line_text(match_line, lines.last) unless section
- section ||= { conflict: !no_conflict, lines: lines }
+ section ||= {conflict: !no_conflict, lines: lines}
section[:id] = line_code(lines.first) unless no_conflict
section
- end
+ }
end
def line_code(line)
@@ -114,7 +114,7 @@ module Gitlab
end
def create_match_line(line)
- Gitlab::Diff::Line.new('', 'match', line.index, line.old_pos, line.new_pos)
+ Gitlab::Diff::Line.new("", "match", line.index, line.old_pos, line.new_pos)
end
# Any line beginning with a letter, an underscore, or a dollar can be used in a
@@ -151,8 +151,8 @@ module Gitlab
json_hash = {
old_path: their_path,
new_path: our_path,
- blob_icon: file_type_icon_class('file', our_mode, our_path),
- blob_path: project_blob_path(merge_request.project, ::File.join(merge_request.diff_refs.head_sha, our_path))
+ blob_icon: file_type_icon_class("file", our_mode, our_path),
+ blob_path: project_blob_path(merge_request.project, ::File.join(merge_request.diff_refs.head_sha, our_path)),
}
json_hash.tap do |json_hash|
@@ -168,9 +168,9 @@ module Gitlab
def content_path
conflict_for_path_project_merge_request_path(merge_request.project,
- merge_request,
- old_path: their_path,
- new_path: our_path)
+ merge_request,
+ old_path: their_path,
+ new_path: our_path)
end
private
@@ -185,7 +185,7 @@ module Gitlab
def their_language
strong_memoize(:their_language) do
- repository.gitattribute(their_path, 'gitlab-language')
+ repository.gitattribute(their_path, "gitlab-language")
end
end
@@ -194,20 +194,20 @@ module Gitlab
if our_path == their_path
their_language
else
- repository.gitattribute(our_path, 'gitlab-language')
+ repository.gitattribute(our_path, "gitlab-language")
end
end
end
def their_lines
strong_memoize(:their_lines) do
- lines.reject { |line| line.type == 'new' }.map(&:text).join("\n")
+ lines.reject { |line| line.type == "new" }.map(&:text).join("\n")
end
end
def our_lines
strong_memoize(:our_lines) do
- lines.reject { |line| line.type == 'old' }.map(&:text).join("\n")
+ lines.reject { |line| line.type == "old" }.map(&:text).join("\n")
end
end
end
diff --git a/lib/gitlab/conflict/file_collection.rb b/lib/gitlab/conflict/file_collection.rb
index 53406af2c4e..b06a9a54584 100644
--- a/lib/gitlab/conflict/file_collection.rb
+++ b/lib/gitlab/conflict/file_collection.rb
@@ -23,7 +23,7 @@ module Gitlab
resolution = Gitlab::Git::Conflict::Resolution.new(user, files, msg)
args = {
source_branch: merge_request.source_branch,
- target_branch: merge_request.target_branch
+ target_branch: merge_request.target_branch,
}
resolver.resolve_conflicts(@source_repo, resolution, args)
ensure
@@ -31,9 +31,9 @@ module Gitlab
end
def files
- @files ||= resolver.conflicts.map do |conflict_file|
+ @files ||= resolver.conflicts.map { |conflict_file|
Gitlab::Conflict::File.new(conflict_file, merge_request: merge_request)
- end
+ }
end
def can_be_resolved_in_ui?
@@ -60,21 +60,21 @@ module Gitlab
source_branch: merge_request.source_branch,
commit_sha: merge_request.diff_head_sha,
commit_message: default_commit_message,
- files: files
+ files: files,
}
end
def default_commit_message
- conflict_filenames = files.map do |conflict|
+ conflict_filenames = files.map { |conflict|
"# #{conflict.our_path}"
- end
+ }
- <<EOM.chomp
-Merge branch '#{merge_request.target_branch}' into '#{merge_request.source_branch}'
+ <<~EOM.chomp
+ Merge branch '#{merge_request.target_branch}' into '#{merge_request.source_branch}'
-# Conflicts:
-#{conflict_filenames.join("\n")}
-EOM
+ # Conflicts:
+ #{conflict_filenames.join("\n")}
+ EOM
end
private
diff --git a/lib/gitlab/content_disposition.rb b/lib/gitlab/content_disposition.rb
index 32207514ce5..934ecf32777 100644
--- a/lib/gitlab/content_disposition.rb
+++ b/lib/gitlab/content_disposition.rb
@@ -1,10 +1,11 @@
# frozen_string_literal: true
+
# This ports ActionDispatch::Http::ContentDisposition (https://github.com/rails/rails/pull/33829,
# which will be available in Rails 6.
module Gitlab
class ContentDisposition # :nodoc:
# Make sure we remove this patch starting with Rails 6.0.
- if Rails.version.start_with?('6.0')
+ if Rails.version.start_with?("6.0")
raise <<~MSG
Please remove this file and use `ActionDispatch::Http::ContentDisposition` instead.
MSG
@@ -39,7 +40,7 @@ module Gitlab
if filename
"#{disposition}; #{ascii_filename}; #{utf8_filename}"
else
- "#{disposition}"
+ disposition.to_s
end
end
diff --git a/lib/gitlab/contributions_calendar.rb b/lib/gitlab/contributions_calendar.rb
index 5ed6427072a..ef5c2bffcc0 100644
--- a/lib/gitlab/contributions_calendar.rb
+++ b/lib/gitlab/contributions_calendar.rb
@@ -10,10 +10,10 @@ module Gitlab
@contributor = contributor
@current_user = current_user
@projects = if @contributor.include_private_contributions?
- ContributedProjectsFinder.new(@contributor).execute(@contributor)
- else
- ContributedProjectsFinder.new(contributor).execute(current_user)
- end
+ ContributedProjectsFinder.new(@contributor).execute(@contributor)
+ else
+ ContributedProjectsFinder.new(contributor).execute(current_user)
+ end
end
# rubocop: disable CodeReuse/ActiveRecord
@@ -36,9 +36,9 @@ module Gitlab
.from_union([repo_events, issue_events, mr_events, note_events])
.map(&:attributes)
- @activity_dates = events.each_with_object(Hash.new {|h, k| h[k] = 0 }) do |event, activities|
+ @activity_dates = events.each_with_object(Hash.new {|h, k| h[k] = 0 }) { |event, activities|
activities[event["date"]] += event["total_amount"]
- end
+ }
end
# rubocop: enable CodeReuse/ActiveRecord
@@ -84,13 +84,13 @@ module Gitlab
.and(t[:author_id].eq(contributor.id))
date_interval = if Gitlab::Database.postgresql?
- "INTERVAL '#{Time.zone.now.utc_offset} seconds'"
- else
- "INTERVAL #{Time.zone.now.utc_offset} SECOND"
- end
+ "INTERVAL '#{Time.zone.now.utc_offset} seconds'"
+ else
+ "INTERVAL #{Time.zone.now.utc_offset} SECOND"
+ end
Event.reorder(nil)
- .select(t[:project_id], t[:target_type], t[:action], "date(created_at + #{date_interval}) AS date", 'count(id) as total_amount')
+ .select(t[:project_id], t[:target_type], t[:action], "date(created_at + #{date_interval}) AS date", "count(id) as total_amount")
.group(t[:project_id], t[:target_type], t[:action], "date(created_at + #{date_interval})")
.where(conditions)
.where("events.project_id in (#{authed_projects.to_sql})") # rubocop:disable GitlabSecurity/SqlInjection
diff --git a/lib/gitlab/correlation_id.rb b/lib/gitlab/correlation_id.rb
index 0f9bde4390e..82e36f8c00d 100644
--- a/lib/gitlab/correlation_id.rb
+++ b/lib/gitlab/correlation_id.rb
@@ -2,7 +2,7 @@
module Gitlab
module CorrelationId
- LOG_KEY = 'correlation_id'.freeze
+ LOG_KEY = "correlation_id"
class << self
def use_id(correlation_id, &blk)
diff --git a/lib/gitlab/cross_project_access.rb b/lib/gitlab/cross_project_access.rb
index 4ddc7e02d1b..e769b03bc71 100644
--- a/lib/gitlab/cross_project_access.rb
+++ b/lib/gitlab/cross_project_access.rb
@@ -4,7 +4,7 @@ module Gitlab
class CrossProjectAccess
class << self
delegate :add_check, :find_check, :checks,
- to: :instance
+ to: :instance
end
def self.instance
@@ -18,17 +18,17 @@ module Gitlab
end
def add_check(
- klass,
- actions: {},
- positive_condition: nil,
- negative_condition: nil,
- skip: false)
+ klass,
+ actions: {},
+ positive_condition: nil,
+ negative_condition: nil,
+ skip: false
+ )
new_check = CheckInfo.new(actions,
- positive_condition,
- negative_condition,
- skip
- )
+ positive_condition,
+ negative_condition,
+ skip)
@checks[klass] ||= Gitlab::CrossProjectAccess::CheckCollection.new
@checks[klass].add_check(new_check)
@@ -38,11 +38,11 @@ module Gitlab
end
def find_check(object)
- @cached_checks ||= Hash.new do |cache, new_class|
+ @cached_checks ||= Hash.new { |cache, new_class|
parent_classes = @checks.keys.select { |existing_class| new_class <= existing_class }
closest_class = closest_parent(parent_classes, new_class)
cache[new_class] = @checks[closest_class]
- end
+ }
@cached_checks[object.class]
end
diff --git a/lib/gitlab/crypto_helper.rb b/lib/gitlab/crypto_helper.rb
index 87a03d9c58f..ae78a17277a 100644
--- a/lib/gitlab/crypto_helper.rb
+++ b/lib/gitlab/crypto_helper.rb
@@ -5,9 +5,9 @@ module Gitlab
extend self
AES256_GCM_OPTIONS = {
- algorithm: 'aes-256-gcm',
+ algorithm: "aes-256-gcm",
key: Settings.attr_encrypted_db_key_base_32,
- iv: Settings.attr_encrypted_db_key_base_12
+ iv: Settings.attr_encrypted_db_key_base_12,
}.freeze
def sha256(value)
diff --git a/lib/gitlab/current_settings.rb b/lib/gitlab/current_settings.rb
index 552aad83dd4..d3a044ae49e 100644
--- a/lib/gitlab/current_settings.rb
+++ b/lib/gitlab/current_settings.rb
@@ -26,7 +26,7 @@ module Gitlab
end
def cached_application_settings
- return in_memory_application_settings if ENV['IN_MEMORY_APPLICATION_SETTINGS'] == 'true'
+ return in_memory_application_settings if ENV["IN_MEMORY_APPLICATION_SETTINGS"] == "true"
begin
::ApplicationSetting.cached
@@ -65,10 +65,14 @@ module Gitlab
def connect_to_db?
# When the DBMS is not available, an exception (e.g. PG::ConnectionBad) is raised
- active_db_connection = ActiveRecord::Base.connection.active? rescue false
+ active_db_connection = begin
+ ActiveRecord::Base.connection.active?
+ rescue
+ false
+ end
active_db_connection &&
- Gitlab::Database.cached_table_exists?('application_settings')
+ Gitlab::Database.cached_table_exists?("application_settings")
rescue ActiveRecord::NoDatabaseError
false
end
diff --git a/lib/gitlab/cycle_analytics/base_event_fetcher.rb b/lib/gitlab/cycle_analytics/base_event_fetcher.rb
index 304d60996a6..0ba1f6bd4c3 100644
--- a/lib/gitlab/cycle_analytics/base_event_fetcher.rb
+++ b/lib/gitlab/cycle_analytics/base_event_fetcher.rb
@@ -18,9 +18,9 @@ module Gitlab
def fetch
update_author!
- event_result.map do |event|
- serialize(event) if has_permission?(event['id'])
- end.compact
+ event_result.map { |event|
+ serialize(event) if has_permission?(event["id"])
+ }.compact
end
def order
@@ -30,9 +30,9 @@ module Gitlab
private
def update_author!
- return unless event_result.any? && event_result.first['author_id']
+ return unless event_result.any? && event_result.first["author_id"]
- Updater.update!(event_result, from: 'author_id', to: 'author', klass: User)
+ Updater.update!(event_result, from: "author_id", to: "author", klass: User)
end
def event_result
@@ -42,7 +42,7 @@ module Gitlab
def events_query
diff_fn = subtract_datetimes_diff(base_query, @options[:start_time_attrs], @options[:end_time_attrs])
- base_query.project(extract_diff_epoch(diff_fn).as('total_time'), *projections).order(order.desc).take(MAX_EVENTS)
+ base_query.project(extract_diff_epoch(diff_fn).as("total_time"), *projections).order(order.desc).take(MAX_EVENTS)
end
def default_order
@@ -50,7 +50,7 @@ module Gitlab
end
def serialize(_event)
- raise NotImplementedError.new("Expected #{self.name} to implement serialize(event)")
+ raise NotImplementedError.new("Expected #{name} to implement serialize(event)")
end
def has_permission?(id)
@@ -64,7 +64,7 @@ module Gitlab
end
def event_result_ids
- event_result.map { |event| event['id'] }
+ event_result.map { |event| event["id"] }
end
end
end
diff --git a/lib/gitlab/cycle_analytics/base_stage.rb b/lib/gitlab/cycle_analytics/base_stage.rb
index e2d6a301734..b39d2924c8e 100644
--- a/lib/gitlab/cycle_analytics/base_stage.rb
+++ b/lib/gitlab/cycle_analytics/base_stage.rb
@@ -19,7 +19,7 @@ module Gitlab
end
def title
- raise NotImplementedError.new("Expected #{self.name} to implement title")
+ raise NotImplementedError.new("Expected #{name} to implement title")
end
def median
@@ -48,7 +48,7 @@ module Gitlab
end
def name
- raise NotImplementedError.new("Expected #{self.name} to implement name")
+ raise NotImplementedError.new("Expected #{name} to implement name")
end
private
diff --git a/lib/gitlab/cycle_analytics/code_event_fetcher.rb b/lib/gitlab/cycle_analytics/code_event_fetcher.rb
index 591db3c35e6..44115d4cb9a 100644
--- a/lib/gitlab/cycle_analytics/code_event_fetcher.rb
+++ b/lib/gitlab/cycle_analytics/code_event_fetcher.rb
@@ -9,7 +9,7 @@ module Gitlab
mr_table[:id],
mr_table[:created_at],
mr_table[:state],
- mr_table[:author_id]]
+ mr_table[:author_id],]
@order = mr_table[:created_at]
super(*args)
diff --git a/lib/gitlab/cycle_analytics/code_stage.rb b/lib/gitlab/cycle_analytics/code_stage.rb
index 2e5f9ef5a40..ead01d1317a 100644
--- a/lib/gitlab/cycle_analytics/code_stage.rb
+++ b/lib/gitlab/cycle_analytics/code_stage.rb
@@ -16,7 +16,7 @@ module Gitlab
end
def title
- s_('CycleAnalyticsStage|Code')
+ s_("CycleAnalyticsStage|Code")
end
def legend
diff --git a/lib/gitlab/cycle_analytics/issue_event_fetcher.rb b/lib/gitlab/cycle_analytics/issue_event_fetcher.rb
index 30c6ead8968..875841cc5d7 100644
--- a/lib/gitlab/cycle_analytics/issue_event_fetcher.rb
+++ b/lib/gitlab/cycle_analytics/issue_event_fetcher.rb
@@ -8,7 +8,7 @@ module Gitlab
issue_table[:iid],
issue_table[:id],
issue_table[:created_at],
- issue_table[:author_id]]
+ issue_table[:author_id],]
super(*args)
end
diff --git a/lib/gitlab/cycle_analytics/issue_stage.rb b/lib/gitlab/cycle_analytics/issue_stage.rb
index 4eae2da512c..d5059f06647 100644
--- a/lib/gitlab/cycle_analytics/issue_stage.rb
+++ b/lib/gitlab/cycle_analytics/issue_stage.rb
@@ -9,7 +9,7 @@ module Gitlab
def end_time_attrs
@end_time_attrs ||= [issue_metrics_table[:first_associated_with_milestone_at],
- issue_metrics_table[:first_added_to_board_at]]
+ issue_metrics_table[:first_added_to_board_at],]
end
def name
@@ -17,7 +17,7 @@ module Gitlab
end
def title
- s_('CycleAnalyticsStage|Issue')
+ s_("CycleAnalyticsStage|Issue")
end
def legend
diff --git a/lib/gitlab/cycle_analytics/permissions.rb b/lib/gitlab/cycle_analytics/permissions.rb
index afefd09b614..30bd6e8c0d7 100644
--- a/lib/gitlab/cycle_analytics/permissions.rb
+++ b/lib/gitlab/cycle_analytics/permissions.rb
@@ -9,7 +9,7 @@ module Gitlab
test: :read_build,
review: :read_merge_request,
staging: :read_build,
- production: :read_issue
+ production: :read_issue,
}.freeze
def self.get(*args)
diff --git a/lib/gitlab/cycle_analytics/plan_event_fetcher.rb b/lib/gitlab/cycle_analytics/plan_event_fetcher.rb
index db8ac3becea..002abe9e089 100644
--- a/lib/gitlab/cycle_analytics/plan_event_fetcher.rb
+++ b/lib/gitlab/cycle_analytics/plan_event_fetcher.rb
@@ -5,7 +5,7 @@ module Gitlab
class PlanEventFetcher < BaseEventFetcher
def initialize(*args)
@projections = [mr_diff_table[:id],
- issue_metrics_table[:first_mentioned_in_commit_at]]
+ issue_metrics_table[:first_mentioned_in_commit_at],]
super(*args)
end
@@ -27,7 +27,7 @@ module Gitlab
def merge_request_diff_commits
@merge_request_diff_commits ||=
MergeRequestDiffCommit
- .where(merge_request_diff_id: event_result.map { |event| event['id'] })
+ .where(merge_request_diff_id: event_result.map { |event| event["id"] })
.group_by(&:merge_request_diff_id)
end
@@ -42,21 +42,21 @@ module Gitlab
def first_time_reference_commit(event)
return nil unless event && merge_request_diff_commits
- commits = merge_request_diff_commits[event['id'].to_i]
+ commits = merge_request_diff_commits[event["id"].to_i]
return nil if commits.blank?
commits.find do |commit|
- next unless commit[:committed_date] && event['first_mentioned_in_commit_at']
+ next unless commit[:committed_date] && event["first_mentioned_in_commit_at"]
- commit[:committed_date].to_i == DateTime.parse(event['first_mentioned_in_commit_at'].to_s).to_i
+ commit[:committed_date].to_i == DateTime.parse(event["first_mentioned_in_commit_at"].to_s).to_i
end
end
def serialize_commit(event, commit, query)
commit = Commit.from_hash(commit.to_hash, @project)
- AnalyticsCommitSerializer.new(project: @project, total_time: event['total_time']).represent(commit)
+ AnalyticsCommitSerializer.new(project: @project, total_time: event["total_time"]).represent(commit)
end
end
end
diff --git a/lib/gitlab/cycle_analytics/plan_stage.rb b/lib/gitlab/cycle_analytics/plan_stage.rb
index 513e4575be0..19a7f2860cb 100644
--- a/lib/gitlab/cycle_analytics/plan_stage.rb
+++ b/lib/gitlab/cycle_analytics/plan_stage.rb
@@ -5,7 +5,7 @@ module Gitlab
class PlanStage < BaseStage
def start_time_attrs
@start_time_attrs ||= [issue_metrics_table[:first_associated_with_milestone_at],
- issue_metrics_table[:first_added_to_board_at]]
+ issue_metrics_table[:first_added_to_board_at],]
end
def end_time_attrs
@@ -17,7 +17,7 @@ module Gitlab
end
def title
- s_('CycleAnalyticsStage|Plan')
+ s_("CycleAnalyticsStage|Plan")
end
def legend
diff --git a/lib/gitlab/cycle_analytics/production_stage.rb b/lib/gitlab/cycle_analytics/production_stage.rb
index 6fd7214dce7..07d1094372a 100644
--- a/lib/gitlab/cycle_analytics/production_stage.rb
+++ b/lib/gitlab/cycle_analytics/production_stage.rb
@@ -18,7 +18,7 @@ module Gitlab
end
def title
- s_('CycleAnalyticsStage|Production')
+ s_("CycleAnalyticsStage|Production")
end
def legend
diff --git a/lib/gitlab/cycle_analytics/review_event_fetcher.rb b/lib/gitlab/cycle_analytics/review_event_fetcher.rb
index de100295281..9c28c64fe82 100644
--- a/lib/gitlab/cycle_analytics/review_event_fetcher.rb
+++ b/lib/gitlab/cycle_analytics/review_event_fetcher.rb
@@ -9,7 +9,7 @@ module Gitlab
mr_table[:id],
mr_table[:created_at],
mr_table[:state],
- mr_table[:author_id]]
+ mr_table[:author_id],]
super(*args)
end
diff --git a/lib/gitlab/cycle_analytics/review_stage.rb b/lib/gitlab/cycle_analytics/review_stage.rb
index 294b656bc55..e92b1b22d44 100644
--- a/lib/gitlab/cycle_analytics/review_stage.rb
+++ b/lib/gitlab/cycle_analytics/review_stage.rb
@@ -16,7 +16,7 @@ module Gitlab
end
def title
- s_('CycleAnalyticsStage|Review')
+ s_("CycleAnalyticsStage|Review")
end
def legend
diff --git a/lib/gitlab/cycle_analytics/stage_summary.rb b/lib/gitlab/cycle_analytics/stage_summary.rb
index 5198dd5b4eb..855a8d4ef8a 100644
--- a/lib/gitlab/cycle_analytics/stage_summary.rb
+++ b/lib/gitlab/cycle_analytics/stage_summary.rb
@@ -12,7 +12,7 @@ module Gitlab
def data
[serialize(Summary::Issue.new(project: @project, from: @from, current_user: @current_user)),
serialize(Summary::Commit.new(project: @project, from: @from)),
- serialize(Summary::Deploy.new(project: @project, from: @from))]
+ serialize(Summary::Deploy.new(project: @project, from: @from)),]
end
private
diff --git a/lib/gitlab/cycle_analytics/staging_event_fetcher.rb b/lib/gitlab/cycle_analytics/staging_event_fetcher.rb
index 70ce82383b3..606c56d471b 100644
--- a/lib/gitlab/cycle_analytics/staging_event_fetcher.rb
+++ b/lib/gitlab/cycle_analytics/staging_event_fetcher.rb
@@ -11,7 +11,7 @@ module Gitlab
end
def fetch
- Updater.update!(event_result, from: 'id', to: 'build', klass: ::Ci::Build)
+ Updater.update!(event_result, from: "id", to: "build", klass: ::Ci::Build)
super
end
@@ -29,7 +29,7 @@ module Gitlab
end
def serialize(event)
- AnalyticsBuildSerializer.new.represent(event['build'])
+ AnalyticsBuildSerializer.new.represent(event["build"])
end
end
end
diff --git a/lib/gitlab/cycle_analytics/staging_stage.rb b/lib/gitlab/cycle_analytics/staging_stage.rb
index dbc2414ff66..448375cfed1 100644
--- a/lib/gitlab/cycle_analytics/staging_stage.rb
+++ b/lib/gitlab/cycle_analytics/staging_stage.rb
@@ -17,7 +17,7 @@ module Gitlab
end
def title
- s_('CycleAnalyticsStage|Staging')
+ s_("CycleAnalyticsStage|Staging")
end
def legend
diff --git a/lib/gitlab/cycle_analytics/summary/base.rb b/lib/gitlab/cycle_analytics/summary/base.rb
index 709221c648e..9ff8bccfa81 100644
--- a/lib/gitlab/cycle_analytics/summary/base.rb
+++ b/lib/gitlab/cycle_analytics/summary/base.rb
@@ -10,11 +10,11 @@ module Gitlab
end
def title
- raise NotImplementedError.new("Expected #{self.name} to implement title")
+ raise NotImplementedError.new("Expected #{name} to implement title")
end
def value
- raise NotImplementedError.new("Expected #{self.name} to implement value")
+ raise NotImplementedError.new("Expected #{name} to implement value")
end
end
end
diff --git a/lib/gitlab/cycle_analytics/summary/commit.rb b/lib/gitlab/cycle_analytics/summary/commit.rb
index f0019b26fa2..d74f75d7d9b 100644
--- a/lib/gitlab/cycle_analytics/summary/commit.rb
+++ b/lib/gitlab/cycle_analytics/summary/commit.rb
@@ -5,7 +5,7 @@ module Gitlab
module Summary
class Commit < Base
def title
- n_('Commit', 'Commits', value)
+ n_("Commit", "Commits", value)
end
def value
diff --git a/lib/gitlab/cycle_analytics/summary/deploy.rb b/lib/gitlab/cycle_analytics/summary/deploy.rb
index 3b56dc2a7bc..1b277545e0e 100644
--- a/lib/gitlab/cycle_analytics/summary/deploy.rb
+++ b/lib/gitlab/cycle_analytics/summary/deploy.rb
@@ -5,7 +5,7 @@ module Gitlab
module Summary
class Deploy < Base
def title
- n_('Deploy', 'Deploys', value)
+ n_("Deploy", "Deploys", value)
end
def value
diff --git a/lib/gitlab/cycle_analytics/summary/issue.rb b/lib/gitlab/cycle_analytics/summary/issue.rb
index 51695c86192..c7bfa55ad7f 100644
--- a/lib/gitlab/cycle_analytics/summary/issue.rb
+++ b/lib/gitlab/cycle_analytics/summary/issue.rb
@@ -11,7 +11,7 @@ module Gitlab
end
def title
- n_('New Issue', 'New Issues', value)
+ n_("New Issue", "New Issues", value)
end
def value
diff --git a/lib/gitlab/cycle_analytics/test_stage.rb b/lib/gitlab/cycle_analytics/test_stage.rb
index c31b664148b..52eae88ae34 100644
--- a/lib/gitlab/cycle_analytics/test_stage.rb
+++ b/lib/gitlab/cycle_analytics/test_stage.rb
@@ -16,7 +16,7 @@ module Gitlab
end
def title
- s_('CycleAnalyticsStage|Test')
+ s_("CycleAnalyticsStage|Test")
end
def legend
diff --git a/lib/gitlab/cycle_analytics/updater.rb b/lib/gitlab/cycle_analytics/updater.rb
index c642809a792..68df5a4ea06 100644
--- a/lib/gitlab/cycle_analytics/updater.rb
+++ b/lib/gitlab/cycle_analytics/updater.rb
@@ -25,7 +25,7 @@ module Gitlab
end
def items
- @items ||= @klass.find(result_ids).group_by { |item| item['id'] }
+ @items ||= @klass.find(result_ids).group_by { |item| item["id"] }
end
end
end
diff --git a/lib/gitlab/cycle_analytics/usage_data.rb b/lib/gitlab/cycle_analytics/usage_data.rb
index 913ee373f54..dd6c20539f8 100644
--- a/lib/gitlab/cycle_analytics/usage_data.rb
+++ b/lib/gitlab/cycle_analytics/usage_data.rb
@@ -9,23 +9,23 @@ module Gitlab
def initialize
@projects = Project.sorted_by_activity.limit(PROJECTS_LIMIT)
- @options = { from: 7.days.ago }
+ @options = {from: 7.days.ago}
end
def to_json
total = 0
values =
- medians_per_stage.each_with_object({}) do |(stage_name, medians), hsh|
+ medians_per_stage.each_with_object({}) { |(stage_name, medians), hsh|
calculations = stage_values(medians)
total += calculations.values.compact.sum
hsh[stage_name] = calculations
- end
+ }
values[:total] = total
- { avg_cycle_analytics: values }
+ {avg_cycle_analytics: values}
end
private
@@ -46,7 +46,7 @@ module Gitlab
{
average: average,
sd: standard_deviation(medians, average),
- missing: projects.length - medians.length
+ missing: projects.length - medians.length,
}
end
@@ -63,9 +63,9 @@ module Gitlab
def sample_variance(values, average)
return 0 if values.length <= 1
- sum = values.inject(0) do |acc, val|
+ sum = values.inject(0) { |acc, val|
acc + (val - average)**2
- end
+ }
sum / (values.length - 1)
end
diff --git a/lib/gitlab/danger/helper.rb b/lib/gitlab/danger/helper.rb
index d2b7ca015d4..b1e7b781738 100644
--- a/lib/gitlab/danger/helper.rb
+++ b/lib/gitlab/danger/helper.rb
@@ -1,13 +1,14 @@
# frozen_string_literal: true
-require 'net/http'
-require 'json'
-require_relative 'teammate'
+require "net/http"
+require "json"
+
+require_relative "teammate"
module Gitlab
module Danger
module Helper
- ROULETTE_DATA_URL = URI.parse('https://about.gitlab.com/roulette.json').freeze
+ ROULETTE_DATA_URL = URI.parse("https://about.gitlab.com/roulette.json").freeze
# Returns a list of all files that have been added, modified or renamed.
# `git.modified_files` might contain paths that already have been renamed,
@@ -37,11 +38,11 @@ module Gitlab
end
def ee?
- ENV['CI_PROJECT_NAME'] == 'gitlab-ee' || File.exist?('../../CHANGELOG-EE.md')
+ ENV["CI_PROJECT_NAME"] == "gitlab-ee" || File.exist?("../../CHANGELOG-EE.md")
end
def project_name
- ee? ? 'gitlab-ee' : 'gitlab-ce'
+ ee? ? "gitlab-ee" : "gitlab-ce"
end
# Looks up the current list of GitLab team members and parses it into a
@@ -96,7 +97,7 @@ module Gitlab
CATEGORY_LABELS = {
docs: "~Documentation",
none: "",
- qa: "~QA"
+ qa: "~QA",
}.freeze
# rubocop:disable Style/RegexpLiteral
@@ -128,7 +129,7 @@ module Gitlab
# Fallbacks in case the above patterns miss anything
%r{\.rb\z} => :backend,
%r{\.(md|txt)\z} => :docs,
- %r{\.js\z} => :frontend
+ %r{\.js\z} => :frontend,
}.freeze
# rubocop:enable Style/RegexpLiteral
end
diff --git a/lib/gitlab/danger/teammate.rb b/lib/gitlab/danger/teammate.rb
index 4b822aa86c5..cc9cba4ad98 100644
--- a/lib/gitlab/danger/teammate.rb
+++ b/lib/gitlab/danger/teammate.rb
@@ -6,9 +6,9 @@ module Gitlab
attr_reader :name, :username, :projects
def initialize(options = {})
- @name = options['name']
- @username = options['username']
- @projects = options['projects']
+ @name = options["name"]
+ @username = options["username"]
+ @projects = options["projects"]
end
def markdown_name
@@ -16,7 +16,7 @@ module Gitlab
end
def in_project?(name)
- projects&.has_key?(name)
+ projects&.key?(name)
end
# Traintainers also count as reviewers
@@ -35,7 +35,7 @@ module Gitlab
private
def capabilities(project)
- projects.fetch(project, '')
+ projects.fetch(project, "")
end
end
end
diff --git a/lib/gitlab/data_builder/build.rb b/lib/gitlab/data_builder/build.rb
index 3407380127e..4fc7c92bf71 100644
--- a/lib/gitlab/data_builder/build.rb
+++ b/lib/gitlab/data_builder/build.rb
@@ -13,7 +13,7 @@ module Gitlab
author_url = build_author_url(build.commit, commit)
data = {
- object_kind: 'build',
+ object_kind: "build",
ref: build.ref,
tag: build.tag,
@@ -39,7 +39,7 @@ module Gitlab
user: {
id: user.try(:id),
name: user.try(:name),
- email: user.try(:email)
+ email: user.try(:email),
},
commit: {
@@ -52,7 +52,7 @@ module Gitlab
status: commit.status,
duration: commit.duration,
started_at: commit.started_at,
- finished_at: commit.finished_at
+ finished_at: commit.finished_at,
},
repository: {
@@ -62,8 +62,8 @@ module Gitlab
homepage: project.web_url,
git_http_url: project.http_url_to_repo,
git_ssh_url: project.ssh_url_to_repo,
- visibility_level: project.visibility_level
- }
+ visibility_level: project.visibility_level,
+ },
}
data
diff --git a/lib/gitlab/data_builder/note.rb b/lib/gitlab/data_builder/note.rb
index 65601dcdf31..4134eac500e 100644
--- a/lib/gitlab/data_builder/note.rb
+++ b/lib/gitlab/data_builder/note.rb
@@ -54,7 +54,7 @@ module Gitlab
end
def build_base_data(project, user, note)
- event_type = note.confidential? ? 'confidential_note' : 'note'
+ event_type = note.confidential? ? "confidential_note" : "note"
base_data = {
object_kind: "note",
@@ -64,7 +64,7 @@ module Gitlab
project: project.hook_attrs,
object_attributes: note.hook_attrs,
# DEPRECATED
- repository: project.hook_attrs.slice(:name, :url, :description, :homepage)
+ repository: project.hook_attrs.slice(:name, :url, :description, :homepage),
}
base_data[:object_attributes][:url] = Gitlab::UrlBuilder.build(note)
diff --git a/lib/gitlab/data_builder/pipeline.rb b/lib/gitlab/data_builder/pipeline.rb
index 76c8b4ec5c2..7167edfd9d1 100644
--- a/lib/gitlab/data_builder/pipeline.rb
+++ b/lib/gitlab/data_builder/pipeline.rb
@@ -7,12 +7,12 @@ module Gitlab
def build(pipeline)
{
- object_kind: 'pipeline',
+ object_kind: "pipeline",
object_attributes: hook_attrs(pipeline),
user: pipeline.user.try(:hook_attrs),
project: pipeline.project.hook_attrs(backward: false),
commit: pipeline.commit.try(:hook_attrs),
- builds: pipeline.builds.map(&method(:build_hook_attrs))
+ builds: pipeline.builds.map(&method(:build_hook_attrs)),
}
end
@@ -29,7 +29,7 @@ module Gitlab
created_at: pipeline.created_at,
finished_at: pipeline.finished_at,
duration: pipeline.duration,
- variables: pipeline.variables.map(&:hook_attrs)
+ variables: pipeline.variables.map(&:hook_attrs),
}
end
@@ -48,8 +48,8 @@ module Gitlab
runner: build.runner && runner_hook_attrs(build.runner),
artifacts_file: {
filename: build.artifacts_file.filename,
- size: build.artifacts_size
- }
+ size: build.artifacts_size,
+ },
}
end
@@ -58,7 +58,7 @@ module Gitlab
id: runner.id,
description: runner.description,
active: runner.active?,
- is_shared: runner.instance_type?
+ is_shared: runner.instance_type?,
}
end
end
diff --git a/lib/gitlab/data_builder/push.rb b/lib/gitlab/data_builder/push.rb
index ea08b5f7eae..1b7d783c945 100644
--- a/lib/gitlab/data_builder/push.rb
+++ b/lib/gitlab/data_builder/push.rb
@@ -27,15 +27,15 @@ module Gitlab
url: "https://test.example.com/gitlab/gitlabhq/commit/c5feabde2d8cd023215af4d2ceeb7a64839fc428",
author: {
name: "Test User",
- email: "test@example.com"
- }
- }
+ email: "test@example.com",
+ },
+ },
],
total_commits_count: 1,
push_options: [
"ci.skip",
- "custom option"
- ]
+ "custom option",
+ ],
}.freeze
# Produce a hash of post-receive data
@@ -73,13 +73,13 @@ module Gitlab
# For performance purposes maximum 20 latest commits
# will be passed as post receive hook data.
# n+1: https://gitlab.com/gitlab-org/gitlab-ce/issues/38259
- commit_attrs = Gitlab::GitalyClient.allow_n_plus_1_calls do
+ commit_attrs = Gitlab::GitalyClient.allow_n_plus_1_calls {
commits_limited.map do |commit|
commit.hook_attrs(with_changed_files: true)
end
- end
+ }
- type = Gitlab::Git.tag_ref?(ref) ? 'tag_push' : 'push'
+ type = Gitlab::Git.tag_ref?(ref) ? "tag_push" : "push"
# Hash to be passed as post_receive_data
{
@@ -102,7 +102,7 @@ module Gitlab
push_options: push_options,
# DEPRECATED
repository: project.hook_attrs.slice(:name, :url, :description, :homepage,
- :git_http_url, :git_ssh_url, :visibility_level)
+ :git_http_url, :git_ssh_url, :visibility_level),
}
end
diff --git a/lib/gitlab/data_builder/repository.rb b/lib/gitlab/data_builder/repository.rb
index 0e627fd623e..0823b12ef0d 100644
--- a/lib/gitlab/data_builder/repository.rb
+++ b/lib/gitlab/data_builder/repository.rb
@@ -6,26 +6,26 @@ module Gitlab
extend self
SAMPLE_DATA = {
- event_name: 'repository_update',
+ event_name: "repository_update",
user_id: 10,
- user_name: 'john.doe',
- user_email: 'test@example.com',
- user_avatar: 'http://example.com/avatar/user.png',
+ user_name: "john.doe",
+ user_email: "test@example.com",
+ user_avatar: "http://example.com/avatar/user.png",
project_id: 40,
changes: [
{
before: "8205ea8d81ce0c6b90fbe8280d118cc9fdad6130",
after: "4045ea7a3df38697b3730a20fb73c8bed8a3e69e",
- ref: "refs/heads/master"
- }
+ ref: "refs/heads/master",
+ },
],
- "refs": ["refs/heads/master"]
+ "refs": ["refs/heads/master"],
}.freeze
# Produce a hash of post-receive data
def update(project, user, changes, refs)
{
- event_name: 'repository_update',
+ event_name: "repository_update",
user_id: user.id,
user_name: user.name,
@@ -37,7 +37,7 @@ module Gitlab
changes: changes,
- refs: refs
+ refs: refs,
}
end
@@ -46,7 +46,7 @@ module Gitlab
{
before: oldrev,
after: newrev,
- ref: ref
+ ref: ref,
}
end
diff --git a/lib/gitlab/data_builder/wiki_page.rb b/lib/gitlab/data_builder/wiki_page.rb
index 9368446fa59..4ae9236665e 100644
--- a/lib/gitlab/data_builder/wiki_page.rb
+++ b/lib/gitlab/data_builder/wiki_page.rb
@@ -16,7 +16,7 @@ module Gitlab
object_attributes: wiki_page.hook_attrs.merge(
url: Gitlab::UrlBuilder.build(wiki_page),
action: action
- )
+ ),
}
end
end
diff --git a/lib/gitlab/database.rb b/lib/gitlab/database.rb
index b6ca777e029..05c97c54a95 100644
--- a/lib/gitlab/database.rb
+++ b/lib/gitlab/database.rb
@@ -16,23 +16,23 @@ module Gitlab
end
def self.username
- config['username'] || ENV['USER']
+ config["username"] || ENV["USER"]
end
def self.database_name
- config['database']
+ config["database"]
end
def self.adapter_name
- config['adapter']
+ config["adapter"]
end
def self.mysql?
- adapter_name.casecmp('mysql2').zero?
+ adapter_name.casecmp("mysql2").zero?
end
def self.postgresql?
- adapter_name.casecmp('postgresql').zero?
+ adapter_name.casecmp("postgresql").zero?
end
def self.read_only?
@@ -40,15 +40,15 @@ module Gitlab
end
def self.read_write?
- !self.read_only?
+ !read_only?
end
# Check whether the underlying database is in read-only mode
def self.db_read_only?
if postgresql?
pg_is_in_recovery =
- ActiveRecord::Base.connection.execute('SELECT pg_is_in_recovery()')
- .first.fetch('pg_is_in_recovery')
+ ActiveRecord::Base.connection.execute("SELECT pg_is_in_recovery()")
+ .first.fetch("pg_is_in_recovery")
Gitlab::Utils.to_boolean(pg_is_in_recovery)
else
@@ -57,7 +57,7 @@ module Gitlab
end
def self.db_read_write?
- !self.db_read_only?
+ !db_read_only?
end
def self.version
@@ -83,22 +83,22 @@ module Gitlab
# map some of the function names that changed between PostgreSQL 9 and 10
# https://wiki.postgresql.org/wiki/New_in_postgres_10
def self.pg_wal_lsn_diff
- Gitlab::Database.postgresql_9_or_less? ? 'pg_xlog_location_diff' : 'pg_wal_lsn_diff'
+ Gitlab::Database.postgresql_9_or_less? ? "pg_xlog_location_diff" : "pg_wal_lsn_diff"
end
def self.pg_current_wal_insert_lsn
- Gitlab::Database.postgresql_9_or_less? ? 'pg_current_xlog_insert_location' : 'pg_current_wal_insert_lsn'
+ Gitlab::Database.postgresql_9_or_less? ? "pg_current_xlog_insert_location" : "pg_current_wal_insert_lsn"
end
def self.pg_last_wal_receive_lsn
- Gitlab::Database.postgresql_9_or_less? ? 'pg_last_xlog_receive_location' : 'pg_last_wal_receive_lsn'
+ Gitlab::Database.postgresql_9_or_less? ? "pg_last_xlog_receive_location" : "pg_last_wal_receive_lsn"
end
def self.pg_last_wal_replay_lsn
- Gitlab::Database.postgresql_9_or_less? ? 'pg_last_xlog_replay_location' : 'pg_last_wal_replay_lsn'
+ Gitlab::Database.postgresql_9_or_less? ? "pg_last_xlog_replay_location" : "pg_last_wal_replay_lsn"
end
- def self.nulls_last_order(field, direction = 'ASC')
+ def self.nulls_last_order(field, direction = "ASC")
order = "#{field} #{direction}"
if postgresql?
@@ -106,13 +106,13 @@ module Gitlab
else
# `field IS NULL` will be `0` for non-NULL columns and `1` for NULL
# columns. In the (default) ascending order, `0` comes first.
- order = "#{field} IS NULL, #{order}" if direction == 'ASC'
+ order = "#{field} IS NULL, #{order}" if direction == "ASC"
end
order
end
- def self.nulls_first_order(field, direction = 'ASC')
+ def self.nulls_first_order(field, direction = "ASC")
order = "#{field} #{direction}"
if postgresql?
@@ -120,7 +120,7 @@ module Gitlab
else
# `field IS NULL` will be `0` for non-NULL columns and `1` for NULL
# columns. In the (default) ascending order, `0` comes first.
- order = "#{field} IS NULL, #{order}" if direction == 'DESC'
+ order = "#{field} IS NULL, #{order}" if direction == "DESC"
end
order
@@ -175,15 +175,15 @@ module Gitlab
return_ids = false if mysql?
disable_quote = Array(disable_quote).to_set
- tuples = rows.map do |row|
+ tuples = rows.map { |row|
keys.map do |k|
disable_quote.include?(k) ? row[k] : connection.quote(row[k])
end
- end
+ }
sql = <<-EOF
- INSERT INTO #{table} (#{columns.join(', ')})
- VALUES #{tuples.map { |tuple| "(#{tuple.join(', ')})" }.join(', ')}
+ INSERT INTO #{table} (#{columns.join(", ")})
+ VALUES #{tuples.map { |tuple| "(#{tuple.join(", ")})" }.join(", ")}
EOF
if return_ids
@@ -210,8 +210,8 @@ module Gitlab
env = Rails.env
original_config = ActiveRecord::Base.configurations
- env_config = original_config[env].merge('pool' => pool_size)
- env_config['host'] = host if host
+ env_config = original_config[env].merge("pool" => pool_size)
+ env_config["host"] = host if host
config = original_config.merge(env => env_config)
@@ -228,7 +228,7 @@ module Gitlab
end
def self.cached_column_exists?(table_name, column_name)
- connection.schema_cache.columns_hash(table_name).has_key?(column_name.to_s)
+ connection.schema_cache.columns_hash(table_name).key?(column_name.to_s)
end
def self.cached_table_exists?(table_name)
@@ -241,7 +241,7 @@ module Gitlab
row = connection.execute("SELECT VERSION()").first
if postgresql?
- row['version']
+ row["version"]
else
row.first
end
@@ -250,13 +250,13 @@ module Gitlab
private_class_method :database_version
def self.add_post_migrate_path_to_rails(force: false)
- return if ENV['SKIP_POST_DEPLOYMENT_MIGRATIONS'] && !force
+ return if ENV["SKIP_POST_DEPLOYMENT_MIGRATIONS"] && !force
- Rails.application.config.paths['db'].each do |db_path|
- path = Rails.root.join(db_path, 'post_migrate').to_s
+ Rails.application.config.paths["db"].each do |db_path|
+ path = Rails.root.join(db_path, "post_migrate").to_s
- unless Rails.application.config.paths['db/migrate'].include? path
- Rails.application.config.paths['db/migrate'] << path
+ unless Rails.application.config.paths["db/migrate"].include? path
+ Rails.application.config.paths["db/migrate"] << path
# Rails memoizes migrations at certain points where it won't read the above
# path just yet. As such we must also update the following list of paths.
diff --git a/lib/gitlab/database/count.rb b/lib/gitlab/database/count.rb
index f3d37ccd72a..a4831aa677b 100644
--- a/lib/gitlab/database/count.rb
+++ b/lib/gitlab/database/count.rb
@@ -15,12 +15,12 @@ module Gitlab
[
ActionView::Template::Error,
ActiveRecord::StatementInvalid,
- PG::Error
+ PG::Error,
].freeze
else
[
ActionView::Template::Error,
- ActiveRecord::StatementInvalid
+ ActiveRecord::StatementInvalid,
].freeze
end
diff --git a/lib/gitlab/database/count/reltuples_count_strategy.rb b/lib/gitlab/database/count/reltuples_count_strategy.rb
index c3a674aeb7e..269d6e96428 100644
--- a/lib/gitlab/database/count/reltuples_count_strategy.rb
+++ b/lib/gitlab/database/count/reltuples_count_strategy.rb
@@ -4,7 +4,7 @@ module Gitlab
module Database
module Count
class PgClass < ActiveRecord::Base
- self.table_name = 'pg_class'
+ self.table_name = "pg_class"
end
# This strategy counts based on PostgreSQL's statistics in pg_stat_user_tables.
@@ -64,11 +64,11 @@ module Gitlab
query = PgClass.joins("LEFT JOIN pg_stat_user_tables USING (relname)")
.where(relname: table_names)
- .select('pg_class.relname AS table_name, reltuples::bigint AS estimate')
+ .select("pg_class.relname AS table_name, reltuples::bigint AS estimate")
if check_statistics
- query = query.where('last_vacuum > ? OR last_autovacuum > ? OR last_analyze > ? OR last_autoanalyze > ?',
- time, time, time, time)
+ query = query.where("last_vacuum > ? OR last_autovacuum > ? OR last_analyze > ? OR last_autoanalyze > ?",
+ time, time, time, time)
end
query
diff --git a/lib/gitlab/database/count/tablesample_count_strategy.rb b/lib/gitlab/database/count/tablesample_count_strategy.rb
index cf1cf054dbf..43272396650 100644
--- a/lib/gitlab/database/count/tablesample_count_strategy.rb
+++ b/lib/gitlab/database/count/tablesample_count_strategy.rb
@@ -58,7 +58,7 @@ module Gitlab
rows = ActiveRecord::Base.connection.select_all(query)
- Integer(rows.first['count'])
+ Integer(rows.first["count"])
end
end
end
diff --git a/lib/gitlab/database/date_time.rb b/lib/gitlab/database/date_time.rb
index 79d2caff151..b2d349fd2bf 100644
--- a/lib/gitlab/database/date_time.rb
+++ b/lib/gitlab/database/date_time.rb
@@ -19,13 +19,15 @@ module Gitlab
if Gitlab::Database.postgresql?
Arel::Nodes::Subtraction.new(
Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(end_time_attrs)),
- Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(start_time_attrs)))
+ Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(start_time_attrs))
+ )
elsif Gitlab::Database.mysql?
Arel::Nodes::NamedFunction.new(
"TIMESTAMPDIFF",
- [Arel.sql('second'),
+ [Arel.sql("second"),
Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(start_time_attrs)),
- Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(end_time_attrs))])
+ Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(end_time_attrs)),]
+ )
end
end
end
diff --git a/lib/gitlab/database/grant.rb b/lib/gitlab/database/grant.rb
index 862ab96c887..5915d6c5688 100644
--- a/lib/gitlab/database/grant.rb
+++ b/lib/gitlab/database/grant.rb
@@ -8,9 +8,9 @@ module Gitlab
self.table_name =
if Database.postgresql?
- 'information_schema.role_table_grants'
+ "information_schema.role_table_grants"
else
- 'information_schema.schema_privileges'
+ "information_schema.schema_privileges"
end
# Returns true if the current user can create and execute triggers on the
@@ -35,18 +35,18 @@ module Gitlab
else
queries = [
Grant.select(1)
- .from('information_schema.user_privileges')
+ .from("information_schema.user_privileges")
.where("PRIVILEGE_TYPE = 'SUPER'")
.where("GRANTEE = CONCAT('\\'', REPLACE(CURRENT_USER(), '@', '\\'@\\''), '\\'')"),
Grant.select(1)
- .from('information_schema.schema_privileges')
+ .from("information_schema.schema_privileges")
.where("PRIVILEGE_TYPE = 'TRIGGER'")
- .where('TABLE_SCHEMA = ?', Gitlab::Database.database_name)
- .where("GRANTEE = CONCAT('\\'', REPLACE(CURRENT_USER(), '@', '\\'@\\''), '\\'')")
+ .where("TABLE_SCHEMA = ?", Gitlab::Database.database_name)
+ .where("GRANTEE = CONCAT('\\'', REPLACE(CURRENT_USER(), '@', '\\'@\\''), '\\'')"),
]
- Grant.from_union(queries, alias_as: 'privs').any?
+ Grant.from_union(queries, alias_as: "privs").any?
end
end
end
diff --git a/lib/gitlab/database/median.rb b/lib/gitlab/database/median.rb
index 1455e410d4b..09ec6a0709e 100644
--- a/lib/gitlab/database/median.rb
+++ b/lib/gitlab/database/median.rb
@@ -20,7 +20,7 @@ module Gitlab
if Gitlab::Database.postgresql?
result = result.first.presence
- result['median']&.to_f if result
+ result["median"]&.to_f if result
elsif Gitlab::Database.mysql?
result.to_a.flatten.first
end
@@ -36,26 +36,26 @@ module Gitlab
def mysql_median_datetime_sql(arel_table, query_so_far, column_sym)
query = arel_table.from
- .from(arel_table.project(Arel.sql('*')).order(arel_table[column_sym]).as(arel_table.table_name))
- .project(average([arel_table[column_sym]], 'median'))
- .where(
- Arel::Nodes::Between.new(
- Arel.sql("(select @row_id := @row_id + 1)"),
- Arel::Nodes::And.new(
- [Arel.sql('@ct/2.0'),
- Arel.sql('@ct/2.0 + 1')]
- )
- )
- ).
- # Disallow negative values
- where(arel_table[column_sym].gteq(0))
+ .from(arel_table.project(Arel.sql("*")).order(arel_table[column_sym]).as(arel_table.table_name))
+ .project(average([arel_table[column_sym]], "median"))
+ .where(
+ Arel::Nodes::Between.new(
+ Arel.sql("(select @row_id := @row_id + 1)"),
+ Arel::Nodes::And.new(
+ [Arel.sql("@ct/2.0"),
+ Arel.sql("@ct/2.0 + 1"),]
+ )
+ )
+ ).
+ # Disallow negative values
+ where(arel_table[column_sym].gteq(0))
[
Arel.sql("CREATE TEMPORARY TABLE IF NOT EXISTS #{query_so_far.to_sql}"),
Arel.sql("set @ct := (select count(1) from #{arel_table.table_name});"),
Arel.sql("set @row_id := 0;"),
query.to_sql,
- Arel.sql("DROP TEMPORARY TABLE IF EXISTS #{arel_table.table_name};")
+ Arel.sql("DROP TEMPORARY TABLE IF EXISTS #{arel_table.table_name};"),
]
end
@@ -87,7 +87,8 @@ module Gitlab
cte_table,
arel_table.project(*rank_rows(arel_table, column_sym, partition_column)).
# Disallow negative values
- where(arel_table[column_sym].gteq(zero_interval)))
+ where(arel_table[column_sym].gteq(zero_interval))
+ )
# From the CTE, select either the middle row or the middle two rows (this is accomplished
# by 'where cte.row_id between cte.ct / 2.0 AND cte.ct / 2.0 + 1'). Find the average of the
@@ -99,8 +100,8 @@ module Gitlab
Arel::Nodes::Between.new(
cte_table[:row_id],
Arel::Nodes::And.new(
- [(cte_table[:ct] / Arel.sql('2.0')),
- (cte_table[:ct] / Arel.sql('2.0') + 1)]
+ [(cte_table[:ct] / Arel.sql("2.0")),
+ (cte_table[:ct] / Arel.sql("2.0") + 1),]
)
)
)
@@ -140,25 +141,25 @@ module Gitlab
partition_row = arel_table[partition_column]
row_id =
Arel::Nodes::Over.new(
- Arel::Nodes::NamedFunction.new('rank', []),
+ Arel::Nodes::NamedFunction.new("rank", []),
Arel::Nodes::Window.new.partition(arel_table[partition_column])
.order(arel_table[column_sym])
- ).as('row_id')
+ ).as("row_id")
count = arel_table.from.from(arel_table.alias)
- .project('COUNT(*)')
- .where(arel_table[partition_column].eq(arel_table.alias[partition_column]))
- .as('ct')
+ .project("COUNT(*)")
+ .where(arel_table[partition_column].eq(arel_table.alias[partition_column]))
+ .as("ct")
[partition_row, column_row, row_id, count]
else
row_id =
Arel::Nodes::Over.new(
- Arel::Nodes::NamedFunction.new('row_number', []),
+ Arel::Nodes::NamedFunction.new("row_number", []),
Arel::Nodes::Window.new.order(arel_table[column_sym])
- ).as('row_id')
+ ).as("row_id")
- count = arel_table.project("COUNT(1)").as('ct')
+ count = arel_table.project("COUNT(1)").as("ct")
[column_row, row_id, count]
end
@@ -172,13 +173,13 @@ module Gitlab
end
def extract_epoch(arel_attribute)
- Arel.sql(%Q{EXTRACT(EPOCH FROM "#{arel_attribute.relation.name}"."#{arel_attribute.name}")})
+ Arel.sql(%{EXTRACT(EPOCH FROM "#{arel_attribute.relation.name}"."#{arel_attribute.name}")})
end
def extract_diff_epoch(diff)
return diff unless Gitlab::Database.postgresql?
- Arel.sql(%Q{EXTRACT(EPOCH FROM (#{diff.to_sql}))})
+ Arel.sql(%{EXTRACT(EPOCH FROM (#{diff.to_sql}))})
end
# Need to cast '0' to an INTERVAL before we can check if the interval is positive
diff --git a/lib/gitlab/database/migration_helpers.rb b/lib/gitlab/database/migration_helpers.rb
index 3abd0600e9d..e8432c7fba0 100644
--- a/lib/gitlab/database/migration_helpers.rb
+++ b/lib/gitlab/database/migration_helpers.rb
@@ -19,9 +19,9 @@ module Gitlab
[:created_at, :updated_at].each do |column_name|
if options[:default] && transaction_open?
- raise '`add_timestamps_with_timezone` with default value cannot be run inside a transaction. ' \
- 'You can disable transactions by calling `disable_ddl_transaction!` ' \
- 'in the body of your migration class'
+ raise "`add_timestamps_with_timezone` with default value cannot be run inside a transaction. " \
+ "You can disable transactions by calling `disable_ddl_transaction!` " \
+ "in the body of your migration class"
end
# If default value is presented, use `add_column_with_default` method instead.
@@ -51,13 +51,13 @@ module Gitlab
# See Rails' `add_index` for more info on the available arguments.
def add_concurrent_index(table_name, column_name, options = {})
if transaction_open?
- raise 'add_concurrent_index can not be run inside a transaction, ' \
- 'you can disable transactions by calling disable_ddl_transaction! ' \
- 'in the body of your migration class'
+ raise "add_concurrent_index can not be run inside a transaction, " \
+ "you can disable transactions by calling disable_ddl_transaction! " \
+ "in the body of your migration class"
end
if Database.postgresql?
- options = options.merge({ algorithm: :concurrently })
+ options = options.merge({algorithm: :concurrently})
end
if index_exists?(table_name, column_name, options)
@@ -81,13 +81,13 @@ module Gitlab
# See Rails' `remove_index` for more info on the available arguments.
def remove_concurrent_index(table_name, column_name, options = {})
if transaction_open?
- raise 'remove_concurrent_index can not be run inside a transaction, ' \
- 'you can disable transactions by calling disable_ddl_transaction! ' \
- 'in the body of your migration class'
+ raise "remove_concurrent_index can not be run inside a transaction, " \
+ "you can disable transactions by calling disable_ddl_transaction! " \
+ "in the body of your migration class"
end
if supports_drop_index_concurrently?
- options = options.merge({ algorithm: :concurrently })
+ options = options.merge({algorithm: :concurrently})
end
unless index_exists?(table_name, column_name, options)
@@ -96,7 +96,7 @@ module Gitlab
end
disable_statement_timeout do
- remove_index(table_name, options.merge({ column: column_name }))
+ remove_index(table_name, options.merge({column: column_name}))
end
end
@@ -111,13 +111,13 @@ module Gitlab
# See Rails' `remove_index` for more info on the available arguments.
def remove_concurrent_index_by_name(table_name, index_name, options = {})
if transaction_open?
- raise 'remove_concurrent_index_by_name can not be run inside a transaction, ' \
- 'you can disable transactions by calling disable_ddl_transaction! ' \
- 'in the body of your migration class'
+ raise "remove_concurrent_index_by_name can not be run inside a transaction, " \
+ "you can disable transactions by calling disable_ddl_transaction! " \
+ "in the body of your migration class"
end
if supports_drop_index_concurrently?
- options = options.merge({ algorithm: :concurrently })
+ options = options.merge({algorithm: :concurrently})
end
unless index_exists_by_name?(table_name, index_name)
@@ -126,7 +126,7 @@ module Gitlab
end
disable_statement_timeout do
- remove_index(table_name, options.merge({ name: index_name }))
+ remove_index(table_name, options.merge({name: index_name}))
end
end
@@ -134,7 +134,7 @@ module Gitlab
def supports_drop_index_concurrently?
return false unless Database.postgresql?
- version = select_one("SELECT current_setting('server_version_num') AS v")['v'].to_i
+ version = select_one("SELECT current_setting('server_version_num') AS v")["v"].to_i
version >= 90200
end
@@ -153,7 +153,7 @@ module Gitlab
# Transactions would result in ALTER TABLE locks being held for the
# duration of the transaction, defeating the purpose of this method.
if transaction_open?
- raise 'add_concurrent_foreign_key can not be run inside a transaction'
+ raise "add_concurrent_foreign_key can not be run inside a transaction"
end
# While MySQL does allow disabling of foreign keys it has no equivalent
@@ -168,10 +168,10 @@ module Gitlab
end
return add_foreign_key(source, target,
- column: column,
- on_delete: on_delete)
+ column: column,
+ on_delete: on_delete)
else
- on_delete = 'SET NULL' if on_delete == :nullify
+ on_delete = "SET NULL" if on_delete == :nullify
end
key_name = concurrent_foreign_key_name(source, column)
@@ -190,7 +190,7 @@ module Gitlab
ADD CONSTRAINT #{key_name}
FOREIGN KEY (#{column})
REFERENCES #{target} (id)
- #{on_delete ? "ON DELETE #{on_delete.upcase}" : ''}
+ #{on_delete ? "ON DELETE #{on_delete.upcase}" : ""}
NOT VALID;
EOF
end
@@ -249,11 +249,11 @@ module Gitlab
if block_given?
begin
- execute('SET statement_timeout TO 0')
+ execute("SET statement_timeout TO 0")
yield
ensure
- execute('RESET ALL')
+ execute("RESET ALL")
end
else
unless transaction_open?
@@ -267,7 +267,7 @@ module Gitlab
ERROR
end
- execute('SET LOCAL statement_timeout TO 0')
+ execute("SET LOCAL statement_timeout TO 0")
end
end
@@ -322,17 +322,17 @@ module Gitlab
# rubocop: disable Metrics/AbcSize
def update_column_in_batches(table, column, value)
if transaction_open?
- raise 'update_column_in_batches can not be run inside a transaction, ' \
- 'you can disable transactions by calling disable_ddl_transaction! ' \
- 'in the body of your migration class'
+ raise "update_column_in_batches can not be run inside a transaction, " \
+ "you can disable transactions by calling disable_ddl_transaction! " \
+ "in the body of your migration class"
end
table = Arel::Table.new(table)
- count_arel = table.project(Arel.star.count.as('count'))
+ count_arel = table.project(Arel.star.count.as("count"))
count_arel = yield table, count_arel if block_given?
- total = exec_query(count_arel.to_sql).to_hash.first['count'].to_i
+ total = exec_query(count_arel.to_sql).to_hash.first["count"].to_i
return if total == 0
@@ -347,7 +347,7 @@ module Gitlab
start_arel = table.project(table[:id]).order(table[:id].asc).take(1)
start_arel = yield table, start_arel if block_given?
- start_id = exec_query(start_arel.to_sql).to_hash.first['id'].to_i
+ start_id = exec_query(start_arel.to_sql).to_hash.first["id"].to_i
loop do
stop_arel = table.project(table[:id])
@@ -365,7 +365,7 @@ module Gitlab
.where(table[:id].gteq(start_id))
if stop_row
- stop_id = stop_row['id'].to_i
+ stop_id = stop_row["id"].to_i
start_id = stop_id
update_arel = update_arel.where(table[:id].lt(stop_id))
end
@@ -405,9 +405,9 @@ module Gitlab
# `update_column_in_batches` method.
def add_column_with_default(table, column, type, default:, limit: nil, allow_null: false, &block)
if transaction_open?
- raise 'add_column_with_default can not be run inside a transaction, ' \
- 'you can disable transactions by calling disable_ddl_transaction! ' \
- 'in the body of your migration class'
+ raise "add_column_with_default can not be run inside a transaction, " \
+ "you can disable transactions by calling disable_ddl_transaction! " \
+ "in the body of your migration class"
end
disable_statement_timeout do
@@ -452,7 +452,7 @@ module Gitlab
# type is used.
def rename_column_concurrently(table, old, new, type: nil)
if transaction_open?
- raise 'rename_column_concurrently can not be run inside a transaction'
+ raise "rename_column_concurrently can not be run inside a transaction"
end
check_trigger_permissions!(table)
@@ -461,9 +461,9 @@ module Gitlab
new_type = type || old_col.type
add_column(table, new, new_type,
- limit: old_col.limit,
- precision: old_col.precision,
- scale: old_col.scale)
+ limit: old_col.limit,
+ precision: old_col.precision,
+ scale: old_col.scale)
# We set the default value _after_ adding the column so we don't end up
# updating any existing data with the default value. This isn't
@@ -494,10 +494,10 @@ module Gitlab
if Database.postgresql?
install_rename_triggers_for_postgresql(trigger_name, quoted_table,
- quoted_old, quoted_new)
+ quoted_old, quoted_new)
else
install_rename_triggers_for_mysql(trigger_name, quoted_table,
- quoted_old, quoted_new)
+ quoted_old, quoted_new)
end
end
@@ -599,7 +599,7 @@ module Gitlab
)
unless relation.model < EachBatch
- raise TypeError, 'The relation must include the EachBatch module'
+ raise TypeError, "The relation must include the EachBatch module"
end
temp_column = "#{column}_for_type_change"
@@ -613,12 +613,12 @@ module Gitlab
# new one. Rows with NULL values in our source column are skipped since
# the target column is already NULL at this point.
relation.where.not(column => nil).each_batch(of: batch_size) do |batch, index|
- start_id, end_id = batch.pluck('MIN(id), MAX(id)').first
+ start_id, end_id = batch.pluck("MIN(id), MAX(id)").first
max_index = index
BackgroundMigrationWorker.perform_in(
index * interval,
- 'CopyColumn',
+ "CopyColumn",
[table, column, temp_column, start_id, end_id]
)
end
@@ -627,15 +627,15 @@ module Gitlab
# the last batch finished.
BackgroundMigrationWorker.perform_in(
(max_index * interval) + 1.hour,
- 'CleanupConcurrentTypeChange',
+ "CleanupConcurrentTypeChange",
[table, column, temp_column]
)
if perform_background_migration_inline?
# To ensure the schema is up to date immediately we perform the
# migration inline in dev / test environments.
- Gitlab::BackgroundMigration.steal('CopyColumn')
- Gitlab::BackgroundMigration.steal('CleanupConcurrentTypeChange')
+ Gitlab::BackgroundMigration.steal("CopyColumn")
+ Gitlab::BackgroundMigration.steal("CleanupConcurrentTypeChange")
end
end
@@ -683,9 +683,9 @@ module Gitlab
max_index = 0
add_column(table, new_column, new_type,
- limit: old_col.limit,
- precision: old_col.precision,
- scale: old_col.scale)
+ limit: old_col.limit,
+ precision: old_col.precision,
+ scale: old_col.scale)
# We set the default value _after_ adding the column so we don't end up
# updating any existing data with the default value. This isn't
@@ -694,22 +694,22 @@ module Gitlab
install_rename_triggers(table, old_column, new_column)
- model = Class.new(ActiveRecord::Base) do
+ model = Class.new(ActiveRecord::Base) {
self.table_name = table
include ::EachBatch
- end
+ }
# Schedule the jobs that will copy the data from the old column to the
# new one. Rows with NULL values in our source column are skipped since
# the target column is already NULL at this point.
model.where.not(old_column => nil).each_batch(of: batch_size) do |batch, index|
- start_id, end_id = batch.pluck('MIN(id), MAX(id)').first
+ start_id, end_id = batch.pluck("MIN(id), MAX(id)").first
max_index = index
BackgroundMigrationWorker.perform_in(
index * interval,
- 'CopyColumn',
+ "CopyColumn",
[table, old_column, new_column, start_id, end_id]
)
end
@@ -718,15 +718,15 @@ module Gitlab
# the last batch finished.
BackgroundMigrationWorker.perform_in(
(max_index * interval) + 1.hour,
- 'CleanupConcurrentRename',
+ "CleanupConcurrentRename",
[table, old_column, new_column]
)
if perform_background_migration_inline?
# To ensure the schema is up to date immediately we perform the
# migration inline in dev / test environments.
- Gitlab::BackgroundMigration.steal('CopyColumn')
- Gitlab::BackgroundMigration.steal('CleanupConcurrentRename')
+ Gitlab::BackgroundMigration.steal("CopyColumn")
+ Gitlab::BackgroundMigration.steal("CleanupConcurrentRename")
end
end
@@ -792,7 +792,7 @@ module Gitlab
# Returns the (base) name to use for triggers when renaming columns.
def rename_trigger_name(table, old, new)
- 'trigger_' + Digest::SHA256.hexdigest("#{table}_#{old}_#{new}").first(12)
+ "trigger_" + Digest::SHA256.hexdigest("#{table}_#{old}_#{new}").first(12)
end
# Returns an Array containing the indexes for the given column
@@ -819,9 +819,9 @@ module Gitlab
new = new.to_s
indexes_for(table, old).each do |index|
- new_columns = index.columns.map do |column|
+ new_columns = index.columns.map { |column|
column == old ? new : column
- end
+ }
# This is necessary as we can't properly rename indexes such as
# "ci_taggings_idx".
@@ -836,7 +836,7 @@ module Gitlab
unique: index.unique,
name: name,
length: index.lengths,
- order: index.orders
+ order: index.orders,
}
# These options are not supported by MySQL, so we only add them if
@@ -866,9 +866,9 @@ module Gitlab
def copy_foreign_keys(table, old, new)
foreign_keys_for(table, old).each do |fk|
add_concurrent_foreign_key(fk.from_table,
- fk.to_table,
- column: new,
- on_delete: fk.on_delete)
+ fk.to_table,
+ column: new,
+ on_delete: fk.on_delete)
end
end
@@ -890,9 +890,9 @@ module Gitlab
if Database.mysql?
locate = Arel::Nodes::NamedFunction
- .new('locate', [quoted_pattern, column])
+ .new("locate", [quoted_pattern, column])
insert_in_place = Arel::Nodes::NamedFunction
- .new('insert', [column, locate, pattern.size, quoted_replacement])
+ .new("insert", [column, locate, pattern.size, quoted_replacement])
Arel::Nodes::SqlLiteral.new(insert_in_place.to_sql)
else
@@ -926,21 +926,21 @@ module Gitlab
dbname = Database.database_name
user = Database.username
- raise <<-EOF
-Your database user is not allowed to create, drop, or execute triggers on the
-table #{table}.
+ raise <<~EOF
+ Your database user is not allowed to create, drop, or execute triggers on the
+ table #{table}.
-If you are using PostgreSQL you can solve this by logging in to the GitLab
-database (#{dbname}) using a super user and running:
+ If you are using PostgreSQL you can solve this by logging in to the GitLab
+ database (#{dbname}) using a super user and running:
- ALTER #{user} WITH SUPERUSER
+ ALTER #{user} WITH SUPERUSER
-For MySQL you instead need to run:
+ For MySQL you instead need to run:
- GRANT ALL PRIVILEGES ON #{dbname}.* TO #{user}@'%'
+ GRANT ALL PRIVILEGES ON #{dbname}.* TO #{user}@'%'
-Both queries will grant the user super user permissions, ensuring you don't run
-into similar problems in the future (e.g. when new tables are created).
+ Both queries will grant the user super user permissions, ensuring you don't run
+ into similar problems in the future (e.g. when new tables are created).
EOF
end
end
@@ -970,7 +970,7 @@ into similar problems in the future (e.g. when new tables are created).
# end
# end
def bulk_queue_background_migration_jobs_by_range(model_class, job_class_name, batch_size: BACKGROUND_MIGRATION_BATCH_SIZE)
- raise "#{model_class} does not have an ID to use for batch ranges" unless model_class.column_names.include?('id')
+ raise "#{model_class} does not have an ID to use for batch ranges" unless model_class.column_names.include?("id")
jobs = []
table_name = model_class.quoted_table_name
@@ -1019,7 +1019,7 @@ into similar problems in the future (e.g. when new tables are created).
# end
# end
def queue_background_migration_jobs_by_range_at_intervals(model_class, job_class_name, delay_interval, batch_size: BACKGROUND_MIGRATION_BATCH_SIZE)
- raise "#{model_class} does not have an ID to use for batch ranges" unless model_class.column_names.include?('id')
+ raise "#{model_class} does not have an ID to use for batch ranges" unless model_class.column_names.include?("id")
# To not overload the worker too much we enforce a minimum interval both
# when scheduling and performing jobs.
@@ -1028,7 +1028,7 @@ into similar problems in the future (e.g. when new tables are created).
end
model_class.each_batch(of: batch_size) do |relation, index|
- start_id, end_id = relation.pluck('MIN(id), MAX(id)').first
+ start_id, end_id = relation.pluck("MIN(id), MAX(id)").first
# `BackgroundMigrationWorker.bulk_perform_in` schedules all jobs for
# the same time, which is not helpful in most cases where we wish to
diff --git a/lib/gitlab/database/multi_threaded_migration.rb b/lib/gitlab/database/multi_threaded_migration.rb
index 1d39a3d0b57..33090d343e2 100644
--- a/lib/gitlab/database/multi_threaded_migration.rb
+++ b/lib/gitlab/database/multi_threaded_migration.rb
@@ -32,18 +32,16 @@ module Gitlab
def with_multiple_threads(thread_count, join: true)
pool = Gitlab::Database.create_connection_pool(thread_count)
- threads = Array.new(thread_count) do
+ threads = Array.new(thread_count) {
Thread.new do
pool.with_connection do |connection|
- begin
- Thread.current[MULTI_THREAD_AR_CONNECTION] = connection
- yield
- ensure
- Thread.current[MULTI_THREAD_AR_CONNECTION] = nil
- end
+ Thread.current[MULTI_THREAD_AR_CONNECTION] = connection
+ yield
+ ensure
+ Thread.current[MULTI_THREAD_AR_CONNECTION] = nil
end
end
- end
+ }
threads.each(&:join) if join
diff --git a/lib/gitlab/database/rename_reserved_paths_migration/v1/migration_classes.rb b/lib/gitlab/database/rename_reserved_paths_migration/v1/migration_classes.rb
index f1dc3ed74fe..838d695a820 100644
--- a/lib/gitlab/database/rename_reserved_paths_migration/v1/migration_classes.rb
+++ b/lib/gitlab/database/rename_reserved_paths_migration/v1/migration_classes.rb
@@ -18,7 +18,7 @@ module Gitlab
def build_full_path
if parent && path
- parent.full_path + '/' + path
+ parent.full_path + "/" + path
else
path
end
@@ -38,42 +38,42 @@ module Gitlab
class Namespace < ActiveRecord::Base
include MigrationClasses::Routable
- self.table_name = 'namespaces'
+ self.table_name = "namespaces"
self.inheritance_column = :_type_disabled
belongs_to :parent,
- class_name: "#{MigrationClasses.name}::Namespace"
+ class_name: "#{MigrationClasses.name}::Namespace"
has_one :route, as: :source
has_many :children,
- class_name: "#{MigrationClasses.name}::Namespace",
- foreign_key: :parent_id
+ class_name: "#{MigrationClasses.name}::Namespace",
+ foreign_key: :parent_id
# Overridden to have the correct `source_type` for the `route` relation
def self.name
- 'Namespace'
+ "Namespace"
end
def kind
- type == 'Group' ? 'group' : 'user'
+ type == "Group" ? "group" : "user"
end
end
class User < ActiveRecord::Base
- self.table_name = 'users'
+ self.table_name = "users"
end
class Route < ActiveRecord::Base
- self.table_name = 'routes'
+ self.table_name = "routes"
belongs_to :source, polymorphic: true
end
class Project < ActiveRecord::Base
include MigrationClasses::Routable
has_one :route, as: :source
- self.table_name = 'projects'
+ self.table_name = "projects"
HASHED_STORAGE_FEATURES = {
repository: 1,
- attachments: 2
+ attachments: 2,
}.freeze
def repository_storage_path
@@ -82,14 +82,14 @@ module Gitlab
# Overridden to have the correct `source_type` for the `route` relation
def self.name
- 'Project'
+ "Project"
end
def hashed_storage?(feature)
raise ArgumentError, "Invalid feature" unless HASHED_STORAGE_FEATURES.include?(feature)
return false unless respond_to?(:storage_version)
- self.storage_version && self.storage_version >= HASHED_STORAGE_FEATURES[feature]
+ storage_version && storage_version >= HASHED_STORAGE_FEATURES[feature]
end
end
end
diff --git a/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_base.rb b/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_base.rb
index 60afa4bcd52..097623e8103 100644
--- a/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_base.rb
+++ b/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_base.rb
@@ -8,11 +8,11 @@ module Gitlab
attr_reader :paths, :migration
delegate :update_column_in_batches,
- :execute,
- :replace_sql,
- :quote_string,
- :say,
- to: :migration
+ :execute,
+ :replace_sql,
+ :quote_string,
+ :say,
+ to: :migration
def initialize(paths, migration)
@paths = paths
@@ -38,7 +38,7 @@ module Gitlab
def perform_rename(routable, old_full_path, new_full_path)
# skips callbacks & validations
- new_path = new_full_path.split('/').last
+ new_path = new_full_path.split("/").last
routable.class.where(id: routable)
.update_all(path: new_path)
@@ -52,17 +52,17 @@ module Gitlab
quoted_old_wildcard_path = quote_string("#{old_full_path}/%")
filter = if Database.mysql?
- "lower(routes.path) = lower('#{quoted_old_full_path}') "\
- "OR routes.path LIKE '#{quoted_old_wildcard_path}'"
- else
- "routes.id IN "\
- "( SELECT routes.id FROM routes WHERE lower(routes.path) = lower('#{quoted_old_full_path}') "\
- "UNION SELECT routes.id FROM routes WHERE routes.path ILIKE '#{quoted_old_wildcard_path}' )"
- end
+ "lower(routes.path) = lower('#{quoted_old_full_path}') "\
+ "OR routes.path LIKE '#{quoted_old_wildcard_path}'"
+ else
+ "routes.id IN "\
+ "( SELECT routes.id FROM routes WHERE lower(routes.path) = lower('#{quoted_old_full_path}') "\
+ "UNION SELECT routes.id FROM routes WHERE routes.path ILIKE '#{quoted_old_wildcard_path}' )"
+ end
replace_statement = replace_sql(Route.arel_table[:path],
- old_full_path,
- new_full_path)
+ old_full_path,
+ new_full_path)
update = Arel::UpdateManager.new
.table(routes)
@@ -165,7 +165,7 @@ module Gitlab
say "renaming #{type} from #{path_after_rename} back to #{path_before_rename}"
begin
yield(path_before_rename, path_after_rename)
- rescue StandardError => e
+ rescue => e
failed_reverts << rename_info
say "Renaming #{type} from #{path_after_rename} back to "\
"#{path_before_rename} failed. Review the error and try "\
diff --git a/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_namespaces.rb b/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_namespaces.rb
index 6bbad707f0f..54d8c42e897 100644
--- a/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_namespaces.rb
+++ b/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_namespaces.rb
@@ -19,16 +19,16 @@ module Gitlab
MigrationClasses::Namespace.where.not(parent_id: nil)
when :top_level
MigrationClasses::Namespace.where(parent_id: nil)
- end
+ end
with_paths = MigrationClasses::Route.arel_table[:path]
- .matches_any(path_patterns)
+ .matches_any(path_patterns)
namespaces.joins(:route).where(with_paths)
end
def rename_namespace(namespace)
old_full_path, new_full_path = rename_path_for_routable(namespace)
- track_rename('namespace', old_full_path, new_full_path)
+ track_rename("namespace", old_full_path, new_full_path)
rename_namespace_dependencies(namespace, old_full_path, new_full_path)
end
@@ -37,15 +37,15 @@ module Gitlab
move_repositories(namespace, old_full_path, new_full_path)
move_uploads(old_full_path, new_full_path)
move_pages(old_full_path, new_full_path)
- rename_user(old_full_path, new_full_path) if namespace.kind == 'user'
+ rename_user(old_full_path, new_full_path) if namespace.kind == "user"
remove_cached_html_for_projects(projects_for_namespace(namespace).map(&:id))
end
def revert_renames
- reverts_for_type('namespace') do |path_before_rename, current_path|
+ reverts_for_type("namespace") do |path_before_rename, current_path|
matches_path = MigrationClasses::Route.arel_table[:path].matches(current_path)
namespace = MigrationClasses::Namespace.joins(:route)
- .where(matches_path).first&.becomes(MigrationClasses::Namespace)
+ .where(matches_path).first&.becomes(MigrationClasses::Namespace)
if namespace
perform_rename(namespace, current_path, path_before_rename)
@@ -83,8 +83,8 @@ module Gitlab
def projects_for_namespace(namespace)
namespace_ids = child_ids_for_parent(namespace, ids: [namespace.id])
namespace_or_children = MigrationClasses::Project
- .arel_table[:namespace_id]
- .in(namespace_ids)
+ .arel_table[:namespace_id]
+ .in(namespace_ids)
MigrationClasses::Project.where(namespace_or_children)
end
diff --git a/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_projects.rb b/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_projects.rb
index 580be9fe267..49d533067b4 100644
--- a/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_projects.rb
+++ b/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_projects.rb
@@ -18,7 +18,7 @@ module Gitlab
def rename_project(project)
old_full_path, new_full_path = rename_path_for_routable(project)
- track_rename('project', old_full_path, new_full_path)
+ track_rename("project", old_full_path, new_full_path)
move_project_folders(project, old_full_path, new_full_path)
end
@@ -34,10 +34,10 @@ module Gitlab
end
def revert_renames
- reverts_for_type('project') do |path_before_rename, current_path|
+ reverts_for_type("project") do |path_before_rename, current_path|
matches_path = MigrationClasses::Route.arel_table[:path].matches(current_path)
project = MigrationClasses::Project.joins(:route)
- .where(matches_path).first
+ .where(matches_path).first
if project
perform_rename(project, current_path, path_before_rename)
@@ -54,8 +54,8 @@ module Gitlab
def move_repository(project, old_path, new_path)
unless gitlab_shell.mv_repository(project.repository_storage,
- old_path,
- new_path)
+ old_path,
+ new_path)
Rails.logger.error "Error moving #{old_path} to #{new_path}"
end
end
@@ -64,7 +64,7 @@ module Gitlab
return @projects_for_paths if @projects_for_paths
with_paths = MigrationClasses::Route.arel_table[:path]
- .matches_any(path_patterns)
+ .matches_any(path_patterns)
@projects_for_paths = MigrationClasses::Project.joins(:route).where(with_paths)
end
diff --git a/lib/gitlab/database/sha_attribute.rb b/lib/gitlab/database/sha_attribute.rb
index 8d97adaff99..f717cef162d 100644
--- a/lib/gitlab/database/sha_attribute.rb
+++ b/lib/gitlab/database/sha_attribute.rb
@@ -17,12 +17,12 @@ module Gitlab
# using them as if they were stored as string values. This gives you the
# ease of use of string values, but without the storage overhead.
class ShaAttribute < BINARY_TYPE
- PACK_FORMAT = 'H*'.freeze
+ PACK_FORMAT = "H*"
# Casts binary data to a SHA1 in hexadecimal.
def deserialize(value)
value = super(value)
- value ? value.unpack(PACK_FORMAT)[0] : nil
+ value ? value.unpack1(PACK_FORMAT) : nil
end
# Casts a SHA1 in hexadecimal to the proper binary format.
diff --git a/lib/gitlab/database/subquery.rb b/lib/gitlab/database/subquery.rb
index 10971d2b274..555a24c5e10 100644
--- a/lib/gitlab/database/subquery.rb
+++ b/lib/gitlab/database/subquery.rb
@@ -10,7 +10,7 @@ module Gitlab
# See https://gitlab.com/gitlab-org/gitlab-ce/issues/51729
r = relation.limit(nil).arel
r.take(relation.limit_value) if relation.limit_value
- t2 = r.as('t2')
+ t2 = r.as("t2")
relation.unscoped.joins(t.join(t2).on(t[:id].eq(t2[:id])).join_sources.first)
end
diff --git a/lib/gitlab/dependency_linker.rb b/lib/gitlab/dependency_linker.rb
index c63d9e5bb71..d5c4d48e8ac 100644
--- a/lib/gitlab/dependency_linker.rb
+++ b/lib/gitlab/dependency_linker.rb
@@ -12,7 +12,7 @@ module Gitlab
PodspecJsonLinker,
CartfileLinker,
GodepsJsonLinker,
- RequirementsTxtLinker
+ RequirementsTxtLinker,
].freeze
def self.linker(blob_name)
diff --git a/lib/gitlab/dependency_linker/base_linker.rb b/lib/gitlab/dependency_linker/base_linker.rb
index ac2efe598b4..1be572b0b66 100644
--- a/lib/gitlab/dependency_linker/base_linker.rb
+++ b/lib/gitlab/dependency_linker/base_linker.rb
@@ -44,7 +44,7 @@ module Gitlab
end
def link_tag(name, url)
- %{<a href="#{ERB::Util.html_escape_once(url)}" rel="nofollow noreferrer noopener" target="_blank">#{ERB::Util.html_escape_once(name)}</a>}
+ %(<a href="#{ERB::Util.html_escape_once(url)}" rel="nofollow noreferrer noopener" target="_blank">#{ERB::Util.html_escape_once(name)}</a>)
end
# Links package names based on regex.
diff --git a/lib/gitlab/dependency_linker/cartfile_linker.rb b/lib/gitlab/dependency_linker/cartfile_linker.rb
index 0e33f0956dd..0229201cbfd 100644
--- a/lib/gitlab/dependency_linker/cartfile_linker.rb
+++ b/lib/gitlab/dependency_linker/cartfile_linker.rb
@@ -8,7 +8,7 @@ module Gitlab
private
def link_dependencies
- link_method_call('github', REPO_REGEX, &method(:github_url))
+ link_method_call("github", REPO_REGEX, &method(:github_url))
link_method_call(%w[github git binary], URL_REGEX, &:itself)
end
end
diff --git a/lib/gitlab/dependency_linker/gemfile_linker.rb b/lib/gitlab/dependency_linker/gemfile_linker.rb
index 8ab219c4962..7bbb4df495a 100644
--- a/lib/gitlab/dependency_linker/gemfile_linker.rb
+++ b/lib/gitlab/dependency_linker/gemfile_linker.rb
@@ -20,12 +20,12 @@ module Gitlab
link_regex(/(git:|:git\s*=>)\s*['"](?<name>#{URL_REGEX})['"]/, &:itself)
# Link `source "https://rubygems.org"` to https://rubygems.org
- link_method_call('source', URL_REGEX, &:itself)
+ link_method_call("source", URL_REGEX, &:itself)
end
def link_packages
# Link `gem "package_name"` to https://rubygems.org/gems/package_name
- link_method_call('gem') do |name|
+ link_method_call("gem") do |name|
"https://rubygems.org/gems/#{name}"
end
end
diff --git a/lib/gitlab/dependency_linker/gemspec_linker.rb b/lib/gitlab/dependency_linker/gemspec_linker.rb
index b924ea86d89..fe4a6156b12 100644
--- a/lib/gitlab/dependency_linker/gemspec_linker.rb
+++ b/lib/gitlab/dependency_linker/gemspec_linker.rb
@@ -8,8 +8,8 @@ module Gitlab
private
def link_dependencies
- link_method_call('homepage', URL_REGEX, &:itself)
- link_method_call('license', &method(:license_url))
+ link_method_call("homepage", URL_REGEX, &:itself)
+ link_method_call("license", &method(:license_url))
link_method_call(%w[name add_dependency add_runtime_dependency add_development_dependency]) do |name|
"https://rubygems.org/gems/#{name}"
diff --git a/lib/gitlab/dependency_linker/godeps_json_linker.rb b/lib/gitlab/dependency_linker/godeps_json_linker.rb
index d24c137793e..2c0bccb4280 100644
--- a/lib/gitlab/dependency_linker/godeps_json_linker.rb
+++ b/lib/gitlab/dependency_linker/godeps_json_linker.rb
@@ -10,7 +10,7 @@ module Gitlab
private
def link_dependencies
- link_json('ImportPath') do |path|
+ link_json("ImportPath") do |path|
case path
when %r{\A(?<repo>gitlab\.com/#{NESTED_REPO_REGEX})\.git/(?<path>.+)\z},
%r{\A(?<repo>git(lab|hub)\.com/#{REPO_REGEX})/(?<path>.+)\z}
diff --git a/lib/gitlab/dependency_linker/json_linker.rb b/lib/gitlab/dependency_linker/json_linker.rb
index 298d214df61..4d6460b0691 100644
--- a/lib/gitlab/dependency_linker/json_linker.rb
+++ b/lib/gitlab/dependency_linker/json_linker.rb
@@ -39,7 +39,11 @@ module Gitlab
end
def json
- @json ||= JSON.parse(plain_text) rescue nil
+ @json ||= begin
+ JSON.parse(plain_text)
+ rescue
+ nil
+ end
end
end
end
diff --git a/lib/gitlab/dependency_linker/package_json_linker.rb b/lib/gitlab/dependency_linker/package_json_linker.rb
index 578e25f806a..c0299f05981 100644
--- a/lib/gitlab/dependency_linker/package_json_linker.rb
+++ b/lib/gitlab/dependency_linker/package_json_linker.rb
@@ -8,8 +8,8 @@ module Gitlab
private
def link_dependencies
- link_json('name', json["name"], &method(:package_url))
- link_json('license', &method(:license_url))
+ link_json("name", json["name"], &method(:package_url))
+ link_json("license", &method(:license_url))
link_json(%w[homepage url], URL_REGEX, &:itself)
link_packages
diff --git a/lib/gitlab/dependency_linker/podfile_linker.rb b/lib/gitlab/dependency_linker/podfile_linker.rb
index def9b04cca9..610bd6f7a42 100644
--- a/lib/gitlab/dependency_linker/podfile_linker.rb
+++ b/lib/gitlab/dependency_linker/podfile_linker.rb
@@ -10,7 +10,7 @@ module Gitlab
private
def link_packages
- link_method_call('pod', &method(:package_url))
+ link_method_call("pod", &method(:package_url))
end
end
end
diff --git a/lib/gitlab/dependency_linker/podspec_json_linker.rb b/lib/gitlab/dependency_linker/podspec_json_linker.rb
index 1a2493e7cc0..cf04992e8f5 100644
--- a/lib/gitlab/dependency_linker/podspec_json_linker.rb
+++ b/lib/gitlab/dependency_linker/podspec_json_linker.rb
@@ -10,8 +10,8 @@ module Gitlab
private
def link_dependencies
- link_json('name', json["name"], &method(:package_url))
- link_json('license', &method(:license_url))
+ link_json("name", json["name"], &method(:package_url))
+ link_json("license", &method(:license_url))
link_json(%w[homepage git], URL_REGEX, &:itself)
link_packages_at_key("dependencies", &method(:package_url))
diff --git a/lib/gitlab/dependency_linker/podspec_linker.rb b/lib/gitlab/dependency_linker/podspec_linker.rb
index 6b1758c5a43..3515c218aaf 100644
--- a/lib/gitlab/dependency_linker/podspec_linker.rb
+++ b/lib/gitlab/dependency_linker/podspec_linker.rb
@@ -12,11 +12,11 @@ module Gitlab
private
def link_dependencies
- link_method_call('homepage', URL_REGEX, &:itself)
+ link_method_call("homepage", URL_REGEX, &:itself)
link_regex(/(git:|:git\s*=>)\s*['"](?<name>#{URL_REGEX})['"]/, &:itself)
- link_method_call('license', &method(:license_url))
+ link_method_call("license", &method(:license_url))
link_regex(/license\s*=\s*\{\s*(type:|:type\s*=>)\s*#{STRING_REGEX}/, &method(:license_url))
link_method_call(%w[name dependency], &method(:package_url))
diff --git a/lib/gitlab/diff/diff_refs.rb b/lib/gitlab/diff/diff_refs.rb
index dc245377ccc..7950959b0a7 100644
--- a/lib/gitlab/diff/diff_refs.rb
+++ b/lib/gitlab/diff/diff_refs.rb
@@ -20,7 +20,7 @@ module Gitlab
Git.shas_eql?(head_sha, other.head_sha)
end
- alias_method :eql?, :==
+ alias eql? ==
def hash
[self.class, base_sha, start_sha, head_sha].hash
@@ -48,9 +48,9 @@ module Gitlab
straight = start_sha == base_sha
CompareService.new(project, head_sha).execute(project,
- start_sha,
- base_sha: base_sha,
- straight: straight)
+ start_sha,
+ base_sha: base_sha,
+ straight: straight)
end
end
end
diff --git a/lib/gitlab/diff/file.rb b/lib/gitlab/diff/file.rb
index c9d89d56884..6ced7926424 100644
--- a/lib/gitlab/diff/file.rb
+++ b/lib/gitlab/diff/file.rb
@@ -21,7 +21,7 @@ module Gitlab
# large files referred to in "Large File Storage" are much more likely to be
# binary than text.
RICH_VIEWERS = [
- DiffViewer::Image
+ DiffViewer::Image,
].sort_by { |v| v.binary? ? 0 : 1 }.freeze
def initialize(
@@ -30,7 +30,8 @@ module Gitlab
diff_refs: nil,
fallback_diff_refs: nil,
stats: nil,
- unique_identifier: nil)
+ unique_identifier: nil
+ )
@diff = diff
@stats = stats
@@ -52,7 +53,7 @@ module Gitlab
diff_refs: diff_refs,
position_type: position_type.to_s,
old_path: old_path,
- new_path: new_path
+ new_path: new_path,
}
if position_type == :text
@@ -75,7 +76,7 @@ module Gitlab
end
def line_for_position(pos)
- return nil unless pos.position_type == 'text'
+ return nil unless pos.position_type == "text"
# This method is normally used to find which line the diff was
# commented on, and in this context, it's normally the raw diff persisted
@@ -190,7 +191,7 @@ module Gitlab
def highlighted_diff_lines
@highlighted_diff_lines ||=
- Gitlab::Diff::Highlight.new(self, repository: self.repository).highlight
+ Gitlab::Diff::Highlight.new(self, repository: repository).highlight
end
# Array[<Hash>] with right/left keys that contains Gitlab::Diff::Line objects which text is hightlighted
@@ -231,7 +232,7 @@ module Gitlab
end
def diffable?
- repository.attributes(file_path).fetch('diff') { true }
+ repository.attributes(file_path).fetch("diff") { true }
end
def binary_in_repo?
@@ -322,7 +323,7 @@ module Gitlab
last_line = lines.last
if last_line.new_pos < total_blob_lines(blob) && !deleted_file?
- match_line = Gitlab::Diff::Line.new("", 'match', nil, last_line.old_pos, last_line.new_pos)
+ match_line = Gitlab::Diff::Line.new("", "match", nil, last_line.old_pos, last_line.new_pos)
lines.push(match_line)
end
@@ -350,7 +351,7 @@ module Gitlab
end
def text_position_properties(line)
- { old_line: line.old_line, new_line: line.new_line }
+ {old_line: line.old_line, new_line: line.new_line}
end
def image_position_properties(image_point)
diff --git a/lib/gitlab/diff/file_collection/base.rb b/lib/gitlab/diff/file_collection/base.rb
index c5bbf522f7c..56640f54c52 100644
--- a/lib/gitlab/diff/file_collection/base.rb
+++ b/lib/gitlab/diff/file_collection/base.rb
@@ -79,10 +79,10 @@ module Gitlab
stats = diff_stats_collection&.find_by_path(diff.new_path)
Gitlab::Diff::File.new(diff,
- repository: project.repository,
- diff_refs: diff_refs,
- fallback_diff_refs: fallback_diff_refs,
- stats: stats)
+ repository: project.repository,
+ diff_refs: diff_refs,
+ fallback_diff_refs: fallback_diff_refs,
+ stats: stats)
end
end
end
diff --git a/lib/gitlab/diff/file_collection/compare.rb b/lib/gitlab/diff/file_collection/compare.rb
index 663bad95db7..3b802bdb44d 100644
--- a/lib/gitlab/diff/file_collection/compare.rb
+++ b/lib/gitlab/diff/file_collection/compare.rb
@@ -6,9 +6,9 @@ module Gitlab
class Compare < Base
def initialize(compare, project:, diff_options:, diff_refs: nil)
super(compare,
- project: project,
+ project: project,
diff_options: diff_options,
- diff_refs: diff_refs)
+ diff_refs: diff_refs)
end
def unfold_diff_lines(positions)
diff --git a/lib/gitlab/diff/formatters/base_formatter.rb b/lib/gitlab/diff/formatters/base_formatter.rb
index 9704aed82c1..af8b8c1a5fb 100644
--- a/lib/gitlab/diff/formatters/base_formatter.rb
+++ b/lib/gitlab/diff/formatters/base_formatter.rb
@@ -42,7 +42,7 @@ module Gitlab
head_sha: head_sha,
old_path: old_path,
new_path: new_path,
- position_type: position_type
+ position_type: position_type,
}
end
diff --git a/lib/gitlab/diff/formatters/text_formatter.rb b/lib/gitlab/diff/formatters/text_formatter.rb
index f6e247ef665..f5118635019 100644
--- a/lib/gitlab/diff/formatters/text_formatter.rb
+++ b/lib/gitlab/diff/formatters/text_formatter.rb
@@ -30,9 +30,9 @@ module Gitlab
if old_line && new_line
nil
elsif new_line
- 'new'
+ "new"
else
- 'old'
+ "old"
end
end
diff --git a/lib/gitlab/diff/highlight.rb b/lib/gitlab/diff/highlight.rb
index d2484217ab9..4c2c1c33824 100644
--- a/lib/gitlab/diff/highlight.rb
+++ b/lib/gitlab/diff/highlight.rb
@@ -35,7 +35,7 @@ module Gitlab
# match the blob, which is a bug. But we shouldn't fail to render
# completely in that case, even though we want to report the error.
rescue RangeError => e
- Gitlab::Sentry.track_exception(e, issue_url: 'https://gitlab.com/gitlab-org/gitlab-ce/issues/45441')
+ Gitlab::Sentry.track_exception(e, issue_url: "https://gitlab.com/gitlab-org/gitlab-ce/issues/45441")
end
end
@@ -48,7 +48,7 @@ module Gitlab
private
def highlight_line(diff_line)
- return unless diff_file && diff_file.diff_refs
+ return unless diff_file&.diff_refs
rich_line =
if diff_line.unchanged? || diff_line.added?
@@ -60,7 +60,7 @@ module Gitlab
# Only update text if line is found. This will prevent
# issues with submodules given the line only exists in diff content.
if rich_line
- line_prefix = diff_line.text =~ /\A(.)/ ? $1 : ' '
+ line_prefix = diff_line.text =~ /\A(.)/ ? $1 : " "
"#{line_prefix}#{rich_line}".html_safe
end
end
diff --git a/lib/gitlab/diff/highlight_cache.rb b/lib/gitlab/diff/highlight_cache.rb
index e4390771db2..01df0158f49 100644
--- a/lib/gitlab/diff/highlight_cache.rb
+++ b/lib/gitlab/diff/highlight_cache.rb
@@ -1,5 +1,5 @@
# frozen_string_literal: true
-#
+
module Gitlab
module Diff
class HighlightCache
@@ -43,7 +43,7 @@ module Gitlab
end
def key
- [diffable, 'highlighted-diff-files', Gitlab::Diff::Line::SERIALIZE_KEYS, diff_options]
+ [diffable, "highlighted-diff-files", Gitlab::Diff::Line::SERIALIZE_KEYS, diff_options]
end
private
diff --git a/lib/gitlab/diff/image_point.rb b/lib/gitlab/diff/image_point.rb
index a3ce032f8e2..90325fcf228 100644
--- a/lib/gitlab/diff/image_point.rb
+++ b/lib/gitlab/diff/image_point.rb
@@ -17,7 +17,7 @@ module Gitlab
width: width,
height: height,
x: x,
- y: y
+ y: y,
}
end
end
diff --git a/lib/gitlab/diff/inline_diff.rb b/lib/gitlab/diff/inline_diff.rb
index 5815d1bae4a..b3591177ee9 100644
--- a/lib/gitlab/diff/inline_diff.rb
+++ b/lib/gitlab/diff/inline_diff.rb
@@ -73,7 +73,7 @@ module Gitlab
def find_changed_line_pairs(lines)
# Prefixes of all diff lines, indicating their types
# For example: `" - + -+ ---+++ --+ -++"`
- line_prefixes = lines.each_with_object(+"") { |line, s| s << (line[0] || ' ') }.gsub(/[^ +-]/, ' ')
+ line_prefixes = lines.each_with_object(+"") { |line, s| s << (line[0] || " ") }.gsub(/[^ +-]/, " ")
changed_line_pairs = []
line_prefixes.scan(LINE_PAIRS_PATTERN) do
diff --git a/lib/gitlab/diff/inline_diff_markdown_marker.rb b/lib/gitlab/diff/inline_diff_markdown_marker.rb
index 3c536c43a9e..d1217e91af5 100644
--- a/lib/gitlab/diff/inline_diff_markdown_marker.rb
+++ b/lib/gitlab/diff/inline_diff_markdown_marker.rb
@@ -5,7 +5,7 @@ module Gitlab
class InlineDiffMarkdownMarker < Gitlab::StringRangeMarker
MARKDOWN_SYMBOLS = {
addition: "+",
- deletion: "-"
+ deletion: "-",
}.freeze
def mark(line_inline_diffs, mode: nil)
diff --git a/lib/gitlab/diff/inline_diff_marker.rb b/lib/gitlab/diff/inline_diff_marker.rb
index 1bbde1ffd2a..82fde1cffdc 100644
--- a/lib/gitlab/diff/inline_diff_marker.rb
+++ b/lib/gitlab/diff/inline_diff_marker.rb
@@ -9,7 +9,7 @@ module Gitlab
def mark(line_inline_diffs, mode: nil)
super(line_inline_diffs) do |text, left:, right:|
- %{<span class="#{html_class_names(left, right, mode)}">#{text}</span>}
+ %(<span class="#{html_class_names(left, right, mode)}">#{text}</span>)
end
end
diff --git a/lib/gitlab/diff/line.rb b/lib/gitlab/diff/line.rb
index 001748afb41..3b4c4a41f6a 100644
--- a/lib/gitlab/diff/line.rb
+++ b/lib/gitlab/diff/line.rb
@@ -3,7 +3,7 @@
module Gitlab
module Diff
class Line
- SERIALIZE_KEYS = %i(line_code rich_text text type index old_pos new_pos).freeze
+ SERIALIZE_KEYS = %i[line_code rich_text text type index old_pos new_pos].freeze
attr_reader :line_code, :type, :old_pos, :new_pos
attr_writer :rich_text
@@ -22,13 +22,13 @@ module Gitlab
def self.init_from_hash(hash)
new(hash[:text],
- hash[:type],
- hash[:index],
- hash[:old_pos],
- hash[:new_pos],
- parent_file: hash[:parent_file],
- line_code: hash[:line_code],
- rich_text: hash[:rich_text])
+ hash[:type],
+ hash[:index],
+ hash[:old_pos],
+ hash[:new_pos],
+ parent_file: hash[:parent_file],
+ line_code: hash[:line_code],
+ rich_text: hash[:rich_text])
end
def to_hash
@@ -88,7 +88,7 @@ module Gitlab
{
old_pos: old_pos,
- new_pos: new_pos
+ new_pos: new_pos,
}
end
diff --git a/lib/gitlab/diff/line_mapper.rb b/lib/gitlab/diff/line_mapper.rb
index fba7bff4781..e4c124329f0 100644
--- a/lib/gitlab/diff/line_mapper.rb
+++ b/lib/gitlab/diff/line_mapper.rb
@@ -39,10 +39,10 @@ module Gitlab
# - The diff line with that exact line number, if it is in the diff context
# - The first diff line with a higher line number, if it falls between diff contexts
# - The last known diff line, if it falls after the last diff context
- diff_line = diff_lines.find do |diff_line|
+ diff_line = diff_lines.find { |diff_line|
diff_from_line = diff_line.public_send(from) # rubocop:disable GitlabSecurity/PublicSend
diff_from_line && diff_from_line >= from_line
- end
+ }
diff_line ||= diff_lines.last
# If no diff line could be found, the file wasn't changed, and the
diff --git a/lib/gitlab/diff/lines_unfolder.rb b/lib/gitlab/diff/lines_unfolder.rb
index 6cf904b2b2a..48dead2c255 100644
--- a/lib/gitlab/diff/lines_unfolder.rb
+++ b/lib/gitlab/diff/lines_unfolder.rb
@@ -39,7 +39,7 @@ module Gitlab
# Blob lines, unlike diffs, doesn't start with an empty space for
# unchanged line, so the parsing and highlighting step can get fuzzy
# without the following change.
- line_prefix = ' '
+ line_prefix = " "
blob_as_diff_lines = @blob.data.each_line.map { |line| "#{line_prefix}#{line}" }
lines = Gitlab::Diff::Parser.new.parse(blob_as_diff_lines, diff_file: @diff_file).to_a
@@ -100,7 +100,7 @@ module Gitlab
blob_lines.each do |line|
new_blob_lines << Gitlab::Diff::Line.new(line.text, line.type, nil, old_pos, new_pos,
- parent_file: @diff_file)
+ parent_file: @diff_file)
old_pos += 1
new_pos += 1
@@ -144,11 +144,11 @@ module Gitlab
def build_match_line(old_pos, new_pos)
blob_lines_length = blob_lines.length
- old_line_ref = [old_pos, blob_lines_length].join(',')
- new_line_ref = [new_pos, blob_lines_length].join(',')
+ old_line_ref = [old_pos, blob_lines_length].join(",")
+ new_line_ref = [new_pos, blob_lines_length].join(",")
new_match_line_str = "@@ -#{old_line_ref}+#{new_line_ref} @@"
- Gitlab::Diff::Line.new(new_match_line_str, 'match', nil, old_pos, new_pos)
+ Gitlab::Diff::Line.new(new_match_line_str, "match", nil, old_pos, new_pos)
end
# Returns the first line position that should be extracted
@@ -223,7 +223,7 @@ module Gitlab
next last_line if bottom?
@diff_file.diff_lines.find do |line|
- line.old_pos > comment_position && line.type == 'match'
+ line.old_pos > comment_position && line.type == "match"
end
end
end
diff --git a/lib/gitlab/diff/parallel_diff.rb b/lib/gitlab/diff/parallel_diff.rb
index 77b65fea726..fff646262f9 100644
--- a/lib/gitlab/diff/parallel_diff.rb
+++ b/lib/gitlab/diff/parallel_diff.rb
@@ -19,7 +19,7 @@ module Gitlab
if line.removed?
lines << {
left: line,
- right: nil
+ right: nil,
}
# Once we come upon a new line it can be put on the right of this old line
@@ -38,7 +38,7 @@ module Gitlab
else
lines << {
left: nil,
- right: line
+ right: line,
}
free_right_index = nil
@@ -48,7 +48,7 @@ module Gitlab
# line in the right panel is the same as in the left one
lines << {
left: line,
- right: line
+ right: line,
}
free_right_index = nil
diff --git a/lib/gitlab/diff/parser.rb b/lib/gitlab/diff/parser.rb
index 4a47e4b80b6..998ab5180b5 100644
--- a/lib/gitlab/diff/parser.rb
+++ b/lib/gitlab/diff/parser.rb
@@ -25,11 +25,19 @@ module Gitlab
full_line = line.delete("\n")
- if line =~ /^@@ -/
+ if /^@@ -/.match?(line)
type = "match"
- line_old = line.match(/\-[0-9]*/)[0].to_i.abs rescue 0
- line_new = line.match(/\+[0-9]*/)[0].to_i.abs rescue 0
+ line_old = begin
+ line.match(/\-[0-9]*/)[0].to_i.abs
+ rescue
+ 0
+ end
+ line_new = begin
+ line.match(/\+[0-9]*/)[0].to_i.abs
+ rescue
+ 0
+ end
next if line_old <= 1 && line_new <= 1 # top of file
@@ -71,9 +79,9 @@ module Gitlab
private
def filename?(line)
- line.start_with?( '--- /dev/null', '+++ /dev/null', '--- a', '+++ b',
- '+++ a', # The line will start with `+++ a` in the reverse diff of an orphan commit
- '--- /tmp/diffy', '+++ /tmp/diffy')
+ line.start_with?("--- /dev/null", "+++ /dev/null", "--- a", "+++ b",
+ "+++ a", # The line will start with `+++ a` in the reverse diff of an orphan commit
+ "--- /tmp/diffy", "+++ /tmp/diffy")
end
def identification_type(line)
@@ -82,8 +90,6 @@ module Gitlab
"new"
when "-"
"old"
- else
- nil
end
end
end
diff --git a/lib/gitlab/diff/position.rb b/lib/gitlab/diff/position.rb
index e8f98f52111..8ad7023d68f 100644
--- a/lib/gitlab/diff/position.rb
+++ b/lib/gitlab/diff/position.rb
@@ -8,17 +8,17 @@ module Gitlab
attr_accessor :formatter
delegate :old_path,
- :new_path,
- :base_sha,
- :start_sha,
- :head_sha,
- :old_line,
- :new_line,
- :width,
- :height,
- :x,
- :y,
- :position_type, to: :formatter
+ :new_path,
+ :base_sha,
+ :start_sha,
+ :head_sha,
+ :old_line,
+ :new_line,
+ :width,
+ :height,
+ :x,
+ :y,
+ :position_type, to: :formatter
# A position can belong to a text line or to an image coordinate
# it depends of the position_type argument.
@@ -34,13 +34,13 @@ module Gitlab
# behavior. In this case, we override these to prevent memoized instance
# variables like `@diff_file` and `@diff_line` from being serialized.
def init_with(coder)
- initialize(coder['attributes'])
+ initialize(coder["attributes"])
self
end
def encode_with(coder)
- coder['attributes'] = formatter.to_h
+ coder["attributes"] = formatter.to_h
end
def key
@@ -84,11 +84,11 @@ module Gitlab
end
def added?
- type == 'new'
+ type == "new"
end
def removed?
- type == 'old'
+ type == "old"
end
def paths
@@ -115,7 +115,7 @@ module Gitlab
project_id: repository.project.id,
start_sha: start_sha,
head_sha: head_sha,
- path: file_path
+ path: file_path,
}
Gitlab::SafeRequestStore.fetch(key) { find_diff_file(repository) }
@@ -123,7 +123,7 @@ module Gitlab
end
def diff_options
- { paths: paths, expanded: true, include_stats: false }
+ {paths: paths, expanded: true, include_stats: false}
end
def diff_line(repository)
@@ -153,7 +153,7 @@ module Gitlab
type ||= "text"
case type
- when 'image'
+ when "image"
Gitlab::Diff::Formatters::ImageFormatter
else
Gitlab::Diff::Formatters::TextFormatter
diff --git a/lib/gitlab/diff/position_tracer.rb b/lib/gitlab/diff/position_tracer.rb
index af3df820422..2e81a0736d5 100644
--- a/lib/gitlab/diff/position_tracer.rb
+++ b/lib/gitlab/diff/position_tracer.rb
@@ -110,21 +110,21 @@ module Gitlab
new_position = position(cd_diff, c_line, d_line)
if valid_position?(new_position)
# If the line is still in the MR, we don't treat this as outdated.
- { position: new_position, outdated: false }
+ {position: new_position, outdated: false}
else
# If the line is no longer in the MR, we unfortunately cannot show
# the current state on the CD diff, so we treat it as outdated.
ac_diff = ac_diffs.diff_file_with_new_path(c_path)
- { position: position(ac_diff, nil, c_line), outdated: true }
+ {position: position(ac_diff, nil, c_line), outdated: true}
end
else
# If the line is still in D and not in C, it is still added.
- { position: position(cd_diff, nil, d_line), outdated: false }
+ {position: position(cd_diff, nil, d_line), outdated: false}
end
else
# If the line is no longer in D, it has been removed from the MR.
- { position: position(bd_diff, b_line, nil), outdated: true }
+ {position: position(bd_diff, b_line, nil), outdated: true}
end
end
@@ -148,14 +148,14 @@ module Gitlab
# removed line into an unchanged one.
bd_diff = bd_diffs.diff_file_with_new_path(d_path)
- { position: position(bd_diff, nil, d_line), outdated: true }
+ {position: position(bd_diff, nil, d_line), outdated: true}
else
# If the line is still in C and not in D, it is still removed.
- { position: position(cd_diff, c_line, nil), outdated: false }
+ {position: position(cd_diff, c_line, nil), outdated: false}
end
else
# If the line is no longer in C, it has been removed outside of the MR.
- { position: position(ac_diff, a_line, nil), outdated: true }
+ {position: position(ac_diff, a_line, nil), outdated: true}
end
end
@@ -181,22 +181,22 @@ module Gitlab
new_position = position(cd_diff, c_line, d_line)
if valid_position?(new_position)
# If the line is still in the MR, we don't treat this as outdated.
- { position: new_position, outdated: false }
+ {position: new_position, outdated: false}
else
# If the line is no longer in the MR, we unfortunately cannot show
# the current state on the CD diff or any change on the BD diff,
# so we treat it as outdated.
- { position: nil, outdated: true }
+ {position: nil, outdated: true}
end
elsif d_line # && !c_line
# If the line is still in D but no longer in C, it has turned from
# an unchanged line into an added one.
# We don't treat this as outdated since the line is still in the MR.
- { position: position(cd_diff, nil, d_line), outdated: false }
+ {position: position(cd_diff, nil, d_line), outdated: false}
else # !d_line && (c_line || !c_line)
# If the line is no longer in D, it has turned from an unchanged line
# into a removed one.
- { position: position(bd_diff, b_line, nil), outdated: true }
+ {position: position(bd_diff, b_line, nil), outdated: true}
end
end
diff --git a/lib/gitlab/discussions_diff/highlight_cache.rb b/lib/gitlab/discussions_diff/highlight_cache.rb
index 270cfb89488..dcc5451e04e 100644
--- a/lib/gitlab/discussions_diff/highlight_cache.rb
+++ b/lib/gitlab/discussions_diff/highlight_cache.rb
@@ -1,5 +1,5 @@
# frozen_string_literal: true
-#
+
module Gitlab
module DiscussionsDiff
class HighlightCache
@@ -35,9 +35,9 @@ module Gitlab
keys = raw_keys.map { |id| cache_key_for(id) }
content =
- Redis::Cache.with do |redis|
+ Redis::Cache.with { |redis|
redis.mget(keys)
- end
+ }
content.map! do |lines|
next unless lines
diff --git a/lib/gitlab/downtime_check.rb b/lib/gitlab/downtime_check.rb
index 31bb6810391..7918521797b 100644
--- a/lib/gitlab/downtime_check.rb
+++ b/lib/gitlab/downtime_check.rb
@@ -52,7 +52,7 @@ module Gitlab
# Returns the class for the given migration file path.
def class_for_migration_file(path)
- File.basename(path, File.extname(path)).split('_', 2).last.camelize
+ File.basename(path, File.extname(path)).split("_", 2).last.camelize
.constantize
end
@@ -65,8 +65,6 @@ module Gitlab
def downtime_reason(migration)
if migration.const_defined?(DOWNTIME_REASON_CONST)
migration.const_get(DOWNTIME_REASON_CONST)
- else
- nil
end
end
end
diff --git a/lib/gitlab/downtime_check/message.rb b/lib/gitlab/downtime_check/message.rb
index ec38bd769a3..5debb754943 100644
--- a/lib/gitlab/downtime_check/message.rb
+++ b/lib/gitlab/downtime_check/message.rb
@@ -5,8 +5,8 @@ module Gitlab
class Message
attr_reader :path, :offline
- OFFLINE = "\e[31moffline\e[0m".freeze
- ONLINE = "\e[32monline\e[0m".freeze
+ OFFLINE = "\e[31moffline\e[0m"
+ ONLINE = "\e[32monline\e[0m"
# path - The file path of the migration.
# offline - When set to `true` the migration will require downtime.
diff --git a/lib/gitlab/ee_compat_check.rb b/lib/gitlab/ee_compat_check.rb
index 01fd261404b..8131e1f6523 100644
--- a/lib/gitlab/ee_compat_check.rb
+++ b/lib/gitlab/ee_compat_check.rb
@@ -4,24 +4,24 @@
module Gitlab
# Checks if a set of migrations requires downtime or not.
class EeCompatCheck
- CANONICAL_CE_PROJECT_URL = 'https://gitlab.com/gitlab-org/gitlab-ce'.freeze
- CANONICAL_EE_REPO_URL = 'https://gitlab.com/gitlab-org/gitlab-ee.git'.freeze
- CHECK_DIR = Rails.root.join('ee_compat_check')
+ CANONICAL_CE_PROJECT_URL = "https://gitlab.com/gitlab-org/gitlab-ce"
+ CANONICAL_EE_REPO_URL = "https://gitlab.com/gitlab-org/gitlab-ee.git"
+ CHECK_DIR = Rails.root.join("ee_compat_check")
IGNORED_FILES_REGEX = /VERSION|CHANGELOG\.md/i.freeze
- PLEASE_READ_THIS_BANNER = %Q{
+ PLEASE_READ_THIS_BANNER = %(
============================================================
===================== PLEASE READ THIS =====================
============================================================
- }.freeze
- STAY_STRONG_LINK_TO_DOCS = %Q{
+ )
+ STAY_STRONG_LINK_TO_DOCS = %(
Stay 💪! For more information, see
https://docs.gitlab.com/ce/development/automatic_ce_ee_merge.html
- }.freeze
- THANKS_FOR_READING_BANNER = %Q{
+ )
+ THANKS_FOR_READING_BANNER = %(
============================================================
==================== THANKS FOR READING ====================
============================================================\n
- }.freeze
+ )
attr_reader :ee_repo_dir, :patches_dir
attr_reader :ce_project_url, :ee_repo_url
@@ -29,11 +29,11 @@ module Gitlab
attr_reader :job_id, :failed_files
def initialize(branch:, ce_project_url: CANONICAL_CE_PROJECT_URL, job_id: nil)
- @ee_repo_dir = CHECK_DIR.join('ee-repo')
- @patches_dir = CHECK_DIR.join('patches')
+ @ee_repo_dir = CHECK_DIR.join("ee-repo")
+ @patches_dir = CHECK_DIR.join("patches")
@ce_branch = branch
@ce_project_url = ce_project_url
- @ee_repo_url = ce_public_repo_url.sub('gitlab-ce', 'gitlab-ee')
+ @ee_repo_url = ce_public_repo_url.sub("gitlab-ce", "gitlab-ee")
@job_id = job_id
end
@@ -41,8 +41,8 @@ module Gitlab
ensure_patches_dir
# We're generating the patch against the canonical-ce remote since forks'
# master branch are not necessarily up-to-date.
- add_remote('canonical-ce', "#{CANONICAL_CE_PROJECT_URL}.git")
- generate_patch(branch: ce_branch, patch_path: ce_patch_full_path, branch_remote: 'origin', master_remote: 'canonical-ce')
+ add_remote("canonical-ce", "#{CANONICAL_CE_PROJECT_URL}.git")
+ generate_patch(branch: ce_branch, patch_path: ce_patch_full_path, branch_remote: "origin", master_remote: "canonical-ce")
ensure_ee_repo
Dir.chdir(ee_repo_dir) do
@@ -51,17 +51,17 @@ module Gitlab
ee_remotes.each do |key, url|
add_remote(key, url)
end
- fetch(branch: 'master', depth: 20, remote: 'canonical-ee')
+ fetch(branch: "master", depth: 20, remote: "canonical-ee")
- status = catch(:halt_check) do
+ status = catch(:halt_check) {
ce_branch_compat_check!
delete_ee_branches_locally!
ee_branch_presence_check!
step("Checking out #{ee_remote_with_branch}/#{ee_branch_found}", %W[git checkout -b #{ee_branch_found} #{ee_remote_with_branch}/#{ee_branch_found}])
- generate_patch(branch: ee_branch_found, patch_path: ee_patch_full_path, branch_remote: ee_remote_with_branch, master_remote: 'canonical-ee')
+ generate_patch(branch: ee_branch_found, patch_path: ee_patch_full_path, branch_remote: ee_remote_with_branch, master_remote: "canonical-ee")
ee_branch_compat_check!
- end
+ }
delete_ee_branches_locally!
@@ -80,10 +80,10 @@ module Gitlab
remotes =
{
- 'ee' => ee_repo_url,
- 'canonical-ee' => CANONICAL_EE_REPO_URL
+ "ee" => ee_repo_url,
+ "canonical-ee" => CANONICAL_EE_REPO_URL,
}
- remotes.delete('ee') unless fork?
+ remotes.delete("ee") unless fork?
@ee_remotes = remotes
end
@@ -142,7 +142,8 @@ module Gitlab
ee_remotes.keys.each do |remote|
output, _ = step(
"Searching #{remote}",
- %W[git ls-remote #{remote} *#{minimal_ee_branch_name}*])
+ %W[git ls-remote #{remote} *#{minimal_ee_branch_name}*]
+ )
branches =
output.scan(%r{(?<=refs/heads/|refs/tags/).+}).sort_by(&:size)
@@ -195,14 +196,12 @@ module Gitlab
puts output
unless status.zero?
- @failed_files = output.lines.reduce([]) do |memo, line|
- if line.start_with?('error: patch failed:')
- file = line.sub(/\Aerror: patch failed: /, '')
+ @failed_files = output.lines.each_with_object([]) { |line, memo|
+ if line.start_with?("error: patch failed:")
+ file = line.sub(/\Aerror: patch failed: /, "")
memo << file unless file =~ IGNORED_FILES_REGEX
end
-
- memo
- end
+ }
status = 0 if failed_files.empty?
end
@@ -235,20 +234,20 @@ module Gitlab
# In total we go (20 + 54 + 148 + 403 = 625) commits deeper
depth = 20
success =
- (3..6).any? do |factor|
+ (3..6).any? { |factor|
depth += Math.exp(factor).to_i
# Repository is initially cloned with a depth of 20 so we need to fetch
# deeper in the case the branch has more than 20 commits on top of master
fetch(branch: branch, depth: depth, remote: branch_remote)
- fetch(branch: 'master', depth: depth, remote: master_remote)
+ fetch(branch: "master", depth: depth, remote: master_remote)
merge_base_found?(branch: branch, branch_remote: branch_remote, master_remote: master_remote)
- end
+ }
raise "\n#{branch} is too far behind #{master_remote}/master, please rebase it!\n" unless success
end
- def fetch(branch:, depth:, remote: 'origin')
+ def fetch(branch:, depth:, remote: "origin")
step(
"Fetching deeper...",
%W[git fetch --depth=#{depth} --prune #{remote} +refs/heads/#{branch}:refs/remotes/#{remote}/#{branch}]
@@ -282,7 +281,7 @@ module Gitlab
end
def minimal_ee_branch_name
- @minimal_ee_branch_name ||= ce_branch.sub(/(\Ace\-|\-ce\z)/, '')
+ @minimal_ee_branch_name ||= ce_branch.sub(/(\Ace\-|\-ce\z)/, "")
end
def patch_name_from_branch(branch_name)
@@ -298,7 +297,7 @@ module Gitlab
if cmd
start = Time.now
- puts "\n$ #{cmd.join(' ')}"
+ puts "\n$ #{cmd.join(" ")}"
output, status = command(cmd)
puts "\n==> Finished in #{Time.now - start} seconds"
@@ -323,7 +322,7 @@ module Gitlab
end
def applies_cleanly_msg(branch)
- %Q{
+ %(
#{PLEASE_READ_THIS_BANNER}
🎉 Congratulations!! 🎉
@@ -332,19 +331,19 @@ module Gitlab
Much ❤️! For more information, see
https://docs.gitlab.com/ce/development/automatic_ce_ee_merge.html
#{THANKS_FOR_READING_BANNER}
- }
+ )
end
def ce_branch_doesnt_apply_cleanly_and_no_ee_branch_msg
ee_repos = ee_remotes.values.uniq
- %Q{
+ %(
#{PLEASE_READ_THIS_BANNER}
💥 Oh no! 💥
The `#{ce_branch}` branch does not apply cleanly to the current
EE/master, and no `#{ee_branch_prefix}` or `#{ee_branch_suffix}` branch
- was found in #{ee_repos.join(' nor in ')}.
+ was found in #{ee_repos.join(" nor in ")}.
If you're a community contributor, don't worry, someone from
GitLab Inc. will take care of this, and you don't have to do anything.
@@ -410,11 +409,11 @@ module Gitlab
#{STAY_STRONG_LINK_TO_DOCS}
#{THANKS_FOR_READING_BANNER}
- }
+ )
end
def ee_branch_doesnt_apply_cleanly_msg
- %Q{
+ %(
#{PLEASE_READ_THIS_BANNER}
💥 Oh no! 💥
@@ -430,7 +429,7 @@ module Gitlab
#{STAY_STRONG_LINK_TO_DOCS}
#{THANKS_FOR_READING_BANNER}
- }
+ )
end
def conflicting_files_msg
diff --git a/lib/gitlab/email/attachment_uploader.rb b/lib/gitlab/email/attachment_uploader.rb
index 3323ce60158..7e5d61b4294 100644
--- a/lib/gitlab/email/attachment_uploader.rb
+++ b/lib/gitlab/email/attachment_uploader.rb
@@ -18,9 +18,9 @@ module Gitlab
File.open(tmp.path, "w+b") { |f| f.write attachment.body.decoded }
file = {
- tempfile: tmp,
- filename: attachment.filename,
- content_type: attachment.content_type
+ tempfile: tmp,
+ filename: attachment.filename,
+ content_type: attachment.content_type,
}
uploader = UploadService.new(project, file).execute
diff --git a/lib/gitlab/email/handler.rb b/lib/gitlab/email/handler.rb
index cebedb19dcc..c8be5d66e35 100644
--- a/lib/gitlab/email/handler.rb
+++ b/lib/gitlab/email/handler.rb
@@ -12,7 +12,7 @@ module Gitlab
UnsubscribeHandler,
CreateNoteHandler,
CreateMergeRequestHandler,
- CreateIssueHandler
+ CreateIssueHandler,
]
end
diff --git a/lib/gitlab/email/handler/base_handler.rb b/lib/gitlab/email/handler/base_handler.rb
index f89d1d15010..a22473e0c3a 100644
--- a/lib/gitlab/email/handler/base_handler.rb
+++ b/lib/gitlab/email/handler/base_handler.rb
@@ -22,7 +22,7 @@ module Gitlab
end
def metrics_params
- { handler: self.class.name }
+ {handler: self.class.name}
end
end
end
diff --git a/lib/gitlab/email/handler/create_issue_handler.rb b/lib/gitlab/email/handler/create_issue_handler.rb
index 78a3a9489ac..3ac4d3e2c2b 100644
--- a/lib/gitlab/email/handler/create_issue_handler.rb
+++ b/lib/gitlab/email/handler/create_issue_handler.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'gitlab/email/handler/base_handler'
+require "gitlab/email/handler/base_handler"
# handles issue creation emails with these formats:
# incoming+gitlab-org-gitlab-ce-20-Author_Token12345678-issue@incoming.gitlab.com
@@ -17,7 +17,7 @@ module Gitlab
def initialize(mail, mail_key)
super(mail, mail_key)
- if !mail_key&.include?('/') && (matched = HANDLER_REGEX.match(mail_key.to_s))
+ if !mail_key&.include?("/") && (matched = HANDLER_REGEX.match(mail_key.to_s))
@project_slug = matched[:project_slug]
@project_id = matched[:project_id]&.to_i
@incoming_email_token = matched[:incoming_email_token]
@@ -39,7 +39,8 @@ module Gitlab
verify_record!(
record: create_issue,
invalid_exception: InvalidIssueError,
- record_name: 'issue')
+ record_name: "issue"
+ )
end
# rubocop: disable CodeReuse/ActiveRecord
@@ -54,13 +55,13 @@ module Gitlab
Issues::CreateService.new(
project,
author,
- title: mail.subject,
+ title: mail.subject,
description: message_including_reply
).execute
end
def can_handle_legacy_format?
- project_path && !incoming_email_token.include?('+') && !mail_key.include?(Gitlab::IncomingEmail::UNSUBSCRIBE_SUFFIX_LEGACY)
+ project_path && !incoming_email_token.include?("+") && !mail_key.include?(Gitlab::IncomingEmail::UNSUBSCRIBE_SUFFIX_LEGACY)
end
end
end
diff --git a/lib/gitlab/email/handler/create_merge_request_handler.rb b/lib/gitlab/email/handler/create_merge_request_handler.rb
index b3b5063f2ca..dc7f8a5614e 100644
--- a/lib/gitlab/email/handler/create_merge_request_handler.rb
+++ b/lib/gitlab/email/handler/create_merge_request_handler.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'gitlab/email/handler/base_handler'
-require 'gitlab/email/handler/reply_processing'
+require "gitlab/email/handler/base_handler"
+require "gitlab/email/handler/reply_processing"
# handles merge request creation emails with these formats:
# incoming+gitlab-org-gitlab-ce-20-Author_Token12345678-merge-request@incoming.gitlab.com
@@ -18,7 +18,7 @@ module Gitlab
def initialize(mail, mail_key)
super(mail, mail_key)
- if !mail_key&.include?('/') && (matched = HANDLER_REGEX.match(mail_key.to_s))
+ if !mail_key&.include?("/") && (matched = HANDLER_REGEX.match(mail_key.to_s))
@project_slug = matched[:project_slug]
@project_id = matched[:project_id]&.to_i
@incoming_email_token = matched[:incoming_email_token]
@@ -41,7 +41,8 @@ module Gitlab
verify_record!(
record: create_merge_request,
invalid_exception: InvalidMergeRequestError,
- record_name: 'merge_request')
+ record_name: "merge_request"
+ )
end
# rubocop: disable CodeReuse/ActiveRecord
@@ -82,7 +83,7 @@ module Gitlab
params = {
source_project_id: project.id,
source_branch: source_branch,
- target_project_id: project.id
+ target_project_id: project.id,
}
params[:description] = message if message.present?
params
@@ -92,8 +93,8 @@ module Gitlab
patches = patch_attachments.map { |patch| patch.body.decoded }
result = Commits::CommitPatchService
- .new(project, author, branch_name: source_branch, patches: patches, start_branch: start_branch)
- .execute
+ .new(project, author, branch_name: source_branch, patches: patches, start_branch: start_branch)
+ .execute
if result[:status] != :success
message = "Could not apply patches to #{source_branch}:\n#{result[:message]}"
@@ -110,8 +111,8 @@ module Gitlab
def patch_attachments
@patches ||= mail.attachments
- .select { |attachment| attachment.filename.ends_with?('.patch') }
- .sort_by(&:filename)
+ .select { |attachment| attachment.filename.ends_with?(".patch") }
+ .sort_by(&:filename)
end
def source_branch
diff --git a/lib/gitlab/email/handler/create_note_handler.rb b/lib/gitlab/email/handler/create_note_handler.rb
index b00af15364d..2efd59ebd84 100644
--- a/lib/gitlab/email/handler/create_note_handler.rb
+++ b/lib/gitlab/email/handler/create_note_handler.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'gitlab/email/handler/base_handler'
-require 'gitlab/email/handler/reply_processing'
+require "gitlab/email/handler/base_handler"
+require "gitlab/email/handler/reply_processing"
# handles note/reply creation emails with these formats:
# incoming+1234567890abcdef1234567890abcdef@incoming.gitlab.com
@@ -29,7 +29,8 @@ module Gitlab
verify_record!(
record: create_note,
invalid_exception: InvalidNoteError,
- record_name: 'comment')
+ record_name: "comment"
+ )
end
private
diff --git a/lib/gitlab/email/handler/reply_processing.rb b/lib/gitlab/email/handler/reply_processing.rb
index d8f4be8ada1..d959fc79afe 100644
--- a/lib/gitlab/email/handler/reply_processing.rb
+++ b/lib/gitlab/email/handler/reply_processing.rb
@@ -43,9 +43,9 @@ module Gitlab
def add_attachments(reply)
attachments = Email::AttachmentUploader.new(mail).execute(project)
- reply + attachments.map do |link|
+ reply + attachments.map { |link|
"\n\n#{link[:markdown]}"
- end.join
+ }.join
end
def validate_permission!(permission)
@@ -65,9 +65,9 @@ module Gitlab
error_title = "The #{record_name} could not be created for the following reasons:"
- msg = error_title + record.errors.full_messages.map do |error|
+ msg = error_title + record.errors.full_messages.map { |error|
"\n\n- #{error}"
- end.join
+ }.join
raise invalid_exception, msg
end
diff --git a/lib/gitlab/email/handler/unsubscribe_handler.rb b/lib/gitlab/email/handler/unsubscribe_handler.rb
index 20e4c125626..490dd6ad64d 100644
--- a/lib/gitlab/email/handler/unsubscribe_handler.rb
+++ b/lib/gitlab/email/handler/unsubscribe_handler.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'gitlab/email/handler/base_handler'
+require "gitlab/email/handler/base_handler"
# handles unsubscribe emails with these formats:
# incoming+1234567890abcdef1234567890abcdef-unsubscribe@incoming.gitlab.com
@@ -11,7 +11,7 @@ module Gitlab
class UnsubscribeHandler < BaseHandler
delegate :project, to: :sent_notification, allow_nil: true
- HANDLER_REGEX_FOR = -> (suffix) { /\A(?<reply_token>\w+)#{Regexp.escape(suffix)}\z/ }.freeze
+ HANDLER_REGEX_FOR = ->(suffix) { /\A(?<reply_token>\w+)#{Regexp.escape(suffix)}\z/ }.freeze
HANDLER_REGEX = HANDLER_REGEX_FOR.call(Gitlab::IncomingEmail::UNSUBSCRIBE_SUFFIX).freeze
HANDLER_REGEX_LEGACY = HANDLER_REGEX_FOR.call(Gitlab::IncomingEmail::UNSUBSCRIBE_SUFFIX_LEGACY).freeze
diff --git a/lib/gitlab/email/hook/additional_headers_interceptor.rb b/lib/gitlab/email/hook/additional_headers_interceptor.rb
index aa2ef76069b..0039aa1b585 100644
--- a/lib/gitlab/email/hook/additional_headers_interceptor.rb
+++ b/lib/gitlab/email/hook/additional_headers_interceptor.rb
@@ -5,8 +5,8 @@ module Gitlab
module Hook
class AdditionalHeadersInterceptor
def self.delivering_email(message)
- message.header['Auto-Submitted'] ||= 'auto-generated'
- message.header['X-Auto-Response-Suppress'] ||= 'All'
+ message.header["Auto-Submitted"] ||= "auto-generated"
+ message.header["X-Auto-Response-Suppress"] ||= "All"
end
end
end
diff --git a/lib/gitlab/email/hook/delivery_metrics_observer.rb b/lib/gitlab/email/hook/delivery_metrics_observer.rb
index c7af485fcc5..47b8ef081a7 100644
--- a/lib/gitlab/email/hook/delivery_metrics_observer.rb
+++ b/lib/gitlab/email/hook/delivery_metrics_observer.rb
@@ -17,14 +17,14 @@ module Gitlab
def self.delivery_attempts_counter
strong_memoize(:delivery_attempts_counter) do
Gitlab::Metrics.counter(:gitlab_emails_delivery_attempts_total,
- 'Counter of total emails delivery attempts')
+ "Counter of total emails delivery attempts")
end
end
def self.delivered_emails_counter
strong_memoize(:delivered_emails_counter) do
Gitlab::Metrics.counter(:gitlab_emails_delivered_total,
- 'Counter of total emails delievered')
+ "Counter of total emails delievered")
end
end
end
diff --git a/lib/gitlab/email/hook/email_template_interceptor.rb b/lib/gitlab/email/hook/email_template_interceptor.rb
index 13f8db2051d..c44dab605cd 100644
--- a/lib/gitlab/email/hook/email_template_interceptor.rb
+++ b/lib/gitlab/email/hook/email_template_interceptor.rb
@@ -10,7 +10,7 @@ module Gitlab
def self.delivering_email(message)
unless Gitlab::CurrentSettings.html_emails_enabled
message.parts.delete_if do |part|
- part.content_type.start_with?('text/html')
+ part.content_type.start_with?("text/html")
end
end
end
diff --git a/lib/gitlab/email/html_parser.rb b/lib/gitlab/email/html_parser.rb
index 77f299bcade..ed580957990 100644
--- a/lib/gitlab/email/html_parser.rb
+++ b/lib/gitlab/email/html_parser.rb
@@ -17,13 +17,13 @@ module Gitlab
end
def filter_replies!
- document.xpath('//blockquote').each(&:remove)
- document.xpath('//table').each(&:remove)
+ document.xpath("//blockquote").each(&:remove)
+ document.xpath("//table").each(&:remove)
# bogus links with no href are sometimes added by outlook,
# and can result in Html2Text adding extra square brackets
# to the text, so we unwrap them here.
- document.xpath('//a[not(@href)]').each do |link|
+ document.xpath("//a[not(@href)]").each do |link|
link.replace(link.children)
end
end
diff --git a/lib/gitlab/email/message/repository_push.rb b/lib/gitlab/email/message/repository_push.rb
index ec412e7a8b1..42e6bd6c055 100644
--- a/lib/gitlab/email/message/repository_push.rb
+++ b/lib/gitlab/email/message/repository_push.rb
@@ -14,7 +14,7 @@ module Gitlab
delegate :username, to: :author, prefix: :author
def initialize(notify, project_id, opts = {})
- raise ArgumentError, 'Missing options: author_id, ref, action' unless
+ raise ArgumentError, "Missing options: author_id, ref, action" unless
opts[:author_id] && opts[:ref] && opts[:action]
@notify = notify
@@ -52,7 +52,7 @@ module Gitlab
end
def compare
- @opts[:compare] if @opts[:compare]
+ @opts[:compare]
end
def diff_refs
@@ -79,11 +79,11 @@ module Gitlab
@action_name ||=
case @action
when :create
- 'pushed new'
+ "pushed new"
when :delete
- 'deleted'
+ "deleted"
else
- 'pushed to'
+ "pushed to"
end
end
@@ -92,7 +92,7 @@ module Gitlab
end
def ref_type
- @ref_type ||= Gitlab::Git.tag_ref?(@ref) ? 'tag' : 'branch'
+ @ref_type ||= Gitlab::Git.tag_ref?(@ref) ? "tag" : "branch"
end
def target_url
@@ -118,10 +118,10 @@ module Gitlab
end
def subject
- subject_text = ['[Git]']
+ subject_text = ["[Git]"]
subject_text << "[#{project.full_path}]"
subject_text << "[#{ref_name}]" if @action == :push
- subject_text << ' '
+ subject_text << " "
if @action == :push && commits
if commits.length > 1
diff --git a/lib/gitlab/email/receiver.rb b/lib/gitlab/email/receiver.rb
index d28f6b301fa..20147deb0b2 100644
--- a/lib/gitlab/email/receiver.rb
+++ b/lib/gitlab/email/receiver.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_dependency 'gitlab/email/handler'
+require_dependency "gitlab/email/handler"
# Inspired in great part by Discourse's Email::Receiver
module Gitlab
@@ -98,12 +98,12 @@ module Gitlab
def ignore_auto_submitted!(mail)
# Mail::Header#[] is case-insensitive
- auto_submitted = mail.header['Auto-Submitted']&.value
+ auto_submitted = mail.header["Auto-Submitted"]&.value
# Mail::Field#value would strip leading and trailing whitespace
raise AutoGeneratedEmailError if
# See also https://tools.ietf.org/html/rfc3834
- auto_submitted && auto_submitted != 'no'
+ auto_submitted && auto_submitted != "no"
end
end
end
diff --git a/lib/gitlab/email/reply_parser.rb b/lib/gitlab/email/reply_parser.rb
index 2743f011ca6..d26ee83a161 100644
--- a/lib/gitlab/email/reply_parser.rb
+++ b/lib/gitlab/email/reply_parser.rb
@@ -20,15 +20,15 @@ module Gitlab
body = EmailReplyTrimmer.trim(body)
end
- return '' unless body
+ return "" unless body
# not using /\s+$/ here because that deletes empty lines
- body = body.gsub(/[ \t]$/, '')
+ body = body.gsub(/[ \t]$/, "")
# NOTE: We currently don't support empty quotes.
# EmailReplyTrimmer allows this as a special case,
# so we detect it manually here.
- return "" if body.lines.all? { |l| l.strip.empty? || l.start_with?('>') }
+ return "" if body.lines.all? { |l| l.strip.empty? || l.start_with?(">") }
body.force_encoding(encoding).encode("UTF-8")
end
@@ -48,11 +48,11 @@ module Gitlab
return "" unless decoded
# Certain trigger phrases that means we didn't parse correctly
- if decoded =~ %r{(Content\-Type\:|multipart/alternative|text/plain)}
+ if %r{(Content\-Type\:|multipart/alternative|text/plain)}.match?(decoded)
return ""
end
- if (part.content_type || '').include? 'text/html'
+ if (part.content_type || "").include? "text/html"
HTMLParser.parse_reply(decoded)
else
decoded
diff --git a/lib/gitlab/emoji.rb b/lib/gitlab/emoji.rb
index ce1dfb0753c..9c3ba1c10ea 100644
--- a/lib/gitlab/emoji.rb
+++ b/lib/gitlab/emoji.rb
@@ -21,7 +21,7 @@ module Gitlab
end
def emojis_aliases
- @emoji_aliases ||= JSON.parse(File.read(Rails.root.join('fixtures', 'emojis', 'aliases.json')))
+ @emoji_aliases ||= JSON.parse(File.read(Rails.root.join("fixtures", "emojis", "aliases.json")))
end
def emoji_filename(name)
@@ -52,17 +52,17 @@ module Gitlab
data = {
name: emoji_name,
- unicode_version: emoji_unicode_version(emoji_name)
+ unicode_version: emoji_unicode_version(emoji_name),
}
- ActionController::Base.helpers.content_tag('gl-emoji', emoji_info['moji'], title: emoji_info['description'], data: data)
+ ActionController::Base.helpers.content_tag("gl-emoji", emoji_info["moji"], title: emoji_info["description"], data: data)
end
private
def emoji_unicode_versions_by_name
@emoji_unicode_versions_by_name ||=
- JSON.parse(File.read(Rails.root.join('fixtures', 'emojis', 'emoji-unicode-version-map.json')))
+ JSON.parse(File.read(Rails.root.join("fixtures", "emojis", "emoji-unicode-version-map.json")))
end
end
end
diff --git a/lib/gitlab/encoding_helper.rb b/lib/gitlab/encoding_helper.rb
index a4a154c80f7..5dfbed77677 100644
--- a/lib/gitlab/encoding_helper.rb
+++ b/lib/gitlab/encoding_helper.rb
@@ -31,7 +31,7 @@ module Gitlab
# encode and clean the bad chars
message.replace clean(message)
rescue ArgumentError => e
- return unless e.message.include?('unknown encoding name')
+ return unless e.message.include?("unknown encoding name")
encoding = detect ? detect[:encoding] : "unknown"
"--broken encoding: #{encoding}"
@@ -57,11 +57,11 @@ module Gitlab
detect = CharlockHolmes::EncodingDetector.detect(message)
if detect && detect[:encoding]
begin
- CharlockHolmes::Converter.convert(message, detect[:encoding], 'UTF-8')
+ CharlockHolmes::Converter.convert(message, detect[:encoding], "UTF-8")
rescue ArgumentError => e
Rails.logger.warn("Ignoring error converting #{detect[:encoding]} into UTF8: #{e.message}")
- ''
+ ""
end
else
clean(message)
@@ -77,7 +77,7 @@ module Gitlab
end
def binary_stringio(str)
- StringIO.new(str.freeze || '').tap { |io| io.set_encoding(Encoding::ASCII_8BIT) }
+ StringIO.new(str.freeze || "").tap { |io| io.set_encoding(Encoding::ASCII_8BIT) }
end
private
diff --git a/lib/gitlab/environment.rb b/lib/gitlab/environment.rb
index b1a9603d3a5..8f4416de435 100644
--- a/lib/gitlab/environment.rb
+++ b/lib/gitlab/environment.rb
@@ -3,7 +3,7 @@
module Gitlab
module Environment
def self.hostname
- @hostname ||= ENV['HOSTNAME'] || Socket.gethostname
+ @hostname ||= ENV["HOSTNAME"] || Socket.gethostname
end
end
end
diff --git a/lib/gitlab/error_tracking/project.rb b/lib/gitlab/error_tracking/project.rb
index 93e81da5034..b98ffcf0007 100644
--- a/lib/gitlab/error_tracking/project.rb
+++ b/lib/gitlab/error_tracking/project.rb
@@ -7,7 +7,7 @@ module Gitlab
ACCESSORS = [
:id, :name, :status, :slug, :organization_name,
- :organization_id, :organization_slug
+ :organization_id, :organization_slug,
].freeze
attr_accessor(*ACCESSORS)
diff --git a/lib/gitlab/etag_caching/middleware.rb b/lib/gitlab/etag_caching/middleware.rb
index a11d6b66409..c39866132ff 100644
--- a/lib/gitlab/etag_caching/middleware.rb
+++ b/lib/gitlab/etag_caching/middleware.rb
@@ -15,7 +15,7 @@ module Gitlab
track_event(:etag_caching_middleware_used, route)
etag, cached_value_present = get_etag(request)
- if_none_match = env['HTTP_IF_NONE_MATCH']
+ if_none_match = env["HTTP_IF_NONE_MATCH"]
if if_none_match == etag
handle_cache_hit(etag, route)
@@ -23,7 +23,7 @@ module Gitlab
track_cache_miss(if_none_match, cached_value_present, route)
status, headers, body = @app.call(env)
- headers['ETag'] = etag
+ headers["ETag"] = etag
[status, headers, body]
end
end
@@ -44,7 +44,7 @@ module Gitlab
end
def weak_etag_format(value)
- %Q{W/"#{value}"}
+ %(W/"#{value}")
end
def handle_cache_hit(etag, route)
@@ -52,7 +52,7 @@ module Gitlab
status_code = Gitlab::PollingInterval.polling_enabled? ? 304 : 429
- [status_code, { 'ETag' => etag, 'X-Gitlab-From-Cache' => 'true' }, []]
+ [status_code, {"ETag" => etag, "X-Gitlab-From-Cache" => "true"}, []]
end
def track_cache_miss(if_none_match, cached_value_present, route)
diff --git a/lib/gitlab/etag_caching/router.rb b/lib/gitlab/etag_caching/router.rb
index 0891f79198d..76f7e5cfa90 100644
--- a/lib/gitlab/etag_caching/router.rb
+++ b/lib/gitlab/etag_caching/router.rb
@@ -18,49 +18,49 @@ module Gitlab
ROUTES = [
Gitlab::EtagCaching::Router::Route.new(
- %r(^(?!.*(#{RESERVED_WORDS_REGEX})).*/noteable/issue/\d+/notes\z),
- 'issue_notes'
+ %r{^(?!.*(#{RESERVED_WORDS_REGEX})).*/noteable/issue/\d+/notes\z},
+ "issue_notes"
),
Gitlab::EtagCaching::Router::Route.new(
- %r(^(?!.*(#{RESERVED_WORDS_REGEX})).*/issues/\d+/realtime_changes\z),
- 'issue_title'
+ %r{^(?!.*(#{RESERVED_WORDS_REGEX})).*/issues/\d+/realtime_changes\z},
+ "issue_title"
),
Gitlab::EtagCaching::Router::Route.new(
- %r(^(?!.*(#{RESERVED_WORDS_REGEX})).*/commit/\S+/pipelines\.json\z),
- 'commit_pipelines'
+ %r{^(?!.*(#{RESERVED_WORDS_REGEX})).*/commit/\S+/pipelines\.json\z},
+ "commit_pipelines"
),
Gitlab::EtagCaching::Router::Route.new(
- %r(^(?!.*(#{RESERVED_WORDS_REGEX})).*/merge_requests/new\.json\z),
- 'new_merge_request_pipelines'
+ %r{^(?!.*(#{RESERVED_WORDS_REGEX})).*/merge_requests/new\.json\z},
+ "new_merge_request_pipelines"
),
Gitlab::EtagCaching::Router::Route.new(
- %r(^(?!.*(#{RESERVED_WORDS_REGEX})).*/merge_requests/\d+/pipelines\.json\z),
- 'merge_request_pipelines'
+ %r{^(?!.*(#{RESERVED_WORDS_REGEX})).*/merge_requests/\d+/pipelines\.json\z},
+ "merge_request_pipelines"
),
Gitlab::EtagCaching::Router::Route.new(
- %r(^(?!.*(#{RESERVED_WORDS_REGEX})).*/pipelines\.json\z),
- 'project_pipelines'
+ %r{^(?!.*(#{RESERVED_WORDS_REGEX})).*/pipelines\.json\z},
+ "project_pipelines"
),
Gitlab::EtagCaching::Router::Route.new(
- %r(^(?!.*(#{RESERVED_WORDS_REGEX})).*/pipelines/\d+\.json\z),
- 'project_pipeline'
+ %r{^(?!.*(#{RESERVED_WORDS_REGEX})).*/pipelines/\d+\.json\z},
+ "project_pipeline"
),
Gitlab::EtagCaching::Router::Route.new(
- %r(^(?!.*(#{RESERVED_WORDS_REGEX})).*/builds/\d+\.json\z),
- 'project_build'
+ %r{^(?!.*(#{RESERVED_WORDS_REGEX})).*/builds/\d+\.json\z},
+ "project_build"
),
Gitlab::EtagCaching::Router::Route.new(
- %r(^(?!.*(#{RESERVED_WORDS_REGEX})).*/environments\.json\z),
- 'environments'
+ %r{^(?!.*(#{RESERVED_WORDS_REGEX})).*/environments\.json\z},
+ "environments"
),
Gitlab::EtagCaching::Router::Route.new(
- %r(^(?!.*(#{RESERVED_WORDS_REGEX})).*/import/github/realtime_changes\.json\z),
- 'realtime_changes_import_github'
+ %r{^(?!.*(#{RESERVED_WORDS_REGEX})).*/import/github/realtime_changes\.json\z},
+ "realtime_changes_import_github"
),
Gitlab::EtagCaching::Router::Route.new(
- %r(^(?!.*(#{RESERVED_WORDS_REGEX})).*/import/gitea/realtime_changes\.json\z),
- 'realtime_changes_import_gitea'
- )
+ %r{^(?!.*(#{RESERVED_WORDS_REGEX})).*/import/gitea/realtime_changes\.json\z},
+ "realtime_changes_import_gitea"
+ ),
].freeze
def self.match(path)
diff --git a/lib/gitlab/etag_caching/store.rb b/lib/gitlab/etag_caching/store.rb
index 2395e7be026..bac9fbba340 100644
--- a/lib/gitlab/etag_caching/store.rb
+++ b/lib/gitlab/etag_caching/store.rb
@@ -4,7 +4,7 @@ module Gitlab
module EtagCaching
class Store
EXPIRY_TIME = 20.minutes
- SHARED_STATE_NAMESPACE = 'etag:'.freeze
+ SHARED_STATE_NAMESPACE = "etag:"
def get(key)
Gitlab::Redis::SharedState.with { |redis| redis.get(redis_shared_state_key(key)) }
@@ -27,7 +27,7 @@ module Gitlab
end
def redis_shared_state_key(key)
- raise 'Invalid key' if !Rails.env.production? && !Gitlab::EtagCaching::Router.match(key)
+ raise "Invalid key" if !Rails.env.production? && !Gitlab::EtagCaching::Router.match(key)
"#{SHARED_STATE_NAMESPACE}#{key}"
end
diff --git a/lib/gitlab/exclusive_lease.rb b/lib/gitlab/exclusive_lease.rb
index d466d2a514c..665b5c9d941 100644
--- a/lib/gitlab/exclusive_lease.rb
+++ b/lib/gitlab/exclusive_lease.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'securerandom'
+require "securerandom"
module Gitlab
# This class implements an 'exclusive lease'. We call it a 'lease'
@@ -12,14 +12,14 @@ module Gitlab
# ExclusiveLease.
#
class ExclusiveLease
- LUA_CANCEL_SCRIPT = <<~EOS.freeze
+ LUA_CANCEL_SCRIPT = <<~EOS
local key, uuid = KEYS[1], ARGV[1]
if redis.call("get", key) == uuid then
redis.call("del", key)
end
EOS
- LUA_RENEW_SCRIPT = <<~EOS.freeze
+ LUA_RENEW_SCRIPT = <<~EOS
local key, uuid, ttl = KEYS[1], ARGV[1], ARGV[2]
if redis.call("get", key) == uuid then
redis.call("expire", key, ttl)
@@ -45,7 +45,7 @@ module Gitlab
# Removes any existing exclusive_lease from redis
# Don't run this in a live system without making sure no one is using the leases
- def self.reset_all!(scope = '*')
+ def self.reset_all!(scope = "*")
Gitlab::Redis::SharedState.with do |redis|
redis.scan_each(match: redis_shared_state_key(scope)).each do |key|
redis.del(key)
diff --git a/lib/gitlab/exclusive_lease_helpers.rb b/lib/gitlab/exclusive_lease_helpers.rb
index 7961d4bbd6e..441c37a9396 100644
--- a/lib/gitlab/exclusive_lease_helpers.rb
+++ b/lib/gitlab/exclusive_lease_helpers.rb
@@ -12,7 +12,7 @@ module Gitlab
# because it holds the connection until all `retries` is consumed.
# This could potentially eat up all connection pools.
def in_lock(key, ttl: 1.minute, retries: 10, sleep_sec: 0.01.seconds)
- raise ArgumentError, 'Key needs to be specified' unless key
+ raise ArgumentError, "Key needs to be specified" unless key
lease = Gitlab::ExclusiveLease.new(key, timeout: ttl)
@@ -23,7 +23,7 @@ module Gitlab
break if (retries -= 1) < 0
end
- raise FailedToObtainLockError, 'Failed to obtain a lock' unless uuid
+ raise FailedToObtainLockError, "Failed to obtain a lock" unless uuid
yield
ensure
diff --git a/lib/gitlab/fake_application_settings.rb b/lib/gitlab/fake_application_settings.rb
index bd806269bf0..4243accb1a8 100644
--- a/lib/gitlab/fake_application_settings.rb
+++ b/lib/gitlab/fake_application_settings.rb
@@ -10,11 +10,11 @@ module Gitlab
# Mimic ActiveRecord predicate methods for boolean values
def self.define_predicate_methods(options)
options.each do |key, value|
- next if key.to_s.end_with?('?')
+ next if key.to_s.end_with?("?")
next unless [true, false].include?(value)
define_method "#{key}?" do
- actual_key = key.to_s.chomp('?')
+ actual_key = key.to_s.chomp("?")
self[actual_key]
end
end
diff --git a/lib/gitlab/favicon.rb b/lib/gitlab/favicon.rb
index 1ae2f9dfd93..c8b75bd7c3d 100644
--- a/lib/gitlab/favicon.rb
+++ b/lib/gitlab/favicon.rb
@@ -7,12 +7,12 @@ module Gitlab
image_name =
if appearance_favicon.exists?
appearance_favicon.url
- elsif Gitlab::Utils.to_boolean(ENV['CANARY'])
- 'favicon-yellow.png'
+ elsif Gitlab::Utils.to_boolean(ENV["CANARY"])
+ "favicon-yellow.png"
elsif Rails.env.development?
- 'favicon-blue.png'
+ "favicon-blue.png"
else
- 'favicon.png'
+ "favicon.png"
end
ActionController::Base.helpers.image_path(image_name, host: host)
@@ -20,7 +20,7 @@ module Gitlab
def status_overlay(status_name)
path = File.join(
- 'ci_favicons',
+ "ci_favicons",
"#{status_name}.png"
)
@@ -29,8 +29,8 @@ module Gitlab
def available_status_names
@available_status_names ||= begin
- Dir.glob(Rails.root.join('app', 'assets', 'images', 'ci_favicons', '*.png'))
- .map { |file| File.basename(file, '.png') }
+ Dir.glob(Rails.root.join("app", "assets", "images", "ci_favicons", "*.png"))
+ .map { |file| File.basename(file, ".png") }
.sort
end
end
diff --git a/lib/gitlab/file_detector.rb b/lib/gitlab/file_detector.rb
index 2770469ca9f..0a2e72c741d 100644
--- a/lib/gitlab/file_detector.rb
+++ b/lib/gitlab/file_detector.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'set'
+require "set"
module Gitlab
# Module that can be used to detect if a path points to a special file such as
@@ -12,30 +12,30 @@ module Gitlab
changelog: %r{\A(changelog|history|changes|news)[^/]*\z}i,
license: %r{\A((un)?licen[sc]e|copying)(\.[^/]+)?\z}i,
contributing: %r{\Acontributing[^/]*\z}i,
- version: 'version',
+ version: "version",
avatar: /\Alogo\.(png|jpg|gif)\z/,
issue_template: %r{\A\.gitlab/issue_templates/[^/]+\.md\z},
merge_request_template: %r{\A\.gitlab/merge_request_templates/[^/]+\.md\z},
xcode_config: %r{\A[^/]*\.(xcodeproj|xcworkspace)(/.+)?\z},
# Configuration files
- gitignore: '.gitignore',
- gitlab_ci: '.gitlab-ci.yml',
- route_map: '.gitlab/route-map.yml',
+ gitignore: ".gitignore",
+ gitlab_ci: ".gitlab-ci.yml",
+ route_map: ".gitlab/route-map.yml",
# Dependency files
cartfile: %r{\ACartfile[^/]*\z},
- composer_json: 'composer.json',
+ composer_json: "composer.json",
gemfile: /\A(Gemfile|gems\.rb)\z/,
- gemfile_lock: 'Gemfile.lock',
+ gemfile_lock: "Gemfile.lock",
gemspec: %r{\A[^/]*\.gemspec\z},
- godeps_json: 'Godeps.json',
- package_json: 'package.json',
- podfile: 'Podfile',
+ godeps_json: "Godeps.json",
+ package_json: "package.json",
+ podfile: "Podfile",
podspec_json: %r{\A[^/]*\.podspec\.json\z},
podspec: %r{\A[^/]*\.podspec\z},
requirements_txt: %r{\A[^/]*requirements\.txt\z},
- yarn_lock: 'yarn.lock'
+ yarn_lock: "yarn.lock",
}.freeze
# Returns an Array of file types based on the given paths.
@@ -69,10 +69,10 @@ module Gitlab
def self.type_of(path)
PATTERNS.each do |type, search|
did_match = if search.is_a?(Regexp)
- path =~ search
- else
- path.casecmp(search) == 0
- end
+ path =~ search
+ else
+ path.casecmp(search) == 0
+ end
return type if did_match
end
diff --git a/lib/gitlab/file_finder.rb b/lib/gitlab/file_finder.rb
index 3958814208c..376c2f34787 100644
--- a/lib/gitlab/file_finder.rb
+++ b/lib/gitlab/file_finder.rb
@@ -14,11 +14,11 @@ module Gitlab
end
def find(query)
- query = Gitlab::Search::Query.new(query, encode_binary: true) do
+ query = Gitlab::Search::Query.new(query, encode_binary: true) {
filter :filename, matcher: ->(filter, blob) { blob.binary_filename =~ /#{filter[:regex_value]}$/i }
filter :path, matcher: ->(filter, blob) { blob.binary_filename =~ /#{filter[:regex_value]}/i }
filter :extension, matcher: ->(filter, blob) { blob.binary_filename =~ /\.#{filter[:regex_value]}$/i }
- end
+ }
files = find_by_filename(query.term) + find_by_content(query.term)
diff --git a/lib/gitlab/file_markdown_link_builder.rb b/lib/gitlab/file_markdown_link_builder.rb
index 180140e7da2..b698d1aa047 100644
--- a/lib/gitlab/file_markdown_link_builder.rb
+++ b/lib/gitlab/file_markdown_link_builder.rb
@@ -9,7 +9,7 @@ module Gitlab
def markdown_link
return unless name = markdown_name
- markdown = "[#{name.gsub(']', '\\]')}](#{secure_url})"
+ markdown = "[#{name.gsub("]", '\\]')}](#{secure_url})"
markdown = "!#{markdown}" if image_or_video? || dangerous?
markdown
end
diff --git a/lib/gitlab/file_type_detection.rb b/lib/gitlab/file_type_detection.rb
index 25ee07cf940..f0524dfcf46 100644
--- a/lib/gitlab/file_type_detection.rb
+++ b/lib/gitlab/file_type_detection.rb
@@ -36,7 +36,7 @@ module Gitlab
def extension_match?(extensions)
return false unless filename
- extension = File.extname(filename).delete('.')
+ extension = File.extname(filename).delete(".")
extensions.include?(extension.downcase)
end
end
diff --git a/lib/gitlab/fogbugz_import/client.rb b/lib/gitlab/fogbugz_import/client.rb
index dd747a79673..41a7c801a10 100644
--- a/lib/gitlab/fogbugz_import/client.rb
+++ b/lib/gitlab/fogbugz_import/client.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'fogbugz'
+require "fogbugz"
module Gitlab
module FogbugzImport
@@ -28,15 +28,15 @@ module Gitlab
def user_map
users = {}
res = @api.command(:listPeople)
- [res['people']['person']].flatten.each do |user|
- users[user['ixPerson']] = { name: user['sFullName'], email: user['sEmail'] }
+ [res["people"]["person"]].flatten.each do |user|
+ users[user["ixPerson"]] = {name: user["sFullName"], email: user["sEmail"]}
end
users
end
def repos
res = @api.command(:listProjects)
- @repos ||= res['projects']['project'].map { |proj| FogbugzImport::Repository.new(proj) }
+ @repos ||= res["projects"]["project"].map { |proj| FogbugzImport::Repository.new(proj) }
end
def repo(id)
@@ -45,10 +45,10 @@ module Gitlab
def cases(project_id)
project_name = repo(project_id).name
- res = @api.command(:search, q: "project:'#{project_name}'", cols: 'ixPersonAssignedTo,ixPersonOpenedBy,ixPersonClosedBy,sStatus,sPriority,sCategory,fOpen,sTitle,sLatestTextSummary,dtOpened,dtClosed,dtResolved,dtLastUpdated,events')
- return [] unless res['cases']['count'].to_i > 0
+ res = @api.command(:search, q: "project:'#{project_name}'", cols: "ixPersonAssignedTo,ixPersonOpenedBy,ixPersonClosedBy,sStatus,sPriority,sCategory,fOpen,sTitle,sLatestTextSummary,dtOpened,dtClosed,dtResolved,dtLastUpdated,events")
+ return [] unless res["cases"]["count"].to_i > 0
- res['cases']['case']
+ res["cases"]["case"]
end
def categories
diff --git a/lib/gitlab/fogbugz_import/importer.rb b/lib/gitlab/fogbugz_import/importer.rb
index 431911d1eee..37aeaec60b5 100644
--- a/lib/gitlab/fogbugz_import/importer.rb
+++ b/lib/gitlab/fogbugz_import/importer.rb
@@ -9,7 +9,7 @@ module Gitlab
@project = project
import_data = project.import_data.try(:data)
- repo_data = import_data['repo'] if import_data
+ repo_data = import_data["repo"] if import_data
if repo_data
@repo = FogbugzImport::Repository.new(repo_data)
@known_labels = Set.new
@@ -34,14 +34,14 @@ module Gitlab
private
def fb_session
- @import_data_credentials ||= project.import_data.credentials[:fb_session] if project.import_data && project.import_data.credentials
+ @import_data_credentials ||= project.import_data.credentials[:fb_session] if project.import_data&.credentials
end
def user_map
@user_map ||= begin
- user_map = Hash.new
+ user_map = {}
import_data = project.import_data.try(:data)
- stored_user_map = import_data['user_map'] if import_data
+ stored_user_map = import_data["user_map"] if import_data
user_map.update(stored_user_map) if stored_user_map
user_map
@@ -49,35 +49,35 @@ module Gitlab
end
def import_labels
- @categories['categories']['category'].each do |label|
- create_label(label['sCategory'])
+ @categories["categories"]["category"].each do |label|
+ create_label(label["sCategory"])
@known_labels << name
end
end
def nice_label_color(name)
case name
- when 'Blocker'
- '#ff0000'
- when 'Crash'
- '#ffcfcf'
- when 'Major'
- '#deffcf'
- when 'Minor'
- '#cfe9ff'
- when 'Bug'
- '#d9534f'
- when 'Feature'
- '#44ad8e'
- when 'Technical Task'
- '#4b6dd0'
+ when "Blocker"
+ "#ff0000"
+ when "Crash"
+ "#ffcfcf"
+ when "Major"
+ "#deffcf"
+ when "Minor"
+ "#cfe9ff"
+ when "Bug"
+ "#d9534f"
+ when "Feature"
+ "#44ad8e"
+ when "Technical Task"
+ "#4b6dd0"
else
- '#e2e2e2'
+ "#e2e2e2"
end
end
def create_label(name)
- params = { title: name, color: nice_label_color(name) }
+ params = {title: name, color: nice_label_color(name)}
::Labels::FindOrCreateService.new(nil, project, params).execute(skip_authorization: true)
end
@@ -85,18 +85,18 @@ module Gitlab
def user_info(person_id)
user_hash = user_map[person_id.to_s]
- user_name = ''
+ user_name = ""
gitlab_id = nil
unless user_hash.nil?
- user_name = user_hash['name']
- if user = User.find_by(id: user_hash['gitlab_user'])
+ user_name = user_hash["name"]
+ if user = User.find_by(id: user_hash["gitlab_user"])
user_name = "@#{user.username}"
gitlab_id = user.id
end
end
- { name: user_name, gitlab_id: gitlab_id }
+ {name: user_name, gitlab_id: gitlab_id}
end
# rubocop: enable CodeReuse/ActiveRecord
@@ -105,16 +105,16 @@ module Gitlab
return unless @cases
while bug = @cases.shift
- author = user_info(bug['ixPersonOpenedBy'])[:name]
- date = DateTime.parse(bug['dtOpened'])
+ author = user_info(bug["ixPersonOpenedBy"])[:name]
+ date = DateTime.parse(bug["dtOpened"])
- comments = bug['events']['event']
+ comments = bug["events"]["event"]
content = format_content(opened_content(comments))
body = format_issue_body(author, date, content)
labels = []
- [bug['sCategory'], bug['sPriority']].each do |label|
+ [bug["sCategory"], bug["sPriority"]].each do |label|
unless label.blank?
labels << label
@@ -125,19 +125,19 @@ module Gitlab
end
end
- assignee_id = user_info(bug['ixPersonAssignedTo'])[:gitlab_id]
- author_id = user_info(bug['ixPersonOpenedBy'])[:gitlab_id] || project.creator_id
+ assignee_id = user_info(bug["ixPersonAssignedTo"])[:gitlab_id]
+ author_id = user_info(bug["ixPersonOpenedBy"])[:gitlab_id] || project.creator_id
issue = Issue.create!(
- iid: bug['ixBug'],
- project_id: project.id,
- title: bug['sTitle'],
- description: body,
- author_id: author_id,
+ iid: bug["ixBug"],
+ project_id: project.id,
+ title: bug["sTitle"],
+ description: body,
+ author_id: author_id,
assignee_ids: [assignee_id],
- state: bug['fOpen'] == 'true' ? 'opened' : 'closed',
- created_at: date,
- updated_at: DateTime.parse(bug['dtLastUpdated'])
+ state: bug["fOpen"] == "true" ? "opened" : "closed",
+ created_at: date,
+ updated_at: DateTime.parse(bug["dtLastUpdated"])
)
issue_labels = ::LabelsFinder.new(nil, project_id: project.id, title: labels).execute(skip_authorization: true)
@@ -150,32 +150,32 @@ module Gitlab
def opened_content(comments)
while comment = comments.shift
- if comment['sVerb'] == 'Opened'
- return comment['s']
+ if comment["sVerb"] == "Opened"
+ return comment["s"]
end
end
- ''
+ ""
end
def import_issue_comments(issue, comments)
Note.transaction do
while comment = comments.shift
- verb = comment['sVerb']
+ verb = comment["sVerb"]
- next if verb == 'Opened'
+ next if verb == "Opened"
- content = format_content(comment['s'])
- attachments = format_attachments(comment['rgAttachments'])
+ content = format_content(comment["s"])
+ attachments = format_attachments(comment["rgAttachments"])
updates = format_updates(comment)
next if content.blank? && attachments.empty? && updates.empty?
- author = user_info(comment['ixPerson'])[:name]
- author_id = user_info(comment['ixPerson'])[:gitlab_id] || project.creator_id
- date = DateTime.parse(comment['dt'])
+ author = user_info(comment["ixPerson"])[:name]
+ author_id = user_info(comment["ixPerson"])[:gitlab_id] || project.creator_id
+ date = DateTime.parse(comment["dt"])
body = format_issue_comment_body(
- comment['ixBugEvent'],
+ comment["ixBugEvent"],
author,
date,
content,
@@ -184,11 +184,11 @@ module Gitlab
)
note = Note.create!(
- project_id: project.id,
- noteable_type: "Issue",
- noteable_id: issue.id,
- author_id: author_id,
- note: body
+ project_id: project.id,
+ noteable_type: "Issue",
+ noteable_id: issue.id,
+ author_id: author_id,
+ note: body
)
note.update_attribute(:created_at, date)
@@ -221,21 +221,21 @@ module Gitlab
def format_attachments(raw_attachments)
return [] unless raw_attachments
- attachments = case raw_attachments['attachment']
+ attachments = case raw_attachments["attachment"]
when Array
- raw_attachments['attachment']
+ raw_attachments["attachment"]
when Hash
- [raw_attachments['attachment']]
+ [raw_attachments["attachment"]]
else
[]
- end
+ end
attachments.map! { |a| format_attachment(a) }
attachments.compact
end
def format_attachment(attachment)
- link = build_attachment_url(attachment['sURL'])
+ link = build_attachment_url(attachment["sURL"])
res = ::Projects::DownloadService.new(project, link).execute
@@ -253,12 +253,12 @@ module Gitlab
def format_updates(comment)
updates = []
- if comment['sChanges']
- updates << "*Changes: #{linkify_issues(comment['sChanges'].chomp)}*"
+ if comment["sChanges"]
+ updates << "*Changes: #{linkify_issues(comment["sChanges"].chomp)}*"
end
- if comment['evtDescription']
- updates << "*#{comment['evtDescription']}*"
+ if comment["evtDescription"]
+ updates << "*#{comment["evtDescription"]}*"
end
updates
@@ -267,10 +267,10 @@ module Gitlab
def format_issue_body(author, date, content)
body = []
body << "*By #{author} on #{date} (imported from FogBugz)*"
- body << '---'
+ body << "---"
if content.blank?
- content = '*(No description has been entered for this issue)*'
+ content = "*(No description has been entered for this issue)*"
end
body << content
@@ -281,7 +281,7 @@ module Gitlab
def format_issue_comment_body(id, author, date, content, attachments, updates)
body = []
body << "*By #{author} on #{date} (imported from FogBugz)*"
- body << '---'
+ body << "---"
if content.blank?
content = "*(No comment has been entered for this change)*"
@@ -290,12 +290,12 @@ module Gitlab
body << content
if updates.any?
- body << '---'
+ body << "---"
body += updates
end
if attachments.any?
- body << '---'
+ body << "---"
body += attachments
end
diff --git a/lib/gitlab/fogbugz_import/project_creator.rb b/lib/gitlab/fogbugz_import/project_creator.rb
index 3c71031a8d9..c5bbe2faa6a 100644
--- a/lib/gitlab/fogbugz_import/project_creator.rb
+++ b/lib/gitlab/fogbugz_import/project_creator.rb
@@ -21,10 +21,10 @@ module Gitlab
namespace: namespace,
creator: current_user,
visibility_level: Gitlab::VisibilityLevel::INTERNAL,
- import_type: 'fogbugz',
+ import_type: "fogbugz",
import_source: repo.name,
import_url: Project::UNKNOWN_IMPORT_URL,
- import_data: { data: { 'repo' => repo.raw_data, 'user_map' => user_map }, credentials: { fb_session: fb_session } }
+ import_data: {data: {"repo" => repo.raw_data, "user_map" => user_map}, credentials: {fb_session: fb_session}}
).execute
end
end
diff --git a/lib/gitlab/fogbugz_import/repository.rb b/lib/gitlab/fogbugz_import/repository.rb
index b958dcf6cbf..f20921b3c8d 100644
--- a/lib/gitlab/fogbugz_import/repository.rb
+++ b/lib/gitlab/fogbugz_import/repository.rb
@@ -14,19 +14,19 @@ module Gitlab
end
def id
- raw_data['ixProject']
+ raw_data["ixProject"]
end
def name
- raw_data['sProject']
+ raw_data["sProject"]
end
def safe_name
- name.gsub(/[^\s\w.-]/, '')
+ name.gsub(/[^\s\w.-]/, "")
end
def path
- safe_name.gsub(/[\s]/, '_')
+ safe_name.gsub(/[\s]/, "_")
end
end
end
diff --git a/lib/gitlab/gfm/reference_rewriter.rb b/lib/gitlab/gfm/reference_rewriter.rb
index 4d82acd9d87..56704bdacb5 100644
--- a/lib/gitlab/gfm/reference_rewriter.rb
+++ b/lib/gitlab/gfm/reference_rewriter.rb
@@ -75,7 +75,7 @@ module Gitlab
def find_referable(reference)
extractor = Gitlab::ReferenceExtractor.new(@source_parent,
- @current_user)
+ @current_user)
extractor.analyze(reference)
extractor.all.first
end
diff --git a/lib/gitlab/gfm/uploads_rewriter.rb b/lib/gitlab/gfm/uploads_rewriter.rb
index 2d1c9ac40ae..835d47a7600 100644
--- a/lib/gitlab/gfm/uploads_rewriter.rb
+++ b/lib/gitlab/gfm/uploads_rewriter.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'fileutils'
+require "fileutils"
module Gitlab
module Gfm
@@ -36,9 +36,9 @@ module Gitlab
end
def files
- referenced_files = @text.scan(@pattern).map do
+ referenced_files = @text.scan(@pattern).map {
find_file(@source_project, $~[:secret], $~[:file])
- end
+ }
referenced_files.compact.select(&:exists?)
end
diff --git a/lib/gitlab/git.rb b/lib/gitlab/git.rb
index 44a62586a23..f1a444a13c5 100644
--- a/lib/gitlab/git.rb
+++ b/lib/gitlab/git.rb
@@ -1,16 +1,16 @@
# frozen_string_literal: true
-require_dependency 'gitlab/encoding_helper'
+require_dependency "gitlab/encoding_helper"
module Gitlab
module Git
# The ID of empty tree.
# See http://stackoverflow.com/a/40884093/1856239 and
# https://github.com/git/git/blob/3ad8b5bf26362ac67c9020bf8c30eee54a84f56d/cache.h#L1011-L1012
- EMPTY_TREE_ID = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'.freeze
- BLANK_SHA = ('0' * 40).freeze
- TAG_REF_PREFIX = "refs/tags/".freeze
- BRANCH_REF_PREFIX = "refs/heads/".freeze
+ EMPTY_TREE_ID = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
+ BLANK_SHA = ("0" * 40).freeze
+ TAG_REF_PREFIX = "refs/tags/"
+ BRANCH_REF_PREFIX = "refs/heads/"
BaseError = Class.new(StandardError)
CommandError = Class.new(BaseError)
@@ -22,15 +22,13 @@ module Gitlab
include Gitlab::EncodingHelper
def ref_name(ref)
- encode!(ref).sub(%r{\Arefs/(tags|heads|remotes)/}, '')
+ encode!(ref).sub(%r{\Arefs/(tags|heads|remotes)/}, "")
end
def branch_name(ref)
ref = ref.to_s
- if self.branch_ref?(ref)
- self.ref_name(ref)
- else
- nil
+ if branch_ref?(ref)
+ ref_name(ref)
end
end
@@ -40,16 +38,14 @@ module Gitlab
{
email: email,
name: name,
- time: Time.now
+ time: Time.now,
}
end
def tag_name(ref)
ref = ref.to_s
- if self.tag_ref?(ref)
- self.ref_name(ref)
- else
- nil
+ if tag_ref?(ref)
+ ref_name(ref)
end
end
@@ -70,7 +66,7 @@ module Gitlab
end
def check_namespace!(*objects)
- expected_namespace = self.name + '::'
+ expected_namespace = name + "::"
objects.each do |object|
unless object.class.name.start_with?(expected_namespace)
raise ArgumentError, "expected object in #{expected_namespace}, got #{object}"
diff --git a/lib/gitlab/git/attributes_at_ref_parser.rb b/lib/gitlab/git/attributes_at_ref_parser.rb
index cbddf836ce8..5b2b8290966 100644
--- a/lib/gitlab/git/attributes_at_ref_parser.rb
+++ b/lib/gitlab/git/attributes_at_ref_parser.rb
@@ -7,7 +7,7 @@ module Gitlab
delegate :attributes, to: :@parser
def initialize(repository, ref)
- blob = repository.blob_at(ref, '.gitattributes')
+ blob = repository.blob_at(ref, ".gitattributes")
@parser = AttributesParser.new(blob&.data)
end
diff --git a/lib/gitlab/git/attributes_parser.rb b/lib/gitlab/git/attributes_parser.rb
index 8b9d74ae8e7..a719357a958 100644
--- a/lib/gitlab/git/attributes_parser.rb
+++ b/lib/gitlab/git/attributes_parser.rb
@@ -15,7 +15,7 @@ module Gitlab
#
# Returns a Hash.
def attributes(file_path)
- absolute_path = File.join('/', file_path)
+ absolute_path = File.join("/", file_path)
patterns.each do |pattern, attrs|
return attrs if File.fnmatch?(pattern, absolute_path)
@@ -42,9 +42,9 @@ module Gitlab
# Returns a Hash containing the attributes and their values.
def parse_attributes(string)
values = {}
- dash = '-'
- equal = '='
- binary = 'binary'
+ dash = "-"
+ equal = "="
+ binary = "binary"
string.split(/\s+/).each do |chunk|
# Data such as "foo = bar" should be treated as "foo" and "bar" being
@@ -72,7 +72,7 @@ module Gitlab
# When the "binary" option is set the "diff" option should be set to
# the inverse. If "diff" is later set it should overwrite the
# automatically set value.
- values['diff'] = false if key == binary && value
+ values["diff"] = false if key == binary && value
end
values
@@ -92,7 +92,7 @@ module Gitlab
# Parses the Git attributes file contents.
def parse_data
pairs = []
- comment = '#'
+ comment = "#"
each_line do |line|
next if line.start_with?(comment) || line.empty?
@@ -101,7 +101,7 @@ module Gitlab
parsed = attrs ? parse_attributes(attrs) : {}
- absolute_pattern = File.join('/', pattern)
+ absolute_pattern = File.join("/", pattern)
pairs << [absolute_pattern, parsed]
end
diff --git a/lib/gitlab/git/blob.rb b/lib/gitlab/git/blob.rb
index 259a2b7911a..f2070fe15ca 100644
--- a/lib/gitlab/git/blob.rb
+++ b/lib/gitlab/git/blob.rb
@@ -25,8 +25,8 @@ module Gitlab
def find(repository, sha, path, limit: MAX_DATA_DISPLAY_SIZE)
return unless path
- path = path.sub(%r{\A/*}, '')
- path = '/' if path.empty?
+ path = path.sub(%r{\A/*}, "")
+ path = "/" if path.empty?
name = File.basename(path)
# Gitaly will think that setting the limit to 0 means unlimited, while
@@ -43,7 +43,7 @@ module Gitlab
case entry.type
when :COMMIT
- new(id: entry.oid, name: name, size: 0, data: '', path: path, commit_id: sha)
+ new(id: entry.oid, name: name, size: 0, data: "", path: path, commit_id: sha)
when :BLOB
new(id: entry.oid, name: name, size: entry.size, data: entry.data.dup, mode: entry.mode.to_s(8),
path: path, commit_id: sha, binary: binary?(entry.data))
@@ -91,8 +91,8 @@ module Gitlab
end
def initialize(options)
- %w(id name path size data mode commit_id binary).each do |key|
- self.__send__("#{key}=", options[key.to_sym]) # rubocop:disable GitlabSecurity/PublicSend
+ %w[id name path size data mode commit_id binary].each do |key|
+ __send__("#{key}=", options[key.to_sym]) # rubocop:disable GitlabSecurity/PublicSend
end
# Retain the actual size before it is encoded
@@ -111,7 +111,7 @@ module Gitlab
# Load all blob data (not just the first MAX_DATA_DISPLAY_SIZE bytes) into
# memory as a Ruby string.
def load_all_data!(repository)
- return if @data == '' # don't mess with submodule blobs
+ return if @data == "" # don't mess with submodule blobs
# Even if we return early, recalculate wether this blob is binary in
# case a blob was initialized as text but the full data isn't
@@ -169,7 +169,7 @@ module Gitlab
:lfs
end
- alias_method :external_size, :lfs_size
+ alias external_size lfs_size
private
diff --git a/lib/gitlab/git/branch.rb b/lib/gitlab/git/branch.rb
index 9447cfa0fb6..465ecc24430 100644
--- a/lib/gitlab/git/branch.rb
+++ b/lib/gitlab/git/branch.rb
@@ -18,7 +18,7 @@ module Gitlab
end
def active?
- self.dereferenced_target.committed_date >= STALE_BRANCH_THRESHOLD.ago
+ dereferenced_target.committed_date >= STALE_BRANCH_THRESHOLD.ago
end
def stale?
diff --git a/lib/gitlab/git/bundle_file.rb b/lib/gitlab/git/bundle_file.rb
index 8384a436fcc..c6c18600f57 100644
--- a/lib/gitlab/git/bundle_file.rb
+++ b/lib/gitlab/git/bundle_file.rb
@@ -21,9 +21,9 @@ module Gitlab
end
def check!
- data = File.open(filename, 'r') { |f| f.read(MAGIC.size) }
+ data = File.open(filename, "r") { |f| f.read(MAGIC.size) }
- raise InvalidBundleError, 'Invalid bundle file' unless data == MAGIC
+ raise InvalidBundleError, "Invalid bundle file" unless data == MAGIC
end
end
end
diff --git a/lib/gitlab/git/commit.rb b/lib/gitlab/git/commit.rb
index 5863815ca85..4c5f4a27ced 100644
--- a/lib/gitlab/git/commit.rb
+++ b/lib/gitlab/git/commit.rb
@@ -14,7 +14,7 @@ module Gitlab
SERIALIZE_KEYS = [
:id, :message, :parent_ids,
:authored_date, :author_name, :author_email,
- :committed_date, :committer_name, :committer_email
+ :committed_date, :committer_name, :committer_email,
].freeze
attr_accessor *SERIALIZE_KEYS # rubocop:disable Lint/AmbiguousOperator
@@ -39,7 +39,7 @@ module Gitlab
#
def where(options)
repo = options.delete(:repo)
- raise 'Gitlab::Git::Repository is required' unless repo.respond_to?(:log)
+ raise "Gitlab::Git::Repository is required" unless repo.respond_to?(:log)
repo.log(options)
end
@@ -60,11 +60,11 @@ module Gitlab
return nil unless commit_id.is_a?(String)
# This saves us an RPC round trip.
- return nil if commit_id.include?(':')
+ return nil if commit_id.include?(":")
- commit = wrapped_gitaly_errors do
+ commit = wrapped_gitaly_errors {
repo.gitaly_commit_client.find_commit(commit_id)
- end
+ }
decorate(repo, commit) if commit
rescue Gitlab::Git::CommandError, Gitlab::Git::Repository::NoRepository, ArgumentError
diff --git a/lib/gitlab/git/conflict/file.rb b/lib/gitlab/git/conflict/file.rb
index 7ffe4a7ae81..33d4c7fd176 100644
--- a/lib/gitlab/git/conflict/file.rb
+++ b/lib/gitlab/git/conflict/file.rb
@@ -23,18 +23,18 @@ module Gitlab
return @lines if defined?(@lines)
begin
- @type = 'text'
+ @type = "text"
@lines = Gitlab::Git::Conflict::Parser.parse(content,
- our_path: our_path,
- their_path: their_path)
+ our_path: our_path,
+ their_path: their_path)
rescue Gitlab::Git::Conflict::Parser::ParserError
- @type = 'text-editor'
+ @type = "text-editor"
@lines = nil
end
end
def content
- @content ||= @raw_content.dup.force_encoding('UTF-8')
+ @content ||= @raw_content.dup.force_encoding("UTF-8")
raise UnsupportedEncoding unless @content.valid_encoding?
@@ -66,7 +66,7 @@ module Gitlab
def resolve_lines(resolution)
section_id = nil
- lines.map do |line|
+ lines.map { |line|
unless line[:type]
section_id = nil
next line
@@ -75,16 +75,16 @@ module Gitlab
section_id ||= line_code(line)
case resolution[section_id]
- when 'head'
- next unless line[:type] == 'new'
- when 'origin'
- next unless line[:type] == 'old'
+ when "head"
+ next unless line[:type] == "new"
+ when "origin"
+ next unless line[:type] == "old"
else
raise Gitlab::Git::Conflict::Resolver::ResolutionError, "Missing resolution for section ID: #{section_id}"
end
line
- end.compact
+ }.compact
end
def resolve_content(resolution)
diff --git a/lib/gitlab/git/conflict/parser.rb b/lib/gitlab/git/conflict/parser.rb
index 20de8ebde4e..6e7c05b34f2 100644
--- a/lib/gitlab/git/conflict/parser.rb
+++ b/lib/gitlab/git/conflict/parser.rb
@@ -23,7 +23,7 @@ module Gitlab
type = nil
lines = []
conflict_start = "<<<<<<< #{our_path}"
- conflict_middle = '======='
+ conflict_middle = "======="
conflict_end = ">>>>>>> #{their_path}"
text.each_line.map do |line|
@@ -32,23 +32,23 @@ module Gitlab
if full_line == conflict_start
validate_delimiter!(type.nil?)
- type = 'new'
+ type = "new"
elsif full_line == conflict_middle
- validate_delimiter!(type == 'new')
+ validate_delimiter!(type == "new")
- type = 'old'
+ type = "old"
elsif full_line == conflict_end
- validate_delimiter!(type == 'old')
+ validate_delimiter!(type == "old")
type = nil
elsif line[0] == '\\'
- type = 'nonewline'
+ type = "nonewline"
lines << {
full_line: full_line,
type: type,
line_obj_index: line_obj_index,
line_old: line_old,
- line_new: line_new
+ line_new: line_new,
}
else
lines << {
@@ -56,11 +56,11 @@ module Gitlab
type: type,
line_obj_index: line_obj_index,
line_old: line_old,
- line_new: line_new
+ line_new: line_new,
}
- line_old += 1 if type != 'new'
- line_new += 1 if type != 'old'
+ line_old += 1 if type != "new"
+ line_new += 1 if type != "old"
line_obj_index += 1
end
diff --git a/lib/gitlab/git/conflict/resolver.rb b/lib/gitlab/git/conflict/resolver.rb
index 26e82643a4c..ec5bb1d054d 100644
--- a/lib/gitlab/git/conflict/resolver.rb
+++ b/lib/gitlab/git/conflict/resolver.rb
@@ -16,9 +16,9 @@ module Gitlab
end
def conflicts
- @conflicts ||= wrapped_gitaly_errors do
+ @conflicts ||= wrapped_gitaly_errors {
gitaly_conflicts_client(@target_repository).list_conflict_files.to_a
- end
+ }
rescue GRPC::FailedPrecondition => e
raise Gitlab::Git::Conflict::Resolver::ConflictSideMissing.new(e.message)
rescue GRPC::BadStatus => e
diff --git a/lib/gitlab/git/diff.rb b/lib/gitlab/git/diff.rb
index 74a4633424f..df9818ed20d 100644
--- a/lib/gitlab/git/diff.rb
+++ b/lib/gitlab/git/diff.rb
@@ -12,14 +12,14 @@ module Gitlab
# Stats properties
attr_accessor :new_file, :renamed_file, :deleted_file
- alias_method :new_file?, :new_file
- alias_method :deleted_file?, :deleted_file
- alias_method :renamed_file?, :renamed_file
+ alias new_file? new_file
+ alias deleted_file? deleted_file
+ alias renamed_file? renamed_file
attr_accessor :expanded
attr_writer :too_large
- alias_method :expanded?, :expanded
+ alias expanded? expanded
# The default maximum content size to display a diff patch.
#
@@ -31,24 +31,24 @@ module Gitlab
# persisting limits over that.
MAX_PATCH_BYTES_UPPER_BOUND = 500.kilobytes
- SERIALIZE_KEYS = %i(diff new_path old_path a_mode b_mode new_file renamed_file deleted_file too_large).freeze
+ SERIALIZE_KEYS = %i[diff new_path old_path a_mode b_mode new_file renamed_file deleted_file too_large].freeze
class << self
def between(repo, head, base, options = {}, *paths)
straight = options.delete(:straight) || false
common_commit = if straight
- base
- else
- # Only show what is new in the source branch
- # compared to the target branch, not the other way
- # around. The linex below with merge_base is
- # equivalent to diff with three dots (git diff
- # branch1...branch2) From the git documentation:
- # "git diff A...B" is equivalent to "git diff
- # $(git-merge-base A B) B"
- repo.merge_base(head, base)
- end
+ base
+ else
+ # Only show what is new in the source branch
+ # compared to the target branch, not the other way
+ # around. The linex below with merge_base is
+ # equivalent to diff with three dots (git diff
+ # branch1...branch2) From the git documentation:
+ # "git diff A...B" is equivalent to "git diff
+ # $(git-merge-base A B) B"
+ repo.merge_base(head, base)
+ end
options ||= {}
actual_options = filter_diff_options(options)
@@ -79,7 +79,7 @@ module Gitlab
# exceeded
def filter_diff_options(options, default_options = {})
allowed_options = [:ignore_whitespace_change, :max_files, :max_lines,
- :limits, :expanded]
+ :limits, :expanded,]
if default_options
actual_defaults = default_options.dup
@@ -167,7 +167,7 @@ module Gitlab
end
def submodule?
- a_mode == '160000' || b_mode == '160000'
+ a_mode == "160000" || b_mode == "160000"
end
def line_count
@@ -183,10 +183,10 @@ module Gitlab
end
# This is used by `to_hash` and `init_from_hash`.
- alias_method :too_large, :too_large?
+ alias too_large too_large?
def too_large!
- @diff = ''
+ @diff = ""
@line_count = 0
@too_large = true
end
@@ -198,7 +198,7 @@ module Gitlab
end
def collapse!
- @diff = ''
+ @diff = ""
@line_count = 0
@collapsed = true
end
@@ -211,7 +211,7 @@ module Gitlab
end
def has_binary_notice?
- @diff.start_with?('Binary')
+ @diff.start_with?("Binary")
end
private
diff --git a/lib/gitlab/git/diff_collection.rb b/lib/gitlab/git/diff_collection.rb
index 5c70cb6c66c..88907203a93 100644
--- a/lib/gitlab/git/diff_collection.rb
+++ b/lib/gitlab/git/diff_collection.rb
@@ -7,7 +7,7 @@ module Gitlab
class DiffCollection
include Enumerable
- DEFAULT_LIMITS = { max_files: 100, max_lines: 5000 }.freeze
+ DEFAULT_LIMITS = {max_files: 100, max_lines: 5000}.freeze
attr_reader :limits
@@ -36,7 +36,7 @@ module Gitlab
@byte_count = 0
@overflow = false
@empty = true
- @array = Array.new
+ @array = []
end
def each(&block)
@@ -88,7 +88,7 @@ module Gitlab
collection
end
- alias_method :to_ary, :to_a
+ alias to_ary to_a
private
diff --git a/lib/gitlab/git/gitmodules_parser.rb b/lib/gitlab/git/gitmodules_parser.rb
index 575e12390cd..7d877c28b74 100644
--- a/lib/gitlab/git/gitmodules_parser.rb
+++ b/lib/gitlab/git/gitmodules_parser.rb
@@ -27,7 +27,7 @@ module Gitlab
# In some .gitmodules files (e.g. nodegit's), a header
# with the same name appears multiple times; we want to
# accumulate the configs across these
- @current_submodule = @result[section] || { 'name' => section }
+ @current_submodule = @result[section] || {"name" => section}
@result[section] = @current_submodule
end
@@ -72,7 +72,7 @@ module Gitlab
# If a submodule doesn't have a path, it is considered bogus
# and is ignored
submodules_by_name.each_with_object({}) do |(name, data), results|
- path = data.delete 'path'
+ path = data.delete "path"
next unless path
results[path] = data
diff --git a/lib/gitlab/git/lfs_pointer_file.rb b/lib/gitlab/git/lfs_pointer_file.rb
index b7019a221ac..efd84e30ad9 100644
--- a/lib/gitlab/git/lfs_pointer_file.rb
+++ b/lib/gitlab/git/lfs_pointer_file.rb
@@ -3,8 +3,8 @@
module Gitlab
module Git
class LfsPointerFile
- VERSION = "https://git-lfs.github.com/spec/v1".freeze
- VERSION_LINE = "version #{VERSION}".freeze
+ VERSION = "https://git-lfs.github.com/spec/v1"
+ VERSION_LINE = "version #{VERSION}"
def initialize(data)
@data = data
diff --git a/lib/gitlab/git/merge_base.rb b/lib/gitlab/git/merge_base.rb
index b27f7038c26..d85553e2f89 100644
--- a/lib/gitlab/git/merge_base.rb
+++ b/lib/gitlab/git/merge_base.rb
@@ -31,7 +31,7 @@ module Gitlab
# the repository, and thus cannot be used to find a merge base.
def unknown_refs
@unknown_refs ||= Hash[@refs.zip(commits_for_refs)]
- .select { |ref, commit| commit.nil? }.keys
+ .select { |ref, commit| commit.nil? }.keys
end
private
diff --git a/lib/gitlab/git/operation_service.rb b/lib/gitlab/git/operation_service.rb
index 8797d3dce24..6107daeca5f 100644
--- a/lib/gitlab/git/operation_service.rb
+++ b/lib/gitlab/git/operation_service.rb
@@ -3,7 +3,7 @@
module Gitlab
module Git
class OperationService
- BranchUpdate = Struct.new(:newrev, :repo_created, :branch_created) do
+ BranchUpdate = Struct.new(:newrev, :repo_created, :branch_created) {
alias_method :repo_created?, :repo_created
alias_method :branch_created?, :branch_created
@@ -16,7 +16,7 @@ module Gitlab
branch_update.branch_created
)
end
- end
+ }
end
end
end
diff --git a/lib/gitlab/git/patches/collection.rb b/lib/gitlab/git/patches/collection.rb
index ad6b5d32abc..5830ef2eeb4 100644
--- a/lib/gitlab/git/patches/collection.rb
+++ b/lib/gitlab/git/patches/collection.rb
@@ -7,9 +7,9 @@ module Gitlab
MAX_PATCH_SIZE = 2.megabytes
def initialize(one_or_more_patches)
- @patches = Array(one_or_more_patches).map do |patch_content|
+ @patches = Array(one_or_more_patches).map { |patch_content|
Gitlab::Git::Patches::Patch.new(patch_content)
- end
+ }
end
def content
diff --git a/lib/gitlab/git/path_helper.rb b/lib/gitlab/git/path_helper.rb
index e3a2031eeca..68c8b52b546 100644
--- a/lib/gitlab/git/path_helper.rb
+++ b/lib/gitlab/git/path_helper.rb
@@ -8,11 +8,11 @@ module Gitlab
class << self
def normalize_path(filename)
# Strip all leading slashes so that //foo -> foo
- filename = filename.sub(%r{\A/*}, '')
+ filename = filename.sub(%r{\A/*}, "")
# Expand relative paths (e.g. foo/../bar)
filename = Pathname.new(filename)
- filename.relative_path_from(Pathname.new(''))
+ filename.relative_path_from(Pathname.new(""))
end
end
end
diff --git a/lib/gitlab/git/pre_receive_error.rb b/lib/gitlab/git/pre_receive_error.rb
index 03caace6fce..8fd378bf571 100644
--- a/lib/gitlab/git/pre_receive_error.rb
+++ b/lib/gitlab/git/pre_receive_error.rb
@@ -7,7 +7,7 @@ module Gitlab
# in the web UI. To prevent XSS we sanitize the message on
# initialization.
class PreReceiveError < StandardError
- def initialize(msg = '')
+ def initialize(msg = "")
super(nlbr(msg))
end
diff --git a/lib/gitlab/git/push.rb b/lib/gitlab/git/push.rb
index b6577ba17f1..def088616dc 100644
--- a/lib/gitlab/git/push.rb
+++ b/lib/gitlab/git/push.rb
@@ -44,7 +44,7 @@ module Gitlab
def modified_paths
unless branch_updated?
- raise ArgumentError, 'Unable to calculate modified paths!'
+ raise ArgumentError, "Unable to calculate modified paths!"
end
strong_memoize(:modified_paths) do
diff --git a/lib/gitlab/git/raw_diff_change.rb b/lib/gitlab/git/raw_diff_change.rb
index e1002af40f6..43aac9d3508 100644
--- a/lib/gitlab/git/raw_diff_change.rb
+++ b/lib/gitlab/git/raw_diff_change.rb
@@ -29,7 +29,7 @@ module Gitlab
# When a file has been renamed:
# 85bc2f9753afd5f4fc5d7c75f74f8d526f26b4f3 107 R060\tfiles/js/commit.js.coffee\tfiles/js/commit.coffee
def parse(raw_change)
- @blob_id, @blob_size, @raw_operation, raw_paths = raw_change.split(' ', 4)
+ @blob_id, @blob_size, @raw_operation, raw_paths = raw_change.split(" ", 4)
@blob_size = @blob_size.to_i
@operation = extract_operation
@old_path, @new_path = extract_paths(raw_paths)
@@ -52,17 +52,17 @@ module Gitlab
return :unknown unless @raw_operation
case @raw_operation[0]
- when 'A'
+ when "A"
:added
- when 'C'
+ when "C"
:copied
- when 'D'
+ when "D"
:deleted
- when 'M'
+ when "M"
:modified
- when 'R'
+ when "R"
:renamed
- when 'T'
+ when "T"
:type_changed
else
:unknown
diff --git a/lib/gitlab/git/ref.rb b/lib/gitlab/git/ref.rb
index eec91194949..ea0d162ec59 100644
--- a/lib/gitlab/git/ref.rb
+++ b/lib/gitlab/git/ref.rb
@@ -23,21 +23,19 @@ module Gitlab
# Ex.
# Ref.extract_branch_name('refs/heads/master') #=> 'master'
def self.extract_branch_name(str)
- str.gsub(%r{\Arefs/heads/}, '')
+ str.gsub(%r{\Arefs/heads/}, "")
end
def initialize(repository, name, target, dereferenced_target)
@name = Gitlab::Git.ref_name(name)
@dereferenced_target = dereferenced_target
@target = if target.respond_to?(:oid)
- target.oid
- elsif target.respond_to?(:name)
- target.name
- elsif target.is_a? String
- target
- else
- nil
- end
+ target.oid
+ elsif target.respond_to?(:name)
+ target.name
+ elsif target.is_a? String
+ target
+ end
end
end
end
diff --git a/lib/gitlab/git/remote_repository.rb b/lib/gitlab/git/remote_repository.rb
index 234541d8145..2f03330d5ef 100644
--- a/lib/gitlab/git/remote_repository.rb
+++ b/lib/gitlab/git/remote_repository.rb
@@ -54,18 +54,18 @@ module Gitlab
end
def fetch_env
- gitaly_ssh = File.absolute_path(File.join(Gitlab.config.gitaly.client_path, 'gitaly-ssh'))
+ gitaly_ssh = File.absolute_path(File.join(Gitlab.config.gitaly.client_path, "gitaly-ssh"))
gitaly_address = gitaly_client.address(storage)
gitaly_token = gitaly_client.token(storage)
request = Gitaly::SSHUploadPackRequest.new(repository: gitaly_repository)
env = {
- 'GITALY_ADDRESS' => gitaly_address,
- 'GITALY_PAYLOAD' => request.to_json,
- 'GITALY_WD' => Dir.pwd,
- 'GIT_SSH_COMMAND' => "#{gitaly_ssh} upload-pack"
+ "GITALY_ADDRESS" => gitaly_address,
+ "GITALY_PAYLOAD" => request.to_json,
+ "GITALY_WD" => Dir.pwd,
+ "GIT_SSH_COMMAND" => "#{gitaly_ssh} upload-pack",
}
- env['GITALY_TOKEN'] = gitaly_token if gitaly_token.present?
+ env["GITALY_TOKEN"] = gitaly_token if gitaly_token.present?
env
end
diff --git a/lib/gitlab/git/repository.rb b/lib/gitlab/git/repository.rb
index aea132a3dd9..9f6580c1c81 100644
--- a/lib/gitlab/git/repository.rb
+++ b/lib/gitlab/git/repository.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'tempfile'
-require 'forwardable'
+require "tempfile"
+require "forwardable"
require "rubygems/package"
module Gitlab
@@ -17,11 +17,11 @@ module Gitlab
# In https://gitlab.com/gitlab-org/gitaly/merge_requests/698
# We copied these two prefixes into gitaly-go, so don't change these
# or things will break! (REBASE_WORKTREE_PREFIX and SQUASH_WORKTREE_PREFIX)
- REBASE_WORKTREE_PREFIX = 'rebase'.freeze
- SQUASH_WORKTREE_PREFIX = 'squash'.freeze
- GITALY_INTERNAL_URL = 'ssh://gitaly/internal.git'.freeze
+ REBASE_WORKTREE_PREFIX = "rebase"
+ SQUASH_WORKTREE_PREFIX = "squash"
+ GITALY_INTERNAL_URL = "ssh://gitaly/internal.git"
GITLAB_PROJECTS_TIMEOUT = Gitlab.config.gitlab_shell.git_timeout
- EMPTY_REPOSITORY_CHECKSUM = '0000000000000000000000000000000000000000'.freeze
+ EMPTY_REPOSITORY_CHECKSUM = "0000000000000000000000000000000000000000"
NoRepository = Class.new(StandardError)
InvalidRepository = Class.new(StandardError)
@@ -35,7 +35,7 @@ module Gitlab
class << self
def create_hooks(repo_path, global_hooks_path)
- local_hooks_path = File.join(repo_path, 'hooks')
+ local_hooks_path = File.join(repo_path, "hooks")
real_local_hooks_path = :not_found
begin
@@ -50,7 +50,8 @@ module Gitlab
# Move the existing hooks somewhere safe
FileUtils.mv(
local_hooks_path,
- "#{local_hooks_path}.old.#{Time.now.to_i}")
+ "#{local_hooks_path}.old.#{Time.now.to_i}"
+ )
end
# Create the hooks symlink
@@ -74,7 +75,7 @@ module Gitlab
# has to be performed on the object pools to update the remote names.
# Else the pool can't be updated anymore and is left in an inconsistent
# state.
- alias_method :object_pool_remote_name, :gl_repository
+ alias object_pool_remote_name gl_repository
# This initializer method is only used on the client side (gitlab-ce).
# Gitaly-ruby uses a different initializer.
@@ -91,7 +92,7 @@ module Gitlab
other.is_a?(self.class) && [storage, relative_path] == [other.storage, other.relative_path]
end
- alias_method :eql?, :==
+ alias eql? ==
def hash
[self.class, storage, relative_path].hash
@@ -168,7 +169,7 @@ module Gitlab
# /refs/git-as-svn/*
# /refs/pulls/*
# This refs by default not visible in project page and not cloned to client side.
- alias_method :has_visible_content?, :has_local_branches?
+ alias has_visible_content? has_local_branches?
# Returns the number of valid tags
def tag_count
@@ -238,10 +239,10 @@ module Gitlab
prefix = archive_prefix(ref, commit.id, project_path, append_sha: append_sha)
{
- 'ArchivePrefix' => prefix,
- 'ArchivePath' => archive_file_path(storage_path, commit.id, prefix, format),
- 'CommitId' => commit.id,
- 'GitalyRepository' => gitaly_repository.to_h
+ "ArchivePrefix" => prefix,
+ "ArchivePath" => archive_file_path(storage_path, commit.id, prefix, format),
+ "CommitId" => commit.id,
+ "GitalyRepository" => gitaly_repository.to_h,
}
end
@@ -250,12 +251,12 @@ module Gitlab
def archive_prefix(ref, sha, project_path, append_sha:)
append_sha = (ref != sha) if append_sha.nil?
- formatted_ref = ref.tr('/', '-')
+ formatted_ref = ref.tr("/", "-")
prefix_segments = [project_path, formatted_ref]
prefix_segments << sha if append_sha
- prefix_segments.join('-')
+ prefix_segments.join("-")
end
private :archive_prefix
@@ -291,7 +292,7 @@ module Gitlab
end
file_name = "#{name}.#{extension}"
- File.join(storage_path, self.gl_repository, sha, file_name)
+ File.join(storage_path, gl_repository, sha, file_name)
end
private :archive_file_path
@@ -321,7 +322,7 @@ module Gitlab
skip_merges: false,
after: nil,
before: nil,
- all: false
+ all: false,
}
options = default_options.merge(options)
@@ -417,9 +418,9 @@ module Gitlab
return [] unless root_sha
- branches = wrapped_gitaly_errors do
+ branches = wrapped_gitaly_errors {
gitaly_merged_branch_names(branch_names, root_sha)
- end
+ }
Set.new(branches)
end
@@ -439,9 +440,9 @@ module Gitlab
return empty_diff_stats
end
- stats = wrapped_gitaly_errors do
+ stats = wrapped_gitaly_errors {
gitaly_commit_client.diff_stats(left_id, right_id)
- end
+ }
Gitlab::Git::DiffStatsCollection.new(stats)
rescue CommandError, TypeError
@@ -581,7 +582,7 @@ module Gitlab
branch_name: branch_name,
message: message,
start_branch_name: start_branch_name,
- start_repository: start_repository
+ start_repository: start_repository,
}
wrapped_gitaly_errors do
@@ -596,7 +597,7 @@ module Gitlab
branch_name: branch_name,
message: message,
start_branch_name: start_branch_name,
- start_repository: start_repository
+ start_repository: start_repository,
}
wrapped_gitaly_errors do
@@ -610,7 +611,7 @@ module Gitlab
submodule: submodule,
commit_sha: commit_sha,
branch: branch,
- message: message
+ message: message,
}
wrapped_gitaly_errors do
@@ -753,7 +754,7 @@ module Gitlab
end
# Refactoring aid; allows us to copy code from app/models/repository.rb
- def commit(ref = 'HEAD')
+ def commit(ref = "HEAD")
Gitlab::Git::Commit.find(self, ref)
end
@@ -818,10 +819,10 @@ module Gitlab
def rebase(user, rebase_id, branch:, branch_sha:, remote_repository:, remote_branch:)
wrapped_gitaly_errors do
gitaly_operation_client.user_rebase(user, rebase_id,
- branch: branch,
- branch_sha: branch_sha,
- remote_repository: remote_repository,
- remote_branch: remote_branch)
+ branch: branch,
+ branch_sha: branch_sha,
+ remote_repository: remote_repository,
+ remote_branch: remote_branch)
end
end
@@ -834,7 +835,7 @@ module Gitlab
def squash(user, squash_id, branch:, start_sha:, end_sha:, author:, message:)
wrapped_gitaly_errors do
gitaly_operation_client.user_squash(user, squash_id, branch,
- start_sha, end_sha, author, message)
+ start_sha, end_sha, author, message)
end
end
@@ -855,12 +856,13 @@ module Gitlab
def multi_action(
user, branch_name:, message:, actions:,
author_email: nil, author_name: nil,
- start_branch_name: nil, start_repository: self)
+ start_branch_name: nil, start_repository: self
+ )
wrapped_gitaly_errors do
gitaly_operation_client.user_commit_files(user, branch_name,
- message, actions, author_email, author_name,
- start_branch_name, start_repository)
+ message, actions, author_email, author_name,
+ start_branch_name, start_repository)
end
end
@@ -868,9 +870,9 @@ module Gitlab
return unless full_path.present?
# This guard avoids Gitaly log/error spam
- raise NoRepository, 'repository does not exist' unless exists?
+ raise NoRepository, "repository does not exist" unless exists?
- set_config('gitlab.fullpath' => full_path)
+ set_config("gitlab.fullpath" => full_path)
end
def set_config(entries)
@@ -925,7 +927,7 @@ module Gitlab
Rails.logger.error("Unable to clean repository on storage #{storage} with relative path #{relative_path}: #{e.message}")
Gitlab::Metrics.counter(
:failed_repository_cleanup_total,
- 'Number of failed repository cleanup events'
+ "Number of failed repository cleanup events"
).increment
end
@@ -1038,12 +1040,12 @@ module Gitlab
return unless commit_object && commit_object.type == :COMMIT
- gitmodules = gitaly_commit_client.tree_entry(ref, '.gitmodules', Gitlab::Git::Blob::MAX_DATA_DISPLAY_SIZE)
+ gitmodules = gitaly_commit_client.tree_entry(ref, ".gitmodules", Gitlab::Git::Blob::MAX_DATA_DISPLAY_SIZE)
return unless gitmodules
found_module = GitmodulesParser.new(gitmodules.data).parse[path]
- found_module && found_module['url']
+ found_module && found_module["url"]
end
# Returns true if the given ref name exists
diff --git a/lib/gitlab/git/tag.rb b/lib/gitlab/git/tag.rb
index 23d989ff258..881061760d9 100644
--- a/lib/gitlab/git/tag.rb
+++ b/lib/gitlab/git/tag.rb
@@ -68,7 +68,7 @@ module Gitlab
return @raw_tag.message.dup if full_message_fetched_from_gitaly?
if @raw_tag.message_size > MAX_TAG_MESSAGE_DISPLAY_SIZE
- '--tag message is too big'
+ "--tag message is too big"
else
self.class.get_message(@repository, target)
end
diff --git a/lib/gitlab/git/tree.rb b/lib/gitlab/git/tree.rb
index 51542bcaaa2..60e066e268e 100644
--- a/lib/gitlab/git/tree.rb
+++ b/lib/gitlab/git/tree.rb
@@ -16,7 +16,7 @@ module Gitlab
#
# Gitaly migration: https://gitlab.com/gitlab-org/gitaly/issues/320
def where(repository, sha, path = nil, recursive = false)
- path = nil if path == '' || path == '/'
+ path = nil if path == "" || path == "/"
wrapped_gitaly_errors do
repository.gitaly_commit_client.tree_entries(repository, sha, path, recursive)
@@ -38,17 +38,17 @@ module Gitlab
#
def find_id_by_path(repository, root_id, path)
root_tree = repository.lookup(root_id)
- path_arr = path.split('/')
+ path_arr = path.split("/")
- entry = root_tree.find do |entry|
+ entry = root_tree.find { |entry|
entry[:name] == path_arr[0] && entry[:type] == :tree
- end
+ }
return nil unless entry
if path_arr.size > 1
path_arr.shift
- find_id_by_path(repository, entry[:oid], path_arr.join('/'))
+ find_id_by_path(repository, entry[:oid], path_arr.join("/"))
else
entry[:oid]
end
@@ -56,8 +56,8 @@ module Gitlab
end
def initialize(options)
- %w(id root_id name path flat_path type mode commit_id).each do |key|
- self.send("#{key}=", options[key.to_sym]) # rubocop:disable GitlabSecurity/PublicSend
+ %w[id root_id name path flat_path type mode commit_id].each do |key|
+ send("#{key}=", options[key.to_sym]) # rubocop:disable GitlabSecurity/PublicSend
end
end
diff --git a/lib/gitlab/git/util.rb b/lib/gitlab/git/util.rb
index 03c2c1367b0..cf8571bf917 100644
--- a/lib/gitlab/git/util.rb
+++ b/lib/gitlab/git/util.rb
@@ -5,7 +5,7 @@
module Gitlab
module Git
module Util
- LINE_SEP = "\n".freeze
+ LINE_SEP = "\n"
def self.count_lines(string)
case string[-1]
diff --git a/lib/gitlab/git/wiki.rb b/lib/gitlab/git/wiki.rb
index c43331bed60..9aa8c8ae8fd 100644
--- a/lib/gitlab/git/wiki.rb
+++ b/lib/gitlab/git/wiki.rb
@@ -10,21 +10,21 @@ module Gitlab
DEFAULT_PAGINATION = Kaminari.config.default_per_page
- CommitDetails = Struct.new(:user_id, :username, :name, :email, :message) do
+ CommitDetails = Struct.new(:user_id, :username, :name, :email, :message) {
def to_h
- { user_id: user_id, username: username, name: name, email: email, message: message }
+ {user_id: user_id, username: username, name: name, email: email, message: message}
end
- end
+ }
# GollumSlug inlines just enough knowledge from Gollum::Page to generate a
# slug, which is used when previewing pages that haven't been persisted
class GollumSlug
class << self
- def cname(name, char_white_sub = '-', char_other_sub = '-')
+ def cname(name, char_white_sub = "-", char_other_sub = "-")
if name.respond_to?(:gsub)
name.gsub(/\s/, char_white_sub).gsub(/[<>+]/, char_other_sub)
else
- ''
+ ""
end
end
@@ -33,22 +33,22 @@ module Gitlab
end
def canonicalize_filename(filename)
- ::File.basename(filename, ::File.extname(filename)).tr('-', ' ')
+ ::File.basename(filename, ::File.extname(filename)).tr("-", " ")
end
def generate(title, format)
ext = format_to_ext(format.to_sym)
- name = cname(title) + '.' + ext
+ name = cname(title) + "." + ext
canonical_name = canonicalize_filename(name)
path =
- if name.include?('/')
- name.sub(%r{/[^/]+$}, '/')
+ if name.include?("/")
+ name.sub(%r{/[^/]+$}, "/")
else
- ''
+ ""
end
- path + cname(canonical_name, '-', '-')
+ path + cname(canonical_name, "-", "-")
end
end
end
@@ -56,7 +56,7 @@ module Gitlab
attr_reader :repository
def self.default_ref
- 'master'
+ "master"
end
# Initialize with a Gitlab::Git::Repository instance
@@ -109,9 +109,9 @@ module Gitlab
# :per_page - The number of items per page.
# :limit - Total number of items to return.
def page_versions(page_path, options = {})
- versions = wrapped_gitaly_errors do
+ versions = wrapped_gitaly_errors {
gitaly_wiki_client.page_versions(page_path, options)
- end
+ }
# Gitaly uses gollum-lib to get the versions. Gollum defaults to 20
# per page, but also fetches 20 if `limit` or `per_page` < 20.
@@ -121,7 +121,7 @@ module Gitlab
end
def count_page_versions(page_path)
- @repository.count_commits(ref: 'HEAD', path: page_path)
+ @repository.count_commits(ref: "HEAD", path: page_path)
end
def preview_slug(title, format)
diff --git a/lib/gitlab/git_access.rb b/lib/gitlab/git_access.rb
index 010bd0e520c..bff3c2f576d 100644
--- a/lib/gitlab/git_access.rb
+++ b/lib/gitlab/git_access.rb
@@ -14,22 +14,22 @@ module Gitlab
# Use the magic string '_any' to indicate we do not know what the
# changes are. This is also what gitlab-shell does.
- ANY = '_any'
+ ANY = "_any"
ERROR_MESSAGES = {
- upload: 'You are not allowed to upload code for this project.',
- download: 'You are not allowed to download code from this project.',
- auth_upload: 'You are not allowed to upload code.',
- auth_download: 'You are not allowed to download code.',
- deploy_key_upload: 'This deploy key does not have write access to this project.',
- no_repo: 'A repository for this project does not exist yet.',
- project_not_found: 'The project you were looking for could not be found.',
+ upload: "You are not allowed to upload code for this project.",
+ download: "You are not allowed to download code from this project.",
+ auth_upload: "You are not allowed to upload code.",
+ auth_download: "You are not allowed to download code.",
+ deploy_key_upload: "This deploy key does not have write access to this project.",
+ no_repo: "A repository for this project does not exist yet.",
+ project_not_found: "The project you were looking for could not be found.",
command_not_allowed: "The command you're trying to execute is not allowed.",
- upload_pack_disabled_over_http: 'Pulling over HTTP is not allowed.',
- receive_pack_disabled_over_http: 'Pushing over HTTP is not allowed.',
- read_only: 'The repository is temporarily read-only. Please try again later.',
+ upload_pack_disabled_over_http: "Pulling over HTTP is not allowed.",
+ receive_pack_disabled_over_http: "Pushing over HTTP is not allowed.",
+ read_only: "The repository is temporarily read-only. Please try again later.",
cannot_push_to_read_only: "You can't push code to a read-only GitLab instance.",
- push_code: 'You are not allowed to push code to this project.'
+ push_code: "You are not allowed to push code to this project.",
}.freeze
INTERNAL_TIMEOUT = 50.seconds.freeze
@@ -39,8 +39,8 @@ module Gitlab
Timing information for debugging purposes:
MESSAGE
- DOWNLOAD_COMMANDS = %w{git-upload-pack git-upload-archive}.freeze
- PUSH_COMMANDS = %w{git-receive-pack}.freeze
+ DOWNLOAD_COMMANDS = %w[git-upload-pack git-upload-archive].freeze
+ PUSH_COMMANDS = %w[git-receive-pack].freeze
ALL_COMMANDS = DOWNLOAD_COMMANDS + PUSH_COMMANDS
attr_reader :actor, :project, :protocol, :authentication_abilities, :namespace_path, :project_path, :redirected_path, :auth_result_type, :changes, :logger
@@ -101,7 +101,7 @@ module Gitlab
end
def request_from_ci_build?
- return false unless protocol == 'http'
+ return false unless protocol == "http"
auth_result_type == :build || auth_result_type == :ci
end
@@ -213,13 +213,13 @@ module Gitlab
project_params = {
path: project_path,
namespace_id: namespace.id,
- visibility_level: Gitlab::VisibilityLevel::PRIVATE
+ visibility_level: Gitlab::VisibilityLevel::PRIVATE,
}
project = Projects::CreateService.new(user, project_params).execute
unless project.saved?
- raise ProjectCreationError, "Could not create project: #{project.errors.full_messages.join(', ')}"
+ raise ProjectCreationError, "Could not create project: #{project.errors.full_messages.join(", ")}"
end
@project = project
@@ -340,15 +340,15 @@ module Gitlab
end
def http?
- protocol == 'http'
+ protocol == "http"
end
def upload_pack?(command)
- command == 'git-upload-pack'
+ command == "git-upload-pack"
end
def receive_pack?(command)
- command == 'git-receive-pack'
+ command == "git-receive-pack"
end
def upload_pack_disabled_over_http?
@@ -383,12 +383,12 @@ module Gitlab
def user_access
@user_access ||= if ci?
- CiAccess.new
- elsif user && request_from_ci_build?
- BuildAccess.new(user, project: project)
- else
- UserAccess.new(user, project: project)
- end
+ CiAccess.new
+ elsif user && request_from_ci_build?
+ BuildAccess.new(user, project: project)
+ else
+ UserAccess.new(user, project: project)
+ end
end
def push_to_read_only_message
diff --git a/lib/gitlab/git_access_wiki.rb b/lib/gitlab/git_access_wiki.rb
index 0af91957fa8..7d43c468265 100644
--- a/lib/gitlab/git_access_wiki.rb
+++ b/lib/gitlab/git_access_wiki.rb
@@ -3,8 +3,8 @@
module Gitlab
class GitAccessWiki < GitAccess
ERROR_MESSAGES = {
- read_only: "You can't push code to a read-only GitLab instance.",
- write_to_wiki: "You are not allowed to write to this project's wiki."
+ read_only: "You can't push code to a read-only GitLab instance.",
+ write_to_wiki: "You are not allowed to write to this project's wiki.",
}.freeze
def guest_can_download_code?
diff --git a/lib/gitlab/git_logger.rb b/lib/gitlab/git_logger.rb
index dac4ddd320f..667d6581268 100644
--- a/lib/gitlab/git_logger.rb
+++ b/lib/gitlab/git_logger.rb
@@ -3,7 +3,7 @@
module Gitlab
class GitLogger < Gitlab::Logger
def self.file_name_noext
- 'githost'
+ "githost"
end
def format_message(severity, timestamp, progname, msg)
diff --git a/lib/gitlab/git_post_receive.rb b/lib/gitlab/git_post_receive.rb
index 426436c2164..7d98cb6191e 100644
--- a/lib/gitlab/git_post_receive.rb
+++ b/lib/gitlab/git_post_receive.rb
@@ -21,7 +21,7 @@ module Gitlab
changes.each do |change|
change.strip!
- oldrev, newrev, ref = change.split(' ')
+ oldrev, newrev, ref = change.split(" ")
yield oldrev, newrev, ref
end
@@ -34,14 +34,14 @@ module Gitlab
end
def utf8_encode_changes(changes)
- changes.force_encoding('UTF-8')
+ changes.force_encoding("UTF-8")
return changes if changes.valid_encoding?
# Convert non-UTF-8 branch/tag names to UTF-8 so they can be dumped as JSON.
detection = CharlockHolmes::EncodingDetector.detect(changes)
return changes unless detection && detection[:encoding]
- CharlockHolmes::Converter.convert(changes, detection[:encoding], 'UTF-8')
+ CharlockHolmes::Converter.convert(changes, detection[:encoding], "UTF-8")
end
end
end
diff --git a/lib/gitlab/git_ref_validator.rb b/lib/gitlab/git_ref_validator.rb
index 3f13ebeb9d0..370fb1601ce 100644
--- a/lib/gitlab/git_ref_validator.rb
+++ b/lib/gitlab/git_ref_validator.rb
@@ -9,9 +9,9 @@ module Gitlab
#
# Returns true for a valid reference name, false otherwise
def validate(ref_name)
- not_allowed_prefixes = %w(refs/heads/ refs/remotes/ -)
+ not_allowed_prefixes = %w[refs/heads/ refs/remotes/ -]
return false if ref_name.start_with?(*not_allowed_prefixes)
- return false if ref_name == 'HEAD'
+ return false if ref_name == "HEAD"
begin
Rugged::Reference.valid_name?("refs/heads/#{ref_name}")
diff --git a/lib/gitlab/gitaly_client.rb b/lib/gitlab/gitaly_client.rb
index 5aeedb0f50d..43aef43b58e 100644
--- a/lib/gitlab/gitaly_client.rb
+++ b/lib/gitlab/gitaly_client.rb
@@ -1,10 +1,10 @@
# frozen_string_literal: true
-require 'base64'
+require "base64"
-require 'gitaly'
-require 'grpc/health/v1/health_pb'
-require 'grpc/health/v1/health_services_pb'
+require "gitaly"
+require "grpc/health/v1/health_pb"
+require "grpc/health/v1/health_services_pb"
module Gitlab
module GitalyClient
@@ -27,9 +27,9 @@ module Gitlab
end
PEM_REGEX = /\-+BEGIN CERTIFICATE\-+.+?\-+END CERTIFICATE\-+/m
- SERVER_VERSION_FILE = 'GITALY_SERVER_VERSION'
+ SERVER_VERSION_FILE = "GITALY_SERVER_VERSION"
MAXIMUM_GITALY_CALLS = 30
- CLIENT_NAME = (Sidekiq.server? ? 'gitlab-sidekiq' : 'gitlab-web').freeze
+ CLIENT_NAME = (Sidekiq.server? ? "gitlab-sidekiq" : "gitlab-web").freeze
MUTEX = Mutex.new
@@ -73,21 +73,21 @@ module Gitlab
def self.stub_certs
return @certs if @certs
- @certs = stub_cert_paths.flat_map do |cert_file|
- File.read(cert_file).scan(PEM_REGEX).map do |cert|
- begin
+ @certs = stub_cert_paths.flat_map { |cert_file|
+ File.read(cert_file).scan(PEM_REGEX).map { |cert|
+
OpenSSL::X509::Certificate.new(cert).to_pem
rescue OpenSSL::OpenSSLError => e
Rails.logger.error "Could not load certificate #{cert_file} #{e}"
- Gitlab::Sentry.track_exception(e, extra: { cert_file: cert_file })
+ Gitlab::Sentry.track_exception(e, extra: {cert_file: cert_file})
nil
- end
- end.compact
- end.uniq.join("\n")
+
+ }.compact
+ }.uniq.join("\n")
end
def self.stub_creds(storage)
- if URI(address(storage)).scheme == 'tls'
+ if URI(address(storage)).scheme == "tls"
GRPC::Core::ChannelCredentials.new stub_certs
else
:this_channel_is_insecure
@@ -103,7 +103,7 @@ module Gitlab
end
def self.stub_address(storage)
- address(storage).sub(%r{^tcp://|^tls://}, '')
+ address(storage).sub(%r{^tcp://|^tls://}, "")
end
def self.clear_stubs!
@@ -120,12 +120,12 @@ module Gitlab
params = Gitlab.config.repositories.storages[storage]
raise "storage not found: #{storage.inspect}" if params.nil?
- address = params['gitaly_address']
+ address = params["gitaly_address"]
unless address.present?
raise "storage #{storage.inspect} is missing a gitaly_address"
end
- unless URI(address).scheme.in?(%w(tcp unix tls))
+ unless URI(address).scheme.in?(%w[tcp unix tls])
raise "Unsupported Gitaly address: #{address.inspect} does not use URL scheme 'tcp' or 'unix' or 'tls'"
end
@@ -137,7 +137,7 @@ module Gitlab
end
def self.connection_data(storage)
- { 'address' => address(storage), 'token' => token(storage) }
+ {"address" => address(storage), "token" => token(storage)}
end
# All Gitaly RPC call sites should use GitalyClient.call. This method
@@ -173,14 +173,15 @@ module Gitlab
self.query_time += duration
gitaly_controller_action_duration_seconds.observe(
current_transaction_labels.merge(gitaly_service: service.to_s, rpc: rpc.to_s),
- duration)
+ duration
+)
add_call_details(feature: "#{service}##{rpc}", duration: duration, request: request_hash, rpc: rpc)
end
def self.handle_grpc_unavailable!(ex)
status = ex.to_status
- raise ex unless status.details == 'Endpoint read failed'
+ raise ex unless status.details == "Endpoint read failed"
# There is a bug in grpc 1.8.x that causes a client process to get stuck
# always raising '14:Endpoint read failed'. The only thing that we can
@@ -192,7 +193,7 @@ module Gitlab
raise Gitlab::SidekiqMiddleware::Shutdown::WantShutdown.new(ex.to_s)
else
# SIGQUIT requests a Unicorn worker to shut down gracefully after the current request.
- Process.kill('QUIT', Process.pid)
+ Process.kill("QUIT", Process.pid)
end
raise ex
@@ -226,19 +227,19 @@ module Gitlab
def self.request_kwargs(storage, timeout, remote_storage: nil)
metadata = {
- 'authorization' => "Bearer #{authorization_token(storage)}",
- 'client_name' => CLIENT_NAME
+ "authorization" => "Bearer #{authorization_token(storage)}",
+ "client_name" => CLIENT_NAME,
}
feature_stack = Thread.current[:gitaly_feature_stack]
feature = feature_stack && feature_stack[0]
- metadata['call_site'] = feature.to_s if feature
- metadata['gitaly-servers'] = address_metadata(remote_storage) if remote_storage
- metadata['x-gitlab-correlation-id'] = Gitlab::CorrelationId.current_id if Gitlab::CorrelationId.current_id
+ metadata["call_site"] = feature.to_s if feature
+ metadata["gitaly-servers"] = address_metadata(remote_storage) if remote_storage
+ metadata["x-gitlab-correlation-id"] = Gitlab::CorrelationId.current_id if Gitlab::CorrelationId.current_id
metadata.merge!(server_feature_flags)
- result = { metadata: metadata }
+ result = {metadata: metadata}
# nil timeout indicates that we should use the default
timeout = default_timeout if timeout.nil?
@@ -254,16 +255,16 @@ module Gitlab
SERVER_FEATURE_FLAGS = %w[].freeze
def self.server_feature_flags
- SERVER_FEATURE_FLAGS.map do |f|
- ["gitaly-feature-#{f.tr('_', '-')}", feature_enabled?(f).to_s]
- end.to_h
+ SERVER_FEATURE_FLAGS.map { |f|
+ ["gitaly-feature-#{f.tr("_", "-")}", feature_enabled?(f).to_s]
+ }.to_h
end
def self.token(storage)
params = Gitlab.config.repositories.storages[storage]
raise "storage not found: #{storage.inspect}" if params.nil?
- params['gitaly_token'].presence || Gitlab.config.gitaly['token']
+ params["gitaly_token"].presence || Gitlab.config.gitaly["token"]
end
def self.feature_enabled?(feature_name)
@@ -338,14 +339,14 @@ module Gitlab
def self.add_call_details(details)
return unless Gitlab::SafeRequestStore[:peek_enabled]
- Gitlab::SafeRequestStore['gitaly_call_details'] ||= []
- Gitlab::SafeRequestStore['gitaly_call_details'] << details
+ Gitlab::SafeRequestStore["gitaly_call_details"] ||= []
+ Gitlab::SafeRequestStore["gitaly_call_details"] << details
end
def self.list_call_details
return [] unless Gitlab::SafeRequestStore[:peek_enabled]
- Gitlab::SafeRequestStore['gitaly_call_details'] || []
+ Gitlab::SafeRequestStore["gitaly_call_details"] || []
end
def self.expected_server_version
@@ -387,7 +388,7 @@ module Gitlab
stack_string = Gitlab::Profiler.clean_backtrace(caller).drop(1).join("\n")
- Gitlab::SafeRequestStore[:stack_counter] ||= Hash.new
+ Gitlab::SafeRequestStore[:stack_counter] ||= {}
count = Gitlab::SafeRequestStore[:stack_counter][stack_string] || 0
Gitlab::SafeRequestStore[:stack_counter][stack_string] = count + 1
diff --git a/lib/gitlab/gitaly_client/blobs_stitcher.rb b/lib/gitlab/gitaly_client/blobs_stitcher.rb
index 01bab854082..f860d8ce517 100644
--- a/lib/gitlab/gitaly_client/blobs_stitcher.rb
+++ b/lib/gitlab/gitaly_client/blobs_stitcher.rb
@@ -13,17 +13,15 @@ module Gitlab
current_blob_data = nil
@rpc_response.each do |msg|
- begin
- if msg.oid.blank? && msg.data.blank?
- next
- elsif msg.oid.present?
- yield new_blob(current_blob_data) if current_blob_data
-
- current_blob_data = msg.to_h.slice(:oid, :path, :size, :revision, :mode)
- current_blob_data[:data] = msg.data.dup
- else
- current_blob_data[:data] << msg.data
- end
+ if msg.oid.blank? && msg.data.blank?
+ next
+ elsif msg.oid.present?
+ yield new_blob(current_blob_data) if current_blob_data
+
+ current_blob_data = msg.to_h.slice(:oid, :path, :size, :revision, :mode)
+ current_blob_data[:data] = msg.data.dup
+ else
+ current_blob_data[:data] << msg.data
end
end
diff --git a/lib/gitlab/gitaly_client/cleanup_service.rb b/lib/gitlab/gitaly_client/cleanup_service.rb
index 3e8d6a773ca..779fc5c4429 100644
--- a/lib/gitlab/gitaly_client/cleanup_service.rb
+++ b/lib/gitlab/gitaly_client/cleanup_service.rb
@@ -15,14 +15,14 @@ module Gitlab
def apply_bfg_object_map(io)
first_request = Gitaly::ApplyBfgObjectMapRequest.new(repository: gitaly_repo)
- enum = Enumerator.new do |y|
+ enum = Enumerator.new { |y|
y.yield first_request
while data = io.read(RepositoryService::MAX_MSG_SIZE)
y.yield Gitaly::ApplyBfgObjectMapRequest.new(object_map: data)
break if io&.eof?
end
- end
+ }
GitalyClient.call(
storage,
diff --git a/lib/gitlab/gitaly_client/commit_service.rb b/lib/gitlab/gitaly_client/commit_service.rb
index ea12424eb4a..a5d575d2543 100644
--- a/lib/gitlab/gitaly_client/commit_service.rb
+++ b/lib/gitlab/gitaly_client/commit_service.rb
@@ -44,7 +44,7 @@ module Gitlab
else
from
end
- end
+ end
to_id = case to
when NilClass
@@ -57,7 +57,7 @@ module Gitlab
else
to
end
- end
+ end
request_params = diff_between_commits_request_params(from_id, to_id, options)
@@ -78,7 +78,7 @@ module Gitlab
end
def tree_entry(ref, path, limit = nil)
- if Pathname.new(path).cleanpath.to_s.start_with?('../')
+ if Pathname.new(path).cleanpath.to_s.start_with?("../")
# The TreeEntry RPC should return an empty reponse in this case but in
# Gitaly 0.107.0 and earlier we get an exception instead. This early return
# saves us a Gitaly roundtrip while also avoiding the exception.
@@ -114,7 +114,7 @@ module Gitlab
request = Gitaly::GetTreeEntriesRequest.new(
repository: @gitaly_repo,
revision: encode_binary(revision),
- path: path.present? ? encode_binary(path) : '.',
+ path: path.present? ? encode_binary(path) : ".",
recursive: recursive
)
@@ -238,7 +238,7 @@ module Gitlab
[]
end
- def commits_by_message(query, revision: '', path: '', limit: 1000, offset: 0)
+ def commits_by_message(query, revision: "", path: "", limit: 1000, offset: 0)
request = Gitaly::CommitsByMessageRequest.new(
repository: @gitaly_repo,
query: query,
@@ -253,10 +253,10 @@ module Gitlab
end
def languages(ref = nil)
- request = Gitaly::CommitLanguagesRequest.new(repository: @gitaly_repo, revision: ref || '')
+ request = Gitaly::CommitLanguagesRequest.new(repository: @gitaly_repo, revision: ref || "")
response = GitalyClient.call(@repository.storage, :commit_service, :commit_languages, request)
- response.languages.map { |l| { value: l.share.round(2), label: l.name, color: l.color, highlight: l.color } }
+ response.languages.map { |l| {value: l.share.round(2), label: l.name, color: l.color, highlight: l.color} }
end
def raw_blame(revision, path)
@@ -279,7 +279,7 @@ module Gitlab
key = {
storage: @gitaly_repo.storage_name,
relative_path: @gitaly_repo.relative_path,
- commit_id: revision
+ commit_id: revision,
}
return Gitlab::SafeRequestStore[key] if Gitlab::SafeRequestStore.exist?(key)
@@ -315,12 +315,12 @@ module Gitlab
def find_commits(options)
request = Gitaly::FindCommitsRequest.new(
- repository: @gitaly_repo,
- limit: options[:limit],
- offset: options[:offset],
- follow: options[:follow],
- skip_merges: options[:skip_merges],
- all: !!options[:all],
+ repository: @gitaly_repo,
+ limit: options[:limit],
+ offset: options[:offset],
+ follow: options[:follow],
+ skip_merges: options[:skip_merges],
+ all: !!options[:all],
disable_walk: true # This option is deprecated. The 'walk' implementation is being removed.
)
request.after = GitalyClient.timestamp(options[:after]) if options[:after]
@@ -337,7 +337,7 @@ module Gitlab
def filter_shas_with_signatures(shas)
request = Gitaly::FilterShasWithSignaturesRequest.new(repository: @gitaly_repo)
- enum = Enumerator.new do |y|
+ enum = Enumerator.new { |y|
shas.each_slice(20) do |revs|
request.shas = encode_repeated(revs)
@@ -345,7 +345,7 @@ module Gitlab
request = Gitaly::FilterShasWithSignaturesRequest.new
end
- end
+ }
response = GitalyClient.call(@repository.storage, :commit_service, :filter_shas_with_signatures, enum, timeout: GitalyClient.fast_timeout)
@@ -358,8 +358,8 @@ module Gitlab
request = Gitaly::ExtractCommitSignatureRequest.new(repository: @gitaly_repo, commit_id: commit_id)
response = GitalyClient.call(@repository.storage, :commit_service, :extract_commit_signature, request)
- signature = +''.b
- signed_text = +''.b
+ signature = +"".b
+ signed_text = +"".b
response.each do |message|
signature << message.signature
@@ -377,7 +377,7 @@ module Gitlab
request = Gitaly::GetCommitSignaturesRequest.new(repository: @gitaly_repo, commit_ids: commit_ids)
response = GitalyClient.call(@repository.storage, :commit_service, :get_commit_signatures, request, timeout: GitalyClient.fast_timeout)
- signatures = Hash.new { |h, k| h[k] = [+''.b, +''.b] }
+ signatures = Hash.new { |h, k| h[k] = [+"".b, +"".b] }
current_commit_id = nil
response.each do |message|
@@ -396,7 +396,7 @@ module Gitlab
request = Gitaly::GetCommitMessagesRequest.new(repository: @gitaly_repo, commit_ids: commit_ids)
response = GitalyClient.call(@repository.storage, :commit_service, :get_commit_messages, request, timeout: GitalyClient.fast_timeout)
- messages = Hash.new { |h, k| h[k] = +''.b }
+ messages = Hash.new { |h, k| h[k] = +"".b }
current_commit_id = nil
response.each do |rpc_message|
@@ -432,7 +432,7 @@ module Gitlab
repository: @gitaly_repo,
left_commit_id: from_id,
right_commit_id: to_id,
- paths: options.fetch(:paths, []).compact.map { |path| encode_binary(path) }
+ paths: options.fetch(:paths, []).compact.map { |path| encode_binary(path) },
}
end
@@ -445,7 +445,7 @@ module Gitlab
end
def encode_repeated(array)
- Google::Protobuf::RepeatedField.new(:bytes, array.map { |s| encode_binary(s) } )
+ Google::Protobuf::RepeatedField.new(:bytes, array.map { |s| encode_binary(s) })
end
def call_find_commit(revision)
diff --git a/lib/gitlab/gitaly_client/conflict_files_stitcher.rb b/lib/gitlab/gitaly_client/conflict_files_stitcher.rb
index 0e00f6e8c44..6fe5902953c 100644
--- a/lib/gitlab/gitaly_client/conflict_files_stitcher.rb
+++ b/lib/gitlab/gitaly_client/conflict_files_stitcher.rb
@@ -34,14 +34,14 @@ module Gitlab
Gitlab::GitalyClient::Util.git_repository(header.repository),
header.commit_oid,
conflict_from_gitaly_file_header(header),
- ''
+ ""
)
end
def conflict_from_gitaly_file_header(header)
{
- ours: { path: header.our_path, mode: header.our_mode },
- theirs: { path: header.their_path }
+ ours: {path: header.our_path, mode: header.our_mode},
+ theirs: {path: header.their_path},
}
end
end
diff --git a/lib/gitlab/gitaly_client/conflicts_service.rb b/lib/gitlab/gitaly_client/conflicts_service.rb
index 6304f998563..ccc7f3dcfd4 100644
--- a/lib/gitlab/gitaly_client/conflicts_service.rb
+++ b/lib/gitlab/gitaly_client/conflicts_service.rb
@@ -39,7 +39,7 @@ module Gitlab
def resolve_conflicts(target_repository, resolution, source_branch, target_branch)
reader = binary_stringio(resolution.files.to_json)
- req_enum = Enumerator.new do |y|
+ req_enum = Enumerator.new { |y|
header = resolve_conflicts_request_header(target_repository, resolution, source_branch, target_branch)
y.yield Gitaly::ResolveConflictsRequest.new(header: header)
@@ -48,7 +48,7 @@ module Gitlab
y.yield Gitaly::ResolveConflictsRequest.new(files_json: chunk)
end
- end
+ }
response = GitalyClient.call(@repository.storage, :conflicts_service, :resolve_conflicts, req_enum, remote_storage: target_repository.storage, timeout: GitalyClient.medium_timeout)
diff --git a/lib/gitlab/gitaly_client/diff.rb b/lib/gitlab/gitaly_client/diff.rb
index dd192ccde1a..c30b8ab1bc8 100644
--- a/lib/gitlab/gitaly_client/diff.rb
+++ b/lib/gitlab/gitaly_client/diff.rb
@@ -3,7 +3,7 @@
module Gitlab
module GitalyClient
class Diff
- ATTRS = %i(from_path to_path old_mode new_mode from_id to_id patch overflow_marker collapsed too_large).freeze
+ ATTRS = %i[from_path to_path old_mode new_mode from_id to_id patch overflow_marker collapsed too_large].freeze
include AttributesBag
end
diff --git a/lib/gitlab/gitaly_client/health_check_service.rb b/lib/gitlab/gitaly_client/health_check_service.rb
index 0c495f60633..5f408c25af4 100644
--- a/lib/gitlab/gitaly_client/health_check_service.rb
+++ b/lib/gitlab/gitaly_client/health_check_service.rb
@@ -12,9 +12,9 @@ module Gitlab
request = Grpc::Health::V1::HealthCheckRequest.new
response = GitalyClient.call(@storage, :health_check, :check, request, timeout: GitalyClient.fast_timeout)
- { success: response&.status == :SERVING }
+ {success: response&.status == :SERVING}
rescue GRPC::BadStatus => e
- { success: false, message: e.to_s }
+ {success: false, message: e.to_s}
end
end
end
diff --git a/lib/gitlab/gitaly_client/object_pool_service.rb b/lib/gitlab/gitaly_client/object_pool_service.rb
index 6e7ede5fd18..287076c0139 100644
--- a/lib/gitlab/gitaly_client/object_pool_service.rb
+++ b/lib/gitlab/gitaly_client/object_pool_service.rb
@@ -13,7 +13,8 @@ module Gitlab
def create(repository)
request = Gitaly::CreateObjectPoolRequest.new(
object_pool: object_pool,
- origin: repository.gitaly_repository)
+ origin: repository.gitaly_repository
+ )
GitalyClient.call(storage, :object_pool_service, :create_object_pool, request)
end
@@ -31,7 +32,7 @@ module Gitlab
)
GitalyClient.call(storage, :object_pool_service, :link_repository_to_object_pool,
- request, timeout: GitalyClient.fast_timeout)
+ request, timeout: GitalyClient.fast_timeout)
end
def unlink_repository(repository)
@@ -41,7 +42,7 @@ module Gitlab
)
GitalyClient.call(storage, :object_pool_service, :unlink_repository_from_object_pool,
- request, timeout: GitalyClient.fast_timeout)
+ request, timeout: GitalyClient.fast_timeout)
end
end
end
diff --git a/lib/gitlab/gitaly_client/operation_service.rb b/lib/gitlab/gitaly_client/operation_service.rb
index d172c798da2..e2bb5ebff86 100644
--- a/lib/gitlab/gitaly_client/operation_service.rb
+++ b/lib/gitlab/gitaly_client/operation_service.rb
@@ -150,7 +150,7 @@ module Gitlab
branch_update = second_response.branch_update
return if branch_update.nil?
- raise Gitlab::Git::CommitError.new('failed to apply merge to branch') unless branch_update.commit_id.present?
+ raise Gitlab::Git::CommitError.new("failed to apply merge to branch") unless branch_update.commit_id.present?
Gitlab::Git::OperationService::BranchUpdate.from_gitaly(branch_update)
ensure
@@ -179,22 +179,22 @@ module Gitlab
def user_cherry_pick(user:, commit:, branch_name:, message:, start_branch_name:, start_repository:)
call_cherry_pick_or_revert(:cherry_pick,
- user: user,
- commit: commit,
- branch_name: branch_name,
- message: message,
- start_branch_name: start_branch_name,
- start_repository: start_repository)
+ user: user,
+ commit: commit,
+ branch_name: branch_name,
+ message: message,
+ start_branch_name: start_branch_name,
+ start_repository: start_repository)
end
def user_revert(user:, commit:, branch_name:, message:, start_branch_name:, start_repository:)
call_cherry_pick_or_revert(:revert,
- user: user,
- commit: commit,
- branch_name: branch_name,
- message: message,
- start_branch_name: start_branch_name,
- start_repository: start_repository)
+ user: user,
+ commit: commit,
+ branch_name: branch_name,
+ message: message,
+ start_branch_name: start_branch_name,
+ start_repository: start_repository)
end
def user_rebase(user, rebase_id, branch:, branch_sha:, remote_repository:, remote_branch:)
@@ -279,12 +279,13 @@ module Gitlab
def user_commit_files(
user, branch_name, commit_message, actions, author_email, author_name,
- start_branch_name, start_repository)
+ start_branch_name, start_repository
+ )
- req_enum = Enumerator.new do |y|
+ req_enum = Enumerator.new { |y|
header = user_commit_files_request_header(user, branch_name,
- commit_message, actions, author_email, author_name,
- start_branch_name, start_repository)
+ commit_message, actions, author_email, author_name,
+ start_branch_name, start_repository)
y.yield Gitaly::UserCommitFilesRequest.new(header: header)
@@ -304,7 +305,7 @@ module Gitlab
)
end
end
- end
+ }
response = GitalyClient.call(@repository.storage, :operation_service,
:user_commit_files, req_enum, remote_storage: start_repository.storage)
@@ -328,7 +329,7 @@ module Gitlab
)
reader = binary_stringio(patches)
- chunks = Enumerator.new do |chunk|
+ chunks = Enumerator.new { |chunk|
chunk.yield Gitaly::UserApplyPatchRequest.new(header: header)
until reader.eof?
@@ -336,7 +337,7 @@ module Gitlab
chunk.yield(Gitaly::UserApplyPatchRequest.new(patches: patch_chunk))
end
- end
+ }
response = GitalyClient.call(@repository.storage, :operation_service, :user_apply_patch, chunks)
@@ -384,7 +385,8 @@ module Gitlab
def user_commit_files_request_header(
user, branch_name, commit_message, actions, author_email, author_name,
- start_branch_name, start_repository)
+ start_branch_name, start_repository
+ )
Gitaly::UserCommitFilesRequestHeader.new(
repository: @gitaly_repo,
@@ -403,7 +405,7 @@ module Gitlab
action: action[:action].upcase.to_sym,
file_path: encode_binary(action[:file_path]),
previous_path: encode_binary(action[:previous_path]),
- base64_content: action[:encoding] == 'base64',
+ base64_content: action[:encoding] == "base64",
execute_filemode: !!action[:execute_filemode],
infer_content: !!action[:infer_content]
)
diff --git a/lib/gitlab/gitaly_client/ref_service.rb b/lib/gitlab/gitaly_client/ref_service.rb
index d5633d167ac..0887574779a 100644
--- a/lib/gitlab/gitaly_client/ref_service.rb
+++ b/lib/gitlab/gitaly_client/ref_service.rb
@@ -220,7 +220,7 @@ module Gitlab
request = Gitaly::GetTagMessagesRequest.new(repository: @gitaly_repo, tag_ids: tag_ids)
response = GitalyClient.call(@repository.storage, :ref_service, :get_tag_messages, request, timeout: GitalyClient.fast_timeout)
- messages = Hash.new { |h, k| h[k] = +''.b }
+ messages = Hash.new { |h, k| h[k] = +"".b }
current_tag_id = nil
response.each do |rpc_message|
@@ -239,7 +239,7 @@ module Gitlab
end
def sort_by_param(sort_by)
- sort_by = 'name' if sort_by == 'name_asc'
+ sort_by = "name" if sort_by == "name_asc"
enum_value = Gitaly::FindLocalBranchesRequest::SortBy.resolve(sort_by.upcase.to_sym)
raise ArgumentError, "Invalid sort_by key `#{sort_by}`" unless enum_value
@@ -270,12 +270,12 @@ module Gitlab
end
def consume_find_all_remote_branches_response(remote_name, response)
- remote_name += '/' unless remote_name.ends_with?('/')
+ remote_name += "/" unless remote_name.ends_with?("/")
response.flat_map do |message|
message.branches.map do |branch|
target_commit = Gitlab::Git::Commit.decorate(@repository, branch.target_commit)
- branch_name = branch.name.sub(remote_name, '')
+ branch_name = branch.name.sub(remote_name, "")
Gitlab::Git::Branch.new(@repository, branch_name, branch.target_commit.id, target_commit)
end
end
@@ -291,7 +291,7 @@ module Gitlab
# Git messages have no encoding enforcements. However, in the UI we only
# handle UTF-8, so basically we cross our fingers that the message force
# encoded to UTF-8 is readable.
- message = response.commit_subject.dup.force_encoding('UTF-8')
+ message = response.commit_subject.dup.force_encoding("UTF-8")
# NOTE: For ease of parsing in Gitaly, we have only the subject of
# the commit and not the full message. This is ok, since all the
@@ -308,7 +308,7 @@ module Gitlab
author_email: response.commit_author.email.dup,
committed_date: Time.at(response.commit_committer.date.seconds),
committer_name: response.commit_committer.name.dup,
- committer_email: response.commit_committer.email.dup
+ committer_email: response.commit_committer.email.dup,
}
Gitlab::Git::Commit.decorate(@repository, hash)
diff --git a/lib/gitlab/gitaly_client/remote_service.rb b/lib/gitlab/gitaly_client/remote_service.rb
index 81fac37ee68..3d92a0f2f26 100644
--- a/lib/gitlab/gitaly_client/remote_service.rb
+++ b/lib/gitlab/gitaly_client/remote_service.rb
@@ -11,9 +11,9 @@ module Gitlab
request = Gitaly::FindRemoteRepositoryRequest.new(remote: remote_url)
response = GitalyClient.call(GitalyClient.random_storage,
- :remote_service,
- :find_remote_repository, request,
- timeout: GitalyClient.medium_timeout)
+ :remote_service,
+ :find_remote_repository, request,
+ timeout: GitalyClient.medium_timeout)
response.exists
end
@@ -50,8 +50,8 @@ module Gitlab
)
response = GitalyClient.call(@storage, :remote_service,
- :fetch_internal_remote, request,
- remote_storage: repository.storage)
+ :fetch_internal_remote, request,
+ remote_storage: repository.storage)
response.result
end
@@ -63,13 +63,13 @@ module Gitlab
)
response = GitalyClient.call(@storage, :remote_service,
- :find_remote_root_ref, request)
+ :find_remote_root_ref, request)
encode_utf8(response.ref)
end
def update_remote_mirror(ref_name, only_branches_matching, ssh_key: nil, known_hosts: nil)
- req_enum = Enumerator.new do |y|
+ req_enum = Enumerator.new { |y|
first_request = Gitaly::UpdateRemoteMirrorRequest.new(
repository: @gitaly_repo,
ref_name: ref_name
@@ -82,18 +82,18 @@ module Gitlab
current_size = 0
- slices = only_branches_matching.slice_before do |branch_name|
+ slices = only_branches_matching.slice_before { |branch_name|
current_size += branch_name.bytesize
next false if current_size < MAX_MSG_SIZE
current_size = 0
- end
+ }
slices.each do |slice|
y.yield Gitaly::UpdateRemoteMirrorRequest.new(only_branches_matching: slice)
end
- end
+ }
GitalyClient.call(@storage, :remote_service, :update_remote_mirror, req_enum)
end
diff --git a/lib/gitlab/gitaly_client/repository_service.rb b/lib/gitlab/gitaly_client/repository_service.rb
index a7e20d9429e..2376ecf952c 100644
--- a/lib/gitlab/gitaly_client/repository_service.rb
+++ b/lib/gitlab/gitaly_client/repository_service.rb
@@ -58,9 +58,9 @@ module Gitlab
request = Gitaly::GetInfoAttributesRequest.new(repository: @gitaly_repo)
response = GitalyClient.call(@storage, :repository_service, :get_info_attributes, request, timeout: GitalyClient.fast_timeout)
- response.each_with_object([]) do |message, attributes|
+ response.each_with_object([]) { |message, attributes|
attributes << message.attributes
- end.join
+ }.join
end
def fetch_remote(remote, ssh_auth:, forced:, no_tags:, timeout:, prune: true)
@@ -368,7 +368,7 @@ module Gitlab
timeout: timeout
)
- File.open(save_path, 'wb') do |f|
+ File.open(save_path, "wb") do |f|
response.each do |message|
f.write(message.data)
end
@@ -379,8 +379,8 @@ module Gitlab
def gitaly_repo_stream_request(file_path, rpc_name, request_class, timeout)
request = request_class.new(repository: @gitaly_repo)
- enum = Enumerator.new do |y|
- File.open(file_path, 'rb') do |f|
+ enum = Enumerator.new { |y|
+ File.open(file_path, "rb") do |f|
while data = f.read(MAX_MSG_SIZE)
request.data = data
@@ -388,7 +388,7 @@ module Gitlab
request = request_class.new
end
end
- end
+ }
GitalyClient.call(
@storage,
diff --git a/lib/gitlab/gitaly_client/storage_settings.rb b/lib/gitlab/gitaly_client/storage_settings.rb
index 754cccb6b3f..d047f64ebc3 100644
--- a/lib/gitlab/gitaly_client/storage_settings.rb
+++ b/lib/gitlab/gitaly_client/storage_settings.rb
@@ -11,7 +11,7 @@ module Gitlab
DirectPathAccessError = Class.new(StandardError)
InvalidConfigurationError = Class.new(StandardError)
- INVALID_STORAGE_MESSAGE = <<~MSG.freeze
+ INVALID_STORAGE_MESSAGE = <<~MSG
Storage is invalid because it has no `path` key.
For source installations, update your config/gitlab.yml Refer to gitlab.yml.example for an updated example.
@@ -39,12 +39,12 @@ module Gitlab
def initialize(storage)
raise InvalidConfigurationError, "expected a Hash, got a #{storage.class.name}" unless storage.is_a?(Hash)
- raise InvalidConfigurationError, INVALID_STORAGE_MESSAGE unless storage.has_key?('path')
+ raise InvalidConfigurationError, INVALID_STORAGE_MESSAGE unless storage.key?("path")
# Support a nil 'path' field because some of the circuit breaker tests use it.
- @legacy_disk_path = File.expand_path(storage['path'], Rails.root) if storage['path']
+ @legacy_disk_path = File.expand_path(storage["path"], Rails.root) if storage["path"]
- storage['path'] = Deprecated
+ storage["path"] = Deprecated
@hash = storage
end
diff --git a/lib/gitlab/gitaly_client/util.rb b/lib/gitlab/gitaly_client/util.rb
index 899921f76e4..96938acfc37 100644
--- a/lib/gitlab/gitaly_client/util.rb
+++ b/lib/gitlab/gitaly_client/util.rb
@@ -6,8 +6,8 @@ module Gitlab
class << self
def repository(repository_storage, relative_path, gl_repository, gl_project_path)
git_env = Gitlab::Git::HookEnv.all(gl_repository)
- git_object_directory = git_env['GIT_OBJECT_DIRECTORY_RELATIVE'].presence
- git_alternate_object_directories = Array.wrap(git_env['GIT_ALTERNATE_OBJECT_DIRECTORIES_RELATIVE'])
+ git_object_directory = git_env["GIT_OBJECT_DIRECTORY_RELATIVE"].presence
+ git_alternate_object_directories = Array.wrap(git_env["GIT_ALTERNATE_OBJECT_DIRECTORIES_RELATIVE"])
Gitaly::Repository.new(
storage_name: repository_storage,
@@ -21,9 +21,9 @@ module Gitlab
def git_repository(gitaly_repository)
Gitlab::Git::Repository.new(gitaly_repository.storage_name,
- gitaly_repository.relative_path,
- gitaly_repository.gl_repository,
- gitaly_repository.gl_project_path)
+ gitaly_repository.relative_path,
+ gitaly_repository.gl_repository,
+ gitaly_repository.gl_project_path)
end
end
end
diff --git a/lib/gitlab/gitaly_client/wiki_file.rb b/lib/gitlab/gitaly_client/wiki_file.rb
index ef2b23732d1..6b72e604870 100644
--- a/lib/gitlab/gitaly_client/wiki_file.rb
+++ b/lib/gitlab/gitaly_client/wiki_file.rb
@@ -3,7 +3,7 @@
module Gitlab
module GitalyClient
class WikiFile
- ATTRS = %i(name mime_type path raw_data).freeze
+ ATTRS = %i[name mime_type path raw_data].freeze
include AttributesBag
end
diff --git a/lib/gitlab/gitaly_client/wiki_page.rb b/lib/gitlab/gitaly_client/wiki_page.rb
index 757a429fb8a..f6ea2c96bbb 100644
--- a/lib/gitlab/gitaly_client/wiki_page.rb
+++ b/lib/gitlab/gitaly_client/wiki_page.rb
@@ -3,7 +3,7 @@
module Gitlab
module GitalyClient
class WikiPage
- ATTRS = %i(title format url_path path name historical raw_data).freeze
+ ATTRS = %i[title format url_path path name historical raw_data].freeze
include AttributesBag
include Gitlab::EncodingHelper
diff --git a/lib/gitlab/gitaly_client/wiki_service.rb b/lib/gitlab/gitaly_client/wiki_service.rb
index 2b3d622af4d..cf016d0e399 100644
--- a/lib/gitlab/gitaly_client/wiki_service.rb
+++ b/lib/gitlab/gitaly_client/wiki_service.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'stringio'
+require "stringio"
module Gitlab
module GitalyClient
@@ -24,7 +24,7 @@ module Gitlab
strio = binary_stringio(content)
- enum = Enumerator.new do |y|
+ enum = Enumerator.new { |y|
until strio.eof?
request.content = strio.read(MAX_MSG_SIZE)
@@ -32,7 +32,7 @@ module Gitlab
request = Gitaly::WikiWritePageRequest.new
end
- end
+ }
response = GitalyClient.call(@repository.storage, :wiki_service, :wiki_write_page, enum)
if error = response.duplicate_error.presence
@@ -51,7 +51,7 @@ module Gitlab
strio = binary_stringio(content)
- enum = Enumerator.new do |y|
+ enum = Enumerator.new { |y|
until strio.eof?
request.content = strio.read(MAX_MSG_SIZE)
@@ -59,7 +59,7 @@ module Gitlab
request = Gitaly::WikiUpdatePageRequest.new
end
- end
+ }
GitalyClient.call(@repository.storage, :wiki_service, :wiki_update_page, enum)
end
diff --git a/lib/gitlab/github_import.rb b/lib/gitlab/github_import.rb
index 14a6d6443ec..63a5df50997 100644
--- a/lib/gitlab/github_import.rb
+++ b/lib/gitlab/github_import.rb
@@ -3,7 +3,7 @@
module Gitlab
module GithubImport
def self.refmap
- [:heads, :tags, '+refs/pull/*/head:refs/merge-requests/*/head']
+ [:heads, :tags, "+refs/pull/*/head:refs/merge-requests/*/head"]
end
def self.new_client_for(project, token: nil, parallel: true)
@@ -14,7 +14,7 @@ module Gitlab
# Returns the ID of the ghost user.
def self.ghost_user_id
- key = 'github-import/ghost-user-id'
+ key = "github-import/ghost-user-id"
Caching.read_integer(key) || Caching.write(key, User.select(:id).ghost.id)
end
diff --git a/lib/gitlab/github_import/caching.rb b/lib/gitlab/github_import/caching.rb
index b08f133794f..b789641e1d9 100644
--- a/lib/gitlab/github_import/caching.rb
+++ b/lib/gitlab/github_import/caching.rb
@@ -135,10 +135,10 @@ module Gitlab
# Returns true when the key was overwritten, false otherwise.
def self.write_if_greater(raw_key, value, timeout: TIMEOUT)
key = cache_key_for(raw_key)
- val = Redis::Cache.with do |redis|
+ val = Redis::Cache.with { |redis|
redis
.eval(WRITE_IF_GREATER_SCRIPT, keys: [key], argv: [value, timeout])
- end
+ }
val ? true : false
end
diff --git a/lib/gitlab/github_import/client.rb b/lib/gitlab/github_import/client.rb
index a61beafae0d..c5db56a3bf3 100644
--- a/lib/gitlab/github_import/client.rb
+++ b/lib/gitlab/github_import/client.rb
@@ -46,7 +46,7 @@ module Gitlab
api_endpoint: api_endpoint
)
- @octokit.connection_options[:ssl] = { verify: verify_ssl }
+ @octokit.connection_options[:ssl] = {verify: verify_ssl}
@parallel = parallel
end
@@ -176,7 +176,7 @@ module Gitlab
def rate_limiting_enabled?
strong_memoize(:rate_limiting_enabled) do
- api_endpoint.include?('.github.com')
+ api_endpoint.include?(".github.com")
end
end
@@ -185,7 +185,7 @@ module Gitlab
end
def custom_api_endpoint
- github_omniauth_provider.dig('args', 'client_options', 'site')
+ github_omniauth_provider.dig("args", "client_options", "site")
end
def default_api_endpoint
@@ -193,24 +193,24 @@ module Gitlab
end
def verify_ssl
- github_omniauth_provider.fetch('verify_ssl', true)
+ github_omniauth_provider.fetch("verify_ssl", true)
end
def github_omniauth_provider
- @github_omniauth_provider ||= Gitlab::Auth::OAuth::Provider.config_for('github').to_h
+ @github_omniauth_provider ||= Gitlab::Auth::OAuth::Provider.config_for("github").to_h
end
def rate_limit_counter
@rate_limit_counter ||= Gitlab::Metrics.counter(
:github_importer_rate_limit_hits,
- 'The number of times we hit the GitHub rate limit when importing projects'
+ "The number of times we hit the GitHub rate limit when importing projects"
)
end
def request_count_counter
@request_counter ||= Gitlab::Metrics.counter(
:github_importer_request_count,
- 'The number of GitHub API calls performed when importing projects'
+ "The number of GitHub API calls performed when importing projects"
)
end
end
diff --git a/lib/gitlab/github_import/importer/diff_note_importer.rb b/lib/gitlab/github_import/importer/diff_note_importer.rb
index d562958e955..b6081401368 100644
--- a/lib/gitlab/github_import/importer/diff_note_importer.rb
+++ b/lib/gitlab/github_import/importer/diff_note_importer.rb
@@ -25,7 +25,7 @@ module Gitlab
MarkdownText.format(note.note, note.author, author_found)
attributes = {
- noteable_type: 'MergeRequest',
+ noteable_type: "MergeRequest",
noteable_id: mr_id,
project_id: project.id,
author_id: author_id,
@@ -33,10 +33,10 @@ module Gitlab
system: false,
commit_id: note.commit_id,
line_code: note.line_code,
- type: 'LegacyDiffNote',
+ type: "LegacyDiffNote",
created_at: note.created_at,
updated_at: note.updated_at,
- st_diff: note.diff_hash.to_yaml
+ st_diff: note.diff_hash.to_yaml,
}
# It's possible that during an import we'll insert tens of thousands
diff --git a/lib/gitlab/github_import/importer/issue_importer.rb b/lib/gitlab/github_import/importer/issue_importer.rb
index 656d46b6a7d..1a98be6153d 100644
--- a/lib/gitlab/github_import/importer/issue_importer.rb
+++ b/lib/gitlab/github_import/importer/issue_importer.rb
@@ -7,7 +7,7 @@ module Gitlab
include Gitlab::Import::DatabaseHelpers
attr_reader :project, :issue, :client, :user_finder, :milestone_finder,
- :issuable_finder
+ :issuable_finder
# Imports an issue if it's a regular issue and not a pull request.
def self.import_if_issue(issue, project, client)
@@ -54,7 +54,7 @@ module Gitlab
milestone_id: milestone_finder.id_for(issue),
state: issue.state,
created_at: issue.created_at,
- updated_at: issue.updated_at
+ updated_at: issue.updated_at,
}
insert_and_return_id(attributes, project.issues)
@@ -71,7 +71,7 @@ module Gitlab
issue.assignees.each do |assignee|
if (user_id = user_finder.user_id_for(assignee))
- assignees << { issue_id: issue_id, user_id: user_id }
+ assignees << {issue_id: issue_id, user_id: user_id}
end
end
diff --git a/lib/gitlab/github_import/importer/issues_importer.rb b/lib/gitlab/github_import/importer/issues_importer.rb
index ac6d0666b3a..f35d3d27f92 100644
--- a/lib/gitlab/github_import/importer/issues_importer.rb
+++ b/lib/gitlab/github_import/importer/issues_importer.rb
@@ -27,7 +27,7 @@ module Gitlab
end
def collection_options
- { state: 'all', sort: 'created', direction: 'asc' }
+ {state: "all", sort: "created", direction: "asc"}
end
end
end
diff --git a/lib/gitlab/github_import/importer/label_links_importer.rb b/lib/gitlab/github_import/importer/label_links_importer.rb
index 2001b7e3482..164c94bc24f 100644
--- a/lib/gitlab/github_import/importer/label_links_importer.rb
+++ b/lib/gitlab/github_import/importer/label_links_importer.rb
@@ -36,7 +36,7 @@ module Gitlab
target_id: target_id,
target_type: issue.issuable_type,
created_at: time,
- updated_at: time
+ updated_at: time,
}
end
diff --git a/lib/gitlab/github_import/importer/labels_importer.rb b/lib/gitlab/github_import/importer/labels_importer.rb
index 80246fa1b77..342bb82d7fa 100644
--- a/lib/gitlab/github_import/importer/labels_importer.rb
+++ b/lib/gitlab/github_import/importer/labels_importer.rb
@@ -40,11 +40,11 @@ module Gitlab
{
title: label.name,
- color: '#' + label.color,
+ color: "#" + label.color,
project_id: project.id,
- type: 'ProjectLabel',
+ type: "ProjectLabel",
created_at: time,
- updated_at: time
+ updated_at: time,
}
end
diff --git a/lib/gitlab/github_import/importer/lfs_objects_importer.rb b/lib/gitlab/github_import/importer/lfs_objects_importer.rb
index 6046e30d4ef..1f8d80d2bec 100644
--- a/lib/gitlab/github_import/importer/lfs_objects_importer.rb
+++ b/lib/gitlab/github_import/importer/lfs_objects_importer.rb
@@ -28,7 +28,7 @@ module Gitlab
lfs_objects.each do |object|
yield object
end
- rescue StandardError => e
+ rescue => e
Rails.logger.error("The Lfs import process failed. #{e.message}")
end
end
diff --git a/lib/gitlab/github_import/importer/milestones_importer.rb b/lib/gitlab/github_import/importer/milestones_importer.rb
index 87cf2c8b598..fc75c397b1a 100644
--- a/lib/gitlab/github_import/importer/milestones_importer.rb
+++ b/lib/gitlab/github_import/importer/milestones_importer.rb
@@ -43,16 +43,16 @@ module Gitlab
project_id: project.id,
state: state_for(milestone),
created_at: milestone.created_at,
- updated_at: milestone.updated_at
+ updated_at: milestone.updated_at,
}
end
def state_for(milestone)
- milestone.state == 'open' ? :active : :closed
+ milestone.state == "open" ? :active : :closed
end
def each_milestone
- client.milestones(project.import_source, state: 'all')
+ client.milestones(project.import_source, state: "all")
end
end
end
diff --git a/lib/gitlab/github_import/importer/note_importer.rb b/lib/gitlab/github_import/importer/note_importer.rb
index 2b06d1b3baf..c0875a47d0e 100644
--- a/lib/gitlab/github_import/importer/note_importer.rb
+++ b/lib/gitlab/github_import/importer/note_importer.rb
@@ -32,7 +32,7 @@ module Gitlab
note: note_body,
system: false,
created_at: note.created_at,
- updated_at: note.updated_at
+ updated_at: note.updated_at,
}
# We're using bulk_insert here so we can bypass any validations and
diff --git a/lib/gitlab/github_import/importer/pull_request_importer.rb b/lib/gitlab/github_import/importer/pull_request_importer.rb
index e294173f992..2ffc51840cc 100644
--- a/lib/gitlab/github_import/importer/pull_request_importer.rb
+++ b/lib/gitlab/github_import/importer/pull_request_importer.rb
@@ -7,7 +7,7 @@ module Gitlab
include Gitlab::Import::MergeRequestHelpers
attr_reader :pull_request, :project, :client, :user_finder,
- :milestone_finder, :issuable_finder
+ :milestone_finder, :issuable_finder
# pull_request - An instance of
# `Gitlab::GithubImport::Representation::PullRequest`.
@@ -59,7 +59,7 @@ module Gitlab
author_id: author_id,
assignee_id: user_finder.assignee_id_for(pull_request),
created_at: pull_request.created_at,
- updated_at: pull_request.updated_at
+ updated_at: pull_request.updated_at,
}
create_merge_request_without_hooks(project, attributes, pull_request.iid)
@@ -92,11 +92,11 @@ module Gitlab
project.repository.add_branch(merge_request.author, source_branch, pull_request.source_branch_sha)
rescue Gitlab::Git::CommandError => e
Gitlab::Sentry.track_acceptable_exception(e,
- extra: {
- source_branch: source_branch,
- project_id: merge_request.project.id,
- merge_request_id: merge_request.id
- })
+ extra: {
+ source_branch: source_branch,
+ project_id: merge_request.project.id,
+ merge_request_id: merge_request.id,
+ })
end
end
end
diff --git a/lib/gitlab/github_import/importer/pull_requests_importer.rb b/lib/gitlab/github_import/importer/pull_requests_importer.rb
index a52866c4b08..842d1dc371f 100644
--- a/lib/gitlab/github_import/importer/pull_requests_importer.rb
+++ b/lib/gitlab/github_import/importer/pull_requests_importer.rb
@@ -36,7 +36,7 @@ module Gitlab
# updating the timestamp.
project.update_column(:last_repository_updated_at, Time.zone.now)
- project.repository.fetch_remote('github', forced: false)
+ project.repository.fetch_remote("github", forced: false)
pname = project.path_with_namespace
@@ -65,13 +65,13 @@ module Gitlab
end
def collection_options
- { state: 'all', sort: 'created', direction: 'asc' }
+ {state: "all", sort: "created", direction: "asc"}
end
def repository_updates_counter
@repository_updates_counter ||= Gitlab::Metrics.counter(
:github_importer_repository_updates,
- 'The number of times repositories have to be updated again'
+ "The number of times repositories have to be updated again"
)
end
end
diff --git a/lib/gitlab/github_import/importer/releases_importer.rb b/lib/gitlab/github_import/importer/releases_importer.rb
index 0e7c9ee0d00..4d6faf055b0 100644
--- a/lib/gitlab/github_import/importer/releases_importer.rb
+++ b/lib/gitlab/github_import/importer/releases_importer.rb
@@ -36,7 +36,7 @@ module Gitlab
description: description_for(release),
created_at: release.created_at,
updated_at: release.updated_at,
- project_id: project.id
+ project_id: project.id,
}
end
diff --git a/lib/gitlab/github_import/importer/repository_importer.rb b/lib/gitlab/github_import/importer/repository_importer.rb
index e2dfb00dcc5..02b803e6742 100644
--- a/lib/gitlab/github_import/importer/repository_importer.rb
+++ b/lib/gitlab/github_import/importer/repository_importer.rb
@@ -50,7 +50,7 @@ module Gitlab
project.ensure_repository
refmap = Gitlab::GithubImport.refmap
- project.repository.fetch_as_mirror(project.import_url, refmap: refmap, forced: true, remote_name: 'github')
+ project.repository.fetch_as_mirror(project.import_url, refmap: refmap, forced: true, remote_name: "github")
true
rescue Gitlab::Git::Repository::NoRepository, Gitlab::Shell::Error => e
@@ -62,7 +62,7 @@ module Gitlab
true
rescue Gitlab::Shell::Error => e
- if e.message !~ /repository not exported/
+ if !/repository not exported/.match?(e.message)
project.create_wiki
fail_import("Failed to import the wiki: #{e.message}")
else
diff --git a/lib/gitlab/github_import/issuable_finder.rb b/lib/gitlab/github_import/issuable_finder.rb
index 211915f1d87..8ed783dc8ce 100644
--- a/lib/gitlab/github_import/issuable_finder.rb
+++ b/lib/gitlab/github_import/issuable_finder.rb
@@ -10,7 +10,7 @@ module Gitlab
attr_reader :project, :object
# The base cache key to use for storing/retrieving issuable IDs.
- CACHE_KEY = 'github-import/issuable-finder/%{project}/%{type}/%{iid}'.freeze
+ CACHE_KEY = "github-import/issuable-finder/%{project}/%{type}/%{iid}"
# project - An instance of `Project`.
# object - The object to look up or set a database ID for.
@@ -41,7 +41,7 @@ module Gitlab
CACHE_KEY % {
project: project.id,
type: cache_key_type,
- iid: cache_key_iid
+ iid: cache_key_iid,
}
end
diff --git a/lib/gitlab/github_import/label_finder.rb b/lib/gitlab/github_import/label_finder.rb
index d2479a8f565..c0280e7f51a 100644
--- a/lib/gitlab/github_import/label_finder.rb
+++ b/lib/gitlab/github_import/label_finder.rb
@@ -6,7 +6,7 @@ module Gitlab
attr_reader :project
# The base cache key to use for storing/retrieving label IDs.
- CACHE_KEY = 'github-import/label-finder/%{project}/%{name}'.freeze
+ CACHE_KEY = "github-import/label-finder/%{project}/%{name}"
# project - An instance of `Project`.
def initialize(project)
@@ -23,16 +23,16 @@ module Gitlab
mapping = @project
.labels
.pluck(:id, :name)
- .each_with_object({}) do |(id, name), hash|
+ .each_with_object({}) { |(id, name), hash|
hash[cache_key_for(name)] = id
- end
+ }
Caching.write_multiple(mapping)
end
# rubocop: enable CodeReuse/ActiveRecord
def cache_key_for(name)
- CACHE_KEY % { project: project.id, name: name }
+ CACHE_KEY % {project: project.id, name: name}
end
end
end
diff --git a/lib/gitlab/github_import/milestone_finder.rb b/lib/gitlab/github_import/milestone_finder.rb
index 5625730e796..7f9de146f4e 100644
--- a/lib/gitlab/github_import/milestone_finder.rb
+++ b/lib/gitlab/github_import/milestone_finder.rb
@@ -6,7 +6,7 @@ module Gitlab
attr_reader :project
# The base cache key to use for storing/retrieving milestone IDs.
- CACHE_KEY = 'github-import/milestone-finder/%{project}/%{iid}'.freeze
+ CACHE_KEY = "github-import/milestone-finder/%{project}/%{iid}"
# project - An instance of `Project`
def initialize(project)
@@ -26,16 +26,16 @@ module Gitlab
mapping = @project
.milestones
.pluck(:id, :iid)
- .each_with_object({}) do |(id, iid), hash|
+ .each_with_object({}) { |(id, iid), hash|
hash[cache_key_for(iid)] = id
- end
+ }
Caching.write_multiple(mapping)
end
# rubocop: enable CodeReuse/ActiveRecord
def cache_key_for(iid)
- CACHE_KEY % { project: project.id, iid: iid }
+ CACHE_KEY % {project: project.id, iid: iid}
end
end
end
diff --git a/lib/gitlab/github_import/page_counter.rb b/lib/gitlab/github_import/page_counter.rb
index c3db2d0b469..e342ddeff3e 100644
--- a/lib/gitlab/github_import/page_counter.rb
+++ b/lib/gitlab/github_import/page_counter.rb
@@ -9,10 +9,10 @@ module Gitlab
attr_reader :cache_key
# The base cache key to use for storing the last page number.
- CACHE_KEY = 'github-importer/page-counter/%{project}/%{collection}'.freeze
+ CACHE_KEY = "github-importer/page-counter/%{project}/%{collection}"
def initialize(project, collection)
- @cache_key = CACHE_KEY % { project: project.id, collection: collection }
+ @cache_key = CACHE_KEY % {project: project.id, collection: collection}
end
# Sets the page number to the given value.
diff --git a/lib/gitlab/github_import/parallel_scheduling.rb b/lib/gitlab/github_import/parallel_scheduling.rb
index d4d1357f5a3..aef37a6996b 100644
--- a/lib/gitlab/github_import/parallel_scheduling.rb
+++ b/lib/gitlab/github_import/parallel_scheduling.rb
@@ -7,7 +7,7 @@ module Gitlab
# The base cache key to use for tracking already imported objects.
ALREADY_IMPORTED_CACHE_KEY =
- 'github-importer/already-imported/%{project}/%{collection}'.freeze
+ "github-importer/already-imported/%{project}/%{collection}"
# project - An instance of `Project`.
# client - An instance of `Gitlab::GithubImport::Client`.
@@ -18,7 +18,7 @@ module Gitlab
@parallel = parallel
@page_counter = PageCounter.new(project, collection_method)
@already_imported_cache_key = ALREADY_IMPORTED_CACHE_KEY %
- { project: project.id, collection: collection_method }
+ {project: project.id, collection: collection_method}
end
def parallel?
diff --git a/lib/gitlab/github_import/representation/diff_note.rb b/lib/gitlab/github_import/representation/diff_note.rb
index be1334ca98a..0675bb359fc 100644
--- a/lib/gitlab/github_import/representation/diff_note.rb
+++ b/lib/gitlab/github_import/representation/diff_note.rb
@@ -10,8 +10,8 @@ module Gitlab
attr_reader :attributes
expose_attribute :noteable_type, :noteable_id, :commit_id, :file_path,
- :diff_hunk, :author, :note, :created_at, :updated_at,
- :github_id
+ :diff_hunk, :author, :note, :created_at, :updated_at,
+ :github_id
NOTEABLE_ID_REGEX = %r{/pull/(?<iid>\d+)}i
@@ -30,7 +30,7 @@ module Gitlab
user = Representation::User.from_api_response(note.user) if note.user
hash = {
- noteable_type: 'MergeRequest',
+ noteable_type: "MergeRequest",
noteable_id: matches[:iid].to_i,
file_path: note.path,
commit_id: note.commit_id,
@@ -39,7 +39,7 @@ module Gitlab
note: note.body,
created_at: note.created_at,
updated_at: note.updated_at,
- github_id: note.id
+ github_id: note.id,
}
new(hash)
@@ -76,9 +76,9 @@ module Gitlab
# These fields are not displayed for LegacyDiffNote notes, so it
# doesn't really matter what we set them to.
- a_mode: '100644',
- b_mode: '100644',
- new_file: false
+ a_mode: "100644",
+ b_mode: "100644",
+ new_file: false,
}
end
end
diff --git a/lib/gitlab/github_import/representation/issue.rb b/lib/gitlab/github_import/representation/issue.rb
index f3071b3e2b3..ac95ecdefdc 100644
--- a/lib/gitlab/github_import/representation/issue.rb
+++ b/lib/gitlab/github_import/representation/issue.rb
@@ -10,8 +10,8 @@ module Gitlab
attr_reader :attributes
expose_attribute :iid, :title, :description, :milestone_number,
- :created_at, :updated_at, :state, :assignees,
- :label_names, :author
+ :created_at, :updated_at, :state, :assignees,
+ :label_names, :author
# Builds an issue from a GitHub API response.
#
@@ -28,7 +28,7 @@ module Gitlab
title: issue.title,
description: issue.body,
milestone_number: issue.milestone&.number,
- state: issue.state == 'open' ? :opened : :closed,
+ state: issue.state == "open" ? :opened : :closed,
assignees: issue.assignees.map do |u|
Representation::User.from_api_response(u)
end,
@@ -36,7 +36,7 @@ module Gitlab
author: user,
created_at: issue.created_at,
updated_at: issue.updated_at,
- pull_request: issue.pull_request ? true : false
+ pull_request: issue.pull_request ? true : false,
}
new(hash)
@@ -64,7 +64,7 @@ module Gitlab
end
def labels?
- label_names && label_names.any?
+ label_names&.any?
end
def pull_request?
@@ -72,7 +72,7 @@ module Gitlab
end
def issuable_type
- pull_request? ? 'MergeRequest' : 'Issue'
+ pull_request? ? "MergeRequest" : "Issue"
end
end
end
diff --git a/lib/gitlab/github_import/representation/lfs_object.rb b/lib/gitlab/github_import/representation/lfs_object.rb
index a4606173f49..b1256418c24 100644
--- a/lib/gitlab/github_import/representation/lfs_object.rb
+++ b/lib/gitlab/github_import/representation/lfs_object.rb
@@ -13,7 +13,7 @@ module Gitlab
# Builds a lfs_object
def self.from_api_response(lfs_object)
- new({ oid: lfs_object.oid, link: lfs_object.link, size: lfs_object.size })
+ new({oid: lfs_object.oid, link: lfs_object.link, size: lfs_object.size})
end
# Builds a new lfs_object using a Hash that was built from a JSON payload.
diff --git a/lib/gitlab/github_import/representation/note.rb b/lib/gitlab/github_import/representation/note.rb
index 070e3b2db8d..53ecd268d77 100644
--- a/lib/gitlab/github_import/representation/note.rb
+++ b/lib/gitlab/github_import/representation/note.rb
@@ -10,7 +10,7 @@ module Gitlab
attr_reader :attributes
expose_attribute :noteable_id, :noteable_type, :author, :note,
- :created_at, :updated_at, :github_id
+ :created_at, :updated_at, :github_id
NOTEABLE_TYPE_REGEX = %r{/(?<type>(pull|issues))/(?<iid>\d+)}i
@@ -28,10 +28,10 @@ module Gitlab
end
noteable_type =
- if matches[:type] == 'pull'
- 'MergeRequest'
+ if matches[:type] == "pull"
+ "MergeRequest"
else
- 'Issue'
+ "Issue"
end
user = Representation::User.from_api_response(note.user) if note.user
@@ -42,7 +42,7 @@ module Gitlab
note: note.body,
created_at: note.created_at,
updated_at: note.updated_at,
- github_id: note.id
+ github_id: note.id,
}
new(hash)
@@ -63,7 +63,7 @@ module Gitlab
@attributes = attributes
end
- alias_method :issuable_type, :noteable_type
+ alias issuable_type noteable_type
end
end
end
diff --git a/lib/gitlab/github_import/representation/pull_request.rb b/lib/gitlab/github_import/representation/pull_request.rb
index 0ccc4bfaed3..7067b59f2f2 100644
--- a/lib/gitlab/github_import/representation/pull_request.rb
+++ b/lib/gitlab/github_import/representation/pull_request.rb
@@ -10,10 +10,10 @@ module Gitlab
attr_reader :attributes
expose_attribute :iid, :title, :description, :source_branch,
- :source_branch_sha, :target_branch, :target_branch_sha,
- :milestone_number, :author, :assignee, :created_at,
- :updated_at, :merged_at, :source_repository_id,
- :target_repository_id, :source_repository_owner
+ :source_branch_sha, :target_branch, :target_branch_sha,
+ :milestone_number, :author, :assignee, :created_at,
+ :updated_at, :merged_at, :source_repository_id,
+ :target_repository_id, :source_repository_owner
# Builds a PR from a GitHub API response.
#
@@ -36,13 +36,13 @@ module Gitlab
source_repository_id: pr.head&.repo&.id,
target_repository_id: pr.base&.repo&.id,
source_repository_owner: pr.head&.user&.login,
- state: pr.state == 'open' ? :opened : :closed,
+ state: pr.state == "open" ? :opened : :closed,
milestone_number: pr.milestone&.number,
author: user,
assignee: assignee,
created_at: pr.created_at,
updated_at: pr.updated_at,
- merged_at: pr.merged_at
+ merged_at: pr.merged_at,
}
new(hash)
@@ -106,7 +106,7 @@ module Gitlab
end
def issuable_type
- 'MergeRequest'
+ "MergeRequest"
end
end
end
diff --git a/lib/gitlab/github_import/sequential_importer.rb b/lib/gitlab/github_import/sequential_importer.rb
index 6a181caf65d..97394f1e779 100644
--- a/lib/gitlab/github_import/sequential_importer.rb
+++ b/lib/gitlab/github_import/sequential_importer.rb
@@ -12,7 +12,7 @@ module Gitlab
SEQUENTIAL_IMPORTERS = [
Importer::LabelsImporter,
Importer::MilestonesImporter,
- Importer::ReleasesImporter
+ Importer::ReleasesImporter,
].freeze
PARALLEL_IMPORTERS = [
@@ -20,7 +20,7 @@ module Gitlab
Importer::IssuesImporter,
Importer::DiffNotesImporter,
Importer::NotesImporter,
- Importer::LfsObjectsImporter
+ Importer::LfsObjectsImporter,
].freeze
# project - The project to import the data into.
diff --git a/lib/gitlab/github_import/user_finder.rb b/lib/gitlab/github_import/user_finder.rb
index 30283f147ef..36416f8db32 100644
--- a/lib/gitlab/github_import/user_finder.rb
+++ b/lib/gitlab/github_import/user_finder.rb
@@ -16,17 +16,17 @@ module Gitlab
# The base cache key to use for caching user IDs for a given GitHub user
# ID.
- ID_CACHE_KEY = 'github-import/user-finder/user-id/%s'.freeze
+ ID_CACHE_KEY = "github-import/user-finder/user-id/%s"
# The base cache key to use for caching user IDs for a given GitHub email
# address.
ID_FOR_EMAIL_CACHE_KEY =
- 'github-import/user-finder/id-for-email/%s'.freeze
+ "github-import/user-finder/id-for-email/%s"
# The base cache key to use for caching the Email addresses of GitHub
# usernames.
EMAIL_FOR_USERNAME_CACHE_KEY =
- 'github-import/user-finder/email-for-username/%s'.freeze
+ "github-import/user-finder/email-for-username/%s"
# project - An instance of `Project`
# client - An instance of `Gitlab::GithubImport::Client`
diff --git a/lib/gitlab/gitlab_import/client.rb b/lib/gitlab/gitlab_import/client.rb
index 86474159f8b..d45aa65c4ec 100644
--- a/lib/gitlab/gitlab_import/client.rb
+++ b/lib/gitlab/gitlab_import/client.rb
@@ -22,7 +22,7 @@ module Gitlab
def authorize_url(redirect_uri)
client.auth_code.authorize_url({
redirect_uri: redirect_uri,
- scope: "api"
+ scope: "api",
})
end
@@ -78,7 +78,7 @@ module Gitlab
end
def config
- Gitlab::Auth::OAuth::Provider.config_for('gitlab')
+ Gitlab::Auth::OAuth::Provider.config_for("gitlab")
end
def gitlab_options
diff --git a/lib/gitlab/gitlab_import/importer.rb b/lib/gitlab/gitlab_import/importer.rb
index e84863deba8..8281eebb96e 100644
--- a/lib/gitlab/gitlab_import/importer.rb
+++ b/lib/gitlab/gitlab_import/importer.rb
@@ -8,7 +8,7 @@ module Gitlab
def initialize(project)
@project = project
import_data = project.import_data
- if import_data && import_data.credentials && import_data.credentials[:password]
+ if import_data&.credentials && import_data.credentials[:password]
@client = Client.new(import_data.credentials[:password])
@formatter = Gitlab::ImportFormatter.new
else
@@ -57,7 +57,7 @@ module Gitlab
# rubocop: disable CodeReuse/ActiveRecord
def gitlab_user_id(project, gitlab_id)
user = User.joins(:identities).find_by("identities.extern_uid = ? AND identities.provider = 'gitlab'", gitlab_id.to_s)
- (user && user.id) || project.creator_id
+ (user&.id) || project.creator_id
end
# rubocop: enable CodeReuse/ActiveRecord
end
diff --git a/lib/gitlab/gl_id.rb b/lib/gitlab/gl_id.rb
index 1ed842c2264..b15fb132d72 100644
--- a/lib/gitlab/gl_id.rb
+++ b/lib/gitlab/gl_id.rb
@@ -6,7 +6,7 @@ module Gitlab
if user.present?
gl_id_from_id_value(user.id)
else
- ''
+ ""
end
end
diff --git a/lib/gitlab/gl_repository.rb b/lib/gitlab/gl_repository.rb
index 435b74806e7..d6b97745211 100644
--- a/lib/gitlab/gl_repository.rb
+++ b/lib/gitlab/gl_repository.rb
@@ -3,7 +3,7 @@
module Gitlab
module GlRepository
def self.gl_repository(project, is_wiki)
- "#{is_wiki ? 'wiki' : 'project'}-#{project.id}"
+ "#{is_wiki ? "wiki" : "project"}-#{project.id}"
end
# rubocop: disable CodeReuse/ActiveRecord
@@ -15,7 +15,7 @@ module Gitlab
type, id = match_data.captures
project = Project.find_by(id: id)
- wiki = type == 'wiki'
+ wiki = type == "wiki"
[project, wiki]
end
diff --git a/lib/gitlab/gon_helper.rb b/lib/gitlab/gon_helper.rb
index 3235d3ccc4e..ffe80c36eed 100644
--- a/lib/gitlab/gon_helper.rb
+++ b/lib/gitlab/gon_helper.rb
@@ -7,21 +7,21 @@ module Gitlab
include WebpackHelper
def add_gon_variables
- gon.api_version = 'v4'
+ gon.api_version = "v4"
gon.default_avatar_url = default_avatar_url
gon.max_file_size = Gitlab::CurrentSettings.max_attachment_size
gon.asset_host = ActionController::Base.asset_host
gon.webpack_public_path = webpack_public_path
gon.relative_url_root = Gitlab.config.gitlab.relative_url_root
- gon.shortcuts_path = Gitlab::Routing.url_helpers.help_page_path('shortcuts')
+ gon.shortcuts_path = Gitlab::Routing.url_helpers.help_page_path("shortcuts")
gon.user_color_scheme = Gitlab::ColorSchemes.for_user(current_user).css_class
gon.sentry_dsn = Gitlab::CurrentSettings.clientside_sentry_dsn if Gitlab::CurrentSettings.clientside_sentry_enabled
gon.gitlab_url = Gitlab.config.gitlab.url
gon.revision = Gitlab.revision
- gon.gitlab_logo = ActionController::Base.helpers.asset_path('gitlab_logo.png')
+ gon.gitlab_logo = ActionController::Base.helpers.asset_path("gitlab_logo.png")
gon.sprite_icons = IconsHelper.sprite_icon_path
gon.sprite_file_icons = IconsHelper.sprite_file_icons_path
- gon.emoji_sprites_css_path = ActionController::Base.helpers.stylesheet_path('emoji_sprites')
+ gon.emoji_sprites_css_path = ActionController::Base.helpers.stylesheet_path("emoji_sprites")
gon.test_env = Rails.env.test?
gon.suggested_label_colors = LabelsHelper.suggested_colors
gon.first_day_of_week = current_user&.first_day_of_week || Gitlab::CurrentSettings.first_day_of_week
@@ -46,7 +46,7 @@ module Gitlab
# Here the `true` argument signals gon that the value should be merged
# into any existing ones, instead of overwriting them. This allows you to
# use this method to push multiple feature flags.
- gon.push({ features: { var_name => enabled } }, true)
+ gon.push({features: {var_name => enabled}}, true)
end
def default_avatar_url
@@ -56,7 +56,7 @@ module Gitlab
# We also can't use Gitlab::Utils.append_path because the image path
# may be an absolute URL.
URI.join(Gitlab.config.gitlab.url,
- ActionController::Base.helpers.image_path('no_avatar.png')).to_s
+ ActionController::Base.helpers.image_path("no_avatar.png")).to_s
end
end
end
diff --git a/lib/gitlab/google_code_import/importer.rb b/lib/gitlab/google_code_import/importer.rb
index 1e7203cb82a..27eada450de 100644
--- a/lib/gitlab/google_code_import/importer.rb
+++ b/lib/gitlab/google_code_import/importer.rb
@@ -7,18 +7,18 @@ module Gitlab
NICE_LABEL_COLOR_HASH =
{
- 'Status: New' => '#428bca',
- 'Status: Accepted' => '#5cb85c',
- 'Status: Started' => '#8e44ad',
- 'Priority: Critical' => '#ffcfcf',
- 'Priority: High' => '#deffcf',
- 'Priority: Medium' => '#fff5cc',
- 'Priority: Low' => '#cfe9ff',
- 'Type: Defect' => '#d9534f',
- 'Type: Enhancement' => '#44ad8e',
- 'Type: Task' => '#4b6dd0',
- 'Type: Review' => '#8e44ad',
- 'Type: Other' => '#7f8c8d'
+ "Status: New" => "#428bca",
+ "Status: Accepted" => "#5cb85c",
+ "Status: Started" => "#8e44ad",
+ "Priority: Critical" => "#ffcfcf",
+ "Priority: High" => "#deffcf",
+ "Priority: Medium" => "#fff5cc",
+ "Priority: Low" => "#cfe9ff",
+ "Type: Defect" => "#d9534f",
+ "Type: Enhancement" => "#44ad8e",
+ "Type: Task" => "#4b6dd0",
+ "Type: Review" => "#8e44ad",
+ "Type: Other" => "#7f8c8d",
}.freeze
def initialize(project)
@@ -48,10 +48,10 @@ module Gitlab
def user_map
@user_map ||= begin
- user_map = Hash.new do |hash, user|
+ user_map = Hash.new { |hash, user|
# Replace ... by \.\.\., so `johnsm...@gmail.com` isn't autolinked.
Client.mask_email(user).sub("...", "\\.\\.\\.")
- end
+ }
import_data = project.import_data.try(:data)
stored_user_map = import_data["user_map"] if import_data
@@ -111,13 +111,13 @@ module Gitlab
end
issue = Issue.create!(
- iid: raw_issue['id'],
- project_id: project.id,
- title: raw_issue['title'],
- description: body,
- author_id: project.creator_id,
+ iid: raw_issue["id"],
+ project_id: project.id,
+ title: raw_issue["title"],
+ description: body,
+ author_id: project.creator_id,
assignee_ids: [assignee_id],
- state: raw_issue['state'] == 'closed' ? 'closed' : 'opened'
+ state: raw_issue["state"] == "closed" ? "closed" : "opened"
)
issue_labels = ::LabelsFinder.new(nil, project_id: project.id, title: labels).execute(skip_authorization: true)
@@ -170,11 +170,11 @@ module Gitlab
# Needs to match order of `comment_columns` below.
Note.create!(
- project_id: project.id,
- noteable_type: "Issue",
- noteable_id: issue.id,
- author_id: project.creator_id,
- note: body
+ project_id: project.id,
+ noteable_type: "Issue",
+ noteable_id: issue.id,
+ author_id: project.creator_id,
+ note: body
)
end
end
@@ -184,15 +184,15 @@ module Gitlab
NICE_LABEL_COLOR_HASH[name] ||
case name
when /\AComponent:/
- '#fff39e'
+ "#fff39e"
when /\AOpSys:/
- '#e2e2e2'
+ "#e2e2e2"
when /\AMilestone:/
- '#fee3ff'
+ "#fee3ff"
when *closed_statuses.map { |s| nice_status_name(s) }
- '#cfcfcf'
+ "#cfcfcf"
else
- '#e2e2e2'
+ "#e2e2e2"
end
end
@@ -228,7 +228,7 @@ module Gitlab
end
def create_label(name)
- params = { name: name, color: nice_label_color(name) }
+ params = {name: name, color: nice_label_color(name)}
::Labels::FindOrCreateService.new(nil, project, params).execute(skip_authorization: true)
end
@@ -248,25 +248,25 @@ module Gitlab
end
if raw_updates.key?("cc")
- cc = raw_updates["cc"].map do |l|
+ cc = raw_updates["cc"].map { |l|
deleted = l.start_with?("-")
l = l[1..-1] if deleted
l = user_map[l]
l = "~~#{l}~~" if deleted
l
- end
+ }
updates << "*Cc: #{cc.join(", ")}*"
end
if raw_updates.key?("labels")
- labels = raw_updates["labels"].map do |l|
+ labels = raw_updates["labels"].map { |l|
deleted = l.start_with?("-")
l = l[1..-1] if deleted
l = nice_label_name(l)
l = "~~#{l}~~" if deleted
l
- end
+ }
updates << "*Labels: #{labels.join(", ")}*"
end
@@ -276,17 +276,17 @@ module Gitlab
end
if raw_updates.key?("blockedOn")
- blocked_ons = raw_updates["blockedOn"].map do |raw_blocked_on|
+ blocked_ons = raw_updates["blockedOn"].map { |raw_blocked_on|
format_blocking_updates(raw_blocked_on)
- end
+ }
updates << "*Blocked on: #{blocked_ons.join(", ")}*"
end
if raw_updates.key?("blocking")
- blockings = raw_updates["blocking"].map do |raw_blocked_on|
+ blockings = raw_updates["blocking"].map { |raw_blocked_on|
format_blocking_updates(raw_blocked_on)
- end
+ }
updates << "*Blocking: #{blockings.join(", ")}*"
end
@@ -314,7 +314,7 @@ module Gitlab
def format_attachments(issue_id, comment_id, raw_attachments)
return [] unless raw_attachments
- raw_attachments.map do |attachment|
+ raw_attachments.map { |attachment|
next if attachment["isDeleted"]
filename = attachment["fileName"]
@@ -323,7 +323,7 @@ module Gitlab
text = "[#{filename}](#{link})"
text = "!#{text}" if filename =~ /\.(png|jpg|jpeg|gif|bmp|tiff)\z/i
text
- end.compact
+ }.compact
end
def format_issue_comment_body(id, author, date, content, updates, attachments)
diff --git a/lib/gitlab/google_code_import/project_creator.rb b/lib/gitlab/google_code_import/project_creator.rb
index eaef85acb98..6969f2ccbe3 100644
--- a/lib/gitlab/google_code_import/project_creator.rb
+++ b/lib/gitlab/google_code_import/project_creator.rb
@@ -24,7 +24,7 @@ module Gitlab
import_type: "google_code",
import_source: repo.name,
import_url: repo.import_url,
- import_data: { data: { 'repo' => repo.raw_data, 'user_map' => user_map } }
+ import_data: {data: {"repo" => repo.raw_data, "user_map" => user_map}}
).execute
end
end
diff --git a/lib/gitlab/gpg.rb b/lib/gitlab/gpg.rb
index 32f61b1d65c..f7e82951093 100644
--- a/lib/gitlab/gpg.rb
+++ b/lib/gitlab/gpg.rb
@@ -44,9 +44,9 @@ module Gitlab
raw_keys.each_with_object({}) do |raw_key, grouped_subkeys|
primary_subkey_id = raw_key.primary_subkey.keyid
- grouped_subkeys[primary_subkey_id] = raw_key.subkeys[1..-1].map do |s|
- { keyid: s.keyid, fingerprint: s.fingerprint }
- end
+ grouped_subkeys[primary_subkey_id] = raw_key.subkeys[1..-1].map { |s|
+ {keyid: s.keyid, fingerprint: s.fingerprint}
+ }
end
end
end
@@ -57,9 +57,9 @@ module Gitlab
GPGME::Key.find(:public, fingerprints).flat_map do |raw_key|
raw_key.uids.each_with_object([]) do |uid, arr|
- name = uid.name.force_encoding('UTF-8')
- email = uid.email.force_encoding('UTF-8')
- arr << { name: name, email: email.downcase } if name.valid_encoding? && email.valid_encoding?
+ name = uid.name.force_encoding("UTF-8")
+ email = uid.email.force_encoding("UTF-8")
+ arr << {name: name, email: email.downcase} if name.valid_encoding? && email.valid_encoding?
end
end
end
@@ -85,7 +85,7 @@ module Gitlab
# `GPGME::Engine.home_dir=`
# 2. Returns the default home directory otherwise
def current_home_dir
- GPGME::Engine.info.first.home_dir || GPGME::Engine.dirinfo('homedir')
+ GPGME::Engine.info.first.home_dir || GPGME::Engine.dirinfo("homedir")
end
private
diff --git a/lib/gitlab/gpg/commit.rb b/lib/gitlab/gpg/commit.rb
index 5ff415b6126..a4471c59f2e 100644
--- a/lib/gitlab/gpg/commit.rb
+++ b/lib/gitlab/gpg/commit.rb
@@ -106,7 +106,7 @@ module Gitlab
gpg_key_primary_keyid: gpg_key&.keyid || verified_signature&.fingerprint,
gpg_key_user_name: user_infos[:name],
gpg_key_user_email: user_infos[:email],
- verification_status: verification_status
+ verification_status: verification_status,
}
end
diff --git a/lib/gitlab/gpg/invalid_gpg_signature_updater.rb b/lib/gitlab/gpg/invalid_gpg_signature_updater.rb
index d892d27a917..a2862daff68 100644
--- a/lib/gitlab/gpg/invalid_gpg_signature_updater.rb
+++ b/lib/gitlab/gpg/invalid_gpg_signature_updater.rb
@@ -11,7 +11,7 @@ module Gitlab
def run
GpgSignature
.select(:id, :commit_sha, :project_id)
- .where('gpg_key_id IS NULL OR verification_status <> ?', GpgSignature.verification_statuses[:verified])
+ .where("gpg_key_id IS NULL OR verification_status <> ?", GpgSignature.verification_statuses[:verified])
.where(gpg_key_primary_keyid: @gpg_key.keyids)
.find_each { |sig| sig.gpg_commit&.update_signature!(sig) }
end
diff --git a/lib/gitlab/grape_logging/formatters/lograge_with_timestamp.rb b/lib/gitlab/grape_logging/formatters/lograge_with_timestamp.rb
index 9bb1e8fc7a2..4dd6c036fdc 100644
--- a/lib/gitlab/grape_logging/formatters/lograge_with_timestamp.rb
+++ b/lib/gitlab/grape_logging/formatters/lograge_with_timestamp.rb
@@ -15,7 +15,7 @@ module Gitlab
severity: severity,
duration: time[:total],
db: time[:db],
- view: time[:view]
+ view: time[:view],
}.merge(data)
::Lograge.formatter.call(attributes) + "\n"
end
@@ -23,11 +23,11 @@ module Gitlab
private
def process_params(data)
- return [] unless data.has_key?(:params)
+ return [] unless data.key?(:params)
data[:params]
.each_pair
- .map { |k, v| { key: k, value: utf8_encode_values(v) } }
+ .map { |k, v| {key: k, value: utf8_encode_values(v)} }
end
def utf8_encode_values(data)
diff --git a/lib/gitlab/grape_logging/loggers/correlation_id_logger.rb b/lib/gitlab/grape_logging/loggers/correlation_id_logger.rb
index fa4c5d86d44..2b2ff8bcf08 100644
--- a/lib/gitlab/grape_logging/loggers/correlation_id_logger.rb
+++ b/lib/gitlab/grape_logging/loggers/correlation_id_logger.rb
@@ -6,7 +6,7 @@ module Gitlab
module Loggers
class CorrelationIdLogger < ::GrapeLogging::Loggers::Base
def parameters(_, _)
- { Gitlab::CorrelationId::LOG_KEY => Gitlab::CorrelationId.current_id }
+ {Gitlab::CorrelationId::LOG_KEY => Gitlab::CorrelationId.current_id}
end
end
end
diff --git a/lib/gitlab/grape_logging/loggers/perf_logger.rb b/lib/gitlab/grape_logging/loggers/perf_logger.rb
index e3b9c59bd6e..118f9c4d5a4 100644
--- a/lib/gitlab/grape_logging/loggers/perf_logger.rb
+++ b/lib/gitlab/grape_logging/loggers/perf_logger.rb
@@ -6,7 +6,7 @@ module Gitlab
module Loggers
class PerfLogger < ::GrapeLogging::Loggers::Base
def parameters(_, _)
- { gitaly_calls: Gitlab::GitalyClient.get_request_count }
+ {gitaly_calls: Gitlab::GitalyClient.get_request_count}
end
end
end
diff --git a/lib/gitlab/grape_logging/loggers/queue_duration_logger.rb b/lib/gitlab/grape_logging/loggers/queue_duration_logger.rb
index 705e23adff2..51f05400698 100644
--- a/lib/gitlab/grape_logging/loggers/queue_duration_logger.rb
+++ b/lib/gitlab/grape_logging/loggers/queue_duration_logger.rb
@@ -13,14 +13,14 @@ module Gitlab
end
def parameters(request, _)
- proxy_start = request.env['HTTP_GITLAB_WORKHORSE_PROXY_START'].presence
+ proxy_start = request.env["HTTP_GITLAB_WORKHORSE_PROXY_START"].presence
return {} unless proxy_start && start_time
# Time in milliseconds since gitlab-workhorse started the request
duration = (start_time.to_f * 1_000 - proxy_start.to_f / 1_000_000).round(2)
- { 'queue_duration': duration }
+ {'queue_duration': duration}
end
end
end
diff --git a/lib/gitlab/grape_logging/loggers/route_logger.rb b/lib/gitlab/grape_logging/loggers/route_logger.rb
index f3146b4dfd9..04820a58f8d 100644
--- a/lib/gitlab/grape_logging/loggers/route_logger.rb
+++ b/lib/gitlab/grape_logging/loggers/route_logger.rb
@@ -12,7 +12,7 @@ module Gitlab
return {} unless route
- { route: route }
+ {route: route}
rescue
# endpoint.route calls env[Grape::Env::GRAPE_ROUTING_ARGS][:route_info]
# but env[Grape::Env::GRAPE_ROUTING_ARGS] is nil in the case of a 405 response
diff --git a/lib/gitlab/graphql/authorize/authorize_resource.rb b/lib/gitlab/graphql/authorize/authorize_resource.rb
index b367a97105c..20076e7c298 100644
--- a/lib/gitlab/graphql/authorize/authorize_resource.rb
+++ b/lib/gitlab/graphql/authorize/authorize_resource.rb
@@ -11,11 +11,11 @@ module Gitlab
# If the `#authorize` call is used on multiple classes, we add the
# permissions specified on a subclass, to the ones that were specified
# on it's superclass.
- @required_permissions ||= if self.respond_to?(:superclass) && superclass.respond_to?(:required_permissions)
- superclass.required_permissions.dup
- else
- []
- end
+ @required_permissions ||= if respond_to?(:superclass) && superclass.respond_to?(:required_permissions)
+ superclass.required_permissions.dup
+ else
+ []
+ end
end
def authorize(*permissions)
@@ -43,7 +43,7 @@ module Gitlab
def authorize!(object)
unless authorized?(object)
raise Gitlab::Graphql::Errors::ResourceNotAvailable,
- "The resource that you are attempting to access does not exist or you don't have permission to perform this action"
+ "The resource that you are attempting to access does not exist or you don't have permission to perform this action"
end
end
diff --git a/lib/gitlab/graphql/authorize/instrumentation.rb b/lib/gitlab/graphql/authorize/instrumentation.rb
index 593da8471dd..39c822be189 100644
--- a/lib/gitlab/graphql/authorize/instrumentation.rb
+++ b/lib/gitlab/graphql/authorize/instrumentation.rb
@@ -12,7 +12,7 @@ module Gitlab
old_resolver = field.resolve_proc
- new_resolver = -> (obj, args, ctx) do
+ new_resolver = ->(obj, args, ctx) do
resolved_obj = old_resolver.call(obj, args, ctx)
checker = build_checker(ctx[:current_user], required_permissions)
diff --git a/lib/gitlab/graphql/expose_permissions.rb b/lib/gitlab/graphql/expose_permissions.rb
index 365b7cca24f..d7f95d5e75f 100644
--- a/lib/gitlab/graphql/expose_permissions.rb
+++ b/lib/gitlab/graphql/expose_permissions.rb
@@ -5,11 +5,11 @@ module Gitlab
module ExposePermissions
extend ActiveSupport::Concern
prepended do
- def self.expose_permissions(permission_type, description: 'Permissions for the current user on the resource')
+ def self.expose_permissions(permission_type, description: "Permissions for the current user on the resource")
field :user_permissions, permission_type,
- description: description,
- null: false,
- resolve: -> (obj, _, _) { obj }
+ description: description,
+ null: false,
+ resolve: ->(obj, _, _) { obj }
end
end
end
diff --git a/lib/gitlab/graphql/loaders/batch_model_loader.rb b/lib/gitlab/graphql/loaders/batch_model_loader.rb
index 5a0099dc6b1..6e1aed417b7 100644
--- a/lib/gitlab/graphql/loaders/batch_model_loader.rb
+++ b/lib/gitlab/graphql/loaders/batch_model_loader.rb
@@ -12,13 +12,13 @@ module Gitlab
# rubocop: disable CodeReuse/ActiveRecord
def find
- BatchLoader.for({ model: model_class, id: model_id }).batch do |loader_info, loader|
+ BatchLoader.for({model: model_class, id: model_id}).batch do |loader_info, loader|
per_model = loader_info.group_by { |info| info[:model] }
per_model.each do |model, info|
ids = info.map { |i| i[:id] }
results = model.where(id: ids)
- results.each { |record| loader.call({ model: model, id: record.id }, record) }
+ results.each { |record| loader.call({model: model, id: record.id}, record) }
end
end
end
diff --git a/lib/gitlab/graphql/mount_mutation.rb b/lib/gitlab/graphql/mount_mutation.rb
index 9048967d4e1..c23cda8ce3e 100644
--- a/lib/gitlab/graphql/mount_mutation.rb
+++ b/lib/gitlab/graphql/mount_mutation.rb
@@ -10,7 +10,7 @@ module Gitlab
# Using an underscored field name symbol will make `graphql-ruby`
# standardize the field name
field mutation_class.graphql_name.underscore.to_sym,
- mutation: mutation_class
+ mutation: mutation_class
end
end
end
diff --git a/lib/gitlab/graphql/present/instrumentation.rb b/lib/gitlab/graphql/present/instrumentation.rb
index ab03c40c22d..1c1bd9c8947 100644
--- a/lib/gitlab/graphql/present/instrumentation.rb
+++ b/lib/gitlab/graphql/present/instrumentation.rb
@@ -13,7 +13,7 @@ module Gitlab
old_resolver = field.resolve_proc
- resolve_with_presenter = -> (presented_type, args, context) do
+ resolve_with_presenter = ->(presented_type, args, context) do
# We need to wrap the original presentation type into a type that
# uses the presenter as an object.
object = presented_type.object
diff --git a/lib/gitlab/graphs/commits.rb b/lib/gitlab/graphs/commits.rb
index 66e1b2e78b4..f5eeb248627 100644
--- a/lib/gitlab/graphs/commits.rb
+++ b/lib/gitlab/graphs/commits.rb
@@ -34,9 +34,9 @@ module Gitlab
(1..31).to_a.each { |day| @commits_per_month[day] = 0 }
@commits.each do |commit|
- hour = commit.committed_date.strftime('%k').to_i
- day_of_month = commit.committed_date.strftime('%e').to_i
- weekday = commit.committed_date.strftime('%A')
+ hour = commit.committed_date.strftime("%k").to_i
+ day_of_month = commit.committed_date.strftime("%e").to_i
+ weekday = commit.committed_date.strftime("%A")
@commits_per_week_days[weekday] ||= 0
@commits_per_week_days[weekday] += 1
diff --git a/lib/gitlab/hashed_storage/rake_helper.rb b/lib/gitlab/hashed_storage/rake_helper.rb
index 38f552fab03..051fc4b3b1f 100644
--- a/lib/gitlab/hashed_storage/rake_helper.rb
+++ b/lib/gitlab/hashed_storage/rake_helper.rb
@@ -4,19 +4,19 @@ module Gitlab
module HashedStorage
module RakeHelper
def self.batch_size
- ENV.fetch('BATCH', 200).to_i
+ ENV.fetch("BATCH", 200).to_i
end
def self.listing_limit
- ENV.fetch('LIMIT', 500).to_i
+ ENV.fetch("LIMIT", 500).to_i
end
def self.range_from
- ENV['ID_FROM']
+ ENV["ID_FROM"]
end
def self.range_to
- ENV['ID_TO']
+ ENV["ID_TO"]
end
def self.range_single_item?
@@ -35,7 +35,7 @@ module Gitlab
# rubocop: disable CodeReuse/ActiveRecord
def self.legacy_attachments_relation
- Upload.joins(<<~SQL).where('projects.storage_version < :version OR projects.storage_version IS NULL', version: Project::HASHED_STORAGE_FEATURES[:attachments])
+ Upload.joins(<<~SQL).where("projects.storage_version < :version OR projects.storage_version IS NULL", version: Project::HASHED_STORAGE_FEATURES[:attachments])
JOIN projects
ON (uploads.model_type='Project' AND uploads.model_id=projects.id)
SQL
@@ -44,7 +44,7 @@ module Gitlab
# rubocop: disable CodeReuse/ActiveRecord
def self.hashed_attachments_relation
- Upload.joins(<<~SQL).where('projects.storage_version >= :version', version: Project::HASHED_STORAGE_FEATURES[:attachments])
+ Upload.joins(<<~SQL).where("projects.storage_version >= :version", version: Project::HASHED_STORAGE_FEATURES[:attachments])
JOIN projects
ON (uploads.model_type='Project' AND uploads.model_id=projects.id)
SQL
diff --git a/lib/gitlab/health_checks/base_abstract_check.rb b/lib/gitlab/health_checks/base_abstract_check.rb
index 1d31f59999c..82dfc56dda6 100644
--- a/lib/gitlab/health_checks/base_abstract_check.rb
+++ b/lib/gitlab/health_checks/base_abstract_check.rb
@@ -8,7 +8,7 @@ module Gitlab
end
def human_name
- name.sub(/_check$/, '').capitalize
+ name.sub(/_check$/, "").capitalize
end
def readiness
@@ -36,11 +36,9 @@ module Gitlab
end
def catch_timeout(seconds, &block)
- begin
- Timeout.timeout(seconds.to_i, &block)
- rescue Timeout::Error => ex
- ex
- end
+ Timeout.timeout(seconds.to_i, &block)
+ rescue Timeout::Error => ex
+ ex
end
end
end
diff --git a/lib/gitlab/health_checks/db_check.rb b/lib/gitlab/health_checks/db_check.rb
index 2bcd25cd3cc..d8e74b0158f 100644
--- a/lib/gitlab/health_checks/db_check.rb
+++ b/lib/gitlab/health_checks/db_check.rb
@@ -9,19 +9,19 @@ module Gitlab
private
def metric_prefix
- 'db_ping'
+ "db_ping"
end
def successful?(result)
- result == '1'
+ result == "1"
end
def check
catch_timeout 10.seconds do
if Gitlab::Database.postgresql?
- ActiveRecord::Base.connection.execute('SELECT 1 as ping')&.first&.[]('ping')&.to_s
+ ActiveRecord::Base.connection.execute("SELECT 1 as ping")&.first&.[]("ping")&.to_s
else
- ActiveRecord::Base.connection.execute('SELECT 1 as ping')&.first&.first&.to_s
+ ActiveRecord::Base.connection.execute("SELECT 1 as ping")&.first&.first&.to_s
end
end
end
diff --git a/lib/gitlab/health_checks/gitaly_check.rb b/lib/gitlab/health_checks/gitaly_check.rb
index 898733fea5d..4b5d1d97f68 100644
--- a/lib/gitlab/health_checks/gitaly_check.rb
+++ b/lib/gitlab/health_checks/gitaly_check.rb
@@ -5,7 +5,7 @@ module Gitlab
class GitalyCheck
extend BaseAbstractCheck
- METRIC_PREFIX = 'gitaly_health_check'.freeze
+ METRIC_PREFIX = "gitaly_health_check"
class << self
def readiness
@@ -17,11 +17,11 @@ module Gitlab
def metrics
Gitaly::Server.all.flat_map do |server|
result, elapsed = with_timing { server.read_writeable? }
- labels = { shard: server.storage }
+ labels = {shard: server.storage}
[
metric("#{metric_prefix}_success", result ? 1 : 0, **labels),
- metric("#{metric_prefix}_latency_seconds", elapsed, **labels)
+ metric("#{metric_prefix}_latency_seconds", elapsed, **labels),
]
end
end
diff --git a/lib/gitlab/health_checks/prometheus_text_format.rb b/lib/gitlab/health_checks/prometheus_text_format.rb
index 2a8f9d31cd5..7a591da362a 100644
--- a/lib/gitlab/health_checks/prometheus_text_format.rb
+++ b/lib/gitlab/health_checks/prometheus_text_format.rb
@@ -29,7 +29,7 @@ module Gitlab
end
def metric_text(metric)
- labels = metric.labels&.map { |key, value| "#{key}=\"#{value}\"" }&.join(',') || ''
+ labels = metric.labels&.map { |key, value| "#{key}=\"#{value}\"" }&.join(",") || ""
if labels.empty?
"#{metric.name} #{metric.value}"
diff --git a/lib/gitlab/health_checks/redis/cache_check.rb b/lib/gitlab/health_checks/redis/cache_check.rb
index 0c8fe83893b..720cfd6d819 100644
--- a/lib/gitlab/health_checks/redis/cache_check.rb
+++ b/lib/gitlab/health_checks/redis/cache_check.rb
@@ -14,11 +14,11 @@ module Gitlab
private
def metric_prefix
- 'redis_cache_ping'
+ "redis_cache_ping"
end
def successful?(result)
- result == 'PONG'
+ result == "PONG"
end
# rubocop: disable CodeReuse/ActiveRecord
diff --git a/lib/gitlab/health_checks/redis/queues_check.rb b/lib/gitlab/health_checks/redis/queues_check.rb
index b1e33b9f459..4317ea295e1 100644
--- a/lib/gitlab/health_checks/redis/queues_check.rb
+++ b/lib/gitlab/health_checks/redis/queues_check.rb
@@ -14,11 +14,11 @@ module Gitlab
private
def metric_prefix
- 'redis_queues_ping'
+ "redis_queues_ping"
end
def successful?(result)
- result == 'PONG'
+ result == "PONG"
end
# rubocop: disable CodeReuse/ActiveRecord
diff --git a/lib/gitlab/health_checks/redis/redis_check.rb b/lib/gitlab/health_checks/redis/redis_check.rb
index f7e46fce134..7c6be0831cb 100644
--- a/lib/gitlab/health_checks/redis/redis_check.rb
+++ b/lib/gitlab/health_checks/redis/redis_check.rb
@@ -10,11 +10,11 @@ module Gitlab
private
def metric_prefix
- 'redis_ping'
+ "redis_ping"
end
def successful?(result)
- result == 'PONG'
+ result == "PONG"
end
def check
diff --git a/lib/gitlab/health_checks/redis/shared_state_check.rb b/lib/gitlab/health_checks/redis/shared_state_check.rb
index 285ac271929..b46595f1fbe 100644
--- a/lib/gitlab/health_checks/redis/shared_state_check.rb
+++ b/lib/gitlab/health_checks/redis/shared_state_check.rb
@@ -14,11 +14,11 @@ module Gitlab
private
def metric_prefix
- 'redis_shared_state_ping'
+ "redis_shared_state_ping"
end
def successful?(result)
- result == 'PONG'
+ result == "PONG"
end
# rubocop: disable CodeReuse/ActiveRecord
diff --git a/lib/gitlab/health_checks/simple_abstract_check.rb b/lib/gitlab/health_checks/simple_abstract_check.rb
index 3588260d6eb..5c4152d9570 100644
--- a/lib/gitlab/health_checks/simple_abstract_check.rb
+++ b/lib/gitlab/health_checks/simple_abstract_check.rb
@@ -22,7 +22,7 @@ module Gitlab
[
metric("#{metric_prefix}_timeout", result.is_a?(Timeout::Error) ? 1 : 0),
metric("#{metric_prefix}_success", successful?(result) ? 1 : 0),
- metric("#{metric_prefix}_latency_seconds", elapsed)
+ metric("#{metric_prefix}_latency_seconds", elapsed),
]
end
diff --git a/lib/gitlab/highlight.rb b/lib/gitlab/highlight.rb
index a4e60bbd828..c3e565be73d 100644
--- a/lib/gitlab/highlight.rb
+++ b/lib/gitlab/highlight.rb
@@ -31,8 +31,8 @@ module Gitlab
def lexer
@lexer ||= custom_language || begin
Rouge::Lexer.guess(filename: @blob_name, source: @blob_content).new
- rescue Rouge::Guesser::Ambiguous => e
- e.alternatives.sort_by(&:tag).first
+ rescue Rouge::Guesser::Ambiguous => e
+ e.alternatives.min_by(&:tag)
end
end
diff --git a/lib/gitlab/hook_data/base_builder.rb b/lib/gitlab/hook_data/base_builder.rb
index d54175bce81..0f6c5616c67 100644
--- a/lib/gitlab/hook_data/base_builder.rb
+++ b/lib/gitlab/hook_data/base_builder.rb
@@ -27,8 +27,8 @@ module Gitlab
markdown_text.gsub(MARKDOWN_SIMPLE_IMAGE) do
if $~[:image]
url = $~[:url]
- url = "#{uploads_prefix}#{url}" if url.start_with?('/uploads')
- url = "/#{url}" unless url.start_with?('/')
+ url = "#{uploads_prefix}#{url}" if url.start_with?("/uploads")
+ url = "/#{url}" unless url.start_with?("/")
"![#{$~[:title]}](#{Gitlab.config.gitlab.url}#{url})"
else
@@ -38,7 +38,7 @@ module Gitlab
end
def uploads_prefix
- project&.full_path || ''
+ project&.full_path || ""
end
def project
diff --git a/lib/gitlab/hook_data/issuable_builder.rb b/lib/gitlab/hook_data/issuable_builder.rb
index 0803df65632..1242dcd6250 100644
--- a/lib/gitlab/hook_data/issuable_builder.rb
+++ b/lib/gitlab/hook_data/issuable_builder.rb
@@ -5,7 +5,7 @@ module Gitlab
class IssuableBuilder < BaseBuilder
CHANGES_KEYS = %i[previous current].freeze
- alias_method :issuable, :object
+ alias issuable object
def build(user: nil, changes: {})
hook_data = {
@@ -17,7 +17,7 @@ module Gitlab
labels: issuable.labels.map(&:hook_attrs),
changes: final_changes(changes.slice(*safe_keys)),
# DEPRECATED
- repository: issuable.project.hook_attrs.slice(:name, :url, :description, :homepage)
+ repository: issuable.project.hook_attrs.slice(:name, :url, :description, :homepage),
}
if issuable.is_a?(Issue)
@@ -57,9 +57,8 @@ module Gitlab
end
def final_changes(changes_hash)
- changes_hash.reduce({}) do |hash, (key, changes_array)|
+ changes_hash.each_with_object({}) do |(key, changes_array), hash|
hash[key] = Hash[CHANGES_KEYS.zip(changes_array)]
- hash
end
end
end
diff --git a/lib/gitlab/hook_data/issue_builder.rb b/lib/gitlab/hook_data/issue_builder.rb
index c99353b9d49..70aaab28684 100644
--- a/lib/gitlab/hook_data/issue_builder.rb
+++ b/lib/gitlab/hook_data/issue_builder.rb
@@ -34,21 +34,21 @@ module Gitlab
].freeze
end
- alias_method :issue, :object
+ alias issue object
def build
attrs = {
- description: absolute_image_urls(issue.description),
- url: Gitlab::UrlBuilder.build(issue),
- total_time_spent: issue.total_time_spent,
- human_total_time_spent: issue.human_total_time_spent,
- human_time_estimate: issue.human_time_estimate,
- assignee_ids: issue.assignee_ids,
- assignee_id: issue.assignee_ids.first # This key is deprecated
+ description: absolute_image_urls(issue.description),
+ url: Gitlab::UrlBuilder.build(issue),
+ total_time_spent: issue.total_time_spent,
+ human_total_time_spent: issue.human_total_time_spent,
+ human_time_estimate: issue.human_time_estimate,
+ assignee_ids: issue.assignee_ids,
+ assignee_id: issue.assignee_ids.first, # This key is deprecated
}
issue.attributes.with_indifferent_access.slice(*self.class.safe_hook_attributes)
- .merge!(attrs)
+ .merge!(attrs)
end
end
end
diff --git a/lib/gitlab/hook_data/merge_request_builder.rb b/lib/gitlab/hook_data/merge_request_builder.rb
index ad38e26e40a..13ae10cb74a 100644
--- a/lib/gitlab/hook_data/merge_request_builder.rb
+++ b/lib/gitlab/hook_data/merge_request_builder.rb
@@ -39,7 +39,7 @@ module Gitlab
total_time_spent
].freeze
- alias_method :merge_request, :object
+ alias merge_request object
def build
attrs = {
@@ -51,11 +51,11 @@ module Gitlab
work_in_progress: merge_request.work_in_progress?,
total_time_spent: merge_request.total_time_spent,
human_total_time_spent: merge_request.human_total_time_spent,
- human_time_estimate: merge_request.human_time_estimate
+ human_time_estimate: merge_request.human_time_estimate,
}
merge_request.attributes.with_indifferent_access.slice(*self.class.safe_hook_attributes)
- .merge!(attrs)
+ .merge!(attrs)
end
end
end
diff --git a/lib/gitlab/hook_data/note_builder.rb b/lib/gitlab/hook_data/note_builder.rb
index ae30ef6364b..746558e9f68 100644
--- a/lib/gitlab/hook_data/note_builder.rb
+++ b/lib/gitlab/hook_data/note_builder.rb
@@ -28,7 +28,7 @@ module Gitlab
updated_by_id
].freeze
- alias_method :note, :object
+ alias note object
def build
note
diff --git a/lib/gitlab/hook_data/wiki_page_builder.rb b/lib/gitlab/hook_data/wiki_page_builder.rb
index 67f06b1ca46..7893d61abf3 100644
--- a/lib/gitlab/hook_data/wiki_page_builder.rb
+++ b/lib/gitlab/hook_data/wiki_page_builder.rb
@@ -3,13 +3,13 @@
module Gitlab
module HookData
class WikiPageBuilder < BaseBuilder
- alias_method :wiki_page, :object
+ alias wiki_page object
def build
wiki_page
.attributes
.merge(
- 'content' => absolute_image_urls(wiki_page.content)
+ "content" => absolute_image_urls(wiki_page.content)
)
end
end
diff --git a/lib/gitlab/http_io.rb b/lib/gitlab/http_io.rb
index 6a9fb85b054..f243597c3da 100644
--- a/lib/gitlab/http_io.rb
+++ b/lib/gitlab/http_io.rb
@@ -14,7 +14,7 @@ module Gitlab
attr_reader :tell
attr_reader :chunk, :chunk_range
- alias_method :pos, :tell
+ alias pos tell
def initialize(url, size)
raise InvalidURLError unless ::Gitlab::UrlSanitizer.valid?(url)
@@ -57,7 +57,7 @@ module Gitlab
-1
end
- raise 'new position is outside of file' if new_pos < 0 || new_pos > size
+ raise "new position is outside of file" if new_pos < 0 || new_pos > size
@tell = new_pos
end
@@ -95,9 +95,7 @@ module Gitlab
out = out.join
# If outbuf is passed, we put the output into the buffer. This supports IO.copy_stream functionality
- if outbuf
- outbuf.replace(out)
- end
+ outbuf&.replace(out)
out
end
@@ -149,11 +147,11 @@ module Gitlab
def get_chunk
unless in_range?
- response = Net::HTTP.start(uri.hostname, uri.port, proxy_from_env: true, use_ssl: uri.scheme == 'https') do |http|
+ response = Net::HTTP.start(uri.hostname, uri.port, proxy_from_env: true, use_ssl: uri.scheme == "https") { |http|
http.request(request)
- end
+ }
- raise FailedToGetChunkError unless response.code == '200' || response.code == '206'
+ raise FailedToGetChunkError unless response.code == "200" || response.code == "206"
@chunk = response.body.force_encoding(Encoding::BINARY)
@chunk_range = response.content_range
diff --git a/lib/gitlab/i18n.rb b/lib/gitlab/i18n.rb
index 7e0398f09af..26841b18ad9 100644
--- a/lib/gitlab/i18n.rb
+++ b/lib/gitlab/i18n.rb
@@ -5,28 +5,28 @@ module Gitlab
extend self
AVAILABLE_LANGUAGES = {
- 'en' => 'English',
- 'es' => 'Español',
- 'gl_ES' => 'Galego',
- 'de' => 'Deutsch',
- 'fr' => 'Français',
- 'pt_BR' => 'Português (Brasil)',
- 'zh_CN' => '简体中文',
- 'zh_HK' => '繁體中文 (香港)',
- 'zh_TW' => '繁體中文 (臺灣)',
- 'bg' => 'български',
- 'ru' => 'Русский',
- 'eo' => 'Esperanto',
- 'it' => 'Italiano',
- 'uk' => 'Українська',
- 'ja' => '日本語',
- 'ko' => '한국어',
- 'nl_NL' => 'Nederlands',
- 'tr_TR' => 'Türkçe',
- 'id_ID' => 'Bahasa Indonesia',
- 'fil_PH' => 'Filipino',
- 'pl_PL' => 'Polski',
- 'cs_CZ' => 'Čeština'
+ "en" => "English",
+ "es" => "Español",
+ "gl_ES" => "Galego",
+ "de" => "Deutsch",
+ "fr" => "Français",
+ "pt_BR" => "Português (Brasil)",
+ "zh_CN" => "简体中文",
+ "zh_HK" => "繁體中文 (香港)",
+ "zh_TW" => "繁體中文 (臺灣)",
+ "bg" => "български",
+ "ru" => "Русский",
+ "eo" => "Esperanto",
+ "it" => "Italiano",
+ "uk" => "Українська",
+ "ja" => "日本語",
+ "ko" => "한국어",
+ "nl_NL" => "Nederlands",
+ "tr_TR" => "Türkçe",
+ "id_ID" => "Bahasa Indonesia",
+ "fil_PH" => "Filipino",
+ "pl_PL" => "Polski",
+ "cs_CZ" => "Čeština",
}.freeze
def available_locales
diff --git a/lib/gitlab/i18n/metadata_entry.rb b/lib/gitlab/i18n/metadata_entry.rb
index 3764e379681..5caabe17d41 100644
--- a/lib/gitlab/i18n/metadata_entry.rb
+++ b/lib/gitlab/i18n/metadata_entry.rb
@@ -17,7 +17,7 @@ module Gitlab
def expected_forms
return nil unless plural_information
- plural_information['nplurals'].to_i
+ plural_information["nplurals"].to_i
end
def forms_to_test
@@ -29,7 +29,7 @@ module Gitlab
def plural_information
return @plural_information if defined?(@plural_information)
- if plural_line = entry_data[:msgstr].detect { |metadata_line| metadata_line.starts_with?('Plural-Forms: ') }
+ if plural_line = entry_data[:msgstr].detect { |metadata_line| metadata_line.starts_with?("Plural-Forms: ") }
@plural_information = Hash[plural_line.scan(/(\w+)=([^;\n]+)/)]
end
end
diff --git a/lib/gitlab/i18n/po_linter.rb b/lib/gitlab/i18n/po_linter.rb
index 3e9a035010f..1079e6e1a08 100644
--- a/lib/gitlab/i18n/po_linter.rb
+++ b/lib/gitlab/i18n/po_linter.rb
@@ -20,7 +20,7 @@ module Gitlab
def validate_po
if parse_error = parse_po
- return 'PO-syntax errors' => [parse_error]
+ return "PO-syntax errors" => [parse_error]
end
validate_entries
@@ -34,12 +34,12 @@ module Gitlab
if entries.first[:msgid].empty?
@metadata_entry = Gitlab::I18n::MetadataEntry.new(entries.shift)
else
- return 'Missing metadata entry.'
+ return "Missing metadata entry."
end
- @translation_entries = entries.map do |entry_data|
+ @translation_entries = entries.map { |entry_data|
Gitlab::I18n::TranslationEntry.new(entry_data, metadata_entry.expected_forms)
- end
+ }
nil
rescue SimplePoParser::ParserError => e
@@ -73,15 +73,15 @@ module Gitlab
def validate_unescaped_chars(errors, entry)
if entry.msgid_contains_unescaped_chars?
- errors << 'contains unescaped `%`, escape it using `%%`'
+ errors << "contains unescaped `%`, escape it using `%%`"
end
if entry.plural_id_contains_unescaped_chars?
- errors << 'plural id contains unescaped `%`, escape it using `%%`'
+ errors << "plural id contains unescaped `%`, escape it using `%%`"
end
if entry.translations_contain_unescaped_chars?
- errors << 'translation contains unescaped `%`, escape it using `%%`'
+ errors << "translation contains unescaped `%`, escape it using `%%`"
end
end
@@ -91,21 +91,21 @@ module Gitlab
if entry.has_plural? && entry.all_translations.size != metadata_entry.expected_forms
errors << "should have #{metadata_entry.expected_forms} "\
- "#{'translations'.pluralize(metadata_entry.expected_forms)}"
+ "#{"translations".pluralize(metadata_entry.expected_forms)}"
end
end
def validate_newlines(errors, entry)
if entry.msgid_has_multiple_lines?
- errors << 'is defined over multiple lines, this breaks some tooling.'
+ errors << "is defined over multiple lines, this breaks some tooling."
end
if entry.plural_id_has_multiple_lines?
- errors << 'plural is defined over multiple lines, this breaks some tooling.'
+ errors << "plural is defined over multiple lines, this breaks some tooling."
end
if entry.translations_have_multiple_lines?
- errors << 'has translations defined over multiple lines, this breaks some tooling.'
+ errors << "has translations defined over multiple lines, this breaks some tooling."
end
end
@@ -160,11 +160,11 @@ module Gitlab
used_variables = entry.msgid.scan(VARIABLE_REGEX)
variables = fill_in_variables(used_variables)
- translation = if entry.msgid.include?('|')
- FastGettext::Translation.s_(entry.msgid)
- else
- FastGettext::Translation._(entry.msgid)
- end
+ translation = if entry.msgid.include?("|")
+ FastGettext::Translation.s_(entry.msgid)
+ else
+ FastGettext::Translation._(entry.msgid)
+ end
translation % variables if used_variables.any?
end
@@ -207,9 +207,9 @@ module Gitlab
# This calls the C function that defines the pluralization rule, it can
# return a boolean (`false` represents 0, `true` represents 1) or an integer
# that specifies the plural form to be used for the given number
- pluralization_result = Gitlab::I18n.with_locale(locale) do
+ pluralization_result = Gitlab::I18n.with_locale(locale) {
FastGettext.pluralisation_rule.call(counter)
- end
+ }
case pluralization_result
when false
@@ -226,13 +226,12 @@ module Gitlab
[]
elsif variables.any? { |variable| unnamed_variable?(variable) }
variables.map do |variable|
- variable == '%d' ? Random.rand(1000) : Gitlab::Utils.random_string
+ variable == "%d" ? Random.rand(1000) : Gitlab::Utils.random_string
end
else
- variables.inject({}) do |hash, variable|
+ variables.each_with_object({}) do |variable, hash|
variable_name = variable[/\w+/]
hash[variable_name] = Gitlab::Utils.random_string
- hash
end
end
end
@@ -241,11 +240,11 @@ module Gitlab
unnamed_variables, named_variables = variables.partition { |name| unnamed_variable?(name) }
if unnamed_variables.any? && named_variables.any?
- errors << 'is combining named variables with unnamed variables'
+ errors << "is combining named variables with unnamed variables"
end
if unnamed_variables.size > 1
- errors << 'is combining multiple unnamed variables'
+ errors << "is combining multiple unnamed variables"
end
end
@@ -269,7 +268,7 @@ module Gitlab
end
def unnamed_variable?(variable_name)
- !variable_name.start_with?('%{')
+ !variable_name.start_with?("%{")
end
def validate_flags(errors, entry)
diff --git a/lib/gitlab/i18n/translation_entry.rb b/lib/gitlab/i18n/translation_entry.rb
index 19c10b2e402..3a503ba8e34 100644
--- a/lib/gitlab/i18n/translation_entry.rb
+++ b/lib/gitlab/i18n/translation_entry.rb
@@ -41,10 +41,10 @@ module Gitlab
return [] unless translated?
@plural_translations ||= if has_singular_translation?
- all_translations.drop(1)
- else
- all_translations
- end
+ all_translations.drop(1)
+ else
+ all_translations
+ end
end
def flag
@@ -87,7 +87,7 @@ module Gitlab
def translation_entries
@translation_entries ||= entry_data.fetch_values(*translation_keys)
- .reject(&:empty?)
+ .reject(&:empty?)
end
def translation_keys
diff --git a/lib/gitlab/identifier.rb b/lib/gitlab/identifier.rb
index d5f94ad04f1..8cf8f1a59ec 100644
--- a/lib/gitlab/identifier.rb
+++ b/lib/gitlab/identifier.rb
@@ -5,10 +5,10 @@
module Gitlab
module Identifier
def identify(identifier)
- if identifier =~ /\Auser-\d+\Z/
+ if /\Auser-\d+\Z/.match?(identifier)
# git push over http
identify_using_user(identifier)
- elsif identifier =~ /\Akey-\d+\Z/
+ elsif /\Akey-\d+\Z/.match?(identifier)
# git push over ssh
identify_using_ssh_key(identifier)
end
@@ -46,7 +46,7 @@ module Gitlab
@identification_cache ||= {
email: {},
user: {},
- ssh_key: {}
+ ssh_key: {},
}
end
end
diff --git a/lib/gitlab/import/database_helpers.rb b/lib/gitlab/import/database_helpers.rb
index 5b3f30d894a..0f57918c72a 100644
--- a/lib/gitlab/import/database_helpers.rb
+++ b/lib/gitlab/import/database_helpers.rb
@@ -14,7 +14,7 @@ module Gitlab
# callbacks or validation rules, as doing this wouldn't scale when
# importing very large projects.
result = Gitlab::Database
- .bulk_insert(relation.table_name, [attributes], return_ids: true)
+ .bulk_insert(relation.table_name, [attributes], return_ids: true)
# MySQL doesn't support returning the IDs of a bulk insert in a way that
# is not a pain, so in this case we'll issue an extra query instead.
diff --git a/lib/gitlab/import/logger.rb b/lib/gitlab/import/logger.rb
index ab3e822a4e9..24fab7b7561 100644
--- a/lib/gitlab/import/logger.rb
+++ b/lib/gitlab/import/logger.rb
@@ -4,7 +4,7 @@ module Gitlab
module Import
class Logger < ::Gitlab::JsonLogger
def self.file_name_noext
- 'importer'
+ "importer"
end
end
end
diff --git a/lib/gitlab/import_export.rb b/lib/gitlab/import_export.rb
index f63a5ece71e..5ddf3452bc9 100644
--- a/lib/gitlab/import_export.rb
+++ b/lib/gitlab/import_export.rb
@@ -5,7 +5,7 @@ module Gitlab
extend self
# For every version update, the version history in import_export.md has to be kept up to date.
- VERSION = '0.2.4'.freeze
+ VERSION = "0.2.4"
FILENAME_LIMIT = 50
def export_path(relative_path:)
@@ -13,11 +13,11 @@ module Gitlab
end
def storage_path
- File.join(Settings.shared['path'], 'tmp/project_exports')
+ File.join(Settings.shared["path"], "tmp/project_exports")
end
def import_upload_path(filename:)
- File.join(storage_path, 'uploads', filename)
+ File.join(storage_path, "uploads", filename)
end
def project_filename
@@ -29,15 +29,15 @@ module Gitlab
end
def config_file
- Rails.root.join('lib/gitlab/import_export/import_export.yml')
+ Rails.root.join("lib/gitlab/import_export/import_export.yml")
end
def version_filename
- 'VERSION'
+ "VERSION"
end
def export_filename(project:)
- basename = "#{Time.now.strftime('%Y-%m-%d_%H-%M-%3N')}_#{project.full_path.tr('/', '_')}"
+ basename = "#{Time.now.strftime("%Y-%m-%d_%H-%M-%3N")}_#{project.full_path.tr("/", "_")}"
"#{basename[0..FILENAME_LIMIT]}_export.tar.gz"
end
diff --git a/lib/gitlab/import_export/after_export_strategies/base_after_export_strategy.rb b/lib/gitlab/import_export/after_export_strategies/base_after_export_strategy.rb
index d39b6fe5955..b2716e844af 100644
--- a/lib/gitlab/import_export/after_export_strategies/base_after_export_strategy.rb
+++ b/lib/gitlab/import_export/after_export_strategies/base_after_export_strategy.rb
@@ -10,7 +10,7 @@ module Gitlab
StrategyError = Class.new(StandardError)
- AFTER_EXPORT_LOCK_FILE_NAME = '.after_export_action'.freeze
+ AFTER_EXPORT_LOCK_FILE_NAME = ".after_export_action"
private
diff --git a/lib/gitlab/import_export/after_export_strategies/web_upload_strategy.rb b/lib/gitlab/import_export/after_export_strategies/web_upload_strategy.rb
index b30900f7c61..ea458fbccbc 100644
--- a/lib/gitlab/import_export/after_export_strategies/web_upload_strategy.rb
+++ b/lib/gitlab/import_export/after_export_strategies/web_upload_strategy.rb
@@ -4,9 +4,9 @@ module Gitlab
module ImportExport
module AfterExportStrategies
class WebUploadStrategy < BaseAfterExportStrategy
- PUT_METHOD = 'PUT'.freeze
- POST_METHOD = 'POST'.freeze
- INVALID_HTTP_METHOD = 'invalid. Only PUT and POST methods allowed.'.freeze
+ PUT_METHOD = "PUT"
+ POST_METHOD = "POST"
+ INVALID_HTTP_METHOD = "invalid. Only PUT and POST methods allowed."
validates :url, url: true
@@ -30,8 +30,8 @@ module Gitlab
def handle_response_error(response)
unless response.success?
- error_code = response.dig('Error', 'Code') || response.code
- error_message = response.dig('Error', 'Message') || response.message
+ error_code = response.dig("Error", "Code") || response.code
+ error_message = response.dig("Error", "Message") || response.message
raise StrategyError.new("Error uploading the project. Code #{error_code}: #{error_message}")
end
@@ -42,7 +42,7 @@ module Gitlab
def send_file
Gitlab::HTTP.public_send(http_method.downcase, url, send_file_options) # rubocop:disable GitlabSecurity/PublicSend
ensure
- export_file.close if export_file
+ export_file&.close
end
def export_file
@@ -52,12 +52,12 @@ module Gitlab
def send_file_options
{
body_stream: export_file,
- headers: headers
+ headers: headers,
}
end
def headers
- { 'Content-Length' => export_size.to_s }
+ {"Content-Length" => export_size.to_s}
end
def export_size
diff --git a/lib/gitlab/import_export/after_export_strategy_builder.rb b/lib/gitlab/import_export/after_export_strategy_builder.rb
index 37394f46a99..7f07bd9cba7 100644
--- a/lib/gitlab/import_export/after_export_strategy_builder.rb
+++ b/lib/gitlab/import_export/after_export_strategy_builder.rb
@@ -9,7 +9,11 @@ module Gitlab
return default_strategy.new unless strategy_klass
attributes ||= {}
- klass = strategy_klass.constantize rescue nil
+ klass = begin
+ strategy_klass.constantize
+ rescue
+ nil
+ end
unless klass && klass < AfterExportStrategies::BaseAfterExportStrategy
raise StrategyNotFoundError.new("Strategy #{strategy_klass} not found")
diff --git a/lib/gitlab/import_export/attribute_cleaner.rb b/lib/gitlab/import_export/attribute_cleaner.rb
index 93b37b7bc5f..a29537fe4a9 100644
--- a/lib/gitlab/import_export/attribute_cleaner.rb
+++ b/lib/gitlab/import_export/attribute_cleaner.rb
@@ -3,7 +3,7 @@
module Gitlab
module ImportExport
class AttributeCleaner
- ALLOWED_REFERENCES = RelationFactory::PROJECT_REFERENCES + RelationFactory::USER_REFERENCES + ['group_id']
+ ALLOWED_REFERENCES = RelationFactory::PROJECT_REFERENCES + RelationFactory::USER_REFERENCES + ["group_id"]
def self.clean(*args)
new(*args).clean
@@ -16,15 +16,15 @@ module Gitlab
end
def clean
- @relation_hash.reject do |key, _value|
+ @relation_hash.reject { |key, _value|
prohibited_key?(key) || !@relation_class.attribute_method?(key) || excluded_key?(key)
- end.except('id')
+ }.except("id")
end
private
def prohibited_key?(key)
- key.end_with?('_id') && !ALLOWED_REFERENCES.include?(key)
+ key.end_with?("_id") && !ALLOWED_REFERENCES.include?(key)
end
def excluded_key?(key)
diff --git a/lib/gitlab/import_export/attributes_finder.rb b/lib/gitlab/import_export/attributes_finder.rb
index 409243e68a5..ff2d8e1a9d8 100644
--- a/lib/gitlab/import_export/attributes_finder.rb
+++ b/lib/gitlab/import_export/attributes_finder.rb
@@ -11,7 +11,7 @@ module Gitlab
def find(model_object)
parsed_hash = find_attributes_only(model_object)
- parsed_hash.empty? ? model_object : { model_object => parsed_hash }
+ parsed_hash.empty? ? model_object : {model_object => parsed_hash}
end
def parse(model_object)
@@ -21,17 +21,17 @@ module Gitlab
def find_included(value)
key = key_from_hash(value)
- @included_attributes[key].nil? ? {} : { only: @included_attributes[key] }
+ @included_attributes[key].nil? ? {} : {only: @included_attributes[key]}
end
def find_excluded(value)
key = key_from_hash(value)
- @excluded_attributes[key].nil? ? {} : { except: @excluded_attributes[key] }
+ @excluded_attributes[key].nil? ? {} : {except: @excluded_attributes[key]}
end
def find_method(value)
key = key_from_hash(value)
- @methods[key].nil? ? {} : { methods: @methods[key] }
+ @methods[key].nil? ? {} : {methods: @methods[key]}
end
def find_excluded_keys(klass_name)
diff --git a/lib/gitlab/import_export/avatar_restorer.rb b/lib/gitlab/import_export/avatar_restorer.rb
index be1b97bd7a7..93c68f43292 100644
--- a/lib/gitlab/import_export/avatar_restorer.rb
+++ b/lib/gitlab/import_export/avatar_restorer.rb
@@ -25,7 +25,7 @@ module Gitlab
end
def avatar_export_path
- File.join(@shared.export_path, 'avatar')
+ File.join(@shared.export_path, "avatar")
end
end
end
diff --git a/lib/gitlab/import_export/avatar_saver.rb b/lib/gitlab/import_export/avatar_saver.rb
index 47ca898c690..43f4f874738 100644
--- a/lib/gitlab/import_export/avatar_saver.rb
+++ b/lib/gitlab/import_export/avatar_saver.rb
@@ -14,7 +14,7 @@ module Gitlab
Gitlab::ImportExport::UploadsManager.new(
project: @project,
shared: @shared,
- relative_export_path: 'avatar'
+ relative_export_path: "avatar"
).save
rescue => e
@shared.error(e)
diff --git a/lib/gitlab/import_export/command_line_util.rb b/lib/gitlab/import_export/command_line_util.rb
index bdecff0931c..e54bdc525df 100644
--- a/lib/gitlab/import_export/command_line_util.rb
+++ b/lib/gitlab/import_export/command_line_util.rb
@@ -3,15 +3,15 @@
module Gitlab
module ImportExport
module CommandLineUtil
- UNTAR_MASK = 'u+rwX,go+rX,go-w'
- DEFAULT_DIR_MODE = 0700
+ UNTAR_MASK = "u+rwX,go+rX,go-w"
+ DEFAULT_DIR_MODE = 0o700
def tar_czf(archive:, dir:)
- tar_with_options(archive: archive, dir: dir, options: 'czf')
+ tar_with_options(archive: archive, dir: dir, options: "czf")
end
def untar_zxf(archive:, dir:)
- untar_with_options(archive: archive, dir: dir, options: 'zxf')
+ untar_with_options(archive: archive, dir: dir, options: "zxf")
end
def mkdir_p(path)
@@ -30,19 +30,19 @@ module Gitlab
end
def download(url, upload_path)
- File.open(upload_path, 'w') do |file|
+ File.open(upload_path, "w") do |file|
# Download (stream) file from the uploader's location
IO.copy_stream(URI.parse(url).open, file)
end
end
def tar_with_options(archive:, dir:, options:)
- execute(%W(tar -#{options} #{archive} -C #{dir} .))
+ execute(%W[tar -#{options} #{archive} -C #{dir} .])
end
def untar_with_options(archive:, dir:, options:)
- execute(%W(tar -#{options} #{archive} -C #{dir}))
- execute(%W(chmod -R #{UNTAR_MASK} #{dir}))
+ execute(%W[tar -#{options} #{archive} -C #{dir}])
+ execute(%W[chmod -R #{UNTAR_MASK} #{dir}])
end
def execute(cmd)
diff --git a/lib/gitlab/import_export/file_importer.rb b/lib/gitlab/import_export/file_importer.rb
index 05432f433e7..0406238a312 100644
--- a/lib/gitlab/import_export/file_importer.rb
+++ b/lib/gitlab/import_export/file_importer.rb
@@ -6,7 +6,7 @@ module Gitlab
include Gitlab::ImportExport::CommandLineUtil
MAX_RETRIES = 8
- IGNORED_FILENAMES = %w(. ..).freeze
+ IGNORED_FILENAMES = %w[. ..].freeze
def self.import(*args)
new(*args).import
diff --git a/lib/gitlab/import_export/group_project_object_builder.rb b/lib/gitlab/import_export/group_project_object_builder.rb
index 1c62591ed5a..62e6937a4d7 100644
--- a/lib/gitlab/import_export/group_project_object_builder.rb
+++ b/lib/gitlab/import_export/group_project_object_builder.rb
@@ -21,8 +21,8 @@ module Gitlab
def initialize(klass, attributes)
@klass = klass < Label ? Label : klass
@attributes = attributes
- @group = @attributes['group']
- @project = @attributes['project']
+ @group = @attributes["group"]
+ @project = @attributes["project"]
end
def find
@@ -36,12 +36,12 @@ module Gitlab
end
def where_clause
- @attributes.slice('title').map do |key, value|
+ @attributes.slice("title").map { |key, value|
scope_clause = table[:project_id].eq(@project.id)
scope_clause = scope_clause.or(table[:group_id].eq(@group.id)) if @group
table[key].eq(value).and(scope_clause)
- end.reduce(:or)
+ }.reduce(:or)
end
def table
@@ -49,13 +49,13 @@ module Gitlab
end
def project_attributes
- @attributes.except('group').tap do |atts|
+ @attributes.except("group").tap do |atts|
if label?
- atts['type'] = 'ProjectLabel' # Always create project labels
+ atts["type"] = "ProjectLabel" # Always create project labels
elsif milestone?
- if atts['group_id'] # Transform new group milestones into project ones
- atts['iid'] = nil
- atts.delete('group_id')
+ if atts["group_id"] # Transform new group milestones into project ones
+ atts["iid"] = nil
+ atts.delete("group_id")
else
claim_iid
end
@@ -79,7 +79,7 @@ module Gitlab
def claim_iid
# The milestone has to be a group milestone, as it's the only case where
# we set the IID as the maximum. The rest of them are fixed.
- milestone = @project.milestones.find_by(iid: @attributes['iid'])
+ milestone = @project.milestones.find_by(iid: @attributes["iid"])
return unless milestone
diff --git a/lib/gitlab/import_export/hash_util.rb b/lib/gitlab/import_export/hash_util.rb
index b6ce89a973b..75e18ab2dc4 100644
--- a/lib/gitlab/import_export/hash_util.rb
+++ b/lib/gitlab/import_export/hash_util.rb
@@ -16,8 +16,8 @@ module Gitlab
end
def self.deep_symbolize_array_with_date!(array)
- self.deep_symbolize_array!(array) do |hash|
- hash.select { |k, _v| k.to_s.end_with?('_date') }.each do |key, value|
+ deep_symbolize_array!(array) do |hash|
+ hash.select { |k, _v| k.to_s.end_with?("_date") }.each do |key, value|
hash[key] = Time.zone.parse(value)
end
end
diff --git a/lib/gitlab/import_export/importer.rb b/lib/gitlab/import_export/importer.rb
index 767f1b5de0e..1adf643b4d9 100644
--- a/lib/gitlab/import_export/importer.rb
+++ b/lib/gitlab/import_export/importer.rb
@@ -21,7 +21,7 @@ module Gitlab
if import_file && check_version! && restorers.all?(&:restore) && overwrite_project
project_tree.restored_project
else
- raise Projects::ImportService::Error.new(@shared.errors.join(', '))
+ raise Projects::ImportService::Error.new(@shared.errors.join(", "))
end
rescue => e
raise Projects::ImportService::Error.new(e.message)
@@ -33,7 +33,7 @@ module Gitlab
def restorers
[repo_restorer, wiki_restorer, project_tree, avatar_restorer,
- uploads_restorer, lfs_restorer, statistics_restorer]
+ uploads_restorer, lfs_restorer, statistics_restorer,]
end
def import_file
@@ -86,11 +86,11 @@ module Gitlab
end
def repo_path
- File.join(@shared.export_path, 'project.bundle')
+ File.join(@shared.export_path, "project.bundle")
end
def wiki_repo_path
- File.join(@shared.export_path, 'project.wiki.bundle')
+ File.join(@shared.export_path, "project.wiki.bundle")
end
def remove_import_file
@@ -109,14 +109,14 @@ module Gitlab
if overwrite_project?
::Projects::OverwriteProjectService.new(project, @current_user)
- .execute(project_to_overwrite)
+ .execute(project_to_overwrite)
end
true
end
def original_path
- @project.import_data&.data&.fetch('original_path', nil)
+ @project.import_data&.data&.fetch("original_path", nil)
end
def overwrite_project?
diff --git a/lib/gitlab/import_export/json_hash_builder.rb b/lib/gitlab/import_export/json_hash_builder.rb
index 477499e1688..a4ecc83142d 100644
--- a/lib/gitlab/import_export/json_hash_builder.rb
+++ b/lib/gitlab/import_export/json_hash_builder.rb
@@ -59,7 +59,7 @@ module Gitlab
# +value+ existing model to be included in the hash
# +json_config_hash+ the original hash containing the root model
def create_model_value(current_key, value, json_config_hash)
- json_config_hash[current_key] = parse_hash(value) || { include: value }
+ json_config_hash[current_key] = parse_hash(value) || {include: value}
end
# Calls attributes finder to parse the hash and add any attributes to it
@@ -70,7 +70,7 @@ module Gitlab
return nil if already_contains_methods?(value)
@attributes_finder.parse(value) do |hash|
- { include: hash_or_merge(value, hash) }
+ {include: hash_or_merge(value, hash)}
end
end
@@ -86,7 +86,7 @@ module Gitlab
# +json_config_hash+ the original hash containing the root model
def add_model_value(current_key, value, json_config_hash)
@attributes_finder.parse(value) do |hash|
- value = { value => hash } unless value.is_a?(Hash)
+ value = {value => hash} unless value.is_a?(Hash)
end
add_to_array(current_key, json_config_hash, value)
@@ -110,7 +110,7 @@ module Gitlab
# +hash+ hash containing configuration generated mainly from +@attributes_finder+
# +value+ existing model to be included in the hash
def hash_or_merge(value, hash)
- value.is_a?(Hash) ? value.merge(hash) : { value => hash }
+ value.is_a?(Hash) ? value.merge(hash) : {value => hash}
end
end
end
diff --git a/lib/gitlab/import_export/lfs_restorer.rb b/lib/gitlab/import_export/lfs_restorer.rb
index 345c7880e30..165a1c05d78 100644
--- a/lib/gitlab/import_export/lfs_restorer.rb
+++ b/lib/gitlab/import_export/lfs_restorer.rb
@@ -38,7 +38,7 @@ module Gitlab
end
def lfs_storage_path
- File.join(@shared.export_path, 'lfs-objects')
+ File.join(@shared.export_path, "lfs-objects")
end
end
end
diff --git a/lib/gitlab/import_export/lfs_saver.rb b/lib/gitlab/import_export/lfs_saver.rb
index 954f6f00078..10540b42220 100644
--- a/lib/gitlab/import_export/lfs_saver.rb
+++ b/lib/gitlab/import_export/lfs_saver.rb
@@ -36,7 +36,7 @@ module Gitlab
destination = destination_path_for_object(lfs_object)
mkdir_p(File.dirname(destination))
- File.open(destination, 'w') do |file|
+ File.open(destination, "w") do |file|
IO.copy_stream(URI.parse(lfs_object.file.url).open, file)
end
end
@@ -50,7 +50,7 @@ module Gitlab
end
def lfs_export_path
- File.join(@shared.export_path, 'lfs-objects')
+ File.join(@shared.export_path, "lfs-objects")
end
end
end
diff --git a/lib/gitlab/import_export/members_mapper.rb b/lib/gitlab/import_export/members_mapper.rb
index 6be95a16513..0846ba647c3 100644
--- a/lib/gitlab/import_export/members_mapper.rb
+++ b/lib/gitlab/import_export/members_mapper.rb
@@ -16,16 +16,14 @@ module Gitlab
def map
@map ||=
begin
- @exported_members.inject(missing_keys_tracking_hash) do |hash, member|
- if member['user']
- old_user_id = member['user']['id']
+ @exported_members.each_with_object(missing_keys_tracking_hash) do |member, hash|
+ if member["user"]
+ old_user_id = member["user"]["id"]
existing_user = User.where(find_project_user_query(member)).first
hash[old_user_id] = existing_user.id if existing_user && add_team_member(member, existing_user)
else
add_team_member(member)
end
-
- hash
end
end
end
@@ -35,7 +33,7 @@ module Gitlab
end
def include?(old_author_id)
- map.keys.include?(old_author_id) && map[old_author_id] != default_user_id
+ map.key?(old_author_id) && map[old_author_id] != default_user_id
end
private
@@ -53,13 +51,13 @@ module Gitlab
end
def add_team_member(member, existing_user = nil)
- member['user'] = existing_user
+ member["user"] = existing_user
ProjectMember.create(member_hash(member)).persisted?
end
def member_hash(member)
- parsed_hash(member).merge('source_id' => @project.id, 'importing' => true)
+ parsed_hash(member).merge("source_id" => @project.id, "importing" => true)
end
def parsed_hash(member)
@@ -68,7 +66,7 @@ module Gitlab
end
def find_project_user_query(member)
- user_arel[:email].eq(member['user']['email']).or(user_arel[:username].eq(member['user']['username']))
+ user_arel[:email].eq(member["user"]["email"]).or(user_arel[:username].eq(member["user"]["username"]))
end
def user_arel
diff --git a/lib/gitlab/import_export/merge_request_parser.rb b/lib/gitlab/import_export/merge_request_parser.rb
index 040a70d6775..8948b1b5a25 100644
--- a/lib/gitlab/import_export/merge_request_parser.rb
+++ b/lib/gitlab/import_export/merge_request_parser.rb
@@ -14,7 +14,7 @@ module Gitlab
def parse!
if fork_merge_request? && @diff_head_sha
- @merge_request.source_project_id = @relation_hash['project_id']
+ @merge_request.source_project_id = @relation_hash["project_id"]
fetch_ref unless branch_exists?(@merge_request.source_branch)
create_target_branch unless branch_exists?(@merge_request.target_branch)
@@ -41,7 +41,7 @@ module Gitlab
end
def fork_merge_request?
- @relation_hash['source_project_id'] == FORKED_PROJECT_ID
+ @relation_hash["source_project_id"] == FORKED_PROJECT_ID
end
end
end
diff --git a/lib/gitlab/import_export/project_tree_restorer.rb b/lib/gitlab/import_export/project_tree_restorer.rb
index 51001750a6c..6504d4d813d 100644
--- a/lib/gitlab/import_export/project_tree_restorer.rb
+++ b/lib/gitlab/import_export/project_tree_restorer.rb
@@ -7,7 +7,7 @@ module Gitlab
GROUP_MODELS = [GroupLabel, Milestone].freeze
def initialize(user:, shared:, project:)
- @path = File.join(shared.export_path, 'project.json')
+ @path = File.join(shared.export_path, "project.json")
@user = user
@shared = shared
@project = project
@@ -21,10 +21,10 @@ module Gitlab
@tree_hash = ActiveSupport::JSON.decode(json)
rescue => e
Rails.logger.error("Import/Export error: #{e.message}")
- raise Gitlab::ImportExport::Error.new('Incorrect JSON format')
+ raise Gitlab::ImportExport::Error.new("Incorrect JSON format")
end
- @project_members = @tree_hash.delete('project_members')
+ @project_members = @tree_hash.delete("project_members")
RelationRenameService.rename(@tree_hash)
@@ -117,21 +117,21 @@ module Gitlab
end
def override_params
- @override_params ||= @project.import_data&.data&.fetch('override_params', nil) || {}
+ @override_params ||= @project.import_data&.data&.fetch("override_params", nil) || {}
end
def json_params
- @json_params ||= @tree_hash.reject do |key, value|
+ @json_params ||= @tree_hash.reject { |key, value|
# return params that are not 1 to many or 1 to 1 relations
value.respond_to?(:each) && !Project.column_names.include?(key)
- end
+ }
end
def visibility_level
- level = override_params['visibility_level'] || json_params['visibility_level'] || @project.visibility_level
+ level = override_params["visibility_level"] || json_params["visibility_level"] || @project.visibility_level
level = @project.group.visibility_level if @project.group && level > @project.group.visibility_level
- { 'visibility_level' => level }
+ {"visibility_level" => level}
end
# Given a relation hash containing one or more models and its relationships,
@@ -202,14 +202,14 @@ module Gitlab
end
def create_relation(relation, relation_hash_list)
- relation_array = [relation_hash_list].flatten.map do |relation_hash|
+ relation_array = [relation_hash_list].flatten.map { |relation_hash|
Gitlab::ImportExport::RelationFactory.create(relation_sym: relation.to_sym,
relation_hash: relation_hash,
members_mapper: members_mapper,
user: @user,
project: @restored_project,
excluded_keys: excluded_keys_for_relation(relation))
- end.compact
+ }.compact
relation_hash_list.is_a?(Array) ? relation_array : relation_array.first
end
@@ -223,7 +223,7 @@ module Gitlab
end
def nil_iid_pipeline?(relation_key, relation_item)
- relation_key == 'ci_pipelines' && relation_item['iid'].nil?
+ relation_key == "ci_pipelines" && relation_item["iid"].nil?
end
end
end
diff --git a/lib/gitlab/import_export/project_tree_saver.rb b/lib/gitlab/import_export/project_tree_saver.rb
index 2255635acdf..4b331753582 100644
--- a/lib/gitlab/import_export/project_tree_saver.rb
+++ b/lib/gitlab/import_export/project_tree_saver.rb
@@ -29,10 +29,10 @@ module Gitlab
def project_json_tree
if @params[:description].present?
- project_json['description'] = @params[:description]
+ project_json["description"] = @params[:description]
end
- project_json['project_members'] += group_members_json
+ project_json["project_members"] += group_members_json
RelationRenameService.add_new_associations(project_json)
@@ -49,7 +49,7 @@ module Gitlab
def group_members_json
group_members.as_json(reader.group_members_tree).each do |group_member|
- group_member['source_type'] = 'Project' # Make group members project members of the future import
+ group_member["source_type"] = "Project" # Make group members project members of the future import
end
end
diff --git a/lib/gitlab/import_export/relation_factory.rb b/lib/gitlab/import_export/relation_factory.rb
index 099b488f68e..89a20114ae4 100644
--- a/lib/gitlab/import_export/relation_factory.rb
+++ b/lib/gitlab/import_export/relation_factory.rb
@@ -3,29 +3,29 @@
module Gitlab
module ImportExport
class RelationFactory
- OVERRIDES = { snippets: :project_snippets,
- ci_pipelines: 'Ci::Pipeline',
- pipelines: 'Ci::Pipeline',
- stages: 'Ci::Stage',
- statuses: 'commit_status',
- triggers: 'Ci::Trigger',
- pipeline_schedules: 'Ci::PipelineSchedule',
- builds: 'Ci::Build',
- runners: 'Ci::Runner',
- hooks: 'ProjectHook',
- merge_access_levels: 'ProtectedBranch::MergeAccessLevel',
- push_access_levels: 'ProtectedBranch::PushAccessLevel',
- create_access_levels: 'ProtectedTag::CreateAccessLevel',
- labels: :project_labels,
- priorities: :label_priorities,
- auto_devops: :project_auto_devops,
- label: :project_label,
- custom_attributes: 'ProjectCustomAttribute',
- project_badges: 'Badge',
- metrics: 'MergeRequest::Metrics',
- ci_cd_settings: 'ProjectCiCdSetting',
- error_tracking_setting: 'ErrorTracking::ProjectErrorTrackingSetting',
- links: 'Releases::Link' }.freeze
+ OVERRIDES = {snippets: :project_snippets,
+ ci_pipelines: "Ci::Pipeline",
+ pipelines: "Ci::Pipeline",
+ stages: "Ci::Stage",
+ statuses: "commit_status",
+ triggers: "Ci::Trigger",
+ pipeline_schedules: "Ci::PipelineSchedule",
+ builds: "Ci::Build",
+ runners: "Ci::Runner",
+ hooks: "ProjectHook",
+ merge_access_levels: "ProtectedBranch::MergeAccessLevel",
+ push_access_levels: "ProtectedBranch::PushAccessLevel",
+ create_access_levels: "ProtectedTag::CreateAccessLevel",
+ labels: :project_labels,
+ priorities: :label_priorities,
+ auto_devops: :project_auto_devops,
+ label: :project_label,
+ custom_attributes: "ProjectCustomAttribute",
+ project_badges: "Badge",
+ metrics: "MergeRequest::Metrics",
+ ci_cd_settings: "ProjectCiCdSetting",
+ error_tracking_setting: "ErrorTracking::ProjectErrorTrackingSetting",
+ links: "Releases::Link",}.freeze
USER_REFERENCES = %w[author_id assignee_id updated_by_id merged_by_id latest_closed_by_id user_id created_by_id last_edited_by_id merge_user_id resolved_by_id closed_by_id].freeze
@@ -33,7 +33,7 @@ module Gitlab
BUILD_MODELS = %w[Ci::Build commit_status].freeze
- IMPORTED_OBJECT_MAX_RETRIES = 5.freeze
+ IMPORTED_OBJECT_MAX_RETRIES = 5
EXISTING_OBJECT_CHECK = %i[milestone milestones label labels project_label project_labels group_label group_labels project_feature].freeze
@@ -54,13 +54,13 @@ module Gitlab
def initialize(relation_sym:, relation_hash:, members_mapper:, user:, project:, excluded_keys: [])
@relation_name = self.class.overrides[relation_sym] || relation_sym
- @relation_hash = relation_hash.except('noteable_id')
+ @relation_hash = relation_hash.except("noteable_id")
@members_mapper = members_mapper
@user = user
@project = project
@imported_object_retries = 0
- @relation_hash['project_id'] = @project.id
+ @relation_hash["project_id"] = @project.id
# Remove excluded keys from relation_hash
# We don't do this in the parsed_relation_hash because of the 'transformed attributes'
@@ -99,7 +99,7 @@ module Gitlab
update_group_references
remove_duplicate_assignees
- setup_pipeline if @relation_name == 'Ci::Pipeline'
+ setup_pipeline if @relation_name == "Ci::Pipeline"
reset_tokens!
remove_encrypted_attributes!
@@ -114,17 +114,17 @@ module Gitlab
end
def remove_duplicate_assignees
- return unless @relation_hash['issue_assignees']
+ return unless @relation_hash["issue_assignees"]
# When an assignee did not exist in the members mapper, the importer is
# assigned. We only need to assign each user once.
- @relation_hash['issue_assignees'].uniq!(&:user_id)
+ @relation_hash["issue_assignees"].uniq!(&:user_id)
end
def setup_note
set_note_author
# attachment is deprecated and note uploads are handled by Markdown uploader
- @relation_hash['attachment'] = nil
+ @relation_hash["attachment"] = nil
end
# Sets the author for a note. If the user importing the project
@@ -132,10 +132,10 @@ module Gitlab
# will be used. Otherwise, a note stating the original author name
# is left.
def set_note_author
- old_author_id = @relation_hash['author_id']
- author = @relation_hash.delete('author')
+ old_author_id = @relation_hash["author_id"]
+ author = @relation_hash.delete("author")
- update_note_for_missing_author(author['name']) unless has_author?(old_author_id)
+ update_note_for_missing_author(author["name"]) unless has_author?(old_author_id)
end
def has_author?(old_author_id)
@@ -143,19 +143,19 @@ module Gitlab
end
def missing_author_note(updated_at, author_name)
- timestamp = updated_at.split('.').first
+ timestamp = updated_at.split(".").first
"\n\n *By #{author_name} on #{timestamp} (imported from GitLab project)*"
end
def generate_imported_object
if BUILD_MODELS.include?(@relation_name)
- @relation_hash.delete('trace') # old export files have trace
- @relation_hash.delete('token')
- @relation_hash.delete('commands')
+ @relation_hash.delete("trace") # old export files have trace
+ @relation_hash.delete("token")
+ @relation_hash.delete("commands")
imported_object
elsif @relation_name == :merge_requests
- MergeRequestParser.new(@project, @relation_hash.delete('diff_head_sha'), imported_object, @relation_hash).parse!
+ MergeRequestParser.new(@project, @relation_hash.delete("diff_head_sha"), imported_object, @relation_hash).parse!
else
imported_object
end
@@ -163,22 +163,22 @@ module Gitlab
def update_project_references
# If source and target are the same, populate them with the new project ID.
- if @relation_hash['source_project_id']
- @relation_hash['source_project_id'] = same_source_and_target? ? @relation_hash['project_id'] : MergeRequestParser::FORKED_PROJECT_ID
+ if @relation_hash["source_project_id"]
+ @relation_hash["source_project_id"] = same_source_and_target? ? @relation_hash["project_id"] : MergeRequestParser::FORKED_PROJECT_ID
end
- @relation_hash['target_project_id'] = @relation_hash['project_id'] if @relation_hash['target_project_id']
+ @relation_hash["target_project_id"] = @relation_hash["project_id"] if @relation_hash["target_project_id"]
end
def same_source_and_target?
- @relation_hash['target_project_id'] && @relation_hash['target_project_id'] == @relation_hash['source_project_id']
+ @relation_hash["target_project_id"] && @relation_hash["target_project_id"] == @relation_hash["source_project_id"]
end
def update_group_references
return unless EXISTING_OBJECT_CHECK.include?(@relation_name)
- return unless @relation_hash['group_id']
+ return unless @relation_hash["group_id"]
- @relation_hash['group_id'] = @project.group&.id
+ @relation_hash["group_id"] = @project.group&.id
end
def reset_tokens!
@@ -186,7 +186,7 @@ module Gitlab
# If we import/export a project to the same instance, tokens will have to be reset.
# We also have to reset them to avoid issues when the gitlab secrets file cannot be copied across.
- relation_class.attribute_names.select { |name| name.include?('token') }.each do |token|
+ relation_class.attribute_names.select { |name| name.include?("token") }.each do |token|
@relation_hash[token] = nil
end
end
@@ -217,8 +217,8 @@ module Gitlab
end
def update_note_for_missing_author(author_name)
- @relation_hash['note'] = '*Blank note*' if @relation_hash['note'].blank?
- @relation_hash['note'] = "#{@relation_hash['note']}#{missing_author_note(@relation_hash['updated_at'], author_name)}"
+ @relation_hash["note"] = "*Blank note*" if @relation_hash["note"].blank?
+ @relation_hash["note"] = "#{@relation_hash["note"]}#{missing_author_note(@relation_hash["updated_at"], author_name)}"
end
def admin_user?
@@ -231,11 +231,11 @@ module Gitlab
end
def setup_diff
- @relation_hash['diff'] = @relation_hash.delete('utf8_diff')
+ @relation_hash["diff"] = @relation_hash.delete("utf8_diff")
end
def setup_pipeline
- @relation_hash.fetch('stages').each do |stage|
+ @relation_hash.fetch("stages").each do |stage|
stage.statuses.each do |status|
status.pipeline = imported_object
end
@@ -247,7 +247,7 @@ module Gitlab
# Otherwise always create the record, skipping the extra SELECT clause.
@existing_or_new_object ||= begin
if EXISTING_OBJECT_CHECK.include?(@relation_name)
- attribute_hash = attribute_hash_for(['events'])
+ attribute_hash = attribute_hash_for(["events"])
existing_object.assign_attributes(attribute_hash) if attribute_hash.any?
@@ -259,9 +259,8 @@ module Gitlab
end
def attribute_hash_for(attributes)
- attributes.inject({}) do |hash, value|
+ attributes.each_with_object({}) do |value, hash|
hash[value] = parsed_relation_hash.delete(value) if parsed_relation_hash[value]
- hash
end
end
@@ -270,8 +269,8 @@ module Gitlab
end
def unknown_service?
- @relation_name == :services && parsed_relation_hash['type'] &&
- !Object.const_defined?(parsed_relation_hash['type'])
+ @relation_name == :services && parsed_relation_hash["type"] &&
+ !Object.const_defined?(parsed_relation_hash["type"])
end
def find_or_create_object!
@@ -279,9 +278,9 @@ module Gitlab
# Can't use IDs as validation exists calling `group` or `project` attributes
finder_hash = parsed_relation_hash.tap do |hash|
- hash['group'] = @project.group if relation_class.attribute_method?('group_id')
- hash['project'] = @project
- hash.delete('project_id')
+ hash["group"] = @project.group if relation_class.attribute_method?("group_id")
+ hash["project"] = @project
+ hash.delete("project_id")
end
GroupProjectObjectBuilder.build(relation_class, finder_hash)
diff --git a/lib/gitlab/import_export/relation_rename_service.rb b/lib/gitlab/import_export/relation_rename_service.rb
index 179bde5e21e..45949d912c0 100644
--- a/lib/gitlab/import_export/relation_rename_service.rb
+++ b/lib/gitlab/import_export/relation_rename_service.rb
@@ -20,7 +20,7 @@ module Gitlab
module ImportExport
class RelationRenameService
RENAMES = {
- 'pipelines' => 'ci_pipelines' # Added in 11.6, remove in 11.7
+ "pipelines" => "ci_pipelines", # Added in 11.6, remove in 11.7
}.freeze
def self.rename(tree_hash)
diff --git a/lib/gitlab/import_export/shared.rb b/lib/gitlab/import_export/shared.rb
index 725c1101d70..c04e192f686 100644
--- a/lib/gitlab/import_export/shared.rb
+++ b/lib/gitlab/import_export/shared.rb
@@ -12,7 +12,7 @@ module Gitlab
end
def active_export_count
- Dir[File.join(archive_path, '*')].count { |name| File.directory?(name) }
+ Dir[File.join(archive_path, "*")].count { |name| File.directory?(name) }
end
def export_path
@@ -60,10 +60,10 @@ module Gitlab
def log_base_data
{
- importer: 'Import/Export',
+ importer: "Import/Export",
import_jid: @project&.import_state&.jid,
project_id: @project&.id,
- project_path: @project&.full_path
+ project_path: @project&.full_path,
}
end
diff --git a/lib/gitlab/import_export/uploads_manager.rb b/lib/gitlab/import_export/uploads_manager.rb
index e232198150a..2bc4e3801bc 100644
--- a/lib/gitlab/import_export/uploads_manager.rb
+++ b/lib/gitlab/import_export/uploads_manager.rb
@@ -7,7 +7,7 @@ module Gitlab
UPLOADS_BATCH_SIZE = 100
- def initialize(project:, shared:, relative_export_path: 'uploads')
+ def initialize(project:, shared:, relative_export_path: "uploads")
@project = project
@shared = shared
@relative_export_path = relative_export_path
@@ -40,7 +40,7 @@ module Gitlab
def add_upload(upload)
uploader_context = FileUploader.extract_dynamic_path(upload).named_captures.symbolize_keys
- UploadService.new(@project, File.open(upload, 'r'), FileUploader, uploader_context).execute.to_h
+ UploadService.new(@project, File.open(upload, "r"), FileUploader, uploader_context).execute.to_h
end
def copy_project_uploads
@@ -64,7 +64,7 @@ module Gitlab
def each_uploader
avatar_path = @project.avatar&.upload&.path
- if @relative_export_path == 'avatar'
+ if @relative_export_path == "avatar"
yield(@project.avatar)
else
project_uploads_except_avatar(avatar_path).find_each(batch_size: UPLOADS_BATCH_SIZE) do |upload|
@@ -80,7 +80,7 @@ module Gitlab
end
def download_and_copy(upload)
- secret = upload.try(:secret) || ''
+ secret = upload.try(:secret) || ""
upload_path = File.join(uploads_export_path, secret, upload.filename)
mkdir_p(File.join(uploads_export_path, secret))
diff --git a/lib/gitlab/import_export/version_checker.rb b/lib/gitlab/import_export/version_checker.rb
index 6d978d00ea5..2409eedf8ed 100644
--- a/lib/gitlab/import_export/version_checker.rb
+++ b/lib/gitlab/import_export/version_checker.rb
@@ -37,7 +37,7 @@ module Gitlab
Gem::Version.new(version) != Gem::Version.new(Gitlab::ImportExport.version)
rescue => e
Rails.logger.error("Import/Export error: #{e.message}")
- raise Gitlab::ImportExport::Error.new('Incorrect VERSION format')
+ raise Gitlab::ImportExport::Error.new("Incorrect VERSION format")
end
end
end
diff --git a/lib/gitlab/import_export/version_saver.rb b/lib/gitlab/import_export/version_saver.rb
index 8230c0f1e77..b09807f3a5b 100644
--- a/lib/gitlab/import_export/version_saver.rb
+++ b/lib/gitlab/import_export/version_saver.rb
@@ -12,7 +12,7 @@ module Gitlab
def save
mkdir_p(@shared.export_path)
- File.write(version_file, Gitlab::ImportExport.version, mode: 'w')
+ File.write(version_file, Gitlab::ImportExport.version, mode: "w")
rescue => e
@shared.error(e)
false
diff --git a/lib/gitlab/import_sources.rb b/lib/gitlab/import_sources.rb
index 67952ca0f2d..bef3aac47c7 100644
--- a/lib/gitlab/import_sources.rb
+++ b/lib/gitlab/import_sources.rb
@@ -11,16 +11,16 @@ module Gitlab
# We exclude `bare_repository` here as it has no import class associated
IMPORT_TABLE = [
- ImportSource.new('github', 'GitHub', Gitlab::GithubImport::ParallelImporter),
- ImportSource.new('bitbucket', 'Bitbucket Cloud', Gitlab::BitbucketImport::Importer),
- ImportSource.new('bitbucket_server', 'Bitbucket Server', Gitlab::BitbucketServerImport::Importer),
- ImportSource.new('gitlab', 'GitLab.com', Gitlab::GitlabImport::Importer),
- ImportSource.new('google_code', 'Google Code', Gitlab::GoogleCodeImport::Importer),
- ImportSource.new('fogbugz', 'FogBugz', Gitlab::FogbugzImport::Importer),
- ImportSource.new('git', 'Repo by URL', nil),
- ImportSource.new('gitlab_project', 'GitLab export', Gitlab::ImportExport::Importer),
- ImportSource.new('gitea', 'Gitea', Gitlab::LegacyGithubImport::Importer),
- ImportSource.new('manifest', 'Manifest file', nil)
+ ImportSource.new("github", "GitHub", Gitlab::GithubImport::ParallelImporter),
+ ImportSource.new("bitbucket", "Bitbucket Cloud", Gitlab::BitbucketImport::Importer),
+ ImportSource.new("bitbucket_server", "Bitbucket Server", Gitlab::BitbucketServerImport::Importer),
+ ImportSource.new("gitlab", "GitLab.com", Gitlab::GitlabImport::Importer),
+ ImportSource.new("google_code", "Google Code", Gitlab::GoogleCodeImport::Importer),
+ ImportSource.new("fogbugz", "FogBugz", Gitlab::FogbugzImport::Importer),
+ ImportSource.new("git", "Repo by URL", nil),
+ ImportSource.new("gitlab_project", "GitLab export", Gitlab::ImportExport::Importer),
+ ImportSource.new("gitea", "Gitea", Gitlab::LegacyGithubImport::Importer),
+ ImportSource.new("manifest", "Manifest file", nil),
].freeze
class << self
diff --git a/lib/gitlab/incoming_email.rb b/lib/gitlab/incoming_email.rb
index cc0c633b943..f94820ba9ba 100644
--- a/lib/gitlab/incoming_email.rb
+++ b/lib/gitlab/incoming_email.rb
@@ -2,9 +2,9 @@
module Gitlab
module IncomingEmail
- UNSUBSCRIBE_SUFFIX = '-unsubscribe'.freeze
- UNSUBSCRIBE_SUFFIX_LEGACY = '+unsubscribe'.freeze
- WILDCARD_PLACEHOLDER = '%{key}'.freeze
+ UNSUBSCRIBE_SUFFIX = "-unsubscribe"
+ UNSUBSCRIBE_SUFFIX_LEGACY = "+unsubscribe"
+ WILDCARD_PLACEHOLDER = "%{key}"
class << self
def enabled?
@@ -12,7 +12,7 @@ module Gitlab
end
def supports_wildcard?
- config.address && config.address.include?(WILDCARD_PLACEHOLDER)
+ config.address&.include?(WILDCARD_PLACEHOLDER)
end
def supports_issue_creation?
@@ -60,7 +60,7 @@ module Gitlab
return nil unless wildcard_address
regex = Regexp.escape(wildcard_address)
- regex = regex.sub(Regexp.escape(WILDCARD_PLACEHOLDER), '(.+)')
+ regex = regex.sub(Regexp.escape(WILDCARD_PLACEHOLDER), "(.+)")
Regexp.new(/\A#{regex}\z/).freeze
end
end
diff --git a/lib/gitlab/insecure_key_fingerprint.rb b/lib/gitlab/insecure_key_fingerprint.rb
index e4f0e9d2c73..3a73347ceaf 100644
--- a/lib/gitlab/insecure_key_fingerprint.rb
+++ b/lib/gitlab/insecure_key_fingerprint.rb
@@ -19,7 +19,7 @@ module Gitlab
end
def fingerprint
- OpenSSL::Digest::MD5.hexdigest(Base64.decode64(@key)).scan(/../).join(':')
+ OpenSSL::Digest::MD5.hexdigest(Base64.decode64(@key)).scan(/../).join(":")
end
end
end
diff --git a/lib/gitlab/issuable_metadata.rb b/lib/gitlab/issuable_metadata.rb
index 351d15605e0..eecbab37467 100644
--- a/lib/gitlab/issuable_metadata.rb
+++ b/lib/gitlab/issuable_metadata.rb
@@ -8,7 +8,7 @@ module Gitlab
issuable_collection.respond_to?(:limit_value) &&
issuable_collection.limit_value.nil?
- raise 'Collection must have a limit applied for preloading meta-data'
+ raise "Collection must have a limit applied for preloading meta-data"
end
# map has to be used here since using pluck or select will
@@ -22,7 +22,7 @@ module Gitlab
issuable_note_count = ::Note.count_for_collection(issuable_ids, collection_type)
issuable_votes_count = ::AwardEmoji.votes_for_collection(issuable_ids, collection_type)
issuable_merge_requests_count =
- if collection_type == 'Issue'
+ if collection_type == "Issue"
::MergeRequestsClosingIssues.count_for_collection(issuable_ids)
else
[]
diff --git a/lib/gitlab/issuable_sorter.rb b/lib/gitlab/issuable_sorter.rb
index 42bbfb32d0b..a4583f5fe11 100644
--- a/lib/gitlab/issuable_sorter.rb
+++ b/lib/gitlab/issuable_sorter.rb
@@ -4,7 +4,7 @@ module Gitlab
module IssuableSorter
class << self
def sort(project, issuables, &sort_key)
- grouped_items = issuables.group_by do |issuable|
+ grouped_items = issuables.group_by { |issuable|
if issuable.project.id == project.id
:project_ref
elsif issuable.project.namespace.id == project.namespace.id
@@ -12,7 +12,7 @@ module Gitlab
else
:full_ref
end
- end
+ }
natural_sort_issuables(grouped_items[:project_ref], project) +
natural_sort_issuables(grouped_items[:namespace_ref], project) +
diff --git a/lib/gitlab/issues_labels.rb b/lib/gitlab/issues_labels.rb
index 17c9cb969df..a363d6283ad 100644
--- a/lib/gitlab/issues_labels.rb
+++ b/lib/gitlab/issues_labels.rb
@@ -4,20 +4,20 @@ module Gitlab
class IssuesLabels
class << self
def generate(project)
- red = '#d9534f'
- yellow = '#f0ad4e'
- blue = '#428bca'
- green = '#5cb85c'
+ red = "#d9534f"
+ yellow = "#f0ad4e"
+ blue = "#428bca"
+ green = "#5cb85c"
labels = [
- { title: "bug", color: red },
- { title: "critical", color: red },
- { title: "confirmed", color: red },
- { title: "documentation", color: yellow },
- { title: "support", color: yellow },
- { title: "discussion", color: blue },
- { title: "suggestion", color: blue },
- { title: "enhancement", color: green }
+ {title: "bug", color: red},
+ {title: "critical", color: red},
+ {title: "confirmed", color: red},
+ {title: "documentation", color: yellow},
+ {title: "support", color: yellow},
+ {title: "discussion", color: blue},
+ {title: "suggestion", color: blue},
+ {title: "enhancement", color: green},
]
labels.each do |params|
diff --git a/lib/gitlab/job_waiter.rb b/lib/gitlab/job_waiter.rb
index e97e961771c..90dbe4d005d 100644
--- a/lib/gitlab/job_waiter.rb
+++ b/lib/gitlab/job_waiter.rb
@@ -17,7 +17,7 @@ module Gitlab
# push to that array when done. Once the waiter has popped `count` items, it
# knows all the jobs are done.
class JobWaiter
- KEY_PREFIX = "gitlab:job_waiter".freeze
+ KEY_PREFIX = "gitlab:job_waiter"
def self.notify(key, jid)
Gitlab::Redis::SharedState.with { |redis| redis.lpush(key, jid) }
diff --git a/lib/gitlab/json_cache.rb b/lib/gitlab/json_cache.rb
index 1adf83739ad..fc7c527e3d0 100644
--- a/lib/gitlab/json_cache.rb
+++ b/lib/gitlab/json_cache.rb
@@ -25,7 +25,7 @@ module Gitlab
expanded_cache_key << Rails.version
end
- expanded_cache_key.join(':')
+ expanded_cache_key.join(":")
end
def expire(key)
diff --git a/lib/gitlab/kubernetes.rb b/lib/gitlab/kubernetes.rb
index a9957a85d48..e8d25dc4fa5 100644
--- a/lib/gitlab/kubernetes.rb
+++ b/lib/gitlab/kubernetes.rb
@@ -10,7 +10,7 @@ module Gitlab
# This is the comand that is run to start a terminal session. Kubernetes
# expects `command=foo&command=bar, not `command[]=foo&command[]=bar`
EXEC_COMMAND = URI.encode_www_form(
- ['sh', '-c', 'bash || sh'].map { |value| ['command', value] }
+ ["sh", "-c", "bash || sh"].map { |value| ["command", value] }
)
# Filters an array of pods (as returned by the kubernetes API) by their labels
@@ -36,22 +36,26 @@ module Gitlab
return unless containers.present? && pod_name.present? && phase == "Running"
- created_at = DateTime.parse(metadata["creationTimestamp"]) rescue nil
+ created_at = begin
+ DateTime.parse(metadata["creationTimestamp"])
+ rescue
+ nil
+ end
containers.map do |container|
{
- selectors: { pod: pod_name, container: container["name"] },
- url: container_exec_url(api_url, namespace, pod_name, container["name"]),
- subprotocols: ['channel.k8s.io'],
- headers: ::Gitlab::Kubernetes.build_header_hash,
- created_at: created_at
+ selectors: {pod: pod_name, container: container["name"]},
+ url: container_exec_url(api_url, namespace, pod_name, container["name"]),
+ subprotocols: ["channel.k8s.io"],
+ headers: ::Gitlab::Kubernetes.build_header_hash,
+ created_at: created_at,
}
end
end
def add_terminal_auth(terminal, token:, max_session_time:, ca_pem: nil)
terminal[:headers] ||= ::Gitlab::Kubernetes.build_header_hash
- terminal[:headers]['Authorization'] << "Bearer #{token}"
+ terminal[:headers]["Authorization"] << "Bearer #{token}"
terminal[:max_session_time] = max_session_time
terminal[:ca_pem] = ca_pem if ca_pem.present?
end
@@ -59,26 +63,26 @@ module Gitlab
def container_exec_url(api_url, namespace, pod_name, container_name)
url = URI.parse(api_url)
url.path = [
- url.path.sub(%r{/+\z}, ''),
- 'api', 'v1',
- 'namespaces', ERB::Util.url_encode(namespace),
- 'pods', ERB::Util.url_encode(pod_name),
- 'exec'
- ].join('/')
+ url.path.sub(%r{/+\z}, ""),
+ "api", "v1",
+ "namespaces", ERB::Util.url_encode(namespace),
+ "pods", ERB::Util.url_encode(pod_name),
+ "exec",
+ ].join("/")
url.query = {
container: container_name,
tty: true,
stdin: true,
stdout: true,
- stderr: true
- }.to_query + '&' + EXEC_COMMAND
+ stderr: true,
+ }.to_query + "&" + EXEC_COMMAND
case url.scheme
- when 'http'
- url.scheme = 'ws'
- when 'https'
- url.scheme = 'wss'
+ when "http"
+ url.scheme = "ws"
+ when "https"
+ url.scheme = "wss"
end
url.to_s
@@ -88,29 +92,29 @@ module Gitlab
return unless token.present?
config = {
- apiVersion: 'v1',
+ apiVersion: "v1",
clusters: [
- name: 'gitlab-deploy',
+ name: "gitlab-deploy",
cluster: {
- server: url
- }
+ server: url,
+ },
],
contexts: [
- name: 'gitlab-deploy',
+ name: "gitlab-deploy",
context: {
- cluster: 'gitlab-deploy',
+ cluster: "gitlab-deploy",
namespace: namespace,
- user: 'gitlab-deploy'
- }
+ user: "gitlab-deploy",
+ },
],
- 'current-context': 'gitlab-deploy',
- kind: 'Config',
+ 'current-context': "gitlab-deploy",
+ kind: "Config",
users: [
{
- name: 'gitlab-deploy',
- user: { token: token }
- }
- ]
+ name: "gitlab-deploy",
+ user: {token: token},
+ },
+ ],
}
kubeconfig_embed_ca_pem(config, ca_pem) if ca_pem
diff --git a/lib/gitlab/kubernetes/cluster_role_binding.rb b/lib/gitlab/kubernetes/cluster_role_binding.rb
index ebea8aff5be..1cc94359790 100644
--- a/lib/gitlab/kubernetes/cluster_role_binding.rb
+++ b/lib/gitlab/kubernetes/cluster_role_binding.rb
@@ -22,14 +22,14 @@ module Gitlab
private
def metadata
- { name: name }
+ {name: name}
end
def role_ref
{
- apiGroup: 'rbac.authorization.k8s.io',
- kind: 'ClusterRole',
- name: cluster_role_name
+ apiGroup: "rbac.authorization.k8s.io",
+ kind: "ClusterRole",
+ name: cluster_role_name,
}
end
end
diff --git a/lib/gitlab/kubernetes/config_map.rb b/lib/gitlab/kubernetes/config_map.rb
index 0bcaaa03974..9e7c5352e69 100644
--- a/lib/gitlab/kubernetes/config_map.rb
+++ b/lib/gitlab/kubernetes/config_map.rb
@@ -27,7 +27,7 @@ module Gitlab
{
name: config_map_name,
namespace: namespace,
- labels: { name: config_map_name }
+ labels: {name: config_map_name},
}
end
diff --git a/lib/gitlab/kubernetes/helm.rb b/lib/gitlab/kubernetes/helm.rb
index 42c4745ff98..baf4fa04423 100644
--- a/lib/gitlab/kubernetes/helm.rb
+++ b/lib/gitlab/kubernetes/helm.rb
@@ -3,12 +3,12 @@
module Gitlab
module Kubernetes
module Helm
- HELM_VERSION = '2.12.3'.freeze
- KUBECTL_VERSION = '1.11.7'.freeze
- NAMESPACE = 'gitlab-managed-apps'.freeze
- SERVICE_ACCOUNT = 'tiller'.freeze
- CLUSTER_ROLE_BINDING = 'tiller-admin'.freeze
- CLUSTER_ROLE = 'cluster-admin'.freeze
+ HELM_VERSION = "2.12.3"
+ KUBECTL_VERSION = "1.11.7"
+ NAMESPACE = "gitlab-managed-apps"
+ SERVICE_ACCOUNT = "tiller"
+ CLUSTER_ROLE_BINDING = "tiller-admin"
+ CLUSTER_ROLE = "cluster-admin"
end
end
end
diff --git a/lib/gitlab/kubernetes/helm/api.rb b/lib/gitlab/kubernetes/helm/api.rb
index 7dfd9ed4f35..37be5d0b533 100644
--- a/lib/gitlab/kubernetes/helm/api.rb
+++ b/lib/gitlab/kubernetes/helm/api.rb
@@ -20,7 +20,7 @@ module Gitlab
kubeclient.create_pod(command.pod_resource)
end
- alias_method :update, :install
+ alias update install
##
# Returns Pod phase
diff --git a/lib/gitlab/kubernetes/helm/certificate.rb b/lib/gitlab/kubernetes/helm/certificate.rb
index 598714e0874..8c8ae0d704f 100644
--- a/lib/gitlab/kubernetes/helm/certificate.rb
+++ b/lib/gitlab/kubernetes/helm/certificate.rb
@@ -1,4 +1,5 @@
# frozen_string_literal: true
+
module Gitlab
module Kubernetes
module Helm
@@ -53,9 +54,9 @@ module Gitlab
extension_factory = OpenSSL::X509::ExtensionFactory.new
extension_factory.subject_certificate = cert
extension_factory.issuer_certificate = cert
- cert.add_extension(extension_factory.create_extension('subjectKeyIdentifier', 'hash'))
- cert.add_extension(extension_factory.create_extension('basicConstraints', 'CA:TRUE', true))
- cert.add_extension(extension_factory.create_extension('keyUsage', 'cRLSign,keyCertSign', true))
+ cert.add_extension(extension_factory.create_extension("subjectKeyIdentifier", "hash"))
+ cert.add_extension(extension_factory.create_extension("basicConstraints", "CA:TRUE", true))
+ cert.add_extension(extension_factory.create_extension("keyUsage", "cRLSign,keyCertSign", true))
end
cert.sign(signed_by&.key || key, OpenSSL::Digest::SHA256.new)
diff --git a/lib/gitlab/kubernetes/helm/client_command.rb b/lib/gitlab/kubernetes/helm/client_command.rb
index 9940272a8bf..93c3c737573 100644
--- a/lib/gitlab/kubernetes/helm/client_command.rb
+++ b/lib/gitlab/kubernetes/helm/client_command.rb
@@ -9,7 +9,7 @@ module Gitlab
# installing an app. We ensure the helm version stored in the
# database is correct by also updating this after transition to
# :installed,:updated in Clusters::Concerns::ApplicationStatus
- 'helm init --upgrade'
+ "helm init --upgrade"
end
def wait_for_tiller_command
@@ -20,7 +20,7 @@ module Gitlab
end
def repository_command
- ['helm', 'repo', 'add', name, repository].shelljoin if repository
+ ["helm", "repo", "add", name, repository].shelljoin if repository
end
end
end
diff --git a/lib/gitlab/kubernetes/helm/init_command.rb b/lib/gitlab/kubernetes/helm/init_command.rb
index 88ed8572ffc..f40ebe09bf1 100644
--- a/lib/gitlab/kubernetes/helm/init_command.rb
+++ b/lib/gitlab/kubernetes/helm/init_command.rb
@@ -16,7 +16,7 @@ module Gitlab
def generate_script
super + [
- init_helm_command
+ init_helm_command,
].join("\n")
end
@@ -33,7 +33,7 @@ module Gitlab
def cluster_role_binding_resource
return unless rbac?
- subjects = [{ kind: 'ServiceAccount', name: service_account_name, namespace: namespace }]
+ subjects = [{kind: "ServiceAccount", name: service_account_name, namespace: namespace}]
Gitlab::Kubernetes::ClusterRoleBinding.new(
cluster_role_binding_name,
@@ -56,18 +56,18 @@ module Gitlab
def tls_flags
[
- '--tiller-tls',
- '--tiller-tls-verify',
- '--tls-ca-cert', "#{files_dir}/ca.pem",
- '--tiller-tls-cert', "#{files_dir}/cert.pem",
- '--tiller-tls-key', "#{files_dir}/key.pem"
+ "--tiller-tls",
+ "--tiller-tls-verify",
+ "--tls-ca-cert", "#{files_dir}/ca.pem",
+ "--tiller-tls-cert", "#{files_dir}/cert.pem",
+ "--tiller-tls-key", "#{files_dir}/key.pem",
]
end
def optional_service_account_flag
return [] unless rbac?
- ['--service-account', service_account_name]
+ ["--service-account", service_account_name]
end
def cluster_role_binding_name
diff --git a/lib/gitlab/kubernetes/helm/install_command.rb b/lib/gitlab/kubernetes/helm/install_command.rb
index f931248b747..3d2b8fca162 100644
--- a/lib/gitlab/kubernetes/helm/install_command.rb
+++ b/lib/gitlab/kubernetes/helm/install_command.rb
@@ -28,7 +28,7 @@ module Gitlab
repository_update_command,
preinstall_command,
install_command,
- postinstall_command
+ postinstall_command,
].compact.join("\n")
end
@@ -39,13 +39,13 @@ module Gitlab
private
def repository_update_command
- 'helm repo update' if repository
+ "helm repo update" if repository
end
# Uses `helm upgrade --install` which means we can use this for both
# installation and uprade of applications
def install_command
- command = ['helm', 'upgrade', name, chart] +
+ command = ["helm", "upgrade", name, chart] +
install_flag +
reset_values_flag +
optional_tls_flags +
@@ -58,27 +58,27 @@ module Gitlab
end
def preinstall_command
- preinstall.join("\n") if preinstall
+ preinstall&.join("\n")
end
def postinstall_command
- postinstall.join("\n") if postinstall
+ postinstall&.join("\n")
end
def install_flag
- ['--install']
+ ["--install"]
end
def reset_values_flag
- ['--reset-values']
+ ["--reset-values"]
end
def value_flag
- ['-f', "/data/helm/#{name}/config/values.yaml"]
+ ["-f", "/data/helm/#{name}/config/values.yaml"]
end
def namespace_flag
- ['--namespace', Gitlab::Kubernetes::Helm::NAMESPACE]
+ ["--namespace", Gitlab::Kubernetes::Helm::NAMESPACE]
end
def rbac_create_flag
@@ -92,17 +92,17 @@ module Gitlab
def optional_version_flag
return [] unless version
- ['--version', version]
+ ["--version", version]
end
def optional_tls_flags
return [] unless files.key?(:'ca.pem')
[
- '--tls',
- '--tls-ca-cert', "#{files_dir}/ca.pem",
- '--tls-cert', "#{files_dir}/cert.pem",
- '--tls-key', "#{files_dir}/key.pem"
+ "--tls",
+ "--tls-ca-cert", "#{files_dir}/ca.pem",
+ "--tls-cert", "#{files_dir}/cert.pem",
+ "--tls-key", "#{files_dir}/key.pem",
]
end
end
diff --git a/lib/gitlab/kubernetes/helm/pod.rb b/lib/gitlab/kubernetes/helm/pod.rb
index 75484f80070..b104cbb8b67 100644
--- a/lib/gitlab/kubernetes/helm/pod.rb
+++ b/lib/gitlab/kubernetes/helm/pod.rb
@@ -11,7 +11,7 @@ module Gitlab
end
def generate
- spec = { containers: [container_specification], restartPolicy: 'Never' }
+ spec = {containers: [container_specification], restartPolicy: "Never"}
spec[:volumes] = volumes_specification
spec[:containers][0][:volumeMounts] = volume_mounts_specification
@@ -26,18 +26,18 @@ module Gitlab
def container_specification
{
- name: 'helm',
+ name: "helm",
image: "registry.gitlab.com/gitlab-org/cluster-integration/helm-install-image/releases/#{Gitlab::Kubernetes::Helm::HELM_VERSION}-kube-#{Gitlab::Kubernetes::Helm::KUBECTL_VERSION}",
env: generate_pod_env(command),
- command: %w(/bin/sh),
- args: %w(-c $(COMMAND_SCRIPT))
+ command: %w[/bin/sh],
+ args: %w(-c $(COMMAND_SCRIPT)),
}
end
def labels
{
- 'gitlab.org/action': 'install',
- 'gitlab.org/application': command.name
+ 'gitlab.org/action': "install",
+ 'gitlab.org/application': command.name,
}
end
@@ -45,7 +45,7 @@ module Gitlab
{
name: command.pod_name,
namespace: namespace_name,
- labels: labels
+ labels: labels,
}
end
@@ -53,28 +53,28 @@ module Gitlab
{
HELM_VERSION: Gitlab::Kubernetes::Helm::HELM_VERSION,
TILLER_NAMESPACE: namespace_name,
- COMMAND_SCRIPT: command.generate_script
- }.map { |key, value| { name: key, value: value } }
+ COMMAND_SCRIPT: command.generate_script,
+ }.map { |key, value| {name: key, value: value} }
end
def volumes_specification
[
{
- name: 'configuration-volume',
+ name: "configuration-volume",
configMap: {
name: "values-content-configuration-#{command.name}",
- items: command.file_names.map { |name| { key: name, path: name } }
- }
- }
+ items: command.file_names.map { |name| {key: name, path: name} },
+ },
+ },
]
end
def volume_mounts_specification
[
{
- name: 'configuration-volume',
- mountPath: "/data/helm/#{command.name}/config"
- }
+ name: "configuration-volume",
+ mountPath: "/data/helm/#{command.name}/config",
+ },
]
end
end
diff --git a/lib/gitlab/kubernetes/kube_client.rb b/lib/gitlab/kubernetes/kube_client.rb
index 624c2c67551..a71d1bba644 100644
--- a/lib/gitlab/kubernetes/kube_client.rb
+++ b/lib/gitlab/kubernetes/kube_client.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'uri'
+require "uri"
module Gitlab
module Kubernetes
@@ -14,10 +14,10 @@ module Gitlab
include Gitlab::Utils::StrongMemoize
SUPPORTED_API_GROUPS = {
- core: { group: 'api', version: 'v1' },
- rbac: { group: 'apis/rbac.authorization.k8s.io', version: 'v1' },
- extensions: { group: 'apis/extensions', version: 'v1beta1' },
- knative: { group: 'apis/serving.knative.dev', version: 'v1alpha1' }
+ core: {group: "api", version: "v1"},
+ rbac: {group: "apis/rbac.authorization.k8s.io", version: "v1"},
+ extensions: {group: "apis/extensions", version: "v1beta1"},
+ knative: {group: "apis/serving.knative.dev", version: "v1alpha1"},
}.freeze
SUPPORTED_API_GROUPS.each do |name, params|
@@ -152,7 +152,7 @@ module Gitlab
def join_api_url(api_prefix, api_path)
url = URI.parse(api_prefix)
- prefix = url.path.sub(%r{/+\z}, '')
+ prefix = url.path.sub(%r{/+\z}, "")
url.path = [prefix, api_path].join("/")
diff --git a/lib/gitlab/kubernetes/logger.rb b/lib/gitlab/kubernetes/logger.rb
index 5e59482419b..941cc3ed3cf 100644
--- a/lib/gitlab/kubernetes/logger.rb
+++ b/lib/gitlab/kubernetes/logger.rb
@@ -4,7 +4,7 @@ module Gitlab
module Kubernetes
class Logger < ::Gitlab::JsonLogger
def self.file_name_noext
- 'kubernetes'
+ "kubernetes"
end
end
end
diff --git a/lib/gitlab/kubernetes/namespace.rb b/lib/gitlab/kubernetes/namespace.rb
index 919f19c86d7..b7924a50113 100644
--- a/lib/gitlab/kubernetes/namespace.rb
+++ b/lib/gitlab/kubernetes/namespace.rb
@@ -17,7 +17,7 @@ module Gitlab
end
def create!
- resource = ::Kubeclient::Resource.new(metadata: { name: name })
+ resource = ::Kubeclient::Resource.new(metadata: {name: name})
@client.create_namespace(resource)
end
diff --git a/lib/gitlab/kubernetes/pod.rb b/lib/gitlab/kubernetes/pod.rb
index 81317e532b2..093e73efaba 100644
--- a/lib/gitlab/kubernetes/pod.rb
+++ b/lib/gitlab/kubernetes/pod.rb
@@ -3,11 +3,11 @@
module Gitlab
module Kubernetes
module Pod
- PENDING = 'Pending'.freeze
- RUNNING = 'Running'.freeze
- SUCCEEDED = 'Succeeded'.freeze
- FAILED = 'Failed'.freeze
- UNKNOWN = 'Unknown'.freeze
+ PENDING = "Pending"
+ RUNNING = "Running"
+ SUCCEEDED = "Succeeded"
+ FAILED = "Failed"
+ UNKNOWN = "Unknown"
PHASES = [PENDING, RUNNING, SUCCEEDED, FAILED, UNKNOWN].freeze
end
end
diff --git a/lib/gitlab/kubernetes/role_binding.rb b/lib/gitlab/kubernetes/role_binding.rb
index cb0cb42d007..47e5d8a5ecb 100644
--- a/lib/gitlab/kubernetes/role_binding.rb
+++ b/lib/gitlab/kubernetes/role_binding.rb
@@ -23,24 +23,24 @@ module Gitlab
attr_reader :name, :role_name, :namespace, :service_account_name
def metadata
- { name: name, namespace: namespace }
+ {name: name, namespace: namespace}
end
def role_ref
{
- apiGroup: 'rbac.authorization.k8s.io',
- kind: 'ClusterRole',
- name: role_name
+ apiGroup: "rbac.authorization.k8s.io",
+ kind: "ClusterRole",
+ name: role_name,
}
end
def subjects
[
{
- kind: 'ServiceAccount',
+ kind: "ServiceAccount",
name: service_account_name,
- namespace: namespace
- }
+ namespace: namespace,
+ },
]
end
end
diff --git a/lib/gitlab/kubernetes/service_account.rb b/lib/gitlab/kubernetes/service_account.rb
index d58fc1c3976..6154d87b3fd 100644
--- a/lib/gitlab/kubernetes/service_account.rb
+++ b/lib/gitlab/kubernetes/service_account.rb
@@ -19,7 +19,7 @@ module Gitlab
def metadata
{
name: name,
- namespace: namespace_name
+ namespace: namespace_name,
}
end
end
diff --git a/lib/gitlab/kubernetes/service_account_token.rb b/lib/gitlab/kubernetes/service_account_token.rb
index 2e912b26c09..a78ce58e0c0 100644
--- a/lib/gitlab/kubernetes/service_account_token.rb
+++ b/lib/gitlab/kubernetes/service_account_token.rb
@@ -19,7 +19,7 @@ module Gitlab
# as per https://kubernetes.io/docs/reference/access-authn-authz/service-accounts-admin/#to-create-additional-api-tokens
def service_acount_token_type
- 'kubernetes.io/service-account-token'
+ "kubernetes.io/service-account-token"
end
def metadata
@@ -27,8 +27,8 @@ module Gitlab
name: name,
namespace: namespace_name,
annotations: {
- "kubernetes.io/service-account.name": service_account_name
- }
+ "kubernetes.io/service-account.name": service_account_name,
+ },
}
end
end
diff --git a/lib/gitlab/language_data.rb b/lib/gitlab/language_data.rb
index bfdd7175198..0034ff0c85f 100644
--- a/lib/gitlab/language_data.rb
+++ b/lib/gitlab/language_data.rb
@@ -11,9 +11,9 @@ module Gitlab
EXTENSION_MUTEX.synchronize do
strong_memoize(:extensions) do
Set.new.tap do |set|
- YAML.load_file(Rails.root.join('vendor', 'languages.yml')).each do |_name, details|
- details['extensions']&.each do |ext|
- next unless ext.start_with?('.')
+ YAML.load_file(Rails.root.join("vendor", "languages.yml")).each do |_name, details|
+ details["extensions"]&.each do |ext|
+ next unless ext.start_with?(".")
set << ext.downcase
end
diff --git a/lib/gitlab/language_detection.rb b/lib/gitlab/language_detection.rb
index 7600e60b904..387f44056d3 100644
--- a/lib/gitlab/language_detection.rb
+++ b/lib/gitlab/language_detection.rb
@@ -26,30 +26,30 @@ module Gitlab
{
project_id: @repository.project.id,
share: detection[new_lang][:value],
- programming_language_id: lang_to_id[new_lang]
+ programming_language_id: lang_to_id[new_lang],
}
end
end
# updates analyses which records only require updating of their share
def updates
- to_update = @repository_languages.select do |lang|
+ to_update = @repository_languages.select { |lang|
detection.key?(lang.name) && detection[lang.name][:value] != lang.share
- end
+ }
to_update.map do |lang|
- { programming_language_id: lang.programming_language_id, share: detection[lang.name][:value] }
+ {programming_language_id: lang.programming_language_id, share: detection[lang.name][:value]}
end
end
# Returns the ids of the programming languages that do not occur in the detection
# as current repository languages
def deletions
- @repository_languages.map do |repo_lang|
+ @repository_languages.map { |repo_lang|
next if detection.key?(repo_lang.name)
repo_lang.programming_language_id
- end.compact
+ }.compact
end
private
@@ -61,10 +61,10 @@ module Gitlab
def detection
@detection ||=
@repository
- .languages
- .first(MAX_LANGUAGES)
- .map { |l| [l[:label], l] }
- .to_h
+ .languages
+ .first(MAX_LANGUAGES)
+ .map { |l| [l[:label], l] }
+ .to_h
end
end
end
diff --git a/lib/gitlab/legacy_github_import/base_formatter.rb b/lib/gitlab/legacy_github_import/base_formatter.rb
index 0b19cf742ed..2a24e16022d 100644
--- a/lib/gitlab/legacy_github_import/base_formatter.rb
+++ b/lib/gitlab/legacy_github_import/base_formatter.rb
@@ -23,7 +23,7 @@ module Gitlab
# rubocop: enable CodeReuse/ActiveRecord
def url
- raw_data.url || ''
+ raw_data.url || ""
end
end
end
diff --git a/lib/gitlab/legacy_github_import/branch_formatter.rb b/lib/gitlab/legacy_github_import/branch_formatter.rb
index 1177751457f..fc4a998da27 100644
--- a/lib/gitlab/legacy_github_import/branch_formatter.rb
+++ b/lib/gitlab/legacy_github_import/branch_formatter.rb
@@ -14,7 +14,7 @@ module Gitlab
end
def user
- raw_data.user&.login || 'unknown'
+ raw_data.user&.login || "unknown"
end
def short_sha
diff --git a/lib/gitlab/legacy_github_import/client.rb b/lib/gitlab/legacy_github_import/client.rb
index bc952147667..80cc369bfdb 100644
--- a/lib/gitlab/legacy_github_import/client.rb
+++ b/lib/gitlab/legacy_github_import/client.rb
@@ -8,9 +8,9 @@ module Gitlab
attr_reader :access_token, :host, :api_version
- def initialize(access_token, host: nil, api_version: 'v3')
+ def initialize(access_token, host: nil, api_version: "v3")
@access_token = access_token
- @host = host.to_s.sub(%r{/+\z}, '')
+ @host = host.to_s.sub(%r{/+\z}, "")
@api_version = api_version
@users = {}
@@ -26,7 +26,7 @@ module Gitlab
# If there is no config, we're connecting to github.com and we
# should verify ssl.
connection_options: {
- ssl: { verify: config ? config['verify_ssl'] : true }
+ ssl: {verify: config ? config["verify_ssl"] : true},
}
)
end
@@ -34,20 +34,20 @@ module Gitlab
def client
unless config
raise Projects::ImportService::Error,
- 'OAuth configuration for GitHub missing.'
+ "OAuth configuration for GitHub missing."
end
@client ||= ::OAuth2::Client.new(
config.app_id,
config.app_secret,
- github_options.merge(ssl: { verify: config['verify_ssl'] })
+ github_options.merge(ssl: {verify: config["verify_ssl"]})
)
end
def authorize_url(redirect_uri)
client.auth_code.authorize_url({
redirect_uri: redirect_uri,
- scope: "repo, user, user:email"
+ scope: "repo, user, user:email",
})
end
@@ -85,7 +85,7 @@ module Gitlab
end
def config
- Gitlab::Auth::OAuth::Provider.config_for('github')
+ Gitlab::Auth::OAuth::Provider.config_for("github")
end
def github_options
diff --git a/lib/gitlab/legacy_github_import/comment_formatter.rb b/lib/gitlab/legacy_github_import/comment_formatter.rb
index d83cc4f6b3c..cc9e71ed0ef 100644
--- a/lib/gitlab/legacy_github_import/comment_formatter.rb
+++ b/lib/gitlab/legacy_github_import/comment_formatter.rb
@@ -14,7 +14,7 @@ module Gitlab
author_id: author_id,
type: type,
created_at: raw_data.created_at,
- updated_at: raw_data.updated_at
+ updated_at: raw_data.updated_at,
}
end
@@ -64,7 +64,7 @@ module Gitlab
end
def type
- 'LegacyDiffNote' if on_diff?
+ "LegacyDiffNote" if on_diff?
end
end
end
diff --git a/lib/gitlab/legacy_github_import/importer.rb b/lib/gitlab/legacy_github_import/importer.rb
index f3323c98af2..e8863e61036 100644
--- a/lib/gitlab/legacy_github_import/importer.rb
+++ b/lib/gitlab/legacy_github_import/importer.rb
@@ -24,17 +24,17 @@ module Gitlab
unless credentials
raise Projects::ImportService::Error,
- "Unable to find project import data credentials for project ID: #{@project.id}"
+ "Unable to find project import data credentials for project ID: #{@project.id}"
end
opts = {}
# Gitea plan to be GitHub compliant
if project.gitea_import?
uri = URI.parse(project.import_url)
- host = "#{uri.scheme}://#{uri.host}:#{uri.port}#{uri.path}".sub(%r{/?[\w-]+/[\w-]+\.git\z}, '')
+ host = "#{uri.scheme}://#{uri.host}:#{uri.port}#{uri.path}".sub(%r{/?[\w-]+/[\w-]+\.git\z}, "")
opts = {
host: host,
- api_version: 'v1'
+ api_version: "v1",
}
end
@@ -81,20 +81,18 @@ module Gitlab
return unless errors.any?
project.import_state.update_column(:last_error, {
- message: 'The remote data could not be fully imported.',
- errors: errors
+ message: "The remote data could not be fully imported.",
+ errors: errors,
}.to_json)
end
def import_labels
fetch_resources(:labels, repo, per_page: 100) do |labels|
labels.each do |raw|
- begin
- gh_label = LabelFormatter.new(project, raw)
- gh_label.create!
- rescue => e
- errors << { type: :label, url: Gitlab::UrlSanitizer.sanitize(gh_label.url), errors: e.message }
- end
+ gh_label = LabelFormatter.new(project, raw)
+ gh_label.create!
+ rescue => e
+ errors << {type: :label, url: Gitlab::UrlSanitizer.sanitize(gh_label.url), errors: e.message}
end
end
@@ -104,12 +102,10 @@ module Gitlab
def import_milestones
fetch_resources(:milestones, repo, state: :all, per_page: 100) do |milestones|
milestones.each do |raw|
- begin
- gh_milestone = MilestoneFormatter.new(project, raw)
- gh_milestone.create!
- rescue => e
- errors << { type: :milestone, url: Gitlab::UrlSanitizer.sanitize(gh_milestone.url), errors: e.message }
- end
+ gh_milestone = MilestoneFormatter.new(project, raw)
+ gh_milestone.create!
+ rescue => e
+ errors << {type: :milestone, url: Gitlab::UrlSanitizer.sanitize(gh_milestone.url), errors: e.message}
end
end
end
@@ -130,7 +126,7 @@ module Gitlab
apply_labels(issuable, raw)
rescue => e
- errors << { type: :issue, url: Gitlab::UrlSanitizer.sanitize(gh_issue.url), errors: e.message }
+ errors << {type: :issue, url: Gitlab::UrlSanitizer.sanitize(gh_issue.url), errors: e.message}
end
end
end
@@ -155,7 +151,7 @@ module Gitlab
apply_labels(merge_request, raw)
end
rescue => e
- errors << { type: :pull_request, url: Gitlab::UrlSanitizer.sanitize(gh_pull_request.url), errors: e.message }
+ errors << {type: :pull_request, url: Gitlab::UrlSanitizer.sanitize(gh_pull_request.url), errors: e.message}
ensure
clean_up_restored_branches(gh_pull_request)
end
@@ -176,7 +172,7 @@ module Gitlab
def remove_branch(name)
project.repository.delete_branch(name)
rescue Gitlab::Git::Repository::DeleteBranchFailed
- errors << { type: :remove_branch, name: name }
+ errors << {type: :remove_branch, name: name}
end
def clean_up_restored_branches(pull_request)
@@ -205,7 +201,7 @@ module Gitlab
# compare it against every comment in the current imported page until we find match, and that's where start importing
# 2. GH returns comments for _both_ issues and PRs through issues_comments API, while pull_requests_comments returns
# only comments on diffs, so select last note not based on noteable_type but on line_code
- line_code_is = issuable_type == :pull_requests ? 'NOT NULL' : 'NULL'
+ line_code_is = issuable_type == :pull_requests ? "NOT NULL" : "NULL"
last_note = project.notes.where("line_code IS #{line_code_is}").last
fetch_resources(resource_type, repo, per_page: 100) do |comments|
@@ -223,24 +219,22 @@ module Gitlab
def create_comments(comments)
ActiveRecord::Base.no_touching do
comments.each do |raw|
- begin
- comment = CommentFormatter.new(project, raw, client)
+ comment = CommentFormatter.new(project, raw, client)
- # GH does not return info about comment's parent, so we guess it by checking its URL!
- *_, parent, iid = URI(raw.html_url).path.split('/')
+ # GH does not return info about comment's parent, so we guess it by checking its URL!
+ *_, parent, iid = URI(raw.html_url).path.split("/")
- issuable = if parent == 'issues'
- Issue.find_by(project_id: project.id, iid: iid)
- else
- MergeRequest.find_by(target_project_id: project.id, iid: iid)
- end
+ issuable = if parent == "issues"
+ Issue.find_by(project_id: project.id, iid: iid)
+ else
+ MergeRequest.find_by(target_project_id: project.id, iid: iid)
+ end
- next unless issuable
+ next unless issuable
- issuable.notes.create!(comment.attributes)
- rescue => e
- errors << { type: :comment, url: Gitlab::UrlSanitizer.sanitize(raw.url), errors: e.message }
- end
+ issuable.notes.create!(comment.attributes)
+ rescue => e
+ errors << {type: :comment, url: Gitlab::UrlSanitizer.sanitize(raw.url), errors: e.message}
end
end
end
@@ -249,13 +243,13 @@ module Gitlab
def discard_inserted_comments(comments, last_note)
last_note_attrs = nil
- cut_off_index = comments.find_index do |raw|
+ cut_off_index = comments.find_index { |raw|
comment = CommentFormatter.new(project, raw)
comment_attrs = comment.attributes
last_note_attrs ||= last_note.slice(*comment_attrs.keys)
comment_attrs.with_indifferent_access == last_note_attrs
- end
+ }
# No matching resource in the collection, which means we got halted right on the end of the last page, so all good
return unless cut_off_index
@@ -273,20 +267,18 @@ module Gitlab
# GitHub error message when the wiki repo has not been created,
# this means that repo has wiki enabled, but have no pages. So,
# we can skip the import.
- if e.message !~ /repository not exported/
- errors << { type: :wiki, errors: e.message }
+ unless /repository not exported/.match?(e.message)
+ errors << {type: :wiki, errors: e.message}
end
end
def import_releases
fetch_resources(:releases, repo, per_page: 100) do |releases|
releases.each do |raw|
- begin
- gh_release = ReleaseFormatter.new(project, raw)
- gh_release.create! if gh_release.valid?
- rescue => e
- errors << { type: :release, url: Gitlab::UrlSanitizer.sanitize(gh_release.url), errors: e.message }
- end
+ gh_release = ReleaseFormatter.new(project, raw)
+ gh_release.create! if gh_release.valid?
+ rescue => e
+ errors << {type: :release, url: Gitlab::UrlSanitizer.sanitize(gh_release.url), errors: e.message}
end
end
end
diff --git a/lib/gitlab/legacy_github_import/issuable_formatter.rb b/lib/gitlab/legacy_github_import/issuable_formatter.rb
index 1a0aefbbd62..cbd1cb54d3f 100644
--- a/lib/gitlab/legacy_github_import/issuable_formatter.rb
+++ b/lib/gitlab/legacy_github_import/issuable_formatter.rb
@@ -12,13 +12,13 @@ module Gitlab
delegate :number, to: :raw_data
def find_condition
- { iid: number }
+ {iid: number}
end
private
def state
- raw_data.state == 'closed' ? 'closed' : 'opened'
+ raw_data.state == "closed" ? "closed" : "opened"
end
def assigned?
diff --git a/lib/gitlab/legacy_github_import/issue_formatter.rb b/lib/gitlab/legacy_github_import/issue_formatter.rb
index 2f46e2e30d1..bf47feb7398 100644
--- a/lib/gitlab/legacy_github_import/issue_formatter.rb
+++ b/lib/gitlab/legacy_github_import/issue_formatter.rb
@@ -14,7 +14,7 @@ module Gitlab
author_id: author_id,
assignee_ids: Array(assignee_id),
created_at: raw_data.created_at,
- updated_at: raw_data.updated_at
+ updated_at: raw_data.updated_at,
}
end
diff --git a/lib/gitlab/legacy_github_import/label_formatter.rb b/lib/gitlab/legacy_github_import/label_formatter.rb
index 89200e794d8..b3c215aba98 100644
--- a/lib/gitlab/legacy_github_import/label_formatter.rb
+++ b/lib/gitlab/legacy_github_import/label_formatter.rb
@@ -7,7 +7,7 @@ module Gitlab
{
project: project,
title: title,
- color: color
+ color: color,
}
end
diff --git a/lib/gitlab/legacy_github_import/milestone_formatter.rb b/lib/gitlab/legacy_github_import/milestone_formatter.rb
index 2fe1b4258d3..f9fedc094c7 100644
--- a/lib/gitlab/legacy_github_import/milestone_formatter.rb
+++ b/lib/gitlab/legacy_github_import/milestone_formatter.rb
@@ -12,7 +12,7 @@ module Gitlab
due_date: raw_data.due_on,
state: state,
created_at: raw_data.created_at,
- updated_at: raw_data.updated_at
+ updated_at: raw_data.updated_at,
}
end
@@ -21,7 +21,7 @@ module Gitlab
end
def find_condition
- { iid: number }
+ {iid: number}
end
def number
@@ -35,7 +35,7 @@ module Gitlab
private
def state
- raw_data.state == 'closed' ? 'closed' : 'active'
+ raw_data.state == "closed" ? "closed" : "active"
end
end
end
diff --git a/lib/gitlab/legacy_github_import/project_creator.rb b/lib/gitlab/legacy_github_import/project_creator.rb
index ca1a1b8e9bd..6be3bf94c40 100644
--- a/lib/gitlab/legacy_github_import/project_creator.rb
+++ b/lib/gitlab/legacy_github_import/project_creator.rb
@@ -5,7 +5,7 @@ module Gitlab
class ProjectCreator
attr_reader :repo, :name, :namespace, :current_user, :session_data, :type
- def initialize(repo, name, namespace, current_user, session_data, type: 'github')
+ def initialize(repo, name, namespace, current_user, session_data, type: "github")
@repo = repo
@name = name
@namespace = namespace
@@ -24,7 +24,7 @@ module Gitlab
import_type: type,
import_source: repo.full_name,
import_url: import_url,
- skip_wiki: skip_wiki
+ skip_wiki: skip_wiki,
}.merge!(extra_attrs)
::Projects::CreateService.new(current_user, attrs).execute
@@ -33,7 +33,7 @@ module Gitlab
private
def import_url
- repo.clone_url.sub('://', "://#{session_data[:github_access_token]}@")
+ repo.clone_url.sub("://", "://#{session_data[:github_access_token]}@")
end
def visibility_level
diff --git a/lib/gitlab/legacy_github_import/pull_request_formatter.rb b/lib/gitlab/legacy_github_import/pull_request_formatter.rb
index 5b847f13d4a..39740d438ec 100644
--- a/lib/gitlab/legacy_github_import/pull_request_formatter.rb
+++ b/lib/gitlab/legacy_github_import/pull_request_formatter.rb
@@ -23,7 +23,7 @@ module Gitlab
assignee_id: assignee_id,
created_at: raw_data.created_at,
updated_at: raw_data.updated_at,
- imported: true
+ imported: true,
}
end
@@ -75,14 +75,14 @@ module Gitlab
end
def opened?
- state == 'opened'
+ state == "opened"
end
private
def state
- if raw_data.state == 'closed' && raw_data.merged_at.present?
- 'merged'
+ if raw_data.state == "closed" && raw_data.merged_at.present?
+ "merged"
else
super
end
diff --git a/lib/gitlab/legacy_github_import/release_formatter.rb b/lib/gitlab/legacy_github_import/release_formatter.rb
index 8c0c17780ca..f1c21795cbf 100644
--- a/lib/gitlab/legacy_github_import/release_formatter.rb
+++ b/lib/gitlab/legacy_github_import/release_formatter.rb
@@ -9,7 +9,7 @@ module Gitlab
tag: raw_data.tag_name,
description: raw_data.body,
created_at: raw_data.created_at,
- updated_at: raw_data.created_at
+ updated_at: raw_data.created_at,
}
end
@@ -18,7 +18,7 @@ module Gitlab
end
def find_condition
- { tag: raw_data.tag_name }
+ {tag: raw_data.tag_name}
end
def valid?
diff --git a/lib/gitlab/legacy_github_import/user_formatter.rb b/lib/gitlab/legacy_github_import/user_formatter.rb
index ec0e221b1ff..5d41841d2c0 100644
--- a/lib/gitlab/legacy_github_import/user_formatter.rb
+++ b/lib/gitlab/legacy_github_import/user_formatter.rb
@@ -28,7 +28,7 @@ module Gitlab
return nil unless email
User.find_by_any_email(email)
- .try(:id)
+ .try(:id)
end
# rubocop: disable CodeReuse/ActiveRecord
@@ -38,10 +38,10 @@ module Gitlab
identities = ::Identity.arel_table
User.select(:id)
- .joins(:identities).where(identities[:provider].eq(:github)
+ .joins(:identities).where(identities[:provider].eq(:github)
.and(identities[:extern_uid].eq(id)))
- .first
- .try(:id)
+ .first
+ .try(:id)
end
# rubocop: enable CodeReuse/ActiveRecord
end
diff --git a/lib/gitlab/lfs_token.rb b/lib/gitlab/lfs_token.rb
index 31e6fc9d8c7..accbf14f961 100644
--- a/lib/gitlab/lfs_token.rb
+++ b/lib/gitlab/lfs_token.rb
@@ -26,7 +26,7 @@ module Gitlab
when Key
actor.user
else
- raise 'Bad Actor'
+ raise "Bad Actor"
end
end
@@ -52,7 +52,7 @@ module Gitlab
username: actor_name,
lfs_token: token,
repository_http_path: repository_http_path,
- expires_in: DEFAULT_EXPIRE_TIME
+ expires_in: DEFAULT_EXPIRE_TIME,
}
end
@@ -68,13 +68,13 @@ module Gitlab
def token(expire_time)
hmac_token = JSONWebToken::HMACToken.new(secret)
hmac_token.expire_time = Time.now + expire_time
- hmac_token[:data] = { actor: actor_name }
+ hmac_token[:data] = {actor: actor_name}
hmac_token.encoded
end
def token_valid?(token_to_check)
decoded_token = JSONWebToken::HMACToken.decode(token_to_check, secret).first
- decoded_token.dig('data', 'actor') == actor_name
+ decoded_token.dig("data", "actor") == actor_name
rescue JWT::DecodeError
false
end
@@ -90,7 +90,7 @@ module Gitlab
def salt
case actor
when DeployKey, Key
- actor.fingerprint.delete(':').first(16)
+ actor.fingerprint.delete(":").first(16)
when User
# Take the last 16 characters as they're more unique than the first 16
actor.id.to_s + actor.encrypted_password.last(16)
diff --git a/lib/gitlab/logger.rb b/lib/gitlab/logger.rb
index 128a5dd8936..5712f772eb0 100644
--- a/lib/gitlab/logger.rb
+++ b/lib/gitlab/logger.rb
@@ -3,7 +3,7 @@
module Gitlab
class Logger < ::Logger
def self.file_name
- file_name_noext + '.log'
+ file_name_noext + ".log"
end
def self.debug(message)
@@ -23,16 +23,16 @@ module Gitlab
end
def self.read_latest
- path = self.full_log_path
+ path = full_log_path
return [] unless File.readable?(path)
- tail_output, _ = Gitlab::Popen.popen(%W(tail -n 2000 #{path}))
+ tail_output, _ = Gitlab::Popen.popen(%W[tail -n 2000 #{path}])
tail_output.split("\n")
end
def self.build
- Gitlab::SafeRequestStore[self.cache_key] ||= new(self.full_log_path)
+ Gitlab::SafeRequestStore[cache_key] ||= new(full_log_path)
end
def self.full_log_path
@@ -40,7 +40,7 @@ module Gitlab
end
def self.cache_key
- 'logger:'.freeze + self.full_log_path.to_s
+ "logger:" + full_log_path.to_s
end
end
end
diff --git a/lib/gitlab/mail_room.rb b/lib/gitlab/mail_room.rb
index 78f2d83c1af..96430db5916 100644
--- a/lib/gitlab/mail_room.rb
+++ b/lib/gitlab/mail_room.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
-require 'yaml'
-require 'json'
-require_relative 'redis/queues' unless defined?(Gitlab::Redis::Queues)
+require "yaml"
+require "json"
+require_relative "redis/queues" unless defined?(Gitlab::Redis::Queues)
module Gitlab
module MailRoom
@@ -11,8 +11,8 @@ module Gitlab
port: 143,
ssl: false,
start_tls: false,
- mailbox: 'inbox',
- idle_timeout: 60
+ mailbox: "inbox",
+ idle_timeout: 60,
}.freeze
class << self
@@ -34,9 +34,9 @@ module Gitlab
return {} unless File.exist?(config_file)
config = YAML.load_file(config_file)[rails_env].deep_symbolize_keys[:incoming_email] || {}
- config = DEFAULT_CONFIG.merge(config) do |_key, oldval, newval|
+ config = DEFAULT_CONFIG.merge(config) { |_key, oldval, newval|
newval.nil? ? oldval : newval
- end
+ }
if config[:enabled] && config[:address]
gitlab_redis_queues = Gitlab::Redis::Queues.new(rails_env)
@@ -51,11 +51,11 @@ module Gitlab
end
def rails_env
- @rails_env ||= ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development'
+ @rails_env ||= ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"
end
def config_file
- ENV['MAIL_ROOM_GITLAB_CONFIG_FILE'] || File.expand_path('../../config/gitlab.yml', __dir__)
+ ENV["MAIL_ROOM_GITLAB_CONFIG_FILE"] || File.expand_path("../../config/gitlab.yml", __dir__)
end
end
end
diff --git a/lib/gitlab/manifest_import/manifest.rb b/lib/gitlab/manifest_import/manifest.rb
index 7208fe5bbc5..4a33c0c3faa 100644
--- a/lib/gitlab/manifest_import/manifest.rb
+++ b/lib/gitlab/manifest_import/manifest.rb
@@ -22,16 +22,16 @@ module Gitlab
@parsed_xml = Nokogiri::XML(file) { |config| config.strict }
@errors = []
rescue Nokogiri::XML::SyntaxError
- @errors = ['The uploaded file is not a valid XML file.']
+ @errors = ["The uploaded file is not a valid XML file."]
end
def projects
raw_projects.each_with_index.map do |project, i|
{
id: i,
- name: project['name'],
- path: project['path'],
- url: repository_url(project['name'])
+ name: project["name"],
+ path: project["path"],
+ url: repository_url(project["name"]),
}
end
end
@@ -40,11 +40,11 @@ module Gitlab
return false if @errors.any?
unless validate_remote
- @errors << 'Make sure a <remote> tag is present and is valid.'
+ @errors << "Make sure a <remote> tag is present and is valid."
end
unless validate_projects
- @errors << 'Make sure every <project> tag has name and path attributes.'
+ @errors << "Make sure every <project> tag has name and path attributes."
end
@errors.empty?
@@ -60,7 +60,7 @@ module Gitlab
def validate_projects
raw_projects.all? do |project|
- project['name'] && project['path']
+ project["name"] && project["path"]
end
end
@@ -71,12 +71,12 @@ module Gitlab
def remote
return @remote if defined?(@remote)
- remote_tag = parsed_xml.css('manifest > remote').first
- @remote = remote_tag['review'] if remote_tag
+ remote_tag = parsed_xml.css("manifest > remote").first
+ @remote = remote_tag["review"] if remote_tag
end
def raw_projects
- @raw_projects ||= parsed_xml.css('manifest > project')
+ @raw_projects ||= parsed_xml.css("manifest > project")
end
end
end
diff --git a/lib/gitlab/manifest_import/project_creator.rb b/lib/gitlab/manifest_import/project_creator.rb
index 837d65e5f7c..f6737fda199 100644
--- a/lib/gitlab/manifest_import/project_creator.rb
+++ b/lib/gitlab/manifest_import/project_creator.rb
@@ -12,17 +12,17 @@ module Gitlab
end
def execute
- group_full_path, _, project_path = repository[:path].rpartition('/')
+ group_full_path, _, project_path = repository[:path].rpartition("/")
group_full_path = File.join(destination.full_path, group_full_path) if destination
group = create_group_with_parents(group_full_path)
params = {
import_url: repository[:url],
- import_type: 'manifest',
+ import_type: "manifest",
namespace_id: group.id,
path: project_path,
name: project_path,
- visibility_level: destination.visibility_level
+ visibility_level: destination.visibility_level,
}
Projects::CreateService.new(current_user, params).execute
@@ -33,7 +33,7 @@ module Gitlab
def create_group_with_parents(full_path)
params = {
group_path: full_path,
- visibility_level: destination.visibility_level
+ visibility_level: destination.visibility_level,
}
Groups::NestedCreateService.new(current_user, params).execute
diff --git a/lib/gitlab/markup_helper.rb b/lib/gitlab/markup_helper.rb
index d419fa66e57..aa85d694b34 100644
--- a/lib/gitlab/markup_helper.rb
+++ b/lib/gitlab/markup_helper.rb
@@ -44,7 +44,7 @@ module Gitlab
#
# Returns boolean
def plain?(filename)
- extension(filename) == 'txt' || plain_filename?(filename)
+ extension(filename) == "txt" || plain_filename?(filename)
end
def previewable?(filename)
@@ -54,7 +54,7 @@ module Gitlab
private
def extension(filename)
- File.extname(filename).downcase.delete('.')
+ File.extname(filename).downcase.delete(".")
end
def plain_filename?(filename)
diff --git a/lib/gitlab/metrics/background_transaction.rb b/lib/gitlab/metrics/background_transaction.rb
index fe1722b1095..90488fcacb2 100644
--- a/lib/gitlab/metrics/background_transaction.rb
+++ b/lib/gitlab/metrics/background_transaction.rb
@@ -9,7 +9,7 @@ module Gitlab
end
def labels
- { controller: @worker_class.name, action: 'perform' }
+ {controller: @worker_class.name, action: "perform"}
end
end
end
diff --git a/lib/gitlab/metrics/influx_db.rb b/lib/gitlab/metrics/influx_db.rb
index 0b04340fbb5..6aaccf3fda5 100644
--- a/lib/gitlab/metrics/influx_db.rb
+++ b/lib/gitlab/metrics/influx_db.rb
@@ -30,13 +30,13 @@ module Gitlab
host: current_settings[:metrics_host],
port: current_settings[:metrics_port],
sample_interval: current_settings[:metrics_sample_interval] || 15,
- packet_size: current_settings[:metrics_packet_size] || 1
- }
+ packet_size: current_settings[:metrics_packet_size] || 1,
+ }
end
end
def mri?
- RUBY_ENGINE == 'ruby'
+ RUBY_ENGINE == "ruby"
end
def method_call_threshold
@@ -52,14 +52,12 @@ module Gitlab
pool&.with do |connection|
prepared.each_slice(settings[:packet_size]) do |slice|
- begin
- connection.write_points(slice)
- rescue StandardError
- end
+ connection.write_points(slice)
+ rescue
end
end
rescue Errno::EADDRNOTAVAIL, SocketError => ex
- Gitlab::EnvironmentLogger.error('Cannot resolve InfluxDB address. GitLab Performance Monitoring will not work.')
+ Gitlab::EnvironmentLogger.error("Cannot resolve InfluxDB address. GitLab Performance Monitoring will not work.")
Gitlab::EnvironmentLogger.error(ex)
end
@@ -80,7 +78,7 @@ module Gitlab
end
def escape_value(value)
- value.to_s.gsub('=', '\\=')
+ value.to_s.gsub("=", '\\=')
end
# Measures the execution time of a block.
@@ -110,20 +108,20 @@ module Gitlab
real_time = (real_stop - real_start)
cpu_time = cpu_stop - cpu_start
- real_duration_seconds = fetch_histogram("gitlab_#{name}_real_duration_seconds".to_sym) do
+ real_duration_seconds = fetch_histogram("gitlab_#{name}_real_duration_seconds".to_sym) {
docstring "Measure #{name}"
base_labels Transaction::BASE_LABELS
buckets EXECUTION_MEASUREMENT_BUCKETS
- end
+ }
real_duration_seconds.observe(trans.labels, real_time)
- cpu_duration_seconds = fetch_histogram("gitlab_#{name}_cpu_duration_seconds".to_sym) do
+ cpu_duration_seconds = fetch_histogram("gitlab_#{name}_cpu_duration_seconds".to_sym) {
docstring "Measure #{name}"
base_labels Transaction::BASE_LABELS
buckets EXECUTION_MEASUREMENT_BUCKETS
with_feature "prometheus_metrics_measure_#{name}_cpu_duration"
- end
+ }
cpu_duration_seconds.observe(trans.labels, cpu_time)
# InfluxDB stores the _real_time and _cpu_time time values as milliseconds
@@ -152,7 +150,7 @@ module Gitlab
# Returns the prefix to use for the name of a series.
def series_prefix
- @series_prefix ||= Sidekiq.server? ? 'sidekiq_' : 'rails_'
+ @series_prefix ||= Sidekiq.server? ? "sidekiq_" : "rails_"
end
# Allow access from other metrics related middlewares
@@ -166,13 +164,13 @@ module Gitlab
if influx_metrics_enabled?
if @pool.nil?
MUTEX.synchronize do
- @pool ||= ConnectionPool.new(size: settings[:pool_size], timeout: settings[:timeout]) do
+ @pool ||= ConnectionPool.new(size: settings[:pool_size], timeout: settings[:timeout]) {
host = settings[:host]
port = settings[:port]
InfluxDB::Client
- .new(udp: { host: host, port: port })
- end
+ .new(udp: {host: host, port: port})
+ }
end
end
diff --git a/lib/gitlab/metrics/instrumentation.rb b/lib/gitlab/metrics/instrumentation.rb
index ff3fffe7b95..80f53b9ab4c 100644
--- a/lib/gitlab/metrics/instrumentation.rb
+++ b/lib/gitlab/metrics/instrumentation.rb
@@ -149,9 +149,9 @@ module Gitlab
# method also accepts them.
args_signature =
if method.arity == 0
- ''
+ ""
else
- '*args'
+ "*args"
end
proxy_module.class_eval <<-EOF, __FILE__, __LINE__ + 1
diff --git a/lib/gitlab/metrics/method_call.rb b/lib/gitlab/metrics/method_call.rb
index d0c63a862c2..93a23f5e955 100644
--- a/lib/gitlab/metrics/method_call.rb
+++ b/lib/gitlab/metrics/method_call.rb
@@ -5,11 +5,11 @@ module Gitlab
# Class for tracking timing information about method calls
class MethodCall
include Gitlab::Metrics::Methods
- BASE_LABELS = { module: nil, method: nil }.freeze
+ BASE_LABELS = {module: nil, method: nil}.freeze
attr_reader :real_time, :cpu_time, :call_count, :labels
define_histogram :gitlab_method_call_duration_seconds do
- docstring 'Method calls real duration'
+ docstring "Method calls real duration"
base_labels Transaction::BASE_LABELS.merge(BASE_LABELS)
buckets [0.01, 0.05, 0.1, 0.5, 1]
with_feature :prometheus_metrics_method_instrumentation
@@ -23,7 +23,7 @@ module Gitlab
@method_name = method_name
@transaction = transaction
@name = name
- @labels = { module: @module_name, method: @method_name }
+ @labels = {module: @module_name, method: @method_name}
@real_time = 0.0
@cpu_time = 0.0
@call_count = 0
@@ -56,7 +56,7 @@ module Gitlab
{
duration: real_time.in_milliseconds.to_i,
cpu_duration: cpu_time.in_milliseconds.to_i,
- call_count: call_count
+ call_count: call_count,
},
method: @name
)
diff --git a/lib/gitlab/metrics/metric.rb b/lib/gitlab/metrics/metric.rb
index 9e4d70a71ff..95e15e22baa 100644
--- a/lib/gitlab/metrics/metric.rb
+++ b/lib/gitlab/metrics/metric.rb
@@ -43,10 +43,10 @@ module Gitlab
time = System.real_time(:nanosecond) + rand(JITTER_RANGE)
{
- series: @series,
- tags: @tags,
- values: @values,
- timestamp: time.to_i
+ series: @series,
+ tags: @tags,
+ values: @values,
+ timestamp: time.to_i,
}
end
end
diff --git a/lib/gitlab/metrics/prometheus.rb b/lib/gitlab/metrics/prometheus.rb
index cab1edab48f..fdf83018d5d 100644
--- a/lib/gitlab/metrics/prometheus.rb
+++ b/lib/gitlab/metrics/prometheus.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'prometheus/client'
+require "prometheus/client"
module Gitlab
module Metrics
diff --git a/lib/gitlab/metrics/rack_middleware.rb b/lib/gitlab/metrics/rack_middleware.rb
index 9aa97515961..59e59694ae8 100644
--- a/lib/gitlab/metrics/rack_middleware.rb
+++ b/lib/gitlab/metrics/rack_middleware.rb
@@ -15,7 +15,6 @@ module Gitlab
begin
retval = trans.run { @app.call(env) }
-
rescue Exception => error # rubocop: disable Lint/RescueException
trans.add_event(:rails_exception)
@@ -33,7 +32,7 @@ module Gitlab
trans = WebTransaction.new(env)
trans.set(:request_uri, filtered_path(env), false)
- trans.set(:request_method, env['REQUEST_METHOD'], false)
+ trans.set(:request_method, env["REQUEST_METHOD"], false)
trans
end
@@ -41,7 +40,7 @@ module Gitlab
private
def filtered_path(env)
- ActionDispatch::Request.new(env).filtered_path.presence || env['REQUEST_URI']
+ ActionDispatch::Request.new(env).filtered_path.presence || env["REQUEST_URI"]
end
end
end
diff --git a/lib/gitlab/metrics/requests_rack_middleware.rb b/lib/gitlab/metrics/requests_rack_middleware.rb
index 26aa0910047..42e328c2322 100644
--- a/lib/gitlab/metrics/requests_rack_middleware.rb
+++ b/lib/gitlab/metrics/requests_rack_middleware.rb
@@ -8,20 +8,20 @@ module Gitlab
end
def self.http_request_total
- @http_request_total ||= ::Gitlab::Metrics.counter(:http_requests_total, 'Request count')
+ @http_request_total ||= ::Gitlab::Metrics.counter(:http_requests_total, "Request count")
end
def self.rack_uncaught_errors_count
- @rack_uncaught_errors_count ||= ::Gitlab::Metrics.counter(:rack_uncaught_errors_total, 'Request handling uncaught errors count')
+ @rack_uncaught_errors_count ||= ::Gitlab::Metrics.counter(:rack_uncaught_errors_total, "Request handling uncaught errors count")
end
def self.http_request_duration_seconds
- @http_request_duration_seconds ||= ::Gitlab::Metrics.histogram(:http_request_duration_seconds, 'Request handling execution time',
- {}, [0.05, 0.1, 0.25, 0.5, 0.7, 1, 2.5, 5, 10, 25])
+ @http_request_duration_seconds ||= ::Gitlab::Metrics.histogram(:http_request_duration_seconds, "Request handling execution time",
+ {}, [0.05, 0.1, 0.25, 0.5, 0.7, 1, 2.5, 5, 10, 25])
end
def call(env)
- method = env['REQUEST_METHOD'].downcase
+ method = env["REQUEST_METHOD"].downcase
started = Time.now.to_f
begin
RequestsRackMiddleware.http_request_total.increment(method: method)
@@ -29,7 +29,7 @@ module Gitlab
status, headers, body = @app.call(env)
elapsed = Time.now.to_f - started
- RequestsRackMiddleware.http_request_duration_seconds.observe({ method: method, status: status }, elapsed)
+ RequestsRackMiddleware.http_request_duration_seconds.observe({method: method, status: status}, elapsed)
[status, headers, body]
rescue
diff --git a/lib/gitlab/metrics/samplers/base_sampler.rb b/lib/gitlab/metrics/samplers/base_sampler.rb
index 6a062e93f0f..6cf9d547fb8 100644
--- a/lib/gitlab/metrics/samplers/base_sampler.rb
+++ b/lib/gitlab/metrics/samplers/base_sampler.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'logger'
+require "logger"
module Gitlab
module Metrics
diff --git a/lib/gitlab/metrics/samplers/influx_sampler.rb b/lib/gitlab/metrics/samplers/influx_sampler.rb
index 5138b37f83e..d332dbcc44f 100644
--- a/lib/gitlab/metrics/samplers/influx_sampler.rb
+++ b/lib/gitlab/metrics/samplers/influx_sampler.rb
@@ -36,11 +36,11 @@ module Gitlab
end
def sample_memory_usage
- add_metric('memory_usage', value: System.memory_usage)
+ add_metric("memory_usage", value: System.memory_usage)
end
def sample_file_descriptors
- add_metric('file_descriptors', value: System.file_descriptor_count)
+ add_metric("file_descriptors", value: System.file_descriptor_count)
end
def sample_gc
@@ -57,11 +57,11 @@ module Gitlab
stats[:count] = stats[:minor_gc_count] + stats[:major_gc_count]
- add_metric('gc_statistics', stats)
+ add_metric("gc_statistics", stats)
end
def add_metric(series, values, tags = {})
- prefix = sidekiq? ? 'sidekiq_' : 'rails_'
+ prefix = sidekiq? ? "sidekiq_" : "rails_"
@metrics << Metric.new("#{prefix}#{series}", values, tags)
end
diff --git a/lib/gitlab/metrics/samplers/ruby_sampler.rb b/lib/gitlab/metrics/samplers/ruby_sampler.rb
index 18a69321905..22e992389ee 100644
--- a/lib/gitlab/metrics/samplers/ruby_sampler.rb
+++ b/lib/gitlab/metrics/samplers/ruby_sampler.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'prometheus/client/support/unicorn'
+require "prometheus/client/support/unicorn"
module Gitlab
module Metrics
@@ -24,14 +24,14 @@ module Gitlab
def init_metrics
metrics = {}
- metrics[:sampler_duration] = ::Gitlab::Metrics.counter(with_prefix(:sampler, :duration_seconds_total), 'Sampler time', labels)
- metrics[:total_time] = ::Gitlab::Metrics.counter(with_prefix(:gc, :duration_seconds_total), 'Total GC time', labels)
+ metrics[:sampler_duration] = ::Gitlab::Metrics.counter(with_prefix(:sampler, :duration_seconds_total), "Sampler time", labels)
+ metrics[:total_time] = ::Gitlab::Metrics.counter(with_prefix(:gc, :duration_seconds_total), "Total GC time", labels)
GC.stat.keys.each do |key|
metrics[key] = ::Gitlab::Metrics.gauge(with_prefix(:gc_stat, key), to_doc_string(key), labels, :livesum)
end
- metrics[:memory_usage] = ::Gitlab::Metrics.gauge(with_prefix(:memory, :bytes), 'Memory used', labels, :livesum)
- metrics[:file_descriptors] = ::Gitlab::Metrics.gauge(with_prefix(:file, :descriptors), 'File descriptors used', labels, :livesum)
+ metrics[:memory_usage] = ::Gitlab::Metrics.gauge(with_prefix(:memory, :bytes), "Memory used", labels, :livesum)
+ metrics[:file_descriptors] = ::Gitlab::Metrics.gauge(with_prefix(:file, :descriptors), "File descriptors used", labels, :livesum)
metrics
end
@@ -67,9 +67,9 @@ module Gitlab
worker_no = ::Prometheus::Client::Support::Unicorn.worker_id
if worker_no
- { worker: worker_no }
+ {worker: worker_no}
else
- { worker: 'master' }
+ {worker: "master"}
end
end
end
diff --git a/lib/gitlab/metrics/samplers/unicorn_sampler.rb b/lib/gitlab/metrics/samplers/unicorn_sampler.rb
index bec64e864b3..7ee303a824e 100644
--- a/lib/gitlab/metrics/samplers/unicorn_sampler.rb
+++ b/lib/gitlab/metrics/samplers/unicorn_sampler.rb
@@ -9,11 +9,11 @@ module Gitlab
end
def unicorn_active_connections
- @unicorn_active_connections ||= ::Gitlab::Metrics.gauge(:unicorn_active_connections, 'Unicorn active connections', {}, :max)
+ @unicorn_active_connections ||= ::Gitlab::Metrics.gauge(:unicorn_active_connections, "Unicorn active connections", {}, :max)
end
def unicorn_queued_connections
- @unicorn_queued_connections ||= ::Gitlab::Metrics.gauge(:unicorn_queued_connections, 'Unicorn queued connections', {}, :max)
+ @unicorn_queued_connections ||= ::Gitlab::Metrics.gauge(:unicorn_queued_connections, "Unicorn queued connections", {}, :max)
end
def enabled?
@@ -23,13 +23,13 @@ module Gitlab
def sample
Raindrops::Linux.tcp_listener_stats(tcp_listeners).each do |addr, stats|
- unicorn_active_connections.set({ socket_type: 'tcp', socket_address: addr }, stats.active)
- unicorn_queued_connections.set({ socket_type: 'tcp', socket_address: addr }, stats.queued)
+ unicorn_active_connections.set({socket_type: "tcp", socket_address: addr}, stats.active)
+ unicorn_queued_connections.set({socket_type: "tcp", socket_address: addr}, stats.queued)
end
Raindrops::Linux.unix_listener_stats(unix_listeners).each do |addr, stats|
- unicorn_active_connections.set({ socket_type: 'unix', socket_address: addr }, stats.active)
- unicorn_queued_connections.set({ socket_type: 'unix', socket_address: addr }, stats.queued)
+ unicorn_active_connections.set({socket_type: "unix", socket_address: addr}, stats.active)
+ unicorn_queued_connections.set({socket_type: "unix", socket_address: addr}, stats.queued)
end
end
diff --git a/lib/gitlab/metrics/sidekiq_metrics_exporter.rb b/lib/gitlab/metrics/sidekiq_metrics_exporter.rb
index 71a5406815f..36e0ccd7ee1 100644
--- a/lib/gitlab/metrics/sidekiq_metrics_exporter.rb
+++ b/lib/gitlab/metrics/sidekiq_metrics_exporter.rb
@@ -1,12 +1,12 @@
# frozen_string_literal: true
-require 'webrick'
-require 'prometheus/client/rack/exporter'
+require "webrick"
+require "prometheus/client/rack/exporter"
module Gitlab
module Metrics
class SidekiqMetricsExporter < Daemon
- LOG_FILENAME = File.join(Rails.root, 'log', 'sidekiq_exporter.log')
+ LOG_FILENAME = File.join(Rails.root, "log", "sidekiq_exporter.log")
def enabled?
::Gitlab::Metrics.metrics_folder_present? && settings.enabled
@@ -23,7 +23,7 @@ module Gitlab
def start_working
logger = WEBrick::Log.new(LOG_FILENAME)
access_log = [
- [logger, WEBrick::AccessLog::COMBINED_LOG_FORMAT]
+ [logger, WEBrick::AccessLog::COMBINED_LOG_FORMAT],
]
@server = ::WEBrick::HTTPServer.new(Port: settings.port, BindAddress: settings.address,
@@ -33,7 +33,7 @@ module Gitlab
end
def stop_working
- server.shutdown if server
+ server&.shutdown
@server = nil
end
@@ -41,7 +41,7 @@ module Gitlab
Rack::Builder.app do
use Rack::Deflater
use ::Prometheus::Client::Rack::Exporter
- run -> (env) { [404, {}, ['']] }
+ run ->(env) { [404, {}, [""]] }
end
end
end
diff --git a/lib/gitlab/metrics/sidekiq_middleware.rb b/lib/gitlab/metrics/sidekiq_middleware.rb
index 0b4485feea9..43a32e9b97b 100644
--- a/lib/gitlab/metrics/sidekiq_middleware.rb
+++ b/lib/gitlab/metrics/sidekiq_middleware.rb
@@ -11,7 +11,7 @@ module Gitlab
begin
# Old gitlad-shell messages don't provide enqueued_at/created_at attributes
- trans.set(:sidekiq_queue_duration, Time.now.to_f - (message['enqueued_at'] || message['created_at'] || 0))
+ trans.set(:sidekiq_queue_duration, Time.now.to_f - (message["enqueued_at"] || message["created_at"] || 0))
trans.run { yield }
rescue Exception => error # rubocop: disable Lint/RescueException
trans.add_event(:sidekiq_exception)
diff --git a/lib/gitlab/metrics/subscribers/action_view.rb b/lib/gitlab/metrics/subscribers/action_view.rb
index c068f8017fd..f45d6356772 100644
--- a/lib/gitlab/metrics/subscribers/action_view.rb
+++ b/lib/gitlab/metrics/subscribers/action_view.rb
@@ -7,21 +7,21 @@ module Gitlab
class ActionView < ActiveSupport::Subscriber
include Gitlab::Metrics::Methods
define_histogram :gitlab_view_rendering_duration_seconds do
- docstring 'View rendering time'
- base_labels Transaction::BASE_LABELS.merge({ path: nil })
+ docstring "View rendering time"
+ base_labels Transaction::BASE_LABELS.merge({path: nil})
buckets [0.001, 0.01, 0.1, 1, 10.0]
with_feature :prometheus_metrics_view_instrumentation
end
attach_to :action_view
- SERIES = 'views'.freeze
+ SERIES = "views"
def render_template(event)
track(event) if current_transaction
end
- alias_method :render_view, :render_template
+ alias render_view render_template
private
@@ -36,17 +36,17 @@ module Gitlab
end
def relative_path(path)
- path.gsub(%r{^#{Rails.root.to_s}/?}, '')
+ path.gsub(%r{^#{Rails.root.to_s}/?}, "")
end
def values_for(event)
- { duration: event.duration }
+ {duration: event.duration}
end
def tags_for(event)
path = relative_path(event.payload[:identifier])
- { view: path }
+ {view: path}
end
def current_transaction
diff --git a/lib/gitlab/metrics/subscribers/active_record.rb b/lib/gitlab/metrics/subscribers/active_record.rb
index a02dd850582..28fbb69872c 100644
--- a/lib/gitlab/metrics/subscribers/active_record.rb
+++ b/lib/gitlab/metrics/subscribers/active_record.rb
@@ -8,14 +8,14 @@ module Gitlab
include Gitlab::Metrics::Methods
attach_to :active_record
- IGNORABLE_SQL = %w{BEGIN COMMIT}.freeze
+ IGNORABLE_SQL = %w[BEGIN COMMIT].freeze
def sql(event)
return unless current_transaction
payload = event.payload
- return if payload[:name] == 'SCHEMA' || IGNORABLE_SQL.include?(payload[:sql])
+ return if payload[:name] == "SCHEMA" || IGNORABLE_SQL.include?(payload[:sql])
self.class.gitlab_sql_duration_seconds.observe(current_transaction.labels, event.duration / 1000.0)
@@ -26,7 +26,7 @@ module Gitlab
private
define_histogram :gitlab_sql_duration_seconds do
- docstring 'SQL time'
+ docstring "SQL time"
base_labels Transaction::BASE_LABELS
buckets [0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0]
end
diff --git a/lib/gitlab/metrics/subscribers/rails_cache.rb b/lib/gitlab/metrics/subscribers/rails_cache.rb
index 01db507761b..365cb719470 100644
--- a/lib/gitlab/metrics/subscribers/rails_cache.rb
+++ b/lib/gitlab/metrics/subscribers/rails_cache.rb
@@ -50,7 +50,7 @@ module Gitlab
def observe(key, duration)
return unless current_transaction
- metric_cache_operation_duration_seconds.observe(current_transaction.labels.merge({ operation: key }), duration / 1000.0)
+ metric_cache_operation_duration_seconds.observe(current_transaction.labels.merge({operation: key}), duration / 1000.0)
current_transaction.increment(:cache_duration, duration, false)
current_transaction.increment(:cache_count, 1, false)
current_transaction.increment("cache_#{key}_duration".to_sym, duration, false)
@@ -66,8 +66,8 @@ module Gitlab
def metric_cache_operation_duration_seconds
@metric_cache_operation_duration_seconds ||= ::Gitlab::Metrics.histogram(
:gitlab_cache_operation_duration_seconds,
- 'Cache access time',
- Transaction::BASE_LABELS.merge({ action: nil }),
+ "Cache access time",
+ Transaction::BASE_LABELS.merge({action: nil}),
[0.001, 0.01, 0.1, 1, 10]
)
end
@@ -75,7 +75,7 @@ module Gitlab
def metric_cache_misses_total
@metric_cache_misses_total ||= ::Gitlab::Metrics.counter(
:gitlab_cache_misses_total,
- 'Cache read miss',
+ "Cache read miss",
Transaction::BASE_LABELS
)
end
diff --git a/lib/gitlab/metrics/system.rb b/lib/gitlab/metrics/system.rb
index 426496855e3..e6d510e57e0 100644
--- a/lib/gitlab/metrics/system.rb
+++ b/lib/gitlab/metrics/system.rb
@@ -7,11 +7,11 @@ module Gitlab
# This module relies on the /proc filesystem being available. If /proc is
# not available the methods of this module will be stubbed.
module System
- if File.exist?('/proc')
+ if File.exist?("/proc")
# Returns the current process' memory usage in bytes.
def self.memory_usage
mem = 0
- match = File.read('/proc/self/status').match(/VmRSS:\s+(\d+)/)
+ match = File.read("/proc/self/status").match(/VmRSS:\s+(\d+)/)
if match && match[1]
mem = match[1].to_f * 1024
@@ -21,7 +21,7 @@ module Gitlab
end
def self.file_descriptor_count
- Dir.glob('/proc/self/fd/*').length
+ Dir.glob("/proc/self/fd/*").length
end
else
def self.memory_usage
diff --git a/lib/gitlab/metrics/transaction.rb b/lib/gitlab/metrics/transaction.rb
index e91803ecd62..6d9dc75a84c 100644
--- a/lib/gitlab/metrics/transaction.rb
+++ b/lib/gitlab/metrics/transaction.rb
@@ -7,12 +7,12 @@ module Gitlab
include Gitlab::Metrics::Methods
# base labels shared among all transactions
- BASE_LABELS = { controller: nil, action: nil }.freeze
+ BASE_LABELS = {controller: nil, action: nil}.freeze
THREAD_KEY = :_gitlab_metrics_transaction
# The series to store events (e.g. Git pushes) in.
- EVENT_SERIES = 'events'.freeze
+ EVENT_SERIES = "events"
attr_reader :tags, :values, :method, :metrics
@@ -75,8 +75,8 @@ module Gitlab
# event_name - The name of the event (e.g. "git_push").
# tags - A set of tags to attach to the event.
def add_event(event_name, tags = {})
- self.class.transaction_metric(event_name, :counter, prefix: 'event_', use_feature_flag: true, tags: tags).increment(tags.merge(labels))
- @metrics << Metric.new(EVENT_SERIES, { count: 1 }, tags.merge(event: event_name), :event)
+ self.class.transaction_metric(event_name, :counter, prefix: "event_", use_feature_flag: true, tags: tags).increment(tags.merge(labels))
+ @metrics << Metric.new(EVENT_SERIES, {count: 1}, tags.merge(event: event_name), :event)
end
# Returns a MethodCall object for the given name.
@@ -104,13 +104,13 @@ module Gitlab
end
def track_self
- values = { duration: duration_milliseconds, allocated_memory: allocated_memory }
+ values = {duration: duration_milliseconds, allocated_memory: allocated_memory}
@values.each do |name, value|
values[name] = value
end
- add_metric('transactions', values, @tags)
+ add_metric("transactions", values, @tags)
end
def submit
@@ -120,12 +120,12 @@ module Gitlab
submit << method.to_metric if method.above_threshold?
end
- submit_hashes = submit.map do |metric|
+ submit_hashes = submit.map { |metric|
hash = metric.to_hash
hash[:tags][:action] ||= action if action && !metric.event?
hash
- end
+ }
::Gitlab::Metrics.submit_metrics(submit_hashes)
end
@@ -140,13 +140,13 @@ module Gitlab
end
define_histogram :gitlab_transaction_duration_seconds do
- docstring 'Transaction duration'
+ docstring "Transaction duration"
base_labels BASE_LABELS
buckets [0.1, 0.25, 0.5, 1.0, 2.5, 5.0]
end
define_histogram :gitlab_transaction_allocated_memory_bytes do
- docstring 'Transaction allocated memory bytes'
+ docstring "Transaction allocated memory bytes"
base_labels BASE_LABELS
buckets [100, 1000, 10000, 100000, 1000000, 10000000]
with_feature :prometheus_metrics_transaction_allocated_memory
diff --git a/lib/gitlab/metrics/web_transaction.rb b/lib/gitlab/metrics/web_transaction.rb
index b2a43d46fb2..8986537b03f 100644
--- a/lib/gitlab/metrics/web_transaction.rb
+++ b/lib/gitlab/metrics/web_transaction.rb
@@ -3,8 +3,8 @@
module Gitlab
module Metrics
class WebTransaction < Transaction
- CONTROLLER_KEY = 'action_controller.instance'.freeze
- ENDPOINT_KEY = 'api.endpoint'.freeze
+ CONTROLLER_KEY = "action_controller.instance"
+ ENDPOINT_KEY = "api.endpoint"
ALLOWED_SUFFIXES = Set.new(%w[json js atom rss xml zip])
def initialize(env)
@@ -17,10 +17,10 @@ module Gitlab
# memoize transaction labels only source env variables were present
@labels = if @env[CONTROLLER_KEY]
- labels_from_controller || {}
- elsif @env[ENDPOINT_KEY]
- labels_from_endpoint || {}
- end
+ labels_from_controller || {}
+ elsif @env[ENDPOINT_KEY]
+ labels_from_endpoint || {}
+ end
@labels || {}
end
@@ -30,7 +30,7 @@ module Gitlab
def labels_from_controller
controller = @env[CONTROLLER_KEY]
- action = "#{controller.action_name}"
+ action = controller.action_name.to_s
# Devise exposes a method called "request_format" that does the below.
# However, this method is not available to all controllers (e.g. certain
@@ -45,7 +45,7 @@ module Gitlab
action = "#{action}.#{suffix}"
end
- { controller: controller.class.name, action: action }
+ {controller: controller.class.name, action: action}
end
def labels_from_endpoint
@@ -61,20 +61,20 @@ module Gitlab
if route
path = endpoint_paths_cache[route.request_method][route.path]
- { controller: 'Grape', action: "#{route.request_method} #{path}" }
+ {controller: "Grape", action: "#{route.request_method} #{path}"}
end
end
def endpoint_paths_cache
- @endpoint_paths_cache ||= Hash.new do |hash, http_method|
- hash[http_method] = Hash.new do |inner_hash, raw_path|
+ @endpoint_paths_cache ||= Hash.new { |hash, http_method|
+ hash[http_method] = Hash.new { |inner_hash, raw_path|
inner_hash[raw_path] = endpoint_instrumentable_path(raw_path)
- end
- end
+ }
+ }
end
def endpoint_instrumentable_path(raw_path)
- raw_path.sub('(.:format)', '').sub('/:version', '')
+ raw_path.sub("(.:format)", "").sub("/:version", "")
end
end
end
diff --git a/lib/gitlab/middleware/basic_health_check.rb b/lib/gitlab/middleware/basic_health_check.rb
index acf8c301b8f..2594392dc3f 100644
--- a/lib/gitlab/middleware/basic_health_check.rb
+++ b/lib/gitlab/middleware/basic_health_check.rb
@@ -12,17 +12,17 @@ module Gitlab
class BasicHealthCheck
# This can't be frozen because Rails::Rack::Logger wraps the body
# rubocop:disable Style/MutableConstant
- OK_RESPONSE = [200, { 'Content-Type' => 'text/plain' }, ["GitLab OK"]]
- EMPTY_RESPONSE = [404, { 'Content-Type' => 'text/plain' }, [""]]
+ OK_RESPONSE = [200, {"Content-Type" => "text/plain"}, ["GitLab OK"]]
+ EMPTY_RESPONSE = [404, {"Content-Type" => "text/plain"}, [""]]
# rubocop:enable Style/MutableConstant
- HEALTH_PATH = '/-/health'
+ HEALTH_PATH = "/-/health"
def initialize(app)
@app = app
end
def call(env)
- return @app.call(env) unless env['PATH_INFO'] == HEALTH_PATH
+ return @app.call(env) unless env["PATH_INFO"] == HEALTH_PATH
request = ActionDispatch::Request.new(env)
diff --git a/lib/gitlab/middleware/go.rb b/lib/gitlab/middleware/go.rb
index f9efef38825..9da495a7f2d 100644
--- a/lib/gitlab/middleware/go.rb
+++ b/lib/gitlab/middleware/go.rb
@@ -31,7 +31,7 @@ module Gitlab
body = go_body(path)
return unless body
- response = Rack::Response.new(body, 200, { 'Content-Type' => 'text/html' })
+ response = Rack::Response.new(body, 200, {"Content-Type" => "text/html"})
response.finish
end
@@ -44,26 +44,26 @@ module Gitlab
project_url = Gitlab::Utils.append_path(config.gitlab.url, path)
import_prefix = strip_url(project_url.to_s)
- repository_url = if Gitlab::CurrentSettings.enabled_git_access_protocol == 'ssh'
- shell = config.gitlab_shell
- port = ":#{shell.ssh_port}" unless shell.ssh_port == 22
- "ssh://#{shell.ssh_user}@#{shell.ssh_host}#{port}/#{path}.git"
- else
- "#{project_url}.git"
- end
+ repository_url = if Gitlab::CurrentSettings.enabled_git_access_protocol == "ssh"
+ shell = config.gitlab_shell
+ port = ":#{shell.ssh_port}" unless shell.ssh_port == 22
+ "ssh://#{shell.ssh_user}@#{shell.ssh_host}#{port}/#{path}.git"
+ else
+ "#{project_url}.git"
+ end
- meta_tag = tag :meta, name: 'go-import', content: "#{import_prefix} git #{repository_url}"
+ meta_tag = tag :meta, name: "go-import", content: "#{import_prefix} git #{repository_url}"
head_tag = content_tag :head, meta_tag
content_tag :html, head_tag
end
def strip_url(url)
- url.gsub(%r{\Ahttps?://}, '')
+ url.gsub(%r{\Ahttps?://}, "")
end
def project_path(request)
path_info = request.env["PATH_INFO"]
- path_info.sub!(%r{^/}, '')
+ path_info.sub!(%r{^/}, "")
project_path_match = "#{path_info}/".match(PROJECT_PATH_REGEX)
return unless project_path_match
@@ -77,15 +77,15 @@ module Gitlab
# `path2/../pathN`, for example.
# We find all potential project paths out of the path segments
- path_segments = path.split('/')
- simple_project_path = path_segments.first(2).join('/')
+ path_segments = path.split("/")
+ simple_project_path = path_segments.first(2).join("/")
# If the path is at most 2 segments long, it is a simple `namespace/project` path and we're done
return simple_project_path if path_segments.length <= 2
project_paths = []
begin
- project_paths << path_segments.join('/')
+ project_paths << path_segments.join("/")
path_segments.pop
end while path_segments.length >= 2
diff --git a/lib/gitlab/middleware/multipart.rb b/lib/gitlab/middleware/multipart.rb
index 433151b80e7..dd7cd0713d7 100644
--- a/lib/gitlab/middleware/multipart.rb
+++ b/lib/gitlab/middleware/multipart.rb
@@ -28,12 +28,12 @@
module Gitlab
module Middleware
class Multipart
- RACK_ENV_KEY = 'HTTP_GITLAB_WORKHORSE_MULTIPART_FIELDS'.freeze
+ RACK_ENV_KEY = "HTTP_GITLAB_WORKHORSE_MULTIPART_FIELDS"
class Handler
def initialize(env, message)
@request = ActionDispatch::Request.new(env)
- @rewritten_fields = message['rewritten_fields']
+ @rewritten_fields = message["rewritten_fields"]
@open_files = []
end
@@ -72,7 +72,7 @@ module Gitlab
case path_value
when nil
- value_hash[path_key] = open_file(value_hash.dig(path_key), '')
+ value_hash[path_key] = open_file(value_hash.dig(path_key), "")
@open_files << value_hash[path_key]
value_hash
when Hash
@@ -87,7 +87,7 @@ module Gitlab
allowed_paths = [
::FileUploader.root,
Gitlab.config.uploads.storage_path,
- File.join(Rails.root, 'public/uploads/tmp')
+ File.join(Rails.root, "public/uploads/tmp"),
]
::UploadedFile.from_params(params, key, allowed_paths)
diff --git a/lib/gitlab/middleware/rails_queue_duration.rb b/lib/gitlab/middleware/rails_queue_duration.rb
index a147e165262..311bbee36f8 100644
--- a/lib/gitlab/middleware/rails_queue_duration.rb
+++ b/lib/gitlab/middleware/rails_queue_duration.rb
@@ -7,7 +7,7 @@
module Gitlab
module Middleware
class RailsQueueDuration
- GITLAB_RAILS_QUEUE_DURATION_KEY = 'GITLAB_RAILS_QUEUE_DURATION'
+ GITLAB_RAILS_QUEUE_DURATION_KEY = "GITLAB_RAILS_QUEUE_DURATION"
def initialize(app)
@app = app
@@ -15,7 +15,7 @@ module Gitlab
def call(env)
trans = Gitlab::Metrics.current_transaction
- proxy_start = env['HTTP_GITLAB_WORKHORSE_PROXY_START'].presence
+ proxy_start = env["HTTP_GITLAB_WORKHORSE_PROXY_START"].presence
if trans && proxy_start
# Time in milliseconds since gitlab-workhorse started the request
duration = Time.now.to_f * 1_000 - proxy_start.to_f / 1_000_000
diff --git a/lib/gitlab/middleware/read_only/controller.rb b/lib/gitlab/middleware/read_only/controller.rb
index 817db12ac55..53e8451bb35 100644
--- a/lib/gitlab/middleware/read_only/controller.rb
+++ b/lib/gitlab/middleware/read_only/controller.rb
@@ -4,18 +4,18 @@ module Gitlab
module Middleware
class ReadOnly
class Controller
- DISALLOWED_METHODS = %w(POST PATCH PUT DELETE).freeze
- APPLICATION_JSON = 'application/json'.freeze
- APPLICATION_JSON_TYPES = %W{#{APPLICATION_JSON} application/vnd.git-lfs+json}.freeze
- ERROR_MESSAGE = 'You cannot perform write operations on a read-only instance'.freeze
+ DISALLOWED_METHODS = %w[POST PATCH PUT DELETE].freeze
+ APPLICATION_JSON = "application/json"
+ APPLICATION_JSON_TYPES = %W[#{APPLICATION_JSON} application/vnd.git-lfs+json].freeze
+ ERROR_MESSAGE = "You cannot perform write operations on a read-only instance"
WHITELISTED_GIT_ROUTES = {
- 'projects/git_http' => %w{git_upload_pack git_receive_pack}
+ "projects/git_http" => %w[git_upload_pack git_receive_pack],
}.freeze
WHITELISTED_GIT_LFS_ROUTES = {
- 'projects/lfs_api' => %w{batch},
- 'projects/lfs_locks_api' => %w{verify create unlock}
+ "projects/lfs_api" => %w[batch],
+ "projects/lfs_locks_api" => %w[verify create unlock],
}.freeze
def initialize(app, env)
@@ -25,15 +25,15 @@ module Gitlab
def call
if disallowed_request? && Gitlab::Database.read_only?
- Rails.logger.debug('GitLab ReadOnly: preventing possible non read-only operation')
+ Rails.logger.debug("GitLab ReadOnly: preventing possible non read-only operation")
if json_request?
- return [403, { 'Content-Type' => APPLICATION_JSON }, [{ 'message' => ERROR_MESSAGE }.to_json]]
+ return [403, {"Content-Type" => APPLICATION_JSON}, [{"message" => ERROR_MESSAGE}.to_json]]
else
rack_flash.alert = ERROR_MESSAGE
- rack_session['flash'] = rack_flash.to_session_value
+ rack_session["flash"] = rack_flash.to_session_value
- return [301, { 'Location' => last_visited_url }, []]
+ return [301, {"Location" => last_visited_url}, []]
end
end
@@ -43,7 +43,7 @@ module Gitlab
private
def disallowed_request?
- DISALLOWED_METHODS.include?(@env['REQUEST_METHOD']) &&
+ DISALLOWED_METHODS.include?(@env["REQUEST_METHOD"]) &&
!whitelisted_routes
end
@@ -56,23 +56,27 @@ module Gitlab
end
def rack_session
- @env['rack.session']
+ @env["rack.session"]
end
def request
- @env['actionpack.request'] ||= ActionDispatch::Request.new(@env)
+ @env["actionpack.request"] ||= ActionDispatch::Request.new(@env)
end
def last_visited_url
- @env['HTTP_REFERER'] || rack_session['user_return_to'] || Gitlab::Routing.url_helpers.root_url
+ @env["HTTP_REFERER"] || rack_session["user_return_to"] || Gitlab::Routing.url_helpers.root_url
end
def route_hash
- @route_hash ||= Rails.application.routes.recognize_path(request.url, { method: request.request_method }) rescue {}
+ @route_hash ||= begin
+ Rails.application.routes.recognize_path(request.url, {method: request.request_method})
+ rescue
+ {}
+ end
end
def relative_url
- File.join('', Gitlab.config.gitlab.relative_url_root).chomp('/')
+ File.join("", Gitlab.config.gitlab.relative_url_root).chomp("/")
end
# Overridden in EE module
@@ -83,7 +87,7 @@ module Gitlab
def grack_route?
# Calling route_hash may be expensive. Only do it if we think there's a possible match
return false unless
- request.path.end_with?('.git/git-upload-pack', '.git/git-receive-pack')
+ request.path.end_with?(".git/git-upload-pack", ".git/git-receive-pack")
WHITELISTED_GIT_ROUTES[route_hash[:controller]]&.include?(route_hash[:action])
end
@@ -94,8 +98,8 @@ module Gitlab
def lfs_route?
# Calling route_hash may be expensive. Only do it if we think there's a possible match
- unless request.path.end_with?('/info/lfs/objects/batch',
- '/info/lfs/locks', '/info/lfs/locks/verify') ||
+ unless request.path.end_with?("/info/lfs/objects/batch",
+ "/info/lfs/locks", "/info/lfs/locks/verify") ||
%r{/info/lfs/locks/\d+/unlock\z}.match?(request.path)
return false
end
diff --git a/lib/gitlab/middleware/release_env.rb b/lib/gitlab/middleware/release_env.rb
index 849cf8f759b..7ed18314728 100644
--- a/lib/gitlab/middleware/release_env.rb
+++ b/lib/gitlab/middleware/release_env.rb
@@ -8,10 +8,10 @@ module Gitlab
# them due to this. Put this middleware as the first middleware so that
# it would clear the env after the request is done, allowing GC gets a
# chance to release memory for the last request.
- ReleaseEnv = Struct.new(:app) do
+ ReleaseEnv = Struct.new(:app) {
def call(env)
app.call(env).tap { env.clear }
end
- end
+ }
end
end
diff --git a/lib/gitlab/middleware/static.rb b/lib/gitlab/middleware/static.rb
index 972fed2134c..6b1b5a4d34e 100644
--- a/lib/gitlab/middleware/static.rb
+++ b/lib/gitlab/middleware/static.rb
@@ -6,7 +6,7 @@ module Gitlab
UPLOADS_REGEX = %r{\A/uploads(/|\z)}.freeze
def call(env)
- return @app.call(env) if env['PATH_INFO'] =~ UPLOADS_REGEX
+ return @app.call(env) if env["PATH_INFO"] =~ UPLOADS_REGEX
super
end
diff --git a/lib/gitlab/multi_collection_paginator.rb b/lib/gitlab/multi_collection_paginator.rb
index 5375077d7dc..726e398c245 100644
--- a/lib/gitlab/multi_collection_paginator.rb
+++ b/lib/gitlab/multi_collection_paginator.rb
@@ -5,7 +5,7 @@ module Gitlab
attr_reader :first_collection, :second_collection, :per_page
def initialize(*collections, per_page: nil)
- raise ArgumentError.new('Only 2 collections are supported') if collections.size != 2
+ raise ArgumentError.new("Only 2 collections are supported") if collections.size != 2
@per_page = (per_page || Kaminari.config.default_per_page).to_i
@first_collection, @second_collection = collections
@@ -23,27 +23,27 @@ module Gitlab
private
def paginated_first_collection(page)
- @first_collection_pages ||= Hash.new do |hash, page|
+ @first_collection_pages ||= Hash.new { |hash, page|
hash[page] = first_collection.page(page).per(per_page)
- end
+ }
@first_collection_pages[page]
end
def paginated_second_collection(page)
- @second_collection_pages ||= Hash.new do |hash, page|
+ @second_collection_pages ||= Hash.new { |hash, page|
second_collection_page = page - first_collection_page_count
offset = if second_collection_page < 1 || first_collection_page_count.zero?
- 0
- else
- per_page - first_collection_last_page_size
- end
+ 0
+ else
+ per_page - first_collection_last_page_size
+ end
hash[page] = second_collection.page(second_collection_page)
- .per(per_page - paginated_first_collection(page).size)
- .padding(offset)
- end
+ .per(per_page - paginated_first_collection(page).size)
+ .padding(offset)
+ }
@second_collection_pages[page]
end
@@ -60,8 +60,8 @@ module Gitlab
return @first_collection_last_page_size if defined?(@first_collection_last_page_size)
@first_collection_last_page_size = paginated_first_collection(first_collection_page_count)
- .except(:select)
- .size
+ .except(:select)
+ .size
end
# rubocop: enable CodeReuse/ActiveRecord
end
diff --git a/lib/gitlab/namespace_sanitizer.rb b/lib/gitlab/namespace_sanitizer.rb
index d755bbbcaf9..5b6d732f245 100644
--- a/lib/gitlab/namespace_sanitizer.rb
+++ b/lib/gitlab/namespace_sanitizer.rb
@@ -3,7 +3,7 @@
module Gitlab
class NamespaceSanitizer
def self.sanitize(namespace)
- namespace.gsub(/[^-a-z0-9]/, '-').gsub(/^-+/, '')
+ namespace.gsub(/[^-a-z0-9]/, "-").gsub(/^-+/, "")
end
end
end
diff --git a/lib/gitlab/object_hierarchy.rb b/lib/gitlab/object_hierarchy.rb
index f2772c733c7..f06f06455bd 100644
--- a/lib/gitlab/object_hierarchy.rb
+++ b/lib/gitlab/object_hierarchy.rb
@@ -108,7 +108,7 @@ module Gitlab
.recursive(ancestors.to_arel, descendants.to_arel)
.from_union([
model.unscoped.from(ancestors_table),
- model.unscoped.from(descendants_table)
+ model.unscoped.from(descendants_table),
])
read_only(relation)
diff --git a/lib/gitlab/omniauth_initializer.rb b/lib/gitlab/omniauth_initializer.rb
index e0ac9eec1f2..b354d516e59 100644
--- a/lib/gitlab/omniauth_initializer.rb
+++ b/lib/gitlab/omniauth_initializer.rb
@@ -8,7 +8,7 @@ module Gitlab
def execute(providers)
providers.each do |provider|
- name = provider['name'].to_sym
+ name = provider["name"].to_sym
add_provider_to_devise(name, *arguments_for(provider))
setup_provider(name)
@@ -28,12 +28,12 @@ module Gitlab
provider_arguments << provider[argument] if provider[argument]
end
- case provider['args']
+ case provider["args"]
when Array
# An Array from the configuration will be expanded.
- provider_arguments.concat provider['args']
+ provider_arguments.concat provider["args"]
when Hash
- hash_arguments = provider['args'].merge(provider_defaults(provider))
+ hash_arguments = provider["args"].merge(provider_defaults(provider))
# A Hash from the configuration will be passed as is.
provider_arguments << hash_arguments.symbolize_keys
@@ -43,13 +43,13 @@ module Gitlab
end
def provider_defaults(provider)
- case provider['name']
- when 'cas3'
- { on_single_sign_out: cas3_signout_handler }
- when 'authentiq'
- { remote_sign_out_handler: authentiq_signout_handler }
- when 'shibboleth'
- { fail_with_empty_uid: true }
+ case provider["name"]
+ when "cas3"
+ {on_single_sign_out: cas3_signout_handler}
+ when "authentiq"
+ {remote_sign_out_handler: authentiq_signout_handler}
+ when "shibboleth"
+ {fail_with_empty_uid: true}
else
{}
end
@@ -67,7 +67,7 @@ module Gitlab
def authentiq_signout_handler
lambda do |request|
- authentiq_session = request.params['sid']
+ authentiq_session = request.params["sid"]
if Gitlab::Auth::OAuth::Session.valid?(:authentiq, authentiq_session)
Gitlab::Auth::OAuth::Session.destroy(:authentiq, authentiq_session)
true
@@ -89,7 +89,7 @@ module Gitlab
def setup_provider(provider)
case provider
when :kerberos
- require 'omniauth-kerberos'
+ require "omniauth-kerberos"
when *omniauth_customized_providers
require_dependency "omni_auth/strategies/#{provider}"
end
diff --git a/lib/gitlab/optimistic_locking.rb b/lib/gitlab/optimistic_locking.rb
index ce4ba9f752b..83d14c0e460 100644
--- a/lib/gitlab/optimistic_locking.rb
+++ b/lib/gitlab/optimistic_locking.rb
@@ -16,6 +16,6 @@ module Gitlab
retry
end
- alias_method :retry_optimistic_lock, :retry_lock
+ alias retry_optimistic_lock retry_lock
end
end
diff --git a/lib/gitlab/otp_key_rotator.rb b/lib/gitlab/otp_key_rotator.rb
index 1d3200aa099..7d3aea38a09 100644
--- a/lib/gitlab/otp_key_rotator.rb
+++ b/lib/gitlab/otp_key_rotator.rb
@@ -56,7 +56,7 @@ module Gitlab
def rollback!
ActiveRecord::Base.transaction do
CSV.foreach(filename, headers: HEADERS, return_headers: false) do |row|
- User.where(id: row['user_id']).update_all(encrypted_otp_secret: row['old_value'])
+ User.where(id: row["user_id"]).update_all(encrypted_otp_secret: row["old_value"])
end
end
end
@@ -76,7 +76,7 @@ module Gitlab
iv: user[:iv].unpack("m").join,
salt: user[:salt].unpack("m").join,
algorithm: otp_secret_settings[:algorithm],
- insecure_mode: otp_secret_settings[:insecure_mode]
+ insecure_mode: otp_secret_settings[:insecure_mode],
}
decrypted = Encryptor.decrypt(original, opts.merge(key: old_key))
diff --git a/lib/gitlab/pages_client.rb b/lib/gitlab/pages_client.rb
index d74fdba2241..6345be0d829 100644
--- a/lib/gitlab/pages_client.rb
+++ b/lib/gitlab/pages_client.rb
@@ -42,10 +42,10 @@ module Gitlab
def request_kwargs(timeout)
encoded_token = Base64.strict_encode64(token.to_s)
metadata = {
- 'authorization' => "Bearer #{encoded_token}"
+ "authorization" => "Bearer #{encoded_token}",
}
- result = { metadata: metadata }
+ result = {metadata: metadata}
return result unless timeout
@@ -75,12 +75,12 @@ module Gitlab
def address
addr = config.address
- addr = addr.sub(%r{^tcp://}, '') if URI(addr).scheme == 'tcp'
+ addr = addr.sub(%r{^tcp://}, "") if URI(addr).scheme == "tcp"
addr
end
def grpc_creds
- if address.start_with?('unix:')
+ if address.start_with?("unix:")
:this_channel_is_insecure
elsif @certificate
GRPC::Core::ChannelCredentials.new(@certificate)
@@ -99,11 +99,11 @@ module Gitlab
end
def token_path
- Rails.root.join('.gitlab_pages_secret').to_s
+ Rails.root.join(".gitlab_pages_secret").to_s
end
def write_token(new_token)
- Tempfile.open(File.basename(token_path), File.dirname(token_path), encoding: 'ascii-8bit') do |f|
+ Tempfile.open(File.basename(token_path), File.dirname(token_path), encoding: "ascii-8bit") do |f|
f.write(new_token)
f.close
File.link(f.path, token_path)
diff --git a/lib/gitlab/patch/sprockets_base_file_digest_key.rb b/lib/gitlab/patch/sprockets_base_file_digest_key.rb
index 1c472638145..48ec8b19d8d 100644
--- a/lib/gitlab/patch/sprockets_base_file_digest_key.rb
+++ b/lib/gitlab/patch/sprockets_base_file_digest_key.rb
@@ -8,7 +8,7 @@ module Gitlab
module SprocketsBaseFileDigestKey
def file_digest(path)
if stat = self.stat(path)
- digest = self.stat_digest(path, stat)
+ digest = stat_digest(path, stat)
integrity_uri = self.integrity_uri(digest)
key = Sprockets::UnloadedAsset.new(path, self).file_digest_key(integrity_uri)
diff --git a/lib/gitlab/path_regex.rb b/lib/gitlab/path_regex.rb
index 3c888be0710..def61009216 100644
--- a/lib/gitlab/path_regex.rb
+++ b/lib/gitlab/path_regex.rb
@@ -125,9 +125,9 @@ module Gitlab
# allow non-regex validations, etc), `NAMESPACE_FORMAT_REGEX_JS` serves as a Javascript-compatible version of
# `NAMESPACE_FORMAT_REGEX`, with the negative lookbehind assertion removed. This means that the client-side validation
# will pass for usernames ending in `.atom` and `.git`, but will be caught by the server-side validation.
- PATH_START_CHAR = '[a-zA-Z0-9_\.]'.freeze
- PATH_REGEX_STR = PATH_START_CHAR + '[a-zA-Z0-9_\-\.]*'.freeze
- NAMESPACE_FORMAT_REGEX_JS = PATH_REGEX_STR + '[a-zA-Z0-9_\-]|[a-zA-Z0-9_]'.freeze
+ PATH_START_CHAR = '[a-zA-Z0-9_\.]'
+ PATH_REGEX_STR = PATH_START_CHAR + '[a-zA-Z0-9_\-\.]*'
+ NAMESPACE_FORMAT_REGEX_JS = PATH_REGEX_STR + '[a-zA-Z0-9_\-]|[a-zA-Z0-9_]'
NO_SUFFIX_REGEX = /(?<!\.git|\.atom)/.freeze
NAMESPACE_FORMAT_REGEX = /(?:#{NAMESPACE_FORMAT_REGEX_JS})#{NO_SUFFIX_REGEX}/.freeze
@@ -238,7 +238,7 @@ module Gitlab
def single_line_regexp(regex)
# Turns a multiline extended regexp into a single line one,
# because `rake routes` breaks on multiline regexes.
- Regexp.new(regex.source.gsub(/\(\?#.+?\)/, '').gsub(/\s*/, ''), regex.options ^ Regexp::EXTENDED).freeze
+ Regexp.new(regex.source.gsub(/\(\?#.+?\)/, "").gsub(/\s*/, ""), regex.options ^ Regexp::EXTENDED).freeze
end
end
end
diff --git a/lib/gitlab/performance_bar.rb b/lib/gitlab/performance_bar.rb
index 4b0c7b5c7f8..8ae4420333e 100644
--- a/lib/gitlab/performance_bar.rb
+++ b/lib/gitlab/performance_bar.rb
@@ -2,7 +2,7 @@
module Gitlab
module PerformanceBar
- ALLOWED_USER_IDS_KEY = 'performance_bar_allowed_user_ids:v2'.freeze
+ ALLOWED_USER_IDS_KEY = "performance_bar_allowed_user_ids:v2"
EXPIRY_TIME = 5.minutes
def self.enabled?(user = nil)
diff --git a/lib/gitlab/performance_bar/peek_query_tracker.rb b/lib/gitlab/performance_bar/peek_query_tracker.rb
index ac392432427..42d7616d88b 100644
--- a/lib/gitlab/performance_bar/peek_query_tracker.rb
+++ b/lib/gitlab/performance_bar/peek_query_tracker.rb
@@ -24,13 +24,13 @@ module Gitlab
PEEK_DB_CLIENT.query_details = []
end
- subscribe('sql.active_record') do |_, start, finish, _, data|
+ subscribe("sql.active_record") do |_, start, finish, _, data|
if Gitlab::SafeRequestStore.store[:peek_enabled]
# data[:cached] is only available starting from Rails 5.1.0
# https://github.com/rails/rails/blob/v5.1.0/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb#L113
# Before that, data[:name] was set to 'CACHE'
# https://github.com/rails/rails/blob/v4.2.9/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb#L80
- unless data.fetch(:cached, data[:name] == 'CACHE')
+ unless data.fetch(:cached, data[:name] == "CACHE")
track_query(data[:sql].strip, data[:binds], start, finish)
end
end
@@ -39,7 +39,7 @@ module Gitlab
def track_query(raw_query, bindings, start, finish)
duration = (finish - start) * 1000.0
- query_info = { duration: duration.round(3), sql: raw_query }
+ query_info = {duration: duration.round(3), sql: raw_query}
PEEK_DB_CLIENT.query_details << query_info
end
diff --git a/lib/gitlab/plugin.rb b/lib/gitlab/plugin.rb
index 23353f36025..68620376cff 100644
--- a/lib/gitlab/plugin.rb
+++ b/lib/gitlab/plugin.rb
@@ -3,7 +3,7 @@
module Gitlab
module Plugin
def self.files
- Dir.glob(Rails.root.join('plugins/*')).select do |entry|
+ Dir.glob(Rails.root.join("plugins/*")).select do |entry|
File.file?(entry)
end
end
@@ -15,9 +15,9 @@ module Gitlab
end
def self.execute(file, data)
- result = Gitlab::Popen.popen_with_detail([file]) do |stdin|
+ result = Gitlab::Popen.popen_with_detail([file]) { |stdin|
stdin.write(data.to_json)
- end
+ }
exit_status = result.status&.exitstatus
[exit_status.zero?, result.stderr]
diff --git a/lib/gitlab/plugin_logger.rb b/lib/gitlab/plugin_logger.rb
index df3bd56fd2f..8f85bf0d9bb 100644
--- a/lib/gitlab/plugin_logger.rb
+++ b/lib/gitlab/plugin_logger.rb
@@ -3,7 +3,7 @@
module Gitlab
class PluginLogger < Gitlab::Logger
def self.file_name_noext
- 'plugin'
+ "plugin"
end
end
end
diff --git a/lib/gitlab/polling_interval.rb b/lib/gitlab/polling_interval.rb
index 0f69990df63..3db3a04d881 100644
--- a/lib/gitlab/polling_interval.rb
+++ b/lib/gitlab/polling_interval.rb
@@ -2,7 +2,7 @@
module Gitlab
class PollingInterval
- HEADER_NAME = 'Poll-Interval'.freeze
+ HEADER_NAME = "Poll-Interval"
def self.set_header(response, interval:)
if polling_enabled?
diff --git a/lib/gitlab/popen.rb b/lib/gitlab/popen.rb
index 7fa00d0c68c..a7d39986ac4 100644
--- a/lib/gitlab/popen.rb
+++ b/lib/gitlab/popen.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'fileutils'
-require 'open3'
+require "fileutils"
+require "open3"
module Gitlab
module Popen
@@ -23,15 +23,15 @@ module Gitlab
end
path ||= Dir.pwd
- vars['PWD'] = path
- options = { chdir: path }
+ vars["PWD"] = path
+ options = {chdir: path}
unless File.directory?(path)
FileUtils.mkdir_p(path)
end
- cmd_stdout = ''
- cmd_stderr = ''
+ cmd_stdout = ""
+ cmd_stderr = ""
cmd_status = nil
start = Time.now
diff --git a/lib/gitlab/private_commit_email.rb b/lib/gitlab/private_commit_email.rb
index 536fc9dae3a..886c2c32d36 100644
--- a/lib/gitlab/private_commit_email.rb
+++ b/lib/gitlab/private_commit_email.rb
@@ -2,7 +2,7 @@
module Gitlab
module PrivateCommitEmail
- TOKEN = "_private".freeze
+ TOKEN = "_private"
class << self
def regex
diff --git a/lib/gitlab/profiler.rb b/lib/gitlab/profiler.rb
index 93a9fcf1591..dc6b7ee989e 100644
--- a/lib/gitlab/profiler.rb
+++ b/lib/gitlab/profiler.rb
@@ -1,9 +1,8 @@
-# coding: utf-8
# frozen_string_literal: true
module Gitlab
module Profiler
- FILTERED_STRING = '[FILTERED]'.freeze
+ FILTERED_STRING = "[FILTERED]"
IGNORE_BACKTRACES = %w[
lib/gitlab/i18n.rb
@@ -43,11 +42,11 @@ module Gitlab
if post_data
verb = :post
- headers['Content-Type'] = 'application/json'
+ headers["Content-Type"] = "application/json"
end
if private_token
- headers['Private-Token'] = private_token
+ headers["Private-Token"] = private_token
user = nil # private_token overrides user
end
@@ -57,21 +56,21 @@ module Gitlab
# Make an initial call for an asset path in development mode to avoid
# sprockets dominating the profiler output.
- ActionController::Base.helpers.asset_path('katex.css') if Rails.env.development?
+ ActionController::Base.helpers.asset_path("katex.css") if Rails.env.development?
# Rails loads internationalization files lazily the first time a
# translation is needed. Running this prevents this overhead from showing
# up in profiles.
- ::I18n.t('.')[:test_string]
+ ::I18n.t(".")[:test_string]
# Remove API route mounting from the profile.
- app.get('/api/v4/users')
+ app.get("/api/v4/users")
- result = with_custom_logger(logger) do
+ result = with_custom_logger(logger) {
with_user(user) do
RubyProf.profile { app.public_send(verb, url, post_data, headers) } # rubocop:disable GitlabSecurity/PublicSend
end
- end
+ }
RequestStore.end!
@@ -103,7 +102,7 @@ module Gitlab
super
Gitlab::Profiler.clean_backtrace(caller).each do |caller_line|
- stripped_caller_line = caller_line.sub("#{Rails.root}/", '')
+ stripped_caller_line = caller_line.sub("#{Rails.root}/", "")
super(" ↳ #{stripped_caller_line}")
end
@@ -158,18 +157,18 @@ module Gitlab
def self.log_load_times_by_model(logger)
return unless logger.respond_to?(:load_times_by_model)
- summarised_load_times = logger.load_times_by_model.to_a.map do |(model, times)|
+ summarised_load_times = logger.load_times_by_model.to_a.map { |(model, times)|
[model, times.count, times.sum]
- end
+ }
- summarised_load_times.sort_by(&:last).reverse.each do |(model, query_count, time)|
+ summarised_load_times.sort_by(&:last).reverse_each do |(model, query_count, time)|
logger.info("#{model} total (#{query_count}): #{time.round(2)}ms")
end
end
# rubocop: enable CodeReuse/ActiveRecord
def self.print_by_total_time(result, options = {})
- default_options = { sort_method: :total_time }
+ default_options = {sort_method: :total_time}
Gitlab::Profiler::TotalTimeFlatPrinter.new(result).print(STDOUT, default_options.merge(options))
end
diff --git a/lib/gitlab/profiler/total_time_flat_printer.rb b/lib/gitlab/profiler/total_time_flat_printer.rb
index 2c105d2722b..123a89d2880 100644
--- a/lib/gitlab/profiler/total_time_flat_printer.rb
+++ b/lib/gitlab/profiler/total_time_flat_printer.rb
@@ -32,7 +32,7 @@ module Gitlab
method.children_time, # children
method.called, # calls
method.recursive? ? "*" : " ", # cycle
- method_name(method) # name
+ method_name(method), # name
]
end
end
diff --git a/lib/gitlab/project_authorizations/with_nested_groups.rb b/lib/gitlab/project_authorizations/with_nested_groups.rb
index 2372a316ab0..07ef664596e 100644
--- a/lib/gitlab/project_authorizations/with_nested_groups.rb
+++ b/lib/gitlab/project_authorizations/with_nested_groups.rb
@@ -32,8 +32,8 @@ module Gitlab
# access to.
Namespace
.unscoped
- .select([alias_as_column(projects[:id], 'project_id'),
- cte_alias[:access_level]])
+ .select([alias_as_column(projects[:id], "project_id"),
+ cte_alias[:access_level],])
.from(cte_alias)
.joins(:projects),
@@ -42,13 +42,13 @@ module Gitlab
.unscoped
.select([links[:project_id],
least(cte_alias[:access_level],
- links[:group_access],
- 'access_level')])
+ links[:group_access],
+ "access_level"),])
.from(cte_alias)
- .joins('INNER JOIN project_group_links ON project_group_links.group_id = namespaces.id')
- .joins('INNER JOIN projects ON projects.id = project_group_links.project_id')
- .joins('INNER JOIN namespaces p_ns ON p_ns.id = projects.namespace_id')
- .where('p_ns.share_with_group_lock IS FALSE')
+ .joins("INNER JOIN project_group_links ON project_group_links.group_id = namespaces.id")
+ .joins("INNER JOIN projects ON projects.id = project_group_links.project_id")
+ .joins("INNER JOIN namespaces p_ns ON p_ns.id = projects.namespace_id")
+ .where("p_ns.share_with_group_lock IS FALSE"),
]
ProjectAuthorization
@@ -75,7 +75,7 @@ module Gitlab
# Sub groups of any groups the user is a member of.
cte << Group.select([namespaces[:id],
greatest(members[:access_level],
- cte.table[:access_level], 'access_level')])
+ cte.table[:access_level], "access_level"),])
.joins(join_cte(cte))
.joins(join_members)
.except(:order)
@@ -90,7 +90,7 @@ module Gitlab
cond = members[:source_id]
.eq(namespaces[:id])
- .and(members[:source_type].eq('Namespace'))
+ .and(members[:source_type].eq("Namespace"))
.and(members[:requested_at].eq(nil))
.and(members[:user_id].eq(user.id))
@@ -106,11 +106,11 @@ module Gitlab
end
def greatest(left, right, column_alias)
- sql_function('GREATEST', [left, right], column_alias)
+ sql_function("GREATEST", [left, right], column_alias)
end
def least(left, right, column_alias)
- sql_function('LEAST', [left, right], column_alias)
+ sql_function("LEAST", [left, right], column_alias)
end
def sql_function(name, args, column_alias)
diff --git a/lib/gitlab/project_authorizations/without_nested_groups.rb b/lib/gitlab/project_authorizations/without_nested_groups.rb
index 50b41b17649..f5daa209ba4 100644
--- a/lib/gitlab/project_authorizations/without_nested_groups.rb
+++ b/lib/gitlab/project_authorizations/without_nested_groups.rb
@@ -23,7 +23,7 @@ module Gitlab
user.groups_projects.select_for_project_authorization,
# Projects shared with groups the user is a member of
- user.groups.joins(:shared_projects).select_for_project_authorization
+ user.groups.joins(:shared_projects).select_for_project_authorization,
]
ProjectAuthorization
diff --git a/lib/gitlab/project_search_results.rb b/lib/gitlab/project_search_results.rb
index a68f8801c2a..d43cf442ada 100644
--- a/lib/gitlab/project_search_results.rb
+++ b/lib/gitlab/project_search_results.rb
@@ -14,13 +14,13 @@ module Gitlab
def objects(scope, page = nil)
case scope
- when 'notes'
+ when "notes"
notes.page(page).per(per_page)
- when 'blobs'
+ when "blobs"
paginated_blobs(blobs, page)
- when 'wiki_blobs'
+ when "wiki_blobs"
paginated_blobs(wiki_blobs, page)
- when 'commits'
+ when "commits"
Kaminari.paginate_array(commits).page(page).per(per_page)
else
super(scope, page, false)
@@ -35,7 +35,7 @@ module Gitlab
def limited_notes_count
return @limited_notes_count if defined?(@limited_notes_count)
- types = %w(issue merge_request commit snippet)
+ types = %w[issue merge_request commit snippet]
@limited_notes_count = 0
types.each do |type|
@@ -58,9 +58,9 @@ module Gitlab
def single_commit_result?
return false if commits_count != 1
- counts = %i(limited_milestones_count limited_notes_count
+ counts = %i[limited_milestones_count limited_notes_count
limited_merge_requests_count limited_issues_count
- blobs_count wiki_blobs_count)
+ blobs_count wiki_blobs_count]
counts.all? { |count_method| public_send(count_method).zero? } # rubocop:disable GitlabSecurity/PublicSend
end
@@ -85,10 +85,10 @@ module Gitlab
@wiki_blobs ||= begin
if project.wiki_enabled? && query.present?
- unless project.wiki.empty?
- Gitlab::WikiFileFinder.new(project, repository_wiki_ref).find(query)
- else
+ if project.wiki.empty?
[]
+ else
+ Gitlab::WikiFileFinder.new(project, repository_wiki_ref).find(query)
end
else
[]
@@ -102,7 +102,7 @@ module Gitlab
# rubocop: disable CodeReuse/ActiveRecord
def notes_finder(type)
- NotesFinder.new(project, @current_user, search: query, target_type: type).execute.user.order('updated_at DESC')
+ NotesFinder.new(project, @current_user, search: query, target_type: type).execute.user.order("updated_at DESC")
end
# rubocop: enable CodeReuse/ActiveRecord
diff --git a/lib/gitlab/project_service_logger.rb b/lib/gitlab/project_service_logger.rb
index 9b0357d3161..1b75e1d04e6 100644
--- a/lib/gitlab/project_service_logger.rb
+++ b/lib/gitlab/project_service_logger.rb
@@ -3,7 +3,7 @@
module Gitlab
class ProjectServiceLogger < Gitlab::JsonLogger
def self.file_name_noext
- 'integrations_json'
+ "integrations_json"
end
end
end
diff --git a/lib/gitlab/project_template.rb b/lib/gitlab/project_template.rb
index 9b6ff602fcd..1eaac9c3a40 100644
--- a/lib/gitlab/project_template.rb
+++ b/lib/gitlab/project_template.rb
@@ -4,7 +4,7 @@ module Gitlab
class ProjectTemplate
attr_reader :title, :name, :description, :preview, :logo
- def initialize(name, title, description, preview, logo = 'illustrations/gitlab_logo.svg')
+ def initialize(name, title, description, preview, logo = "illustrations/gitlab_logo.svg")
@name, @title, @description, @preview, @logo = name, title, description, preview, logo
end
@@ -25,21 +25,21 @@ module Gitlab
end
TEMPLATES_TABLE = [
- ProjectTemplate.new('rails', 'Ruby on Rails', _('Includes an MVC structure, Gemfile, Rakefile, along with many others, to help you get started.'), 'https://gitlab.com/gitlab-org/project-templates/rails', 'illustrations/logos/rails.svg'),
- ProjectTemplate.new('spring', 'Spring', _('Includes an MVC structure, mvnw and pom.xml to help you get started.'), 'https://gitlab.com/gitlab-org/project-templates/spring', 'illustrations/logos/spring.svg'),
- ProjectTemplate.new('express', 'NodeJS Express', _('Includes an MVC structure to help you get started.'), 'https://gitlab.com/gitlab-org/project-templates/express', 'illustrations/logos/express.svg'),
- ProjectTemplate.new('dotnetcore', '.NET Core', _('A .NET Core console application template, customizable for any .NET Core project'), 'https://gitlab.com/gitlab-org/project-templates/dotnetcore', 'illustrations/logos/dotnet.svg'),
- ProjectTemplate.new('gomicro', 'Go Micro', _('Go Micro is a framework for micro service development.'), 'https://gitlab.com/gitlab-org/project-templates/go-micro'),
- ProjectTemplate.new('hugo', 'Pages/Hugo', _('Everything you need to create a GitLab Pages site using Hugo.'), 'https://gitlab.com/pages/hugo'),
- ProjectTemplate.new('jekyll', 'Pages/Jekyll', _('Everything you need to create a GitLab Pages site using Jekyll.'), 'https://gitlab.com/pages/jekyll'),
- ProjectTemplate.new('plainhtml', 'Pages/Plain HTML', _('Everything you need to create a GitLab Pages site using plain HTML.'), 'https://gitlab.com/pages/plain-html'),
- ProjectTemplate.new('gitbook', 'Pages/GitBook', _('Everything you need to create a GitLab Pages site using GitBook.'), 'https://gitlab.com/pages/gitbook'),
- ProjectTemplate.new('hexo', 'Pages/Hexo', _('Everything you need to create a GitLab Pages site using Hexo.'), 'https://gitlab.com/pages/hexo'),
- ProjectTemplate.new('nfhugo', 'Netlify/Hugo', _('A Hugo site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features.'), 'https://gitlab.com/pages/nfhugo', 'illustrations/logos/netlify.svg'),
- ProjectTemplate.new('nfjekyll', 'Netlify/Jekyll', _('A Jekyll site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features.'), 'https://gitlab.com/pages/nfjekyll', 'illustrations/logos/netlify.svg'),
- ProjectTemplate.new('nfplainhtml', 'Netlify/Plain HTML', _('A plain HTML site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features.'), 'https://gitlab.com/pages/nfplain-html', 'illustrations/logos/netlify.svg'),
- ProjectTemplate.new('nfgitbook', 'Netlify/GitBook', _('A GitBook site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features.'), 'https://gitlab.com/pages/nfgitbook', 'illustrations/logos/netlify.svg'),
- ProjectTemplate.new('nfhexo', 'Netlify/Hexo', _('A Hexo site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features.'), 'https://gitlab.com/pages/nfhexo', 'illustrations/logos/netlify.svg')
+ ProjectTemplate.new("rails", "Ruby on Rails", _("Includes an MVC structure, Gemfile, Rakefile, along with many others, to help you get started."), "https://gitlab.com/gitlab-org/project-templates/rails", "illustrations/logos/rails.svg"),
+ ProjectTemplate.new("spring", "Spring", _("Includes an MVC structure, mvnw and pom.xml to help you get started."), "https://gitlab.com/gitlab-org/project-templates/spring", "illustrations/logos/spring.svg"),
+ ProjectTemplate.new("express", "NodeJS Express", _("Includes an MVC structure to help you get started."), "https://gitlab.com/gitlab-org/project-templates/express", "illustrations/logos/express.svg"),
+ ProjectTemplate.new("dotnetcore", ".NET Core", _("A .NET Core console application template, customizable for any .NET Core project"), "https://gitlab.com/gitlab-org/project-templates/dotnetcore", "illustrations/logos/dotnet.svg"),
+ ProjectTemplate.new("gomicro", "Go Micro", _("Go Micro is a framework for micro service development."), "https://gitlab.com/gitlab-org/project-templates/go-micro"),
+ ProjectTemplate.new("hugo", "Pages/Hugo", _("Everything you need to create a GitLab Pages site using Hugo."), "https://gitlab.com/pages/hugo"),
+ ProjectTemplate.new("jekyll", "Pages/Jekyll", _("Everything you need to create a GitLab Pages site using Jekyll."), "https://gitlab.com/pages/jekyll"),
+ ProjectTemplate.new("plainhtml", "Pages/Plain HTML", _("Everything you need to create a GitLab Pages site using plain HTML."), "https://gitlab.com/pages/plain-html"),
+ ProjectTemplate.new("gitbook", "Pages/GitBook", _("Everything you need to create a GitLab Pages site using GitBook."), "https://gitlab.com/pages/gitbook"),
+ ProjectTemplate.new("hexo", "Pages/Hexo", _("Everything you need to create a GitLab Pages site using Hexo."), "https://gitlab.com/pages/hexo"),
+ ProjectTemplate.new("nfhugo", "Netlify/Hugo", _("A Hugo site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features."), "https://gitlab.com/pages/nfhugo", "illustrations/logos/netlify.svg"),
+ ProjectTemplate.new("nfjekyll", "Netlify/Jekyll", _("A Jekyll site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features."), "https://gitlab.com/pages/nfjekyll", "illustrations/logos/netlify.svg"),
+ ProjectTemplate.new("nfplainhtml", "Netlify/Plain HTML", _("A plain HTML site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features."), "https://gitlab.com/pages/nfplain-html", "illustrations/logos/netlify.svg"),
+ ProjectTemplate.new("nfgitbook", "Netlify/GitBook", _("A GitBook site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features."), "https://gitlab.com/pages/nfgitbook", "illustrations/logos/netlify.svg"),
+ ProjectTemplate.new("nfhexo", "Netlify/Hexo", _("A Hexo site that uses Netlify for CI/CD instead of GitLab, but still with all the other great GitLab features."), "https://gitlab.com/pages/nfhexo", "illustrations/logos/netlify.svg"),
].freeze
class << self
diff --git a/lib/gitlab/project_transfer.rb b/lib/gitlab/project_transfer.rb
index d8f1d1e2316..171da51f270 100644
--- a/lib/gitlab/project_transfer.rb
+++ b/lib/gitlab/project_transfer.rb
@@ -5,8 +5,8 @@ module Gitlab
class ProjectTransfer
# nil parent_path (or parent_path_was) represents a root namespace
def move_namespace(path, parent_path_was, parent_path)
- parent_path_was ||= ''
- parent_path ||= ''
+ parent_path_was ||= ""
+ parent_path ||= ""
new_parent_folder = File.join(root_dir, parent_path)
FileUtils.mkdir_p(new_parent_folder)
from = File.join(root_dir, parent_path_was, path)
@@ -14,7 +14,7 @@ module Gitlab
move(from, to, "")
end
- alias_method :move_project, :move_namespace
+ alias move_project move_namespace
def rename_project(path_was, path, namespace_path)
base_dir = File.join(root_dir, namespace_path)
@@ -32,7 +32,7 @@ module Gitlab
private
def move(path_was, path, base_dir = nil)
- base_dir = root_dir unless base_dir
+ base_dir ||= root_dir
from = File.join(base_dir, path_was)
to = File.join(base_dir, path)
FileUtils.mv(from, to)
diff --git a/lib/gitlab/prometheus/additional_metrics_parser.rb b/lib/gitlab/prometheus/additional_metrics_parser.rb
index bd4ca578840..3a3f3629861 100644
--- a/lib/gitlab/prometheus/additional_metrics_parser.rb
+++ b/lib/gitlab/prometheus/additional_metrics_parser.rb
@@ -3,7 +3,7 @@
module Gitlab
module Prometheus
module AdditionalMetricsParser
- CONFIG_ROOT = 'config/prometheus'.freeze
+ CONFIG_ROOT = "config/prometheus"
MUTEX = Mutex.new
extend self
diff --git a/lib/gitlab/prometheus/metric.rb b/lib/gitlab/prometheus/metric.rb
index 7ebfc2e25a9..2ef4c3f6b39 100644
--- a/lib/gitlab/prometheus/metric.rb
+++ b/lib/gitlab/prometheus/metric.rb
@@ -11,7 +11,7 @@ module Gitlab
def initialize(params = {})
super(params)
- @y_label ||= 'Values'
+ @y_label ||= "Values"
end
end
end
diff --git a/lib/gitlab/prometheus/metric_group.rb b/lib/gitlab/prometheus/metric_group.rb
index 394556e8708..2912bab54f7 100644
--- a/lib/gitlab/prometheus/metric_group.rb
+++ b/lib/gitlab/prometheus/metric_group.rb
@@ -10,13 +10,13 @@ module Gitlab
validates :name, :priority, :metrics, presence: true
def self.common_metrics
- all_groups = ::PrometheusMetric.common.group_by(&:group_title).map do |name, metrics|
+ all_groups = ::PrometheusMetric.common.group_by(&:group_title).map { |name, metrics|
MetricGroup.new(
name: name,
priority: metrics.map(&:priority).max,
metrics: metrics.map(&:to_query_metric)
)
- end
+ }
all_groups.sort_by(&:priority).reverse
end
diff --git a/lib/gitlab/prometheus/queries/deployment_query.rb b/lib/gitlab/prometheus/queries/deployment_query.rb
index fc32c4353f0..4559f23508c 100644
--- a/lib/gitlab/prometheus/queries/deployment_query.rb
+++ b/lib/gitlab/prometheus/queries/deployment_query.rb
@@ -24,7 +24,7 @@ module Gitlab
cpu_values: client_query_range(cpu_query, start: timeframe_start, stop: timeframe_end),
cpu_before: client_query(cpu_avg_query, time: deployment.created_at.to_f),
- cpu_after: client_query(cpu_avg_query, time: timeframe_end)
+ cpu_after: client_query(cpu_avg_query, time: timeframe_end),
}
end
end
diff --git a/lib/gitlab/prometheus/queries/environment_query.rb b/lib/gitlab/prometheus/queries/environment_query.rb
index 56195f85a70..fd284246397 100644
--- a/lib/gitlab/prometheus/queries/environment_query.rb
+++ b/lib/gitlab/prometheus/queries/environment_query.rb
@@ -18,7 +18,7 @@ module Gitlab
memory_values: client_query_range(memory_query, start: timeframe_start, stop: timeframe_end),
memory_current: client_query(memory_query, time: timeframe_end),
cpu_values: client_query_range(cpu_query, start: timeframe_start, stop: timeframe_end),
- cpu_current: client_query(cpu_query, time: timeframe_end)
+ cpu_current: client_query(cpu_query, time: timeframe_end),
}
end
end
diff --git a/lib/gitlab/prometheus/queries/matched_metric_query.rb b/lib/gitlab/prometheus/queries/matched_metric_query.rb
index 32294756aa2..b640a045768 100644
--- a/lib/gitlab/prometheus/queries/matched_metric_query.rb
+++ b/lib/gitlab/prometheus/queries/matched_metric_query.rb
@@ -4,7 +4,7 @@ module Gitlab
module Prometheus
module Queries
class MatchedMetricQuery < BaseQuery
- MAX_QUERY_ITEMS = 40.freeze
+ MAX_QUERY_ITEMS = 40
def query
groups_data.map do |group, data|
@@ -12,7 +12,7 @@ module Gitlab
group: group.name,
priority: group.priority,
active_metrics: data[:active_metrics],
- metrics_missing_requirements: data[:metrics_missing_requirements]
+ metrics_missing_requirements: data[:metrics_missing_requirements],
}
end
end
@@ -26,7 +26,7 @@ module Gitlab
groups = {}
metrics_groups.each do |group|
- groups[group] ||= { active_metrics: 0, metrics_missing_requirements: 0 }
+ groups[group] ||= {active_metrics: 0, metrics_missing_requirements: 0}
active_metrics = group.metrics.count { |metric| metric.required_metrics.all?(&lookup.method(:has_key?)) }
groups[group][:active_metrics] += active_metrics
@@ -42,16 +42,16 @@ module Gitlab
series = metric_groups.flat_map(&:metrics).flat_map(&:required_metrics).uniq
- lookup = series.each_slice(MAX_QUERY_ITEMS).flat_map do |batched_series|
+ lookup = series.each_slice(MAX_QUERY_ITEMS).flat_map { |batched_series|
client_series(*batched_series, start: timeframe_start, stop: timeframe_end)
.select(&method(:has_matching_label?))
- .map { |series_info| [series_info['__name__'], true] }
- end
+ .map { |series_info| [series_info["__name__"], true] }
+ }
lookup.to_h
end
def has_matching_label?(series_info)
- series_info.key?('environment')
+ series_info.key?("environment")
end
def available_metrics
diff --git a/lib/gitlab/prometheus/queries/query_additional_metrics.rb b/lib/gitlab/prometheus/queries/query_additional_metrics.rb
index 960d3536ec0..c10438cfe16 100644
--- a/lib/gitlab/prometheus/queries/query_additional_metrics.rb
+++ b/lib/gitlab/prometheus/queries/query_additional_metrics.rb
@@ -15,23 +15,23 @@ module Gitlab
query_processor = method(:process_query).curry[query_context]
lambda do |group|
- metrics = group.metrics.map do |metric|
+ metrics = group.metrics.map { |metric|
metric_hsh = {
title: metric.title,
weight: metric.weight,
y_label: metric.y_label,
- queries: metric.queries.map(&query_processor).select(&method(:query_with_result))
+ queries: metric.queries.map(&query_processor).select(&method(:query_with_result)),
}
metric_hsh[:id] = metric.id if metric.id
metric_hsh
- end
+ }
{
group: group.name,
priority: group.priority,
- metrics: metrics.select(&method(:metric_with_any_queries))
+ metrics: metrics.select(&method(:metric_with_any_queries)),
}
end
end
@@ -72,12 +72,12 @@ module Gitlab
end
def matched_metrics(project)
- result = Gitlab::Prometheus::MetricGroup.for_project(project).map do |group|
+ result = Gitlab::Prometheus::MetricGroup.for_project(project).map { |group|
group.metrics.select! do |metric|
metric.required_metrics.all?(&available_metrics.method(:include?))
end
group
- end
+ }
result.select { |group| group.metrics.any? }
end
@@ -90,7 +90,7 @@ module Gitlab
def base_query_context(timeframe_start, timeframe_end)
{
timeframe_start: timeframe_start,
- timeframe_end: timeframe_end
+ timeframe_end: timeframe_end,
}
end
end
diff --git a/lib/gitlab/prometheus/query_variables.rb b/lib/gitlab/prometheus/query_variables.rb
index 1cc85d4b4a6..ef02c830dac 100644
--- a/lib/gitlab/prometheus/query_variables.rb
+++ b/lib/gitlab/prometheus/query_variables.rb
@@ -6,8 +6,8 @@ module Gitlab
def self.call(environment)
{
ci_environment_slug: environment.slug,
- kube_namespace: environment.deployment_platform&.actual_namespace || '',
- environment_filter: %{container_name!="POD",environment="#{environment.slug}"}
+ kube_namespace: environment.deployment_platform&.actual_namespace || "",
+ environment_filter: %(container_name!="POD",environment="#{environment.slug}"),
}
end
end
diff --git a/lib/gitlab/prometheus_client.rb b/lib/gitlab/prometheus_client.rb
index 45828c77a33..a7bcc04fa12 100644
--- a/lib/gitlab/prometheus_client.rb
+++ b/lib/gitlab/prometheus_client.rb
@@ -13,42 +13,42 @@ module Gitlab
end
def ping
- json_api_get('query', query: '1')
+ json_api_get("query", query: "1")
end
def query(query, time: Time.now)
- get_result('vector') do
- json_api_get('query', query: query, time: time.to_f)
+ get_result("vector") do
+ json_api_get("query", query: query, time: time.to_f)
end
end
def query_range(query, start: 8.hours.ago, stop: Time.now)
- get_result('matrix') do
- json_api_get('query_range',
- query: query,
- start: start.to_f,
- end: stop.to_f,
- step: 1.minute.to_i)
+ get_result("matrix") do
+ json_api_get("query_range",
+ query: query,
+ start: start.to_f,
+ end: stop.to_f,
+ step: 1.minute.to_i)
end
end
- def label_values(name = '__name__')
+ def label_values(name = "__name__")
json_api_get("label/#{name}/values")
end
def series(*matches, start: 8.hours.ago, stop: Time.now)
- json_api_get('series', 'match': matches, start: start.to_f, end: stop.to_f)
+ json_api_get("series", 'match': matches, start: start.to_f, end: stop.to_f)
end
private
def json_api_get(type, args = {})
- path = ['api', 'v1', type].join('/')
+ path = ["api", "v1", type].join("/")
get(path, args)
rescue JSON::ParserError
- raise PrometheusClient::Error, 'Parsing response failed'
+ raise PrometheusClient::Error, "Parsing response failed"
rescue Errno::ECONNREFUSED
- raise PrometheusClient::Error, 'Connection refused'
+ raise PrometheusClient::Error, "Connection refused"
end
def get(path, args)
@@ -70,19 +70,19 @@ module Gitlab
def handle_response(response)
json_data = JSON.parse(response.body)
- if response.code == 200 && json_data['status'] == 'success'
- json_data['data'] || {}
+ if response.code == 200 && json_data["status"] == "success"
+ json_data["data"] || {}
else
raise PrometheusClient::Error, "#{response.code} - #{response.body}"
end
end
def handle_exception_response(response)
- if response.code == 200 && response['status'] == 'success'
- response['data'] || {}
+ if response.code == 200 && response["status"] == "success"
+ response["data"] || {}
elsif response.code == 400
json_data = JSON.parse(response.body)
- raise PrometheusClient::QueryError, json_data['error'] || 'Bad data received'
+ raise PrometheusClient::QueryError, json_data["error"] || "Bad data received"
else
raise PrometheusClient::Error, "#{response.code} - #{response.body}"
end
@@ -90,7 +90,7 @@ module Gitlab
def get_result(expected_type)
data = yield
- data['result'] if data['resultType'] == expected_type
+ data["result"] if data["resultType"] == expected_type
end
end
end
diff --git a/lib/gitlab/protocol_access.rb b/lib/gitlab/protocol_access.rb
index efeb1e07d49..c5889f8c4a7 100644
--- a/lib/gitlab/protocol_access.rb
+++ b/lib/gitlab/protocol_access.rb
@@ -3,7 +3,7 @@
module Gitlab
module ProtocolAccess
def self.allowed?(protocol)
- if protocol == 'web'
+ if protocol == "web"
true
elsif Gitlab::CurrentSettings.enabled_git_access_protocol.blank?
true
diff --git a/lib/gitlab/query_limiting.rb b/lib/gitlab/query_limiting.rb
index 31e6b120e45..72d2cde1c09 100644
--- a/lib/gitlab/query_limiting.rb
+++ b/lib/gitlab/query_limiting.rb
@@ -21,10 +21,10 @@ module Gitlab
def self.whitelist(issue_url)
return unless enable_whitelist?
- unless issue_url.start_with?('https://')
+ unless issue_url.start_with?("https://")
raise(
ArgumentError,
- 'You must provide a valid issue URL in order to whitelist a block of code'
+ "You must provide a valid issue URL in order to whitelist a block of code"
)
end
diff --git a/lib/gitlab/query_limiting/active_support_subscriber.rb b/lib/gitlab/query_limiting/active_support_subscriber.rb
index 065862174bb..3e9614da57b 100644
--- a/lib/gitlab/query_limiting/active_support_subscriber.rb
+++ b/lib/gitlab/query_limiting/active_support_subscriber.rb
@@ -6,7 +6,7 @@ module Gitlab
attach_to :active_record
def sql(event)
- unless event.payload.fetch(:cached, event.payload[:name] == 'CACHE')
+ unless event.payload.fetch(:cached, event.payload[:name] == "CACHE")
Transaction.current&.increment
end
end
diff --git a/lib/gitlab/query_limiting/middleware.rb b/lib/gitlab/query_limiting/middleware.rb
index 949ae79a047..65810b0a7cf 100644
--- a/lib/gitlab/query_limiting/middleware.rb
+++ b/lib/gitlab/query_limiting/middleware.rb
@@ -5,17 +5,17 @@ module Gitlab
# Middleware for reporting (or raising) when a request performs more than a
# certain amount of database queries.
class Middleware
- CONTROLLER_KEY = 'action_controller.instance'.freeze
- ENDPOINT_KEY = 'api.endpoint'.freeze
+ CONTROLLER_KEY = "action_controller.instance"
+ ENDPOINT_KEY = "api.endpoint"
def initialize(app)
@app = app
end
def call(env)
- transaction, retval = Transaction.run do
+ transaction, retval = Transaction.run {
@app.call(env)
- end
+ }
transaction.action = action_name(env)
transaction.act_upon_results
@@ -37,7 +37,7 @@ module Gitlab
controller = env[CONTROLLER_KEY]
action = "#{controller.class.name}##{controller.action_name}"
- if controller.content_type == 'text/html'
+ if controller.content_type == "text/html"
action
else
"#{action} (#{controller.content_type})"
@@ -46,7 +46,11 @@ module Gitlab
def action_for_grape(env)
endpoint = env[ENDPOINT_KEY]
- route = endpoint.route rescue nil
+ route = begin
+ endpoint.route
+ rescue
+ nil
+ end
"#{route.request_method} #{route.path}" if route
end
diff --git a/lib/gitlab/query_limiting/transaction.rb b/lib/gitlab/query_limiting/transaction.rb
index e8fad067fa6..a764d88d5f6 100644
--- a/lib/gitlab/query_limiting/transaction.rb
+++ b/lib/gitlab/query_limiting/transaction.rb
@@ -69,7 +69,7 @@ module Gitlab
end
def error_message
- header = 'Too many SQL queries were executed'
+ header = "Too many SQL queries were executed"
header = "#{header} in #{action}" if action
"#{header}: a maximum of #{THRESHOLD} is allowed but #{count} SQL queries were executed"
diff --git a/lib/gitlab/quick_actions/command_definition.rb b/lib/gitlab/quick_actions/command_definition.rb
index 259345b8a9a..5b36bc7f9ec 100644
--- a/lib/gitlab/quick_actions/command_definition.rb
+++ b/lib/gitlab/quick_actions/command_definition.rb
@@ -10,9 +10,9 @@ module Gitlab
@name = name
@aliases = attributes[:aliases] || []
- @description = attributes[:description] || ''
- @warning = attributes[:warning] || ''
- @explanation = attributes[:explanation] || ''
+ @description = attributes[:description] || ""
+ @warning = attributes[:warning] || ""
+ @explanation = attributes[:explanation] || ""
@params = attributes[:params] || []
@condition_block = attributes[:condition_block]
@parse_params_block = attributes[:parse_params_block]
@@ -37,10 +37,10 @@ module Gitlab
return unless available?(context)
message = if explanation.respond_to?(:call)
- execute_block(explanation, context, arg)
- else
- explanation
- end
+ execute_block(explanation, context, arg)
+ else
+ explanation
+ end
warning.empty? ? message : "#{message} (#{warning})"
end
@@ -54,12 +54,20 @@ module Gitlab
def to_h(context)
desc = description
if desc.respond_to?(:call)
- desc = context.instance_exec(&desc) rescue ''
+ desc = begin
+ context.instance_exec(&desc)
+ rescue
+ ""
+ end
end
prms = params
if prms.respond_to?(:call)
- prms = Array(context.instance_exec(&prms)) rescue params
+ prms = begin
+ Array(context.instance_exec(&prms))
+ rescue
+ params
+ end
end
{
@@ -67,7 +75,7 @@ module Gitlab
aliases: aliases,
description: desc,
warning: warning,
- params: prms
+ params: prms,
}
end
diff --git a/lib/gitlab/quick_actions/dsl.rb b/lib/gitlab/quick_actions/dsl.rb
index a3aab92061b..aad462e5383 100644
--- a/lib/gitlab/quick_actions/dsl.rb
+++ b/lib/gitlab/quick_actions/dsl.rb
@@ -29,11 +29,11 @@ module Gitlab
# command :command_key do |arguments|
# # Awesome code block
# end
- def desc(text = '', &block)
+ def desc(text = "", &block)
@description = block_given? ? block : text
end
- def warning(message = '')
+ def warning(message = "")
@warning = message
end
@@ -62,7 +62,7 @@ module Gitlab
# command :command_key do |arguments|
# # Awesome code block
# end
- def explanation(text = '', &block)
+ def explanation(text = "", &block)
@explanation = block_given? ? block : text
end
@@ -147,10 +147,10 @@ module Gitlab
action_block: block
)
- self.command_definitions << definition
+ command_definitions << definition
definition.all_names.each do |name|
- self.command_definitions_by_name[name] = definition
+ command_definitions_by_name[name] = definition
end
@description = nil
diff --git a/lib/gitlab/quick_actions/extractor.rb b/lib/gitlab/quick_actions/extractor.rb
index ff9bb293b47..2fa83527224 100644
--- a/lib/gitlab/quick_actions/extractor.rb
+++ b/lib/gitlab/quick_actions/extractor.rb
@@ -42,7 +42,7 @@ module Gitlab
content.gsub!(commands_regex(only: only)) do
if $~[:cmd]
commands << [$~[:cmd].downcase, $~[:arg]].reject(&:blank?)
- ''
+ ""
else
$~[0]
end
@@ -117,9 +117,9 @@ module Gitlab
def perform_substitutions(content, commands)
return unless content
- substitution_definitions = self.command_definitions.select do |definition|
+ substitution_definitions = command_definitions.select { |definition|
definition.is_a?(Gitlab::QuickActions::SubstitutionDefinition)
- end
+ }
substitution_definitions.each do |substitution|
match_data = substitution.match(content.downcase)
@@ -136,7 +136,7 @@ module Gitlab
end
def command_names(limit_to_commands:)
- command_definitions.flat_map do |command|
+ command_definitions.flat_map { |command|
next if command.noop?
if limit_to_commands && (command.all_names & limit_to_commands).empty?
@@ -144,7 +144,7 @@ module Gitlab
end
command.all_names
- end.compact
+ }.compact
end
end
end
diff --git a/lib/gitlab/quick_actions/spend_time_and_date_separator.rb b/lib/gitlab/quick_actions/spend_time_and_date_separator.rb
index f5176376a60..e1ffe5cc834 100644
--- a/lib/gitlab/quick_actions/spend_time_and_date_separator.rb
+++ b/lib/gitlab/quick_actions/spend_time_and_date_separator.rb
@@ -28,7 +28,7 @@ module Gitlab
private
def get_time
- raw_time = @spend_arg.gsub(DATE_REGEX, '')
+ raw_time = @spend_arg.gsub(DATE_REGEX, "")
Gitlab::TimeTrackingFormatter.parse(raw_time)
end
@@ -43,7 +43,11 @@ module Gitlab
def valid_date?
string_date = @spend_arg.match(DATE_REGEX)[0]
- date = Date.parse(string_date) rescue nil
+ date = begin
+ Date.parse(string_date)
+ rescue
+ nil
+ end
date_past_or_today?(date)
end
diff --git a/lib/gitlab/redis/cache.rb b/lib/gitlab/redis/cache.rb
index 6e8403ad878..5ece44f707a 100644
--- a/lib/gitlab/redis/cache.rb
+++ b/lib/gitlab/redis/cache.rb
@@ -1,14 +1,14 @@
# frozen_string_literal: true
# please require all dependencies below:
-require_relative 'wrapper' unless defined?(::Rails) && ::Rails.root.present?
+require_relative "wrapper" unless defined?(::Rails) && ::Rails.root.present?
module Gitlab
module Redis
class Cache < ::Gitlab::Redis::Wrapper
- CACHE_NAMESPACE = 'cache:gitlab'.freeze
- DEFAULT_REDIS_CACHE_URL = 'redis://localhost:6380'.freeze
- REDIS_CACHE_CONFIG_ENV_VAR_NAME = 'GITLAB_REDIS_CACHE_CONFIG_FILE'.freeze
+ CACHE_NAMESPACE = "cache:gitlab"
+ DEFAULT_REDIS_CACHE_URL = "redis://localhost:6380"
+ REDIS_CACHE_CONFIG_ENV_VAR_NAME = "GITLAB_REDIS_CACHE_CONFIG_FILE"
class << self
def default_url
@@ -21,7 +21,7 @@ module Gitlab
return file_name unless file_name.nil?
# otherwise, if config files exists for this class, use it
- file_name = config_file_path('redis.cache.yml')
+ file_name = config_file_path("redis.cache.yml")
return file_name if File.file?(file_name)
# this will force use of DEFAULT_REDIS_QUEUES_URL when config file is absent
diff --git a/lib/gitlab/redis/queues.rb b/lib/gitlab/redis/queues.rb
index 8b42c269dd0..8f45d2016d1 100644
--- a/lib/gitlab/redis/queues.rb
+++ b/lib/gitlab/redis/queues.rb
@@ -1,15 +1,15 @@
# frozen_string_literal: true
# please require all dependencies below:
-require_relative 'wrapper' unless defined?(::Gitlab::Redis::Wrapper)
+require_relative "wrapper" unless defined?(::Gitlab::Redis::Wrapper)
module Gitlab
module Redis
class Queues < ::Gitlab::Redis::Wrapper
- SIDEKIQ_NAMESPACE = 'resque:gitlab'.freeze
- MAILROOM_NAMESPACE = 'mail_room:gitlab'.freeze
- DEFAULT_REDIS_QUEUES_URL = 'redis://localhost:6381'.freeze
- REDIS_QUEUES_CONFIG_ENV_VAR_NAME = 'GITLAB_REDIS_QUEUES_CONFIG_FILE'.freeze
+ SIDEKIQ_NAMESPACE = "resque:gitlab"
+ MAILROOM_NAMESPACE = "mail_room:gitlab"
+ DEFAULT_REDIS_QUEUES_URL = "redis://localhost:6381"
+ REDIS_QUEUES_CONFIG_ENV_VAR_NAME = "GITLAB_REDIS_QUEUES_CONFIG_FILE"
class << self
def default_url
@@ -22,7 +22,7 @@ module Gitlab
return file_name if file_name
# otherwise, if config files exists for this class, use it
- file_name = config_file_path('redis.queues.yml')
+ file_name = config_file_path("redis.queues.yml")
return file_name if File.file?(file_name)
# this will force use of DEFAULT_REDIS_QUEUES_URL when config file is absent
diff --git a/lib/gitlab/redis/shared_state.rb b/lib/gitlab/redis/shared_state.rb
index 9066606ca21..fa1fd9f2ca5 100644
--- a/lib/gitlab/redis/shared_state.rb
+++ b/lib/gitlab/redis/shared_state.rb
@@ -1,16 +1,16 @@
# frozen_string_literal: true
# please require all dependencies below:
-require_relative 'wrapper' unless defined?(::Gitlab::Redis::Wrapper)
+require_relative "wrapper" unless defined?(::Gitlab::Redis::Wrapper)
module Gitlab
module Redis
class SharedState < ::Gitlab::Redis::Wrapper
- SESSION_NAMESPACE = 'session:gitlab'.freeze
- USER_SESSIONS_NAMESPACE = 'session:user:gitlab'.freeze
- USER_SESSIONS_LOOKUP_NAMESPACE = 'session:lookup:user:gitlab'.freeze
- DEFAULT_REDIS_SHARED_STATE_URL = 'redis://localhost:6382'.freeze
- REDIS_SHARED_STATE_CONFIG_ENV_VAR_NAME = 'GITLAB_REDIS_SHARED_STATE_CONFIG_FILE'.freeze
+ SESSION_NAMESPACE = "session:gitlab"
+ USER_SESSIONS_NAMESPACE = "session:user:gitlab"
+ USER_SESSIONS_LOOKUP_NAMESPACE = "session:lookup:user:gitlab"
+ DEFAULT_REDIS_SHARED_STATE_URL = "redis://localhost:6382"
+ REDIS_SHARED_STATE_CONFIG_ENV_VAR_NAME = "GITLAB_REDIS_SHARED_STATE_CONFIG_FILE"
class << self
def default_url
@@ -23,7 +23,7 @@ module Gitlab
return file_name if file_name
# otherwise, if config files exists for this class, use it
- file_name = config_file_path('redis.shared_state.yml')
+ file_name = config_file_path("redis.shared_state.yml")
return file_name if File.file?(file_name)
# this will force use of DEFAULT_REDIS_SHARED_STATE_URL when config file is absent
diff --git a/lib/gitlab/redis/wrapper.rb b/lib/gitlab/redis/wrapper.rb
index 07a1e20b076..90ec49facf4 100644
--- a/lib/gitlab/redis/wrapper.rb
+++ b/lib/gitlab/redis/wrapper.rb
@@ -2,14 +2,14 @@
# This file should only be used by sub-classes, not directly by any clients of the sub-classes
# please require all dependencies below:
-require 'active_support/core_ext/hash/keys'
-require 'active_support/core_ext/module/delegation'
+require "active_support/core_ext/hash/keys"
+require "active_support/core_ext/module/delegation"
module Gitlab
module Redis
class Wrapper
- DEFAULT_REDIS_URL = 'redis://localhost:6379'.freeze
- REDIS_CONFIG_ENV_VAR_NAME = 'GITLAB_REDIS_CONFIG_FILE'.freeze
+ DEFAULT_REDIS_URL = "redis://localhost:6379"
+ REDIS_CONFIG_ENV_VAR_NAME = "GITLAB_REDIS_CONFIG_FILE"
class << self
delegate :params, :url, to: :new
@@ -63,7 +63,7 @@ module Gitlab
return file_name unless file_name.nil?
# otherwise, if config files exists for wrapper class, use it
- file_name = config_file_path('resque.yml')
+ file_name = config_file_path("resque.yml")
return file_name if File.file?(file_name)
# nil will force use of DEFAULT_REDIS_URL when config file is absent
@@ -98,7 +98,7 @@ module Gitlab
redis_url = config.delete(:url)
redis_uri = URI.parse(redis_url)
- if redis_uri.scheme == 'unix'
+ if redis_uri.scheme == "unix"
# Redis::Store does not handle Unix sockets well, so let's do it for them
config[:path] = redis_uri.path
query = redis_uri.query
@@ -121,9 +121,9 @@ module Gitlab
config_data = fetch_config
if config_data
- config_data.is_a?(String) ? { url: config_data } : config_data.deep_symbolize_keys
+ config_data.is_a?(String) ? {url: config_data} : config_data.deep_symbolize_keys
else
- { url: self.class.default_url }
+ {url: self.class.default_url}
end
end
diff --git a/lib/gitlab/reference_extractor.rb b/lib/gitlab/reference_extractor.rb
index 00f817c2399..1dba71d3303 100644
--- a/lib/gitlab/reference_extractor.rb
+++ b/lib/gitlab/reference_extractor.rb
@@ -3,7 +3,7 @@
module Gitlab
# Extract possible GFM references from an arbitrary String for further processing.
class ReferenceExtractor < Banzai::ReferenceExtractor
- REFERABLES = %i(user issue label milestone merge_request snippet commit commit_range directly_addressed_user epic).freeze
+ REFERABLES = %i[user issue label milestone merge_request snippet commit commit_range directly_addressed_user epic].freeze
attr_accessor :project, :current_user, :author
def initialize(project, current_user = nil)
@@ -34,7 +34,7 @@ module Gitlab
end
def issues
- if project && project.jira_tracker?
+ if project&.jira_tracker?
if project.issues_enabled?
@references[:all_issues] ||= references(:external_issue) + references(:issue)
else
@@ -54,9 +54,9 @@ module Gitlab
def self.references_pattern
return @pattern if @pattern
- patterns = REFERABLES.map do |ref|
+ patterns = REFERABLES.map { |ref|
ref.to_s.classify.constantize.try(:reference_pattern)
- end
+ }
@pattern = Regexp.union(patterns.compact)
end
diff --git a/lib/gitlab/repo_path.rb b/lib/gitlab/repo_path.rb
index 202d310e237..480bc6d1284 100644
--- a/lib/gitlab/repo_path.rb
+++ b/lib/gitlab/repo_path.rb
@@ -6,12 +6,12 @@ module Gitlab
def self.parse(repo_path)
wiki = false
- project_path = repo_path.sub(/\.git\z/, '').sub(%r{\A/}, '')
+ project_path = repo_path.sub(/\.git\z/, "").sub(%r{\A/}, "")
project, was_redirected = find_project(project_path)
- if project_path.end_with?('.wiki') && project.nil?
- project, was_redirected = find_project(project_path.chomp('.wiki'))
+ if project_path.end_with?(".wiki") && project.nil?
+ project, was_redirected = find_project(project_path.chomp(".wiki"))
wiki = true
end
diff --git a/lib/gitlab/repository_cache_adapter.rb b/lib/gitlab/repository_cache_adapter.rb
index 931298b5117..eec75247b8e 100644
--- a/lib/gitlab/repository_cache_adapter.rb
+++ b/lib/gitlab/repository_cache_adapter.rb
@@ -160,7 +160,7 @@ module Gitlab
private
def memoizable_name(name)
- "#{name.to_s.tr('?!', '')}"
+ name.to_s.tr("?!", "").to_s
end
def expire_request_store_method_caches(methods)
diff --git a/lib/gitlab/repository_check_logger.rb b/lib/gitlab/repository_check_logger.rb
index e90b0a002af..9fd2727e59e 100644
--- a/lib/gitlab/repository_check_logger.rb
+++ b/lib/gitlab/repository_check_logger.rb
@@ -3,7 +3,7 @@
module Gitlab
class RepositoryCheckLogger < Gitlab::Logger
def self.file_name_noext
- 'repocheck'
+ "repocheck"
end
end
end
diff --git a/lib/gitlab/request_profiler.rb b/lib/gitlab/request_profiler.rb
index 64593153686..0abebf3d215 100644
--- a/lib/gitlab/request_profiler.rb
+++ b/lib/gitlab/request_profiler.rb
@@ -1,13 +1,13 @@
# frozen_string_literal: true
-require 'fileutils'
+require "fileutils"
module Gitlab
module RequestProfiler
- PROFILES_DIR = "#{Gitlab.config.shared.path}/tmp/requests_profiles".freeze
+ PROFILES_DIR = "#{Gitlab.config.shared.path}/tmp/requests_profiles"
def profile_token
- Rails.cache.fetch('profile-token') do
+ Rails.cache.fetch("profile-token") do
Devise.friendly_token
end
end
diff --git a/lib/gitlab/request_profiler/middleware.rb b/lib/gitlab/request_profiler/middleware.rb
index 7615f6f443b..1a6ec735449 100644
--- a/lib/gitlab/request_profiler/middleware.rb
+++ b/lib/gitlab/request_profiler/middleware.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'ruby-prof'
+require "ruby-prof"
module Gitlab
module RequestProfiler
@@ -18,7 +18,7 @@ module Gitlab
end
def profile?(env)
- header_token = env['HTTP_X_PROFILE_TOKEN']
+ header_token = env["HTTP_X_PROFILE_TOKEN"]
return unless header_token.present?
profile_token = Gitlab::RequestProfiler.profile_token
@@ -29,18 +29,18 @@ module Gitlab
def call_with_profiling(env)
ret = nil
- result = RubyProf::Profile.profile do
- ret = catch(:warden) do
+ result = RubyProf::Profile.profile {
+ ret = catch(:warden) {
@app.call(env)
- end
- end
+ }
+ }
printer = RubyProf::CallStackPrinter.new(result)
- file_name = "#{env['PATH_INFO'].tr('/', '|')}_#{Time.current.to_i}.html"
+ file_name = "#{env["PATH_INFO"].tr("/", "|")}_#{Time.current.to_i}.html"
file_path = "#{PROFILES_DIR}/#{file_name}"
FileUtils.mkdir_p(PROFILES_DIR)
- File.open(file_path, 'wb') do |file|
+ File.open(file_path, "wb") do |file|
printer.print(file)
end
diff --git a/lib/gitlab/request_profiler/profile.rb b/lib/gitlab/request_profiler/profile.rb
index 46996ef8c51..da27ce806c7 100644
--- a/lib/gitlab/request_profiler/profile.rb
+++ b/lib/gitlab/request_profiler/profile.rb
@@ -5,7 +5,7 @@ module Gitlab
class Profile
attr_reader :name, :time, :request_path
- alias_method :to_param, :name
+ alias to_param name
def self.all
Dir["#{PROFILES_DIR}/*.html"].map do |path|
@@ -15,7 +15,7 @@ module Gitlab
def self.find(name)
name_dup = name.dup
- name_dup << '.html' unless name.end_with?('.html')
+ name_dup << ".html" unless name.end_with?(".html")
file_path = "#{PROFILES_DIR}/#{name_dup}"
return unless File.exist?(file_path)
@@ -37,7 +37,7 @@ module Gitlab
def set_attributes
_, path, timestamp = name.split(/(.*)_(\d+)\.html$/)
- @request_path = path.tr('|', '/')
+ @request_path = path.tr("|", "/")
@time = Time.at(timestamp.to_i).utc
end
end
diff --git a/lib/gitlab/route_map.rb b/lib/gitlab/route_map.rb
index a555bf1d812..46620f7988d 100644
--- a/lib/gitlab/route_map.rb
+++ b/lib/gitlab/route_map.rb
@@ -8,10 +8,10 @@ module Gitlab
begin
entries = YAML.safe_load(data)
rescue
- raise FormatError, 'Route map is not valid YAML'
+ raise FormatError, "Route map is not valid YAML"
end
- raise FormatError, 'Route map is not an array' unless entries.is_a?(Array)
+ raise FormatError, "Route map is not an array" unless entries.is_a?(Array)
@map = entries.map { |entry| parse_entry(entry) }
end
@@ -30,15 +30,15 @@ module Gitlab
private
def parse_entry(entry)
- raise FormatError, 'Route map entry is not a hash' unless entry.is_a?(Hash)
- raise FormatError, 'Route map entry does not have a source key' unless entry.key?('source')
- raise FormatError, 'Route map entry does not have a public key' unless entry.key?('public')
+ raise FormatError, "Route map entry is not a hash" unless entry.is_a?(Hash)
+ raise FormatError, "Route map entry does not have a source key" unless entry.key?("source")
+ raise FormatError, "Route map entry does not have a public key" unless entry.key?("public")
- source_pattern = entry['source']
- public_path = entry['public']
+ source_pattern = entry["source"]
+ public_path = entry["public"]
- if source_pattern.start_with?('/') && source_pattern.end_with?('/')
- source_pattern = source_pattern[1...-1].gsub('\/', '/')
+ if source_pattern.start_with?("/") && source_pattern.end_with?("/")
+ source_pattern = source_pattern[1...-1].gsub('\/', "/")
begin
source_pattern = Gitlab::UntrustedRegexp.new('\A' + source_pattern + '\z')
@@ -49,7 +49,7 @@ module Gitlab
{
source: source_pattern,
- public: public_path
+ public: public_path,
}
end
end
diff --git a/lib/gitlab/routing.rb b/lib/gitlab/routing.rb
index 3b05f181ed2..7a2fb3ad52c 100644
--- a/lib/gitlab/routing.rb
+++ b/lib/gitlab/routing.rb
@@ -14,7 +14,7 @@ module Gitlab
end
def self.includes_helpers(klass)
- self._includers << klass
+ _includers << klass
end
def self.add_helpers(mod)
@@ -56,9 +56,9 @@ module Gitlab
paths.each do |path|
router.match "/#{path}(/*rest)",
- via: [:get, :post, :patch, :delete],
- to: router.redirect { |params, request| build_redirect_path.call(request, params, path) },
- as: "legacy_#{path}_redirect"
+ via: [:get, :post, :patch, :delete],
+ to: router.redirect { |params, request| build_redirect_path.call(request, params, path) },
+ as: "legacy_#{path}_redirect"
end
end
end
diff --git a/lib/gitlab/sanitizers/svg.rb b/lib/gitlab/sanitizers/svg.rb
index 0d4e6be2129..a17df42ce22 100644
--- a/lib/gitlab/sanitizers/svg.rb
+++ b/lib/gitlab/sanitizers/svg.rb
@@ -47,11 +47,11 @@ module Gitlab
end
def unsafe_href?(attr)
- attribute_name_with_namespace(attr) == 'xlink:href' && !attr.value.start_with?('#')
+ attribute_name_with_namespace(attr) == "xlink:href" && !attr.value.start_with?("#")
end
def data_attribute?(attr)
- attr.name.start_with?('data-') && attr.name =~ DATA_ATTR_PATTERN && attr.namespace.nil?
+ attr.name.start_with?("data-") && attr.name =~ DATA_ATTR_PATTERN && attr.namespace.nil?
end
end
end
diff --git a/lib/gitlab/sanitizers/svg/whitelist.rb b/lib/gitlab/sanitizers/svg/whitelist.rb
index b4da24b3215..3a7ca597835 100644
--- a/lib/gitlab/sanitizers/svg/whitelist.rb
+++ b/lib/gitlab/sanitizers/svg/whitelist.rb
@@ -25,86 +25,86 @@ module Gitlab
ALLOWED_DATA_ATTRIBUTES_IN_ELEMENTS = %w[svg].freeze
ALLOWED_ATTRIBUTES = {
- 'a' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage target text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
- 'altGlyph' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dx dy enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight format glyph-orientation-horizontal glyph-orientation-vertical glyphRef id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures rotate shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering unicode-bidi visibility word-spacing writing-mode x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
- 'altGlyphDef' => %w[id xml:base xml:lang xml:space],
- 'altGlyphItem' => %w[id xml:base xml:lang xml:space],
- 'animate' => %w[accumulate additive alignment-baseline attributeName attributeType baseline-shift begin by calcMode clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dur enable-background end externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight from glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning keySplines keyTimes letter-spacing lighting-color marker-end marker-mid marker-start mask max min onbegin onend onload onrepeat opacity overflow pointer-events repeatCount repeatDur requiredExtensions requiredFeatures restart shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width systemLanguage text-anchor text-decoration text-rendering to unicode-bidi values visibility word-spacing writing-mode xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
- 'animateColor' => %w[accumulate additive alignment-baseline attributeName attributeType baseline-shift begin by calcMode clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dur enable-background end externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight from glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning keySplines keyTimes letter-spacing lighting-color marker-end marker-mid marker-start mask max min onbegin onend onload onrepeat opacity overflow pointer-events repeatCount repeatDur requiredExtensions requiredFeatures restart shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width systemLanguage text-anchor text-decoration text-rendering to unicode-bidi values visibility word-spacing writing-mode xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
- 'animateMotion' => %w[accumulate additive begin by calcMode dur end externalResourcesRequired fill from id keyPoints keySplines keyTimes max min onbegin onend onload onrepeat origin path repeatCount repeatDur requiredExtensions requiredFeatures restart rotate systemLanguage to values xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
- 'animateTransform' => %w[accumulate additive attributeName attributeType begin by calcMode dur end externalResourcesRequired fill from id keySplines keyTimes max min onbegin onend onload onrepeat repeatCount repeatDur requiredExtensions requiredFeatures restart systemLanguage to type values xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
- 'circle' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor cx cy direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events r requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'clipPath' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule clipPathUnits color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'color-profile' => %w[id local name rendering-intent xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
- 'cursor' => %w[externalResourcesRequired id requiredExtensions requiredFeatures systemLanguage x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
- 'defs' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'desc' => %w[class id style xml:base xml:lang xml:space],
- 'ellipse' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor cx cy direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures rx ry shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'feBlend' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in in2 kerning letter-spacing lighting-color marker-end marker-mid marker-start mask mode opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'feColorMatrix' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering type unicode-bidi values visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'feComponentTransfer' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'feComposite' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in in2 k1 k2 k3 k4 kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity operator overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'feConvolveMatrix' => %w[alignment-baseline baseline-shift bias class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display divisor dominant-baseline edgeMode enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kernelMatrix kernelUnitLength kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity order overflow pointer-events preserveAlpha result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style targetX targetY text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'feDiffuseLighting' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor diffuseConstant direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kernelUnitLength kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style surfaceScale text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'feDisplacementMap' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in in2 kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result scale shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xChannelSelector xml:base xml:lang xml:space y yChannelSelector],
- 'feDistantLight' => %w[azimuth elevation id xml:base xml:lang xml:space],
- 'feFlood' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'feFuncA' => %w[amplitude exponent id intercept offset slope tableValues type xml:base xml:lang xml:space],
- 'feFuncB' => %w[amplitude exponent id intercept offset slope tableValues type xml:base xml:lang xml:space],
- 'feFuncG' => %w[amplitude exponent id intercept offset slope tableValues type xml:base xml:lang xml:space],
- 'feFuncR' => %w[amplitude exponent id intercept offset slope tableValues type xml:base xml:lang xml:space],
- 'feGaussianBlur' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stdDeviation stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'feImage' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events preserveAspectRatio result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
- 'feMerge' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'feMergeNode' => %w[id xml:base xml:lang xml:space],
- 'feMorphology' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity operator overflow pointer-events radius result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'feOffset' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dx dy enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'fePointLight' => %w[id x xml:base xml:lang xml:space y z],
- 'feSpecularLighting' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kernelUnitLength kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering specularConstant specularExponent stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style surfaceScale text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'feSpotLight' => %w[id limitingConeAngle pointsAtX pointsAtY pointsAtZ specularExponent x xml:base xml:lang xml:space y z],
- 'feTile' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'feTurbulence' => %w[alignment-baseline baseFrequency baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask numOctaves opacity overflow pointer-events result seed shape-rendering stitchTiles stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering type unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'filter' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter filterRes filterUnits flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events primitiveUnits shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
- 'font' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x horiz-origin-y id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi vert-adv-y vert-origin-x vert-origin-y visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'font-face' => %w[accent-height alphabetic ascent bbox cap-height descent font-family font-size font-stretch font-style font-variant font-weight hanging id ideographic mathematical overline-position overline-thickness panose-1 slope stemh stemv strikethrough-position strikethrough-thickness underline-position underline-thickness unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical widths x-height xml:base xml:lang xml:space],
- 'font-face-format' => %w[id string xml:base xml:lang xml:space],
- 'font-face-name' => %w[id name xml:base xml:lang xml:space],
- 'font-face-src' => %w[id xml:base xml:lang xml:space],
- 'font-face-uri' => %w[id xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
- 'foreignObject' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'g' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'glyph' => %w[alignment-baseline arabic-form baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor d direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x id image-rendering kerning lang letter-spacing lighting-color marker-end marker-mid marker-start mask opacity orientation overflow pointer-events shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode unicode-bidi vert-adv-y vert-origin-x vert-origin-y visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'glyphRef' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dx dy enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight format glyph-orientation-horizontal glyph-orientation-vertical glyphRef id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility word-spacing writing-mode x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
- 'hkern' => %w[g1 g2 id k u1 u2 xml:base xml:lang xml:space],
- 'image' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events preserveAspectRatio requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility width word-spacing writing-mode x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
- 'line' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode x1 x2 xml:base xml:lang xml:space y1 y2],
- 'linearGradient' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical gradientTransform gradientUnits id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events shape-rendering spreadMethod stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility word-spacing writing-mode x1 x2 xlink:arcrole xlink:href xlink:role xlink:title xlink:type xml:base xml:lang xml:space y1 y2],
- 'marker' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start markerHeight markerUnits markerWidth mask opacity orient overflow pointer-events preserveAspectRatio refX refY shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi viewBox visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'mask' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask maskContentUnits maskUnits opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'metadata' => %w[id xml:base xml:lang xml:space],
- 'missing-glyph' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor d direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi vert-adv-y vert-origin-x vert-origin-y visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'mpath' => %w[externalResourcesRequired id xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
- 'path' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor d direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pathLength pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'pattern' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow patternContentUnits patternTransform patternUnits pointer-events preserveAspectRatio requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering unicode-bidi viewBox visibility width word-spacing writing-mode x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
- 'polygon' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events points requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'polyline' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events points requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'radialGradient' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor cx cy direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight fx fy glyph-orientation-horizontal glyph-orientation-vertical gradientTransform gradientUnits id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events r shape-rendering spreadMethod stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility word-spacing writing-mode xlink:arcrole xlink:href xlink:role xlink:title xlink:type xml:base xml:lang xml:space],
- 'rect' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures rx ry shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'script' => %w[externalResourcesRequired id type xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
- 'set' => %w[attributeName attributeType begin dur end externalResourcesRequired fill id max min onbegin onend onload onrepeat repeatCount repeatDur requiredExtensions requiredFeatures restart systemLanguage to xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
- 'stop' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask offset opacity overflow pointer-events shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'style' => %w[id media title type xml:base xml:lang xml:space],
- 'svg' => %w[alignment-baseline baseProfile baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering contentScriptType contentStyleType cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onabort onactivate onclick onerror onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup onresize onscroll onunload onzoom opacity overflow pointer-events preserveAspectRatio requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering unicode-bidi version viewBox visibility width word-spacing writing-mode x xml:base xml:lang xml:space xmlns y zoomAndPan],
- 'switch' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'symbol' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events preserveAspectRatio shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi viewBox visibility word-spacing writing-mode xml:base xml:lang xml:space],
- 'text' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dx dy enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning lengthAdjust letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures rotate shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering textLength transform unicode-bidi visibility word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'textPath' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning lengthAdjust letter-spacing lighting-color marker-end marker-mid marker-start mask method onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering spacing startOffset stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering textLength unicode-bidi visibility word-spacing writing-mode xlink:arcrole xlink:href xlink:role xlink:title xlink:type xml:base xml:lang xml:space],
- 'title' => %w[class id style xml:base xml:lang xml:space],
- 'tref' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dx dy enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning lengthAdjust letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures rotate shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering textLength unicode-bidi visibility word-spacing writing-mode x xlink:arcrole xlink:href xlink:role xlink:title xlink:type xml:base xml:lang xml:space y],
- 'tspan' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dx dy enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning lengthAdjust letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures rotate shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering textLength unicode-bidi visibility word-spacing writing-mode x xml:base xml:lang xml:space y],
- 'use' => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility width word-spacing writing-mode x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
- 'view' => %w[externalResourcesRequired id preserveAspectRatio viewBox viewTarget xml:base xml:lang xml:space zoomAndPan],
- 'vkern' => %w[g1 g2 id k u1 u2 xml:base xml:lang xml:space]
+ "a" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage target text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
+ "altGlyph" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dx dy enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight format glyph-orientation-horizontal glyph-orientation-vertical glyphRef id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures rotate shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering unicode-bidi visibility word-spacing writing-mode x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
+ "altGlyphDef" => %w[id xml:base xml:lang xml:space],
+ "altGlyphItem" => %w[id xml:base xml:lang xml:space],
+ "animate" => %w[accumulate additive alignment-baseline attributeName attributeType baseline-shift begin by calcMode clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dur enable-background end externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight from glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning keySplines keyTimes letter-spacing lighting-color marker-end marker-mid marker-start mask max min onbegin onend onload onrepeat opacity overflow pointer-events repeatCount repeatDur requiredExtensions requiredFeatures restart shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width systemLanguage text-anchor text-decoration text-rendering to unicode-bidi values visibility word-spacing writing-mode xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
+ "animateColor" => %w[accumulate additive alignment-baseline attributeName attributeType baseline-shift begin by calcMode clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dur enable-background end externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight from glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning keySplines keyTimes letter-spacing lighting-color marker-end marker-mid marker-start mask max min onbegin onend onload onrepeat opacity overflow pointer-events repeatCount repeatDur requiredExtensions requiredFeatures restart shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width systemLanguage text-anchor text-decoration text-rendering to unicode-bidi values visibility word-spacing writing-mode xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
+ "animateMotion" => %w[accumulate additive begin by calcMode dur end externalResourcesRequired fill from id keyPoints keySplines keyTimes max min onbegin onend onload onrepeat origin path repeatCount repeatDur requiredExtensions requiredFeatures restart rotate systemLanguage to values xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
+ "animateTransform" => %w[accumulate additive attributeName attributeType begin by calcMode dur end externalResourcesRequired fill from id keySplines keyTimes max min onbegin onend onload onrepeat repeatCount repeatDur requiredExtensions requiredFeatures restart systemLanguage to type values xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
+ "circle" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor cx cy direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events r requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "clipPath" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule clipPathUnits color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "color-profile" => %w[id local name rendering-intent xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
+ "cursor" => %w[externalResourcesRequired id requiredExtensions requiredFeatures systemLanguage x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
+ "defs" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "desc" => %w[class id style xml:base xml:lang xml:space],
+ "ellipse" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor cx cy direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures rx ry shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "feBlend" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in in2 kerning letter-spacing lighting-color marker-end marker-mid marker-start mask mode opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "feColorMatrix" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering type unicode-bidi values visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "feComponentTransfer" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "feComposite" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in in2 k1 k2 k3 k4 kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity operator overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "feConvolveMatrix" => %w[alignment-baseline baseline-shift bias class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display divisor dominant-baseline edgeMode enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kernelMatrix kernelUnitLength kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity order overflow pointer-events preserveAlpha result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style targetX targetY text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "feDiffuseLighting" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor diffuseConstant direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kernelUnitLength kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style surfaceScale text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "feDisplacementMap" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in in2 kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result scale shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xChannelSelector xml:base xml:lang xml:space y yChannelSelector],
+ "feDistantLight" => %w[azimuth elevation id xml:base xml:lang xml:space],
+ "feFlood" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "feFuncA" => %w[amplitude exponent id intercept offset slope tableValues type xml:base xml:lang xml:space],
+ "feFuncB" => %w[amplitude exponent id intercept offset slope tableValues type xml:base xml:lang xml:space],
+ "feFuncG" => %w[amplitude exponent id intercept offset slope tableValues type xml:base xml:lang xml:space],
+ "feFuncR" => %w[amplitude exponent id intercept offset slope tableValues type xml:base xml:lang xml:space],
+ "feGaussianBlur" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stdDeviation stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "feImage" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events preserveAspectRatio result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
+ "feMerge" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "feMergeNode" => %w[id xml:base xml:lang xml:space],
+ "feMorphology" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity operator overflow pointer-events radius result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "feOffset" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dx dy enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "fePointLight" => %w[id x xml:base xml:lang xml:space y z],
+ "feSpecularLighting" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kernelUnitLength kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering specularConstant specularExponent stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style surfaceScale text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "feSpotLight" => %w[id limitingConeAngle pointsAtX pointsAtY pointsAtZ specularExponent x xml:base xml:lang xml:space y z],
+ "feTile" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering in kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events result shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "feTurbulence" => %w[alignment-baseline baseFrequency baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask numOctaves opacity overflow pointer-events result seed shape-rendering stitchTiles stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering type unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "filter" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter filterRes filterUnits flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events primitiveUnits shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
+ "font" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x horiz-origin-y id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi vert-adv-y vert-origin-x vert-origin-y visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "font-face" => %w[accent-height alphabetic ascent bbox cap-height descent font-family font-size font-stretch font-style font-variant font-weight hanging id ideographic mathematical overline-position overline-thickness panose-1 slope stemh stemv strikethrough-position strikethrough-thickness underline-position underline-thickness unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical widths x-height xml:base xml:lang xml:space],
+ "font-face-format" => %w[id string xml:base xml:lang xml:space],
+ "font-face-name" => %w[id name xml:base xml:lang xml:space],
+ "font-face-src" => %w[id xml:base xml:lang xml:space],
+ "font-face-uri" => %w[id xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
+ "foreignObject" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "g" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "glyph" => %w[alignment-baseline arabic-form baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor d direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x id image-rendering kerning lang letter-spacing lighting-color marker-end marker-mid marker-start mask opacity orientation overflow pointer-events shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode unicode-bidi vert-adv-y vert-origin-x vert-origin-y visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "glyphRef" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dx dy enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight format glyph-orientation-horizontal glyph-orientation-vertical glyphRef id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility word-spacing writing-mode x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
+ "hkern" => %w[g1 g2 id k u1 u2 xml:base xml:lang xml:space],
+ "image" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events preserveAspectRatio requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility width word-spacing writing-mode x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
+ "line" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode x1 x2 xml:base xml:lang xml:space y1 y2],
+ "linearGradient" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical gradientTransform gradientUnits id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events shape-rendering spreadMethod stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility word-spacing writing-mode x1 x2 xlink:arcrole xlink:href xlink:role xlink:title xlink:type xml:base xml:lang xml:space y1 y2],
+ "marker" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start markerHeight markerUnits markerWidth mask opacity orient overflow pointer-events preserveAspectRatio refX refY shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi viewBox visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "mask" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask maskContentUnits maskUnits opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "metadata" => %w[id xml:base xml:lang xml:space],
+ "missing-glyph" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor d direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi vert-adv-y vert-origin-x vert-origin-y visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "mpath" => %w[externalResourcesRequired id xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
+ "path" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor d direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pathLength pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "pattern" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow patternContentUnits patternTransform patternUnits pointer-events preserveAspectRatio requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering unicode-bidi viewBox visibility width word-spacing writing-mode x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
+ "polygon" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events points requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "polyline" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events points requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "radialGradient" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor cx cy direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight fx fy glyph-orientation-horizontal glyph-orientation-vertical gradientTransform gradientUnits id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events r shape-rendering spreadMethod stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility word-spacing writing-mode xlink:arcrole xlink:href xlink:role xlink:title xlink:type xml:base xml:lang xml:space],
+ "rect" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures rx ry shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility width word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "script" => %w[externalResourcesRequired id type xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
+ "set" => %w[attributeName attributeType begin dur end externalResourcesRequired fill id max min onbegin onend onload onrepeat repeatCount repeatDur requiredExtensions requiredFeatures restart systemLanguage to xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space],
+ "stop" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask offset opacity overflow pointer-events shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "style" => %w[id media title type xml:base xml:lang xml:space],
+ "svg" => %w[alignment-baseline baseProfile baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering contentScriptType contentStyleType cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onabort onactivate onclick onerror onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup onresize onscroll onunload onzoom opacity overflow pointer-events preserveAspectRatio requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering unicode-bidi version viewBox visibility width word-spacing writing-mode x xml:base xml:lang xml:space xmlns y zoomAndPan],
+ "switch" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "symbol" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events preserveAspectRatio shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style text-anchor text-decoration text-rendering unicode-bidi viewBox visibility word-spacing writing-mode xml:base xml:lang xml:space],
+ "text" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dx dy enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning lengthAdjust letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures rotate shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering textLength transform unicode-bidi visibility word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "textPath" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning lengthAdjust letter-spacing lighting-color marker-end marker-mid marker-start mask method onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering spacing startOffset stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering textLength unicode-bidi visibility word-spacing writing-mode xlink:arcrole xlink:href xlink:role xlink:title xlink:type xml:base xml:lang xml:space],
+ "title" => %w[class id style xml:base xml:lang xml:space],
+ "tref" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dx dy enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning lengthAdjust letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures rotate shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering textLength unicode-bidi visibility word-spacing writing-mode x xlink:arcrole xlink:href xlink:role xlink:title xlink:type xml:base xml:lang xml:space y],
+ "tspan" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline dx dy enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical id image-rendering kerning lengthAdjust letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures rotate shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering textLength unicode-bidi visibility word-spacing writing-mode x xml:base xml:lang xml:space y],
+ "use" => %w[alignment-baseline baseline-shift class clip clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering cursor direction display dominant-baseline enable-background externalResourcesRequired fill fill-opacity fill-rule filter flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical height id image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask onactivate onclick onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup opacity overflow pointer-events requiredExtensions requiredFeatures shape-rendering stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style systemLanguage text-anchor text-decoration text-rendering transform unicode-bidi visibility width word-spacing writing-mode x xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y],
+ "view" => %w[externalResourcesRequired id preserveAspectRatio viewBox viewTarget xml:base xml:lang xml:space zoomAndPan],
+ "vkern" => %w[g1 g2 id k u1 u2 xml:base xml:lang xml:space],
}.freeze
end
end
diff --git a/lib/gitlab/search/found_blob.rb b/lib/gitlab/search/found_blob.rb
index a62ab1521a7..4b275b80ac2 100644
--- a/lib/gitlab/search/found_blob.rb
+++ b/lib/gitlab/search/found_blob.rb
@@ -84,7 +84,7 @@ module Gitlab
def fetch_blob
path = [ref, blob_filename]
- missing_blob = { binary_filename: blob_filename }
+ missing_blob = {binary_filename: blob_filename}
BatchLoader.for(path).batch(default_value: missing_blob) do |refs, loader|
Gitlab::Git::Blob.batch(repository, refs, blob_size_limit: 1024).each do |blob|
@@ -97,7 +97,7 @@ module Gitlab
ref: ref,
startline: 1,
binary_data: blob.data,
- project: project
+ project: project,
}
loader.call([ref, blob.path], data)
@@ -138,10 +138,10 @@ module Gitlab
startline = matches[:startline]
startline = startline.to_i - index
extname = Regexp.escape(File.extname(filename))
- basename = filename.sub(/#{extname}$/, '')
+ basename = filename.sub(/#{extname}$/, "")
end
- data << line.sub(prefix.to_s, '')
+ data << line.sub(prefix.to_s, "")
end
{
@@ -150,7 +150,7 @@ module Gitlab
ref: ref,
startline: startline,
binary_data: data.join,
- project: project
+ project: project,
}
end
diff --git a/lib/gitlab/search/query.rb b/lib/gitlab/search/query.rb
index ba0e16607a6..124ca4841fc 100644
--- a/lib/gitlab/search/query.rb
+++ b/lib/gitlab/search/query.rb
@@ -8,9 +8,9 @@ module Gitlab
def initialize(query, filter_opts = {}, &block)
@raw_query = query.dup
@filters = []
- @filter_options = { default_parser: :downcase.to_proc }.merge(filter_opts)
+ @filter_options = {default_parser: :downcase.to_proc}.merge(filter_opts)
- self.instance_eval(&block) if block_given?
+ instance_eval(&block) if block_given?
@query = Gitlab::Search::ParsedQuery.new(*extract_filters)
# set the ParsedQuery as our default delegator thanks to SimpleDelegator
@@ -20,7 +20,7 @@ module Gitlab
private
def filter(name, **attributes)
- filter = { parser: @filter_options[:default_parser], name: name }.merge(attributes)
+ filter = {parser: @filter_options[:default_parser], name: name}.merge(attributes)
@filters << filter
end
@@ -32,21 +32,21 @@ module Gitlab
def extract_filters
fragments = []
- filters = @filters.each_with_object([]) do |filter, parsed_filters|
+ filters = @filters.each_with_object([]) { |filter, parsed_filters|
match = @raw_query.split.find { |part| part =~ /\A#{filter[:name]}:/ }
next unless match
- input = match.split(':')[1..-1].join
+ input = match.split(":")[1..-1].join
next if input.empty?
filter[:value] = parse_filter(filter, input)
- filter[:regex_value] = Regexp.escape(filter[:value]).gsub('\*', '.*?')
+ filter[:regex_value] = Regexp.escape(filter[:value]).gsub('\*', ".*?")
fragments << match
parsed_filters << filter
- end
+ }
- query = (@raw_query.split - fragments).join(' ')
+ query = (@raw_query.split - fragments).join(" ")
[query, filters]
end
diff --git a/lib/gitlab/search_results.rb b/lib/gitlab/search_results.rb
index 491148ec1a6..63b9087fb16 100644
--- a/lib/gitlab/search_results.rb
+++ b/lib/gitlab/search_results.rb
@@ -24,17 +24,17 @@ module Gitlab
def objects(scope, page = nil, without_count = true)
collection = case scope
- when 'projects'
+ when "projects"
projects.page(page).per(per_page)
- when 'issues'
+ when "issues"
issues.page(page).per(per_page)
- when 'merge_requests'
+ when "merge_requests"
merge_requests.page(page).per(per_page)
- when 'milestones'
+ when "milestones"
milestones.page(page).per(per_page)
else
Kaminari.paginate_array([]).page(page).per(per_page)
- end
+ end
without_count ? collection.without_count : collection
end
@@ -99,7 +99,7 @@ module Gitlab
issues.full_search(query)
end
- issues.reorder('updated_at DESC')
+ issues.reorder("updated_at DESC")
end
# rubocop: enable CodeReuse/ActiveRecord
@@ -107,7 +107,7 @@ module Gitlab
def milestones
milestones = Milestone.where(project_id: project_ids_relation)
milestones = milestones.search(query)
- milestones.reorder('updated_at DESC')
+ milestones.reorder("updated_at DESC")
end
# rubocop: enable CodeReuse/ActiveRecord
@@ -125,12 +125,12 @@ module Gitlab
merge_requests.full_search(query)
end
- merge_requests.reorder('updated_at DESC')
+ merge_requests.reorder("updated_at DESC")
end
# rubocop: enable CodeReuse/ActiveRecord
def default_scope
- 'projects'
+ "projects"
end
# rubocop: disable CodeReuse/ActiveRecord
diff --git a/lib/gitlab/sentry.rb b/lib/gitlab/sentry.rb
index 956c16117f5..851a1f9a5a8 100644
--- a/lib/gitlab/sentry.rb
+++ b/lib/gitlab/sentry.rb
@@ -45,7 +45,7 @@ module Gitlab
context # Make sure we've set everything we know in the context
tags = {
- Gitlab::CorrelationId::LOG_KEY.to_sym => Gitlab::CorrelationId.current_id
+ Gitlab::CorrelationId::LOG_KEY.to_sym => Gitlab::CorrelationId.current_id,
}
Raven.capture_exception(exception, tags: tags, extra: extra)
diff --git a/lib/gitlab/setup_helper.rb b/lib/gitlab/setup_helper.rb
index 2b7e12639be..a662b1d3311 100644
--- a/lib/gitlab/setup_helper.rb
+++ b/lib/gitlab/setup_helper.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'toml-rb'
+require "toml-rb"
module Gitlab
module SetupHelper
@@ -19,29 +19,29 @@ module Gitlab
Gitlab.config.repositories.storages.each do |key, val|
if address
- if address != val['gitaly_address']
+ if address != val["gitaly_address"]
raise ArgumentError, "Your gitlab.yml contains more than one gitaly_address."
end
- elsif URI(val['gitaly_address']).scheme != 'unix'
+ elsif URI(val["gitaly_address"]).scheme != "unix"
raise ArgumentError, "Automatic config.toml generation only supports 'unix:' addresses."
else
- address = val['gitaly_address']
+ address = val["gitaly_address"]
end
- storages << { name: key, path: storage_paths[key] }
+ storages << {name: key, path: storage_paths[key]}
end
if Rails.env.test?
- storage_path = Rails.root.join('tmp', 'tests', 'second_storage').to_s
+ storage_path = Rails.root.join("tmp", "tests", "second_storage").to_s
FileUtils.mkdir(storage_path) unless File.exist?(storage_path)
- storages << { name: 'test_second_storage', path: storage_path }
+ storages << {name: "test_second_storage", path: storage_path}
end
- config = { socket_path: address.sub(/\Aunix:/, ''), storage: storages }
- config[:auth] = { token: 'secret' } if Rails.env.test?
- config[:'gitaly-ruby'] = { dir: File.join(gitaly_dir, 'ruby') } if gitaly_ruby
- config[:'gitlab-shell'] = { dir: Gitlab.config.gitlab_shell.path }
+ config = {socket_path: address.sub(/\Aunix:/, ""), storage: storages}
+ config[:auth] = {token: "secret"} if Rails.env.test?
+ config[:'gitaly-ruby'] = {dir: File.join(gitaly_dir, "ruby")} if gitaly_ruby
+ config[:'gitlab-shell'] = {dir: Gitlab.config.gitlab_shell.path}
config[:bin_dir] = Gitlab.config.gitaly.client_path
TomlRB.dump(config)
@@ -49,7 +49,7 @@ module Gitlab
# rubocop:disable Rails/Output
def create_gitaly_configuration(dir, storage_paths, force: false)
- config_path = File.join(dir, 'config.toml')
+ config_path = File.join(dir, "config.toml")
FileUtils.rm_f(config_path) if force
File.open(config_path, File::WRONLY | File::CREAT | File::EXCL) do |f|
diff --git a/lib/gitlab/shard_health_cache.rb b/lib/gitlab/shard_health_cache.rb
index 6612347438e..dca3ab942a5 100644
--- a/lib/gitlab/shard_health_cache.rb
+++ b/lib/gitlab/shard_health_cache.rb
@@ -2,7 +2,7 @@
module Gitlab
class ShardHealthCache
- HEALTHY_SHARDS_KEY = 'gitlab-healthy-shards'.freeze
+ HEALTHY_SHARDS_KEY = "gitlab-healthy-shards"
HEALTHY_SHARDS_TIMEOUT = 300
# Clears the Redis set storing the list of healthy shards
diff --git a/lib/gitlab/shell.rb b/lib/gitlab/shell.rb
index 40b641b8317..c1ba80c9cbc 100644
--- a/lib/gitlab/shell.rb
+++ b/lib/gitlab/shell.rb
@@ -2,15 +2,15 @@
# Gitaly note: SSH key operations are not part of Gitaly so will never be migrated.
-require 'securerandom'
+require "securerandom"
module Gitlab
class Shell
- GITLAB_SHELL_ENV_VARS = %w(GIT_TERMINAL_PROMPT).freeze
+ GITLAB_SHELL_ENV_VARS = %w[GIT_TERMINAL_PROMPT].freeze
Error = Class.new(StandardError)
- KeyAdder = Struct.new(:io) do
+ KeyAdder = Struct.new(:io) {
def add_key(id, key)
key = Gitlab::Shell.strip_key(key)
# Newline and tab are part of the 'protocol' used to transmit id+key to the other end
@@ -20,7 +20,7 @@ module Gitlab
io.puts("#{id}\t#{key}")
end
- end
+ }
class << self
def secret_token
@@ -30,18 +30,18 @@ module Gitlab
end
def ensure_secret_token!
- return if File.exist?(File.join(Gitlab.config.gitlab_shell.path, '.gitlab_shell_secret'))
+ return if File.exist?(File.join(Gitlab.config.gitlab_shell.path, ".gitlab_shell_secret"))
generate_and_link_secret_token
end
def version_required
@version_required ||= File.read(Rails.root
- .join('GITLAB_SHELL_VERSION')).strip
+ .join("GITLAB_SHELL_VERSION")).strip
end
def strip_key(key)
- key.split(/[ ]+/)[0, 2].join(' ')
+ key.split(/[ ]+/)[0, 2].join(" ")
end
private
@@ -57,7 +57,7 @@ module Gitlab
File.write(secret_file, @secret_token)
end
- link_path = File.join(shell_path, '.gitlab_shell_secret')
+ link_path = File.join(shell_path, ".gitlab_shell_secret")
if File.exist?(shell_path) && !File.exist?(link_path)
FileUtils.symlink(secret_file, link_path)
end
@@ -84,12 +84,12 @@ module Gitlab
#
def create_repository(storage, disk_path, gl_project_path)
relative_path = disk_path.dup
- relative_path << '.git' unless relative_path.end_with?('.git')
+ relative_path << ".git" unless relative_path.end_with?(".git")
# During creation of a repository, gl_repository may not be known
# because that depends on a yet-to-be assigned project ID in the
# database (e.g. project-1234), so for now it is blank.
- repository = Gitlab::Git::Repository.new(storage, relative_path, '', gl_project_path)
+ repository = Gitlab::Git::Repository.new(storage, relative_path, "", gl_project_path)
wrapped_gitaly_errors { repository.gitaly_repository_client.create_repository }
true
@@ -116,7 +116,7 @@ module Gitlab
# import_repository("nfs-file06", "gitlab/gitlab-ci", "https://gitlab.com/gitlab-org/gitlab-test.git")
#
def import_repository(storage, name, url, gl_project_path)
- if url.start_with?('.', '/')
+ if url.start_with?(".", "/")
raise Error.new("don't use disk paths with import_repository: #{url.inspect}")
end
@@ -179,10 +179,10 @@ module Gitlab
# add_key("key-42", "sha-rsa ...")
#
def add_key(key_id, key_content)
- return unless self.authorized_keys_enabled?
+ return unless authorized_keys_enabled?
gitlab_shell_fast_execute([gitlab_shell_keys_path,
- 'add-key', key_id, self.class.strip_key(key_content)])
+ "add-key", key_id, self.class.strip_key(key_content),])
end
# Batch-add keys to authorized_keys
@@ -190,9 +190,9 @@ module Gitlab
# Ex.
# batch_add_keys { |adder| adder.add_key("key-42", "sha-rsa ...") }
def batch_add_keys(&block)
- return unless self.authorized_keys_enabled?
+ return unless authorized_keys_enabled?
- IO.popen(%W(#{gitlab_shell_path}/bin/gitlab-keys batch-add-keys), 'w') do |io|
+ IO.popen(%W[#{gitlab_shell_path}/bin/gitlab-keys batch-add-keys], "w") do |io|
yield(KeyAdder.new(io))
end
end
@@ -203,9 +203,9 @@ module Gitlab
# remove_key("key-342", "sha-rsa ...")
#
def remove_key(key_id, key_content = nil)
- return unless self.authorized_keys_enabled?
+ return unless authorized_keys_enabled?
- args = [gitlab_shell_keys_path, 'rm-key', key_id]
+ args = [gitlab_shell_keys_path, "rm-key", key_id]
args << key_content if key_content
gitlab_shell_fast_execute(args)
end
@@ -216,9 +216,9 @@ module Gitlab
# remove_all_keys
#
def remove_all_keys
- return unless self.authorized_keys_enabled?
+ return unless authorized_keys_enabled?
- gitlab_shell_fast_execute([gitlab_shell_keys_path, 'clear'])
+ gitlab_shell_fast_execute([gitlab_shell_keys_path, "clear"])
end
# Remove ssh keys from gitlab shell that are not in the DB
@@ -228,7 +228,7 @@ module Gitlab
#
# rubocop: disable CodeReuse/ActiveRecord
def remove_keys_not_found_in_db
- return unless self.authorized_keys_enabled?
+ return unless authorized_keys_enabled?
Rails.logger.info("Removing keys not found in DB")
@@ -253,7 +253,7 @@ module Gitlab
# batch_read_key_ids { |batch| keys = Key.where(id: batch) }
#
def batch_read_key_ids(batch_size: 100, &block)
- return unless self.authorized_keys_enabled?
+ return unless authorized_keys_enabled?
list_key_ids do |key_id_stream|
key_id_stream.lazy.each_slice(batch_size) do |lines|
@@ -269,9 +269,9 @@ module Gitlab
# list_key_ids
#
def list_key_ids(&block)
- return unless self.authorized_keys_enabled?
+ return unless authorized_keys_enabled?
- IO.popen(%W(#{gitlab_shell_path}/bin/gitlab-keys list-key-ids), &block)
+ IO.popen(%W[#{gitlab_shell_path}/bin/gitlab-keys list-key-ids], &block)
end
# Add empty directory for storing repositories
@@ -299,7 +299,7 @@ module Gitlab
rescue GRPC::InvalidArgument => e
raise ArgumentError, e.message
end
- alias_method :rm_directory, :rm_namespace
+ alias rm_directory rm_namespace
# Move namespace directory inside repositories storage
#
@@ -309,11 +309,11 @@ module Gitlab
def mv_namespace(storage, old_name, new_name)
Gitlab::GitalyClient::NamespaceService.new(storage).rename(old_name, new_name)
rescue GRPC::InvalidArgument => e
- Gitlab::Sentry.track_acceptable_exception(e, extra: { old_name: old_name, new_name: new_name, storage: storage })
+ Gitlab::Sentry.track_acceptable_exception(e, extra: {old_name: old_name, new_name: new_name, storage: storage})
false
end
- alias_method :mv_directory, :mv_namespace # Note: ShellWorker uses this alias
+ alias mv_directory mv_namespace # Note: ShellWorker uses this alias
def url_to_repo(path)
Gitlab.config.gitlab_shell.ssh_path_prefix + "#{path}.git"
@@ -341,7 +341,7 @@ module Gitlab
# rubocop: enable CodeReuse/ActiveRecord
def hooks_path
- File.join(gitlab_shell_path, 'hooks')
+ File.join(gitlab_shell_path, "hooks")
end
protected
@@ -361,11 +361,11 @@ module Gitlab
end
def gitlab_shell_projects_path
- File.join(gitlab_shell_path, 'bin', 'gitlab-projects')
+ File.join(gitlab_shell_path, "bin", "gitlab-projects")
end
def gitlab_shell_keys_path
- File.join(gitlab_shell_path, 'bin', 'gitlab-keys')
+ File.join(gitlab_shell_path, "bin", "gitlab-keys")
end
def authorized_keys_enabled?
@@ -421,7 +421,7 @@ module Gitlab
def initialize(shard_name, repository_relative_path, gl_project_path)
@shard_name = shard_name
@repository_relative_path = repository_relative_path
- @output = ''
+ @output = ""
@gl_project_path = gl_project_path
end
diff --git a/lib/gitlab/sherlock.rb b/lib/gitlab/sherlock.rb
index a1471c9de47..725929d01f5 100644
--- a/lib/gitlab/sherlock.rb
+++ b/lib/gitlab/sherlock.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'securerandom'
+require "securerandom"
module Gitlab
module Sherlock
@@ -11,11 +11,11 @@ module Gitlab
end
def self.enabled?
- Rails.env.development? && !!ENV['ENABLE_SHERLOCK']
+ Rails.env.development? && !!ENV["ENABLE_SHERLOCK"]
end
def self.enable_line_profiler?
- RUBY_ENGINE == 'ruby'
+ RUBY_ENGINE == "ruby"
end
end
end
diff --git a/lib/gitlab/sherlock/collection.rb b/lib/gitlab/sherlock/collection.rb
index ce3a376cf75..01074cc542b 100644
--- a/lib/gitlab/sherlock/collection.rb
+++ b/lib/gitlab/sherlock/collection.rb
@@ -19,7 +19,7 @@ module Gitlab
synchronize { @transactions << transaction }
end
- alias_method :<<, :add
+ alias << add
def each(&block)
synchronize { @transactions.each(&block) }
diff --git a/lib/gitlab/sherlock/file_sample.rb b/lib/gitlab/sherlock/file_sample.rb
index 604b6df12cc..7b6fc34d997 100644
--- a/lib/gitlab/sherlock/file_sample.rb
+++ b/lib/gitlab/sherlock/file_sample.rb
@@ -18,7 +18,7 @@ module Gitlab
end
def relative_path
- @relative_path ||= @file.gsub(%r{^#{Rails.root.to_s}/?}, '')
+ @relative_path ||= @file.gsub(%r{^#{Rails.root.to_s}/?}, "")
end
def to_param
diff --git a/lib/gitlab/sherlock/line_profiler.rb b/lib/gitlab/sherlock/line_profiler.rb
index 209ba784f9c..aa7e1afc386 100644
--- a/lib/gitlab/sherlock/line_profiler.rb
+++ b/lib/gitlab/sherlock/line_profiler.rb
@@ -36,13 +36,13 @@ module Gitlab
profile_mri(&block)
else
raise NotImplementedError,
- 'Line profiling is not supported on this platform'
+ "Line profiling is not supported on this platform"
end
end
# Profiles the given block using rblineprof (MRI only).
def profile_mri
- require 'rblineprof'
+ require "rblineprof"
retval = nil
samples = lineprof(/^#{Rails.root.to_s}/) { retval = yield }
@@ -93,7 +93,7 @@ module Gitlab
end
def mri?
- RUBY_ENGINE == 'ruby'
+ RUBY_ENGINE == "ruby"
end
end
end
diff --git a/lib/gitlab/sherlock/middleware.rb b/lib/gitlab/sherlock/middleware.rb
index 747cb0f9142..5e504fb5760 100644
--- a/lib/gitlab/sherlock/middleware.rb
+++ b/lib/gitlab/sherlock/middleware.rb
@@ -31,12 +31,12 @@ module Gitlab
end
def instrument?(env)
- !!(env['HTTP_ACCEPT'] =~ CONTENT_TYPES &&
- env['REQUEST_URI'] !~ IGNORE_PATHS)
+ !!(env["HTTP_ACCEPT"] =~ CONTENT_TYPES &&
+ env["REQUEST_URI"] !~ IGNORE_PATHS)
end
def transaction_from_env(env)
- Transaction.new(env['REQUEST_METHOD'], env['REQUEST_URI'])
+ Transaction.new(env["REQUEST_METHOD"], env["REQUEST_URI"])
end
end
end
diff --git a/lib/gitlab/sherlock/query.rb b/lib/gitlab/sherlock/query.rb
index 11561eec32a..8ce2b00dd31 100644
--- a/lib/gitlab/sherlock/query.rb
+++ b/lib/gitlab/sherlock/query.rb
@@ -45,11 +45,11 @@ module Gitlab
@query = query
@started_at = started_at
@finished_at = finished_at
- @backtrace = caller_locations.map do |loc|
+ @backtrace = caller_locations.map { |loc|
Location.from_ruby_location(loc)
- end
+ }
- unless @query.end_with?(';')
+ unless @query.end_with?(";")
@query = "#{@query};"
end
end
diff --git a/lib/gitlab/sherlock/transaction.rb b/lib/gitlab/sherlock/transaction.rb
index d04624977dc..a3fbd205faf 100644
--- a/lib/gitlab/sherlock/transaction.rb
+++ b/lib/gitlab/sherlock/transaction.rb
@@ -24,9 +24,9 @@ module Gitlab
def run
@started_at = Time.now
- retval = with_subscriptions do
+ retval = with_subscriptions {
profile_lines { yield }
- end
+ }
@finished_at = Time.now
@@ -88,10 +88,10 @@ module Gitlab
end
def subscribe_to_active_record
- ActiveSupport::Notifications.subscribe('sql.active_record') do |_, start, finish, _, data|
+ ActiveSupport::Notifications.subscribe("sql.active_record") do |_, start, finish, _, data|
next unless same_thread?
- unless data.fetch(:cached, data[:name] == 'CACHE')
+ unless data.fetch(:cached, data[:name] == "CACHE")
track_query(data[:sql].strip, data[:binds], start, finish)
end
end
diff --git a/lib/gitlab/sidekiq_config.rb b/lib/gitlab/sidekiq_config.rb
index 3b8de64913b..e2f02ca2608 100644
--- a/lib/gitlab/sidekiq_config.rb
+++ b/lib/gitlab/sidekiq_config.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'yaml'
-require 'set'
+require "yaml"
+require "set"
module Gitlab
module SidekiqConfig
@@ -12,16 +12,16 @@ module Gitlab
def self.worker_queues(rails_path = Rails.root.to_s)
@worker_queues ||= {}
- @worker_queues[rails_path] ||= QUEUE_CONFIG_PATHS.flat_map do |path|
+ @worker_queues[rails_path] ||= QUEUE_CONFIG_PATHS.flat_map { |path|
full_path = File.join(rails_path, path)
File.exist?(full_path) ? YAML.load_file(full_path) : []
- end
+ }
end
# This method is called by `bin/sidekiq-cluster` in EE, which runs outside
# of bundler/Rails context, so we cannot use any gem or Rails methods.
- def self.expand_queues(queues, all_queues = self.worker_queues)
+ def self.expand_queues(queues, all_queues = worker_queues)
return [] if queues.empty?
queues_set = all_queues.to_set
@@ -38,27 +38,27 @@ module Gitlab
def self.config_queues
@config_queues ||= begin
- config = YAML.load_file(Rails.root.join('config/sidekiq_queues.yml'))
+ config = YAML.load_file(Rails.root.join("config/sidekiq_queues.yml"))
config[:queues].map(&:first)
end
end
def self.cron_workers
- @cron_workers ||= Settings.cron_jobs.map { |job_name, options| options['job_class'].constantize }
+ @cron_workers ||= Settings.cron_jobs.map { |job_name, options| options["job_class"].constantize }
end
def self.workers
- @workers ||= find_workers(Rails.root.join('app', 'workers'))
+ @workers ||= find_workers(Rails.root.join("app", "workers"))
end
def self.find_workers(root)
- concerns = root.join('concerns').to_s
+ concerns = root.join("concerns").to_s
- workers = Dir[root.join('**', '*.rb')]
+ workers = Dir[root.join("**", "*.rb")]
.reject { |path| path.start_with?(concerns) }
workers.map! do |path|
- ns = Pathname.new(path).relative_path_from(root).to_s.gsub('.rb', '')
+ ns = Pathname.new(path).relative_path_from(root).to_s.gsub(".rb", "")
ns.camelize.constantize
end
diff --git a/lib/gitlab/sidekiq_logger.rb b/lib/gitlab/sidekiq_logger.rb
index ce82a6f04bb..d2a8453fc73 100644
--- a/lib/gitlab/sidekiq_logger.rb
+++ b/lib/gitlab/sidekiq_logger.rb
@@ -3,7 +3,7 @@
module Gitlab
class SidekiqLogger < Gitlab::Logger
def self.file_name_noext
- 'sidekiq'
+ "sidekiq"
end
end
end
diff --git a/lib/gitlab/sidekiq_logging/json_formatter.rb b/lib/gitlab/sidekiq_logging/json_formatter.rb
index 88888c5994e..d279955114f 100644
--- a/lib/gitlab/sidekiq_logging/json_formatter.rb
+++ b/lib/gitlab/sidekiq_logging/json_formatter.rb
@@ -6,7 +6,7 @@ module Gitlab
def call(severity, timestamp, progname, data)
output = {
severity: severity,
- time: timestamp.utc.iso8601(3)
+ time: timestamp.utc.iso8601(3),
}
case data
diff --git a/lib/gitlab/sidekiq_logging/structured_logger.rb b/lib/gitlab/sidekiq_logging/structured_logger.rb
index fdc0d518c59..dfb0942a99c 100644
--- a/lib/gitlab/sidekiq_logging/structured_logger.rb
+++ b/lib/gitlab/sidekiq_logging/structured_logger.rb
@@ -25,32 +25,32 @@ module Gitlab
private
def base_message(payload)
- "#{payload['class']} JID-#{payload['jid']}"
+ "#{payload["class"]} JID-#{payload["jid"]}"
end
def log_job_start(started_at, payload)
- payload['message'] = "#{base_message(payload)}: start"
- payload['job_status'] = 'start'
+ payload["message"] = "#{base_message(payload)}: start"
+ payload["job_status"] = "start"
payload
end
def log_job_done(started_at, payload, job_exception = nil)
payload = payload.dup
- payload['duration'] = elapsed(started_at)
- payload['completed_at'] = Time.now.utc
+ payload["duration"] = elapsed(started_at)
+ payload["completed_at"] = Time.now.utc
message = base_message(payload)
if job_exception
- payload['message'] = "#{message}: fail: #{payload['duration']} sec"
- payload['job_status'] = 'fail'
- payload['error_message'] = job_exception.message
- payload['error'] = job_exception.class
- payload['error_backtrace'] = backtrace_cleaner.clean(job_exception.backtrace)
+ payload["message"] = "#{message}: fail: #{payload["duration"]} sec"
+ payload["job_status"] = "fail"
+ payload["error_message"] = job_exception.message
+ payload["error"] = job_exception.class
+ payload["error_backtrace"] = backtrace_cleaner.clean(job_exception.backtrace)
else
- payload['message'] = "#{message}: done: #{payload['duration']} sec"
- payload['job_status'] = 'done'
+ payload["message"] = "#{message}: done: #{payload["duration"]} sec"
+ payload["job_status"] = "done"
end
convert_to_iso8601(payload, DONE_TIMESTAMP_FIELDS)
@@ -62,10 +62,10 @@ module Gitlab
job = job.dup
# Add process id params
- job['pid'] = ::Process.pid
+ job["pid"] = ::Process.pid
- job.delete('args') unless ENV['SIDEKIQ_LOG_ARGUMENTS']
- job['args'] = limited_job_args(job['args']) if job['args']
+ job.delete("args") unless ENV["SIDEKIQ_LOG_ARGUMENTS"]
+ job["args"] = limited_job_args(job["args"]) if job["args"]
convert_to_iso8601(job, START_TIMESTAMP_FIELDS)
@@ -100,13 +100,13 @@ module Gitlab
return unless args.is_a?(Array)
total_length = 0
- limited_args = args.take_while do |arg|
+ limited_args = args.take_while { |arg|
total_length += arg.to_json.length
total_length <= MAXIMUM_JOB_ARGUMENTS_LENGTH
- end
+ }
- limited_args.push('...') if total_length > MAXIMUM_JOB_ARGUMENTS_LENGTH
+ limited_args.push("...") if total_length > MAXIMUM_JOB_ARGUMENTS_LENGTH
limited_args
end
diff --git a/lib/gitlab/sidekiq_middleware/arguments_logger.rb b/lib/gitlab/sidekiq_middleware/arguments_logger.rb
index 2859aa5f4a6..431d4a1280d 100644
--- a/lib/gitlab/sidekiq_middleware/arguments_logger.rb
+++ b/lib/gitlab/sidekiq_middleware/arguments_logger.rb
@@ -4,7 +4,7 @@ module Gitlab
module SidekiqMiddleware
class ArgumentsLogger
def call(worker, job, queue)
- Sidekiq.logger.info "arguments: #{JSON.dump(job['args'])}"
+ Sidekiq.logger.info "arguments: #{JSON.dump(job["args"])}"
yield
end
end
diff --git a/lib/gitlab/sidekiq_middleware/shutdown.rb b/lib/gitlab/sidekiq_middleware/shutdown.rb
index 19f3be83bce..bd3ec3803e5 100644
--- a/lib/gitlab/sidekiq_middleware/shutdown.rb
+++ b/lib/gitlab/sidekiq_middleware/shutdown.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'mutex_m'
+require "mutex_m"
module Gitlab
module SidekiqMiddleware
@@ -8,11 +8,11 @@ module Gitlab
extend Mutex_m
# Default the RSS limit to 0, meaning the MemoryKiller is disabled
- MAX_RSS = (ENV['SIDEKIQ_MEMORY_KILLER_MAX_RSS'] || 0).to_s.to_i
+ MAX_RSS = (ENV["SIDEKIQ_MEMORY_KILLER_MAX_RSS"] || 0).to_s.to_i
# Give Sidekiq 15 minutes of grace time after exceeding the RSS limit
- GRACE_TIME = (ENV['SIDEKIQ_MEMORY_KILLER_GRACE_TIME'] || 15 * 60).to_s.to_i
+ GRACE_TIME = (ENV["SIDEKIQ_MEMORY_KILLER_GRACE_TIME"] || 15 * 60).to_s.to_i
# Wait 30 seconds for running jobs to finish during graceful shutdown
- SHUTDOWN_WAIT = (ENV['SIDEKIQ_MEMORY_KILLER_SHUTDOWN_WAIT'] || 30).to_s.to_i
+ SHUTDOWN_WAIT = (ENV["SIDEKIQ_MEMORY_KILLER_SHUTDOWN_WAIT"] || 30).to_s.to_i
# This exception can be used to request that the middleware start shutting down Sidekiq
WantShutdown = Class.new(StandardError)
@@ -70,21 +70,21 @@ module Gitlab
def do_shutdown(worker, job, shutdown_exception)
Sidekiq.logger.warn "Sidekiq worker PID-#{pid} shutting down because of #{shutdown_exception} after job "\
- "#{worker.class} JID-#{job['jid']}"
+ "#{worker.class} JID-#{job["jid"]}"
Sidekiq.logger.warn "Sidekiq worker PID-#{pid} will stop fetching new jobs in #{GRACE_TIME} seconds, and will be shut down #{SHUTDOWN_WAIT} seconds later"
# Wait `GRACE_TIME` to give the memory intensive job time to finish.
# Then, tell Sidekiq to stop fetching new jobs.
- wait_and_signal(GRACE_TIME, 'SIGTSTP', 'stop fetching new jobs')
+ wait_and_signal(GRACE_TIME, "SIGTSTP", "stop fetching new jobs")
# Wait `SHUTDOWN_WAIT` to give already fetched jobs time to finish.
# Then, tell Sidekiq to gracefully shut down by giving jobs a few more
# moments to finish, killing and requeuing them if they didn't, and
# then terminating itself.
- wait_and_signal(SHUTDOWN_WAIT, 'SIGTERM', 'gracefully shut down')
+ wait_and_signal(SHUTDOWN_WAIT, "SIGTERM", "gracefully shut down")
# Wait for Sidekiq to shutdown gracefully, and kill it if it didn't.
- wait_and_signal(Sidekiq.options[:timeout] + 2, 'SIGKILL', 'die')
+ wait_and_signal(Sidekiq.options[:timeout] + 2, "SIGKILL", "die")
end
def check_rss!
@@ -97,7 +97,7 @@ module Gitlab
end
def get_rss
- output, status = Gitlab::Popen.popen(%W(ps -o rss= -p #{pid}), Rails.root.to_s)
+ output, status = Gitlab::Popen.popen(%W[ps -o rss= -p #{pid}], Rails.root.to_s)
return 0 unless status.zero?
output.to_i
diff --git a/lib/gitlab/sidekiq_status.rb b/lib/gitlab/sidekiq_status.rb
index 583a970bf4e..867e6d53fdc 100644
--- a/lib/gitlab/sidekiq_status.rb
+++ b/lib/gitlab/sidekiq_status.rb
@@ -18,7 +18,7 @@ module Gitlab
# expire after a certain period of time to prevent storing too many keys in
# Redis.
module SidekiqStatus
- STATUS_KEY = 'gitlab-sidekiq-status:%s'.freeze
+ STATUS_KEY = "gitlab-sidekiq-status:%s"
# The default time (in seconds) after which a status key is expired
# automatically. The default of 30 minutes should be more than sufficient
@@ -50,7 +50,7 @@ module Gitlab
#
# Returns true or false.
def self.all_completed?(job_ids)
- self.num_running(job_ids).zero?
+ num_running(job_ids).zero?
end
# Returns true if the given job is running
@@ -64,7 +64,7 @@ module Gitlab
#
# job_ids - The Sidekiq job IDs to check.
def self.num_running(job_ids)
- responses = self.job_status(job_ids)
+ responses = job_status(job_ids)
responses.select(&:present?).count
end
@@ -73,7 +73,7 @@ module Gitlab
#
# job_ids - The Sidekiq job IDs to check.
def self.num_completed(job_ids)
- job_ids.size - self.num_running(job_ids)
+ job_ids.size - num_running(job_ids)
end
# Returns the job status for each of the given job IDs.
diff --git a/lib/gitlab/sidekiq_status/client_middleware.rb b/lib/gitlab/sidekiq_status/client_middleware.rb
index bfd5038557d..5f2f32eaa41 100644
--- a/lib/gitlab/sidekiq_status/client_middleware.rb
+++ b/lib/gitlab/sidekiq_status/client_middleware.rb
@@ -4,9 +4,9 @@ module Gitlab
module SidekiqStatus
class ClientMiddleware
def call(_, job, _, _)
- status_expiration = job['status_expiration'] || Gitlab::SidekiqStatus::DEFAULT_EXPIRATION
+ status_expiration = job["status_expiration"] || Gitlab::SidekiqStatus::DEFAULT_EXPIRATION
- Gitlab::SidekiqStatus.set(job['jid'], status_expiration)
+ Gitlab::SidekiqStatus.set(job["jid"], status_expiration)
yield
end
end
diff --git a/lib/gitlab/sidekiq_status/server_middleware.rb b/lib/gitlab/sidekiq_status/server_middleware.rb
index 01bc58fd2be..e3215b0174b 100644
--- a/lib/gitlab/sidekiq_status/server_middleware.rb
+++ b/lib/gitlab/sidekiq_status/server_middleware.rb
@@ -6,7 +6,7 @@ module Gitlab
def call(worker, job, queue)
ret = yield
- Gitlab::SidekiqStatus.unset(job['jid'])
+ Gitlab::SidekiqStatus.unset(job["jid"])
ret
end
diff --git a/lib/gitlab/sidekiq_versioning.rb b/lib/gitlab/sidekiq_versioning.rb
index 8164a5a9d7a..288640e9706 100644
--- a/lib/gitlab/sidekiq_versioning.rb
+++ b/lib/gitlab/sidekiq_versioning.rb
@@ -15,7 +15,7 @@ module Gitlab
Sidekiq.redis do |conn|
conn.pipelined do
queues.each do |queue|
- conn.sadd('queues', queue)
+ conn.sadd("queues", queue)
end
end
end
diff --git a/lib/gitlab/slash_commands/command.rb b/lib/gitlab/slash_commands/command.rb
index 7c963fcf38a..6cc9ebf158e 100644
--- a/lib/gitlab/slash_commands/command.rb
+++ b/lib/gitlab/slash_commands/command.rb
@@ -10,7 +10,7 @@ module Gitlab
Gitlab::SlashCommands::IssueSearch,
Gitlab::SlashCommands::IssueMove,
Gitlab::SlashCommands::Deploy,
- Gitlab::SlashCommands::Run
+ Gitlab::SlashCommands::Run,
]
end
@@ -32,9 +32,9 @@ module Gitlab
def match_command
match = nil
service =
- available_commands.find do |klass|
+ available_commands.find { |klass|
match = klass.match(params[:text])
- end
+ }
[service, match]
end
diff --git a/lib/gitlab/slash_commands/deploy.rb b/lib/gitlab/slash_commands/deploy.rb
index 157d924f99f..f33a5ba5b5d 100644
--- a/lib/gitlab/slash_commands/deploy.rb
+++ b/lib/gitlab/slash_commands/deploy.rb
@@ -8,7 +8,7 @@ module Gitlab
end
def self.help_message
- 'deploy <environment> to <target-environment>'
+ "deploy <environment> to <target-environment>"
end
def self.available?(project)
@@ -43,9 +43,9 @@ module Gitlab
environment = project.environments.find_by(name: from)
return unless environment
- actions = environment.actions_for(to).select do |action|
+ actions = environment.actions_for(to).select { |action|
action.starts_environment?
- end
+ }
if actions.many?
actions.find { |action| action.name == to.to_s }
diff --git a/lib/gitlab/slash_commands/help.rb b/lib/gitlab/slash_commands/help.rb
index dbe15baa3d7..0688bbd5fa4 100644
--- a/lib/gitlab/slash_commands/help.rb
+++ b/lib/gitlab/slash_commands/help.rb
@@ -11,7 +11,7 @@ module Gitlab
end
def self.help_message
- 'help'
+ "help"
end
def self.allowed?(_project, _user)
diff --git a/lib/gitlab/slash_commands/issue_move.rb b/lib/gitlab/slash_commands/issue_move.rb
index d2f1f130b38..42a5de9a567 100644
--- a/lib/gitlab/slash_commands/issue_move.rb
+++ b/lib/gitlab/slash_commands/issue_move.rb
@@ -14,7 +14,7 @@ module Gitlab
end
def self.help_message
- 'issue move <issue_id> (to)? <project_path>'
+ "issue move <issue_id> (to)? <project_path>"
end
def self.allowed?(project, user)
@@ -30,7 +30,7 @@ module Gitlab
end
new_issue = Issues::MoveService.new(project, current_user)
- .execute(old_issue, target_project)
+ .execute(old_issue, target_project)
presenter(new_issue).present(old_issue)
rescue Issues::MoveService::MoveError => e
diff --git a/lib/gitlab/slash_commands/issue_new.rb b/lib/gitlab/slash_commands/issue_new.rb
index 48379031537..6faa19740f2 100644
--- a/lib/gitlab/slash_commands/issue_new.rb
+++ b/lib/gitlab/slash_commands/issue_new.rb
@@ -10,7 +10,7 @@ module Gitlab
end
def self.help_message
- 'issue new <title> *`⇧ Shift`*+*`↵ Enter`* <description>'
+ "issue new <title> *`⇧ Shift`*+*`↵ Enter`* <description>"
end
def self.allowed?(project, user)
diff --git a/lib/gitlab/slash_commands/presenters/base.rb b/lib/gitlab/slash_commands/presenters/base.rb
index 73814aa180f..ca3aab9d67e 100644
--- a/lib/gitlab/slash_commands/presenters/base.rb
+++ b/lib/gitlab/slash_commands/presenters/base.rb
@@ -31,7 +31,7 @@ module Gitlab
def ephemeral_response(message)
response = {
response_type: :ephemeral,
- status: 200
+ status: 200,
}.merge(message)
format_response(response)
@@ -40,7 +40,7 @@ module Gitlab
def in_channel_response(message)
response = {
response_type: :in_channel,
- status: 200
+ status: 200,
}.merge(message)
format_response(response)
@@ -69,7 +69,7 @@ module Gitlab
[
@resource.project.namespace.becomes(Namespace),
@resource.project,
- @resource
+ @resource,
]
)
end
diff --git a/lib/gitlab/slash_commands/presenters/help.rb b/lib/gitlab/slash_commands/presenters/help.rb
index 480d7aa6a30..35c27530060 100644
--- a/lib/gitlab/slash_commands/presenters/help.rb
+++ b/lib/gitlab/slash_commands/presenters/help.rb
@@ -13,7 +13,7 @@ module Gitlab
def help_message(trigger, text)
return "No commands available :thinking_face:" unless @resource.present?
- if text.start_with?('help')
+ if text.start_with?("help")
header_with_list("Available commands", full_commands(trigger))
else
header_with_list("Unknown command, these commands are available", full_commands(trigger))
diff --git a/lib/gitlab/slash_commands/presenters/issue_base.rb b/lib/gitlab/slash_commands/presenters/issue_base.rb
index b6db103b82b..8f7ed78234d 100644
--- a/lib/gitlab/slash_commands/presenters/issue_base.rb
+++ b/lib/gitlab/slash_commands/presenters/issue_base.rb
@@ -5,11 +5,11 @@ module Gitlab
module Presenters
module IssueBase
def color(issuable)
- issuable.open? ? '#38ae67' : '#d22852'
+ issuable.open? ? "#38ae67" : "#d22852"
end
def status_text(issuable)
- issuable.open? ? 'Open' : 'Closed'
+ issuable.open? ? "Open" : "Closed"
end
def project
@@ -25,18 +25,18 @@ module Gitlab
{
title: "Assignee",
value: resource.assignees.any? ? resource.assignees.first.name : "_None_",
- short: true
+ short: true,
},
{
title: "Milestone",
value: resource.milestone ? resource.milestone.title : "_None_",
- short: true
+ short: true,
},
{
title: "Labels",
- value: resource.labels.any? ? resource.label_names.join(', ') : "_None_",
- short: true
- }
+ value: resource.labels.any? ? resource.label_names.join(", ") : "_None_",
+ short: true,
+ },
]
end
diff --git a/lib/gitlab/slash_commands/presenters/issue_move.rb b/lib/gitlab/slash_commands/presenters/issue_move.rb
index ca0644ede95..fb16aa3a9c7 100644
--- a/lib/gitlab/slash_commands/presenters/issue_move.rb
+++ b/lib/gitlab/slash_commands/presenters/issue_move.rb
@@ -1,4 +1,3 @@
-# coding: utf-8
# frozen_string_literal: true
module Gitlab
@@ -23,22 +22,22 @@ module Gitlab
{
attachments: [
{
- title: "#{@resource.title} · #{@resource.to_reference}",
- title_link: resource_url,
- author_name: author.name,
- author_icon: author.avatar_url,
- fallback: "Issue #{@resource.to_reference}: #{@resource.title}",
- pretext: pretext(old_issue),
- color: color(@resource),
- fields: fields,
+ title: "#{@resource.title} · #{@resource.to_reference}",
+ title_link: resource_url,
+ author_name: author.name,
+ author_icon: author.avatar_url,
+ fallback: "Issue #{@resource.to_reference}: #{@resource.title}",
+ pretext: pretext(old_issue),
+ color: color(@resource),
+ fields: fields,
mrkdwn_in: [
:title,
:pretext,
:text,
- :fields
- ]
- }
- ]
+ :fields,
+ ],
+ },
+ ],
}
end
diff --git a/lib/gitlab/slash_commands/presenters/issue_new.rb b/lib/gitlab/slash_commands/presenters/issue_new.rb
index ac78745ae70..aff1ae53bfd 100644
--- a/lib/gitlab/slash_commands/presenters/issue_new.rb
+++ b/lib/gitlab/slash_commands/presenters/issue_new.rb
@@ -16,22 +16,22 @@ module Gitlab
{
attachments: [
{
- title: "#{@resource.title} · #{@resource.to_reference}",
- title_link: resource_url,
- author_name: author.name,
- author_icon: author.avatar_url,
- fallback: "New issue #{@resource.to_reference}: #{@resource.title}",
- pretext: pretext,
- color: color(@resource),
- fields: fields,
+ title: "#{@resource.title} · #{@resource.to_reference}",
+ title_link: resource_url,
+ author_name: author.name,
+ author_icon: author.avatar_url,
+ fallback: "New issue #{@resource.to_reference}: #{@resource.title}",
+ pretext: pretext,
+ color: color(@resource),
+ fields: fields,
mrkdwn_in: [
:title,
:pretext,
:text,
- :fields
- ]
- }
- ]
+ :fields,
+ ],
+ },
+ ],
}
end
diff --git a/lib/gitlab/slash_commands/presenters/issue_search.rb b/lib/gitlab/slash_commands/presenters/issue_search.rb
index 0d497efec0e..7fa7894fc51 100644
--- a/lib/gitlab/slash_commands/presenters/issue_search.rb
+++ b/lib/gitlab/slash_commands/presenters/issue_search.rb
@@ -8,12 +8,12 @@ module Gitlab
def present
text = if @resource.count >= 5
- "Here are the first 5 issues I found:"
- elsif @resource.one?
- "Here is the only issue I found:"
- else
- "Here are the #{@resource.count} issues I found:"
- end
+ "Here are the first 5 issues I found:"
+ elsif @resource.one?
+ "Here is the only issue I found:"
+ else
+ "Here are the #{@resource.count} issues I found:"
+ end
ephemeral_response(text: text, attachments: attachments)
end
@@ -30,8 +30,8 @@ module Gitlab
text: "#{url} · #{issue.title} (#{status_text(issue)})",
mrkdwn_in: [
- :text
- ]
+ :text,
+ ],
}
end
end
diff --git a/lib/gitlab/slash_commands/presenters/issue_show.rb b/lib/gitlab/slash_commands/presenters/issue_show.rb
index 5a2c79a928e..d0ff981673a 100644
--- a/lib/gitlab/slash_commands/presenters/issue_show.rb
+++ b/lib/gitlab/slash_commands/presenters/issue_show.rb
@@ -20,22 +20,22 @@ module Gitlab
{
attachments: [
{
- title: "#{@resource.title} · #{@resource.to_reference}",
- title_link: resource_url,
- author_name: author.name,
- author_icon: author.avatar_url,
- fallback: "Issue #{@resource.to_reference}: #{@resource.title}",
- pretext: pretext,
- text: text,
- color: color(@resource),
- fields: fields,
+ title: "#{@resource.title} · #{@resource.to_reference}",
+ title_link: resource_url,
+ author_name: author.name,
+ author_icon: author.avatar_url,
+ fallback: "Issue #{@resource.to_reference}: #{@resource.title}",
+ pretext: pretext,
+ text: text,
+ color: color(@resource),
+ fields: fields,
mrkdwn_in: [
:pretext,
:text,
- :fields
- ]
- }
- ]
+ :fields,
+ ],
+ },
+ ],
}
end
diff --git a/lib/gitlab/slash_commands/presenters/run.rb b/lib/gitlab/slash_commands/presenters/run.rb
index c4bbc231464..7960c4b2851 100644
--- a/lib/gitlab/slash_commands/presenters/run.rb
+++ b/lib/gitlab/slash_commands/presenters/run.rb
@@ -17,13 +17,13 @@ module Gitlab
# rubocop: enable CodeReuse/ActiveRecord
def unsupported_chat_service
- ephemeral_response(text: 'Sorry, this chat service is currently not supported by GitLab ChatOps.')
+ ephemeral_response(text: "Sorry, this chat service is currently not supported by GitLab ChatOps.")
end
def failed_to_schedule(command)
ephemeral_response(
- text: 'The command could not be scheduled. Make sure that your ' \
- 'project has a .gitlab-ci.yml that defines a job with the ' \
+ text: "The command could not be scheduled. Make sure that your " \
+ "project has a .gitlab-ci.yml that defines a job with the " \
"name #{command.inspect}"
)
end
diff --git a/lib/gitlab/slash_commands/run.rb b/lib/gitlab/slash_commands/run.rb
index 10a545e28ac..df54030235a 100644
--- a/lib/gitlab/slash_commands/run.rb
+++ b/lib/gitlab/slash_commands/run.rb
@@ -9,7 +9,7 @@ module Gitlab
end
def self.help_message
- 'run <command> <arguments>'
+ "run <command> <arguments>"
end
def self.available?(project)
diff --git a/lib/gitlab/snippet_search_results.rb b/lib/gitlab/snippet_search_results.rb
index e360b552f89..422799f9d43 100644
--- a/lib/gitlab/snippet_search_results.rb
+++ b/lib/gitlab/snippet_search_results.rb
@@ -13,9 +13,9 @@ module Gitlab
def objects(scope, page = nil)
case scope
- when 'snippet_titles'
+ when "snippet_titles"
snippet_titles.page(page).per(per_page)
- when 'snippet_blobs'
+ when "snippet_blobs"
snippet_blobs.page(page).per(per_page)
else
super(scope, nil, false)
@@ -34,18 +34,18 @@ module Gitlab
# rubocop: disable CodeReuse/ActiveRecord
def snippet_titles
- limit_snippets.search(query).order('updated_at DESC').includes(:author)
+ limit_snippets.search(query).order("updated_at DESC").includes(:author)
end
# rubocop: enable CodeReuse/ActiveRecord
# rubocop: disable CodeReuse/ActiveRecord
def snippet_blobs
- limit_snippets.search_code(query).order('updated_at DESC').includes(:author)
+ limit_snippets.search_code(query).order("updated_at DESC").includes(:author)
end
# rubocop: enable CodeReuse/ActiveRecord
def default_scope
- 'snippet_blobs'
+ "snippet_blobs"
end
end
end
diff --git a/lib/gitlab/sql/glob.rb b/lib/gitlab/sql/glob.rb
index f3421bd95d2..40973210c59 100644
--- a/lib/gitlab/sql/glob.rb
+++ b/lib/gitlab/sql/glob.rb
@@ -10,9 +10,9 @@ module Gitlab
def to_like(pattern)
<<~SQL
REPLACE(REPLACE(REPLACE(#{pattern},
- #{q('%')}, #{q('\\%')}),
- #{q('_')}, #{q('\\_')}),
- #{q('*')}, #{q('%')})
+ #{q("%")}, #{q('\\%')}),
+ #{q("_")}, #{q('\\_')}),
+ #{q("*")}, #{q("%")})
SQL
end
diff --git a/lib/gitlab/sql/pattern.rb b/lib/gitlab/sql/pattern.rb
index 92388262035..4b019ba4eb9 100644
--- a/lib/gitlab/sql/pattern.rb
+++ b/lib/gitlab/sql/pattern.rb
@@ -44,7 +44,7 @@ module Gitlab
# case insensitive match with the query as a whole
if lower_exact_match
Arel::Nodes::NamedFunction
- .new('LOWER', [arel_table[column]])
+ .new("LOWER", [arel_table[column]])
.eq(query)
else
arel_table[column].matches(sanitize_sql_like(query))
@@ -55,7 +55,7 @@ module Gitlab
def select_fuzzy_words(query)
quoted_words = query.scan(REGEX_QUOTED_WORD)
- query = quoted_words.reduce(query) { |q, quoted_word| q.sub(quoted_word, '') }
+ query = quoted_words.reduce(query) { |q, quoted_word| q.sub(quoted_word, "") }
words = query.split
diff --git a/lib/gitlab/sql/recursive_cte.rb b/lib/gitlab/sql/recursive_cte.rb
index e45ac5d4765..52fbe48eca9 100644
--- a/lib/gitlab/sql/recursive_cte.rb
+++ b/lib/gitlab/sql/recursive_cte.rb
@@ -48,7 +48,7 @@ module Gitlab
#
# alias_table - The Arel table to use as the alias.
def alias_to(alias_table)
- Arel::Nodes::As.new(table, Arel::Table.new(alias_table.name.tr('.', '_')))
+ Arel::Nodes::As.new(table, Arel::Table.new(alias_table.name.tr(".", "_")))
end
# Applies the CTE to the given relation, returning a new one that will
diff --git a/lib/gitlab/sql/union.rb b/lib/gitlab/sql/union.rb
index f05592fc3a3..4ec399d5685 100644
--- a/lib/gitlab/sql/union.rb
+++ b/lib/gitlab/sql/union.rb
@@ -24,19 +24,19 @@ module Gitlab
# aren't incremented properly when joining relations together this way.
# By using "unprepared_statements" we remove the usage of placeholders
# (thus fixing this problem), at a slight performance cost.
- fragments = ActiveRecord::Base.connection.unprepared_statement do
+ fragments = ActiveRecord::Base.connection.unprepared_statement {
@relations.map { |rel| rel.reorder(nil).to_sql }.reject(&:blank?)
- end
+ }
if fragments.any?
fragments.join("\n#{union_keyword}\n")
else
- 'NULL'
+ "NULL"
end
end
def union_keyword
- @remove_duplicates ? 'UNION' : 'UNION ALL'
+ @remove_duplicates ? "UNION" : "UNION ALL"
end
end
end
diff --git a/lib/gitlab/ssh_public_key.rb b/lib/gitlab/ssh_public_key.rb
index 6df54852d02..a34c177338b 100644
--- a/lib/gitlab/ssh_public_key.rb
+++ b/lib/gitlab/ssh_public_key.rb
@@ -8,7 +8,7 @@ module Gitlab
Technology.new(:rsa, OpenSSL::PKey::RSA, [1024, 2048, 3072, 4096]),
Technology.new(:dsa, OpenSSL::PKey::DSA, [1024, 2048, 3072]),
Technology.new(:ecdsa, OpenSSL::PKey::EC, [256, 384, 521]),
- Technology.new(:ed25519, Net::SSH::Authentication::ED25519::PubKey, [256])
+ Technology.new(:ed25519, Net::SSH::Authentication::ED25519::PubKey, [256]),
].freeze
def self.technology(name)
@@ -32,7 +32,7 @@ module Gitlab
content << part
if Gitlab::SSHPublicKey.new(content).valid?
- break [content, parts[index + 1]].compact.join(' ') # Add the comment part if present
+ break [content, parts[index + 1]].compact.join(" ") # Add the comment part if present
elsif parts.size == index + 1 # return original content if we've reached the last element
break key_content
end
diff --git a/lib/gitlab/string_range_marker.rb b/lib/gitlab/string_range_marker.rb
index 780fe4c7725..ae7d7c9ffe6 100644
--- a/lib/gitlab/string_range_marker.rb
+++ b/lib/gitlab/string_range_marker.rb
@@ -58,8 +58,8 @@ module Gitlab
# The raw and rich lines are the same except for HTML tags,
# so skip over any `<...>` segment
- while rich_char == '<'
- until rich_char == '>'
+ while rich_char == "<"
+ until rich_char == ">"
rich_pos += 1
rich_char = rich_line[rich_pos]
end
@@ -69,9 +69,9 @@ module Gitlab
end
# multi-char HTML entities in the rich line correspond to a single character in the raw line
- if rich_char == '&'
+ if rich_char == "&"
multichar_mapping = [rich_pos]
- until rich_char == ';'
+ until rich_char == ";"
rich_pos += 1
multichar_mapping << rich_pos
rich_char = rich_line[rich_pos]
diff --git a/lib/gitlab/task_helpers.rb b/lib/gitlab/task_helpers.rb
index 8532845f3cb..6d74d700d46 100644
--- a/lib/gitlab/task_helpers.rb
+++ b/lib/gitlab/task_helpers.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'rainbow/ext/string'
-require_dependency 'gitlab/utils/strong_memoize'
+require "rainbow/ext/string"
+require_dependency "gitlab/utils/strong_memoize"
# rubocop:disable Rails/Output
module Gitlab
@@ -24,7 +24,7 @@ module Gitlab
# Returns "yes" the user chose to continue
# Raises Gitlab::TaskAbortedByUserError if the user chose *not* to continue
def ask_to_continue
- answer = prompt("Do you want to continue (yes/no)? ".color(:blue), %w{yes no})
+ answer = prompt("Do you want to continue (yes/no)? ".color(:blue), %w[yes no])
raise Gitlab::TaskAbortedByUserError unless answer == "yes"
end
@@ -33,18 +33,18 @@ module Gitlab
# It will primarily use lsb_relase to determine the OS.
# It has fallbacks to Debian, SuSE, OS X and systems running systemd.
def os_name
- os_name = run_command(%w(lsb_release -irs))
+ os_name = run_command(%w[lsb_release -irs])
os_name ||=
- if File.readable?('/etc/system-release')
- File.read('/etc/system-release')
- elsif File.readable?('/etc/debian_version')
- "Debian #{File.read('/etc/debian_version')}"
- elsif File.readable?('/etc/SuSE-release')
- File.read('/etc/SuSE-release')
- elsif os_x_version = run_command(%w(sw_vers -productVersion))
+ if File.readable?("/etc/system-release")
+ File.read("/etc/system-release")
+ elsif File.readable?("/etc/debian_version")
+ "Debian #{File.read("/etc/debian_version")}"
+ elsif File.readable?("/etc/SuSE-release")
+ File.read("/etc/SuSE-release")
+ elsif os_x_version = run_command(%w[sw_vers -productVersion])
"Mac OS X #{os_x_version}"
- elsif File.readable?('/etc/os-release')
- File.read('/etc/os-release').match(/PRETTY_NAME=\"(.+)\"/)[1]
+ elsif File.readable?("/etc/os-release")
+ File.read("/etc/os-release").match(/PRETTY_NAME=\"(.+)\"/)[1]
end
os_name.try(:squish)
@@ -85,7 +85,7 @@ module Gitlab
output, _ = Gitlab::Popen.popen(command)
output
rescue Errno::ENOENT
- '' # if the command does not exist, return an empty string
+ "" # if the command does not exist, return an empty string
end
# Runs the given command and raises a Gitlab::TaskFailedError exception if
@@ -101,7 +101,7 @@ module Gitlab
end
def uid_for(user_name)
- run_command(%W(id -u #{user_name})).chomp.to_i
+ run_command(%W[id -u #{user_name}]).chomp.to_i
end
def gid_for(group_name)
@@ -116,7 +116,7 @@ module Gitlab
def gitlab_user?
strong_memoize(:is_gitlab_user) do
- current_user = run_command(%w(whoami)).chomp
+ current_user = run_command(%w[whoami]).chomp
current_user == gitlab_user
end
end
@@ -125,7 +125,7 @@ module Gitlab
return if gitlab_user?
strong_memoize(:warned_user_not_gitlab) do
- current_user = run_command(%w(whoami)).chomp
+ current_user = run_command(%w[whoami]).chomp
puts " Warning ".color(:black).background(:yellow)
puts " You are running as user #{current_user.color(:magenta)}, we hope you know what you are doing."
@@ -138,7 +138,7 @@ module Gitlab
def all_repos
Gitlab::GitalyClient::StorageSettings.allow_disk_access do
Gitlab.config.repositories.storages.each_value do |repository_storage|
- IO.popen(%W(find #{repository_storage.legacy_disk_path} -mindepth 2 -type d -name *.git)) do |find|
+ IO.popen(%W[find #{repository_storage.legacy_disk_path} -mindepth 2 -type d -name *.git]) do |find|
find.each_line do |path|
yield path.chomp
end
@@ -154,13 +154,13 @@ module Gitlab
end
def user_home
- Rails.env.test? ? Rails.root.join('tmp/tests') : Gitlab.config.gitlab.user_home
+ Rails.env.test? ? Rails.root.join("tmp/tests") : Gitlab.config.gitlab.user_home
end
def checkout_or_clone_version(version:, repo:, target_dir:)
version =
if version.starts_with?("=")
- version.sub(/\A=/, '') # tag or branch
+ version.sub(/\A=/, "") # tag or branch
else
"v#{version}" # tag
end
diff --git a/lib/gitlab/tcp_checker.rb b/lib/gitlab/tcp_checker.rb
index f37a044b607..651a7ae5dab 100644
--- a/lib/gitlab/tcp_checker.rb
+++ b/lib/gitlab/tcp_checker.rb
@@ -39,7 +39,7 @@ module Gitlab
private
def join_host_port(host, port)
- host = "[#{host}]" if host.include?(':')
+ host = "[#{host}]" if host.include?(":")
"#{host}:#{port}"
end
diff --git a/lib/gitlab/template/base_template.rb b/lib/gitlab/template/base_template.rb
index 0b4cc571dc0..637643332bd 100644
--- a/lib/gitlab/template/base_template.rb
+++ b/lib/gitlab/template/base_template.rb
@@ -14,7 +14,7 @@ module Gitlab
def name
File.basename(@path, self.class.extension)
end
- alias_method :key, :name
+ alias key name
def content
@finder.read(@path)
@@ -28,7 +28,7 @@ module Gitlab
end
def to_json
- { key: key, name: name, content: content }
+ {key: key, name: name, content: content}
end
def <=>(other)
@@ -45,7 +45,7 @@ module Gitlab
end
def find(key, project = nil)
- path = self.finder(project).find(key)
+ path = finder(project).find(key)
path.present? ? new(path, project) : nil
end
@@ -90,13 +90,13 @@ module Gitlab
return [] if project && !project.repository.exists?
if categories.any?
- categories.keys.map do |category|
- files = self.by_category(category, project)
- [category, files.map { |t| { name: t.name } }]
- end.to_h
+ categories.keys.map { |category|
+ files = by_category(category, project)
+ [category, files.map { |t| {name: t.name} }]
+ }.to_h
else
- files = self.all(project)
- files.map { |t| { name: t.name } }
+ files = all(project)
+ files.map { |t| {name: t.name} }
end
end
end
diff --git a/lib/gitlab/template/dockerfile_template.rb b/lib/gitlab/template/dockerfile_template.rb
index 3b516bb862a..34c550cff94 100644
--- a/lib/gitlab/template/dockerfile_template.rb
+++ b/lib/gitlab/template/dockerfile_template.rb
@@ -10,21 +10,21 @@ module Gitlab
class << self
def extension
- '.Dockerfile'
+ ".Dockerfile"
end
def categories
{
- "General" => ''
+ "General" => "",
}
end
def base_dir
- Rails.root.join('vendor/Dockerfile')
+ Rails.root.join("vendor/Dockerfile")
end
def finder(project = nil)
- Gitlab::Template::Finders::GlobalTemplateFinder.new(self.base_dir, self.extension, self.categories)
+ Gitlab::Template::Finders::GlobalTemplateFinder.new(base_dir, extension, categories)
end
end
end
diff --git a/lib/gitlab/template/finders/global_template_finder.rb b/lib/gitlab/template/finders/global_template_finder.rb
index 2dd4b7a4092..b6100f219ce 100644
--- a/lib/gitlab/template/finders/global_template_finder.rb
+++ b/lib/gitlab/template/finders/global_template_finder.rb
@@ -27,7 +27,7 @@ module Gitlab
end
def list_files_for(dir)
- dir = "#{dir}/" unless dir.end_with?('/')
+ dir = "#{dir}/" unless dir.end_with?("/")
Dir.glob(File.join(dir, "*#{@extension}")).select { |f| f =~ self.class.filter_regex(@extension) }
end
diff --git a/lib/gitlab/template/finders/repo_template_finder.rb b/lib/gitlab/template/finders/repo_template_finder.rb
index 8e234148a63..0d3ddf41ede 100644
--- a/lib/gitlab/template/finders/repo_template_finder.rb
+++ b/lib/gitlab/template/finders/repo_template_finder.rb
@@ -40,7 +40,7 @@ module Gitlab
def list_files_for(dir)
return [] unless @commit
- dir = "#{dir}/" unless dir.end_with?('/')
+ dir = "#{dir}/" unless dir.end_with?("/")
entries = @repository.tree(:head, dir).entries
diff --git a/lib/gitlab/template/gitignore_template.rb b/lib/gitlab/template/gitignore_template.rb
index 72a1b7460c2..27318e6e33e 100644
--- a/lib/gitlab/template/gitignore_template.rb
+++ b/lib/gitlab/template/gitignore_template.rb
@@ -5,22 +5,22 @@ module Gitlab
class GitignoreTemplate < BaseTemplate
class << self
def extension
- '.gitignore'
+ ".gitignore"
end
def categories
{
- "Languages" => '',
- "Global" => 'Global'
+ "Languages" => "",
+ "Global" => "Global",
}
end
def base_dir
- Rails.root.join('vendor/gitignore')
+ Rails.root.join("vendor/gitignore")
end
def finder(project = nil)
- Gitlab::Template::Finders::GlobalTemplateFinder.new(self.base_dir, self.extension, self.categories)
+ Gitlab::Template::Finders::GlobalTemplateFinder.new(base_dir, extension, categories)
end
end
end
diff --git a/lib/gitlab/template/gitlab_ci_yml_template.rb b/lib/gitlab/template/gitlab_ci_yml_template.rb
index fbefb5f7f0e..4760304bed9 100644
--- a/lib/gitlab/template/gitlab_ci_yml_template.rb
+++ b/lib/gitlab/template/gitlab_ci_yml_template.rb
@@ -10,27 +10,27 @@ module Gitlab
class << self
def extension
- '.gitlab-ci.yml'
+ ".gitlab-ci.yml"
end
def categories
{
- 'General' => '',
- 'Pages' => 'Pages',
- 'Auto deploy' => 'autodeploy'
+ "General" => "",
+ "Pages" => "Pages",
+ "Auto deploy" => "autodeploy",
}
end
def base_dir
- Rails.root.join('lib/gitlab/ci/templates')
+ Rails.root.join("lib/gitlab/ci/templates")
end
def finder(project = nil)
- Gitlab::Template::Finders::GlobalTemplateFinder.new(self.base_dir, self.extension, self.categories)
+ Gitlab::Template::Finders::GlobalTemplateFinder.new(base_dir, extension, categories)
end
def dropdown_names(context)
- categories = context == 'autodeploy' ? ['Auto deploy'] : %w(General Pages)
+ categories = context == "autodeploy" ? ["Auto deploy"] : %w[General Pages]
super().slice(*categories)
end
end
diff --git a/lib/gitlab/template/issue_template.rb b/lib/gitlab/template/issue_template.rb
index 01b191733d4..a1e5c53be94 100644
--- a/lib/gitlab/template/issue_template.rb
+++ b/lib/gitlab/template/issue_template.rb
@@ -5,15 +5,15 @@ module Gitlab
class IssueTemplate < BaseTemplate
class << self
def extension
- '.md'
+ ".md"
end
def base_dir
- '.gitlab/issue_templates/'
+ ".gitlab/issue_templates/"
end
def finder(project)
- Gitlab::Template::Finders::RepoTemplateFinder.new(project, self.base_dir, self.extension, self.categories)
+ Gitlab::Template::Finders::RepoTemplateFinder.new(project, base_dir, extension, categories)
end
end
end
diff --git a/lib/gitlab/template/merge_request_template.rb b/lib/gitlab/template/merge_request_template.rb
index 357b31cd82e..d32822691df 100644
--- a/lib/gitlab/template/merge_request_template.rb
+++ b/lib/gitlab/template/merge_request_template.rb
@@ -5,15 +5,15 @@ module Gitlab
class MergeRequestTemplate < BaseTemplate
class << self
def extension
- '.md'
+ ".md"
end
def base_dir
- '.gitlab/merge_request_templates/'
+ ".gitlab/merge_request_templates/"
end
def finder(project)
- Gitlab::Template::Finders::RepoTemplateFinder.new(project, self.base_dir, self.extension, self.categories)
+ Gitlab::Template::Finders::RepoTemplateFinder.new(project, base_dir, extension, categories)
end
end
end
diff --git a/lib/gitlab/testing/request_blocker_middleware.rb b/lib/gitlab/testing/request_blocker_middleware.rb
index 513cbe839ba..49894f35462 100644
--- a/lib/gitlab/testing/request_blocker_middleware.rb
+++ b/lib/gitlab/testing/request_blocker_middleware.rb
@@ -46,7 +46,6 @@ module Gitlab
sleep 0.2 if slow_requests?
@app.call(env)
end
-
ensure
decrement_active_requests
end
diff --git a/lib/gitlab/testing/request_inspector_middleware.rb b/lib/gitlab/testing/request_inspector_middleware.rb
index 36cdfebcc28..7b2bdc4f8f8 100644
--- a/lib/gitlab/testing/request_inspector_middleware.rb
+++ b/lib/gitlab/testing/request_inspector_middleware.rb
@@ -32,12 +32,12 @@ module Gitlab
def call(env)
return @app.call(env) unless @@log_requests.true?
- url = env['REQUEST_URI']
+ url = env["REQUEST_URI"]
env.merge! http_headers_env(@@inject_headers) if @@inject_headers.any?
request_headers = env_http_headers(env)
status, headers, body = @app.call(env)
- full_body = +''
+ full_body = +""
body.each { |b| full_body << b }
request = OpenStruct.new(
@@ -55,17 +55,17 @@ module Gitlab
private
def env_http_headers(env)
- Hash[*env.select { |k, v| k.start_with? 'HTTP_' }
- .collect { |k, v| [k.sub(/^HTTP_/, ''), v] }
- .collect { |k, v| [k.split('_').collect(&:capitalize).join('-'), v] }
+ Hash[*env.select { |k, v| k.start_with? "HTTP_" }
+ .collect { |k, v| [k.sub(/^HTTP_/, ""), v] }
+ .collect { |k, v| [k.split("_").collect(&:capitalize).join("-"), v] }
.sort
.flatten]
end
def http_headers_env(headers)
Hash[*headers
- .collect { |k, v| [k.split('-').collect(&:upcase).join('_'), v] }
- .collect { |k, v| [k.prepend('HTTP_'), v] }
+ .collect { |k, v| [k.split("-").collect(&:upcase).join("_"), v] }
+ .collect { |k, v| [k.prepend("HTTP_"), v] }
.flatten]
end
diff --git a/lib/gitlab/themes.rb b/lib/gitlab/themes.rb
index 63860b9cb26..4b06d5725ba 100644
--- a/lib/gitlab/themes.rb
+++ b/lib/gitlab/themes.rb
@@ -14,16 +14,16 @@ module Gitlab
# All available Themes
THEMES = [
- Theme.new(1, 'Indigo', 'ui-indigo'),
- Theme.new(6, 'Light Indigo', 'ui-light-indigo'),
- Theme.new(4, 'Blue', 'ui-blue'),
- Theme.new(7, 'Light Blue', 'ui-light-blue'),
- Theme.new(5, 'Green', 'ui-green'),
- Theme.new(8, 'Light Green', 'ui-light-green'),
- Theme.new(9, 'Red', 'ui-red'),
- Theme.new(10, 'Light Red', 'ui-light-red'),
- Theme.new(2, 'Dark', 'ui-dark'),
- Theme.new(3, 'Light', 'ui-light')
+ Theme.new(1, "Indigo", "ui-indigo"),
+ Theme.new(6, "Light Indigo", "ui-light-indigo"),
+ Theme.new(4, "Blue", "ui-blue"),
+ Theme.new(7, "Light Blue", "ui-light-blue"),
+ Theme.new(5, "Green", "ui-green"),
+ Theme.new(8, "Light Green", "ui-light-green"),
+ Theme.new(9, "Red", "ui-red"),
+ Theme.new(10, "Light Red", "ui-light-red"),
+ Theme.new(2, "Dark", "ui-dark"),
+ Theme.new(3, "Light", "ui-light"),
].freeze
# Convenience method to get a space-separated String of all the theme
@@ -31,7 +31,7 @@ module Gitlab
#
# Returns a String
def body_classes
- THEMES.collect(&:css_class).uniq.join(' ')
+ THEMES.collect(&:css_class).uniq.join(" ")
end
# Get a Theme by its ID
diff --git a/lib/gitlab/time_tracking_formatter.rb b/lib/gitlab/time_tracking_formatter.rb
index cc206010e74..f89d605b296 100644
--- a/lib/gitlab/time_tracking_formatter.rb
+++ b/lib/gitlab/time_tracking_formatter.rb
@@ -6,9 +6,13 @@ module Gitlab
def parse(string)
with_custom_config do
- string.sub!(/\A-/, '')
+ string.sub!(/\A-/, "")
- seconds = ChronicDuration.parse(string, default_unit: 'hours') rescue nil
+ seconds = begin
+ ChronicDuration.parse(string, default_unit: "hours")
+ rescue
+ nil
+ end
seconds *= -1 if seconds && Regexp.last_match
seconds
end
@@ -16,7 +20,9 @@ module Gitlab
def output(seconds)
with_custom_config do
- ChronicDuration.output(seconds, format: :short, limit_to_hours: false, weeks: true) rescue nil
+ ChronicDuration.output(seconds, format: :short, limit_to_hours: false, weeks: true)
+ rescue
+ nil
end
end
diff --git a/lib/gitlab/timeless.rb b/lib/gitlab/timeless.rb
index 4f974c98c71..3a946198e60 100644
--- a/lib/gitlab/timeless.rb
+++ b/lib/gitlab/timeless.rb
@@ -11,7 +11,6 @@ module Gitlab
else
block.call
end
-
ensure
model.record_timestamps = original_record_timestamps
end
diff --git a/lib/gitlab/tracing.rb b/lib/gitlab/tracing.rb
index 29517591c51..08e55374655 100644
--- a/lib/gitlab/tracing.rb
+++ b/lib/gitlab/tracing.rb
@@ -11,11 +11,11 @@ module Gitlab
end
def self.connection_string
- ENV['GITLAB_TRACING']
+ ENV["GITLAB_TRACING"]
end
def self.tracing_url_template
- ENV['GITLAB_TRACING_URL']
+ ENV["GITLAB_TRACING_URL"]
end
def self.tracing_url_enabled?
diff --git a/lib/gitlab/tracing/common.rb b/lib/gitlab/tracing/common.rb
index 3a08ede8138..18cb3bf9d33 100644
--- a/lib/gitlab/tracing/common.rb
+++ b/lib/gitlab/tracing/common.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'opentracing'
+require "opentracing"
module Gitlab
module Tracing
@@ -21,7 +21,7 @@ module Gitlab
# Add correlation details to the span if we have them
correlation_id = Gitlab::CorrelationId.current_id
if correlation_id
- span.set_tag('correlation_id', correlation_id)
+ span.set_tag("correlation_id", correlation_id)
end
begin
@@ -43,7 +43,7 @@ module Gitlab
end
def log_exception_on_span(span, exception)
- span.set_tag('error', true)
+ span.set_tag("error", true)
span.log_kv(kv_tags_for_exception(exception))
end
@@ -51,16 +51,16 @@ module Gitlab
case exception
when Exception
{
- 'event': 'error',
+ 'event': "error",
'error.kind': exception.class.to_s,
- 'message': Gitlab::UrlSanitizer.sanitize(exception.message),
- 'stack': exception.backtrace&.join("\n")
+ 'message': Gitlab::UrlSanitizer.sanitize(exception.message),
+ 'stack': exception.backtrace&.join("\n"),
}
else
{
- 'event': 'error',
- 'error.kind': exception.class.to_s,
- 'error.object': Gitlab::UrlSanitizer.sanitize(exception.to_s)
+ 'event': "error",
+ 'error.kind': exception.class.to_s,
+ 'error.object': Gitlab::UrlSanitizer.sanitize(exception.to_s),
}
end
end
diff --git a/lib/gitlab/tracing/factory.rb b/lib/gitlab/tracing/factory.rb
index fc714164353..1218c52331b 100644
--- a/lib/gitlab/tracing/factory.rb
+++ b/lib/gitlab/tracing/factory.rb
@@ -36,7 +36,7 @@ module Gitlab
{
driver_name: parsed.host,
- options: parse_query(parsed.query)
+ options: parse_query(parsed.query),
}
end
private_class_method :parse_connection_string
diff --git a/lib/gitlab/tracing/grpc_interceptor.rb b/lib/gitlab/tracing/grpc_interceptor.rb
index 6c2aab73125..5a74ba107c4 100644
--- a/lib/gitlab/tracing/grpc_interceptor.rb
+++ b/lib/gitlab/tracing/grpc_interceptor.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'opentracing'
-require 'grpc'
+require "opentracing"
+require "grpc"
module Gitlab
module Tracing
@@ -10,25 +10,25 @@ module Gitlab
include Singleton
def request_response(request:, call:, method:, metadata:)
- wrap_with_tracing(method, 'unary', metadata) do
+ wrap_with_tracing(method, "unary", metadata) do
yield
end
end
def client_streamer(requests:, call:, method:, metadata:)
- wrap_with_tracing(method, 'client_stream', metadata) do
+ wrap_with_tracing(method, "client_stream", metadata) do
yield
end
end
def server_streamer(request:, call:, method:, metadata:)
- wrap_with_tracing(method, 'server_stream', metadata) do
+ wrap_with_tracing(method, "server_stream", metadata) do
yield
end
end
def bidi_streamer(requests:, call:, method:, metadata:)
- wrap_with_tracing(method, 'bidi_stream', metadata) do
+ wrap_with_tracing(method, "bidi_stream", metadata) do
yield
end
end
@@ -37,10 +37,10 @@ module Gitlab
def wrap_with_tracing(method, grpc_type, metadata)
tags = {
- 'component' => 'grpc',
- 'span.kind' => 'client',
- 'grpc.method' => method,
- 'grpc.type' => grpc_type
+ "component" => "grpc",
+ "span.kind" => "client",
+ "grpc.method" => method,
+ "grpc.type" => grpc_type,
}
in_tracing_span(operation_name: "grpc:#{method}", tags: tags) do |span|
diff --git a/lib/gitlab/tracing/jaeger_factory.rb b/lib/gitlab/tracing/jaeger_factory.rb
index 2682007302a..fb3003ecb4d 100644
--- a/lib/gitlab/tracing/jaeger_factory.rb
+++ b/lib/gitlab/tracing/jaeger_factory.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'jaeger/client'
+require "jaeger/client"
module Gitlab
module Tracing
@@ -21,7 +21,7 @@ module Gitlab
kwargs = {
service_name: service_name,
sampler: get_sampler(options[:sampler], options[:sampler_param]),
- reporter: get_reporter(service_name, options[:http_endpoint], options[:udp_endpoint])
+ reporter: get_reporter(service_name, options[:http_endpoint], options[:udp_endpoint]),
}.compact
extra_params = options.except(:sampler, :sampler_param, :http_endpoint, :udp_endpoint, :strict_parsing, :debug) # rubocop: disable CodeReuse/ActiveRecord
@@ -46,8 +46,6 @@ module Gitlab
when "const"
const_value = sampler_param == "1"
Jaeger::Samplers::Const.new(const_value)
- else
- nil
end
end
private_class_method :get_sampler
diff --git a/lib/gitlab/tracing/rack_middleware.rb b/lib/gitlab/tracing/rack_middleware.rb
index e6a31293f7b..5e5f083a14b 100644
--- a/lib/gitlab/tracing/rack_middleware.rb
+++ b/lib/gitlab/tracing/rack_middleware.rb
@@ -1,13 +1,13 @@
# frozen_string_literal: true
-require 'opentracing'
+require "opentracing"
module Gitlab
module Tracing
class RackMiddleware
include Common
- REQUEST_METHOD = 'REQUEST_METHOD'
+ REQUEST_METHOD = "REQUEST_METHOD"
def initialize(app)
@app = app
@@ -18,15 +18,15 @@ module Gitlab
context = tracer.extract(OpenTracing::FORMAT_RACK, env)
tags = {
- 'component' => 'rack',
- 'span.kind' => 'server',
- 'http.method' => method,
- 'http.url' => self.class.build_sanitized_url_from_env(env)
+ "component" => "rack",
+ "span.kind" => "server",
+ "http.method" => method,
+ "http.url" => self.class.build_sanitized_url_from_env(env),
}
in_tracing_span(operation_name: "http:#{method}", child_of: context, tags: tags) do |span|
@app.call(env).tap do |status_code, _headers, _body|
- span.set_tag('http.status_code', status_code)
+ span.set_tag("http.status_code", status_code)
end
end
end
diff --git a/lib/gitlab/tracing/rails/action_view_subscriber.rb b/lib/gitlab/tracing/rails/action_view_subscriber.rb
index 88816e1fb32..bb86e45d347 100644
--- a/lib/gitlab/tracing/rails/action_view_subscriber.rb
+++ b/lib/gitlab/tracing/rails/action_view_subscriber.rb
@@ -6,10 +6,10 @@ module Gitlab
class ActionViewSubscriber
include RailsCommon
- COMPONENT_TAG = 'ActionView'
- RENDER_TEMPLATE_NOTIFICATION_TOPIC = 'render_template.action_view'
- RENDER_COLLECTION_NOTIFICATION_TOPIC = 'render_collection.action_view'
- RENDER_PARTIAL_NOTIFICATION_TOPIC = 'render_partial.action_view'
+ COMPONENT_TAG = "ActionView"
+ RENDER_TEMPLATE_NOTIFICATION_TOPIC = "render_template.action_view"
+ RENDER_COLLECTION_NOTIFICATION_TOPIC = "render_collection.action_view"
+ RENDER_PARTIAL_NOTIFICATION_TOPIC = "render_partial.action_view"
# Instruments Rails ActionView events for opentracing.
# Returns a lambda, which, when called will unsubscribe from the notifications
@@ -25,7 +25,7 @@ module Gitlab
end,
ActiveSupport::Notifications.subscribe(RENDER_PARTIAL_NOTIFICATION_TOPIC) do |_, start, finish, _, payload|
subscriber.notify_render_partial(start, finish, payload)
- end
+ end,
]
create_unsubscriber subscriptions
@@ -48,25 +48,25 @@ module Gitlab
def tags_for_render_template(payload)
{
- 'component' => COMPONENT_TAG,
- 'template.id' => payload[:identifier],
- 'template.layout' => payload[:layout]
+ "component" => COMPONENT_TAG,
+ "template.id" => payload[:identifier],
+ "template.layout" => payload[:layout],
}
end
def tags_for_render_collection(payload)
{
- 'component' => COMPONENT_TAG,
- 'template.id' => payload[:identifier],
- 'template.count' => payload[:count] || 0,
- 'template.cache.hits' => payload[:cache_hits] || 0
+ "component" => COMPONENT_TAG,
+ "template.id" => payload[:identifier],
+ "template.count" => payload[:count] || 0,
+ "template.cache.hits" => payload[:cache_hits] || 0,
}
end
def tags_for_render_partial(payload)
{
- 'component' => COMPONENT_TAG,
- 'template.id' => payload[:identifier]
+ "component" => COMPONENT_TAG,
+ "template.id" => payload[:identifier],
}
end
end
diff --git a/lib/gitlab/tracing/rails/active_record_subscriber.rb b/lib/gitlab/tracing/rails/active_record_subscriber.rb
index 32f5658e57e..5fbf07038a4 100644
--- a/lib/gitlab/tracing/rails/active_record_subscriber.rb
+++ b/lib/gitlab/tracing/rails/active_record_subscriber.rb
@@ -6,18 +6,18 @@ module Gitlab
class ActiveRecordSubscriber
include RailsCommon
- ACTIVE_RECORD_NOTIFICATION_TOPIC = 'sql.active_record'
- OPERATION_NAME_PREFIX = 'active_record:'
- DEFAULT_OPERATION_NAME = 'sqlquery'
+ ACTIVE_RECORD_NOTIFICATION_TOPIC = "sql.active_record"
+ OPERATION_NAME_PREFIX = "active_record:"
+ DEFAULT_OPERATION_NAME = "sqlquery"
# Instruments Rails ActiveRecord events for opentracing.
# Returns a lambda, which, when called will unsubscribe from the notifications
def self.instrument
subscriber = new
- subscription = ActiveSupport::Notifications.subscribe(ACTIVE_RECORD_NOTIFICATION_TOPIC) do |_, start, finish, _, payload|
+ subscription = ActiveSupport::Notifications.subscribe(ACTIVE_RECORD_NOTIFICATION_TOPIC) { |_, start, finish, _, payload|
subscriber.notify(start, finish, payload)
- end
+ }
create_unsubscriber [subscription]
end
@@ -35,12 +35,12 @@ module Gitlab
def tags_for_notification(payload)
{
- 'component' => 'ActiveRecord',
- 'span.kind' => 'client',
- 'db.type' => 'sql',
- 'db.connection_id' => payload[:connection_id],
- 'db.cached' => payload[:cached] || false,
- 'db.statement' => payload[:sql]
+ "component" => "ActiveRecord",
+ "span.kind" => "client",
+ "db.type" => "sql",
+ "db.connection_id" => payload[:connection_id],
+ "db.cached" => payload[:cached] || false,
+ "db.statement" => payload[:sql],
}
end
end
diff --git a/lib/gitlab/tracing/sidekiq/client_middleware.rb b/lib/gitlab/tracing/sidekiq/client_middleware.rb
index 2b71c1ea21e..008f106d6e3 100644
--- a/lib/gitlab/tracing/sidekiq/client_middleware.rb
+++ b/lib/gitlab/tracing/sidekiq/client_middleware.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'opentracing'
+require "opentracing"
module Gitlab
module Tracing
@@ -8,12 +8,13 @@ module Gitlab
class ClientMiddleware
include SidekiqCommon
- SPAN_KIND = 'client'
+ SPAN_KIND = "client"
def call(worker_class, job, queue, redis_pool)
in_tracing_span(
- operation_name: "sidekiq:#{job['class']}",
- tags: tags_from_job(job, SPAN_KIND)) do |span|
+ operation_name: "sidekiq:#{job["class"]}",
+ tags: tags_from_job(job, SPAN_KIND)
+ ) do |span|
# Inject the details directly into the job
tracer.inject(span.context, OpenTracing::FORMAT_TEXT_MAP, job)
diff --git a/lib/gitlab/tracing/sidekiq/server_middleware.rb b/lib/gitlab/tracing/sidekiq/server_middleware.rb
index 5b43c4310e6..d83fb17148e 100644
--- a/lib/gitlab/tracing/sidekiq/server_middleware.rb
+++ b/lib/gitlab/tracing/sidekiq/server_middleware.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'opentracing'
+require "opentracing"
module Gitlab
module Tracing
@@ -8,15 +8,16 @@ module Gitlab
class ServerMiddleware
include SidekiqCommon
- SPAN_KIND = 'server'
+ SPAN_KIND = "server"
def call(worker, job, queue)
context = tracer.extract(OpenTracing::FORMAT_TEXT_MAP, job)
in_tracing_span(
- operation_name: "sidekiq:#{job['class']}",
+ operation_name: "sidekiq:#{job["class"]}",
child_of: context,
- tags: tags_from_job(job, SPAN_KIND)) do |span|
+ tags: tags_from_job(job, SPAN_KIND)
+ ) do |span|
yield
end
end
diff --git a/lib/gitlab/tracing/sidekiq/sidekiq_common.rb b/lib/gitlab/tracing/sidekiq/sidekiq_common.rb
index a911a29d773..d8208d54c60 100644
--- a/lib/gitlab/tracing/sidekiq/sidekiq_common.rb
+++ b/lib/gitlab/tracing/sidekiq/sidekiq_common.rb
@@ -8,12 +8,12 @@ module Gitlab
def tags_from_job(job, kind)
{
- 'component' => 'sidekiq',
- 'span.kind' => kind,
- 'sidekiq.queue' => job['queue'],
- 'sidekiq.jid' => job['jid'],
- 'sidekiq.retry' => job['retry'].to_s,
- 'sidekiq.args' => job['args']&.join(", ")
+ "component" => "sidekiq",
+ "span.kind" => kind,
+ "sidekiq.queue" => job["queue"],
+ "sidekiq.jid" => job["jid"],
+ "sidekiq.retry" => job["retry"].to_s,
+ "sidekiq.args" => job["args"]&.join(", "),
}
end
end
diff --git a/lib/gitlab/tree_summary.rb b/lib/gitlab/tree_summary.rb
index 453d78e2f7b..833e3880f1a 100644
--- a/lib/gitlab/tree_summary.rb
+++ b/lib/gitlab/tree_summary.rb
@@ -71,14 +71,14 @@ module Gitlab
end
def build_entry(entry)
- { file_name: entry.name, type: entry.type }
+ {file_name: entry.name, type: entry.type}
end
def fill_last_commits!(entries)
# Ensure the path is in "path/" format
ensured_path =
if path
- File.join(*[path, ""])
+ File.join(path, "")
end
commits_hsh = repository.list_last_commits_for_tree(commit.id, ensured_path, offset: offset, limit: limit)
@@ -109,7 +109,7 @@ module Gitlab
[
*tree.trees,
*tree.blobs,
- *tree.submodules
+ *tree.submodules,
]
end
end
diff --git a/lib/gitlab/untrusted_regexp.rb b/lib/gitlab/untrusted_regexp.rb
index ba1137313d8..31a087c066e 100644
--- a/lib/gitlab/untrusted_regexp.rb
+++ b/lib/gitlab/untrusted_regexp.rb
@@ -11,7 +11,7 @@ module Gitlab
# there is a strict limit on total execution time. See the RE2 documentation
# at https://github.com/google/re2/wiki/Syntax for more details.
class UntrustedRegexp
- require_dependency 're2'
+ require_dependency "re2"
delegate :===, :source, to: :regexp
@@ -40,7 +40,7 @@ module Gitlab
end
def ==(other)
- self.source == other.source
+ source == other.source
end
# Handles regular expressions with the preferred RE2 library where possible
@@ -57,7 +57,7 @@ module Gitlab
end
def self.valid?(pattern)
- !!self.fabricate(pattern)
+ !!fabricate(pattern)
rescue RegexpError
false
end
@@ -65,13 +65,13 @@ module Gitlab
def self.fabricate(pattern)
matches = pattern.match(%r{^/(?<regexp>.+)/(?<flags>[ismU]*)$})
- raise RegexpError, 'Invalid regular expression!' if matches.nil?
+ raise RegexpError, "Invalid regular expression!" if matches.nil?
expression = matches[:regexp]
flags = matches[:flags]
expression.prepend("(?#{flags})") if flags.present?
- self.new(expression, multiline: false)
+ new(expression, multiline: false)
end
private
@@ -83,7 +83,7 @@ module Gitlab
def scan_regexp
@scan_regexp ||=
if regexp.number_of_capturing_groups.zero?
- RE2::Regexp.new('(' + regexp.source + ')')
+ RE2::Regexp.new("(" + regexp.source + ")")
else
regexp
end
diff --git a/lib/gitlab/url_blocker.rb b/lib/gitlab/url_blocker.rb
index 9b7b0db9525..e153d6b6437 100644
--- a/lib/gitlab/url_blocker.rb
+++ b/lib/gitlab/url_blocker.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'resolv'
-require 'ipaddress'
+require "resolv"
+require "ipaddress"
module Gitlab
class UrlBlocker
@@ -27,9 +27,9 @@ module Gitlab
validate_unicode_restriction!(uri) if ascii_only
begin
- addrs_info = Addrinfo.getaddrinfo(uri.hostname, port, nil, :STREAM).map do |addr|
+ addrs_info = Addrinfo.getaddrinfo(uri.hostname, port, nil, :STREAM).map { |addr|
addr.ipv6_v4mapped? ? addr.ipv6_to_ipv4 : addr
- end
+ }
rescue SocketError
return true
end
@@ -60,7 +60,7 @@ module Gitlab
uri_str = uri.to_s
sanitized_uri = ActionController::Base.helpers.sanitize(uri_str, tags: [])
if sanitized_uri != uri_str
- raise BlockedUrlError, 'HTML/CSS/JS tags are not allowed'
+ raise BlockedUrlError, "HTML/CSS/JS tags are not allowed"
end
end
@@ -69,7 +69,7 @@ module Gitlab
Addressable::URI.parse(url)
rescue Addressable::URI::InvalidURIError, URI::InvalidURIError
- raise BlockedUrlError, 'URI is invalid'
+ raise BlockedUrlError, "URI is invalid"
end
def multiline?(url)
@@ -82,12 +82,12 @@ module Gitlab
return if port >= 1024
return if ports.include?(port)
- raise BlockedUrlError, "Only allowed ports are #{ports.join(', ')}, and any over 1024"
+ raise BlockedUrlError, "Only allowed ports are #{ports.join(", ")}, and any over 1024"
end
def validate_protocol!(protocol, protocols)
if protocol.blank? || (protocols.any? && !protocols.include?(protocol))
- raise BlockedUrlError, "Only allowed protocols are #{protocols.join(', ')}"
+ raise BlockedUrlError, "Only allowed protocols are #{protocols.join(", ")}"
end
end
@@ -134,7 +134,7 @@ module Gitlab
end
def validate_link_local!(addrs_info)
- netmask = IPAddr.new('169.254.0.0/16')
+ netmask = IPAddr.new("169.254.0.0/16")
return unless addrs_info.any? { |addr| addr.ipv6_linklocal? || netmask.include?(addr.ip_address) }
raise BlockedUrlError, "Requests to the link local network are not allowed"
@@ -151,7 +151,7 @@ module Gitlab
end
def internal_shell?(uri)
- uri.scheme == 'ssh' &&
+ uri.scheme == "ssh" &&
uri.hostname == config.gitlab_shell.ssh_host &&
(uri.port.blank? || uri.port == config.gitlab_shell.ssh_port)
end
diff --git a/lib/gitlab/url_builder.rb b/lib/gitlab/url_builder.rb
index f86d599e4cb..a5819b63640 100644
--- a/lib/gitlab/url_builder.rb
+++ b/lib/gitlab/url_builder.rb
@@ -42,12 +42,12 @@ module Gitlab
end
def commit_url(opts = {})
- return '' if object.project.nil?
+ return "" if object.project.nil?
namespace_project_commit_url({
namespace_id: object.project.namespace,
project_id: object.project,
- id: object.id
+ id: object.id,
}.merge!(opts))
end
diff --git a/lib/gitlab/url_sanitizer.rb b/lib/gitlab/url_sanitizer.rb
index 880712de5fe..dbd0b2deb7a 100644
--- a/lib/gitlab/url_sanitizer.rb
+++ b/lib/gitlab/url_sanitizer.rb
@@ -9,7 +9,7 @@ module Gitlab
content.gsub(regexp) { |url| new(url).masked_url }
rescue Addressable::URI::InvalidURIError
- content.gsub(regexp, '')
+ content.gsub(regexp, "")
end
def self.valid?(url)
@@ -44,7 +44,7 @@ module Gitlab
end
def credentials
- @credentials ||= { user: @url.user.presence, password: @url.password.presence }
+ @credentials ||= {user: @url.user.presence, password: @url.password.presence}
end
def full_url
@@ -59,10 +59,10 @@ module Gitlab
raw_credentials = match[1] if match
if raw_credentials.present?
- url.sub!("#{raw_credentials}@", '')
+ url.sub!("#{raw_credentials}@", "")
- user, _, password = raw_credentials.partition(':')
- @credentials ||= { user: user.presence, password: password.presence }
+ user, _, password = raw_credentials.partition(":")
+ @credentials ||= {user: user.presence, password: password.presence}
end
url = Addressable::URI.parse(url)
@@ -88,12 +88,12 @@ module Gitlab
end
def valid_credentials?
- credentials && credentials.is_a?(Hash) && credentials.any?
+ credentials&.is_a?(Hash) && credentials&.any?
end
def encode_percent(string)
# CGI.escape converts spaces to +, but this doesn't work for git clone
- CGI.escape(string).gsub('+', '%20')
+ CGI.escape(string).gsub("+", "%20")
end
end
end
diff --git a/lib/gitlab/usage_data.rb b/lib/gitlab/usage_data.rb
index 0101ccc046a..a8fad547c2e 100644
--- a/lib/gitlab/usage_data.rb
+++ b/lib/gitlab/usage_data.rb
@@ -6,15 +6,15 @@ module Gitlab
class << self
def data(force_refresh: false)
- Rails.cache.fetch('usage_data', force: force_refresh, expires_in: 2.weeks) { uncached_data }
+ Rails.cache.fetch("usage_data", force: force_refresh, expires_in: 2.weeks) { uncached_data }
end
def uncached_data
license_usage_data.merge(system_usage_data)
- .merge(features_usage_data)
- .merge(components_usage_data)
- .merge(cycle_analytics_usage_data)
- .merge(usage_counters)
+ .merge(features_usage_data)
+ .merge(components_usage_data)
+ .merge(cycle_analytics_usage_data)
+ .merge(usage_counters)
end
def to_json(force_refresh: false)
@@ -29,7 +29,7 @@ module Gitlab
installation_type: Gitlab::INSTALLATION_TYPE,
active_user_count: count(User.active),
recorded_at: Time.now,
- edition: 'CE'
+ edition: "CE",
}
usage_data
@@ -80,8 +80,8 @@ module Gitlab
milestones: count(Milestone),
pages_domains: count(PagesDomain),
projects: count(Project),
- projects_imported_from_github: count(Project.where(import_type: 'github')),
- projects_with_repositories_enabled: count(ProjectFeature.where('repository_access_level > ?', ProjectFeature::DISABLED)),
+ projects_imported_from_github: count(Project.where(import_type: "github")),
+ projects_with_repositories_enabled: count(ProjectFeature.where("repository_access_level > ?", ProjectFeature::DISABLED)),
protected_branches: count(ProtectedBranch),
releases: count(Release),
remote_mirrors: count(RemoteMirror),
@@ -89,10 +89,10 @@ module Gitlab
suggestions: count(Suggestion),
todos: count(Todo),
uploads: count(Upload),
- web_hooks: count(WebHook)
+ web_hooks: count(WebHook),
}
- .merge(services_usage)
- .merge(approximate_counts)
+ .merge(services_usage)
+ .merge(approximate_counts),
}.tap do |data|
if Feature.enabled?(:group_overview_security_dashboard)
data[:counts][:user_preferences] = user_preferences_usage
@@ -118,21 +118,21 @@ module Gitlab
mattermost_enabled: Gitlab.config.mattermost.enabled,
omniauth_enabled: Gitlab::Auth.omniauth_enabled?,
reply_by_email_enabled: Gitlab::IncomingEmail.enabled?,
- signup_enabled: Gitlab::CurrentSettings.allow_signup?
+ signup_enabled: Gitlab::CurrentSettings.allow_signup?,
}
end
def usage_counters
{
- web_ide_commits: Gitlab::WebIdeCommitsCounter.total_count
+ web_ide_commits: Gitlab::WebIdeCommitsCounter.total_count,
}
end
def components_usage_data
{
- gitlab_pages: { enabled: Gitlab.config.pages.enabled, version: Gitlab::Pages::VERSION },
- git: { version: Gitlab::Git.version },
- database: { adapter: Gitlab::Database.adapter_name, version: Gitlab::Database.version }
+ gitlab_pages: {enabled: Gitlab.config.pages.enabled, version: Gitlab::Pages::VERSION},
+ git: {version: Gitlab::Git.version},
+ database: {adapter: Gitlab::Database.adapter_name, version: Gitlab::Database.version},
}
end
@@ -141,7 +141,7 @@ module Gitlab
types = {
SlackService: :projects_slack_notifications_active,
SlackSlashCommandsService: :projects_slack_slash_active,
- PrometheusService: :projects_prometheus_active
+ PrometheusService: :projects_prometheus_active,
}
results = count(Service.unscoped.where(type: types.keys, active: true).group(:type), fallback: Hash.new(-1))
@@ -159,9 +159,9 @@ module Gitlab
)
{
- projects_jira_server_active: services['server'] || 0,
- projects_jira_cloud_active: services['cloud'] || 0,
- projects_jira_active: services['server'] == -1 ? -1 : services.values.sum
+ projects_jira_server_active: services["server"] || 0,
+ projects_jira_cloud_active: services["cloud"] || 0,
+ projects_jira_active: services["server"] == -1 ? -1 : services.values.sum,
}
end
diff --git a/lib/gitlab/user_access.rb b/lib/gitlab/user_access.rb
index 980a8014409..432ed725af1 100644
--- a/lib/gitlab/user_access.rb
+++ b/lib/gitlab/user_access.rb
@@ -20,9 +20,9 @@ module Gitlab
return false unless can_access_git?
permission_cache[action] =
- permission_cache.fetch(action) do
+ permission_cache.fetch(action) {
user.can?(action, project)
- end
+ }
end
def cannot_do_action?(action)
@@ -99,7 +99,7 @@ module Gitlab
end
def can_access_git?
- user && user.can?(:access_git)
+ user&.can?(:access_git)
end
def protected_branch_accessible_to?(ref, action:)
@@ -107,7 +107,8 @@ module Gitlab
ref, user,
project: project,
action: action,
- protected_refs: project.protected_branches)
+ protected_refs: project.protected_branches
+ )
end
def protected_tag_accessible_to?(ref, action:)
@@ -115,7 +116,8 @@ module Gitlab
ref, user,
project: project,
action: action,
- protected_refs: project.protected_tags)
+ protected_refs: project.protected_tags
+ )
end
request_cache def protected?(kind, project, ref)
diff --git a/lib/gitlab/user_extractor.rb b/lib/gitlab/user_extractor.rb
index 874599688bb..2a2da6c6434 100644
--- a/lib/gitlab/user_extractor.rb
+++ b/lib/gitlab/user_extractor.rb
@@ -35,7 +35,7 @@ module Gitlab
def matches
@matches ||= {
emails: @text.scan(EMAIL_REGEXP).flatten.uniq,
- usernames: @text.scan(USERNAME_REGEXP).flatten.uniq
+ usernames: @text.scan(USERNAME_REGEXP).flatten.uniq,
}
end
diff --git a/lib/gitlab/utils.rb b/lib/gitlab/utils.rb
index 99fa65e0e90..327a5c5c115 100644
--- a/lib/gitlab/utils.rb
+++ b/lib/gitlab/utils.rb
@@ -7,8 +7,8 @@ module Gitlab
# Ensure that the relative path will not traverse outside the base directory
def check_path_traversal!(path)
raise StandardError.new("Invalid path") if path.start_with?("..#{File::SEPARATOR}") ||
- path.include?("#{File::SEPARATOR}..#{File::SEPARATOR}") ||
- path.end_with?("#{File::SEPARATOR}..")
+ path.include?("#{File::SEPARATOR}..#{File::SEPARATOR}") ||
+ path.end_with?("#{File::SEPARATOR}..")
path
end
@@ -26,23 +26,23 @@ module Gitlab
end
def ensure_utf8_size(str, bytes:)
- raise ArgumentError, 'Empty string provided!' if str.empty?
- raise ArgumentError, 'Negative string size provided!' if bytes.negative?
+ raise ArgumentError, "Empty string provided!" if str.empty?
+ raise ArgumentError, "Negative string size provided!" if bytes.negative?
- truncated = str.each_char.each_with_object(+'') do |char, object|
+ truncated = str.each_char.each_with_object(+"") { |char, object|
if object.bytesize + char.bytesize > bytes
break object
else
object.concat(char)
end
- end
+ }
- truncated + ('0' * (bytes - truncated.bytesize))
+ truncated + ("0" * (bytes - truncated.bytesize))
end
# Append path to host, making sure there's one single / in between
def append_path(host, path)
- "#{host.to_s.sub(%r{\/+$}, '')}/#{path.to_s.sub(%r{^\/+}, '')}"
+ "#{host.to_s.sub(%r{\/+$}, "")}/#{path.to_s.sub(%r{^\/+}, "")}"
end
# A slugified version of the string, suitable for inclusion in URLs and
@@ -53,18 +53,18 @@ module Gitlab
# * Maximum length is 63 bytes
# * First/Last Character is not a hyphen
def slugify(str)
- return str.downcase
- .gsub(/[^a-z0-9]/, '-')[0..62]
- .gsub(/(\A-+|-+\z)/, '')
+ str.downcase
+ .gsub(/[^a-z0-9]/, "-")[0..62]
+ .gsub(/(\A-+|-+\z)/, "")
end
# Converts newlines into HTML line break elements
def nlbr(str)
- ActionView::Base.full_sanitizer.sanitize(+str, tags: []).gsub(/\r?\n/, '<br>').html_safe
+ ActionView::Base.full_sanitizer.sanitize(+str, tags: []).gsub(/\r?\n/, "<br>").html_safe
end
def remove_line_breaks(str)
- str.gsub(/\r?\n/, '')
+ str.gsub(/\r?\n/, "")
end
def to_boolean(value)
@@ -77,9 +77,9 @@ module Gitlab
def boolean_to_yes_no(bool)
if bool
- 'Yes'
+ "Yes"
else
- 'No'
+ "No"
end
end
@@ -92,9 +92,9 @@ module Gitlab
#
# which('ruby') #=> /usr/bin/ruby
def which(cmd, env = ENV)
- exts = env['PATHEXT'] ? env['PATHEXT'].split(';') : ['']
+ exts = env["PATHEXT"] ? env["PATHEXT"].split(";") : [""]
- env['PATH'].split(File::PATH_SEPARATOR).each do |path|
+ env["PATH"].split(File::PATH_SEPARATOR).each do |path|
exts.each do |ext|
exe = File.join(path, "#{cmd}#{ext}")
return exe if File.executable?(exe) && !File.directory?(exe)
@@ -113,7 +113,7 @@ module Gitlab
def ensure_array_from_string(string_or_array)
return string_or_array if string_or_array.is_a?(Array)
- string_or_array.split(',').map(&:strip)
+ string_or_array.split(",").map(&:strip)
end
def deep_indifferent_access(data)
diff --git a/lib/gitlab/utils/merge_hash.rb b/lib/gitlab/utils/merge_hash.rb
index 48ba13b8561..612f800830d 100644
--- a/lib/gitlab/utils/merge_hash.rb
+++ b/lib/gitlab/utils/merge_hash.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_dependency 'gitlab/utils'
+require_dependency "gitlab/utils"
module Gitlab
module Utils
diff --git a/lib/gitlab/utils/override.rb b/lib/gitlab/utils/override.rb
index f5299439fce..18a65b2e409 100644
--- a/lib/gitlab/utils/override.rb
+++ b/lib/gitlab/utils/override.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_dependency 'gitlab/utils'
+require_dependency "gitlab/utils"
module Gitlab
module Utils
@@ -10,7 +10,8 @@ module Gitlab
extension = new(klass)
parents = extension.parents_for(klass)
extension.verify_method!(
- klass: klass, parents: parents, method_name: method_name, sub_method_arity: arity)
+ klass: klass, parents: parents, method_name: method_name, sub_method_arity: arity
+ )
end
attr_reader :subject
@@ -33,15 +34,16 @@ module Gitlab
klass: klass,
parents: parents,
method_name: method_name,
- sub_method_arity: arity)
+ sub_method_arity: arity
+ )
end
end
end
def verify_method!(klass:, parents:, method_name:, sub_method_arity:)
- overridden_parent = parents.find do |parent|
+ overridden_parent = parents.find { |parent|
instance_method_defined?(parent, method_name)
- end
+ }
raise NotImplementedError.new("#{klass}\##{method_name} doesn't exist!") unless overridden_parent
@@ -61,7 +63,7 @@ module Gitlab
end
def verify_override?(method_name)
- method_names.has_key?(method_name)
+ method_names.key?(method_name)
end
private
@@ -117,7 +119,7 @@ module Gitlab
# This would make sure we're overriding something. See:
# https://gitlab.com/gitlab-org/gitlab-ee/issues/1819
def override(method_name)
- return unless ENV['STATIC_VERIFICATION']
+ return unless ENV["STATIC_VERIFICATION"]
Override.extensions[self] ||= Extension.new(self)
Override.extensions[self].add_method_name(method_name)
@@ -126,7 +128,7 @@ module Gitlab
def method_added(method_name)
super
- return unless ENV['STATIC_VERIFICATION']
+ return unless ENV["STATIC_VERIFICATION"]
return unless Override.extensions[self]&.verify_override?(method_name)
method_arity = instance_method(method_name).arity
@@ -156,7 +158,7 @@ module Gitlab
end
def queue_verification(base)
- return unless ENV['STATIC_VERIFICATION']
+ return unless ENV["STATIC_VERIFICATION"]
if base.is_a?(Class) # We could check for Class in `override`
# This could be `nil` if `override` was never called
diff --git a/lib/gitlab/utils/strong_memoize.rb b/lib/gitlab/utils/strong_memoize.rb
index 3021a91dd83..b575a98320a 100644
--- a/lib/gitlab/utils/strong_memoize.rb
+++ b/lib/gitlab/utils/strong_memoize.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_dependency 'gitlab/utils'
+require_dependency "gitlab/utils"
module Gitlab
module Utils
diff --git a/lib/gitlab/verify/batch_verifier.rb b/lib/gitlab/verify/batch_verifier.rb
index dbda19a4a66..6f8b8afd0cf 100644
--- a/lib/gitlab/verify/batch_verifier.rb
+++ b/lib/gitlab/verify/batch_verifier.rb
@@ -47,15 +47,15 @@ module Gitlab
expected = expected_checksum(object)
actual = actual_checksum(object)
- return failure(object, 'Checksum missing') unless expected.present?
- return failure(object, 'Checksum mismatch') unless expected == actual
+ return failure(object, "Checksum missing") unless expected.present?
+ return failure(object, "Checksum mismatch") unless expected == actual
success
end
# We don't calculate checksum for remote objects, so just check existence
def verify_remote(object)
- return failure(object, 'Remote object does not exist') unless remote_object_exists?(object)
+ return failure(object, "Remote object does not exist") unless remote_object_exists?(object)
success
end
@@ -71,7 +71,7 @@ module Gitlab
# It's already set to Logger::INFO, but acts as if it is set to
# Logger::DEBUG, and this fixes it...
def fix_google_api_logger
- if Object.const_defined?('Google::Apis')
+ if Object.const_defined?("Google::Apis")
Google::Apis.logger.level = Logger::INFO
end
end
diff --git a/lib/gitlab/verify/job_artifacts.rb b/lib/gitlab/verify/job_artifacts.rb
index 3b90c8b1a8e..603b1ede8ee 100644
--- a/lib/gitlab/verify/job_artifacts.rb
+++ b/lib/gitlab/verify/job_artifacts.rb
@@ -4,7 +4,7 @@ module Gitlab
module Verify
class JobArtifacts < BatchVerifier
def name
- 'Job artifacts'
+ "Job artifacts"
end
def describe(object)
diff --git a/lib/gitlab/verify/lfs_objects.rb b/lib/gitlab/verify/lfs_objects.rb
index 20dbb7addff..f2dc359f49b 100644
--- a/lib/gitlab/verify/lfs_objects.rb
+++ b/lib/gitlab/verify/lfs_objects.rb
@@ -4,7 +4,7 @@ module Gitlab
module Verify
class LfsObjects < BatchVerifier
def name
- 'LFS objects'
+ "LFS objects"
end
def describe(object)
diff --git a/lib/gitlab/verify/rake_task.rb b/lib/gitlab/verify/rake_task.rb
index 3efed311237..0e908684b16 100644
--- a/lib/gitlab/verify/rake_task.rb
+++ b/lib/gitlab/verify/rake_task.rb
@@ -5,12 +5,12 @@ module Gitlab
class RakeTask
def self.run!(verify_kls)
verifier = verify_kls.new(
- batch_size: ENV.fetch('BATCH', 200).to_i,
- start: ENV['ID_FROM'],
- finish: ENV['ID_TO']
+ batch_size: ENV.fetch("BATCH", 200).to_i,
+ start: ENV["ID_FROM"],
+ finish: ENV["ID_TO"]
)
- verbose = Gitlab::Utils.to_boolean(ENV['VERBOSE'])
+ verbose = Gitlab::Utils.to_boolean(ENV["VERBOSE"])
new(verifier, verbose).run!
end
@@ -27,7 +27,7 @@ module Gitlab
verifier.run_batches { |*args| run_batch(*args) }
- say 'Done!'
+ say "Done!"
end
def verbose?
diff --git a/lib/gitlab/verify/uploads.rb b/lib/gitlab/verify/uploads.rb
index 875e8a120e9..50ddb7dbb85 100644
--- a/lib/gitlab/verify/uploads.rb
+++ b/lib/gitlab/verify/uploads.rb
@@ -4,7 +4,7 @@ module Gitlab
module Verify
class Uploads < BatchVerifier
def name
- 'Uploads'
+ "Uploads"
end
def describe(object)
diff --git a/lib/gitlab/visibility_level.rb b/lib/gitlab/visibility_level.rb
index a3c7de87765..a0e05d2f1f8 100644
--- a/lib/gitlab/visibility_level.rb
+++ b/lib/gitlab/visibility_level.rb
@@ -11,10 +11,10 @@ module Gitlab
included do
scope :public_only, -> { where(visibility_level: PUBLIC) }
- scope :public_and_internal_only, -> { where(visibility_level: [PUBLIC, INTERNAL] ) }
+ scope :public_and_internal_only, -> { where(visibility_level: [PUBLIC, INTERNAL]) }
scope :non_public_only, -> { where.not(visibility_level: PUBLIC) }
- scope :public_to_user, -> (user = nil) do
+ scope :public_to_user, ->(user = nil) do
where(visibility_level: VisibilityLevel.levels_for_user(user))
end
end
@@ -44,24 +44,24 @@ module Gitlab
def options
{
- N_('VisibilityLevel|Private') => PRIVATE,
- N_('VisibilityLevel|Internal') => INTERNAL,
- N_('VisibilityLevel|Public') => PUBLIC
+ N_("VisibilityLevel|Private") => PRIVATE,
+ N_("VisibilityLevel|Internal") => INTERNAL,
+ N_("VisibilityLevel|Public") => PUBLIC,
}
end
def string_options
{
- 'private' => PRIVATE,
- 'internal' => INTERNAL,
- 'public' => PUBLIC
+ "private" => PRIVATE,
+ "internal" => INTERNAL,
+ "public" => PUBLIC,
}
end
def allowed_levels
restricted_levels = Gitlab::CurrentSettings.restricted_visibility_levels
- self.values - Array(restricted_levels)
+ values - Array(restricted_levels)
end
def closest_allowed_level(target_level)
@@ -96,7 +96,7 @@ module Gitlab
end
def level_name(level)
- level_name = N_('VisibilityLevel|Unknown')
+ level_name = N_("VisibilityLevel|Unknown")
options.each do |name, lvl|
level_name = name if lvl == level.to_i
end
diff --git a/lib/gitlab/web_ide_commits_counter.rb b/lib/gitlab/web_ide_commits_counter.rb
index 1cd9b5295b9..3d016210a11 100644
--- a/lib/gitlab/web_ide_commits_counter.rb
+++ b/lib/gitlab/web_ide_commits_counter.rb
@@ -2,7 +2,7 @@
module Gitlab
module WebIdeCommitsCounter
- WEB_IDE_COMMITS_KEY = "WEB_IDE_COMMITS_COUNT".freeze
+ WEB_IDE_COMMITS_KEY = "WEB_IDE_COMMITS_COUNT"
class << self
def increment
diff --git a/lib/gitlab/webpack/dev_server_middleware.rb b/lib/gitlab/webpack/dev_server_middleware.rb
index fda41da5a94..55d175bd6f9 100644
--- a/lib/gitlab/webpack/dev_server_middleware.rb
+++ b/lib/gitlab/webpack/dev_server_middleware.rb
@@ -8,7 +8,7 @@ module Gitlab
module Webpack
class DevServerMiddleware < Rack::Proxy
def initialize(app = nil, opts = {})
- @proxy_host = opts.fetch(:proxy_host, 'localhost')
+ @proxy_host = opts.fetch(:proxy_host, "localhost")
@proxy_port = opts.fetch(:proxy_port, 3808)
@proxy_path = opts[:proxy_path] if opts[:proxy_path]
@@ -16,10 +16,10 @@ module Gitlab
end
def perform_request(env)
- if @proxy_path && env['PATH_INFO'].start_with?("/#{@proxy_path}")
+ if @proxy_path && env["PATH_INFO"].start_with?("/#{@proxy_path}")
if relative_url_root = Rails.application.config.relative_url_root
- env['SCRIPT_NAME'] = ""
- env['REQUEST_PATH'].sub!(/\A#{Regexp.escape(relative_url_root)}/, '')
+ env["SCRIPT_NAME"] = ""
+ env["REQUEST_PATH"].sub!(/\A#{Regexp.escape(relative_url_root)}/, "")
end
super(env)
diff --git a/lib/gitlab/webpack/manifest.rb b/lib/gitlab/webpack/manifest.rb
index 1d2aff5e5b4..dfd1e251531 100644
--- a/lib/gitlab/webpack/manifest.rb
+++ b/lib/gitlab/webpack/manifest.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'webpack/rails/manifest'
+require "webpack/rails/manifest"
module Gitlab
module Webpack
diff --git a/lib/gitlab/wiki_file_finder.rb b/lib/gitlab/wiki_file_finder.rb
index e9be6db50da..7c0c0b50913 100644
--- a/lib/gitlab/wiki_file_finder.rb
+++ b/lib/gitlab/wiki_file_finder.rb
@@ -13,7 +13,7 @@ module Gitlab
private
def search_filenames(query)
- safe_query = Regexp.escape(query.tr(' ', '-'))
+ safe_query = Regexp.escape(query.tr(" ", "-"))
safe_query = Regexp.new(safe_query, Regexp::IGNORECASE)
filenames = repository.ls_files(ref)
diff --git a/lib/gitlab/workhorse.rb b/lib/gitlab/workhorse.rb
index 265f6213a99..2e5b9ae0589 100644
--- a/lib/gitlab/workhorse.rb
+++ b/lib/gitlab/workhorse.rb
@@ -1,19 +1,19 @@
# frozen_string_literal: true
-require 'base64'
-require 'json'
-require 'securerandom'
-require 'uri'
+require "base64"
+require "json"
+require "securerandom"
+require "uri"
module Gitlab
class Workhorse
- SEND_DATA_HEADER = 'Gitlab-Workhorse-Send-Data'.freeze
- VERSION_FILE = 'GITLAB_WORKHORSE_VERSION'.freeze
- INTERNAL_API_CONTENT_TYPE = 'application/vnd.gitlab-workhorse+json'.freeze
- INTERNAL_API_REQUEST_HEADER = 'Gitlab-Workhorse-Api-Request'.freeze
- NOTIFICATION_CHANNEL = 'workhorse:notifications'.freeze
+ SEND_DATA_HEADER = "Gitlab-Workhorse-Send-Data"
+ VERSION_FILE = "GITLAB_WORKHORSE_VERSION"
+ INTERNAL_API_CONTENT_TYPE = "application/vnd.gitlab-workhorse+json"
+ INTERNAL_API_REQUEST_HEADER = "Gitlab-Workhorse-Api-Request"
+ NOTIFICATION_CHANNEL = "workhorse:notifications"
ALLOWED_GIT_HTTP_ACTIONS = %w[git_receive_pack git_upload_pack info_refs].freeze
- DETECT_HEADER = 'Gitlab-Workhorse-Detect-Content-Type'.freeze
+ DETECT_HEADER = "Gitlab-Workhorse-Detect-Content-Type"
# Supposedly the effective key size for HMAC-SHA256 is 256 bits, i.e. 32
# bytes https://tools.ietf.org/html/rfc4868#section-2.6
@@ -34,8 +34,8 @@ module Gitlab
GitConfigOptions: [],
GitalyServer: {
address: Gitlab::GitalyClient.address(project.repository_storage),
- token: Gitlab::GitalyClient.token(project.repository_storage)
- }
+ token: Gitlab::GitalyClient.token(project.repository_storage),
+ },
}
# Custom option for git-receive-pack command
@@ -49,76 +49,76 @@ module Gitlab
def send_git_blob(repository, blob)
params = {
- 'GitalyServer' => gitaly_server_hash(repository),
- 'GetBlobRequest' => {
+ "GitalyServer" => gitaly_server_hash(repository),
+ "GetBlobRequest" => {
repository: repository.gitaly_repository.to_h,
oid: blob.id,
- limit: -1
- }
+ limit: -1,
+ },
}
[
SEND_DATA_HEADER,
- "git-blob:#{encode(params)}"
+ "git-blob:#{encode(params)}",
]
end
def send_git_archive(repository, ref:, format:, append_sha:)
- format ||= 'tar.gz'
+ format ||= "tar.gz"
format = format.downcase
params = repository.archive_metadata(ref, Gitlab.config.gitlab.repository_downloads_path, format, append_sha: append_sha)
raise "Repository or ref not found" if params.empty?
- params['GitalyServer'] = gitaly_server_hash(repository)
+ params["GitalyServer"] = gitaly_server_hash(repository)
# If present DisableCache must be a Boolean. Otherwise workhorse ignores it.
- params['DisableCache'] = true if git_archive_cache_disabled?
+ params["DisableCache"] = true if git_archive_cache_disabled?
[
SEND_DATA_HEADER,
- "git-archive:#{encode(params)}"
+ "git-archive:#{encode(params)}",
]
end
def send_git_snapshot(repository)
params = {
- 'GitalyServer' => gitaly_server_hash(repository),
- 'GetSnapshotRequest' => Gitaly::GetSnapshotRequest.new(
+ "GitalyServer" => gitaly_server_hash(repository),
+ "GetSnapshotRequest" => Gitaly::GetSnapshotRequest.new(
repository: repository.gitaly_repository
- ).to_json
+ ).to_json,
}
[
SEND_DATA_HEADER,
- "git-snapshot:#{encode(params)}"
+ "git-snapshot:#{encode(params)}",
]
end
def send_git_diff(repository, diff_refs)
params = {
- 'GitalyServer' => gitaly_server_hash(repository),
- 'RawDiffRequest' => Gitaly::RawDiffRequest.new(
+ "GitalyServer" => gitaly_server_hash(repository),
+ "RawDiffRequest" => Gitaly::RawDiffRequest.new(
gitaly_diff_or_patch_hash(repository, diff_refs)
- ).to_json
+ ).to_json,
}
[
SEND_DATA_HEADER,
- "git-diff:#{encode(params)}"
+ "git-diff:#{encode(params)}",
]
end
def send_git_patch(repository, diff_refs)
params = {
- 'GitalyServer' => gitaly_server_hash(repository),
- 'RawPatchRequest' => Gitaly::RawPatchRequest.new(
+ "GitalyServer" => gitaly_server_hash(repository),
+ "RawPatchRequest" => Gitaly::RawPatchRequest.new(
gitaly_diff_or_patch_hash(repository, diff_refs)
- ).to_json
+ ).to_json,
}
[
SEND_DATA_HEADER,
- "git-format-patch:#{encode(params)}"
+ "git-format-patch:#{encode(params)}",
]
end
@@ -127,45 +127,45 @@ module Gitlab
archive = file.file_storage? ? file.path : file.url
params = {
- 'Archive' => archive,
- 'Entry' => Base64.encode64(entry.to_s)
+ "Archive" => archive,
+ "Entry" => Base64.encode64(entry.to_s),
}
[
SEND_DATA_HEADER,
- "artifacts-entry:#{encode(params)}"
+ "artifacts-entry:#{encode(params)}",
]
end
def send_url(url, allow_redirects: false)
params = {
- 'URL' => url,
- 'AllowRedirects' => allow_redirects
+ "URL" => url,
+ "AllowRedirects" => allow_redirects,
}
[
SEND_DATA_HEADER,
- "send-url:#{encode(params)}"
+ "send-url:#{encode(params)}",
]
end
def terminal_websocket(terminal)
details = {
- 'Terminal' => {
- 'Subprotocols' => terminal[:subprotocols],
- 'Url' => terminal[:url],
- 'Header' => terminal[:headers],
- 'MaxSessionTime' => terminal[:max_session_time]
- }
+ "Terminal" => {
+ "Subprotocols" => terminal[:subprotocols],
+ "Url" => terminal[:url],
+ "Header" => terminal[:headers],
+ "MaxSessionTime" => terminal[:max_session_time],
+ },
}
- details['Terminal']['CAPem'] = terminal[:ca_pem] if terminal.key?(:ca_pem)
+ details["Terminal"]["CAPem"] = terminal[:ca_pem] if terminal.key?(:ca_pem)
details
end
def version
path = Rails.root.join(VERSION_FILE)
- path.readable? ? path.read.chomp : 'unknown'
+ path.readable? ? path.read.chomp : "unknown"
end
def secret
@@ -179,8 +179,8 @@ module Gitlab
def write_secret
bytes = SecureRandom.random_bytes(SECRET_LENGTH)
- File.open(secret_path, 'w:BINARY', 0600) do |f|
- f.chmod(0600) # If the file already existed, the '0600' passed to 'open' above was a no-op.
+ File.open(secret_path, "w:BINARY", 0o600) do |f|
+ f.chmod(0o600) # If the file already existed, the '0600' passed to 'open' above was a no-op.
f.write(Base64.strict_encode64(bytes))
end
end
@@ -194,7 +194,7 @@ module Gitlab
encoded_message,
secret,
true,
- { iss: 'gitlab-workhorse', verify_iss: true, algorithm: 'HS256' }
+ {iss: "gitlab-workhorse", verify_iss: true, algorithm: "HS256"}
)
end
@@ -223,7 +223,7 @@ module Gitlab
def gitaly_server_hash(repository)
{
address: Gitlab::GitalyClient.address(repository.project.repository_storage),
- token: Gitlab::GitalyClient.token(repository.project.repository_storage)
+ token: Gitlab::GitalyClient.token(repository.project.repository_storage),
}
end
@@ -231,12 +231,12 @@ module Gitlab
{
repository: repository.gitaly_repository,
left_commit_id: diff_refs.base_sha,
- right_commit_id: diff_refs.head_sha
+ right_commit_id: diff_refs.head_sha,
}
end
def git_archive_cache_disabled?
- ENV['WORKHORSE_ARCHIVE_CACHE_DISABLED'].present? || Feature.enabled?(:workhorse_archive_cache_disabled)
+ ENV["WORKHORSE_ARCHIVE_CACHE_DISABLED"].present? || Feature.enabled?(:workhorse_archive_cache_disabled)
end
end
end
diff --git a/lib/google_api/auth.rb b/lib/google_api/auth.rb
index 56f056fd869..36b60ce19ca 100644
--- a/lib/google_api/auth.rb
+++ b/lib/google_api/auth.rb
@@ -22,7 +22,7 @@ module GoogleApi
def get_token(code)
ret = client.auth_code.get_token(code, redirect_uri: redirect_uri)
- return ret.token, ret.expires_at
+ [ret.token, ret.expires_at]
end
protected
@@ -34,7 +34,7 @@ module GoogleApi
private
def config
- Gitlab::Auth::OAuth::Provider.config_for('google_oauth2')
+ Gitlab::Auth::OAuth::Provider.config_for("google_oauth2")
end
def client
@@ -47,9 +47,9 @@ module GoogleApi
@client = ::OAuth2::Client.new(
config.app_id,
config.app_secret,
- site: 'https://accounts.google.com',
- token_url: '/o/oauth2/token',
- authorize_url: '/o/oauth2/auth'
+ site: "https://accounts.google.com",
+ token_url: "/o/oauth2/token",
+ authorize_url: "/o/oauth2/auth"
)
end
end
diff --git a/lib/google_api/cloud_platform/client.rb b/lib/google_api/cloud_platform/client.rb
index e74ff6a9129..6be1ecb60c4 100644
--- a/lib/google_api/cloud_platform/client.rb
+++ b/lib/google_api/cloud_platform/client.rb
@@ -1,14 +1,14 @@
# frozen_string_literal: true
-require 'google/apis/compute_v1'
-require 'google/apis/container_v1'
-require 'google/apis/cloudbilling_v1'
-require 'google/apis/cloudresourcemanager_v1'
+require "google/apis/compute_v1"
+require "google/apis/container_v1"
+require "google/apis/cloudbilling_v1"
+require "google/apis/cloudresourcemanager_v1"
module GoogleApi
module CloudPlatform
class Client < GoogleApi::Auth
- SCOPE = 'https://www.googleapis.com/auth/cloud-platform'.freeze
+ SCOPE = "https://www.googleapis.com/auth/cloud-platform"
LEAST_TOKEN_LIFE_TIME = 10.minutes
class << self
@@ -62,12 +62,12 @@ module GoogleApi
"name": cluster_name,
"initial_node_count": cluster_size,
"node_config": {
- "machine_type": machine_type
+ "machine_type": machine_type,
},
"legacy_abac": {
- "enabled": legacy_abac
- }
- }
+ "enabled": legacy_abac,
+ },
+ },
}
)
@@ -89,12 +89,12 @@ module GoogleApi
private
def token_life_time(expires_at)
- DateTime.strptime(expires_at, '%s').to_time.utc - Time.now.utc
+ DateTime.strptime(expires_at, "%s").to_time.utc - Time.now.utc
end
def user_agent_header
Google::Apis::RequestOptions.new.tap do |options|
- options.header = { 'User-Agent': "GitLab/#{Gitlab::VERSION.match('(\d+\.\d+)').captures.first} (GPN:GitLab;)" }
+ options.header = {'User-Agent': "GitLab/#{Gitlab::VERSION.match('(\d+\.\d+)').captures.first} (GPN:GitLab;)"}
end
end
end
diff --git a/lib/haml_lint/inline_javascript.rb b/lib/haml_lint/inline_javascript.rb
index 2e98227a05e..92c69a798bd 100644
--- a/lib/haml_lint/inline_javascript.rb
+++ b/lib/haml_lint/inline_javascript.rb
@@ -2,24 +2,24 @@
# frozen_string_literal: true
unless Rails.env.production?
- require_dependency 'haml_lint/haml_visitor'
- require_dependency 'haml_lint/linter'
- require_dependency 'haml_lint/linter_registry'
+ require_dependency "haml_lint/haml_visitor"
+ require_dependency "haml_lint/linter"
+ require_dependency "haml_lint/linter_registry"
module HamlLint
class Linter::InlineJavaScript < Linter
include LinterRegistry
def visit_filter(node)
- return unless node.filter_type == 'javascript'
+ return unless node.filter_type == "javascript"
- record_lint(node, 'Inline JavaScript is discouraged (https://docs.gitlab.com/ee/development/gotchas.html#do-not-use-inline-javascript-in-views)')
+ record_lint(node, "Inline JavaScript is discouraged (https://docs.gitlab.com/ee/development/gotchas.html#do-not-use-inline-javascript-in-views)")
end
def visit_tag(node)
- return unless node.tag_name == 'script'
+ return unless node.tag_name == "script"
- record_lint(node, 'Inline JavaScript is discouraged (https://docs.gitlab.com/ee/development/gotchas.html#do-not-use-inline-javascript-in-views)')
+ record_lint(node, "Inline JavaScript is discouraged (https://docs.gitlab.com/ee/development/gotchas.html#do-not-use-inline-javascript-in-views)")
end
end
end
diff --git a/lib/json_web_token/hmac_token.rb b/lib/json_web_token/hmac_token.rb
index ec0917ab49d..2275c0e3a1d 100644
--- a/lib/json_web_token/hmac_token.rb
+++ b/lib/json_web_token/hmac_token.rb
@@ -1,11 +1,11 @@
# frozen_string_literal: true
-require 'jwt'
+require "jwt"
module JSONWebToken
class HMACToken < Token
IAT_LEEWAY = 60
- JWT_ALGORITHM = 'HS256'
+ JWT_ALGORITHM = "HS256"
def initialize(secret)
super()
@@ -18,7 +18,7 @@ module JSONWebToken
end
def encoded
- JWT.encode(payload, secret, JWT_ALGORITHM, { typ: 'JWT' })
+ JWT.encode(payload, secret, JWT_ALGORITHM, {typ: "JWT"})
end
private
diff --git a/lib/json_web_token/rsa_token.rb b/lib/json_web_token/rsa_token.rb
index bcce811cd28..021d5b7258a 100644
--- a/lib/json_web_token/rsa_token.rb
+++ b/lib/json_web_token/rsa_token.rb
@@ -12,9 +12,9 @@ module JSONWebToken
def encoded
headers = {
kid: kid,
- typ: 'JWT'
+ typ: "JWT",
}
- JWT.encode(payload, key, 'RS256', headers)
+ JWT.encode(payload, key, "RS256", headers)
end
private
@@ -39,7 +39,7 @@ module JSONWebToken
kid = Base32.encode(kid[0..29])
# insert colon every 4 characters
- kid.scan(/.{4}/).join(':')
+ kid.scan(/.{4}/).join(":")
end
end
end
diff --git a/lib/json_web_token/token.rb b/lib/json_web_token/token.rb
index c59beef02c9..f69a86ef5cc 100644
--- a/lib/json_web_token/token.rb
+++ b/lib/json_web_token/token.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require 'securerandom'
+require "securerandom"
module JSONWebToken
class Token
@@ -46,7 +46,7 @@ module JSONWebToken
iss: issuer,
iat: issued_at.to_i,
nbf: not_before.to_i,
- exp: expire_time.to_i
+ exp: expire_time.to_i,
}.compact
end
end
diff --git a/lib/mattermost/client.rb b/lib/mattermost/client.rb
index 293d0c563c5..e6f633f81be 100644
--- a/lib/mattermost/client.rb
+++ b/lib/mattermost/client.rb
@@ -52,12 +52,12 @@ module Mattermost
json_response = JSON.parse(response.body)
unless response.success?
- raise Mattermost::ClientError.new(json_response['message'] || 'Undefined error')
+ raise Mattermost::ClientError.new(json_response["message"] || "Undefined error")
end
json_response
rescue JSON::JSONError
- raise Mattermost::ClientError.new('Cannot parse response')
+ raise Mattermost::ClientError.new("Cannot parse response")
end
end
end
diff --git a/lib/mattermost/command.rb b/lib/mattermost/command.rb
index a02745486d6..866338d07f3 100644
--- a/lib/mattermost/command.rb
+++ b/lib/mattermost/command.rb
@@ -3,10 +3,10 @@
module Mattermost
class Command < Client
def create(params)
- response = session_post('/api/v4/commands',
+ response = session_post("/api/v4/commands",
body: params.to_json)
- response['token']
+ response["token"]
end
end
end
diff --git a/lib/mattermost/session.rb b/lib/mattermost/session.rb
index e2083848a8d..7096e41fcbd 100644
--- a/lib/mattermost/session.rb
+++ b/lib/mattermost/session.rb
@@ -3,7 +3,7 @@
module Mattermost
class NoSessionError < Mattermost::Error
def message
- 'No session could be set up, is Mattermost configured with Single Sign On?'
+ "No session could be set up, is Mattermost configured with Single Sign On?"
end
end
@@ -52,7 +52,8 @@ module Mattermost
# Next methods are needed for Doorkeeper
def pre_auth
@pre_auth ||= Doorkeeper::OAuth::PreAuthorization.new(
- Doorkeeper.configuration, server.client_via_uid, params)
+ Doorkeeper.configuration, server.client_via_uid, params
+ )
end
def authorization
@@ -107,14 +108,14 @@ module Mattermost
raise Mattermost::NoSessionError unless @token
@headers = {
- Authorization: "Bearer #{@token}"
+ Authorization: "Bearer #{@token}",
}
@token
end
def destroy
- post('/api/v4/users/logout')
+ post("/api/v4/users/logout")
end
def oauth_uri
@@ -122,15 +123,15 @@ module Mattermost
@oauth_uri = nil
- response = get('/oauth/gitlab/login', follow_redirects: false, format: 'text/html')
+ response = get("/oauth/gitlab/login", follow_redirects: false, format: "text/html")
return unless (300...400) === response.code
- redirect_uri = response.headers['location']
+ redirect_uri = response.headers["location"]
return unless redirect_uri
oauth_cookie = parse_cookie(response)
@headers = {
- Cookie: oauth_cookie.to_cookie_string
+ Cookie: oauth_cookie.to_cookie_string,
}
@oauth_uri = URI.parse(redirect_uri)
@@ -147,7 +148,7 @@ module Mattermost
response = get(token_uri, follow_redirects: false)
if (200...400) === response.code
- response.headers['token']
+ response.headers["token"]
end
end
@@ -181,7 +182,7 @@ module Mattermost
def parse_cookie(response)
cookie_hash = Gitlab::HTTP::CookieHash.new
- response.get_fields('Set-Cookie').each { |c| cookie_hash.add_cookies(c) }
+ response.get_fields("Set-Cookie").each { |c| cookie_hash.add_cookies(c) }
cookie_hash
end
end
diff --git a/lib/mattermost/team.rb b/lib/mattermost/team.rb
index 58120178f50..12e6cb65ce4 100644
--- a/lib/mattermost/team.rb
+++ b/lib/mattermost/team.rb
@@ -10,10 +10,10 @@ module Mattermost
# Creates a team on the linked Mattermost instance, the team admin will be the
# `current_user` passed to the Mattermost::Client instance
def create(name:, display_name:, type:)
- session_post('/api/v4/teams', body: {
+ session_post("/api/v4/teams", body: {
name: name,
display_name: display_name,
- type: type
+ type: type,
}.to_json)
end
diff --git a/lib/microsoft_teams/activity.rb b/lib/microsoft_teams/activity.rb
index 207e90d2638..6e70b00446c 100644
--- a/lib/microsoft_teams/activity.rb
+++ b/lib/microsoft_teams/activity.rb
@@ -11,10 +11,10 @@ module MicrosoftTeams
def prepare
{
- 'activityTitle' => @title,
- 'activitySubtitle' => @subtitle,
- 'activityText' => @text,
- 'activityImage' => @image
+ "activityTitle" => @title,
+ "activitySubtitle" => @subtitle,
+ "activityText" => @text,
+ "activityImage" => @image,
}
end
end
diff --git a/lib/microsoft_teams/notifier.rb b/lib/microsoft_teams/notifier.rb
index c7dec09ba6b..e2e14f70274 100644
--- a/lib/microsoft_teams/notifier.rb
+++ b/lib/microsoft_teams/notifier.rb
@@ -4,7 +4,7 @@ module MicrosoftTeams
class Notifier
def initialize(webhook)
@webhook = webhook
- @header = { 'Content-type' => 'application/json' }
+ @header = {"Content-type" => "application/json"}
end
def ping(options = {})
@@ -29,17 +29,17 @@ module MicrosoftTeams
private
def body(options = {})
- result = { 'sections' => [] }
+ result = {"sections" => []}
- result['title'] = options[:title]
- result['summary'] = options[:summary]
- result['sections'] << MicrosoftTeams::Activity.new(options[:activity]).prepare
+ result["title"] = options[:title]
+ result["summary"] = options[:summary]
+ result["sections"] << MicrosoftTeams::Activity.new(options[:activity]).prepare
attachments = options[:attachments]
unless attachments.blank?
- result['sections'] << {
- 'title' => 'Details',
- 'facts' => [{ 'name' => 'Attachments', 'value' => attachments }]
+ result["sections"] << {
+ "title" => "Details",
+ "facts" => [{"name" => "Attachments", "value" => attachments}],
}
end
diff --git a/lib/milestone_array.rb b/lib/milestone_array.rb
index 461e73e9670..107abe2913d 100644
--- a/lib/milestone_array.rb
+++ b/lib/milestone_array.rb
@@ -4,18 +4,18 @@ module MilestoneArray
class << self
def sort(array, sort_method)
case sort_method
- when 'due_date_asc'
- sort_asc_nulls_last(array, 'due_date')
- when 'due_date_desc'
- sort_desc_nulls_last(array, 'due_date')
- when 'start_date_asc'
- sort_asc_nulls_last(array, 'start_date')
- when 'start_date_desc'
- sort_desc_nulls_last(array, 'start_date')
- when 'name_asc'
- sort_asc(array, 'title')
- when 'name_desc'
- sort_asc(array, 'title').reverse
+ when "due_date_asc"
+ sort_asc_nulls_last(array, "due_date")
+ when "due_date_desc"
+ sort_desc_nulls_last(array, "due_date")
+ when "start_date_asc"
+ sort_asc_nulls_last(array, "start_date")
+ when "start_date_desc"
+ sort_desc_nulls_last(array, "start_date")
+ when "name_asc"
+ sort_asc(array, "title")
+ when "name_desc"
+ sort_asc(array, "title").reverse
else
array
end
diff --git a/lib/mysql_zero_date.rb b/lib/mysql_zero_date.rb
index f36610abf8f..3be5a7d76b2 100644
--- a/lib/mysql_zero_date.rb
+++ b/lib/mysql_zero_date.rb
@@ -7,7 +7,7 @@
# and NO_ZERO_DATE has to be explicitly disabled. Disabling strict mode
# is not sufficient.
-require 'active_record/connection_adapters/abstract_mysql_adapter'
+require "active_record/connection_adapters/abstract_mysql_adapter"
module MysqlZeroDate
def configure_connection
diff --git a/lib/object_storage/direct_upload.rb b/lib/object_storage/direct_upload.rb
index fd26663fef0..4fe5c4a14b3 100644
--- a/lib/object_storage/direct_upload.rb
+++ b/lib/object_storage/direct_upload.rb
@@ -27,7 +27,7 @@ module ObjectStorage
def initialize(credentials, bucket_name, object_name, has_length:, maximum_size: nil)
unless has_length
- raise ArgumentError, 'maximum_size has to be specified if length is unknown' unless maximum_size
+ raise ArgumentError, "maximum_size has to be specified if length is unknown" unless maximum_size
end
@credentials = credentials
@@ -45,7 +45,7 @@ module ObjectStorage
DeleteURL: delete_url,
MultipartUpload: multipart_upload_hash,
CustomPutHeaders: true,
- PutHeaders: upload_options
+ PutHeaders: upload_options,
}.compact
end
@@ -56,7 +56,7 @@ module ObjectStorage
PartSize: rounded_multipart_part_size,
PartURLs: multipart_part_urls,
CompleteURL: multipart_complete_url,
- AbortURL: multipart_abort_url
+ AbortURL: multipart_abort_url,
}
end
@@ -88,32 +88,32 @@ module ObjectStorage
# Implements https://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPart.html
def multipart_part_upload_url(part_number)
connection.signed_url({
- method: 'PUT',
+ method: "PUT",
bucket_name: bucket_name,
object_name: object_name,
- query: { 'uploadId' => upload_id, 'partNumber' => part_number },
- headers: upload_options
+ query: {"uploadId" => upload_id, "partNumber" => part_number},
+ headers: upload_options,
}, expire_at)
end
# Implements https://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadComplete.html
def multipart_complete_url
connection.signed_url({
- method: 'POST',
+ method: "POST",
bucket_name: bucket_name,
object_name: object_name,
- query: { 'uploadId' => upload_id },
- headers: { 'Content-Type' => 'application/xml' }
+ query: {"uploadId" => upload_id},
+ headers: {"Content-Type" => "application/xml"},
}, expire_at)
end
# Implements https://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadAbort.html
def multipart_abort_url
connection.signed_url({
- method: 'DELETE',
+ method: "DELETE",
bucket_name: bucket_name,
object_name: object_name,
- query: { 'uploadId' => upload_id }
+ query: {"uploadId" => upload_id},
}, expire_at)
end
@@ -132,12 +132,12 @@ module ObjectStorage
[
# round maximum_size up to minimum_mulitpart_size
(maximum_size + MINIMUM_MULTIPART_SIZE - 1) / MINIMUM_MULTIPART_SIZE,
- MAXIMUM_MULTIPART_PARTS
+ MAXIMUM_MULTIPART_PARTS,
].min
end
def aws?
- provider == 'AWS'
+ provider == "AWS"
end
def requires_multipart_upload?
diff --git a/lib/omni_auth/strategies/bitbucket.rb b/lib/omni_auth/strategies/bitbucket.rb
index 6c914b4222a..043b8e58ad1 100644
--- a/lib/omni_auth/strategies/bitbucket.rb
+++ b/lib/omni_auth/strategies/bitbucket.rb
@@ -1,42 +1,42 @@
# frozen_string_literal: true
-require 'omniauth-oauth2'
+require "omniauth-oauth2"
module OmniAuth
module Strategies
class Bitbucket < OmniAuth::Strategies::OAuth2
- option :name, 'bitbucket'
+ option :name, "bitbucket"
option :client_options, {
- site: 'https://bitbucket.org',
- authorize_url: 'https://bitbucket.org/site/oauth2/authorize',
- token_url: 'https://bitbucket.org/site/oauth2/access_token'
+ site: "https://bitbucket.org",
+ authorize_url: "https://bitbucket.org/site/oauth2/authorize",
+ token_url: "https://bitbucket.org/site/oauth2/access_token",
}
uid do
- raw_info['username']
+ raw_info["username"]
end
info do
{
- name: raw_info['display_name'],
- avatar: raw_info['links']['avatar']['href'],
- email: primary_email
+ name: raw_info["display_name"],
+ avatar: raw_info["links"]["avatar"]["href"],
+ email: primary_email,
}
end
def raw_info
- @raw_info ||= access_token.get('api/2.0/user').parsed
+ @raw_info ||= access_token.get("api/2.0/user").parsed
end
def primary_email
- primary = emails.find { |i| i['is_primary'] && i['is_confirmed'] }
- primary && primary['email'] || nil
+ primary = emails.find { |i| i["is_primary"] && i["is_confirmed"] }
+ primary && primary["email"] || nil
end
def emails
- email_response = access_token.get('api/2.0/user/emails').parsed
- @emails ||= email_response && email_response['values'] || nil
+ email_response = access_token.get("api/2.0/user/emails").parsed
+ @emails ||= email_response && email_response["values"] || nil
end
def callback_url
diff --git a/lib/omni_auth/strategies/jwt.rb b/lib/omni_auth/strategies/jwt.rb
index 2f3d477a591..02d0ecd2c63 100644
--- a/lib/omni_auth/strategies/jwt.rb
+++ b/lib/omni_auth/strategies/jwt.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
-require 'omniauth'
-require 'openssl'
-require 'jwt'
+require "omniauth"
+require "openssl"
+require "jwt"
module OmniAuth
module Strategies
@@ -14,17 +14,17 @@ module OmniAuth
args [:secret]
option :secret, nil
- option :algorithm, 'HS256'
- option :uid_claim, 'email'
- option :required_claims, %w(name email)
- option :info_map, { name: "name", email: "email" }
+ option :algorithm, "HS256"
+ option :uid_claim, "email"
+ option :required_claims, %w[name email]
+ option :info_map, {name: "name", email: "email"}
option :auth_url, nil
option :valid_within, nil
uid { decoded[options.uid_claim] }
extra do
- { raw_info: decoded }
+ {raw_info: decoded}
end
info do
@@ -40,17 +40,17 @@ module OmniAuth
def decoded
secret =
case options.algorithm
- when *%w[RS256 RS384 RS512]
+ when "RS256", "RS384", "RS512"
OpenSSL::PKey::RSA.new(options.secret).public_key
- when *%w[ES256 ES384 ES512]
+ when "ES256", "ES384", "ES512"
OpenSSL::PKey::EC.new(options.secret).tap { |key| key.private_key = nil }
- when *%w(HS256 HS384 HS512)
+ when "HS256", "HS384", "HS512"
options.secret
else
raise NotImplementedError, "Unsupported algorithm: #{options.algorithm}"
end
- @decoded ||= ::JWT.decode(request.params['jwt'], secret, true, { algorithm: options.algorithm }).first
+ @decoded ||= ::JWT.decode(request.params["jwt"], secret, true, {algorithm: options.algorithm}).first
(options.required_claims || []).each do |field|
raise ClaimInvalid, "Missing required '#{field}' claim" unless @decoded.key?(field.to_s)
diff --git a/lib/peek/views/gitaly.rb b/lib/peek/views/gitaly.rb
index 30f95a10024..80097cda3a4 100644
--- a/lib/peek/views/gitaly.rb
+++ b/lib/peek/views/gitaly.rb
@@ -15,7 +15,7 @@ module Peek
{
duration: formatted_duration,
calls: calls,
- details: details
+ details: details,
}
end
@@ -44,7 +44,7 @@ module Peek
end
def setup_subscribers
- subscribe 'start_processing.action_controller' do
+ subscribe "start_processing.action_controller" do
::Gitlab::GitalyClient.query_time = 0
end
end
diff --git a/lib/peek/views/host.rb b/lib/peek/views/host.rb
index b77355ea11b..3fbf86b64f0 100644
--- a/lib/peek/views/host.rb
+++ b/lib/peek/views/host.rb
@@ -6,7 +6,7 @@ module Peek
def results
{
hostname: Gitlab::Environment.hostname,
- canary: Gitlab::Utils.to_boolean(ENV['CANARY'])
+ canary: Gitlab::Utils.to_boolean(ENV["CANARY"]),
}
end
end
diff --git a/lib/peek/views/tracing.rb b/lib/peek/views/tracing.rb
index 0de32a8fdda..e513b248052 100644
--- a/lib/peek/views/tracing.rb
+++ b/lib/peek/views/tracing.rb
@@ -5,7 +5,7 @@ module Peek
class Tracing < View
def results
{
- tracing_url: Gitlab::Tracing.tracing_url
+ tracing_url: Gitlab::Tracing.tracing_url,
}
end
end
diff --git a/lib/quality/helm_client.rb b/lib/quality/helm_client.rb
index cf1f03b35b5..a5852988758 100644
--- a/lib/quality/helm_client.rb
+++ b/lib/quality/helm_client.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-require 'time'
-require_relative '../gitlab/popen' unless defined?(Gitlab::Popen)
+require "time"
+require_relative "../gitlab/popen" unless defined?(Gitlab::Popen)
module Quality
class HelmClient
@@ -11,7 +11,7 @@ module Quality
RELEASE_JSON_ATTRIBUTES = %w[Name Revision Updated Status Chart AppVersion Namespace].freeze
- Release = Struct.new(:name, :revision, :last_update, :status, :chart, :app_version, :namespace) do
+ Release = Struct.new(:name, :revision, :last_update, :status, :chart, :app_version, :namespace) {
def revision
@revision ||= self[:revision].to_i
end
@@ -19,7 +19,7 @@ module Quality
def last_update
@last_update ||= Time.parse(self[:last_update])
end
- end
+ }
# A single page of data and the corresponding page number.
Page = Struct.new(:releases, :number)
@@ -34,17 +34,17 @@ module Quality
def delete(release_name:)
run_command([
- 'delete',
+ "delete",
%(--tiller-namespace "#{namespace}"),
- '--purge',
- release_name
+ "--purge",
+ release_name,
])
end
private
def run_command(command)
- final_command = ['helm', *command].join(' ')
+ final_command = ["helm", *command].join(" ")
puts "Running command: `#{final_command}`" # rubocop:disable Rails/Output
result = Gitlab::Popen.popen_with_detail([final_command])
@@ -58,18 +58,18 @@ module Quality
def raw_releases(args = [])
command = [
- 'list',
+ "list",
%(--namespace "#{namespace}"),
%(--tiller-namespace "#{namespace}" --output json),
- *args
+ *args,
]
json = JSON.parse(run_command(command))
- releases = json['Releases'].map do |json_release|
+ releases = json["Releases"].map { |json_release|
Release.new(*json_release.values_at(*RELEASE_JSON_ATTRIBUTES))
- end
+ }
- [releases, json['Next']]
+ [releases, json["Next"]]
rescue JSON::ParserError => ex
puts "Ignoring this JSON parsing error: #{ex}" # rubocop:disable Rails/Output
[[], nil]
@@ -84,7 +84,7 @@ module Quality
return to_enum(__method__, args) unless block_given?
page = 1
- offset = ''
+ offset = ""
loop do
final_args = args.dup
diff --git a/lib/quality/kubernetes_client.rb b/lib/quality/kubernetes_client.rb
index 2ff9e811425..16a3305534d 100644
--- a/lib/quality/kubernetes_client.rb
+++ b/lib/quality/kubernetes_client.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_relative '../gitlab/popen' unless defined?(Gitlab::Popen)
+require_relative "../gitlab/popen" unless defined?(Gitlab::Popen)
module Quality
class KubernetesClient
@@ -15,10 +15,10 @@ module Quality
def cleanup(release_name:)
command = [
%(--namespace "#{namespace}"),
- 'delete',
- 'ingress,svc,pdb,hpa,deploy,statefulset,job,pod,secret,configmap,pvc,secret,clusterrole,clusterrolebinding,role,rolebinding,sa',
- '--now',
- %(-l release="#{release_name}")
+ "delete",
+ "ingress,svc,pdb,hpa,deploy,statefulset,job,pod,secret,configmap,pvc,secret,clusterrole,clusterrolebinding,role,rolebinding,sa",
+ "--now",
+ %(-l release="#{release_name}"),
]
run_command(command)
@@ -27,7 +27,7 @@ module Quality
private
def run_command(command)
- final_command = ['kubectl', *command].join(' ')
+ final_command = ["kubectl", *command].join(" ")
puts "Running command: `#{final_command}`" # rubocop:disable Rails/Output
result = Gitlab::Popen.popen_with_detail([final_command])
diff --git a/lib/rouge/formatters/html_gitlab.rb b/lib/rouge/formatters/html_gitlab.rb
index e2a7d3ef5ba..088fb158444 100644
--- a/lib/rouge/formatters/html_gitlab.rb
+++ b/lib/rouge/formatters/html_gitlab.rb
@@ -3,7 +3,7 @@
module Rouge
module Formatters
class HTMLGitlab < Rouge::Formatters::HTML
- tag 'html_gitlab'
+ tag "html_gitlab"
# Creates a new <tt>Rouge::Formatter::HTMLGitlab</tt> instance.
#
diff --git a/lib/rspec_flaky/config.rb b/lib/rspec_flaky/config.rb
index 55c1d4747b4..c07ca65ee48 100644
--- a/lib/rspec_flaky/config.rb
+++ b/lib/rspec_flaky/config.rb
@@ -3,19 +3,19 @@
module RspecFlaky
class Config
def self.generate_report?
- !!(ENV['FLAKY_RSPEC_GENERATE_REPORT'] =~ /1|true/)
+ !!(ENV["FLAKY_RSPEC_GENERATE_REPORT"] =~ /1|true/)
end
def self.suite_flaky_examples_report_path
- ENV['SUITE_FLAKY_RSPEC_REPORT_PATH'] || Rails.root.join("rspec_flaky/suite-report.json")
+ ENV["SUITE_FLAKY_RSPEC_REPORT_PATH"] || Rails.root.join("rspec_flaky/suite-report.json")
end
def self.flaky_examples_report_path
- ENV['FLAKY_RSPEC_REPORT_PATH'] || Rails.root.join("rspec_flaky/report.json")
+ ENV["FLAKY_RSPEC_REPORT_PATH"] || Rails.root.join("rspec_flaky/report.json")
end
def self.new_flaky_examples_report_path
- ENV['NEW_FLAKY_RSPEC_REPORT_PATH'] || Rails.root.join("rspec_flaky/new-report.json")
+ ENV["NEW_FLAKY_RSPEC_REPORT_PATH"] || Rails.root.join("rspec_flaky/new-report.json")
end
end
end
diff --git a/lib/rspec_flaky/flaky_example.rb b/lib/rspec_flaky/flaky_example.rb
index da5dbf06bc9..e4484dde6a5 100644
--- a/lib/rspec_flaky/flaky_example.rb
+++ b/lib/rspec_flaky/flaky_example.rb
@@ -23,8 +23,8 @@ module RspecFlaky
self.flaky_reports += 1
self.last_attempts_count = last_attempts_count if last_attempts_count
- if ENV['CI_PROJECT_URL'] && ENV['CI_JOB_ID']
- self.last_flaky_job = "#{ENV['CI_PROJECT_URL']}/-/jobs/#{ENV['CI_JOB_ID']}"
+ if ENV["CI_PROJECT_URL"] && ENV["CI_JOB_ID"]
+ self.last_flaky_job = "#{ENV["CI_PROJECT_URL"]}/-/jobs/#{ENV["CI_JOB_ID"]}"
end
end
@@ -32,7 +32,8 @@ module RspecFlaky
super.merge(
first_flaky_at: first_flaky_at,
last_flaky_at: last_flaky_at,
- last_flaky_job: last_flaky_job)
+ last_flaky_job: last_flaky_job
+ )
end
end
end
diff --git a/lib/rspec_flaky/flaky_examples_collection.rb b/lib/rspec_flaky/flaky_examples_collection.rb
index 290a51766e9..173e1deb544 100644
--- a/lib/rspec_flaky/flaky_examples_collection.rb
+++ b/lib/rspec_flaky/flaky_examples_collection.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
-require 'active_support/hash_with_indifferent_access'
+require "active_support/hash_with_indifferent_access"
-require_relative 'flaky_example'
+require_relative "flaky_example"
module RspecFlaky
class FlakyExamplesCollection < SimpleDelegator
@@ -12,12 +12,12 @@ module RspecFlaky
end
collection_of_flaky_examples =
- collection.map do |uid, example|
+ collection.map { |uid, example|
[
uid,
- example.is_a?(RspecFlaky::FlakyExample) ? example : RspecFlaky::FlakyExample.new(example)
+ example.is_a?(RspecFlaky::FlakyExample) ? example : RspecFlaky::FlakyExample.new(example),
]
- end
+ }
super(Hash[collection_of_flaky_examples])
end
diff --git a/lib/rspec_flaky/listener.rb b/lib/rspec_flaky/listener.rb
index 19cc0baa2d3..db21cf69029 100644
--- a/lib/rspec_flaky/listener.rb
+++ b/lib/rspec_flaky/listener.rb
@@ -1,12 +1,12 @@
# frozen_string_literal: true
-require 'json'
+require "json"
-require_dependency 'rspec_flaky/config'
-require_dependency 'rspec_flaky/example'
-require_dependency 'rspec_flaky/flaky_example'
-require_dependency 'rspec_flaky/flaky_examples_collection'
-require_dependency 'rspec_flaky/report'
+require_dependency "rspec_flaky/config"
+require_dependency "rspec_flaky/example"
+require_dependency "rspec_flaky/flaky_example"
+require_dependency "rspec_flaky/flaky_examples_collection"
+require_dependency "rspec_flaky/report"
module RspecFlaky
class Listener
diff --git a/lib/rspec_flaky/report.rb b/lib/rspec_flaky/report.rb
index 9a0fb88c424..1d7c9aa49a7 100644
--- a/lib/rspec_flaky/report.rb
+++ b/lib/rspec_flaky/report.rb
@@ -1,10 +1,10 @@
# frozen_string_literal: true
-require 'json'
-require 'time'
+require "json"
+require "time"
-require_dependency 'rspec_flaky/config'
-require_dependency 'rspec_flaky/flaky_examples_collection'
+require_dependency "rspec_flaky/config"
+require_dependency "rspec_flaky/flaky_examples_collection"
module RspecFlaky
# This class is responsible for loading/saving JSON reports, and pruning
@@ -46,9 +46,9 @@ module RspecFlaky
def prune_outdated(days: OUTDATED_DAYS_THRESHOLD)
outdated_date_threshold = Time.now - (3600 * 24 * days)
updated_hash = flaky_examples.dup
- .delete_if do |uid, hash|
+ .delete_if { |uid, hash|
hash[:last_flaky_at] && Time.parse(hash[:last_flaky_at]).to_i < outdated_date_threshold.to_i
- end
+ }
self.class.new(RspecFlaky::FlakyExamplesCollection.new(updated_hash))
end
diff --git a/lib/safe_zip/extract.rb b/lib/safe_zip/extract.rb
index 679c021c730..9abb53d4cdb 100644
--- a/lib/safe_zip/extract.rb
+++ b/lib/safe_zip/extract.rb
@@ -43,7 +43,7 @@ module SafeZip
extracted += extract_all_entries(zip_archive, params,
zip_archive.lazy.reject(&:directory?).reject(&:file?))
- raise NoMatchingError, 'No entries extracted' unless extracted > 0
+ raise NoMatchingError, "No entries extracted" unless extracted > 0
end
end
@@ -57,16 +57,16 @@ module SafeZip
def legacy_unsafe_extract_with_system_zip(params)
# Requires UnZip at least 6.00 Info-ZIP.
# -n never overwrite existing files
- args = %W(unzip -n -qq #{archive_path})
+ args = %W[unzip -n -qq #{archive_path}]
# We add * to end of directory, because we want to extract directory and all subdirectories
args += params.directories_wildcard
# Target directory where we extract
- args += %W(-d #{params.extract_path})
+ args += %W[-d #{params.extract_path}]
unless system(*args)
- raise Error, 'archive failed to extract'
+ raise Error, "archive failed to extract"
end
end
end
diff --git a/lib/safe_zip/extract_params.rb b/lib/safe_zip/extract_params.rb
index bd3b788bac9..17f0b38fb33 100644
--- a/lib/safe_zip/extract_params.rb
+++ b/lib/safe_zip/extract_params.rb
@@ -20,7 +20,7 @@ module SafeZip
def target_directories
strong_memoize(:target_directories) do
directories.map do |directory|
- ::File.join(::File.expand_path(directory, extract_path), '')
+ ::File.join(::File.expand_path(directory, extract_path), "")
end
end
end
@@ -28,7 +28,7 @@ module SafeZip
def directories_wildcard
strong_memoize(:directories_wildcard) do
directories.map do |directory|
- ::File.join(directory, '*')
+ ::File.join(directory, "*")
end
end
end
diff --git a/lib/sentry/client.rb b/lib/sentry/client.rb
index 49ec196b103..2a0836cae96 100644
--- a/lib/sentry/client.rb
+++ b/lib/sentry/client.rb
@@ -29,9 +29,9 @@ module Sentry
def request_params
{
headers: {
- 'Authorization' => "Bearer #{@token}"
+ "Authorization" => "Bearer #{@token}",
},
- follow_redirects: false
+ follow_redirects: false,
}
end
@@ -44,7 +44,7 @@ module Sentry
def get_issues(issue_status:, limit:)
http_get(issues_api_url, query: {
query: "is:#{issue_status}",
- limit: limit
+ limit: limit,
})
end
@@ -62,14 +62,14 @@ module Sentry
def projects_api_url
projects_url = URI(@url)
- projects_url.path = '/api/0/projects/'
+ projects_url.path = "/api/0/projects/"
projects_url
end
def issues_api_url
- issues_url = URI(@url + '/issues/')
- issues_url.path.squeeze!('/')
+ issues_url = URI(@url + "/issues/")
+ issues_url.path.squeeze!("/")
issues_url
end
@@ -87,53 +87,53 @@ module Sentry
issues_url = ErrorTracking::ProjectErrorTrackingSetting.extract_sentry_external_url(issues_url)
uri = URI(issues_url)
- uri.path.squeeze!('/')
+ uri.path.squeeze!("/")
uri.to_s
end
def map_to_error(issue)
- id = issue.fetch('id')
- project = issue.fetch('project')
+ id = issue.fetch("id")
+ project = issue.fetch("project")
- count = issue.fetch('count', nil)
+ count = issue.fetch("count", nil)
- frequency = issue.dig('stats', '24h')
- message = issue.dig('metadata', 'value')
+ frequency = issue.dig("stats", "24h")
+ message = issue.dig("metadata", "value")
external_url = issue_url(id)
Gitlab::ErrorTracking::Error.new(
id: id,
- first_seen: issue.fetch('firstSeen', nil),
- last_seen: issue.fetch('lastSeen', nil),
- title: issue.fetch('title', nil),
- type: issue.fetch('type', nil),
- user_count: issue.fetch('userCount', nil),
+ first_seen: issue.fetch("firstSeen", nil),
+ last_seen: issue.fetch("lastSeen", nil),
+ title: issue.fetch("title", nil),
+ type: issue.fetch("type", nil),
+ user_count: issue.fetch("userCount", nil),
count: count,
message: message,
- culprit: issue.fetch('culprit', nil),
+ culprit: issue.fetch("culprit", nil),
external_url: external_url,
- short_id: issue.fetch('shortId', nil),
- status: issue.fetch('status', nil),
+ short_id: issue.fetch("shortId", nil),
+ status: issue.fetch("status", nil),
frequency: frequency,
- project_id: project.fetch('id'),
- project_name: project.fetch('name', nil),
- project_slug: project.fetch('slug', nil)
+ project_id: project.fetch("id"),
+ project_name: project.fetch("name", nil),
+ project_slug: project.fetch("slug", nil)
)
end
def map_to_project(project)
- organization = project.fetch('organization')
+ organization = project.fetch("organization")
Gitlab::ErrorTracking::Project.new(
- id: project.fetch('id'),
- name: project.fetch('name'),
- slug: project.fetch('slug'),
- status: project.dig('status'),
- organization_name: organization.fetch('name'),
- organization_id: organization.fetch('id'),
- organization_slug: organization.fetch('slug')
+ id: project.fetch("id"),
+ name: project.fetch("name"),
+ slug: project.fetch("slug"),
+ status: project.dig("status"),
+ organization_name: organization.fetch("name"),
+ organization_id: organization.fetch("id"),
+ organization_slug: organization.fetch("slug")
)
end
end
diff --git a/lib/static_model.rb b/lib/static_model.rb
index 86bf8d62f9a..0734fceb0fc 100644
--- a/lib/static_model.rb
+++ b/lib/static_model.rb
@@ -7,7 +7,7 @@ module StaticModel
class_methods do
# Used by ActiveRecord's polymorphic association to set object_id
def primary_key
- 'id'
+ "id"
end
# Used by ActiveRecord's polymorphic association to set object_type
diff --git a/lib/system_check/app/active_users_check.rb b/lib/system_check/app/active_users_check.rb
index 8446c2fc2c8..f837a12aea9 100644
--- a/lib/system_check/app/active_users_check.rb
+++ b/lib/system_check/app/active_users_check.rb
@@ -3,7 +3,7 @@
module SystemCheck
module App
class ActiveUsersCheck < SystemCheck::BaseCheck
- set_name 'Active users:'
+ set_name "Active users:"
def multi_check
active_users = User.active.count
diff --git a/lib/system_check/app/database_config_exists_check.rb b/lib/system_check/app/database_config_exists_check.rb
index 1769145ed63..e0a6a5c64a7 100644
--- a/lib/system_check/app/database_config_exists_check.rb
+++ b/lib/system_check/app/database_config_exists_check.rb
@@ -3,22 +3,22 @@
module SystemCheck
module App
class DatabaseConfigExistsCheck < SystemCheck::BaseCheck
- set_name 'Database config exists?'
+ set_name "Database config exists?"
def check?
- database_config_file = Rails.root.join('config', 'database.yml')
+ database_config_file = Rails.root.join("config", "database.yml")
File.exist?(database_config_file)
end
def show_error
try_fixing_it(
- 'Copy config/database.yml.<your db> to config/database.yml',
- 'Check that the information in config/database.yml is correct'
+ "Copy config/database.yml.<your db> to config/database.yml",
+ "Check that the information in config/database.yml is correct"
)
for_more_information(
- 'doc/install/databases.md',
- 'http://guides.rubyonrails.org/getting_started.html#configuring-a-database'
+ "doc/install/databases.md",
+ "http://guides.rubyonrails.org/getting_started.html#configuring-a-database"
)
fix_and_rerun
end
diff --git a/lib/system_check/app/git_config_check.rb b/lib/system_check/app/git_config_check.rb
index 4e8d607096c..e50a103a089 100644
--- a/lib/system_check/app/git_config_check.rb
+++ b/lib/system_check/app/git_config_check.rb
@@ -4,15 +4,15 @@ module SystemCheck
module App
class GitConfigCheck < SystemCheck::BaseCheck
OPTIONS = {
- 'core.autocrlf' => 'input'
+ "core.autocrlf" => "input",
}.freeze
- set_name 'Git configured correctly?'
+ set_name "Git configured correctly?"
def check?
- correct_options = OPTIONS.map do |name, value|
- run_command(%W(#{Gitlab.config.git.bin_path} config --global --get #{name})).try(:squish) == value
- end
+ correct_options = OPTIONS.map { |name, value|
+ run_command(%W[#{Gitlab.config.git.bin_path} config --global --get #{name}]).try(:squish) == value
+ }
correct_options.all?
end
@@ -24,19 +24,19 @@ module SystemCheck
def repair!
return false unless gitlab_user?
- command_success = OPTIONS.map do |name, value|
- system(*%W(#{Gitlab.config.git.bin_path} config --global #{name} #{value}))
- end
+ command_success = OPTIONS.map { |name, value|
+ system(Gitlab.config.git.bin_path.to_s, "config", "--global", name.to_s, value.to_s)
+ }
command_success.all?
end
def show_error
try_fixing_it(
- sudo_gitlab("\"#{Gitlab.config.git.bin_path}\" config --global core.autocrlf \"#{OPTIONS['core.autocrlf']}\"")
+ sudo_gitlab("\"#{Gitlab.config.git.bin_path}\" config --global core.autocrlf \"#{OPTIONS["core.autocrlf"]}\"")
)
for_more_information(
- see_installation_guide_section 'GitLab'
+ see_installation_guide_section("GitLab")
)
end
end
diff --git a/lib/system_check/app/git_user_default_ssh_config_check.rb b/lib/system_check/app/git_user_default_ssh_config_check.rb
index 6cd53779bfd..bac06a6108f 100644
--- a/lib/system_check/app/git_user_default_ssh_config_check.rb
+++ b/lib/system_check/app/git_user_default_ssh_config_check.rb
@@ -12,8 +12,8 @@ module SystemCheck
known_hosts
].freeze
- set_name 'Git user has default SSH configuration?'
- set_skip_reason 'skipped (git user is not present / configured)'
+ set_name "Git user has default SSH configuration?"
+ set_skip_reason "skipped (git user is not present / configured)"
def skip?
!home_dir || !File.directory?(home_dir)
@@ -26,9 +26,9 @@ module SystemCheck
def show_error
backup_dir = "~/gitlab-check-backup-#{Time.now.to_i}"
- instructions = forbidden_files.map do |filename|
+ instructions = forbidden_files.map { |filename|
"sudo mv #{Shellwords.escape(filename)} #{backup_dir}"
- end
+ }
try_fixing_it("mkdir #{backup_dir}", *instructions)
for_more_information('doc/ssh/README.md in section "SSH on the GitLab server"')
@@ -55,13 +55,13 @@ module SystemCheck
def ssh_dir
return nil unless home_dir
- File.join(home_dir, '.ssh')
+ File.join(home_dir, ".ssh")
end
def forbidden_files
@forbidden_files ||=
begin
- present = Dir[File.join(ssh_dir, '*')]
+ present = Dir[File.join(ssh_dir, "*")]
whitelisted = WHITELIST.map { |basename| File.join(ssh_dir, basename) }
present - whitelisted
diff --git a/lib/system_check/app/git_version_check.rb b/lib/system_check/app/git_version_check.rb
index 7c3e7759dd0..59f6abba2ce 100644
--- a/lib/system_check/app/git_version_check.rb
+++ b/lib/system_check/app/git_version_check.rb
@@ -3,15 +3,15 @@
module SystemCheck
module App
class GitVersionCheck < SystemCheck::BaseCheck
- set_name -> { "Git version >= #{self.required_version} ?" }
- set_check_pass -> { "yes (#{self.current_version})" }
+ set_name -> { "Git version >= #{required_version} ?" }
+ set_check_pass -> { "yes (#{current_version})" }
def self.required_version
- @required_version ||= Gitlab::VersionInfo.parse('2.18.0')
+ @required_version ||= Gitlab::VersionInfo.parse("2.18.0")
end
def self.current_version
- @current_version ||= Gitlab::VersionInfo.parse(Gitlab::TaskHelpers.run_command(%W(#{Gitlab.config.git.bin_path} --version)))
+ @current_version ||= Gitlab::VersionInfo.parse(Gitlab::TaskHelpers.run_command(%W[#{Gitlab.config.git.bin_path} --version]))
end
def check?
diff --git a/lib/system_check/app/gitlab_config_exists_check.rb b/lib/system_check/app/gitlab_config_exists_check.rb
index 1cc5ead0d89..b29aa66d8a9 100644
--- a/lib/system_check/app/gitlab_config_exists_check.rb
+++ b/lib/system_check/app/gitlab_config_exists_check.rb
@@ -3,21 +3,21 @@
module SystemCheck
module App
class GitlabConfigExistsCheck < SystemCheck::BaseCheck
- set_name 'GitLab config exists?'
+ set_name "GitLab config exists?"
def check?
- gitlab_config_file = Rails.root.join('config', 'gitlab.yml')
+ gitlab_config_file = Rails.root.join("config", "gitlab.yml")
File.exist?(gitlab_config_file)
end
def show_error
try_fixing_it(
- 'Copy config/gitlab.yml.example to config/gitlab.yml',
- 'Update config/gitlab.yml to match your setup'
+ "Copy config/gitlab.yml.example to config/gitlab.yml",
+ "Update config/gitlab.yml to match your setup"
)
for_more_information(
- see_installation_guide_section 'GitLab'
+ see_installation_guide_section("GitLab")
)
fix_and_rerun
end
diff --git a/lib/system_check/app/gitlab_config_up_to_date_check.rb b/lib/system_check/app/gitlab_config_up_to_date_check.rb
index 58c7e3039c8..be4144941c1 100644
--- a/lib/system_check/app/gitlab_config_up_to_date_check.rb
+++ b/lib/system_check/app/gitlab_config_up_to_date_check.rb
@@ -3,27 +3,27 @@
module SystemCheck
module App
class GitlabConfigUpToDateCheck < SystemCheck::BaseCheck
- set_name 'GitLab config up to date?'
+ set_name "GitLab config up to date?"
set_skip_reason "can't check because of previous errors"
def skip?
- gitlab_config_file = Rails.root.join('config', 'gitlab.yml')
+ gitlab_config_file = Rails.root.join("config", "gitlab.yml")
!File.exist?(gitlab_config_file)
end
def check?
# omniauth or ldap could have been deleted from the file
- !Gitlab.config['git_host']
+ !Gitlab.config["git_host"]
end
def show_error
try_fixing_it(
- 'Back-up your config/gitlab.yml',
- 'Copy config/gitlab.yml.example to config/gitlab.yml',
- 'Update config/gitlab.yml to match your setup'
+ "Back-up your config/gitlab.yml",
+ "Copy config/gitlab.yml.example to config/gitlab.yml",
+ "Update config/gitlab.yml to match your setup"
)
for_more_information(
- see_installation_guide_section 'GitLab'
+ see_installation_guide_section("GitLab")
)
fix_and_rerun
end
diff --git a/lib/system_check/app/init_script_exists_check.rb b/lib/system_check/app/init_script_exists_check.rb
index d36dbe7d67d..99c1f8eab91 100644
--- a/lib/system_check/app/init_script_exists_check.rb
+++ b/lib/system_check/app/init_script_exists_check.rb
@@ -3,24 +3,24 @@
module SystemCheck
module App
class InitScriptExistsCheck < SystemCheck::BaseCheck
- set_name 'Init script exists?'
- set_skip_reason 'skipped (omnibus-gitlab has no init script)'
+ set_name "Init script exists?"
+ set_skip_reason "skipped (omnibus-gitlab has no init script)"
def skip?
omnibus_gitlab?
end
def check?
- script_path = '/etc/init.d/gitlab'
+ script_path = "/etc/init.d/gitlab"
File.exist?(script_path)
end
def show_error
try_fixing_it(
- 'Install the init script'
+ "Install the init script"
)
for_more_information(
- see_installation_guide_section 'Install Init Script'
+ see_installation_guide_section("Install Init Script")
)
fix_and_rerun
end
diff --git a/lib/system_check/app/init_script_up_to_date_check.rb b/lib/system_check/app/init_script_up_to_date_check.rb
index 569c41df6e4..79ef616b5cd 100644
--- a/lib/system_check/app/init_script_up_to_date_check.rb
+++ b/lib/system_check/app/init_script_up_to_date_check.rb
@@ -3,10 +3,10 @@
module SystemCheck
module App
class InitScriptUpToDateCheck < SystemCheck::BaseCheck
- SCRIPT_PATH = '/etc/init.d/gitlab'.freeze
+ SCRIPT_PATH = "/etc/init.d/gitlab"
- set_name 'Init script up-to-date?'
- set_skip_reason 'skipped (omnibus-gitlab has no init script)'
+ set_name "Init script up-to-date?"
+ set_skip_reason "skipped (omnibus-gitlab has no init script)"
def skip?
return true if omnibus_gitlab?
@@ -19,7 +19,7 @@ module SystemCheck
end
def check?
- recipe_path = Rails.root.join('lib/support/init.d/', 'gitlab')
+ recipe_path = Rails.root.join("lib/support/init.d/", "gitlab")
recipe_content = File.read(recipe_path)
script_content = File.read(SCRIPT_PATH)
@@ -29,10 +29,10 @@ module SystemCheck
def show_error
try_fixing_it(
- 'Re-download the init script'
+ "Re-download the init script"
)
for_more_information(
- see_installation_guide_section 'Install Init Script'
+ see_installation_guide_section("Install Init Script")
)
fix_and_rerun
end
diff --git a/lib/system_check/app/log_writable_check.rb b/lib/system_check/app/log_writable_check.rb
index e26ad143eb8..15c69a53c75 100644
--- a/lib/system_check/app/log_writable_check.rb
+++ b/lib/system_check/app/log_writable_check.rb
@@ -3,7 +3,7 @@
module SystemCheck
module App
class LogWritableCheck < SystemCheck::BaseCheck
- set_name 'Log directory writable?'
+ set_name "Log directory writable?"
def check?
File.writable?(log_path)
@@ -15,7 +15,7 @@ module SystemCheck
"sudo chmod -R u+rwX #{log_path}"
)
for_more_information(
- see_installation_guide_section 'GitLab'
+ see_installation_guide_section("GitLab")
)
fix_and_rerun
end
@@ -23,7 +23,7 @@ module SystemCheck
private
def log_path
- Rails.root.join('log')
+ Rails.root.join("log")
end
end
end
diff --git a/lib/system_check/app/migrations_are_up_check.rb b/lib/system_check/app/migrations_are_up_check.rb
index b12e9ac6bba..4d84a248e31 100644
--- a/lib/system_check/app/migrations_are_up_check.rb
+++ b/lib/system_check/app/migrations_are_up_check.rb
@@ -3,17 +3,17 @@
module SystemCheck
module App
class MigrationsAreUpCheck < SystemCheck::BaseCheck
- set_name 'All migrations up?'
+ set_name "All migrations up?"
def check?
- migration_status, _ = Gitlab::Popen.popen(%w(bundle exec rake db:migrate:status))
+ migration_status, _ = Gitlab::Popen.popen(%w[bundle exec rake db:migrate:status])
migration_status !~ /down\s+\d{14}/
end
def show_error
try_fixing_it(
- sudo_gitlab('bundle exec rake db:migrate RAILS_ENV=production')
+ sudo_gitlab("bundle exec rake db:migrate RAILS_ENV=production")
)
fix_and_rerun
end
diff --git a/lib/system_check/app/orphaned_group_members_check.rb b/lib/system_check/app/orphaned_group_members_check.rb
index 3e6ffb8190b..4d8b4b5a54d 100644
--- a/lib/system_check/app/orphaned_group_members_check.rb
+++ b/lib/system_check/app/orphaned_group_members_check.rb
@@ -3,17 +3,17 @@
module SystemCheck
module App
class OrphanedGroupMembersCheck < SystemCheck::BaseCheck
- set_name 'Database contains orphaned GroupMembers?'
- set_check_pass 'no'
- set_check_fail 'yes'
+ set_name "Database contains orphaned GroupMembers?"
+ set_check_pass "no"
+ set_check_fail "yes"
def check?
- !GroupMember.where('user_id not in (select id from users)').exists?
+ !GroupMember.where("user_id not in (select id from users)").exists?
end
def show_error
try_fixing_it(
- 'You can delete the orphaned records using something along the lines of:',
+ "You can delete the orphaned records using something along the lines of:",
sudo_gitlab("bundle exec rails runner -e production 'GroupMember.where(\"user_id NOT IN (SELECT id FROM users)\").delete_all'")
)
end
diff --git a/lib/system_check/app/projects_have_namespace_check.rb b/lib/system_check/app/projects_have_namespace_check.rb
index 2bf2529acf1..b47ce5ac0b7 100644
--- a/lib/system_check/app/projects_have_namespace_check.rb
+++ b/lib/system_check/app/projects_have_namespace_check.rb
@@ -3,7 +3,7 @@
module SystemCheck
module App
class ProjectsHaveNamespaceCheck < SystemCheck::BaseCheck
- set_name 'Projects have namespace:'
+ set_name "Projects have namespace:"
set_skip_reason "can't check, you have no projects"
def skip?
@@ -11,15 +11,15 @@ module SystemCheck
end
def multi_check
- $stdout.puts ''
+ $stdout.puts ""
Project.find_each(batch_size: 100) do |project|
$stdout.print sanitized_message(project)
if project.namespace
- $stdout.puts 'yes'.color(:green)
+ $stdout.puts "yes".color(:green)
else
- $stdout.puts 'no'.color(:red)
+ $stdout.puts "no".color(:red)
show_error
end
end
diff --git a/lib/system_check/app/redis_version_check.rb b/lib/system_check/app/redis_version_check.rb
index 890f8b44d13..6f66fe8fe43 100644
--- a/lib/system_check/app/redis_version_check.rb
+++ b/lib/system_check/app/redis_version_check.rb
@@ -3,11 +3,11 @@
module SystemCheck
module App
class RedisVersionCheck < SystemCheck::BaseCheck
- MIN_REDIS_VERSION = '2.8.0'.freeze
+ MIN_REDIS_VERSION = "2.8.0"
set_name "Redis version >= #{MIN_REDIS_VERSION}?"
def check?
- redis_version = run_command(%w(redis-cli --version))
+ redis_version = run_command(%w[redis-cli --version])
redis_version = redis_version.try(:match, /redis-cli (\d+\.\d+\.\d+)/)
redis_version && (Gem::Version.new(redis_version[1]) > Gem::Version.new(MIN_REDIS_VERSION))
@@ -18,7 +18,7 @@ module SystemCheck
"Update your redis server to a version >= #{MIN_REDIS_VERSION}"
)
for_more_information(
- 'gitlab-public-wiki/wiki/Trouble-Shooting-Guide in section sidekiq'
+ "gitlab-public-wiki/wiki/Trouble-Shooting-Guide in section sidekiq"
)
fix_and_rerun
end
diff --git a/lib/system_check/app/ruby_version_check.rb b/lib/system_check/app/ruby_version_check.rb
index 60e07718338..81540b43f49 100644
--- a/lib/system_check/app/ruby_version_check.rb
+++ b/lib/system_check/app/ruby_version_check.rb
@@ -3,8 +3,8 @@
module SystemCheck
module App
class RubyVersionCheck < SystemCheck::BaseCheck
- set_name -> { "Ruby version >= #{self.required_version} ?" }
- set_check_pass -> { "yes (#{self.current_version})" }
+ set_name -> { "Ruby version >= #{required_version} ?" }
+ set_check_pass -> { "yes (#{current_version})" }
def self.required_version
@required_version ||= Gitlab::VersionInfo.new(2, 3, 5)
diff --git a/lib/system_check/app/tmp_writable_check.rb b/lib/system_check/app/tmp_writable_check.rb
index 6687df091d3..63f6e57b498 100644
--- a/lib/system_check/app/tmp_writable_check.rb
+++ b/lib/system_check/app/tmp_writable_check.rb
@@ -3,7 +3,7 @@
module SystemCheck
module App
class TmpWritableCheck < SystemCheck::BaseCheck
- set_name 'Tmp directory writable?'
+ set_name "Tmp directory writable?"
def check?
File.writable?(tmp_path)
@@ -15,7 +15,7 @@ module SystemCheck
"sudo chmod -R u+rwX #{tmp_path}"
)
for_more_information(
- see_installation_guide_section 'GitLab'
+ see_installation_guide_section("GitLab")
)
fix_and_rerun
end
@@ -23,7 +23,7 @@ module SystemCheck
private
def tmp_path
- Rails.root.join('tmp')
+ Rails.root.join("tmp")
end
end
end
diff --git a/lib/system_check/app/uploads_directory_exists_check.rb b/lib/system_check/app/uploads_directory_exists_check.rb
index 940eff9d4cf..dd61b8093c8 100644
--- a/lib/system_check/app/uploads_directory_exists_check.rb
+++ b/lib/system_check/app/uploads_directory_exists_check.rb
@@ -3,10 +3,10 @@
module SystemCheck
module App
class UploadsDirectoryExistsCheck < SystemCheck::BaseCheck
- set_name 'Uploads directory exists?'
+ set_name "Uploads directory exists?"
def check?
- File.directory?(Rails.root.join('public/uploads'))
+ File.directory?(Rails.root.join("public/uploads"))
end
def show_error
@@ -14,7 +14,7 @@ module SystemCheck
"sudo -u #{gitlab_user} mkdir #{Rails.root}/public/uploads"
)
for_more_information(
- see_installation_guide_section 'GitLab'
+ see_installation_guide_section("GitLab")
)
fix_and_rerun
end
diff --git a/lib/system_check/app/uploads_path_permission_check.rb b/lib/system_check/app/uploads_path_permission_check.rb
index 4a49f3bc2bb..e1fdf88d6f7 100644
--- a/lib/system_check/app/uploads_path_permission_check.rb
+++ b/lib/system_check/app/uploads_path_permission_check.rb
@@ -3,15 +3,15 @@
module SystemCheck
module App
class UploadsPathPermissionCheck < SystemCheck::BaseCheck
- set_name 'Uploads directory has correct permissions?'
- set_skip_reason 'skipped (no uploads folder found)'
+ set_name "Uploads directory has correct permissions?"
+ set_skip_reason "skipped (no uploads folder found)"
def skip?
!File.directory?(rails_uploads_path)
end
def check?
- File.stat(uploads_fullpath).mode == 040700
+ File.stat(uploads_fullpath).mode == 0o40700
end
def show_error
@@ -19,7 +19,7 @@ module SystemCheck
"sudo chmod 700 #{uploads_fullpath}"
)
for_more_information(
- see_installation_guide_section 'GitLab'
+ see_installation_guide_section("GitLab")
)
fix_and_rerun
end
@@ -27,7 +27,7 @@ module SystemCheck
private
def rails_uploads_path
- Rails.root.join('public/uploads')
+ Rails.root.join("public/uploads")
end
def uploads_fullpath
diff --git a/lib/system_check/app/uploads_path_tmp_permission_check.rb b/lib/system_check/app/uploads_path_tmp_permission_check.rb
index ae374f4707c..1c6aea6d9ac 100644
--- a/lib/system_check/app/uploads_path_tmp_permission_check.rb
+++ b/lib/system_check/app/uploads_path_tmp_permission_check.rb
@@ -3,8 +3,8 @@
module SystemCheck
module App
class UploadsPathTmpPermissionCheck < SystemCheck::BaseCheck
- set_name 'Uploads directory tmp has correct permissions?'
- set_skip_reason 'skipped (no tmp uploads folder yet)'
+ set_name "Uploads directory tmp has correct permissions?"
+ set_skip_reason "skipped (no tmp uploads folder yet)"
def skip?
!File.directory?(uploads_fullpath) || !Dir.exist?(upload_path_tmp)
@@ -13,7 +13,7 @@ module SystemCheck
def check?
# If tmp upload dir has incorrect permissions, assume others do as well
# Verify drwx------ permissions
- File.stat(upload_path_tmp).mode == 040700 && File.owned?(upload_path_tmp)
+ File.stat(upload_path_tmp).mode == 0o40700 && File.owned?(upload_path_tmp)
end
def show_error
@@ -23,7 +23,7 @@ module SystemCheck
"sudo find #{uploads_fullpath} -type d -not -path #{uploads_fullpath} -exec chmod 0700 {} \\;"
)
for_more_information(
- see_installation_guide_section 'GitLab'
+ see_installation_guide_section("GitLab")
)
fix_and_rerun
end
@@ -31,11 +31,11 @@ module SystemCheck
private
def upload_path_tmp
- File.join(uploads_fullpath, 'tmp')
+ File.join(uploads_fullpath, "tmp")
end
def uploads_fullpath
- File.realpath(Rails.root.join('public/uploads'))
+ File.realpath(Rails.root.join("public/uploads"))
end
end
end
diff --git a/lib/system_check/base_check.rb b/lib/system_check/base_check.rb
index 46aad8aa885..d374bea1936 100644
--- a/lib/system_check/base_check.rb
+++ b/lib/system_check/base_check.rb
@@ -40,28 +40,28 @@ module SystemCheck
#
# @return [String] term when check passed ('yes' if not re-defined in a subclass)
def self.check_pass
- call_or_return(@check_pass) || 'yes'
+ call_or_return(@check_pass) || "yes"
end
## Term to be displayed when check failed
#
# @return [String] term when check failed ('no' if not re-defined in a subclass)
def self.check_fail
- call_or_return(@check_fail) || 'no'
+ call_or_return(@check_fail) || "no"
end
# Name of the SystemCheck defined by the subclass
#
# @return [String] the name
def self.display_name
- call_or_return(@name) || self.name
+ call_or_return(@name) || name
end
# Skip reason defined by the subclass
#
# @return [String] the reason
def self.skip_reason
- call_or_return(@skip_reason) || 'skipped'
+ call_or_return(@skip_reason) || "skipped"
end
# Define a reason why we skipped the SystemCheck (during runtime)
diff --git a/lib/system_check/gitaly_check.rb b/lib/system_check/gitaly_check.rb
index 3d2517a7aca..9ce78d9c8d3 100644
--- a/lib/system_check/gitaly_check.rb
+++ b/lib/system_check/gitaly_check.rb
@@ -2,14 +2,14 @@
module SystemCheck
class GitalyCheck < BaseCheck
- set_name 'Gitaly:'
+ set_name "Gitaly:"
def multi_check
Gitlab::HealthChecks::GitalyCheck.readiness.each do |result|
$stdout.print "#{result.labels[:shard]} ... "
if result.success
- $stdout.puts 'OK'.color(:green)
+ $stdout.puts "OK".color(:green)
else
$stdout.puts "FAIL: #{result.message}".color(:red)
end
diff --git a/lib/system_check/gitlab_shell_check.rb b/lib/system_check/gitlab_shell_check.rb
index 31c4ec33247..bd12c57051b 100644
--- a/lib/system_check/gitlab_shell_check.rb
+++ b/lib/system_check/gitlab_shell_check.rb
@@ -3,7 +3,7 @@
module SystemCheck
# Used by gitlab:gitlab_shell:check rake task
class GitlabShellCheck < BaseCheck
- set_name 'GitLab Shell:'
+ set_name "GitLab Shell:"
def multi_check
check_gitlab_shell
@@ -26,17 +26,17 @@ module SystemCheck
def check_gitlab_shell_self_test
gitlab_shell_repo_base = gitlab_shell_path
- check_cmd = File.expand_path('bin/check', gitlab_shell_repo_base)
+ check_cmd = File.expand_path("bin/check", gitlab_shell_repo_base)
$stdout.puts "Running #{check_cmd}"
if system(check_cmd, chdir: gitlab_shell_repo_base)
- $stdout.puts 'gitlab-shell self-check successful'.color(:green)
+ $stdout.puts "gitlab-shell self-check successful".color(:green)
else
- $stdout.puts 'gitlab-shell self-check failed'.color(:red)
+ $stdout.puts "gitlab-shell self-check failed".color(:red)
try_fixing_it(
- 'Make sure GitLab is running;',
- 'Check the gitlab-shell configuration file:',
- sudo_gitlab("editor #{File.expand_path('config.yml', gitlab_shell_repo_base)}")
+ "Make sure GitLab is running;",
+ "Check the gitlab-shell configuration file:",
+ sudo_gitlab("editor #{File.expand_path("config.yml", gitlab_shell_repo_base)}")
)
fix_and_rerun
end
diff --git a/lib/system_check/helpers.rb b/lib/system_check/helpers.rb
index 07d479848fe..daad28c78ff 100644
--- a/lib/system_check/helpers.rb
+++ b/lib/system_check/helpers.rb
@@ -6,14 +6,14 @@ module SystemCheck
# Display a message telling to fix and rerun the checks
def fix_and_rerun
- $stdout.puts ' Please fix the error above and rerun the checks.'.color(:red)
+ $stdout.puts " Please fix the error above and rerun the checks.".color(:red)
end
# Display a formatted list of references (documentation or links) where to find more information
#
# @param [Array<String>] sources one or more references (documentation or links)
def for_more_information(*sources)
- $stdout.puts ' For more information see:'.color(:blue)
+ $stdout.puts " For more information see:".color(:blue)
sources.each do |source|
$stdout.puts " #{source}"
end
@@ -25,15 +25,15 @@ module SystemCheck
# @deprecated This will no longer be used when all checks were executed using SystemCheck
def finished_checking(component)
- $stdout.puts ''
- $stdout.puts "Checking #{component.color(:yellow)} ... #{'Finished'.color(:green)}"
- $stdout.puts ''
+ $stdout.puts ""
+ $stdout.puts "Checking #{component.color(:yellow)} ... #{"Finished".color(:green)}"
+ $stdout.puts ""
end
# @deprecated This will no longer be used when all checks were executed using SystemCheck
def start_checking(component)
$stdout.puts "Checking #{component.color(:yellow)} ..."
- $stdout.puts ''
+ $stdout.puts ""
end
# Display a formatted list of instructions on how to fix the issue identified by the #check?
@@ -42,7 +42,7 @@ module SystemCheck
def try_fixing_it(*steps)
steps = steps.shift if steps.first.is_a?(Array)
- $stdout.puts ' Try fixing it:'.color(:blue)
+ $stdout.puts " Try fixing it:".color(:blue)
steps.each do |step|
$stdout.puts " #{step}"
end
@@ -57,15 +57,11 @@ module SystemCheck
end
def should_sanitize?
- if ENV['SANITIZE'] == 'true'
- true
- else
- false
- end
+ ENV["SANITIZE"] == "true"
end
def omnibus_gitlab?
- Dir.pwd == '/opt/gitlab/embedded/service/gitlab-rails'
+ Dir.pwd == "/opt/gitlab/embedded/service/gitlab-rails"
end
def sudo_gitlab(command)
diff --git a/lib/system_check/incoming_email/foreman_configured_check.rb b/lib/system_check/incoming_email/foreman_configured_check.rb
index 944913087da..f5206998276 100644
--- a/lib/system_check/incoming_email/foreman_configured_check.rb
+++ b/lib/system_check/incoming_email/foreman_configured_check.rb
@@ -3,20 +3,20 @@
module SystemCheck
module IncomingEmail
class ForemanConfiguredCheck < SystemCheck::BaseCheck
- set_name 'Foreman configured correctly?'
+ set_name "Foreman configured correctly?"
def check?
- path = Rails.root.join('Procfile')
+ path = Rails.root.join("Procfile")
File.exist?(path) && File.read(path) =~ /^mail_room:/
end
def show_error
try_fixing_it(
- 'Enable mail_room in your Procfile.'
+ "Enable mail_room in your Procfile."
)
for_more_information(
- 'doc/administration/reply_by_email.md'
+ "doc/administration/reply_by_email.md"
)
fix_and_rerun
end
diff --git a/lib/system_check/incoming_email/imap_authentication_check.rb b/lib/system_check/incoming_email/imap_authentication_check.rb
index 613c2296375..d9f67011ee2 100644
--- a/lib/system_check/incoming_email/imap_authentication_check.rb
+++ b/lib/system_check/incoming_email/imap_authentication_check.rb
@@ -3,7 +3,7 @@
module SystemCheck
module IncomingEmail
class ImapAuthenticationCheck < SystemCheck::BaseCheck
- set_name 'IMAP server credentials are correct?'
+ set_name "IMAP server credentials are correct?"
def check?
if config
@@ -17,10 +17,10 @@ module SystemCheck
def show_error
try_fixing_it(
"An error occurred: #{@error.class}: #{@error.message}",
- 'Check that the information in config/gitlab.yml is correct'
+ "Check that the information in config/gitlab.yml is correct"
)
for_more_information(
- 'doc/administration/reply_by_email.md'
+ "doc/administration/reply_by_email.md"
)
fix_and_rerun
end
@@ -43,7 +43,7 @@ module SystemCheck
def mail_room_config_path
@mail_room_config_path ||=
- Rails.root.join('config', 'mail_room.yml').to_s
+ Rails.root.join("config", "mail_room.yml").to_s
end
def load_config
diff --git a/lib/system_check/incoming_email/initd_configured_check.rb b/lib/system_check/incoming_email/initd_configured_check.rb
index acb4b5a9e74..ae300938958 100644
--- a/lib/system_check/incoming_email/initd_configured_check.rb
+++ b/lib/system_check/incoming_email/initd_configured_check.rb
@@ -3,7 +3,7 @@
module SystemCheck
module IncomingEmail
class InitdConfiguredCheck < SystemCheck::BaseCheck
- set_name 'Init.d configured correctly?'
+ set_name "Init.d configured correctly?"
def skip?
omnibus_gitlab?
@@ -15,10 +15,10 @@ module SystemCheck
def show_error
try_fixing_it(
- 'Enable mail_room in the init.d configuration.'
+ "Enable mail_room in the init.d configuration."
)
for_more_information(
- 'doc/administration/reply_by_email.md'
+ "doc/administration/reply_by_email.md"
)
fix_and_rerun
end
@@ -26,8 +26,8 @@ module SystemCheck
private
def mail_room_configured?
- path = '/etc/default/gitlab'
- File.exist?(path) && File.read(path).include?('mail_room_enabled=true')
+ path = "/etc/default/gitlab"
+ File.exist?(path) && File.read(path).include?("mail_room_enabled=true")
end
end
end
diff --git a/lib/system_check/incoming_email/mail_room_running_check.rb b/lib/system_check/incoming_email/mail_room_running_check.rb
index b7aead4624e..f979b1f322d 100644
--- a/lib/system_check/incoming_email/mail_room_running_check.rb
+++ b/lib/system_check/incoming_email/mail_room_running_check.rb
@@ -3,7 +3,7 @@
module SystemCheck
module IncomingEmail
class MailRoomRunningCheck < SystemCheck::BaseCheck
- set_name 'MailRoom running?'
+ set_name "MailRoom running?"
def skip?
return true if omnibus_gitlab?
@@ -20,11 +20,11 @@ module SystemCheck
def show_error
try_fixing_it(
- sudo_gitlab('RAILS_ENV=production bin/mail_room start')
+ sudo_gitlab("RAILS_ENV=production bin/mail_room start")
)
for_more_information(
- see_installation_guide_section('Install Init Script'),
- 'see log/mail_room.log for possible errors'
+ see_installation_guide_section("Install Init Script"),
+ "see log/mail_room.log for possible errors"
)
fix_and_rerun
end
@@ -32,12 +32,12 @@ module SystemCheck
private
def mail_room_configured?
- path = '/etc/default/gitlab'
- File.exist?(path) && File.read(path).include?('mail_room_enabled=true')
+ path = "/etc/default/gitlab"
+ File.exist?(path) && File.read(path).include?("mail_room_enabled=true")
end
def mail_room_running?
- ps_ux, _ = Gitlab::Popen.popen(%w(ps uxww))
+ ps_ux, _ = Gitlab::Popen.popen(%w[ps uxww])
ps_ux.include?("mail_room")
end
end
diff --git a/lib/system_check/incoming_email_check.rb b/lib/system_check/incoming_email_check.rb
index 155b6547595..96642eb651d 100644
--- a/lib/system_check/incoming_email_check.rb
+++ b/lib/system_check/incoming_email_check.rb
@@ -3,12 +3,12 @@
module SystemCheck
# Used by gitlab:incoming_email:check rake task
class IncomingEmailCheck < BaseCheck
- set_name 'Incoming Email:'
+ set_name "Incoming Email:"
def multi_check
if Gitlab.config.incoming_email.enabled
checks = [
- SystemCheck::IncomingEmail::ImapAuthenticationCheck
+ SystemCheck::IncomingEmail::ImapAuthenticationCheck,
]
if Rails.env.production?
@@ -18,9 +18,9 @@ module SystemCheck
checks << SystemCheck::IncomingEmail::ForemanConfiguredCheck
end
- SystemCheck.run('Reply by email', checks)
+ SystemCheck.run("Reply by email", checks)
else
- $stdout.puts 'Reply by email is disabled in config/gitlab.yml'
+ $stdout.puts "Reply by email is disabled in config/gitlab.yml"
end
end
end
diff --git a/lib/system_check/ldap_check.rb b/lib/system_check/ldap_check.rb
index 619fb3cccb8..45fd6285829 100644
--- a/lib/system_check/ldap_check.rb
+++ b/lib/system_check/ldap_check.rb
@@ -3,18 +3,18 @@
module SystemCheck
# Used by gitlab:ldap:check rake task
class LdapCheck < BaseCheck
- set_name 'LDAP:'
+ set_name "LDAP:"
def multi_check
if Gitlab::Auth::LDAP::Config.enabled?
# Only show up to 100 results because LDAP directories can be very big.
# This setting only affects the `rake gitlab:check` script.
- limit = ENV['LDAP_CHECK_LIMIT']
+ limit = ENV["LDAP_CHECK_LIMIT"]
limit = 100 if limit.blank?
check_ldap(limit)
else
- $stdout.puts 'LDAP is disabled in config/gitlab.yml'
+ $stdout.puts "LDAP is disabled in config/gitlab.yml"
end
end
@@ -32,7 +32,7 @@ module SystemCheck
$stdout.puts "LDAP users with access to your GitLab server (only showing the first #{limit} results)"
- users = adapter.users(adapter.config.uid, '*', limit)
+ users = adapter.users(adapter.config.uid, "*", limit)
users.each do |user|
$stdout.puts "\tDN: #{user.dn}\t #{adapter.config.uid}: #{user.uid}"
end
@@ -47,12 +47,12 @@ module SystemCheck
auth = adapter.config.has_auth?
message = if auth && adapter.ldap.bind
- 'Success'.color(:green)
- elsif auth
- 'Failed. Check `bind_dn` and `password` configuration values'.color(:red)
- else
- 'Anonymous. No `bind_dn` or `password` configured'.color(:yellow)
- end
+ "Success".color(:green)
+ elsif auth
+ "Failed. Check `bind_dn` and `password` configuration values".color(:red)
+ else
+ "Anonymous. No `bind_dn` or `password` configured".color(:yellow)
+ end
$stdout.puts "LDAP authentication... #{message}"
end
diff --git a/lib/system_check/orphans/namespace_check.rb b/lib/system_check/orphans/namespace_check.rb
index 53b2d8fd5b3..71bb4809a45 100644
--- a/lib/system_check/orphans/namespace_check.rb
+++ b/lib/system_check/orphans/namespace_check.rb
@@ -3,7 +3,7 @@
module SystemCheck
module Orphans
class NamespaceCheck < SystemCheck::BaseCheck
- set_name 'Orphaned namespaces:'
+ set_name "Orphaned namespaces:"
def multi_check
Gitlab::GitalyClient::StorageSettings.allow_disk_access do
@@ -36,14 +36,14 @@ module SystemCheck
def disk_namespaces(storage_path)
fetch_disk_namespaces(storage_path).each_with_object([]) do |namespace_path, result|
namespace = File.basename(namespace_path)
- next if namespace.eql?('@hashed')
+ next if namespace.eql?("@hashed")
result << namespace
end
end
def fetch_disk_namespaces(storage_path)
- Dir.glob(File.join(storage_path, '*'))
+ Dir.glob(File.join(storage_path, "*"))
end
def existing_namespaces
diff --git a/lib/system_check/orphans/repository_check.rb b/lib/system_check/orphans/repository_check.rb
index 33020417e95..c1b290486b0 100644
--- a/lib/system_check/orphans/repository_check.rb
+++ b/lib/system_check/orphans/repository_check.rb
@@ -3,7 +3,7 @@
module SystemCheck
module Orphans
class RepositoryCheck < SystemCheck::BaseCheck
- set_name 'Orphaned repositories:'
+ set_name "Orphaned repositories:"
def multi_check
Gitlab::GitalyClient::StorageSettings.allow_disk_access do
@@ -37,7 +37,7 @@ module SystemCheck
def disk_repositories(storage_path)
fetch_disk_namespaces(storage_path).each_with_object([]) do |namespace_path, result|
namespace = File.basename(namespace_path)
- next if namespace.eql?('@hashed')
+ next if namespace.eql?("@hashed")
fetch_disk_repositories(namespace_path).each do |repo|
result << "#{namespace}/#{File.basename(repo)}"
@@ -62,11 +62,11 @@ module SystemCheck
end
def fetch_disk_namespaces(storage_path)
- Dir.glob(File.join(storage_path, '*'))
+ Dir.glob(File.join(storage_path, "*"))
end
def fetch_disk_repositories(namespace_path)
- Dir.glob(File.join(namespace_path, '*'))
+ Dir.glob(File.join(namespace_path, "*"))
end
end
end
diff --git a/lib/system_check/rake_task/app_task.rb b/lib/system_check/rake_task/app_task.rb
index cc32feb8604..3dba8800139 100644
--- a/lib/system_check/rake_task/app_task.rb
+++ b/lib/system_check/rake_task/app_task.rb
@@ -7,7 +7,7 @@ module SystemCheck
extend RakeTaskHelpers
def self.name
- 'GitLab App'
+ "GitLab App"
end
def self.checks
@@ -30,7 +30,7 @@ module SystemCheck
SystemCheck::App::RubyVersionCheck,
SystemCheck::App::GitVersionCheck,
SystemCheck::App::GitUserDefaultSSHConfigCheck,
- SystemCheck::App::ActiveUsersCheck
+ SystemCheck::App::ActiveUsersCheck,
]
end
end
diff --git a/lib/system_check/rake_task/gitaly_task.rb b/lib/system_check/rake_task/gitaly_task.rb
index 0c3f694f98a..cf7ac292445 100644
--- a/lib/system_check/rake_task/gitaly_task.rb
+++ b/lib/system_check/rake_task/gitaly_task.rb
@@ -7,7 +7,7 @@ module SystemCheck
extend RakeTaskHelpers
def self.name
- 'Gitaly'
+ "Gitaly"
end
def self.checks
diff --git a/lib/system_check/rake_task/gitlab_shell_task.rb b/lib/system_check/rake_task/gitlab_shell_task.rb
index 120e984c68b..453962260cb 100644
--- a/lib/system_check/rake_task/gitlab_shell_task.rb
+++ b/lib/system_check/rake_task/gitlab_shell_task.rb
@@ -7,7 +7,7 @@ module SystemCheck
extend RakeTaskHelpers
def self.name
- 'GitLab Shell'
+ "GitLab Shell"
end
def self.checks
diff --git a/lib/system_check/rake_task/gitlab_task.rb b/lib/system_check/rake_task/gitlab_task.rb
index 7ff36fd6eb5..6001d72f643 100644
--- a/lib/system_check/rake_task/gitlab_task.rb
+++ b/lib/system_check/rake_task/gitlab_task.rb
@@ -7,7 +7,7 @@ module SystemCheck
extend RakeTaskHelpers
def self.name
- 'GitLab'
+ "GitLab"
end
def self.manual_run_checks!
@@ -25,7 +25,7 @@ module SystemCheck
SystemCheck::RakeTask::SidekiqTask,
SystemCheck::RakeTask::IncomingEmailTask,
SystemCheck::RakeTask::LdapTask,
- SystemCheck::RakeTask::AppTask
+ SystemCheck::RakeTask::AppTask,
]
end
end
diff --git a/lib/system_check/rake_task/incoming_email_task.rb b/lib/system_check/rake_task/incoming_email_task.rb
index c296c46feab..562367d63fa 100644
--- a/lib/system_check/rake_task/incoming_email_task.rb
+++ b/lib/system_check/rake_task/incoming_email_task.rb
@@ -7,7 +7,7 @@ module SystemCheck
extend RakeTaskHelpers
def self.name
- 'Incoming Email'
+ "Incoming Email"
end
def self.checks
diff --git a/lib/system_check/rake_task/ldap_task.rb b/lib/system_check/rake_task/ldap_task.rb
index 03a180b9dfb..10e85da0c1f 100644
--- a/lib/system_check/rake_task/ldap_task.rb
+++ b/lib/system_check/rake_task/ldap_task.rb
@@ -7,7 +7,7 @@ module SystemCheck
extend RakeTaskHelpers
def self.name
- 'LDAP'
+ "LDAP"
end
def self.checks
diff --git a/lib/system_check/rake_task/orphans/namespace_task.rb b/lib/system_check/rake_task/orphans/namespace_task.rb
index 2822da45bc1..20a321ef4df 100644
--- a/lib/system_check/rake_task/orphans/namespace_task.rb
+++ b/lib/system_check/rake_task/orphans/namespace_task.rb
@@ -8,7 +8,7 @@ module SystemCheck
extend RakeTaskHelpers
def self.name
- 'Orphans'
+ "Orphans"
end
def self.checks
diff --git a/lib/system_check/rake_task/orphans/repository_task.rb b/lib/system_check/rake_task/orphans/repository_task.rb
index f14b3af22e8..8eb84c707da 100644
--- a/lib/system_check/rake_task/orphans/repository_task.rb
+++ b/lib/system_check/rake_task/orphans/repository_task.rb
@@ -8,7 +8,7 @@ module SystemCheck
extend RakeTaskHelpers
def self.name
- 'Orphans'
+ "Orphans"
end
def self.checks
diff --git a/lib/system_check/rake_task/orphans_task.rb b/lib/system_check/rake_task/orphans_task.rb
index 31f8ede25e0..5677e4e21a8 100644
--- a/lib/system_check/rake_task/orphans_task.rb
+++ b/lib/system_check/rake_task/orphans_task.rb
@@ -7,13 +7,13 @@ module SystemCheck
extend RakeTaskHelpers
def self.name
- 'Orphans'
+ "Orphans"
end
def self.checks
[
SystemCheck::Orphans::NamespaceCheck,
- SystemCheck::Orphans::RepositoryCheck
+ SystemCheck::Orphans::RepositoryCheck,
]
end
end
diff --git a/lib/system_check/rake_task/rake_task_helpers.rb b/lib/system_check/rake_task/rake_task_helpers.rb
index 95f2a34a719..0c4b3967168 100644
--- a/lib/system_check/rake_task/rake_task_helpers.rb
+++ b/lib/system_check/rake_task/rake_task_helpers.rb
@@ -9,7 +9,7 @@ module SystemCheck
def run!
warn_user_is_not_gitlab
- if self.respond_to?(:manual_run_checks!)
+ if respond_to?(:manual_run_checks!)
manual_run_checks!
else
run_checks!
diff --git a/lib/system_check/rake_task/sidekiq_task.rb b/lib/system_check/rake_task/sidekiq_task.rb
index 3ccf009d4b9..5c3af5e1a2c 100644
--- a/lib/system_check/rake_task/sidekiq_task.rb
+++ b/lib/system_check/rake_task/sidekiq_task.rb
@@ -7,7 +7,7 @@ module SystemCheck
extend RakeTaskHelpers
def self.name
- 'Sidekiq'
+ "Sidekiq"
end
def self.checks
diff --git a/lib/system_check/sidekiq_check.rb b/lib/system_check/sidekiq_check.rb
index 2f5fc2cea89..f7d1e7bf172 100644
--- a/lib/system_check/sidekiq_check.rb
+++ b/lib/system_check/sidekiq_check.rb
@@ -3,7 +3,7 @@
module SystemCheck
# Used by gitlab:sidekiq:check rake task
class SidekiqCheck < BaseCheck
- set_name 'Sidekiq:'
+ set_name "Sidekiq:"
def multi_check
check_sidekiq_running
@@ -34,24 +34,24 @@ module SystemCheck
process_count = sidekiq_process_count
return if process_count.zero?
- $stdout.print 'Number of Sidekiq processes ... '
+ $stdout.print "Number of Sidekiq processes ... "
if process_count == 1
- $stdout.puts '1'.color(:green)
+ $stdout.puts "1".color(:green)
else
- $stdout.puts "#{process_count}".color(:red)
+ $stdout.puts process_count.to_s.color(:red)
try_fixing_it(
- 'sudo service gitlab stop',
+ "sudo service gitlab stop",
"sudo pkill -u #{gitlab_user} -f sidekiq",
"sleep 10 && sudo pkill -9 -u #{gitlab_user} -f sidekiq",
- 'sudo service gitlab start'
+ "sudo service gitlab start"
)
fix_and_rerun
end
end
def sidekiq_process_count
- ps_ux, _ = Gitlab::Popen.popen(%w(ps uxww))
+ ps_ux, _ = Gitlab::Popen.popen(%w[ps uxww])
ps_ux.scan(/sidekiq \d+\.\d+\.\d+/).count
end
end
diff --git a/lib/system_check/simple_executor.rb b/lib/system_check/simple_executor.rb
index 11818ae54f8..0801e4e0d9b 100644
--- a/lib/system_check/simple_executor.rb
+++ b/lib/system_check/simple_executor.rb
@@ -67,7 +67,7 @@ module SystemCheck
print_check_failure(check_klass)
if check.can_repair?
- $stdout.print 'Trying to fix error automatically. ...'
+ $stdout.print "Trying to fix error automatically. ..."
if check.repair!
print_success
@@ -79,7 +79,7 @@ module SystemCheck
check.show_error
end
- rescue StandardError => e
+ rescue => e
$stdout.puts "Exception: #{e.message}".color(:red)
end
@@ -98,11 +98,11 @@ module SystemCheck
end
def print_success
- $stdout.puts 'Success'.color(:green)
+ $stdout.puts "Success".color(:green)
end
def print_failure
- $stdout.puts 'Failed'.color(:red)
+ $stdout.puts "Failed".color(:red)
end
# Prints header content for the series of checks to be executed for this component
@@ -110,16 +110,16 @@ module SystemCheck
# @param [String] component name of the component relative to the checks being executed
def start_checking(component)
$stdout.puts "Checking #{component.color(:yellow)} ..."
- $stdout.puts ''
+ $stdout.puts ""
end
# Prints footer content for the series of checks executed for this component
#
# @param [String] component name of the component relative to the checks being executed
def finished_checking(component)
- $stdout.puts ''
- $stdout.puts "Checking #{component.color(:yellow)} ... #{'Finished'.color(:green)}"
- $stdout.puts ''
+ $stdout.puts ""
+ $stdout.puts "Checking #{component.color(:yellow)} ... #{"Finished".color(:green)}"
+ $stdout.puts ""
end
end
end
diff --git a/lib/tasks/brakeman.rake b/lib/tasks/brakeman.rake
index 2301ec9b228..284b077f1d3 100644
--- a/lib/tasks/brakeman.rake
+++ b/lib/tasks/brakeman.rake
@@ -1,11 +1,11 @@
-desc 'Security check via brakeman'
+desc "Security check via brakeman"
task :brakeman do
# We get 0 warnings at level 'w3' but we would like to reach 'w2'. Merge
# requests are welcome!
- if system(*%w(brakeman --no-progress --skip-files lib/backup/repository.rb -w3 -z))
- puts 'Security check succeed'
+ if system("brakeman", "--no-progress", "--skip-files", "lib/backup/repository.rb", "-w3", "-z")
+ puts "Security check succeed"
else
- puts 'Security check failed'
+ puts "Security check failed"
exit 1
end
end
diff --git a/lib/tasks/cache.rake b/lib/tasks/cache.rake
index cb4d5abffbc..3b2cae9eef5 100644
--- a/lib/tasks/cache.rake
+++ b/lib/tasks/cache.rake
@@ -1,7 +1,7 @@
namespace :cache do
namespace :clear do
REDIS_CLEAR_BATCH_SIZE = 1000 # There seems to be no speedup when pushing beyond 1,000
- REDIS_SCAN_START_STOP = '0'.freeze # Magic value, see http://redis.io/commands/scan
+ REDIS_SCAN_START_STOP = "0".freeze # Magic value, see http://redis.io/commands/scan
desc "GitLab | Clear redis cache"
task redis: :environment do
@@ -29,5 +29,5 @@ namespace :cache do
task all: [:redis]
end
- task clear: 'cache:clear:redis'
+ task clear: "cache:clear:redis"
end
diff --git a/lib/tasks/ci/cleanup.rake b/lib/tasks/ci/cleanup.rake
index 2f4d11bd942..4ae3754f3ef 100644
--- a/lib/tasks/ci/cleanup.rake
+++ b/lib/tasks/ci/cleanup.rake
@@ -2,7 +2,7 @@ namespace :ci do
namespace :cleanup do
desc "GitLab CI | Clean running builds"
task builds: :environment do
- Ci::Build.running.update_all(status: 'canceled')
+ Ci::Build.running.update_all(status: "canceled")
end
end
end
diff --git a/lib/tasks/config_lint.rake b/lib/tasks/config_lint.rake
index ddbcf1e1eb8..6ebe4374378 100644
--- a/lib/tasks/config_lint.rake
+++ b/lib/tasks/config_lint.rake
@@ -1,8 +1,8 @@
module ConfigLint
def self.run(files)
- failures = files.reject do |file|
+ failures = files.reject { |file|
yield(file)
- end
+ }
if failures.present?
puts failures
@@ -14,12 +14,12 @@ end
desc "Checks syntax for shell scripts and nginx config files in 'lib/support/'"
task :config_lint do
shell_scripts = [
- 'lib/support/init.d/gitlab',
- 'lib/support/init.d/gitlab.default.example',
- 'lib/support/deploy/deploy.sh'
+ "lib/support/init.d/gitlab",
+ "lib/support/init.d/gitlab.default.example",
+ "lib/support/deploy/deploy.sh",
]
ConfigLint.run(shell_scripts) do |file|
- Kernel.system('bash', '-n', file)
+ Kernel.system("bash", "-n", file)
end
end
diff --git a/lib/tasks/dev.rake b/lib/tasks/dev.rake
index b1db4dc94a6..7b4d55ce9a5 100644
--- a/lib/tasks/dev.rake
+++ b/lib/tasks/dev.rake
@@ -3,7 +3,7 @@ task dev: ["dev:setup"]
namespace :dev do
desc "GitLab | Setup developer environment (db, fixtures)"
task setup: :environment do
- ENV['force'] = 'yes'
+ ENV["force"] = "yes"
Rake::Task["gitlab:setup"].invoke
Rake::Task["gitlab:shell:setup"].invoke
end
diff --git a/lib/tasks/downtime_check.rake b/lib/tasks/downtime_check.rake
index 557f4fef10b..b55882a3973 100644
--- a/lib/tasks/downtime_check.rake
+++ b/lib/tasks/downtime_check.rake
@@ -1,12 +1,12 @@
-desc 'Checks if migrations in a branch require downtime'
+desc "Checks if migrations in a branch require downtime"
task downtime_check: :environment do
repo = if defined?(Gitlab::License)
- 'gitlab-ee'
- else
- 'gitlab-ce'
- end
+ "gitlab-ee"
+ else
+ "gitlab-ce"
+ end
`git fetch https://gitlab.com/gitlab-org/#{repo}.git --depth 1`
- Rake::Task['gitlab:db:downtime_check'].invoke('FETCH_HEAD')
+ Rake::Task["gitlab:db:downtime_check"].invoke("FETCH_HEAD")
end
diff --git a/lib/tasks/ee_compat_check.rake b/lib/tasks/ee_compat_check.rake
index f494fa5c5c2..e9f88fad326 100644
--- a/lib/tasks/ee_compat_check.rake
+++ b/lib/tasks/ee_compat_check.rake
@@ -1,4 +1,4 @@
-desc 'Checks if the branch would apply cleanly to EE'
+desc "Checks if the branch would apply cleanly to EE"
task ee_compat_check: :environment do
- Rake::Task['gitlab:dev:ee_compat_check'].invoke
+ Rake::Task["gitlab:dev:ee_compat_check"].invoke
end
diff --git a/lib/tasks/eslint.rake b/lib/tasks/eslint.rake
index 51f5d768102..49d2a8cd821 100644
--- a/lib/tasks/eslint.rake
+++ b/lib/tasks/eslint.rake
@@ -1,8 +1,8 @@
unless Rails.env.production?
desc "GitLab | Run ESLint"
- task eslint: ['yarn:check'] do
- unless system('yarn run eslint')
- abort('rake eslint failed')
+ task eslint: ["yarn:check"] do
+ unless system("yarn run eslint")
+ abort("rake eslint failed")
end
end
end
diff --git a/lib/tasks/gemojione.rake b/lib/tasks/gemojione.rake
index 560a52053d8..e7fc46be9b3 100644
--- a/lib/tasks/gemojione.rake
+++ b/lib/tasks/gemojione.rake
@@ -1,34 +1,34 @@
namespace :gemojione do
- desc 'Generates Emoji SHA256 digests'
+ desc "Generates Emoji SHA256 digests"
- task aliases: ['yarn:check', 'environment'] do
- require 'json'
+ task aliases: ["yarn:check", "environment"] do
+ require "json"
aliases = {}
- index_file = File.join(Rails.root, 'fixtures', 'emojis', 'index.json')
+ index_file = File.join(Rails.root, "fixtures", "emojis", "index.json")
index = JSON.parse(File.read(index_file))
index.each_pair do |key, data|
- data['aliases'].each do |a|
- a.tr!(':', '')
+ data["aliases"].each do |a|
+ a.tr!(":", "")
aliases[a] = key
end
end
- out = File.join(Rails.root, 'fixtures', 'emojis', 'aliases.json')
- File.open(out, 'w') do |handle|
- handle.write(JSON.pretty_generate(aliases, indent: ' ', space: '', space_before: ''))
+ out = File.join(Rails.root, "fixtures", "emojis", "aliases.json")
+ File.open(out, "w") do |handle|
+ handle.write(JSON.pretty_generate(aliases, indent: " ", space: "", space_before: ""))
end
end
- task digests: ['yarn:check', 'environment'] do
- require 'digest/sha2'
- require 'json'
+ task digests: ["yarn:check", "environment"] do
+ require "digest/sha2"
+ require "json"
# We don't have `node_modules` available in built versions of GitLab
- FileUtils.cp_r(Rails.root.join('node_modules', 'emoji-unicode-version', 'emoji-unicode-version-map.json'), File.join(Rails.root, 'fixtures', 'emojis'))
+ FileUtils.cp_r(Rails.root.join("node_modules", "emoji-unicode-version", "emoji-unicode-version-map.json"), File.join(Rails.root, "fixtures", "emojis"))
dir = Gemojione.images_path
resultant_emoji_map = {}
@@ -36,28 +36,28 @@ namespace :gemojione do
Gitlab::Emoji.emojis.each do |name, emoji_hash|
# Ignore aliases
unless Gitlab::Emoji.emojis_aliases.key?(name)
- fpath = File.join(dir, "#{emoji_hash['unicode']}.png")
+ fpath = File.join(dir, "#{emoji_hash["unicode"]}.png")
hash_digest = Digest::SHA256.file(fpath).hexdigest
- category = emoji_hash['category']
- if name == 'gay_pride_flag'
- category = 'flags'
+ category = emoji_hash["category"]
+ if name == "gay_pride_flag"
+ category = "flags"
end
entry = {
category: category,
- moji: emoji_hash['moji'],
- description: emoji_hash['description'],
+ moji: emoji_hash["moji"],
+ description: emoji_hash["description"],
unicodeVersion: Gitlab::Emoji.emoji_unicode_version(name),
- digest: hash_digest
+ digest: hash_digest,
}
resultant_emoji_map[name] = entry
end
end
- out = File.join(Rails.root, 'fixtures', 'emojis', 'digests.json')
- File.open(out, 'w') do |handle|
+ out = File.join(Rails.root, "fixtures", "emojis", "digests.json")
+ File.open(out, "w") do |handle|
handle.write(JSON.pretty_generate(resultant_emoji_map))
end
end
@@ -70,8 +70,8 @@ namespace :gemojione do
# occasionally, such as when new Emojis are added to Gemojione.
task sprite: :environment do
begin
- require 'sprite_factory'
- require 'rmagick'
+ require "sprite_factory"
+ require "rmagick"
rescue LoadError
# noop
end
@@ -91,22 +91,22 @@ namespace :gemojione do
Gitlab::Emoji.emojis.each do |name, emoji_hash|
# Ignore aliases
unless Gitlab::Emoji.emojis_aliases.key?(name)
- emoji_unicode_string_to_name_map[emoji_hash['unicode']] = name
+ emoji_unicode_string_to_name_map[emoji_hash["unicode"]] = name
end
end
# Copy the Gemojione assets to the temporary folder for renaming
emoji_dir = "app/assets/images/emoji"
FileUtils.rm_rf(emoji_dir)
- FileUtils.mkdir_p(emoji_dir, mode: 0700)
- FileUtils.cp_r(File.join(Gemojione.images_path, '.'), emoji_dir)
+ FileUtils.mkdir_p(emoji_dir, mode: 0o700)
+ FileUtils.cp_r(File.join(Gemojione.images_path, "."), emoji_dir)
Dir[File.join(emoji_dir, "**/*.png")].each do |png|
image_path = png
rename_to_named_emoji_image!(emoji_unicode_string_to_name_map, image_path)
end
Dir.mktmpdir do |tmpdir|
- FileUtils.cp_r(File.join(emoji_dir, '.'), tmpdir)
+ FileUtils.cp_r(File.join(emoji_dir, "."), tmpdir)
Dir.chdir(tmpdir) do
Dir["**/*.png"].each do |png|
@@ -115,28 +115,28 @@ namespace :gemojione do
end
end
- style_path = Rails.root.join(*%w(app assets stylesheets framework emoji_sprites.scss))
+ style_path = Rails.root.join("app", "assets", "stylesheets", "framework", "emoji_sprites.scss")
# Combine the resized assets into a packed sprite and re-generate the SCSS
SpriteFactory.cssurl = "image-url('$IMAGE')"
SpriteFactory.run!(tmpdir, {
output_style: style_path,
output_image: "app/assets/images/emoji.png",
- selector: '.emoji-',
- style: :scss,
- nocomments: true,
- pngcrush: true,
- layout: :packed
+ selector: ".emoji-",
+ style: :scss,
+ nocomments: true,
+ pngcrush: true,
+ layout: :packed,
})
# SpriteFactory's SCSS is a bit too verbose for our purposes here, so
# let's simplify it
- system(%Q(sed -i '' "s/width: #{SIZE}px; height: #{SIZE}px; background: image-url('emoji.png')/background-position:/" #{style_path}))
- system(%Q(sed -i '' "s/ no-repeat//" #{style_path}))
- system(%Q(sed -i '' "s/ 0px/ 0/g" #{style_path}))
+ system(%(sed -i '' "s/width: #{SIZE}px; height: #{SIZE}px; background: image-url('emoji.png')/background-position:/" #{style_path}))
+ system(%(sed -i '' "s/ no-repeat//" #{style_path}))
+ system(%(sed -i '' "s/ 0px/ 0/g" #{style_path}))
# Append a generic rule that applies to all Emojis
- File.open(style_path, 'a') do |f|
+ File.open(style_path, "a") do |f|
f.puts
f.puts <<-CSS.strip_heredoc
.emoji-icon {
@@ -164,7 +164,7 @@ namespace :gemojione do
# Now do it again but for Retina
Dir.mktmpdir do |tmpdir|
# Copy the Gemojione assets to the temporary folder for resizing
- FileUtils.cp_r(File.join(emoji_dir, '.'), tmpdir)
+ FileUtils.cp_r(File.join(emoji_dir, "."), tmpdir)
Dir.chdir(tmpdir) do
Dir["**/*.png"].each do |png|
@@ -176,10 +176,10 @@ namespace :gemojione do
# Combine the resized assets into a packed sprite and re-generate the SCSS
SpriteFactory.run!(tmpdir, {
output_image: "app/assets/images/emoji@2x.png",
- style: false,
- nocomments: true,
- pngcrush: true,
- layout: :packed
+ style: false,
+ nocomments: true,
+ pngcrush: true,
+ layout: :packed,
})
end
end
diff --git a/lib/tasks/gettext.rake b/lib/tasks/gettext.rake
index 2235a6ba194..81754bb9eeb 100644
--- a/lib/tasks/gettext.rake
+++ b/lib/tasks/gettext.rake
@@ -4,8 +4,8 @@ namespace :gettext do
# Customize list of translatable files
# See: https://github.com/grosser/gettext_i18n_rails#customizing-list-of-translatable-files
def files_to_translate
- folders = %W(ee app lib config #{locale_path}).join(',')
- exts = %w(rb erb haml slim rhtml js jsx vue handlebars hbs mustache).join(',')
+ folders = %W[ee app lib config #{locale_path}].join(",")
+ exts = %w[rb erb haml slim rhtml js jsx vue handlebars hbs mustache].join(",")
Dir.glob(
"{#{folders}}/**/*.{#{exts}}"
@@ -14,55 +14,55 @@ namespace :gettext do
task :compile do
# See: https://gitlab.com/gitlab-org/gitlab-ce/issues/33014#note_31218998
- FileUtils.touch(File.join(Rails.root, 'locale/gitlab.pot'))
+ FileUtils.touch(File.join(Rails.root, "locale/gitlab.pot"))
- Rake::Task['gettext:po_to_json'].invoke
+ Rake::Task["gettext:po_to_json"].invoke
end
task :regenerate do
- pot_file = 'locale/gitlab.pot'
+ pot_file = "locale/gitlab.pot"
# Remove all translated files, this speeds up finding
- FileUtils.rm Dir['locale/**/gitlab.*']
+ FileUtils.rm Dir["locale/**/gitlab.*"]
# remove the `pot` file to ensure it's completely regenerated
FileUtils.rm_f pot_file
- Rake::Task['gettext:find'].invoke
+ Rake::Task["gettext:find"].invoke
# leave only the required changes.
`git checkout -- locale/*/gitlab.po`
# Remove timestamps from the pot file
pot_content = File.read pot_file
- pot_content.gsub!(/^"POT?\-(?:Creation|Revision)\-Date\:.*\n/, '')
+ pot_content.gsub!(/^"POT?\-(?:Creation|Revision)\-Date\:.*\n/, "")
File.write pot_file, pot_content
puts <<~MSG
- All done. Please commit the changes to `locale/gitlab.pot`.
+ All done. Please commit the changes to `locale/gitlab.pot`.
MSG
end
- desc 'Lint all po files in `locale/'
+ desc "Lint all po files in `locale/"
task lint: :environment do
- require 'simple_po_parser'
- require 'gitlab/utils'
+ require "simple_po_parser"
+ require "gitlab/utils"
FastGettext.silence_errors
- files = Dir.glob(Rails.root.join('locale/*/gitlab.po'))
+ files = Dir.glob(Rails.root.join("locale/*/gitlab.po"))
- linters = files.map do |file|
+ linters = files.map { |file|
locale = File.basename(File.dirname(file))
Gitlab::I18n::PoLinter.new(file, locale)
- end
+ }
- pot_file = Rails.root.join('locale/gitlab.pot')
+ pot_file = Rails.root.join("locale/gitlab.pot")
linters.unshift(Gitlab::I18n::PoLinter.new(pot_file))
failed_linters = linters.select { |linter| linter.errors.any? }
if failed_linters.empty?
- puts 'All PO files are valid.'
+ puts "All PO files are valid."
else
failed_linters.each do |linter|
report_errors_for_file(linter.po_path, linter.errors)
@@ -73,17 +73,17 @@ namespace :gettext do
end
task :updated_check do
- pot_file = 'locale/gitlab.pot'
+ pot_file = "locale/gitlab.pot"
# Removing all pre-translated files speeds up `gettext:find` as the
# files don't need to be merged.
# Having `LC_MESSAGES/gitlab.mo files present also confuses the output.
- FileUtils.rm Dir['locale/**/gitlab.*']
+ FileUtils.rm Dir["locale/**/gitlab.*"]
FileUtils.rm_f pot_file
# `gettext:find` writes touches to temp files to `stderr` which would cause
# `static-analysis` to report failures. We can ignore these.
silence_stderr do
- Rake::Task['gettext:find'].invoke
+ Rake::Task["gettext:find"].invoke
end
pot_diff = `git diff -- #{pot_file} | grep -E '^(\\+|-)msgid'`.strip
@@ -112,8 +112,8 @@ namespace :gettext do
errors_for_file.each do |message_id, errors|
puts " #{message_id}"
errors.each do |error|
- spaces = ' ' * 4
- error = error.lines.join("#{spaces}")
+ spaces = " " * 4
+ error = error.lines.join(spaces.to_s)
puts "#{spaces}#{error}"
end
end
diff --git a/lib/tasks/gitlab/artifacts/check.rake b/lib/tasks/gitlab/artifacts/check.rake
index a105261ed51..662204b650c 100644
--- a/lib/tasks/gitlab/artifacts/check.rake
+++ b/lib/tasks/gitlab/artifacts/check.rake
@@ -1,6 +1,6 @@
namespace :gitlab do
namespace :artifacts do
- desc 'GitLab | Artifacts | Check integrity of uploaded job artifacts'
+ desc "GitLab | Artifacts | Check integrity of uploaded job artifacts"
task check: :environment do
Gitlab::Verify::RakeTask.run!(Gitlab::Verify::JobArtifacts)
end
diff --git a/lib/tasks/gitlab/artifacts/migrate.rake b/lib/tasks/gitlab/artifacts/migrate.rake
index e7634d2ed4f..3458d6ca5f5 100644
--- a/lib/tasks/gitlab/artifacts/migrate.rake
+++ b/lib/tasks/gitlab/artifacts/migrate.rake
@@ -1,24 +1,23 @@
-require 'logger'
-require 'resolv-replace'
+require "logger"
+require "resolv-replace"
desc "GitLab | Migrate files for artifacts to comply with new storage format"
namespace :gitlab do
namespace :artifacts do
task migrate: :environment do
logger = Logger.new(STDOUT)
- logger.info('Starting transfer of artifacts')
+ logger.info("Starting transfer of artifacts")
Ci::Build.joins(:project)
.with_artifacts_stored_locally
.find_each(batch_size: 10) do |build|
- begin
- build.artifacts_file.migrate!(ObjectStorage::Store::REMOTE)
- build.artifacts_metadata.migrate!(ObjectStorage::Store::REMOTE)
- logger.info("Transferred artifact ID #{build.id} with size #{build.artifacts_size} to object storage")
- rescue => e
- logger.error("Failed to transfer artifacts of #{build.id} with error: #{e.message}")
- end
+ build.artifacts_file.migrate!(ObjectStorage::Store::REMOTE)
+ build.artifacts_metadata.migrate!(ObjectStorage::Store::REMOTE)
+
+ logger.info("Transferred artifact ID #{build.id} with size #{build.artifacts_size} to object storage")
+ rescue => e
+ logger.error("Failed to transfer artifacts of #{build.id} with error: #{e.message}")
end
end
end
diff --git a/lib/tasks/gitlab/assets.rake b/lib/tasks/gitlab/assets.rake
index 7a42e4e92a0..9d425af8266 100644
--- a/lib/tasks/gitlab/assets.rake
+++ b/lib/tasks/gitlab/assets.rake
@@ -1,8 +1,8 @@
namespace :gitlab do
namespace :assets do
- desc 'GitLab | Assets | Compile all frontend assets'
+ desc "GitLab | Assets | Compile all frontend assets"
task :compile do
- require_dependency 'gitlab/task_helpers'
+ require_dependency "gitlab/task_helpers"
%w[
yarn:check
@@ -13,18 +13,18 @@ namespace :gitlab do
].each(&Gitlab::TaskHelpers.method(:invoke_and_time_task))
end
- desc 'GitLab | Assets | Clean up old compiled frontend assets'
- task clean: ['rake:assets:clean']
+ desc "GitLab | Assets | Clean up old compiled frontend assets"
+ task clean: ["rake:assets:clean"]
- desc 'GitLab | Assets | Remove all compiled frontend assets'
- task purge: ['rake:assets:clobber']
+ desc "GitLab | Assets | Remove all compiled frontend assets"
+ task purge: ["rake:assets:clobber"]
- desc 'GitLab | Assets | Uninstall frontend dependencies'
- task purge_modules: ['yarn:clobber']
+ desc "GitLab | Assets | Uninstall frontend dependencies"
+ task purge_modules: ["yarn:clobber"]
- desc 'GitLab | Assets | Fix all absolute url references in CSS'
+ desc "GitLab | Assets | Fix all absolute url references in CSS"
task :fix_urls do
- css_files = Dir['public/assets/*.css']
+ css_files = Dir["public/assets/*.css"]
css_files.each do |file|
# replace url(/assets/*) with url(./*)
puts "Fixing #{file}"
@@ -38,7 +38,7 @@ namespace :gitlab do
FileUtils.rm(gzip)
mtime = File.stat(file).mtime
- File.open(gzip, 'wb+') do |f|
+ File.open(gzip, "wb+") do |f|
gz = Zlib::GzipWriter.new(f, Zlib::BEST_COMPRESSION)
gz.mtime = mtime
gz.write IO.binread(file)
diff --git a/lib/tasks/gitlab/backup.rake b/lib/tasks/gitlab/backup.rake
index 3a1a36e36ce..1204dd2195c 100644
--- a/lib/tasks/gitlab/backup.rake
+++ b/lib/tasks/gitlab/backup.rake
@@ -1,4 +1,4 @@
-require 'active_record/fixtures'
+require "active_record/fixtures"
namespace :gitlab do
namespace :backup do
@@ -23,16 +23,16 @@ namespace :gitlab do
end
# Restore backup of GitLab system
- desc 'GitLab | Restore a previously created backup'
+ desc "GitLab | Restore a previously created backup"
task restore: :gitlab_environment do
warn_user_is_not_gitlab
backup = Backup::Manager.new(progress)
backup.unpack
- unless backup.skipped?('db')
+ unless backup.skipped?("db")
begin
- unless ENV['force'] == 'yes'
+ unless ENV["force"] == "yes"
warning = <<-MSG.strip_heredoc
Before restoring the database, we will remove all existing
tables to avoid future upgrade problems. Be aware that if you have
@@ -41,31 +41,31 @@ namespace :gitlab do
MSG
puts warning.color(:red)
ask_to_continue
- puts 'Removing all tables. Press `Ctrl-C` within 5 seconds to abort'.color(:yellow)
+ puts "Removing all tables. Press `Ctrl-C` within 5 seconds to abort".color(:yellow)
sleep(5)
end
# Drop all tables Load the schema to ensure we don't have any newer tables
# hanging out from a failed upgrade
- puts_time 'Cleaning the database ... '.color(:blue)
- Rake::Task['gitlab:db:drop_tables'].invoke
- puts_time 'done'.color(:green)
- Rake::Task['gitlab:backup:db:restore'].invoke
+ puts_time "Cleaning the database ... ".color(:blue)
+ Rake::Task["gitlab:db:drop_tables"].invoke
+ puts_time "done".color(:green)
+ Rake::Task["gitlab:backup:db:restore"].invoke
rescue Gitlab::TaskAbortedByUserError
puts "Quitting...".color(:red)
exit 1
end
end
- Rake::Task['gitlab:backup:repo:restore'].invoke unless backup.skipped?('repositories')
- Rake::Task['gitlab:backup:uploads:restore'].invoke unless backup.skipped?('uploads')
- Rake::Task['gitlab:backup:builds:restore'].invoke unless backup.skipped?('builds')
- Rake::Task['gitlab:backup:artifacts:restore'].invoke unless backup.skipped?('artifacts')
- Rake::Task["gitlab:backup:pages:restore"].invoke unless backup.skipped?('pages')
- Rake::Task['gitlab:backup:lfs:restore'].invoke unless backup.skipped?('lfs')
- Rake::Task['gitlab:backup:registry:restore'].invoke unless backup.skipped?('registry')
- Rake::Task['gitlab:shell:setup'].invoke
- Rake::Task['cache:clear'].invoke
+ Rake::Task["gitlab:backup:repo:restore"].invoke unless backup.skipped?("repositories")
+ Rake::Task["gitlab:backup:uploads:restore"].invoke unless backup.skipped?("uploads")
+ Rake::Task["gitlab:backup:builds:restore"].invoke unless backup.skipped?("builds")
+ Rake::Task["gitlab:backup:artifacts:restore"].invoke unless backup.skipped?("artifacts")
+ Rake::Task["gitlab:backup:pages:restore"].invoke unless backup.skipped?("pages")
+ Rake::Task["gitlab:backup:lfs:restore"].invoke unless backup.skipped?("lfs")
+ Rake::Task["gitlab:backup:registry:restore"].invoke unless backup.skipped?("registry")
+ Rake::Task["gitlab:shell:setup"].invoke
+ Rake::Task["cache:clear"].invoke
backup.cleanup
end
@@ -74,7 +74,7 @@ namespace :gitlab do
task create: :gitlab_environment do
puts_time "Dumping repositories ...".color(:blue)
- if ENV["SKIP"] && ENV["SKIP"].include?("repositories")
+ if ENV["SKIP"]&.include?("repositories")
puts_time "[SKIPPED]".color(:cyan)
else
Backup::Repository.new(progress).dump
@@ -93,7 +93,7 @@ namespace :gitlab do
task create: :gitlab_environment do
puts_time "Dumping database ... ".color(:blue)
- if ENV["SKIP"] && ENV["SKIP"].include?("db")
+ if ENV["SKIP"]&.include?("db")
puts_time "[SKIPPED]".color(:cyan)
else
Backup::Database.new(progress).dump
@@ -112,7 +112,7 @@ namespace :gitlab do
task create: :gitlab_environment do
puts_time "Dumping builds ... ".color(:blue)
- if ENV["SKIP"] && ENV["SKIP"].include?("builds")
+ if ENV["SKIP"]&.include?("builds")
puts_time "[SKIPPED]".color(:cyan)
else
Backup::Builds.new(progress).dump
@@ -131,7 +131,7 @@ namespace :gitlab do
task create: :gitlab_environment do
puts_time "Dumping uploads ... ".color(:blue)
- if ENV["SKIP"] && ENV["SKIP"].include?("uploads")
+ if ENV["SKIP"]&.include?("uploads")
puts_time "[SKIPPED]".color(:cyan)
else
Backup::Uploads.new(progress).dump
@@ -150,7 +150,7 @@ namespace :gitlab do
task create: :gitlab_environment do
puts_time "Dumping artifacts ... ".color(:blue)
- if ENV["SKIP"] && ENV["SKIP"].include?("artifacts")
+ if ENV["SKIP"]&.include?("artifacts")
puts_time "[SKIPPED]".color(:cyan)
else
Backup::Artifacts.new(progress).dump
@@ -169,7 +169,7 @@ namespace :gitlab do
task create: :gitlab_environment do
puts_time "Dumping pages ... ".color(:blue)
- if ENV["SKIP"] && ENV["SKIP"].include?("pages")
+ if ENV["SKIP"]&.include?("pages")
puts_time "[SKIPPED]".color(:cyan)
else
Backup::Pages.new(progress).dump
@@ -188,7 +188,7 @@ namespace :gitlab do
task create: :gitlab_environment do
puts_time "Dumping lfs objects ... ".color(:blue)
- if ENV["SKIP"] && ENV["SKIP"].include?("lfs")
+ if ENV["SKIP"]&.include?("lfs")
puts_time "[SKIPPED]".color(:cyan)
else
Backup::Lfs.new(progress).dump
@@ -208,7 +208,7 @@ namespace :gitlab do
puts_time "Dumping container registry images ... ".color(:blue)
if Gitlab.config.registry.enabled
- if ENV["SKIP"] && ENV["SKIP"].include?("registry")
+ if ENV["SKIP"]&.include?("registry")
puts_time "[SKIPPED]".color(:cyan)
else
Backup::Registry.new(progress).dump
@@ -236,10 +236,10 @@ namespace :gitlab do
end
def progress
- if ENV['CRON']
+ if ENV["CRON"]
# We need an object we can say 'puts' and 'print' to; let's use a
# StringIO.
- require 'stringio'
+ require "stringio"
StringIO.new
else
$stdout
diff --git a/lib/tasks/gitlab/check.rake b/lib/tasks/gitlab/check.rake
index b594f150c3b..365c8b674a1 100644
--- a/lib/tasks/gitlab/check.rake
+++ b/lib/tasks/gitlab/check.rake
@@ -1,11 +1,11 @@
namespace :gitlab do
- desc 'GitLab | Check the configuration of GitLab and its environment'
+ desc "GitLab | Check the configuration of GitLab and its environment"
task check: :gitlab_environment do
SystemCheck::RakeTask::GitlabTask.run!
end
namespace :app do
- desc 'GitLab | Check the configuration of the GitLab Rails app'
+ desc "GitLab | Check the configuration of the GitLab Rails app"
task check: :gitlab_environment do
SystemCheck::RakeTask::AppTask.run!
end
@@ -19,7 +19,7 @@ namespace :gitlab do
end
namespace :gitaly do
- desc 'GitLab | Check the health of Gitaly'
+ desc "GitLab | Check the health of Gitaly"
task check: :gitlab_environment do
SystemCheck::RakeTask::GitalyTask.run!
end
@@ -41,24 +41,24 @@ namespace :gitlab do
namespace :ldap do
task :check, [:limit] => :gitlab_environment do |_, args|
- ENV['LDAP_CHECK_LIMIT'] = args.limit if args.limit.present?
+ ENV["LDAP_CHECK_LIMIT"] = args.limit if args.limit.present?
SystemCheck::RakeTask::LdapTask.run!
end
end
namespace :orphans do
- desc 'Gitlab | Check for orphaned namespaces and repositories'
+ desc "Gitlab | Check for orphaned namespaces and repositories"
task check: :gitlab_environment do
SystemCheck::RakeTask::OrphansTask.run!
end
- desc 'GitLab | Check for orphaned namespaces in the repositories path'
+ desc "GitLab | Check for orphaned namespaces in the repositories path"
task check_namespaces: :gitlab_environment do
SystemCheck::RakeTask::Orphans::NamespaceTask.run!
end
- desc 'GitLab | Check for orphaned repositories in the repositories path'
+ desc "GitLab | Check for orphaned repositories in the repositories path"
task check_repositories: :gitlab_environment do
SystemCheck::RakeTask::Orphans::RepositoryTask.run!
end
diff --git a/lib/tasks/gitlab/cleanup.rake b/lib/tasks/gitlab/cleanup.rake
index 451ba651674..3d8b537ecc3 100644
--- a/lib/tasks/gitlab/cleanup.rake
+++ b/lib/tasks/gitlab/cleanup.rake
@@ -1,5 +1,6 @@
# frozen_string_literal: true
-require 'set'
+
+require "set"
namespace :gitlab do
namespace :cleanup do
@@ -12,7 +13,7 @@ namespace :gitlab do
all_dirs = Gitlab::GitalyClient::StorageService
.new(server.storage)
.list_directories(depth: 0)
- .reject { |dir| dir.ends_with?('.git') || namespaces.include?(File.basename(dir)) }
+ .reject { |dir| dir.ends_with?(".git") || namespaces.include?(File.basename(dir)) }
puts "Looking for directories to remove... "
all_dirs.each do |dir_path|
@@ -22,7 +23,7 @@ namespace :gitlab do
.remove(dir_path)
puts "Removed...#{dir_path}"
- rescue StandardError => e
+ rescue => e
puts "Cannot remove #{dir_path}: #{e.message}".color(:red)
end
else
@@ -45,7 +46,7 @@ namespace :gitlab do
.new(server.storage)
.list_directories
.each do |path|
- repo_with_namespace = path.chomp('.git').chomp('.wiki')
+ repo_with_namespace = path.chomp(".git").chomp(".wiki")
# TODO ignoring hashed repositories for now. But revisit to fully support
# possible orphaned hashed repos
@@ -53,13 +54,13 @@ namespace :gitlab do
next if Project.find_by_full_path(repo_with_namespace)
new_path = path + move_suffix
- puts path.inspect + ' -> ' + new_path.inspect
+ puts path.inspect + " -> " + new_path.inspect
begin
Gitlab::GitalyClient::NamespaceService
.new(server.storage)
.rename(path, new_path)
- rescue StandardError => e
+ rescue => e
puts "Error occured while moving the repository: #{e.message}".color(:red)
end
end
@@ -69,7 +70,7 @@ namespace :gitlab do
desc "GitLab | Cleanup | Block users that have been removed in LDAP"
task block_removed_ldap_users: :gitlab_environment do
warn_user_is_not_gitlab
- block_flag = ENV['BLOCK']
+ block_flag = ENV["BLOCK"]
User.find_each do |user|
next unless user.ldap_user?
@@ -105,7 +106,7 @@ namespace :gitlab do
end
end
- desc 'GitLab | Cleanup | Clean orphan remote upload files that do not exist in the db'
+ desc "GitLab | Cleanup | Clean orphan remote upload files that do not exist in the db"
task remote_upload_files: :environment do
cleaner = Gitlab::Cleanup::RemoteUploads.new(logger: logger)
cleaner.run!(dry_run: dry_run?)
@@ -116,23 +117,23 @@ namespace :gitlab do
end
def remove?
- ENV['REMOVE'] == 'true'
+ ENV["REMOVE"] == "true"
end
def dry_run?
- ENV['DRY_RUN'] != 'false'
+ ENV["DRY_RUN"] != "false"
end
def logger
return @logger if defined?(@logger)
@logger = if Rails.env.development? || Rails.env.production?
- Logger.new(STDOUT).tap do |stdout_logger|
- stdout_logger.extend(ActiveSupport::Logger.broadcast(Rails.logger))
- end
- else
- Rails.logger
- end
+ Logger.new(STDOUT).tap do |stdout_logger|
+ stdout_logger.extend(ActiveSupport::Logger.broadcast(Rails.logger))
+ end
+ else
+ Rails.logger
+ end
end
end
end
diff --git a/lib/tasks/gitlab/db.rake b/lib/tasks/gitlab/db.rake
index b94b21775ee..0dd6a5b5c29 100644
--- a/lib/tasks/gitlab/db.rake
+++ b/lib/tasks/gitlab/db.rake
@@ -1,6 +1,6 @@
namespace :gitlab do
namespace :db do
- desc 'GitLab | Manually insert schema migration version'
+ desc "GitLab | Manually insert schema migration version"
task :mark_migration_complete, [:version] => :environment do |_, args|
unless args[:version]
puts "Must specify a migration version as an argument".color(:red)
@@ -22,18 +22,18 @@ namespace :gitlab do
end
end
- desc 'Drop all tables'
+ desc "Drop all tables"
task drop_tables: :environment do
connection = ActiveRecord::Base.connection
# If MySQL, turn off foreign key checks
- connection.execute('SET FOREIGN_KEY_CHECKS=0') if Gitlab::Database.mysql?
+ connection.execute("SET FOREIGN_KEY_CHECKS=0") if Gitlab::Database.mysql?
tables = connection.data_sources
# Removes the entry from the array
- tables.delete 'schema_migrations'
+ tables.delete "schema_migrations"
# Truncate schema_migrations to ensure migrations re-run
- connection.execute('TRUNCATE schema_migrations') if connection.data_source_exists? 'schema_migrations'
+ connection.execute("TRUNCATE schema_migrations") if connection.data_source_exists? "schema_migrations"
# Drop tables with cascade to avoid dependent table errors
# PG: http://www.postgresql.org/docs/current/static/ddl-depend.html
@@ -42,28 +42,28 @@ namespace :gitlab do
tables.each { |t| connection.execute("DROP TABLE IF EXISTS #{connection.quote_table_name(t)} CASCADE") }
# If MySQL, re-enable foreign key checks
- connection.execute('SET FOREIGN_KEY_CHECKS=1') if Gitlab::Database.mysql?
+ connection.execute("SET FOREIGN_KEY_CHECKS=1") if Gitlab::Database.mysql?
end
- desc 'Configures the database by running migrate, or by loading the schema and seeding if needed'
+ desc "Configures the database by running migrate, or by loading the schema and seeding if needed"
task configure: :environment do
# Check if we have existing db tables
# The schema_migrations table will still exist if drop_tables was called
if ActiveRecord::Base.connection.tables.count > 1
- Rake::Task['db:migrate'].invoke
+ Rake::Task["db:migrate"].invoke
else
# Add post-migrate paths to ensure we mark all migrations as up
Gitlab::Database.add_post_migrate_path_to_rails(force: true)
- Rake::Task['db:schema:load'].invoke
- Rake::Task['db:seed_fu'].invoke
+ Rake::Task["db:schema:load"].invoke
+ Rake::Task["db:seed_fu"].invoke
end
end
- desc 'Checks if migrations require downtime or not'
+ desc "Checks if migrations require downtime or not"
task :downtime_check, [:ref] => :environment do |_, args|
- abort 'You must specify a Git reference to compare with' unless args[:ref]
+ abort "You must specify a Git reference to compare with" unless args[:ref]
- require 'shellwords'
+ require "shellwords"
ref = Shellwords.escape(args[:ref])
diff --git a/lib/tasks/gitlab/dev.rake b/lib/tasks/gitlab/dev.rake
index 77c28615856..64a7306724e 100644
--- a/lib/tasks/gitlab/dev.rake
+++ b/lib/tasks/gitlab/dev.rake
@@ -1,13 +1,13 @@
namespace :gitlab do
namespace :dev do
- desc 'Checks if the branch would apply cleanly to EE'
+ desc "Checks if the branch would apply cleanly to EE"
task :ee_compat_check, [:branch] => :environment do |_, args|
opts =
- if ENV['CI']
+ if ENV["CI"]
{
- ce_project_url: ENV['CI_PROJECT_URL'],
- branch: ENV['CI_COMMIT_REF_NAME'],
- job_id: ENV['CI_JOB_ID']
+ ce_project_url: ENV["CI_PROJECT_URL"],
+ branch: ENV["CI_COMMIT_REF_NAME"],
+ job_id: ENV["CI_JOB_ID"],
}
else
unless args[:branch]
@@ -18,7 +18,7 @@ namespace :gitlab do
args
end
- if File.basename(Rails.root) == 'gitlab-ee'
+ if File.basename(Rails.root) == "gitlab-ee"
puts "Skipping EE projects"
exit 0
elsif Gitlab::EeCompatCheck.new(opts || {}).check
diff --git a/lib/tasks/gitlab/exclusive_lease.rake b/lib/tasks/gitlab/exclusive_lease.rake
index 83722bf6d94..547d35f9310 100644
--- a/lib/tasks/gitlab/exclusive_lease.rake
+++ b/lib/tasks/gitlab/exclusive_lease.rake
@@ -1,9 +1,9 @@
namespace :gitlab do
namespace :exclusive_lease do
- desc 'GitLab | Clear existing exclusive leases for specified scope (default: *)'
+ desc "GitLab | Clear existing exclusive leases for specified scope (default: *)"
task :clear, [:scope] => [:environment] do |_, args|
args[:scope].nil? ? Gitlab::ExclusiveLease.reset_all! : Gitlab::ExclusiveLease.reset_all!(args[:scope])
- puts 'All exclusive lease entries were removed.'
+ puts "All exclusive lease entries were removed."
end
end
end
diff --git a/lib/tasks/gitlab/git.rake b/lib/tasks/gitlab/git.rake
index 8a53b51d4fe..2924d40d2ce 100644
--- a/lib/tasks/gitlab/git.rake
+++ b/lib/tasks/gitlab/git.rake
@@ -1,12 +1,11 @@
namespace :gitlab do
namespace :git do
- desc 'GitLab | Git | Check all repos integrity'
+ desc "GitLab | Git | Check all repos integrity"
task fsck: :gitlab_environment do
failures = []
Project.find_each(batch_size: 100) do |project|
begin
project.repository.fsck
-
rescue => e
failures << "#{project.full_path} on #{project.repository_storage}: #{e}"
end
diff --git a/lib/tasks/gitlab/gitaly.rake b/lib/tasks/gitlab/gitaly.rake
index 80de3d2ef51..c5e1d7084df 100644
--- a/lib/tasks/gitlab/gitaly.rake
+++ b/lib/tasks/gitlab/gitaly.rake
@@ -9,7 +9,7 @@ namespace :gitlab do
Usage: rake "gitlab:gitaly:install[/installation/dir,/storage/path]")
end
- args.with_defaults(repo: 'https://gitlab.com/gitlab-org/gitaly.git')
+ args.with_defaults(repo: "https://gitlab.com/gitlab-org/gitaly.git")
version = Gitlab::GitalyClient.expected_server_version
@@ -18,19 +18,20 @@ Usage: rake "gitlab:gitaly:install[/installation/dir,/storage/path]")
command = %w[/usr/bin/env -u RUBYOPT -u BUNDLE_GEMFILE]
_, status = Gitlab::Popen.popen(%w[which gmake])
- command << (status.zero? ? 'gmake' : 'make')
+ command << (status.zero? ? "gmake" : "make")
if Rails.env.test?
command.push(
- 'BUNDLE_FLAGS=--no-deployment',
- "BUNDLE_PATH=#{Bundler.bundle_path}")
+ "BUNDLE_FLAGS=--no-deployment",
+ "BUNDLE_PATH=#{Bundler.bundle_path}"
+ )
end
- storage_paths = { 'default' => args.storage_path }
+ storage_paths = {"default" => args.storage_path}
Gitlab::SetupHelper.create_gitaly_configuration(args.dir, storage_paths)
Dir.chdir(args.dir) do
# In CI we run scripts/gitaly-test-build instead of this command
- unless ENV['CI'].present?
+ unless ENV["CI"].present?
Bundler.with_original_env { run_command!(command) }
end
end
diff --git a/lib/tasks/gitlab/helpers.rake b/lib/tasks/gitlab/helpers.rake
index 14d1125a03d..5ca40df05cb 100644
--- a/lib/tasks/gitlab/helpers.rake
+++ b/lib/tasks/gitlab/helpers.rake
@@ -1,5 +1,5 @@
# Prevent StateMachine warnings from outputting during a cron task
-StateMachines::Machine.ignore_method_conflicts = true if ENV['CRON']
+StateMachines::Machine.ignore_method_conflicts = true if ENV["CRON"]
task gitlab_environment: :environment do
extend SystemCheck::Helpers
diff --git a/lib/tasks/gitlab/import.rake b/lib/tasks/gitlab/import.rake
index adfcc3cda22..a224515b63e 100644
--- a/lib/tasks/gitlab/import.rake
+++ b/lib/tasks/gitlab/import.rake
@@ -11,7 +11,7 @@ namespace :gitlab do
desc "GitLab | Import bare repositories from repositories -> storages into GitLab project instance"
task :repos, [:import_path] => :environment do |_t, args|
unless args.import_path
- puts 'Please specify an import path that contains the repositories'.color(:red)
+ puts "Please specify an import path that contains the repositories".color(:red)
exit 1
end
diff --git a/lib/tasks/gitlab/import_export.rake b/lib/tasks/gitlab/import_export.rake
index 900dbf7be24..f34c83aba7b 100644
--- a/lib/tasks/gitlab/import_export.rake
+++ b/lib/tasks/gitlab/import_export.rake
@@ -7,20 +7,20 @@ namespace :gitlab do
desc "GitLab | Display exported DB structure"
task data: :environment do
- puts YAML.load_file(Gitlab::ImportExport.config_file)['project_tree'].to_yaml(SortKeys: true)
+ puts YAML.load_file(Gitlab::ImportExport.config_file)["project_tree"].to_yaml(SortKeys: true)
end
- desc 'GitLab | Bumps the Import/Export version in fixtures and project templates'
+ desc "GitLab | Bumps the Import/Export version in fixtures and project templates"
task bump_version: :environment do
- archives = Dir['vendor/project_templates/*.tar.gz']
- archives.push('spec/features/projects/import_export/test_project_export.tar.gz')
+ archives = Dir["vendor/project_templates/*.tar.gz"]
+ archives.push("spec/features/projects/import_export/test_project_export.tar.gz")
archives.each do |archive|
raise ArgumentError unless File.exist?(archive)
Dir.mktmpdir do |tmp_dir|
system("tar -zxf #{archive} -C #{tmp_dir} > /dev/null")
- File.write(File.join(tmp_dir, 'VERSION'), Gitlab::ImportExport.version, mode: 'w')
+ File.write(File.join(tmp_dir, "VERSION"), Gitlab::ImportExport.version, mode: "w")
system("tar -zcvf #{archive} -C #{tmp_dir} . > /dev/null")
end
end
diff --git a/lib/tasks/gitlab/info.rake b/lib/tasks/gitlab/info.rake
index b8798fb3cfd..d3075d8282b 100644
--- a/lib/tasks/gitlab/info.rake
+++ b/lib/tasks/gitlab/info.rake
@@ -3,26 +3,26 @@ namespace :gitlab do
desc "GitLab | Show information about GitLab and its environment"
task info: :gitlab_environment do
# check if there is an RVM environment
- rvm_version = run_and_match(%w(rvm --version), /[\d\.]+/).try(:to_s)
+ rvm_version = run_and_match(%w[rvm --version], /[\d\.]+/).try(:to_s)
# check Ruby version
- ruby_version = run_and_match(%w(ruby --version), /[\d\.p]+/).try(:to_s)
+ ruby_version = run_and_match(%w[ruby --version], /[\d\.p]+/).try(:to_s)
# check Gem version
- gem_version = run_command(%w(gem --version))
+ gem_version = run_command(%w[gem --version])
# check Bundler version
- bunder_version = run_and_match(%w(bundle --version), /[\d\.]+/).try(:to_s)
+ bunder_version = run_and_match(%w[bundle --version], /[\d\.]+/).try(:to_s)
# check Rake version
- rake_version = run_and_match(%w(rake --version), /[\d\.]+/).try(:to_s)
+ rake_version = run_and_match(%w[rake --version], /[\d\.]+/).try(:to_s)
# check redis version
- redis_version = run_and_match(%w(redis-cli --version), /redis-cli (\d+\.\d+\.\d+)/).to_a
+ redis_version = run_and_match(%w[redis-cli --version], /redis-cli (\d+\.\d+\.\d+)/).to_a
# check Git version
- git_version = run_and_match([Gitlab.config.git.bin_path, '--version'], /git version ([\d\.]+)/).to_a
+ git_version = run_and_match([Gitlab.config.git.bin_path, "--version"], /git version ([\d\.]+)/).to_a
# check Go version
- go_version = run_and_match(%w(go version), /go version (.+)/).to_a
+ go_version = run_and_match(%w[go version], /go version (.+)/).to_a
puts ""
puts "System information".color(:yellow)
puts "System:\t\t#{os_name || "unknown".color(:red)}"
- puts "Current User:\t#{run_command(%w(whoami))}"
+ puts "Current User:\t#{run_command(%w[whoami])}"
puts "Using RVM:\t#{rvm_version.present? ? "yes".color(:green) : "no"}"
puts "RVM Version:\t#{rvm_version}" if rvm_version.present?
puts "Ruby Version:\t#{ruby_version || "unknown".color(:red)}"
@@ -42,7 +42,7 @@ namespace :gitlab do
http_clone_url = project.http_url_to_repo
ssh_clone_url = project.ssh_url_to_repo
- omniauth_providers = Gitlab.config.omniauth.providers.map { |provider| provider['name'] }
+ omniauth_providers = Gitlab.config.omniauth.providers.map { |provider| provider["name"] }
puts ""
puts "GitLab information".color(:yellow)
@@ -55,7 +55,7 @@ namespace :gitlab do
puts "SSH Clone URL:\t#{ssh_clone_url}"
puts "Using LDAP:\t#{Gitlab.config.ldap.enabled ? "yes".color(:green) : "no"}"
puts "Using Omniauth:\t#{Gitlab::Auth.omniauth_enabled? ? "yes".color(:green) : "no"}"
- puts "Omniauth Providers: #{omniauth_providers.join(', ')}" if Gitlab::Auth.omniauth_enabled?
+ puts "Omniauth Providers: #{omniauth_providers.join(", ")}" if Gitlab::Auth.omniauth_enabled?
# check Gitolite version
gitlab_shell_version_file = "#{Gitlab.config.gitlab_shell.path}/VERSION"
diff --git a/lib/tasks/gitlab/ldap.rake b/lib/tasks/gitlab/ldap.rake
index 0459de27c96..3a17961afe3 100644
--- a/lib/tasks/gitlab/ldap.rake
+++ b/lib/tasks/gitlab/ldap.rake
@@ -1,38 +1,38 @@
namespace :gitlab do
namespace :ldap do
- desc 'GitLab | LDAP | Rename provider'
+ desc "GitLab | LDAP | Rename provider"
task :rename_provider, [:old_provider, :new_provider] => :gitlab_environment do |_, args|
old_provider = args[:old_provider] ||
- prompt('What is the old provider? Ex. \'ldapmain\': '.color(:blue))
+ prompt("What is the old provider? Ex. 'ldapmain': ".color(:blue))
new_provider = args[:new_provider] ||
- prompt('What is the new provider ID? Ex. \'ldapcustom\': '.color(:blue))
- puts '' # Add some separation in the output
+ prompt("What is the new provider ID? Ex. 'ldapcustom': ".color(:blue))
+ puts "" # Add some separation in the output
identities = Identity.where(provider: old_provider)
identity_count = identities.count
if identities.empty?
puts "Found no user identities with '#{old_provider}' provider."
- puts 'Please check the provider name and try again.'
+ puts "Please check the provider name and try again."
exit 1
end
- plural_id_count = ActionController::Base.helpers.pluralize(identity_count, 'user')
+ plural_id_count = ActionController::Base.helpers.pluralize(identity_count, "user")
- unless ENV['force'] == 'yes'
+ unless ENV["force"] == "yes"
puts "#{plural_id_count} with provider '#{old_provider}' will be updated to '#{new_provider}'"
- puts 'If the new provider is incorrect, users will be unable to sign in'
+ puts "If the new provider is incorrect, users will be unable to sign in"
ask_to_continue
- puts ''
+ puts ""
end
updated_count = identities.update_all(provider: new_provider)
if updated_count == identity_count
- puts 'User identities were successfully updated'.color(:green)
+ puts "User identities were successfully updated".color(:green)
else
- plural_updated_count = ActionController::Base.helpers.pluralize(updated_count, 'user')
- puts 'Some user identities could not be updated'.color(:red)
+ plural_updated_count = ActionController::Base.helpers.pluralize(updated_count, "user")
+ puts "Some user identities could not be updated".color(:red)
puts "Successfully updated #{plural_updated_count} out of #{plural_id_count} total"
end
end
diff --git a/lib/tasks/gitlab/lfs/check.rake b/lib/tasks/gitlab/lfs/check.rake
index 869463d4e5d..dbcb9697643 100644
--- a/lib/tasks/gitlab/lfs/check.rake
+++ b/lib/tasks/gitlab/lfs/check.rake
@@ -1,6 +1,6 @@
namespace :gitlab do
namespace :lfs do
- desc 'GitLab | LFS | Check integrity of uploaded LFS objects'
+ desc "GitLab | LFS | Check integrity of uploaded LFS objects"
task check: :environment do
Gitlab::Verify::RakeTask.run!(Gitlab::Verify::LfsObjects)
end
diff --git a/lib/tasks/gitlab/lfs/migrate.rake b/lib/tasks/gitlab/lfs/migrate.rake
index a45e5ca91e0..7560e1022ce 100644
--- a/lib/tasks/gitlab/lfs/migrate.rake
+++ b/lib/tasks/gitlab/lfs/migrate.rake
@@ -1,21 +1,20 @@
-require 'logger'
+require "logger"
desc "GitLab | Migrate LFS objects to remote storage"
namespace :gitlab do
namespace :lfs do
task migrate: :environment do
logger = Logger.new(STDOUT)
- logger.info('Starting transfer of LFS files to object storage')
+ logger.info("Starting transfer of LFS files to object storage")
LfsObject.with_files_stored_locally
.find_each(batch_size: 10) do |lfs_object|
- begin
- lfs_object.file.migrate!(LfsObjectUploader::Store::REMOTE)
- logger.info("Transferred LFS object #{lfs_object.oid} of size #{lfs_object.size.to_i.bytes} to object storage")
- rescue => e
- logger.error("Failed to transfer LFS object #{lfs_object.oid} with error: #{e.message}")
- end
+ lfs_object.file.migrate!(LfsObjectUploader::Store::REMOTE)
+
+ logger.info("Transferred LFS object #{lfs_object.oid} of size #{lfs_object.size.to_i.bytes} to object storage")
+ rescue => e
+ logger.error("Failed to transfer LFS object #{lfs_object.oid} with error: #{e.message}")
end
end
end
diff --git a/lib/tasks/gitlab/list_repos.rake b/lib/tasks/gitlab/list_repos.rake
index b854c34a8e5..43dc65adf89 100644
--- a/lib/tasks/gitlab/list_repos.rake
+++ b/lib/tasks/gitlab/list_repos.rake
@@ -1,12 +1,12 @@
namespace :gitlab do
task list_repos: :environment do
scope = Project
- if ENV['SINCE']
- date = Time.parse(ENV['SINCE'])
+ if ENV["SINCE"]
+ date = Time.parse(ENV["SINCE"])
warn "Listing repositories with activity or changes since #{date}"
- project_ids = Project.where('last_activity_at > ? OR updated_at > ?', date, date).pluck(:id).sort
- namespace_ids = Namespace.where(['updated_at > ?', date]).pluck(:id).sort
- scope = scope.where('id IN (?) OR namespace_id in (?)', project_ids, namespace_ids)
+ project_ids = Project.where("last_activity_at > ? OR updated_at > ?", date, date).pluck(:id).sort
+ namespace_ids = Namespace.where(["updated_at > ?", date]).pluck(:id).sort
+ scope = scope.where("id IN (?) OR namespace_id in (?)", project_ids, namespace_ids)
end
scope.find_each do |project|
diff --git a/lib/tasks/gitlab/pages.rake b/lib/tasks/gitlab/pages.rake
index 100e480bd66..1f536d8c6e8 100644
--- a/lib/tasks/gitlab/pages.rake
+++ b/lib/tasks/gitlab/pages.rake
@@ -1,6 +1,6 @@
namespace :gitlab do
namespace :pages do
- desc 'Ping the pages admin API'
+ desc "Ping the pages admin API"
task admin_ping: :gitlab_environment do
Gitlab::PagesClient.ping
puts "OK: gitlab-pages admin API is reachable"
diff --git a/lib/tasks/gitlab/setup.rake b/lib/tasks/gitlab/setup.rake
index e876b23d43f..ec4d3c06f77 100644
--- a/lib/tasks/gitlab/setup.rake
+++ b/lib/tasks/gitlab/setup.rake
@@ -18,7 +18,7 @@ namespace :gitlab do
def setup_db
warn_user_is_not_gitlab
- unless ENV['force'] == 'yes'
+ unless ENV["force"] == "yes"
puts "This will create the necessary database tables and seed the database."
puts "You will lose any previous data stored in the database."
ask_to_continue
@@ -49,10 +49,10 @@ namespace :gitlab do
return false unless Gitlab::Database.postgresql?
cmd = <<~SQL
- SELECT pg_terminate_backend(pg_stat_activity.pid)
- FROM pg_stat_activity
- WHERE datname = current_database()
- AND pid <> pg_backend_pid();
+ SELECT pg_terminate_backend(pg_stat_activity.pid)
+ FROM pg_stat_activity
+ WHERE datname = current_database()
+ AND pid <> pg_backend_pid();
SQL
ActiveRecord::Base.connection.execute(cmd)&.result_status == PG::PGRES_TUPLES_OK
diff --git a/lib/tasks/gitlab/shell.rake b/lib/tasks/gitlab/shell.rake
index 0ebc6f00793..75604da22ad 100644
--- a/lib/tasks/gitlab/shell.rake
+++ b/lib/tasks/gitlab/shell.rake
@@ -5,11 +5,11 @@ namespace :gitlab do
warn_user_is_not_gitlab
default_version = Gitlab::Shell.version_required
- args.with_defaults(repo: 'https://gitlab.com/gitlab-org/gitlab-shell.git')
+ args.with_defaults(repo: "https://gitlab.com/gitlab-org/gitlab-shell.git")
gitlab_url = Gitlab.config.gitlab.url
# gitlab-shell requires a / at the end of the url
- gitlab_url += '/' unless gitlab_url.end_with?('/')
+ gitlab_url += "/" unless gitlab_url.end_with?("/")
target_dir = Gitlab.config.gitlab_shell.path
checkout_or_clone_version(version: default_version, repo: args.repo, target_dir: target_dir)
@@ -19,40 +19,40 @@ namespace :gitlab do
config = {
user: Gitlab.config.gitlab.user,
gitlab_url: gitlab_url,
- http_settings: { self_signed_cert: false }.stringify_keys,
+ http_settings: {self_signed_cert: false}.stringify_keys,
auth_file: File.join(user_home, ".ssh", "authorized_keys"),
redis: {
bin: `which redis-cli`.chomp,
- namespace: "resque:gitlab"
+ namespace: "resque:gitlab",
}.stringify_keys,
log_level: "INFO",
- audit_usernames: false
+ audit_usernames: false,
}.stringify_keys
- redis_url = URI.parse(ENV['REDIS_URL'] || "redis://localhost:6379")
+ redis_url = URI.parse(ENV["REDIS_URL"] || "redis://localhost:6379")
- if redis_url.scheme == 'unix'
- config['redis']['socket'] = redis_url.path
+ if redis_url.scheme == "unix"
+ config["redis"]["socket"] = redis_url.path
else
- config['redis']['host'] = redis_url.host
- config['redis']['port'] = redis_url.port
+ config["redis"]["host"] = redis_url.host
+ config["redis"]["port"] = redis_url.port
end
# Generate config.yml based on existing gitlab settings
File.open("config.yml", "w+") {|f| f.puts config.to_yaml}
[
- %w(bin/install) + repository_storage_paths_args,
- %w(bin/compile)
+ %w[bin/install] + repository_storage_paths_args,
+ %w[bin/compile],
].each do |cmd|
unless Kernel.system(*cmd)
- raise "command failed: #{cmd.join(' ')}"
+ raise "command failed: #{cmd.join(" ")}"
end
end
end
# (Re)create hooks
- Rake::Task['gitlab:shell:create_hooks'].invoke
+ Rake::Task["gitlab:shell:create_hooks"].invoke
Gitlab::Shell.ensure_secret_token!
end
@@ -67,25 +67,25 @@ namespace :gitlab do
Project.find_each(batch_size: 1000) do |project|
path_to_repo = project.repository.path_to_repo
if File.exist?(path_to_repo)
- print '-'
+ print "-"
else
if Gitlab::Shell.new.create_repository(project.repository_storage,
- project.disk_path)
- print '.'
+ project.disk_path)
+ print "."
else
- print 'F'
+ print "F"
end
end
end
end
- desc 'Create or repair repository hooks symlink'
+ desc "Create or repair repository hooks symlink"
task create_hooks: :gitlab_environment do
warn_user_is_not_gitlab
- puts 'Creating/Repairing hooks symlinks for all repositories'
- system(*%W(#{Gitlab.config.gitlab_shell.path}/bin/create-hooks) + repository_storage_paths_args)
- puts 'done'.color(:green)
+ puts "Creating/Repairing hooks symlinks for all repositories"
+ system(*%W[#{Gitlab.config.gitlab_shell.path}/bin/create-hooks] + repository_storage_paths_args)
+ puts "done".color(:green)
end
end
@@ -94,7 +94,7 @@ namespace :gitlab do
ensure_write_to_authorized_keys_is_enabled
- unless ENV['force'] == 'yes'
+ unless ENV["force"] == "yes"
puts "This task will now rebuild the authorized_keys file."
puts "You will lose any data stored in the authorized_keys file."
ask_to_continue
@@ -106,7 +106,7 @@ namespace :gitlab do
Gitlab::Shell.new.batch_add_keys do |adder|
Key.find_each(batch_size: 1000) do |key|
adder.add_key(key.shell_id, key.key)
- print '.'
+ print "."
end
end
puts ""
@@ -115,7 +115,6 @@ namespace :gitlab do
puts "Failed to add keys...".color(:red)
exit 1
end
-
rescue Gitlab::TaskAbortedByUserError
puts "Quitting...".color(:red)
exit 1
@@ -126,7 +125,7 @@ namespace :gitlab do
puts authorized_keys_is_disabled_warning
- unless ENV['force'] == 'yes'
+ unless ENV["force"] == "yes"
puts 'Do you want to permanently enable the "Write to authorized_keys file" setting now?'
ask_to_continue
end
@@ -135,7 +134,7 @@ namespace :gitlab do
Gitlab::CurrentSettings.current_application_settings.update!(authorized_keys_enabled: true)
puts 'Successfully enabled "Write to authorized_keys file"!'
- puts ''
+ puts ""
end
def authorized_keys_is_disabled_warning
diff --git a/lib/tasks/gitlab/storage.rake b/lib/tasks/gitlab/storage.rake
index f9ce3e1d338..ad9ef0b2e61 100644
--- a/lib/tasks/gitlab/storage.rake
+++ b/lib/tasks/gitlab/storage.rake
@@ -1,9 +1,9 @@
namespace :gitlab do
namespace :storage do
- desc 'GitLab | Storage | Migrate existing projects to Hashed Storage'
+ desc "GitLab | Storage | Migrate existing projects to Hashed Storage"
task migrate_to_hashed: :environment do
if Gitlab::Database.read_only?
- warn 'This task requires database write access. Exiting.'
+ warn "This task requires database write access. Exiting."
next
end
@@ -29,7 +29,7 @@ namespace :gitlab do
legacy_projects_count = Project.with_unmigrated_storage.count
if legacy_projects_count == 0
- warn 'There are no projects requiring storage migration. Nothing to do!'
+ warn "There are no projects requiring storage migration. Nothing to do!"
next
end
@@ -39,58 +39,58 @@ namespace :gitlab do
helper.project_id_batches do |start, finish|
storage_migrator.bulk_schedule(start: start, finish: finish)
- print '.'
+ print "."
end
- puts ' Done!'
+ puts " Done!"
end
- desc 'Gitlab | Storage | Summary of existing projects using Legacy Storage'
+ desc "Gitlab | Storage | Summary of existing projects using Legacy Storage"
task legacy_projects: :environment do
helper = Gitlab::HashedStorage::RakeHelper
- helper.relation_summary('projects using Legacy Storage', Project.without_storage_feature(:repository))
+ helper.relation_summary("projects using Legacy Storage", Project.without_storage_feature(:repository))
end
- desc 'Gitlab | Storage | List existing projects using Legacy Storage'
+ desc "Gitlab | Storage | List existing projects using Legacy Storage"
task list_legacy_projects: :environment do
helper = Gitlab::HashedStorage::RakeHelper
- helper.projects_list('projects using Legacy Storage', Project.without_storage_feature(:repository))
+ helper.projects_list("projects using Legacy Storage", Project.without_storage_feature(:repository))
end
- desc 'Gitlab | Storage | Summary of existing projects using Hashed Storage'
+ desc "Gitlab | Storage | Summary of existing projects using Hashed Storage"
task hashed_projects: :environment do
helper = Gitlab::HashedStorage::RakeHelper
- helper.relation_summary('projects using Hashed Storage', Project.with_storage_feature(:repository))
+ helper.relation_summary("projects using Hashed Storage", Project.with_storage_feature(:repository))
end
- desc 'Gitlab | Storage | List existing projects using Hashed Storage'
+ desc "Gitlab | Storage | List existing projects using Hashed Storage"
task list_hashed_projects: :environment do
helper = Gitlab::HashedStorage::RakeHelper
- helper.projects_list('projects using Hashed Storage', Project.with_storage_feature(:repository))
+ helper.projects_list("projects using Hashed Storage", Project.with_storage_feature(:repository))
end
- desc 'Gitlab | Storage | Summary of project attachments using Legacy Storage'
+ desc "Gitlab | Storage | Summary of project attachments using Legacy Storage"
task legacy_attachments: :environment do
helper = Gitlab::HashedStorage::RakeHelper
- helper.relation_summary('attachments using Legacy Storage', helper.legacy_attachments_relation)
+ helper.relation_summary("attachments using Legacy Storage", helper.legacy_attachments_relation)
end
- desc 'Gitlab | Storage | List existing project attachments using Legacy Storage'
+ desc "Gitlab | Storage | List existing project attachments using Legacy Storage"
task list_legacy_attachments: :environment do
helper = Gitlab::HashedStorage::RakeHelper
- helper.attachments_list('attachments using Legacy Storage', helper.legacy_attachments_relation)
+ helper.attachments_list("attachments using Legacy Storage", helper.legacy_attachments_relation)
end
- desc 'Gitlab | Storage | Summary of project attachments using Hashed Storage'
+ desc "Gitlab | Storage | Summary of project attachments using Hashed Storage"
task hashed_attachments: :environment do
helper = Gitlab::HashedStorage::RakeHelper
- helper.relation_summary('attachments using Hashed Storage', helper.hashed_attachments_relation)
+ helper.relation_summary("attachments using Hashed Storage", helper.hashed_attachments_relation)
end
- desc 'Gitlab | Storage | List existing project attachments using Hashed Storage'
+ desc "Gitlab | Storage | List existing project attachments using Hashed Storage"
task list_hashed_attachments: :environment do
helper = Gitlab::HashedStorage::RakeHelper
- helper.attachments_list('attachments using Hashed Storage', helper.hashed_attachments_relation)
+ helper.attachments_list("attachments using Hashed Storage", helper.hashed_attachments_relation)
end
end
end
diff --git a/lib/tasks/gitlab/tcp_check.rake b/lib/tasks/gitlab/tcp_check.rake
index 1400f57d6b9..6a44862a9ff 100644
--- a/lib/tasks/gitlab/tcp_check.rake
+++ b/lib/tasks/gitlab/tcp_check.rake
@@ -13,7 +13,7 @@ namespace :gitlab do
else
puts "TCP connection to #{checker.remote} failed: #{checker.error}".color(:red)
puts
- puts 'Check that host and port are correct, and that the traffic is permitted through any firewalls.'
+ puts "Check that host and port are correct, and that the traffic is permitted through any firewalls."
exit 1
end
end
diff --git a/lib/tasks/gitlab/test.rake b/lib/tasks/gitlab/test.rake
index 2222807fe13..7a64baf7f8d 100644
--- a/lib/tasks/gitlab/test.rake
+++ b/lib/tasks/gitlab/test.rake
@@ -2,14 +2,14 @@ namespace :gitlab do
desc "GitLab | Run all tests"
task :test do
cmds = [
- %w(rake brakeman),
- %w(rake rubocop),
- %w(rake spec),
- %w(rake karma)
+ %w[rake brakeman],
+ %w[rake rubocop],
+ %w[rake spec],
+ %w[rake karma],
]
cmds.each do |cmd|
- system({ 'RAILS_ENV' => 'test', 'force' => 'yes' }, *cmd) || raise("#{cmd} failed!")
+ system({"RAILS_ENV" => "test", "force" => "yes"}, *cmd) || raise("#{cmd} failed!")
end
end
end
diff --git a/lib/tasks/gitlab/traces.rake b/lib/tasks/gitlab/traces.rake
index 5a232091a7e..8e060a77cbd 100644
--- a/lib/tasks/gitlab/traces.rake
+++ b/lib/tasks/gitlab/traces.rake
@@ -1,12 +1,12 @@
-require 'logger'
-require 'resolv-replace'
+require "logger"
+require "resolv-replace"
desc "GitLab | Archive legacy traces to trace artifacts"
namespace :gitlab do
namespace :traces do
task archive: :environment do
logger = Logger.new(STDOUT)
- logger.info('Archiving legacy traces')
+ logger.info("Archiving legacy traces")
Ci::Build.finished.without_archived_trace
.order(id: :asc)
@@ -21,18 +21,17 @@ namespace :gitlab do
task migrate: :environment do
logger = Logger.new(STDOUT)
- logger.info('Starting transfer of job traces')
+ logger.info("Starting transfer of job traces")
Ci::Build.joins(:project)
.with_archived_trace_stored_locally
.find_each(batch_size: 10) do |build|
- begin
- build.job_artifacts_trace.file.migrate!(ObjectStorage::Store::REMOTE)
- logger.info("Transferred job trace of #{build.id} to object storage")
- rescue => e
- logger.error("Failed to transfer artifacts of #{build.id} with error: #{e.message}")
- end
+ build.job_artifacts_trace.file.migrate!(ObjectStorage::Store::REMOTE)
+
+ logger.info("Transferred job trace of #{build.id} to object storage")
+ rescue => e
+ logger.error("Failed to transfer artifacts of #{build.id} with error: #{e.message}")
end
end
end
diff --git a/lib/tasks/gitlab/track_deployment.rake b/lib/tasks/gitlab/track_deployment.rake
index 6f101aea303..8814a53fd90 100644
--- a/lib/tasks/gitlab/track_deployment.rake
+++ b/lib/tasks/gitlab/track_deployment.rake
@@ -1,8 +1,8 @@
namespace :gitlab do
- desc 'GitLab | Tracks a deployment in GitLab Performance Monitoring'
+ desc "GitLab | Tracks a deployment in GitLab Performance Monitoring"
task track_deployment: :environment do
metric = Gitlab::Metrics::Metric
- .new('deployments', version: Gitlab::VERSION)
+ .new("deployments", version: Gitlab::VERSION)
Gitlab::Metrics.submit_metrics([metric.to_hash])
end
diff --git a/lib/tasks/gitlab/two_factor.rake b/lib/tasks/gitlab/two_factor.rake
index 6b22499a5c8..d2400181dfd 100644
--- a/lib/tasks/gitlab/two_factor.rake
+++ b/lib/tasks/gitlab/two_factor.rake
@@ -22,12 +22,12 @@ namespace :gitlab do
namespace :rotate_key do
def rotator
- @rotator ||= Gitlab::OtpKeyRotator.new(ENV['filename'])
+ @rotator ||= Gitlab::OtpKeyRotator.new(ENV["filename"])
end
desc "Encrypt user OTP secrets with a new encryption key"
task apply: :environment do |t, args|
- rotator.rotate!(old_key: ENV['old_key'], new_key: ENV['new_key'])
+ rotator.rotate!(old_key: ENV["old_key"], new_key: ENV["new_key"])
end
desc "Rollback to secrets encrypted with the old encryption key"
diff --git a/lib/tasks/gitlab/update_templates.rake b/lib/tasks/gitlab/update_templates.rake
index abe10f5580e..eef13a9d90e 100644
--- a/lib/tasks/gitlab/update_templates.rake
+++ b/lib/tasks/gitlab/update_templates.rake
@@ -25,7 +25,7 @@ namespace :gitlab do
import_url: template.clone_url,
namespace_id: admin.namespace.id,
path: template.name,
- skip_wiki: true
+ skip_wiki: true,
}
puts "Creating project for #{template.title}"
@@ -102,10 +102,10 @@ namespace :gitlab do
Template.new(
"https://gitlab.com/gitlab-org/Dockerfile.git",
/(\.{1,2}|LICENSE|CONTRIBUTING.md|\.Dockerfile)\z/
- )
+ ),
].freeze
def vendor_directory
- Rails.root.join('vendor')
+ Rails.root.join("vendor")
end
end
diff --git a/lib/tasks/gitlab/uploads/check.rake b/lib/tasks/gitlab/uploads/check.rake
index 2be2ec7f9c9..d7d55bef28d 100644
--- a/lib/tasks/gitlab/uploads/check.rake
+++ b/lib/tasks/gitlab/uploads/check.rake
@@ -1,6 +1,6 @@
namespace :gitlab do
namespace :uploads do
- desc 'GitLab | Uploads | Check integrity of uploaded files'
+ desc "GitLab | Uploads | Check integrity of uploaded files"
task check: :environment do
Gitlab::Verify::RakeTask.run!(Gitlab::Verify::Uploads)
end
diff --git a/lib/tasks/gitlab/uploads/migrate.rake b/lib/tasks/gitlab/uploads/migrate.rake
index 1c93609a006..c2ab52b9907 100644
--- a/lib/tasks/gitlab/uploads/migrate.rake
+++ b/lib/tasks/gitlab/uploads/migrate.rake
@@ -3,17 +3,17 @@ namespace :gitlab do
namespace :migrate do
desc "GitLab | Uploads | Migrate all uploaded files to object storage"
task all: :environment do
- categories = [%w(AvatarUploader Project :avatar),
- %w(AvatarUploader Group :avatar),
- %w(AvatarUploader User :avatar),
- %w(AttachmentUploader Note :attachment),
- %w(AttachmentUploader Appearance :logo),
- %w(AttachmentUploader Appearance :header_logo),
- %w(FaviconUploader Appearance :favicon),
- %w(FileUploader Project),
- %w(PersonalFileUploader Snippet),
- %w(NamespaceFileUploader Snippet),
- %w(FileUploader MergeRequest)]
+ categories = [%w[AvatarUploader Project :avatar],
+ %w[AvatarUploader Group :avatar],
+ %w[AvatarUploader User :avatar],
+ %w[AttachmentUploader Note :attachment],
+ %w[AttachmentUploader Appearance :logo],
+ %w[AttachmentUploader Appearance :header_logo],
+ %w[FaviconUploader Appearance :favicon],
+ %w[FileUploader Project],
+ %w[PersonalFileUploader Snippet],
+ %w[NamespaceFileUploader Snippet],
+ %w[FileUploader MergeRequest],]
categories.each do |args|
Rake::Task["gitlab:uploads:migrate"].invoke(*args)
@@ -24,11 +24,11 @@ namespace :gitlab do
# The following is the actual rake task that migrates uploads of specified
# category to object storage
- desc 'GitLab | Uploads | Migrate the uploaded files of specified type to object storage'
+ desc "GitLab | Uploads | Migrate the uploaded files of specified type to object storage"
task :migrate, [:uploader_class, :model_class, :mounted_as] => :environment do |task, args|
- batch_size = ENV.fetch('BATCH', 200).to_i
+ batch_size = ENV.fetch("BATCH", 200).to_i
@to_store = ObjectStorage::Store::REMOTE
- @mounted_as = args.mounted_as&.gsub(':', '')&.to_sym
+ @mounted_as = args.mounted_as&.gsub(":", "")&.to_sym
@uploader_class = args.uploader_class.constantize
@model_class = args.model_class.constantize
@@ -37,9 +37,9 @@ namespace :gitlab do
def enqueue_batch(batch, index)
job = ObjectStorage::MigrateUploadsWorker.enqueue!(batch,
- @model_class,
- @mounted_as,
- @to_store)
+ @model_class,
+ @mounted_as,
+ @to_store)
puts "Enqueued job ##{index}: #{job}"
rescue ObjectStorage::MigrateUploadsWorker::SanityCheckError => e
# continue for the next batch
diff --git a/lib/tasks/gitlab/web_hook.rake b/lib/tasks/gitlab/web_hook.rake
index 15cec80b6a6..92038fa3228 100644
--- a/lib/tasks/gitlab/web_hook.rake
+++ b/lib/tasks/gitlab/web_hook.rake
@@ -2,8 +2,8 @@ namespace :gitlab do
namespace :web_hook do
desc "GitLab | Adds a webhook to the projects"
task add: :environment do
- web_hook_url = ENV['URL']
- namespace_path = ENV['NAMESPACE']
+ web_hook_url = ENV["URL"]
+ namespace_path = ENV["NAMESPACE"]
projects = find_projects(namespace_path)
@@ -22,8 +22,8 @@ namespace :gitlab do
desc "GitLab | Remove a webhook from the projects"
task rm: :environment do
- web_hook_url = ENV['URL']
- namespace_path = ENV['NAMESPACE']
+ web_hook_url = ENV["URL"]
+ namespace_path = ENV["NAMESPACE"]
web_hooks = find_web_hooks(namespace_path)
@@ -46,7 +46,7 @@ namespace :gitlab do
desc "GitLab | List webhooks"
task list: :environment do
- namespace_path = ENV['NAMESPACE']
+ namespace_path = ENV["NAMESPACE"]
web_hooks = find_web_hooks(namespace_path)
web_hooks.find_each do |hook|
diff --git a/lib/tasks/gitlab/workhorse.rake b/lib/tasks/gitlab/workhorse.rake
index b917a293095..be1d278f63b 100644
--- a/lib/tasks/gitlab/workhorse.rake
+++ b/lib/tasks/gitlab/workhorse.rake
@@ -8,14 +8,14 @@ namespace :gitlab do
abort %(Please specify the directory where you want to install gitlab-workhorse:\n rake "gitlab:workhorse:install[/home/git/gitlab-workhorse]")
end
- args.with_defaults(repo: 'https://gitlab.com/gitlab-org/gitlab-workhorse.git')
+ args.with_defaults(repo: "https://gitlab.com/gitlab-org/gitlab-workhorse.git")
version = Gitlab::Workhorse.version
checkout_or_clone_version(version: version, repo: args.repo, target_dir: args.dir)
_, status = Gitlab::Popen.popen(%w[which gmake])
- command = status.zero? ? 'gmake' : 'make'
+ command = status.zero? ? "gmake" : "make"
Dir.chdir(args.dir) do
run_command!([command])
diff --git a/lib/tasks/grape.rake b/lib/tasks/grape.rake
index ea2698da606..b0739faa9c4 100644
--- a/lib/tasks/grape.rake
+++ b/lib/tasks/grape.rake
@@ -1,5 +1,5 @@
namespace :grape do
- desc 'Print compiled grape routes'
+ desc "Print compiled grape routes"
task routes: :environment do
API::API.routes.each do |route|
puts "#{route.options[:method]} #{route.path} - #{route_description(route.options)}"
diff --git a/lib/tasks/haml-lint.rake b/lib/tasks/haml-lint.rake
index 786efd14b1a..63344f448cb 100644
--- a/lib/tasks/haml-lint.rake
+++ b/lib/tasks/haml-lint.rake
@@ -1,13 +1,13 @@
unless Rails.env.production?
- require 'haml_lint/rake_task'
- require 'haml_lint/inline_javascript'
+ require "haml_lint/rake_task"
+ require "haml_lint/inline_javascript"
# Workaround for warnings from parser/current
# Keep it even if it no longer emits any warnings,
# because we'll still see warnings in console/server anyway,
# and we don't need to break static-analysis for this.
task :haml_lint do
- require 'parser'
+ require "parser"
def Parser.warn(*args)
puts(*args) # static-analysis ignores stdout if status is 0
end
diff --git a/lib/tasks/import.rake b/lib/tasks/import.rake
index f912f521dfb..6bd83ef1b2b 100644
--- a/lib/tasks/import.rake
+++ b/lib/tasks/import.rake
@@ -1,5 +1,5 @@
-require 'benchmark'
-require 'rainbow/ext/string'
+require "benchmark"
+require "rainbow/ext/string"
class GithubImport
def self.run!(*args)
@@ -7,7 +7,7 @@ class GithubImport
end
def initialize(token, gitlab_username, project_path, extras)
- @options = { token: token }
+ @options = {token: token}
@project_path = project_path
@current_user = UserFinder.new(gitlab_username).find_by_username
@@ -21,7 +21,7 @@ class GithubImport
.new(@options[:token], @current_user, @github_repo)
.choose_one!
- raise 'No repo found!' unless @repo
+ raise "No repo found!" unless @repo
show_warning!
@@ -38,7 +38,7 @@ class GithubImport
STDIN.getch
- puts 'Starting the import (this could take a while)'.color(:green)
+ puts "Starting the import (this could take a while)".color(:green)
end
def import!
@@ -46,11 +46,11 @@ class GithubImport
import_success = false
- timings = Benchmark.measure do
+ timings = Benchmark.measure {
import_success = Gitlab::GithubImport::SequentialImporter
.new(@project, token: @options[:token])
.execute
- end
+ }
if import_success
@project.after_import
@@ -63,7 +63,7 @@ class GithubImport
def new_project
Project.transaction do
- namespace_path, _sep, name = @project_path.rpartition('/')
+ namespace_path, _sep, name = @project_path.rpartition("/")
namespace = find_or_create_namespace(namespace_path)
project = Projects::CreateService.new(
@@ -77,9 +77,9 @@ class GithubImport
).execute
project.update!(
- import_type: 'github',
+ import_type: "github",
import_source: @repo.full_name,
- import_url: @repo.clone_url.sub('://', "://#{@options[:token]}@")
+ import_url: @repo.clone_url.sub("://", "://#{@options[:token]}@")
)
project
@@ -119,7 +119,7 @@ class GithubRepos
print "\tName: #{repo.full_name}\n".color(:green)
end
- print 'ID? '.bright
+ print "ID? ".bright
repos.find { |repo| repo.id == repo_id }
end
@@ -138,9 +138,9 @@ class GithubRepos
end
namespace :import do
- desc 'Import a GitHub project - Example: import:github[ToKeN,root,root/blah,my/github_repo] (optional my/github_repo)'
+ desc "Import a GitHub project - Example: import:github[ToKeN,root,root/blah,my/github_repo] (optional my/github_repo)"
task :github, [:token, :gitlab_username, :project_path] => :environment do |_t, args|
- abort 'Project path must be: namespace(s)/project_name'.color(:red) unless args.project_path.include?('/')
+ abort "Project path must be: namespace(s)/project_name".color(:red) unless args.project_path.include?("/")
GithubImport.run!(args.token, args.gitlab_username, args.project_path, args.extras)
end
diff --git a/lib/tasks/karma.rake b/lib/tasks/karma.rake
index 62a12174efa..3a00073d509 100644
--- a/lib/tasks/karma.rake
+++ b/lib/tasks/karma.rake
@@ -1,21 +1,21 @@
unless Rails.env.production?
namespace :karma do
- desc 'GitLab | Karma | Generate fixtures for JavaScript tests'
+ desc "GitLab | Karma | Generate fixtures for JavaScript tests"
RSpec::Core::RakeTask.new(:fixtures, [:pattern]) do |t, args|
- args.with_defaults(pattern: 'spec/javascripts/fixtures/*.rb')
- ENV['NO_KNAPSACK'] = 'true'
+ args.with_defaults(pattern: "spec/javascripts/fixtures/*.rb")
+ ENV["NO_KNAPSACK"] = "true"
t.pattern = args[:pattern]
- t.rspec_opts = '--format documentation'
+ t.rspec_opts = "--format documentation"
end
- desc 'GitLab | Karma | Run JavaScript tests'
- task tests: ['yarn:check'] do
+ desc "GitLab | Karma | Run JavaScript tests"
+ task tests: ["yarn:check"] do
sh "yarn run karma" do |ok, res|
- abort('rake karma:tests failed') unless ok
+ abort("rake karma:tests failed") unless ok
end
end
end
- desc 'GitLab | Karma | Shortcut for karma:fixtures and karma:tests'
- task karma: ['karma:fixtures', 'karma:tests']
+ desc "GitLab | Karma | Shortcut for karma:fixtures and karma:tests"
+ task karma: ["karma:fixtures", "karma:tests"]
end
diff --git a/lib/tasks/lint.rake b/lib/tasks/lint.rake
index 5d673a1a285..6680bf0fb4a 100644
--- a/lib/tasks/lint.rake
+++ b/lib/tasks/lint.rake
@@ -1,7 +1,7 @@
unless Rails.env.production?
namespace :lint do
task :static_verification_env do
- ENV['STATIC_VERIFICATION'] = 'true'
+ ENV["STATIC_VERIFICATION"] = "true"
end
desc "GitLab | lint | Static verification"
@@ -14,16 +14,14 @@ unless Rails.env.production?
desc "GitLab | lint | Lint JavaScript files using ESLint"
task :javascript do
- Rake::Task['eslint'].invoke
+ Rake::Task["eslint"].invoke
end
desc "GitLab | lint | Lint HAML files"
task :haml do
- begin
- Rake::Task['haml_lint'].invoke
- rescue RuntimeError # The haml_lint tasks raise a RuntimeError
- exit(1)
- end
+ Rake::Task["haml_lint"].invoke
+ rescue RuntimeError # The haml_lint tasks raise a RuntimeError
+ exit(1)
end
desc "GitLab | lint | Run several lint checks"
@@ -38,7 +36,7 @@ unless Rails.env.production?
gettext:updated_check
lint:static_verification
].each do |task|
- pid = Process.fork do
+ pid = Process.fork {
rd_out, wr_out = IO.pipe
rd_err, wr_err = IO.pipe
stdout = $stdout.dup
@@ -65,7 +63,7 @@ unless Rails.env.production?
IO.copy_stream(rd_out, $stdout)
IO.copy_stream(rd_err, $stderr)
end
- end
+ }
Process.waitpid(pid)
status += $?.exitstatus
diff --git a/lib/tasks/migrate/add_limits_mysql.rake b/lib/tasks/migrate/add_limits_mysql.rake
index c77fa49d586..81392a3769b 100644
--- a/lib/tasks/migrate/add_limits_mysql.rake
+++ b/lib/tasks/migrate/add_limits_mysql.rake
@@ -1,9 +1,9 @@
-require Rails.root.join('db/migrate/limits_to_mysql')
-require Rails.root.join('db/migrate/markdown_cache_limits_to_mysql')
-require Rails.root.join('db/migrate/merge_request_diff_file_limits_to_mysql')
-require Rails.root.join('db/migrate/limits_ci_build_trace_chunks_raw_data_for_mysql')
-require Rails.root.join('db/migrate/gpg_keys_limits_to_mysql')
-require Rails.root.join('db/migrate/prometheus_metrics_limits_to_mysql')
+require Rails.root.join("db/migrate/limits_to_mysql")
+require Rails.root.join("db/migrate/markdown_cache_limits_to_mysql")
+require Rails.root.join("db/migrate/merge_request_diff_file_limits_to_mysql")
+require Rails.root.join("db/migrate/limits_ci_build_trace_chunks_raw_data_for_mysql")
+require Rails.root.join("db/migrate/gpg_keys_limits_to_mysql")
+require Rails.root.join("db/migrate/prometheus_metrics_limits_to_mysql")
desc "GitLab | Add limits to strings in mysql database"
task add_limits_mysql: :environment do
diff --git a/lib/tasks/migrate/composite_primary_keys.rake b/lib/tasks/migrate/composite_primary_keys.rake
index eb112434dd9..fb8bba42a84 100644
--- a/lib/tasks/migrate/composite_primary_keys.rake
+++ b/lib/tasks/migrate/composite_primary_keys.rake
@@ -1,14 +1,14 @@
namespace :gitlab do
namespace :db do
- desc 'GitLab | Adds primary keys to tables that only have composite unique keys'
+ desc "GitLab | Adds primary keys to tables that only have composite unique keys"
task composite_primary_keys_add: :environment do
- require Rails.root.join('db/optional_migrations/composite_primary_keys')
+ require Rails.root.join("db/optional_migrations/composite_primary_keys")
CompositePrimaryKeysMigration.new.up
end
- desc 'GitLab | Removes previously added composite primary keys'
+ desc "GitLab | Removes previously added composite primary keys"
task composite_primary_keys_drop: :environment do
- require Rails.root.join('db/optional_migrations/composite_primary_keys')
+ require Rails.root.join("db/optional_migrations/composite_primary_keys")
CompositePrimaryKeysMigration.new.down
end
end
diff --git a/lib/tasks/migrate/migrate_iids.rake b/lib/tasks/migrate/migrate_iids.rake
index aa2d01730d7..b04ab63efa9 100644
--- a/lib/tasks/migrate/migrate_iids.rake
+++ b/lib/tasks/migrate/migrate_iids.rake
@@ -1,51 +1,45 @@
desc "GitLab | Build internal ids for issues and merge requests"
task migrate_iids: :environment do
- puts 'Issues'.color(:yellow)
+ puts "Issues".color(:yellow)
Issue.where(iid: nil).find_each(batch_size: 100) do |issue|
- begin
- issue.set_iid
+ issue.set_iid
- if issue.update_attribute(:iid, issue.iid)
- print '.'
- else
- print 'F'
- end
- rescue
- print 'F'
+ if issue.update_attribute(:iid, issue.iid)
+ print "."
+ else
+ print "F"
end
+ rescue
+ print "F"
end
- puts 'done'
- puts 'Merge Requests'.color(:yellow)
+ puts "done"
+ puts "Merge Requests".color(:yellow)
MergeRequest.where(iid: nil).find_each(batch_size: 100) do |mr|
- begin
- mr.set_iid
+ mr.set_iid
- if mr.update_attribute(:iid, mr.iid)
- print '.'
- else
- print 'F'
- end
- rescue
- print 'F'
+ if mr.update_attribute(:iid, mr.iid)
+ print "."
+ else
+ print "F"
end
+ rescue
+ print "F"
end
- puts 'done'
- puts 'Milestones'.color(:yellow)
+ puts "done"
+ puts "Milestones".color(:yellow)
Milestone.where(iid: nil).find_each(batch_size: 100) do |m|
- begin
- m.set_iid
+ m.set_iid
- if m.update_attribute(:iid, m.iid)
- print '.'
- else
- print 'F'
- end
- rescue
- print 'F'
+ if m.update_attribute(:iid, m.iid)
+ print "."
+ else
+ print "F"
end
+ rescue
+ print "F"
end
- puts 'done'
+ puts "done"
end
diff --git a/lib/tasks/migrate/setup_postgresql.rake b/lib/tasks/migrate/setup_postgresql.rake
index f69d204c579..5d1a1433fd8 100644
--- a/lib/tasks/migrate/setup_postgresql.rake
+++ b/lib/tasks/migrate/setup_postgresql.rake
@@ -1,15 +1,15 @@
-desc 'GitLab | Sets up PostgreSQL'
+desc "GitLab | Sets up PostgreSQL"
task setup_postgresql: :environment do
- require Rails.root.join('db/migrate/20151007120511_namespaces_projects_path_lower_indexes')
- require Rails.root.join('db/migrate/20151008110232_add_users_lower_username_email_indexes')
- require Rails.root.join('db/migrate/20161212142807_add_lower_path_index_to_routes')
- require Rails.root.join('db/migrate/20170317203554_index_routes_path_for_like')
- require Rails.root.join('db/migrate/20170724214302_add_lower_path_index_to_redirect_routes')
- require Rails.root.join('db/migrate/20170503185032_index_redirect_routes_path_for_like')
- require Rails.root.join('db/migrate/20171220191323_add_index_on_namespaces_lower_name.rb')
- require Rails.root.join('db/migrate/20180215181245_users_name_lower_index.rb')
- require Rails.root.join('db/migrate/20180504195842_project_name_lower_index.rb')
- require Rails.root.join('db/post_migrate/20180306164012_add_path_index_to_redirect_routes.rb')
+ require Rails.root.join("db/migrate/20151007120511_namespaces_projects_path_lower_indexes")
+ require Rails.root.join("db/migrate/20151008110232_add_users_lower_username_email_indexes")
+ require Rails.root.join("db/migrate/20161212142807_add_lower_path_index_to_routes")
+ require Rails.root.join("db/migrate/20170317203554_index_routes_path_for_like")
+ require Rails.root.join("db/migrate/20170724214302_add_lower_path_index_to_redirect_routes")
+ require Rails.root.join("db/migrate/20170503185032_index_redirect_routes_path_for_like")
+ require Rails.root.join("db/migrate/20171220191323_add_index_on_namespaces_lower_name.rb")
+ require Rails.root.join("db/migrate/20180215181245_users_name_lower_index.rb")
+ require Rails.root.join("db/migrate/20180504195842_project_name_lower_index.rb")
+ require Rails.root.join("db/post_migrate/20180306164012_add_path_index_to_redirect_routes.rb")
NamespacesProjectsPathLowerIndexes.new.up
AddUsersLowerUsernameEmailIndexes.new.up
@@ -23,17 +23,17 @@ task setup_postgresql: :environment do
AddPathIndexToRedirectRoutes.new.up
end
-desc 'GitLab | Generate PostgreSQL Password Hash'
+desc "GitLab | Generate PostgreSQL Password Hash"
task :postgresql_md5_hash do
- require 'digest'
- username = ENV.fetch('USERNAME') do |missing|
+ require "digest"
+ username = ENV.fetch("USERNAME") { |missing|
puts "You must provide an username with '#{missing}' ENV variable"
exit(1)
- end
- password = ENV.fetch('PASSWORD') do |missing|
+ }
+ password = ENV.fetch("PASSWORD") { |missing|
puts "You must provide a password with '#{missing}' ENV variable"
exit(1)
- end
+ }
hash = Digest::MD5.hexdigest("#{password}#{username}")
puts "The MD5 hash of your database password for user: #{username} -> #{hash}"
end
diff --git a/lib/tasks/plugins.rake b/lib/tasks/plugins.rake
index e73dd7e68df..d6434d58ab6 100644
--- a/lib/tasks/plugins.rake
+++ b/lib/tasks/plugins.rake
@@ -1,7 +1,7 @@
namespace :plugins do
- desc 'Validate existing plugins'
+ desc "Validate existing plugins"
task validate: :environment do
- puts 'Validating plugins from /plugins directory'
+ puts "Validating plugins from /plugins directory"
Gitlab::Plugin.files.each do |file|
success, message = Gitlab::Plugin.execute(file, Gitlab::DataBuilder::Push::SAMPLE_DATA)
diff --git a/lib/tasks/rubocop.rake b/lib/tasks/rubocop.rake
index 78ffccc9d06..17327b57c73 100644
--- a/lib/tasks/rubocop.rake
+++ b/lib/tasks/rubocop.rake
@@ -1,5 +1,5 @@
unless Rails.env.production?
- require 'rubocop/rake_task'
+ require "rubocop/rake_task"
RuboCop::RakeTask.new
end
diff --git a/lib/tasks/scss-lint.rake b/lib/tasks/scss-lint.rake
index 250fd8699e4..e64a0d71a4a 100644
--- a/lib/tasks/scss-lint.rake
+++ b/lib/tasks/scss-lint.rake
@@ -1,8 +1,8 @@
unless Rails.env.production?
- require 'scss_lint/rake_task'
+ require "scss_lint/rake_task"
SCSSLint::RakeTask.new do |t|
- t.config = '.scss-lint.yml'
+ t.config = ".scss-lint.yml"
# See https://github.com/brigade/scss-lint/issues/726
# Hack, otherwise linter won't respect scss_files option in config file.
t.files = []
diff --git a/lib/tasks/services.rake b/lib/tasks/services.rake
index 56b81106c5f..1c0a39fbc8f 100644
--- a/lib/tasks/services.rake
+++ b/lib/tasks/services.rake
@@ -1,60 +1,60 @@
-services_template = <<-ERB
-# Services
+services_template = <<~ERB
+ # Services
-<% services.each do |service| %>
-## <%= service[:title] %>
+ <% services.each do |service| %>
+ ## <%= service[:title] %>
-<% unless service[:description].blank? %>
-<%= service[:description] %>
-<% end %>
+ <% unless service[:description].blank? %>
+ <%= service[:description] %>
+ <% end %>
-### Create/Edit <%= service[:title] %> service
+ ### Create/Edit <%= service[:title] %> service
-Set <%= service[:title] %> service for a project.
-<% unless service[:help].blank? %>
+ Set <%= service[:title] %> service for a project.
+ <% unless service[:help].blank? %>
-> <%= service[:help].gsub("\n", ' ') %>
+ > <%= service[:help].gsub("\n", ' ') %>
-<% end %>
+ <% end %>
-```
-PUT /projects/:id/services/<%= service[:dashed_name] %>
+ ```
+ PUT /projects/:id/services/<%= service[:dashed_name] %>
-```
+ ```
-Parameters:
+ Parameters:
-<% service[:params].each do |param| %>
-- `<%= param[:name] %>` <%= param[:required] ? "(**required**)" : "(optional)" %><%= [" -", param[:description]].join(" ").gsub("\n", '') unless param[:description].blank? %>
+ <% service[:params].each do |param| %>
+ - `<%= param[:name] %>` <%= param[:required] ? "(**required**)" : "(optional)" %><%= [" -", param[:description]].join(" ").gsub("\n", '') unless param[:description].blank? %>
-<% end %>
+ <% end %>
-### Delete <%= service[:title] %> service
+ ### Delete <%= service[:title] %> service
-Delete <%= service[:title] %> service for a project.
+ Delete <%= service[:title] %> service for a project.
-```
-DELETE /projects/:id/services/<%= service[:dashed_name] %>
+ ```
+ DELETE /projects/:id/services/<%= service[:dashed_name] %>
-```
+ ```
-### Get <%= service[:title] %> service settings
+ ### Get <%= service[:title] %> service settings
-Get <%= service[:title] %> service settings for a project.
+ Get <%= service[:title] %> service settings for a project.
-```
-GET /projects/:id/services/<%= service[:dashed_name] %>
+ ```
+ GET /projects/:id/services/<%= service[:dashed_name] %>
-```
+ ```
-<% end %>
+ <% end %>
ERB
namespace :services do
task doc: :environment do
- services = Service.available_services_names.map do |s|
+ services = Service.available_services_names.map { |s|
service_start = Time.now
klass = "#{s}_service".classify.constantize
@@ -66,30 +66,30 @@ namespace :services do
service_hash[:dashed_name] = s.dasherize
service_hash[:description] = service.description
service_hash[:help] = service.help
- service_hash[:params] = service.fields.map do |p|
+ service_hash[:params] = service.fields.map { |p|
param_hash = {}
param_hash[:name] = p[:name]
param_hash[:description] = p[:placeholder] || p[:title]
- param_hash[:required] = klass.validators_on(p[:name].to_sym).any? do |v|
+ param_hash[:required] = klass.validators_on(p[:name].to_sym).any? { |v|
v.class == ActiveRecord::Validations::PresenceValidator
- end
+ }
param_hash
- end
+ }
service_hash[:params].sort_by! { |p| p[:required] ? 0 : 1 }
puts "Collected data for: #{service.title}, #{Time.now - service_start}"
service_hash
- end
+ }
doc_start = Time.now
- doc_path = File.join(Rails.root, 'doc', 'api', 'services.md')
+ doc_path = File.join(Rails.root, "doc", "api", "services.md")
- result = ERB.new(services_template, 0, '>')
+ result = ERB.new(services_template, 0, ">")
.result(OpenStruct.new(services: services).instance_eval { binding })
- File.open(doc_path, 'w') do |f|
+ File.open(doc_path, "w") do |f|
f.write result
end
diff --git a/lib/tasks/sidekiq.rake b/lib/tasks/sidekiq.rake
index dd9ce86f7ca..68c61cb9099 100644
--- a/lib/tasks/sidekiq.rake
+++ b/lib/tasks/sidekiq.rake
@@ -1,21 +1,21 @@
namespace :sidekiq do
desc "GitLab | Stop sidekiq"
task :stop do
- system(*%w(bin/background_jobs stop))
+ system("bin/background_jobs", "stop")
end
desc "GitLab | Start sidekiq"
task :start do
- system(*%w(bin/background_jobs start))
+ system("bin/background_jobs", "start")
end
- desc 'GitLab | Restart sidekiq'
+ desc "GitLab | Restart sidekiq"
task :restart do
- system(*%w(bin/background_jobs restart))
+ system("bin/background_jobs", "restart")
end
desc "GitLab | Start sidekiq with launchd on Mac OS X"
task :launchd do
- system(*%w(bin/background_jobs start_no_deamonize))
+ system("bin/background_jobs", "start_no_deamonize")
end
end
diff --git a/lib/tasks/spec.rake b/lib/tasks/spec.rake
index 2eddcb3c777..f7d47c1b945 100644
--- a/lib/tasks/spec.rake
+++ b/lib/tasks/spec.rake
@@ -1,56 +1,56 @@
-Rake::Task["spec"].clear if Rake::Task.task_defined?('spec')
+Rake::Task["spec"].clear if Rake::Task.task_defined?("spec")
namespace :spec do
- desc 'GitLab | Rspec | Run request specs'
+ desc "GitLab | Rspec | Run request specs"
task :api do
cmds = [
- %w(rake gitlab:setup),
- %w(rspec spec --tag @api)
+ %w[rake gitlab:setup],
+ %w[rspec spec --tag @api],
]
run_commands(cmds)
end
- desc 'GitLab | Rspec | Run feature specs'
+ desc "GitLab | Rspec | Run feature specs"
task :feature do
cmds = [
- %w(rake gitlab:setup),
- %w(rspec spec --tag @feature)
+ %w[rake gitlab:setup],
+ %w[rspec spec --tag @feature],
]
run_commands(cmds)
end
- desc 'GitLab | Rspec | Run model specs'
+ desc "GitLab | Rspec | Run model specs"
task :models do
cmds = [
- %w(rake gitlab:setup),
- %w(rspec spec --tag @models)
+ %w[rake gitlab:setup],
+ %w[rspec spec --tag @models],
]
run_commands(cmds)
end
- desc 'GitLab | Rspec | Run service specs'
+ desc "GitLab | Rspec | Run service specs"
task :services do
cmds = [
- %w(rake gitlab:setup),
- %w(rspec spec --tag @services)
+ %w[rake gitlab:setup],
+ %w[rspec spec --tag @services],
]
run_commands(cmds)
end
- desc 'GitLab | Rspec | Run lib specs'
+ desc "GitLab | Rspec | Run lib specs"
task :lib do
cmds = [
- %w(rake gitlab:setup),
- %w(rspec spec --tag @lib)
+ %w[rake gitlab:setup],
+ %w[rspec spec --tag @lib],
]
run_commands(cmds)
end
- desc 'GitLab | Rspec | Run other specs'
+ desc "GitLab | Rspec | Run other specs"
task :other do
cmds = [
- %w(rake gitlab:setup),
- %w(rspec spec --tag ~@api --tag ~@feature --tag ~@models --tag ~@lib --tag ~@services)
+ %w[rake gitlab:setup],
+ %w[rspec spec --tag ~@api --tag ~@feature --tag ~@models --tag ~@lib --tag ~@services],
]
run_commands(cmds)
end
@@ -59,14 +59,14 @@ end
desc "GitLab | Run specs"
task :spec do
cmds = [
- %w(rake gitlab:setup),
- %w(rspec spec)
+ %w[rake gitlab:setup],
+ %w[rspec spec],
]
run_commands(cmds)
end
def run_commands(cmds)
cmds.each do |cmd|
- system({ 'RAILS_ENV' => 'test', 'force' => 'yes' }, *cmd) || raise("#{cmd} failed!")
+ system({"RAILS_ENV" => "test", "force" => "yes"}, *cmd) || raise("#{cmd} failed!")
end
end
diff --git a/lib/tasks/tokens.rake b/lib/tasks/tokens.rake
index eec024f9bbb..99ddf008434 100644
--- a/lib/tasks/tokens.rake
+++ b/lib/tasks/tokens.rake
@@ -1,7 +1,7 @@
-require_relative '../../app/models/concerns/token_authenticatable.rb'
-require_relative '../../app/models/concerns/token_authenticatable_strategies/base.rb'
-require_relative '../../app/models/concerns/token_authenticatable_strategies/insecure.rb'
-require_relative '../../app/models/concerns/token_authenticatable_strategies/digest.rb'
+require_relative "../../app/models/concerns/token_authenticatable.rb"
+require_relative "../../app/models/concerns/token_authenticatable_strategies/base.rb"
+require_relative "../../app/models/concerns/token_authenticatable_strategies/insecure.rb"
+require_relative "../../app/models/concerns/token_authenticatable_strategies/digest.rb"
namespace :tokens do
desc "Reset all GitLab incoming email tokens"
@@ -27,7 +27,7 @@ end
class TmpUser < ActiveRecord::Base
include TokenAuthenticatable
- self.table_name = 'users'
+ self.table_name = "users"
add_authentication_token_field :incoming_email_token, token_generator: -> { SecureRandom.hex.to_i(16).to_s(36) }
add_authentication_token_field :feed_token
diff --git a/lib/tasks/yarn.rake b/lib/tasks/yarn.rake
index 2ac88a039e7..8d2a1339821 100644
--- a/lib/tasks/yarn.rake
+++ b/lib/tasks/yarn.rake
@@ -1,40 +1,39 @@
-
namespace :yarn do
- desc 'Ensure Yarn is installed'
+ desc "Ensure Yarn is installed"
task :available do
- unless system('yarn --version', out: File::NULL)
+ unless system("yarn --version", out: File::NULL)
warn(
- 'Error: Yarn executable was not detected in the system.'.color(:red),
- 'Download Yarn at https://yarnpkg.com/en/docs/install'.color(:green)
+ "Error: Yarn executable was not detected in the system.".color(:red),
+ "Download Yarn at https://yarnpkg.com/en/docs/install".color(:green)
)
abort
end
end
- desc 'Ensure Node dependencies are installed'
- task check: ['yarn:available'] do
- unless system('yarn check --ignore-engines', out: File::NULL)
+ desc "Ensure Node dependencies are installed"
+ task check: ["yarn:available"] do
+ unless system("yarn check --ignore-engines", out: File::NULL)
warn(
- 'Error: You have unmet dependencies. (`yarn check` command failed)'.color(:red),
- 'Run `yarn install` to install missing modules.'.color(:green)
+ "Error: You have unmet dependencies. (`yarn check` command failed)".color(:red),
+ "Run `yarn install` to install missing modules.".color(:green)
)
abort
end
end
- desc 'Install Node dependencies with Yarn'
- task install: ['yarn:available'] do
- unless system('yarn install --pure-lockfile --ignore-engines')
- abort 'Error: Unable to install node modules.'.color(:red)
+ desc "Install Node dependencies with Yarn"
+ task install: ["yarn:available"] do
+ unless system("yarn install --pure-lockfile --ignore-engines")
+ abort "Error: Unable to install node modules.".color(:red)
end
end
- desc 'Remove Node dependencies'
+ desc "Remove Node dependencies"
task :clobber do
- warn 'Purging ./node_modules directory'.color(:red)
- FileUtils.rm_rf 'node_modules'
+ warn "Purging ./node_modules directory".color(:red)
+ FileUtils.rm_rf "node_modules"
end
end
-desc 'Install Node dependencies with Yarn'
-task yarn: ['yarn:install']
+desc "Install Node dependencies with Yarn"
+task yarn: ["yarn:install"]
diff --git a/lib/unfold_form.rb b/lib/unfold_form.rb
index 05bb3ed7f1c..2fca1d69b73 100644
--- a/lib/unfold_form.rb
+++ b/lib/unfold_form.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-require_relative 'gt_one_coercion'
+require_relative "gt_one_coercion"
class UnfoldForm
include Virtus.model
diff --git a/lib/uploaded_file.rb b/lib/uploaded_file.rb
index aae542f02ac..87f1b87626d 100644
--- a/lib/uploaded_file.rb
+++ b/lib/uploaded_file.rb
@@ -27,7 +27,7 @@ class UploadedFile
@content_type = content_type
@sha256 = sha256
@remote_id = remote_id
- @tempfile = File.new(path, 'rb')
+ @tempfile = File.new(path, "rb")
end
def self.from_params(params, field, upload_paths)
@@ -40,13 +40,13 @@ class UploadedFile
file_path = File.realpath(params["#{field}.path"])
paths = Array(upload_paths) << Dir.tmpdir
- unless self.allowed_path?(file_path, paths.compact)
+ unless allowed_path?(file_path, paths.compact)
raise InvalidPathError, "insecure path used '#{file_path}'"
end
UploadedFile.new(file_path,
filename: params["#{field}.name"],
- content_type: params["#{field}.type"] || 'application/octet-stream',
+ content_type: params["#{field}.type"] || "application/octet-stream",
sha256: params["#{field}.sha256"],
remote_id: params["#{field}.remote_id"])
end
@@ -71,7 +71,7 @@ class UploadedFile
@tempfile.path
end
- alias_method :local_path, :path
+ alias local_path path
def method_missing(method_name, *args, &block) #:nodoc:
@tempfile.__send__(method_name, *args, &block) # rubocop:disable GitlabSecurity/PublicSend
diff --git a/lib/version_check.rb b/lib/version_check.rb
index c9f102f6b19..85e922ba2a7 100644
--- a/lib/version_check.rb
+++ b/lib/version_check.rb
@@ -6,7 +6,7 @@ require "base64"
# check if it is a new version for update
class VersionCheck
def self.data
- { version: Gitlab::VERSION }
+ {version: Gitlab::VERSION}
end
def self.url
@@ -16,6 +16,6 @@ class VersionCheck
end
def self.host
- 'https://version.gitlab.com/check.svg'
+ "https://version.gitlab.com/check.svg"
end
end